Configure and Execute Test Cases Using Junit Framework

Local Environment Setup

JUnit is a framework for Java, so the very first requirement is to have JDK installed in your machine.

System Requirement

JDK 1.5 or above.
Memory no minimum requirement.
Disk Space no minimum requirement.
Operating System no minimum requirement.

Step 1 – verify Java installation in your machine

Now open console and execute the following java command.

OS Task Command
Windows Open Command Console c:\> java -version
Linux Open Command Terminal $ java -version
Mac Open Terminal machine:~ joseph$ java -version
Let’s verify the output for all the operating systems:

OS Output
Windows java version “1.6.0_21”
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Linux java version “1.6.0_21”
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Mac java version “1.6.0_21”
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)
If you do not have Java installed, install the Java Software Development Kit (SDK) from http://www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java 1.6.0_21 as installed version for this tutorial.

Step 2: Set JAVA environment

Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example

OS Output
Windows Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21
Linux export JAVA_HOME=/usr/local/java-current
Mac export JAVA_HOME=/Library/Java/Home
Append Java compiler location to System Path.

OS Output
Windows Append the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the end of the system variable, Path.
Linux export PATH=$PATH:$JAVA_HOME/bin/
Mac not required
Verify Java Installation using java -version command explained above.

Step 3: Download Junit archive

Download latest version of JUnit jar file from http://www.junit.org. At the time of writing this tutorial, I downloaded Junit-4.10.jar and copied it into C:\>JUnit folder.

OS Archive name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar

Step 4: Set JUnit environment

Set the JUNIT_HOME environment variable to point to the base directory location where JUNIT jar is stored on your machine. Assuming, we’ve stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.

OS Output
Windows Set the environment variable JUNIT_HOME to C:\JUNIT
Linux export JUNIT_HOME=/usr/local/JUNIT
Mac export JUNIT_HOME=/Library/JUNIT

Step 5: Set CLASSPATH variable

Set the CLASSPATH environment variable to point to the JUNIT jar location. Assuming, we’ve stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.

OS Output
Windows Set the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%\junit4.10.jar;.;
Linux export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.10.jar:.
Mac export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.10.jar:.

Step 6: Test JUnit Setup

Create a java class file name TestJunit in C:\ > JUNIT_WORKSPACE

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
@Test
public void testAdd() {
String str= “Junit is working fine”;
assertEquals(“Junit is working fine”,str);
}
}

Create a java class file name TestRunner in C:\ > JUNIT_WORKSPACE to execute Test case(s)

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}

Step 7: Verify the Result

Compile the classes using javac compiler as follows

C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java
Now run the Test Runner to see the result

C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.

true

Advertisements
| Leave a comment

Connect and Fetch data from Cassendra Using Java Code

1 Connector Class :

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;

import static java.lang.System.out;

/**
* Class used for connecting to Cassandra database.
*/
public class CassandraConnector
{
/** Cassandra Cluster. */
private Cluster cluster;

/** Cassandra Session. */
private Session session;

/**
* Connect to Cassandra Cluster specified by provided node IP
* address and port number.
*
* @param node Cluster node IP address.
* @param port Port of cluster host.
*/
public void connect(final String node, final int port)
{
this.cluster = Cluster.builder().addContactPoint(node).withPort(port).build();
final Metadata metadata = cluster.getMetadata();
out.printf(“Connected to cluster: %s\n”, metadata.getClusterName());
for (final Host host : metadata.getAllHosts())
{
out.printf(“Datacenter: %s; Host: %s; Rack: %s\n”,
host.getDatacenter(), host.getAddress(), host.getRack());
}
session = cluster.connect();
}

/**
* Provide my Session.
*
* @return My session.
*/
public Session getSession()
{
return this.session;
}

/** Close cluster. */
public void close()
{
cluster.close();
}

/**
* Main function for demonstrating connecting to Cassandra with host and port.
*
* @param args Command-line arguments; first argument, if provided, is the
* host and second argument, if provided, is the port.
*/
public static void main(final String[] args)
{
final CassandraConnector client = new CassandraConnector();
final String ipAddress = args.length > 0 ? args[0] : “localhost”;
final int port = args.length > 1 ? Integer.parseInt(args[1]) : 9160;
out.println(“Connecting to IP Address ” + ipAddress + “:” + port + “…”);
client.connect(ipAddress, port);
client.close();
}

}

2 Client Class

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;

