Friday, 10 May 2013

Sharding and Replica Set with MongoDB

Sharding-Replica-set with MongoDB


Setting Replica set on three machines
Suppose three machines with host name and ip as follows
192.168.1.25: mongodbTest25
192.168.1.26: mongodbTest26
192.168.1.27: mongodbTest27

Steps 1 : Install MongoDB in all server in /usr/local/ folder as 'mongodb'

Step 2 : On each of the host execute the the following command as

mongodbTest25$ mkdir -p /data/db
mongodbTest26$ ?mkdir -p /data/db
mongodbTest27$ ?mkdir -p /data/db

Step 3 : Go to the /usr/local/mongodb/bin/ directory in all machines and execute the following
command on each machine as

mongodbTest25$ cd /usr/local/mongodb/bin/

$./mongod --port 10000 --rest --replSet testset

Similarly on 26 and 27 server.

Step 4 : we can execute the following command on any of the machines.

$./mongo
>? config = {_id: '?testset', members: [ {_id: 0, host: '192.168.1.25:10000'},
{_id: 1, host: '?192.168.1.26:10000'},{_id: 2, host: '?192.168.1.27:10000'}] };
>rs.initiate(config);
>rs.status();

Step 5 : after executing the above steps and you can view the status as

http://192.168.1.25:11000/

Sharding and Replica set in a cluster

we will set up a nearly production ready cluster of MongoDB instances with the following setup:
3 replica sets (each replica set consisting of 3 mongod instances)
3 config servers
1 mongos server

Step 1 : Install the mongodb in all instances in /usr/local/mongodb

Creating replica set 1:
Step 2 : Open one terminal on each machines
execute on server 1 ie 192.168.1.25
mongodbTest25$ cd /usr/local/mongodb/bin
$ mkdir -p /data/db/
$mkdir /data/db/test1
$./mongod --shardsvr --dbpath /data/db/test1 --port 10000 --rest --replSet testset > /tmp/shard1.log &

execute on server 2 ie 192.168.1.26
mongodbTest26$ cd /usr/local/mongodb/bin
$ mkdir -p /data/db/
$mkdir /data/db/test1
$./mongod --shardsvr --dbpath /data/db/test1 --port 10000 --rest --replSet testset > /tmp/shard1.log &

execute on server 3 ie 192.168.1.27
mongodbTest27$ cd /usr/local/mongodb/bin
$ mkdir -p /data/db/
$mkdir /data/db/test1
$./mongod --shardsvr --dbpath /data/db/test1 --port 10000 --rest --replSet testset > /tmp/shard1.log &

on server 1

$./mongo localhost:10000/admin

>config = {_id: 'testset', members: [{_id: 0, host: '192.168.1.25:10000'},{_id: 1, host: '192.168.1.26:10000'},
{_id: 2, host: '192.168.1.159:10000'}] };
>rs.initiate(config)
>rs.status();

Step 3 : Now we need to start our config server,which will store our meta data (there can be a maximum of 3
config servers).

Again on each of the virtual machines execute the following commands:

$ mkdir /data/db/config
$./mongod --configsvr --dbpath /data/db/config --port 20000 > /tmp/config.log &

Step 4 : Starting a mongos instance (dispatcher): Now we need a mongos instance that will act as a
routing service and load balancer. In production environment it is recommended to have a mongos instance
on every application
server. This way the app server can communicate to it locally and there will be no requests to mongos
servers that are not there.

Open up a new terminal and connect to server1 ie 192.168.1.25
$./mongos --configdb 192.168.1.25:20000,192.168.1.26:20000,192.168.1.27:20000 --port 23000 > /tmp/mongos.log &

Step 5 : Now everything is ready to create the Shard1 :In the terminal where you started the mongos instance enter
the following commands:

$./mongo localhost:23000/admin
>db.runCommand({addshard : "testset/192.168.1.25:10000,192.168.1.26:10000,192.168.1.27:10000"});

