Monday 16 June 2014

Jetty 9 & Websockets Example


Jetty is best webserver for Embedded application  deployment.  I don’t want to change the slogan of Jetty to make it understand in a better way  , it was defined in a simple way like below .

"Jetty has a slogan, "Don't deploy your application in Jetty, deploy Jetty in your application." What this means is that as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a software component that can be instantiated and used in a Java program just like any POJO. Put another way, running Jetty in embedded mode means putting an HTTP module into your application, rather than putting your application into an HTTP server.  "

Simple Idea about Jetty:
Jetty  is nothing but adding the Http Server  component in your application. I would like to take this opportunity  to share my experience  with customized http server application .  I used Apache HTTP COMPONENTS for HTTP server application, which is a good option for simple http interactions.


Better  Deployment:
Jetty has introduced the "jetty.base" in Jetty 9 onwards  to isolate  the configuration with other  content like  lib,xml files,start script. SO in Jetty Base we can expect the logs,webapps,start.ini(configuration file) and start.d.


Start of Jetty :

As we know that we have executable jar file in java , in the same way we have executable jar file for starting the Jetty Server.

> java -jar start.jar

You can also add arguments to above statement for server startup command to change  the behavior of Jetty.

If you need any better options please use  "--help" at the end of above start command.  You will get know Module Management,Start,ShutDown,Classpath,Loglevels, log location etc…
" java -jar start.jar --help".


First thing we want to change PORT of Jetty :
Unix Version:
jetty.home = Jetty base directory (jetty-distribution-9.1.4.v20140401).
Windows Version:
JETTY_HOME = Jetty base directory (jetty-distribution-9.1.4.v20140401).
Path : $jetty.home/Start.d/http.ini
# HTTP port to listen on
jetty.port=8080

You can also change port from command start using jetty.port command like below:

c:\> java  -jar start.jar -jetty.port=9999
After executing above command  jetty will start on port 9999.


WebSockets in Jetty :

Jetty has different implementation on different versions. If you are using version lesser than Jetty 9.x then implementation will  be bit tough. From Jetty 9.x onwards they have solid and flexible implementation. Thanks to Jetty Team of Contributors. Here I am using Jetty Latest Version of today (jetty-distribution-9.1.4.v20140401). This implementation strictly doesn't support backward compatibility.

I am explaining about the Websocket usage with Jetty API.
We have 3 ways to do the things :
  1. Listener Design
  2. Annotation
  3. Adapter



A WebSocket TEXT Message can only ever be UTF-8 encoded. (if  you need other forms of encoding, use a BINARY Message).
A WebSocket BINARY Message can be anything that will fit in a byte array.



Jetty Implemented  Websocks:

Step-1 :
We have to create the WebSocketServlet .

package com.webapps.token;

import javax.servlet.annotation.WebServlet;

import org.apache.log4j.Logger;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;


@WebServlet(name = "MyEcho WebSocket Servlet", urlPatterns = { "/websocks" })
public class MyWebSockServlet extends WebSocketServlet
{

private static final Logger log = Logger.getLogger(MyWebSockServlet.class);

/**
 *
 */
private static final long serialVersionUID = -7560239504376396230L;

@Override
public void configure(WebSocketServletFactory wsfactory)
{
log.debug(" Configured the WebSockFactory");
 // register a socket class as default
//wsfactory.getPolicy().setIdleTimeout(10000);
        wsfactory.register(TokenWebSocket.class);
}

}


Step-2:

Create the websocket which register in Websocket factory.


package com.webapps.token;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;