public class CassendraClient {
//private Cluster cluster;

private Cluster cluster;
private Session session;

public void connect(String node) {

cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build();
session = cluster.connect(“appsonekeyspace”);

ResultSet results = session.execute(“SELECT * FROM users”);
for (Row row : results) {
System.out.format(“%s %s\n”, row.getString(“user_name”), row.getString(“password”));
}
}

public void close() {
//cluster.shutdown();
}

public static void main(String[] args) {
CassendraClient client = new CassendraClient();
client.connect(“10.1.1.249”);
//client.close();
}
}

| Tagged , , | Leave a comment

Simple Queries for Execute Apache Cassendra

Create KeySpace 1:

CREATE KEYSPACE appsonekeyspace WITH REPLICATION = { ‘class’ : ‘SimpleStrategy’, ‘replication_factor’ : 1 };

Use KeySpace 2:

use appsonekeyspace;

Create table in Keyspace 3:

CREATE TABLE users (
user_id int PRIMARY KEY,
user_name text,
password text
);

Insert Some Values into Table 4:

INSERT INTO users (user_id, user_name, password) VALUES (1745, ‘Ashoka’, ‘test’);
INSERT INTO users (user_id, user_name, password) VALUES (1744, ‘Murali’, ‘demo’);
INSERT INTO users (user_id, user_name, password) VALUES (1746, ‘Bhat’, ‘sample’);

Query Simple SELECT 4:

SELECT * FROM users;

| Leave a comment

Apache Cassendra Installation and Configuration Guide

Installing Cassandra Locally

This document aims to provide a few easy to follow steps to take the first-time user from installation, to running single node Cassandra, and overview to configure multinode cluster. Cassandra is meant to run on a cluster of nodes, but will run equally well on a single machine. This is a handy way of getting familiar with the software while avoiding the complexities of a larger system.

Step 0: Prerequisites and Connecting to the Community

Cassandra requires the most stable version of Java 7 or 8 you can deploy, preferably the Oracle/Sun JVM. Cassandra also runs on OpenJDK and the IBM JVM. (It will NOT run on JRockit, which is only compatible with Java 6.)

The best way to ensure you always have up to date information on the project, releases, stability, bugs, and features is to subscribe to the users mailing list (subscription required) and participate in the #cassandra channel on IRC.

Step 1: Download Cassandra

Download links for the latest stable release can always be found on the website.
Users of Debian or Debian-based derivatives can install the latest stable release in package form, see DebianPackaging for details.
Users of RPM-based distributions can get packages from Datastax.
If you are interested in building Cassandra from source, please refer to How to Build page.
For more details about misc builds, please refer to Cassandra versions and builds page.

Step 2: Basic Configuration

The Cassandra configuration files can be found in the conf directory of binary and source distributions. If you have installed Cassandra from a deb or rpm package, the configuration files will be located in /etc/cassandra.

Step 2.1: Directories Used by Cassandra

If you’ve installed Cassandra with a deb or rpm package, the directories that Cassandra will use should already be created an have the correct permissions. Otherwise, you will want to check the following config settings from conf/cassandra.yaml: data_file_directories (/var/lib/cassandra/data), commitlog_directory (/var/lib/cassandra/commitlog), and saved_caches_directory (/var/lib/cassandra/saved_caches). Make sure these directories exist and can be written to.

By default, Cassandra will write its logs in /var/log/cassandra/. Make sure this directory exists and is writeable, or change this line in conf/log4j-server.properies:

log4j.appender.R.File=/var/log/cassandra/system.log
Note that in Cassandra 2.1+, the logger in use is logback, so change this logging directory in your conf/logback.xml file such as:

/var/log/cassandra/system.log
JVM-level settings such as heap size can be set in conf/cassandra-env.sh.

Step 3: Start Cassandra

And now for the moment of truth, start up Cassandra by invoking ‘bin/cassandra -f’ from the command line1. The service should start in the foreground and log gratuitously to the console. Assuming you don’t see messages with scary words like “error”, or “fatal”, or anything that looks like a Java stack trace, then everything should be working.

Press “Control-C” to stop Cassandra.

If you start up Cassandra without the “-f” option, it will run in the background. You can stop the process by killing it, using ‘pkill -f CassandraDaemon’, for example.

Cassandra Users of recent Linux distributions and Mac OS X Snow Leopard should be able to start up Cassandra simply by untarring and invoking bin/cassandra -f. Since Cassandra 2.1, the tar.gz download has shipped with the log and data directories defaulting to the Cassandra directory. Versions prior defaulted to /var/log/cassandra and /var/lib/cassandra/. Due to this it is necessary to either start Cassandra with root privileges or change the conf/cassandra.yaml to use a directory owned by the current user. Snow Leopard ships with Java 1.6.0 and does not require changing the JAVA_HOME environment variable or adding any directory to your PATH. On Linux just make sure you have a working Java JDK package installed such as the openjdk-6-jdk on Ubuntu Lucid Lynx.