Step 6 : Activate sharding for the (data)collection and manage it by the num key (sharding will be done
according to the ‘num’ key, you need to find a balanced key in order to have good sharding):
Enable sharding on the db then on the collection

>use admin
>db.runCommand( { enablesharding : "test" } );
>db.runCommand( { shardcollection : "test.data" , key : { num : 1 } } );

Step 7 : now look at the shard list as

>db.runCommand( {listshards : 1} );

Similarly we will be creates Replica set 2

Step 1 :

On each of the machines execute the following commands:

$ mkdir /data/db/test2
$./mongod --shardsvr --dbpath /data/db/test2 --port 10001 --rest --replSet testset2 > /tmp/shard2.log &

Step 2 : Enter the MongoDB shell on server1:
$./mongo localhost:10001/admin
>config = {_id: 'testset2', members: [{_id: 0, host: '192.168.1.25:10001'},{_id: 1, host: '192.168.1.26:10001'},
{_id: 2, host: '192.168.1.27:10001'}]};
>rs.initiate(config);
>rs.status();

Step 3 : Creating shard 2:

//Connect to mongo shell on the mongos instance on server1:

$./mongo localhost:23000/admin

//In the mongo shell add the replica set 'testset2' to a new shard:

>db.runCommand({addshard : "testset2/192.168.1.25:10001,192.168.1.26:10001,192.168.1.27:10001"});
>db.runCommand( {listshards : 1} );


Similarly we will be creates Replica set 3:
Step 1 :
On each of the machines execute the following commands:

$ mkdir /data/db/test3
$./mongod --shardsvr --dbpath /data/db/test3 --port 10002 --rest --replSet testset3 > /tmp/shard3.log &

Step 2 :
Enter the MongoDB shell on server1:

$./mongo localhost:10002/admin
>config = {_id: 'testset3', members: [{_id: 0, host: '192.168.1.25:10002'},{_id: 1, host: '192.168.1.26:10002'},
{_id: 2, host: '192.168.1.27:10002'}]};
>rs.initiate(config);
>rs.status();

Step 3 : Creating shard 3:
Connect to mongo shell on the mongos instance on server1:

$./mongo localhost:23000/admin
>db.runCommand({addshard : "testset3/192.168.1.25:10002,192.168.1.26:10002,192.168.1.27:10002"});
>db.runCommand( {listshards : 1} );

Step 4 : Congratulations, you have setup a production ready MongoDB cluster.

Thursday, 9 May 2013

MongoDB Install and Configure (NO-SQL database)

MongoDB Install and Configure (NO-SQL database)


Description
MongoDB is an opensource document database and the leading NoSQL database. Written in C++.
The Features of MongoDB are as Follows :
1 : Document-oriented storage
2 : Full Index Support
3 : Replication and High availability
4 : Auto sharding
5 : Querying
6 : Map/Reduce
7 : GridFS
8 : Commercial Support.

How to install and configure MongoDB on linux.
MongoDB runs on most platforms, and supports 32-bit and 64-bit architectures. 10gen, the MongoDB makers,
provides both binaries and packages.

The 10gen repository contains two packages :
mongo-10gen-server :
This package contains the mongod and mongos daemons from the latest stable release and associated configuration
and init scripts.
mongo-10gen :
This package contains all MongoDB tools from the latest stable release.
Install MongoDB
Step 1 : Configure Package Management System (YUM)
Create a /etc/yum.repos.d/10gen.repo file to hold information about your repository. If you are running a 64-bit
system (recommended,) place the following configuration in /etc/yum.repos.d/10gen.repo file.

[10gen]
name=10gen Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64
gpgcheck=0
enabled=1

If you are running a 32-bit system, which isn’t recommended for production deployments, place the following
configuration in /etc/yum.repos.d/10gen.repo file:

[10gen]
name=10gen Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/i686
gpgcheck=0
enabled=1