@WebSocket(maxBinaryMessageSize = 4 * 1024 * 1024,maxTextMessageSize= 4 * 1024 * 1024)
public class TokenWebSocket
{

private static final Logger log = Logger.getLogger(TokenWebSocket.class);

private String log_prefix="<mws>:";

@OnWebSocketMessage
public void onWebSocketBinary(Session session,byte[] payload, int offset, int length)
{
// TODO Auto-generated method stub
log.debug("onWebSocketBinary Called");
String test= new String(payload);
log.debug("Binary payload:["+test+"]");
 // simple TEXT message received, with Connection
     // that it occurred on.
log.debug(" on Text Message Called ");
RemoteEndpoint remote = session.getRemote();

log.debug("Message:Rcvd["+test+"]");
try {
//remote.sendString(test+" OK  Bingo!!!");
remote.sendBytes(ByteBuffer.wrap((test+"  OK Bing0!!!!").getBytes()));
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("whie senfing ", e);
}
}

@OnWebSocketClose
public void onWebSocketClose(Session session,int statusCode, String reason)
{

session.close();
log.debug("onWebSocketClose Called .....statuscode ["+statusCode+"] reason ["+reason+"]");
}

@OnWebSocketConnect
public void onWebSocketConnect(Session session)
{
InetSocketAddress remoteAddr = session.getRemoteAddress();
log.debug("<ws-open>: Remote IP ["+remoteAddr.getAddress().getHostAddress()+"] :Port["+remoteAddr.getPort()+"] SessionID:["+session.getProtocolVersion()+"]");

}

@OnWebSocketError
public void onWebSocketError(Session session,Throwable exception) {

this.webSession.close();
exception.printStackTrace(System.err);

}

@OnWebSocketMessage
public void onTextMethod(Session session, String message)
{
     // simple TEXT message received, with Connection
     // that it occurred on.
log.debug(" on Text Message Called ");
RemoteEndpoint remote = session.getRemote();

log.debug("Message:Rcvd["+message+"]");
try {
remote.sendString(message+" OK  Bingo!!!");

} catch (Exception e) {
// TODO Auto-generated catch block
log.error("whie sending ", e);
}

// Async Send of a BINARY message to remote endpoint
/*ByteBuffer buf = ByteBuffer.wrap(new byte[] { 0x11, 0x22, 0x33, 0x44 });
Future<Void> fut = null;
try
{
    fut = remote.sendBytesByFuture(buf);
    // wait for completion (timeout)
    fut.get(2,TimeUnit.SECONDS);
}
catch ( InterruptedException e)
{
    e.printStackTrace();
}
catch (TimeoutException e)
{
    e.printStackTrace();
    if (fut != null)
    {
        fut.cancel(true);
    }
} catch (ExecutionException e) {

e.printStackTrace();
}finally{

log.debug(" ON Message Text Done !!!!!!");
}*/


}

}


Step- 3:
Add these to your source package and deploy in Jetty server, that’s it . This is the tested code.


I will upload the total zip of source soon.

Add BLOB to DB in Java using JDBC

  

    byte[] buffer= {(byte)0xC9, (byte)0xCB, (byte)0xBB,

            (byte)0xCC, (byte)0xCE, (byte)0xB9,

            (byte)0xC8, (byte)0xCA, (byte)0xBC,

            (byte)0xCC, (byte)0xCE, (byte)0xB9,

            (byte)0xC9, (byte)0xCB, (byte)0xBB};

     PreparedStatement pstmt = con.prepareStatement(query);

    pstmt.setBytes(1, buffer);

    Examples :

   public static void addTXN_DATA(String query, byte[] buffer,

            String entryMode, String verifyResult, double actAmt, double tipAmt) {

        try {
            connect();
            PreparedStatement pstmt = con.prepareStatement(query);
            pstmt.setBytes(1, buffer);
            pstmt.setString(2, entryMode);
            pstmt.setString(3, verifyResult);
            pstmt.setDouble(4, actAmt);
            pstmt.setDouble(5, tipAmt);
            log.debug("BINARY- TXN_DATA-" + Util.byteArrayToHexString(buffer));
            int count = pstmt.executeUpdate();
            con.commit();

            log.debug("Succesfully Added to DB BLOB " + count);

        } catch (DatastoreException e) {
            log.debug("While Updating the TXn info to DB", e);
        } catch (SQLException e) {
            log.debug("While Updating the TXn info to DB", e);
        }
    }

    public static byte[] getTXN_DATA(String ref) {
        try {
            connect();
            // Prepare a Statement:
           PreparedStatement stmnt = con.prepareStatement("SELECT TXN_DATA FROM TNX WHERE REF = "+ ref);
            // Execute
            ResultSet rs = stmnt.executeQuery();
            while (rs.next()) {
                try {
                    // Get as a BLOB
                    Blob aBlob = rs.getBlob(1);
                   byte[] allBytesInBlob = aBlob.getBytes(1,(int) aBlob.length());
                    return allBytesInBlob;
                } catch (Exception ex) {
                    // The driver could not handle this as a BLOB...
                    // Fallback to default (and slower) byte[] handling
                    byte[] bytes = rs.getBytes(1);
                    return bytes;
                }
            }
            // Close resources
            rs.close();
            stmnt.close();
        } catch (Exception ex) {
            log.debug("Error when trying to read BLOB: ", ex);
        } catch (DatastoreException e) {
            log.debug("Error when trying to read BLOB: ", e);
        }
        return null;
    }