Step 4: Using cqlsh

bin/cqlsh is an interactive command line interface for Cassandra. cqlsh allows you to execute CQL (Cassandra Query Language) statements against Cassandra. Using CQL, you can define a schema, insert data, execute queries. Run the following command to connect to your local Cassandra instance with cqlsh:

$ bin/cqlsh
You should see the following prompt, if successful:

Connected to Test Cluster at localhost:9160.
[cqlsh 2.3.0 | Cassandra 1.2.2 | CQL spec 3.0.0 | Thrift protocol 19.35.0]
Use HELP for help.
For clarity, we will omit the cqlsh prompt in the following examples.

You can access the online help with ‘help;’ command. Commands are terminated with a semicolon (‘;’) in cqlsh.

First, create a keyspace — a namespace of tables.

CREATE KEYSPACE mykeyspace
WITH REPLICATION = { ‘class’ : ‘SimpleStrategy’, ‘replication_factor’ : 1 };
Second, authenticate to the new keyspace:

USE mykeyspace;
Third, create a users table:

CREATE TABLE users (
user_id int PRIMARY KEY,
fname text,
lname text
);
Now you can store data into users:

INSERT INTO users (user_id, fname, lname)
VALUES (1745, ‘john’, ‘smith’);
INSERT INTO users (user_id, fname, lname)
VALUES (1744, ‘john’, ‘doe’);
INSERT INTO users (user_id, fname, lname)
VALUES (1746, ‘john’, ‘smith’);
Now let’s fetch the data you inserted:

SELECT * FROM users;
You should see output reflecting your new rows:

user_id | fname | lname
———+——-+——-
1745 | john | smith
1744 | john | doe
1746 | john | smith
You can retrieve data about users whose last name is smith by creating an index, then querying the table as follows:

CREATE INDEX ON users (lname);

SELECT * FROM users WHERE lname = ‘smith’;

user_id | fname | lname
———+——-+——-
1745 | john | smith
1746 | john | smith
Write your Application

To connect to Cassandra, you’ll need a database driver for your language of choice. DataStax sponsors development of CQL drivers at https://github.com/datastax. A full list of CQL drivers can be found on the ClientOptions page.

When deciding how to design your schema and layout your data, it will be helpful to review the resources on how to DataModel.

You may also want to read the full CQL documentation.

Configuring Multinode Clusters

Now you have single working Cassandra node. It is a Cassandra cluster which has only one node. By adding more nodes, you can make it a multi node cluster.

Setting up a Cassandra cluster is almost as simple as repeating the above procedures for each node in your cluster. There are a few minor exceptions though.

Cassandra nodes exchange information about one another using a mechanism called Gossip, but to get the ball rolling a newly started node needs to know of at least one other, this is called a Seed. It’s customary to pick a small number of relatively stable nodes to serve as your seeds, but there is no hard-and-fast rule here. Do make sure that each seed also knows of at least one other, remember, the goal is to avoid a chicken-and-egg scenario and provide an avenue for all nodes in the cluster to discover one another.