Install Packages
Issue the following command (as root or with sudo) to install the latest stable version of MongoDB and
the associated tools.

yum install mongo-10gen mongo-10gen-server

When this command completes, you have successfully installed MongoDB.

Configure MongoDB
You can configure MongoDB using /etc/mongod.conf file. and you can find the control script at
/etc/rc.d/init.d/mongod

This MongoDB instance will store its data files in the /var/lib/mongo and its log files in /var/log/mongo,
and run using the mongod user account.
Note If you change the user that runs the MongoDB process, you will need to modify the access control rights to
the /var/lib/mongo and /var/log/mongo directories.

Start MongoDB
You can start the MongoDB using the following command as

service mongod start

You can verify that the mongod process has started successfully by checking the contents of the log file
at /var/log/mongo/mongod.log

You may optionally, ensure that MongoDB will start following a system reboot, by issuing the following command
(with root privileges:)

chkconfig mongod on

Stop MongoDB
Stop the mongod process by issuing the following command (as root, or with sudo)

service mongod stop

Restart MongoDB
You can restart the mongod process by issuing the following command (as root, or with sudo)

service mongod restart

Using MongoDB

Connect to a mongod as

mongo

> db.test.save( { a: 1 } )
> db.test.find()

Select a Database

db

db returns the name of the current database.


JAX-WS SOAP Handler

JAX-WS Soap Handler

SOAP handler is a SOAP message interceptor, which is able to intercept incoming or outgoing SOAP message
and manipulate its values.
For example, A SOAP handler in client side, which will inject client’s computer MAC address into the SOAP
header block for every outgoing SOAP message that is send by the client. In server side, attach another SOAP handler,
to retrieve back the client’s MAC address in SOAP header block from every incoming SOAP message.
So that the server side is able to determine which computer is allow to access the published service.

We understand the soap handler in 2 parts.

Part 1 : SOAP handler in server side


Step 1 :Web Service

package com.test.ws;

import javax.jws.HandlerChain;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public class ServerInfo{
@WebMethod
public String getServerName() {
return "test server";
}
}

Step 2 : Generate necessary Java files for the web service deployment

wsgen -keep -verbose -cp . com.test.ws.ServerInfo

Two files are generated
**********GetServerName.java************
package com.test.ws.jaxws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "getServerName", namespace = "http://ws.test.com/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getServerName", namespace = "http://ws.test.com/")
public class GetServerName {
}

*********GetServerNameResponse.java**************

package com.test.ws.jaxws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "getServerNameResponse", namespace = "http://ws.test.com/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getServerNameResponse", namespace = "http://ws.test.com/")
public class GetServerNameResponse {
@XmlElement(name = "return", namespace = "")
private String _return;
/**
*
* @return
* returns String
*/
public String getReturn() {
return this._return;
}
/**
*
* @param _return
* the value for the _return property
*/
public void setReturn(String _return) {
this._return = _return;
}
}

Step 3 : SOAP Handler
Create a SOAP handler to retrieve the value in SOAP header block, for every incoming SOAP message.

*********MacAddressValidatorHandler.java****************

package com.test.handler;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import javax.xml.ws.soap.SOAPFaultException;