XML to XSD , XSD Generator


XSD Generation:

If you have sample XML File with test data then generate the XSD automatically with some tools which was provided by MICROSOFT.
Please download the xsd.exe file or you can download from here xsd.exe; (Google for xsd.exe )

How to  use this tool:

The XML Schema Definition (Xsd.exe) tool generates XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly.

xsd file.xdr [/outputdir:directory][/parameters:file.xml]

xsd file.xml [/outputdir:directory] [/parameters:file.xml]
xsd file.xsd {/classes | /dataset} [/element:element]
             [/enableLinqDataSet] [/language:language]
                          [/namespace:namespace] [/outputdir:directory] [URI:uri]
                          [/parameters:file.xml]
xsd {file.dll | file.exe} [/outputdir:directory] [/type:typename [...]][/parameters:file.xml]

For more details please  look into this website :



How to change datatype  in xsd :

  1. Open the xsd in eclipse
  2. Open in design mode .

SSL Certificate


Today we will learn about  " How SSL Works ?" , which is a common question to most of the techies who work with the socket and SSL.
 I assume reader knows about the browser and web server .

Why Use SSL?

Inshort, SSL stands for Secure Socket Layer. It adds more security to the communication. It is used with HTTP or TCP or FTP. To avoid data tampering in the communication we will choose SSL.
 
Transferring sensitive information over a network can be risky due to the following three issues:
  • You cannot always be sure that the entity with whom you are communicating is really who you think it is.
  • Network data can be intercepted, so it is possible that it can be read by an unauthorized third party, sometimes known as an attacker.
  • If an attacker can intercept the data, the attacker may be able to modify the data before sending it on to the receiver.
SSL addresses each of these issues. It addresses the first issue by optionally allowing each of two communicating parties to ensure the identity of the other party in a process called authentication. Once the parties are authenticated, SSL provides an encrypted connection between the two parties for secure message transmission. Encrypting the communication between the two parties provides privacy and therefore addresses the second issue. The encryption algorithms used with SSL include a secure hash function, which is similar to a checksum. This ensures that data is not modified in transit. The secure hash function addresses the third issue of data integrity.
Note, both authentication and encryption are optional, and depend on the the negotiated cipher suites between the two entities.
The most obvious example of when you would use SSL is in an e-commerce transaction. In an e-commerce transaction, it would be foolish to assume that you can guarantee the identity of the server with whom you are communicating. It would be easy enough for someone to create a phony Web site promising great services if only you enter your credit card number. SSL allows you, the client, to authenticate the identity of the server. It also allows the server to authenticate the identity of the client, although in Internet transactions, this is seldom done.
Once the client and the server are comfortable with each other's identity, SSL provides privacy and data integrity through the encryption algorithms it uses. This allows sensitive information, such as credit card numbers, to be transmitted securely over the Internet.
While SSL provides authentication, privacy, and data integrity, it does not provide non-repudiation services. Non-repudiation means that an entity that sends a message cannot later deny that they sent it. When the digital equivalent of a signature is associated with a message, the communication can later be proved. SSL alone does not provide non-repudiation.

How SSL Works?