Wednesday 27 November 2013

Java Socket Example


Trail: Custom Networking


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    public static void main(String[] args) {
        new Server().startServer();
    }

    public void startServer() {
        final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);

        Runnable serverTask = new Runnable() {
            public void run() {
                try {
                    ServerSocket serverSocket = new ServerSocket(9999);
                    System.out.println("Waiting for clients to connect...");
                    while (true) {
                        Socket clientSocket = serverSocket.accept();
                        clientProcessingPool.submit(new ClientTask(clientSocket));
                    }
                } catch (Exception e) {
                    System.err.println("Unable to process client request");
                    e.printStackTrace();
                }
            }
        };
        Thread serverThread = new Thread(serverTask);
        serverThread.start();

    }

    private class ClientTask implements Runnable {
        private final Socket clientSocket;

        private ClientTask(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        public void run() {
            System.out.println("Got a client !");
            // Do whatever required to process the client's request
            try {
                System.out.println("Just connected to " + clientSocket.getRemoteSocketAddress());
                OutputStream outToServer = clientSocket.getOutputStream();
                DataOutputStream out = new DataOutputStream(outToServer);

                out.writeUTF("Hello from " + clientSocket.getLocalSocketAddress());

                InputStream inFromServer = clientSocket.getInputStream();
                DataInputStream in = new DataInputStream(inFromServer);
                System.out.println("Server says " + in.readUTF());
                clientSocket.close();

                try {
                    clientSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}



import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class GreetingServer extends Thread {
    private ServerSocket serverSocket;

    public GreetingServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(1000000);
    }

    public void run() {
        while (true) {
            try {
                System.out.println("Waiting for client on port " +
                        serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();
                System.out.println("Just connected to "
                        + server.getRemoteSocketAddress());

                DataInputStream in =
                        new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out =
                        new DataOutputStream(server.getOutputStream());
                out.writeUTF("Thank you for connecting to "
                        + server.getLocalSocketAddress() + "\nGoodbye!");
                server.close();
            } catch (SocketTimeoutException s) {
                System.out.println("Socket timed out!");
                break;
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
    }

    public static void main(String[] args) {
        int port = Integer.parseInt(args[0]);
        try {
            Thread t = new GreetingServer(port);
            t.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class GreetingClient {
    public static void main(String[] args) {
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);
        try {
            System.out.println("Connecting to " + serverName
                    + " on port " + port);
            Socket client = new Socket(serverName, port);
            System.out.println("Just connected to "
                    + client.getRemoteSocketAddress());
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out =
                    new DataOutputStream(outToServer);

            out.writeUTF("Hello from "
                    + client.getLocalSocketAddress());
            InputStream inFromServer = client.getInputStream();
            DataInputStream in =
                    new DataInputStream(inFromServer);
            System.out.println("Server says " + in.readUTF());
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



public class TestJava {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

 }

}

Friday 1 November 2013

Oracle Query slow due to incompatible data types Date and Timestamp

The performance of sql produced by hibernate will be affected  due to incompatible data types. It appears that column data type(DATE) and hibernate data type(TIMESTAMP) mismatch causes implicit data type conversion. Oracle uses INTERNAL_FUNCTION to transfer date column to match the passed bind variable hibernate data type TimeStamp.

Resolve this Issue:


  • Use  ojdbc6 version 11 (http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#08_01)

  com.oracle
  ojdbc6
  11.2.0.4
  • CustomDateTimeUserType class defined to set the date time as java.sql.Date object to map with DB Data column.               
preparedStatement.setObject(i, timestamp, java.sql.Types.DATE)



User defined hibernate date type
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomDateTimeUserType implements UserType {

 private final Logger logger = LoggerFactory.getLogger(this.getClass());

 @Override
 public int[] sqlTypes() {
  return new int[] { Types.TIMESTAMP };
 }

 @SuppressWarnings("rawtypes")
 @Override
 public Class returnedClass() {
  return Date.class;
 }

 @Override
 public boolean equals(Object x, Object y) throws HibernateException {
  return x == y || !(x == null || y == null) && x.equals(y);
 }

 @Override
 public int hashCode(Object x) throws HibernateException {
  assert (x != null);
  return x.hashCode();
 }

 @Override
 public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
   throws HibernateException, SQLException {
  Timestamp timestamp = rs.getTimestamp(names[0]);
  if (rs.wasNull()) {
   return null;
  }
  return new Date(timestamp.getTime());
 }

 @Override
 public void nullSafeSet(PreparedStatement st, Object value, int index)
   throws HibernateException, SQLException {
  // if (value == null) {
  // st.setNull(index, Types.TIMESTAMP);
  //
  // }
  // else {
  // Date date = (Date) value;
  // Timestamp timestamp = new Timestamp(date.getTime());
  // st.setTimestamp(index, timestamp);
  // }
  if (value == null) {
   st.setNull(index, Types.DATE);

  } else {
   Date date = (Date) value;
   Timestamp timestamp = new Timestamp(date.getTime());
   st.setTimestamp(index, timestamp);
   // st.setDate(index, new java.sql.Date(date.getTime()));
   st.setObject(index, timestamp, java.sql.Types.DATE);
  }
 }

 @Override
 public Object deepCopy(Object value) throws HibernateException {
  return value;
 }

 @Override
 public boolean isMutable() {
  return false;
 }

 @Override
 public Serializable disassemble(Object value) throws HibernateException {
  return (Serializable) value;
 }

 @Override
 public Object assemble(Serializable cached, Object owner)
   throws HibernateException {
  return cached;
 }

 @Override
 public Object replace(Object original, Object target, Object owner)
   throws HibernateException {
  return original;
 }
}


References:

Wednesday 10 July 2013

Sencha GXT 2.x to 3.0 Migration Guide


There are some major difference between GXT3 & GXT2 frame works such as events , layout , data, data widgets, binding, stores etc.... ...

-------------------------------------------------------------------------------------------------------------

Event Handling


GXT 3 is very different than GXT 2 - events are one such example. GXT 3 changed to use an event model more like how GWT events work.

At the time GXT 2 was written, GWT didn't have the event model it has today, so GXT used its own solution. Once GWT had another solution, we decided to follow it in GXT 3 to be more consistent.

Instead of having a BaseEvent for all events, and using EventType instances to compare, GWT has just the GwtEvent type. Subclasses then describe both their own behavior, and the kind of handler that should get called by them.

When listening for an event, it is almost always just as simple as invoking object.addSomeEventHandler(new SomeHandler() {...}). The handler then has a specific method that is called when that particular kind of event goes off, instead of having a general handleEvent() method.


GWT documentation on handling events:
https://developers.google.com/web-to...uideUiHandlers

GXT 3 migration guide:
http://www.sencha.com/learn/sencha-g...gration-guide/

-------------------------------------------------------------------------------------------------------------






References:

Wednesday 3 July 2013

Monday 11 March 2013

LAG & LEAD Analytic function in Oracle




The LAG and LEAD  and  other analytic functions are available in Oracle to  give access to multiple rows within a table, without the need for a self-join. These function will be very handy.
For example: 
To get previous record column value
To calculate difference between column value. 



http://oracle-base.com/articles/misc/lag-lead-analytic-functions.php

http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions070.htm

http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions074.htm#i83834

http://oracle-base.com/articles/misc/rank-dense-rank-first-last-analytic-functions.php


Tuesday 5 March 2013

Using sql count/sum in a case statement in Oracle


Note :
For COUNT : need to use null  value you like to ignore
For SUM  : need to use null /zero value you like to ignore




select count(case
               when retrieve_time is null then
                null
               else
                1
             END) as retrieved
  from TABLE_A
 where CREATED_TIME > gmt_sysdate - 30;


select sum(case
             when retrieve_time is null then
              0
             else
              1
           END) as retrieved
  from TABLE_A
 where CREATED_TIME > gmt_sysdate - 30;

 select sum(case
               when retrieve_time is null then
                null
               else
                1
             END) as retrieved
  from TABLE_A
 where CREATED_TIME > gmt_sysdate - 30;



select to_char(CREATED_TIME, 'YYYY/MM/DD'),
       count(case
               when retrieve_time is null then
                null
               else
                1
             END) as retrieved
  from TABLE_A
 where CREATED_TIME > gmt_sysdate - 30
 group by to_char(CREATED_TIME, 'YYYY/MM/DD');