public class MacAddressValidatorHandler implements SOAPHandler{

@Override
public boolean handleMessage(SOAPMessageContext context) {

System.out.println("Server : handleMessage()......");

Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

//for response message only, true for outbound messages, false for inbound
if(!isRequest){

try{
SOAPMessage soapMsg = context.getMessage();
SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader();

//if no header, add one
if (soapHeader == null){
soapHeader = soapEnv.addHeader();
//throw exception
generateSOAPErrMessage(soapMsg, "No SOAP header.");
}

//Get client mac address from SOAP header
Iterator it = soapHeader.extractHeaderElements(SOAPConstants.URI_SOAP_ACTOR_NEXT);

//if no header block for next actor found? throw exception
if (it == null || !it.hasNext()){
generateSOAPErrMessage(soapMsg, "No header block for next actor.");
}

//if no mac address found? throw exception
Node macNode = (Node) it.next();
String macValue = (macNode == null) ? null : macNode.getValue();

if (macValue == null){
generateSOAPErrMessage(soapMsg, "No mac address in header block.");
}

//if mac address is not match, throw exception
if(!macValue.equals("90-4C-E5-44-B9-8F")){
generateSOAPErrMessage(soapMsg, "Invalid mac address, access is denied.");
}
//tracking
soapMsg.writeTo(System.out);

}catch(SOAPException e){
System.err.println(e);
}catch(IOException e){
System.err.println(e);
}

}
//continue other handler chain
return true;
}

@Override
public boolean handleFault(SOAPMessageContext context) {

System.out.println("Server : handleFault()......");

return true;
}

@Override
public void close(MessageContext context) {
System.out.println("Server : close()......");
}

@Override
public Set getHeaders() {
System.out.println("Server : getHeaders()......");
return null;
}
private void generateSOAPErrMessage(SOAPMessage msg, String reason) {
try {
SOAPBody soapBody = msg.getSOAPPart().getEnvelope().getBody();
SOAPFault soapFault = soapBody.addFault();
soapFault.setFaultString(reason);
throw new SOAPFaultException(soapFault);
}
catch(SOAPException e) { }
}
}

Step 4 : SOAP Handler XML File

Create a SOAP handler XML File, and puts your SOAP handler declaration.
File : handler-chain.xml


Step 5 : Attach SOAP Handler with web service

package com.test.ws;
import javax.jws.HandlerChain;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
@HandlerChain(file="handler-chain.xml")
public class ServerInfo{
@WebMethod
public String getServerName() {
return "test server";
}
}
Step 6 : Web Service Publisher
package com.test.endpoint;
import javax.xml.ws.Endpoint;
import com.test.ws.ServerInfo;
//Endpoint publisher
public class TestWsPublisher{
public static void main(String[] args) {
Endpoint.publish("http://localhost:8089/ws/server", new ServerInfo());
System.out.println("Service is published!");
}
}

Part 2 : SOAP handler in Client side