In addition to seeds, you’ll also need to configure the IP interface to listen on for Gossip and CQL, (listen_address and rpc_address respectively). Use a ‘listen_address that will be reachable from the listen_address used on all other nodes, and a rpc_address` that will be accessible to clients.

Once everything is configured and the nodes are running, use the bin/nodetool status utility to verify a properly connected cluster. For example:

$ bin/nodetool -host 192.168.0.10 -p 7199 status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
— Address Load Tokens Owns Host ID Rack
UN 127.0.0.3 30.99 KB 256 32.4% 92b20e08-9ddd-4f55-9173-8516e74d27f5 rack1
UN 127.0.0.2 31 KB 256 31.5% b9616658-c744-48fb-b64f-83f96b007d93 rack1
UN 127.0.0.1 30.96 KB 256 36.1% f7a08973-85bd-460f-8176-d6f9df8c23f4 rack1
Advanced cluster management is described in Operations.

If you don’t yet have access to hardware for a real Cassandra cluster, you can manage local clusters easily with ccm (Cassandra Cluster Manager).

| Leave a comment

Kafka Installation and Configuration Guide

This assumes you are starting fresh and have no existing Kafka or ZooKeeper data.

Step 1: Download the code

Download the 0.8.2.0 release and un-tar it.
> tar -xzf kafka_2.10-0.8.2.0.tgz
> cd kafka_2.10-0.8.2.0

Step 2: Start the server

Kafka uses ZooKeeper so you need to first start a ZooKeeper server if you don’t already have one. You can use the convenience script packaged with kafka to get a quick-and-dirty single-node ZooKeeper instance.
> bin/zookeeper-server-start.sh config/zookeeper.properties
[2013-04-22 15:01:37,495] INFO Reading configuration from: config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)

Now start the Kafka server:
> bin/kafka-server-start.sh config/server.properties
[2013-04-22 15:01:47,028] INFO Verifying properties (kafka.utils.VerifiableProperties)
[2013-04-22 15:01:47,051] INFO Property socket.send.buffer.bytes is overridden to 1048576 (kafka.utils.VerifiableProperties)

Step 3: Create a topic

Let’s create a topic named “test” with a single partition and only one replica:
> bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic test
We can now see that topic if we run the list topic command:
> bin/kafka-topics.sh –list –zookeeper localhost:2181
test
Alternatively, instead of manually creating topics you can also configure your brokers to auto-create topics when a non-existent topic is published to.

Step 4: Send some messages

Kafka comes with a command line client that will take input from a file or from standard input and send it out as messages to the Kafka cluster. By default each line will be sent as a separate message.
Run the producer and then type a few messages into the console to send to the server.

> bin/kafka-console-producer.sh –broker-list localhost:9092 –topic test
This is a message
This is another message
Step 5: Start a consumer
Kafka also has a command line consumer that will dump out messages to standard output.

> bin/kafka-console-consumer.sh –zookeeper localhost:2181 –topic test –from-beginning
This is a message
This is another message
If you have each of the above commands running in a different terminal then you should now be able to type messages into the producer terminal and see them appear in the consumer terminal.
All of the command line tools have additional options; running the command with no arguments will display usage information documenting them in more detail.

Step 6: Setting up a multi-broker cluster

So far we have been running against a single broker, but that’s no fun. For Kafka, a single broker is just a cluster of size one, so nothing much changes other than starting a few more broker instances. But just to get feel for it, let’s expand our cluster to three nodes (still all on our local machine).
First we make a config file for each of the brokers:
> cp config/server.properties config/server-1.properties
> cp config/server.properties config/server-2.properties
Now edit these new files and set the following properties:

config/server-1.properties:
broker.id=1
port=9093
log.dir=/tmp/kafka-logs-1

config/server-2.properties:
broker.id=2
port=9094
log.dir=/tmp/kafka-logs-2

The broker.id property is the unique and permanent name of each node in the cluster. We have to override the port and log directory only because we are running these all on the same machine and we want to keep the brokers from all trying to register on the same port or overwrite each others data.
We already have Zookeeper and our single node started, so we just need to start the two new nodes:
> bin/kafka-server-start.sh config/server-1.properties &

> bin/kafka-server-start.sh config/server-2.properties &

Now create a new topic with a replication factor of three:

> bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 3 –partitions 1 –topic my-replicated-topic
Okay but now that we have a cluster how can we know which broker is doing what? To see that run the “describe topics” command:
> bin/kafka-topics.sh –describe –zookeeper localhost:2181 –topic my-replicated-topic
Topic:my-replicated-topic PartitionCount:1 ReplicationFactor:3 Configs:
Topic: my-replicated-topic Partition: 0 Leader: 1 Replicas: 1,2,0 Isr: 1,2,0
Here is an explanation of output. The first line gives a summary of all the partitions, each additional line gives information about one partition. Since we have only one partition for this topic there is only one line.
• “leader” is the node responsible for all reads and writes for the given partition. Each node will be the leader for a randomly selected portion of the partitions.
• “replicas” is the list of nodes that replicate the log for this partition regardless of whether they are the leader or even if they are currently alive.
• “isr” is the set of “in-sync” replicas. This is the subset of the replicas list that is currently alive and caught-up to the leader.
Note that in my example node 1 is the leader for the only partition of the topic.
We can run the same command on the original topic we created to see where it is:
> bin/kafka-topics.sh –describe –zookeeper localhost:2181 –topic test
Topic:test PartitionCount:1 ReplicationFactor:1 Configs:
Topic: test Partition: 0 Leader: 0 Replicas: 0 Isr: 0
So there is no surprise there—the original topic has no replicas and is on server 0, the only server in our cluster when we created it.

Let’s publish a few messages to our new topic:
> bin/kafka-console-producer.sh –broker-list localhost:9092 –topic my-replicated-topic

my test message 1
my test message 2
^C
Now let’s consume these messages:
> bin/kafka-console-consumer.sh –zookeeper localhost:2181 –from-beginning –topic my-replicated-topic

my test message 1
my test message 2
^C
Now let’s test out fault-tolerance. Broker 1 was acting as the leader so let’s kill it:
> ps | grep server-1.properties
7564 ttys002 0:15.91 /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java…
> kill -9 7564
Leadership has switched to one of the slaves and node 1 is no longer in the in-sync replica set:
> bin/kafka-topics.sh –describe –zookeeper localhost:2181 –topic my-replicated-topic
Topic:my-replicated-topic PartitionCount:1 ReplicationFactor:3 Configs:
Topic: my-replicated-topic Partition: 0 Leader: 2 Replicas: 1,2,0 Isr: 2,0
But the messages are still be available for consumption even though the leader that took the writes originally is down:
> bin/kafka-console-consumer.sh –zookeeper localhost:2181 –from-beginning –topic my-replicated-topic

my test message 1
my test message 2
^C

| Tagged | Leave a comment

Windows Management Infrastructure(WMIC) Installation and Configuration

1] Download WMIC
ashok-pc:~# cd /tmp
ashok-pc:/tmp# wget http://www.edcint.co.nz/checkwmiplus/wmi-1.3.14.tar.gz
–2012-11-18 17:23:45– http://www.edcint.co.nz/checkwmiplus/wmi-1.3.14.tar.gz
Resolving http://www.edcint.co.nz… 50.22.11.45
Connecting to http://www.edcint.co.nz|50.22.11.45|:80… connected.
HTTP request sent, awaiting response… 200 OK
Length: 3994744 (3.8M) [application/x-gzip]
Saving to: “wmi-1.3.14.tar.gz”
100%[=========================================================================================>] 3,994,744 419K/s in 11s
2012-11-18 17:23:57 (366 KB/s) – “wmi-1.3.14.tar.gz” saved [3994744/3994744]

2] Unpack WMIC
ashok-pc:/tmp# tar xzvf wmi-1.3.14.tar.gz
ashok-pc:/tmp# cd wmi-1.3.14

3] Compile WMIC (takes about 5-10 minutes)
ashok-pc:/tmp/wmi-1.3.14# make

4] Test WMIC
ashok-pc:/tmp/wmi-1.3.14#wmic
Usage: [-?|–help] [–usage] [-d|–debuglevel DEBUGLEVEL] [–debug-stderr]
[-s|–configfile CONFIGFILE] [–option=name=value]
[-l|–log-basename LOGFILEBASE] [–leak-report] [–leak-report-full]
[-R|–name-resolve NAME-RESOLVE-ORDER]
[-O|–socket-options SOCKETOPTIONS] [-n|–netbiosname NETBIOSNAME]
[-W|–workgroup WORKGROUP] [–realm=REALM] [-i|–scope SCOPE]
[-m|–maxprotocol MAXPROTOCOL] [-U|–user [DOMAIN\]USERNAME[%PASSWORD]]
[-N|–no-pass] [–password=STRING] [-A|–authentication-file FILE]
[-S|–signing on|off|required] [-P|–machine-pass]
[–simple-bind-dn=STRING] [-k|–kerberos STRING]
[–use-security-mechanisms=STRING] [-V|–version] [–namespace=STRING]
[–delimiter=STRING]

//host query
Example: wmic -U [domain/]adminuser%password //host “select * from Win32_ComputerSystem”
ashok-pc:/tmp/wmi-1.3.14#/bin/wmic -U USER%PASS //HOST ‘Select Caption From Win32_OperatingSystem’
CLASS: Win32_OperatingSystem
Caption|Name
Microsoft Windows XP Professional|Microsoft Windows XP Professional|C:\WINDOWS|\Device\Harddisk0\Partition1

| Leave a comment

MySQL Migration Version 5.1 to 5.6 in CentOS/RHEL

1] Remove Existing MySQL 5.1 Package
Yum Remove mysql

2] Update Cent OS Packages
Sudo Yum Update

3] Create a Directory for download MySQL Package
Mkdir MySQL

4] Enter into the MySQL directory
cd MySQL

5] Download MySQL 5.6 Package from URL
wget http://dev.mysql.com/get/Downloads/MySQL-5.6/MySQL-5.6.16-1.el6.x86_64.rpm-bundle.tar

6] Unzip Downloaded Tar Zip file
tar -xvf MySQL-5.6.16-1.el6.x86_64.rpm-bundle.tar

7] Install MySQL 5.6 Package
yum install MySQL*rpm

8] Start MySQL Service
/etc/init.d/mysql start

| Leave a comment