In this article, You will develop a web service client to access the published service in previous article,
and attach a handler to inject client’s MAC address into header block, for every outgoing SOAP message that’s
send by client side
Step 1 : Web Service Client
Use wsimport command to parse the published service WSDL file (http://localhost:8089/ws/server?wsdl) and generate
all required files to access the service.

wsimport -keep -verbose http://localhost:8089/ws/server?wsdl

Six files are generated automatically.

******* ServerInfoService.java************
@WebServiceClient(name = "ServerInfoService",
targetNamespace = "http://ws.test.com/",
wsdlLocation = "http://localhost:8089/ws/server?wsdl")
public class ServerInfoService extends Service
{
}

A client to access the published web service.

******* WsClient.java************

package com.test.client;
import com.test.ws.ServerInfo;
import com.test.ws.ServerInfoService;
public class WsClient{
public static void main(String[] args) throws Exception {
ServerInfoService sis = new ServerInfoService();
ServerInfo si = sis.getServerInfoPort();
System.out.println(si.getServerName());
}
}
Step 2 : SOAP Handler
Create a SOAP handler to inject client’s MAC address into the SOAP header block, for every outgoing SOAP message.

********** MacAddressInjectHandler.java ****************

package com.test.handler;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class MacAddressInjectHandler implements SOAPHandler{
@Override
public boolean handleMessage(SOAPMessageContext context) {
System.out.println("Client : handleMessage()......");
Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
//if this is a request, true for outbound messages, false for inbound
if(isRequest){
try{
SOAPMessage soapMsg = context.getMessage();
SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader();

//if no header, add one
if (soapHeader == null){
soapHeader = soapEnv.addHeader();
}
//get mac address
String mac = getMACAddress();
//add a soap header, name as "mac address"
QName qname = new QName("http://ws.test.com/", "macAddress");
SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(qname);

soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
soapHeaderElement.addTextNode(mac);
soapMsg.saveChanges();
//tracking
soapMsg.writeTo(System.out);

}catch(SOAPException e){
System.err.println(e);
}catch(IOException e){
System.err.println(e);
}
}
//continue other handler chain
return true;
}

@Override
public boolean handleFault(SOAPMessageContext context) {
System.out.println("Client : handleFault()......");
return true;
}

@Override
public void close(MessageContext context) {
System.out.println("Client : close()......");
}
@Override
public Set getHeaders() {
System.out.println("Client : getHeaders()......");
return null;
}
// return current client mac address
private String getMACAddress(){
InetAddress ip;
StringBuilder sb = new StringBuilder();
try {
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");

for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
} catch (UnknownHostException e) {
e.printStackTrace();

} catch (SocketException e){
e.printStackTrace();
}
return sb.toString();
}
}

Step 3 : SOAP Handler XML File
Create a SOAP handler XML file, and puts your SOAP handler declaration.
***** File : handler-chain.xml **********

Step 4 : Attach SOAP Handler in Web Service Client
To attach above SOAP handler to web service client, edit the ServerInfoService.java file (generated via wsimport),
and annotate with @HandlerChain and specify the SOAP handler file name inside.
******** File : ServerInfoService.java **********
@WebServiceClient(name = "ServerInfoService",
targetNamespace = "http://ws.test.com/",
wsdlLocation = "http://localhost:8089/ws/server?wsdl")
@HandlerChain(file="handler-chain.xml")
public class ServerInfoService extends Service
{
}

Wednesday, 8 May 2013

Custom String Formator in Java


Custom String Formator in Java

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CustomStringFormator {
private static final String fieldStart = "\\$\\{";
    private static final String fieldEnd = "\\}";

    private static final String regex = fieldStart + "([^}]+)" + fieldEnd;
    private static final Pattern pattern = Pattern.compile(regex);

    public static String format(String format, Map<String, Object> objects) {
        Matcher m = pattern.matcher(format);
        String result = format;
        try{
        while (m.find()) {
            String[] found = m.group(1).split("\\.");
            Object o = objects.get(found[0]);
            Field f = o.getClass().getField(found[1]);
            String newVal = f.get(o).toString();
            result = result.replaceFirst(regex, newVal);
        }
        }catch(Exception ex){}
        return result;
    }

    static class Dog {
        public String name;
        public String owner;
        public String gender;
    }
    static class User{
    public String username;
    public int id;
    public String country;
    }

    public static void main(String[] args) {
        Dog d1 = new Dog();
        d1.name = "fido";
        d1.owner = "Jane Doe";
        d1.gender = "him";
        User u=new User();
        u.id=2;
        u.username="wakil";
        u.country="india";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("d", d1);
        map.put("u",u);
        System.out.println(CustomStringFormator.format("My dog is named ${d.name}, and ${d.owner} owns ${d.gender}. hell user your ${u.id} and username is ${u.username} and country is ${u.country}", map));
    }
}

Friday, 3 May 2013

Mysql Replication Setup on Windows Machine

Mysql Replication on windows machine

Mysql Replication Setup on Windows Machine

There are several steps for installing and configuring mysql replication on windows operating system
Step 1 : Install mysql-5.5.11-win32.msi
On windows machine while installation choose custom installation and change path to D:\MySQL\MySQL Server 5.5
1.1 : Use all the default parameter like Service name is MYSQL and port number is 3306 and setup bin path.
1.2 :Modify root password to admin.
1.3 : Open dos prompt and type the following command as
mysql -u root -padmin -h localhost -P 3306
1.4 :If your mysql command get executed then everything is ok.
We will mention mysql 5.5 is MASTER.
1.5 : Now create one database named as 'wakil'
mysql> create database wakil; Step 2 :Install (another version or same) of mysql (mysql-5.1.56-win32.msi)
for SLAVE. Again while installing choose custom Installation and change installation path to
D:\MySQL\MySQL Server 5.1
2.1 :Change service name to MYSQL2 and port number to 3307
2.2 : Modify root password to admin123.
2.3 :Open new dos prompot and type below command as
C:\> mysql -u root -p admin123 -h localhost -P 3307;
2.4 : We will treat it mysql 5.1 as SLAVE.
2.5 : Now again create database names as 'wakil'
mysql> create database wakil;
Now in your windows machine two mysql instances are running, First instance ie MASTER is running on 3306 port
and second ie SLAVE is running on port 3307 port.

Step 3 : Now Start replication
Open D:\MySQL\MySQL Server 5.5\my.ini then add four options to the [mysqld] section of the my.ini file

[mysqld]
log-bin=mysql1-bin.log
server-id=1
innodb_flush_log_at_trx_commit=1
sync_binlog=1
Save it and Restart the MYSQL service from Computer ie . MyComputer -> Right click -> click on Manage ->
Services and Application -> Services ->On MYSQL and click on restart.

Step 4 :Creating Replication Account used for replication
Create an account on the master server that the slave server can use to connect. This account must be
given the REPLICATION SLAVE privilege.
Open one dos windows for all MASTER operation.
C:\>mysql -uroot -padmin -h localhost -P 3306;
mysql> create user 'replication_user' identified by 'password';
mysql> grant replication slave on *.* to 'replication_user'@'%' identified by 'password';
mysql> flush privileges;
mysql> FLUSH TABLES WITH READ LOCK;
mysql> SHOW MASTER STATUS;

+--------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+--------------------+----------+--------------+------------------+
| mysql1-bin.000001 | 338 | | |
+--------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

Now take your backup of your MASTER database as we have new database so this below step are not required.
But when you have to create SLAVE of running database then it step must be required,
so lets go these below step too.

Open new dos prompt.
Taking backup from MASTER:
C:\>mysqldump -u root -padmin -h localhost -P3306 wakil > d:\test.sql
Now export this back to SLAVE, run below command on same dos windows.
C:\Users\wakilahmad>mysql -u root -padmin123 -h localhost -P3307 wakil < d:\test.sql

Step 5 : Now Some changes on SLAVE Side
Open D:\MySQL\MySQL Server 5.1\my.ini then add four options to the [mysqld] section of the my.ini file
[mysqld]
server-id=2

save it and Restart the MYSQL2 service from your as above
Open one dos windows for all SLAVE operation.

c:\>mysql -u root -padmin -h localhost -P 3307;

mysql> stop slave;
mysql> CHANGE MASTER TO
MASTER_HOST='localhost',
MASTER_USER='replication_user',
MASTER_PASSWORD='password',
MASTER_PORT=3306,
MASTER_LOG_FILE='mysql1-bin.000001',
MASTER_LOG_POS=338;

mysql> show slave status\G;
Output will come huge, among two line should be like:
Slave_IO_Running: No
Slave_SQL_Running: No
Because slave is stopped now.
Now time came to start slave.
Step 6 : On SLAVE side
mysql> start slave;
Now check slave status:
mysql> show slave status\G;
Output will come huge, among two line should be like:
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
---

If both values are Yes, then everything are ok.
Now you can check your replication work.

Create some table in MASTER wakil database or any database (those should be there at SLAVE side)
then check at slave side.
Now you stop slave again then you change of MASTER will not come but once again you will start slave then
slave will get automatically updated from last time stopped pointer.

For more details you may read mysql replication http://dev.mysql.com/doc/refman/5.0/en/replication.html


Done

Thursday, 2 May 2013

Application authentication via JAX-WS

Application authentication via JAX-WS


To handle the authentication at application level, follows the following steps
Step 1 : Create a test hello application
At webservice server side
*****************************************************************
package com.test.ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface TestHello {
@WebMethod
public String sayHello();

}

********************************************************************
package com.test.ws;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
@WebService(endpointInterface = "com.test.ws.TestHello")
public class TestHelloImpl implements TestHello{
@Resource
WebServiceContext wsctx;
@Override
public String sayHello() {
MessageContext mctx = wsctx.getMessageContext();
//get detail from request headers
Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
List userList = (List) http_headers.get("username");
List passList = (List) http_headers.get("password");

String username = "";
String password = "";

if(userList!=null){
//get username
username = userList.get(0).toString();
}
if(passList!=null){
//get password
password = passList.get(0).toString();
}
//Should validate username and password
if (username.equals("wakil") && password.equals("ahmad")){
return "Hello - Congrates valid user";
}else{
return "Invalid user";
}

}
}

Step 2 : EndPoint Publisher
Create an endpoint publisher to deploy web service at URL : “http://localhost:8090/ws/test”
********************************************************************************
package com.test.endpoint;
import javax.xml.ws.Endpoint;
import com.test.ws.TestHelloImpl;
public class TestPublisher{
public static void main(String[] args) {
Endpoint.publish("http://localhost:8090/ws/test", new TestHelloImpl());
}
}
******************************************************************************
Step 3 : Web Service Client

package com.test.client;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;
import com.test.ws.TestHello;
public class TestClient {
private static final String WS_URL = "http://localhost:8090/ws/test?wsdl";
public static void main(String[] args) throws Exception {
URL url = new URL(WS_URL);
QName qname = new QName("http://ws.test.com/", "TestHelloImplService");
Service service = Service.create(url, qname);
TestHello test = service.getPort(TestHello.class);
/** UserName & Password */
Map req_ctx = ((BindingProvider)test).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
Map> headers = new HashMap>();
headers.put("username", Collections.singletonList("wakil"));
headers.put("password", Collections.singletonList("ahmad"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
System.out.println(test.sayHello());
}
}

When you run the above client, you can find the following output as below:
Output
Hello - Congrates valid user

Tracing soap traffic
How soap envelope flows between client and server
1:Client send request, the username “wakil” and password “ahmad” are included in the soap envelope.

2. Server send back a response as.

Wednesday, 1 May 2013

Deploy Web Service On Tomcat Server

Deploy Web Service On Tomcat Server

There are following steps to create web service and deploy it on tomcat server
Step 1 :Create a web service
package com.test.ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld{
@WebMethod String sayHello();
}

package com.test.ws;
import javax.jws.WebService;
@WebService(endpointInterface = "com.test.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
@Override
public String sayHello() {
return "Hello World";
}
}

Later you will deploy this web service on tomcat server

Step 2 : sun-jaxws.xml
Create a web service deployment descriptor, sun-jaxws.xml.


When user access /hello/ URL path, it will access the declared web service, which is HelloWorldImpl.java.

Step 3 : web.xml
Create a web.xml deployment descriptor for the deployment. Defines WSServletContextListener as listener class,
and WSServlet as your servlet.

Step 4 : War content for deployment

WEB-INF/classes/com/test/ws/HelloWorld.class
WEB-INF/classes/com/test/ws/HelloWorldImpl.class
WEB-INF/web.xml
WEB-INF/sun-jaxws.xml
Step 5 : Download a web service dependency from here :http://jax-ws.java.net/
put all jar files in the lib folder as :
jaxb-impl.jar
jaxws-api.jar
jaxws-rt.jar
gmbal-api-only.jar
management-api.jar
stax-ex.jar
streambuffer.jar
policy.jar
Step 6 : Deployment on tomcat
create war file with lib folder as given above and deploy on tomcat webapps folder
Restart the tomcat server , now you can access the url as

http://localhost:8080/HelloWorld/hello , if you see the following page output then you are successfully
deployed the web service on tomcat.
Done !