>

Thursday, July 30, 2015

Switching Java Home Variable for Java Different Version on Windows

For years I didn't write any post on my blog, now have a little times, I will write the simplest post. The topic is how to change JAVA_HOME and PATH variable in windows. Sometime we are dealing with between project and another project which are using different java version, but we do not want bother to switch setting java home variable environment for each java version.
On windows operating system we can create simple script with extension (.bat )that can override the java JAVA_HOME and PATH.
  • The requirement what we need here just notepad
  • A little window batch scripting syntax set and echo


The script is shown  below:
---------------------------------------------------------


@echo off
echo Setting JAVA_HOME
set JAVA_HOME =C:\JAVA\jdk1.7.51
echo setting PATH
set PATH=C:\JAVA\jdk1.7.51\bin;%PATH%
echo Display java version
java –version

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

The explanation:
echo is for display the message on command line
set is to declare the environment variable that we want to change or to override
java –version is syntax to check  whether  the JAVA_HOME is already change or not.

Then we save as  on notepad as file with extension .bat for example is switching-java-variable.bat

how to run :

we can put the anywhere the file location, I put on drive D. let's run our script.

the result  is shown in the image above.

the script it was just simple script, beside you can implement on java, we can implement on ant and also maven. sometime we need oldest version.

note :
feel free to let me know if there were something that I have missed 



Wednesday, January 16, 2013

Simple Application Use Servlet Part II Creating Baseline

Simple Application Use Servlet Part II
Creating Baseline

we will create the baseline for our simple application as we mentioned in last post, we just using one servlet for centralizing the request and response, as we know that our application not just, one request, but more. To meet this condition.
the step i chose:
  • we stay have one servlet
  • we have a lot url pattern servlet but stay one servlet and one name servlet
  • on the method doPost and doGet we instantiate only one object i will be named it CallingAction,
  • in callingAction we just call one method and pass parameter, userpath (request path/ url pattern)

    shabby note - simple application
    Baseline for Simple Application


why we create CallingAction, the idea is every time user do a request we provide by specific url pattern for each different request type, in the servlet class we can retrieve request path(url pattern name) that user hit. For handling the right method for the right url path. I chose step as describe bellow:

  • create labels for each name url pattern, method for the right request and also the class belong to the method
  • each specific url pattern has method, and has class belong to method, have the same labels name
  • based on labels that we created, by using java reflection for picking the right object and method for specific url pattern in CallingAction

For storing labels, I will use interface and grouping for each url path, method and the class belong to method, I will use interface too. The labels will have value as points bellow:
url path → url pattern name
method → method name
class →package_name.class_name

For storing data, I used Hashmap in singleton method. Every time user create user name or edited will be put in the hashmap .

Monday, January 14, 2013

Simple Application Use Servlet Part I

Simple Application Use Servlet Part I

Servlet is a java class can accept request from another java class, web client or other servlet, which can trigger the response, Sometime servlet is named HTTP Servlet because servlet were used combine with HTTP, but servlet itself not one of client server protocol specification.

We can make web application in java use servlet,  in web application there are many request-response process and make a lot servlet then make it our application is hard to maintain, web application requires a centralized access point for HTTP request handling to support the integration of system services like security, data validation etc, content retrieval, view management, and dispatching. When the user accesses the view directly without going through a centralized mechanism, few problems may occur :

  • Each view is required to provide its own system services often resulting in duplicate code.
  • View navigation is left to the views. This may result in shared code for view content and view navigation.
  • Distributed control is more difficult to maintain, since changes will often need to be made in numerous places.
Generally we write specific servlets for specific request handling. These servlets are responsible for data validation, error handling, invoking business services and finally forwarding the request to a specific JSP view to display the results to the user.

According that we better only have one Servlet (instead of having specific Servlet for each specific request) centralizing the handling of all the requests and delegating the functions like validation, invoking business services etc to a command or a helper component. The benefit that we have only one servlet are :
  • Avoid duplicating the control logic like security check, flow control etc.
  • Apply the common logic, which is shared by multiple requests in one controller.
  • Separate the system processing logic from the view processing logic.
  • Provides a controlled and centralized access point for your system.
As I describe about let’s gather requirement for making simple application using servlet.
Tool :
  • java JDK 1.6 or above because all servlet management such as naming, mapping or url pattern, initial params, because we can use annotation. I used Java JDK 1.7.
  • server I used tomcat 7
  • editor Eclipse Indigo
  • for storing data, I will use Collection class, map and stay in JVM in singleton state
Application process constraint:
  • user can log in to application and can edit his/ her profile after save the page will be directed to login form. For checking that the profile has been change user just login again and she/ he will see the profile and edit again.
  • If user not register yet, can go to page sign up after finish entry all data and submit user will be directed to login form and For checking that the profile has been change user just login again and she/ he will see the profile and edit again.

Tuesday, January 1, 2013

JAVA REFLECTION

JAVA REFLECTION

Java reflection is a class in java from package java.lang.reflect we can get all the properties and explore from other classes such as its constructors, methods, and fields. let’s try.
First we create super class 

abstract public class Person {
   abstract void yourName();
}

and then we create the class which is extends Person Class

public class Myself extends Person{
   @Override
   void yourName() {
      System.out.println("my name is Iman");
   }
}


now we create demo class how java reflection work, in our demo class we just try to retrieve all the methods in a class and its super class .
One thing that we should aware that when to call the name of class when using java reflection Class for “Class”, if we didn’t put our java file in package we can invoke Class.forName(“class_name”) but if we put our class in package Class.forName(“package_name.class_name”)


import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionDemo {

   public static void main(String[] args) {
     try {
     Class demo = Class.forName("demo.Myself");
     // this for retrieving method name
     Method method[] =demo.getDeclaredMethods();
     for (int i = 0; i < method.length; i++) {
       System.out.println(" the method name is  --"
        +method[i].toString());
     }

    // retrieving super class from Myself Class
    Class superClass = demo.getSuperclass();
    System.out.println("Name of super class for Myself is --" 
    +superClass.getName());

    // this for retrieving method name in super class
    Method superMethods[] = superClass.getDeclaredMethods();
    for (int i = 0; i < superMethods.length; i++) {
     System.out.println(" the method name is -- "   
        +superMethods[i].toString());
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
  }
}

the console will show bellow :


the method name is -- void demo.Myself.yourName()
Name of super class for Myself is -- demo.Person
the method name is -- abstract void demo.Person.yourName()



java reflection can retrieve all methods or fields even in private mode on, one unique things that we can access private method using reflection, let’s try how to access the private method that in real OOP we can’t access.
in MySelf class we add method :

private String sayHello(String hello){
    return hello;
}

and in DemoReflection class we add few line code for accessing private method




// try to access private method
Myself myself = new Myself();
// get the method which is private
Method privateMethod = demo.Myself.class.getDeclaredMethod("sayHello", String.class);
// this the key for making us access the private method
privateMethod.setAccessible(true);
String returnValue = (String)privateMethod.invoke(myself, "hello...guys!!!");
System.out.println("AHHA !!!!! we got the method .... "+returnValue);

if we run DemoReflection the console will look like bellow :

the method name is -- private java.lang.String demo.Myself.sayHello(java.lang.String)
the method name is -- void demo.Myself.yourName()
Name of super class for Myself is -- demo.Person
the method name is -- abstract void demo.Person.yourName()
AHHA !!!!! we got the method .... hello...guys!!!




Now we access the private field using reflection, by giving value to private field, execute method that not private method which invoke private field.
Add code bellow to Myself

private String name;

String yourNameIs(){
   return name;
}


And then we add code to our DemoReflection to accessing private field

// get the field which is private
Field field = Myself.class.getDeclaredField("name");
// this the key let us accessing the private field
field.setAccessible(true);
field.set(myself, "iman");
System.out.println(" --- "+myself.yourNameIs());

and the console we show like bellow :

the method name is -- java.lang.String demo.Myself.yourNameIs()
Name of super class for Myself is -- demo.Person
the method name is -- abstract void demo.Person.yourName()
AHHA !!!!! we got the method .... hello...guys!!!
--- iman



as seen above we can access field private and private method, what about with OOP concept, private it means the others class cannot access fields or methods, because of java has reflection class we can access all private mode. one thing that we should note that private is intended to prevent misuse, but not security mechanis













 

Sunday, December 16, 2012

Stream Socket (using TCP) Socket Programming In Java

Stream Socket (using TCP) Socket Programming In Java

Perhaps, before you read this post you better to read my earlier post l link, perhaps you want to know what socket is?, what is socket programming?, and technically for create your code or for your comparing about method socket programming in java. or you just skip it.

Stream Socket(Using TCP)
socket programming using TCP, there is condition we must fulfill first, between server and client must establish connection first once server accept, the client can send message.

Now I will make server class first:



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
  public static void main(String[] args) throws IOException {

   ServerSocket serverSocket = new ServerSocket(3000);
   Socket client = null;

   try {
    System.out.println("waiting for request...");
    while (true) {
      client = serverSocket.accept();
      BufferedReader bufferedReader = new BufferedReader(new 
      InputStreamReader(client.getInputStream()));

      OutputStream outputStream = client.getOutputStream();
      String sentences = bufferedReader.readLine();

      System.out.println("sentences "+sentences.length());

      if(sentences.length()!= 0){
        System.out.println("message from client --- "+
        sentences);

        outputStream.write( ("\nyou have send message to"+  
        "server----"+ sentences).getBytes());

        outputStream.write("End\n".getBytes());
      }
     }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
}


and then I created client


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class TCPClient {
  public static void main(String[] args) throws IOException {

   BufferedReader userInput = new BufferedReader(new 
   InputStreamReader(System.in));

   String sentence = userInput.readLine();

   Socket clientSocket = null;
   OutputStream outputStream = null;
   BufferedReader bufferedReader = null;

   try {
    clientSocket = new Socket("localhost", 3000);
    outputStream = clientSocket.getOutputStream();
    bufferedReader=newBufferedReader(new 
    InputStreamReader(clientSocket.getInputStream()));

    outputStream.write((sentence + "\n").getBytes());
    outputStream.write(("End\n").getBytes());

    String reply;
    while (true) {
      reply = bufferedReader.readLine();
      if (reply.equalsIgnoreCase("End")) {
        break;
       }
      if(reply.length()!= 0){
       System.out.println("you got reply ---"+ reply);
       }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }finally{
    outputStream.close();
   bufferedReader.close();
   clientSocket.close();
  }
  }
}
both client and server has been created if you want to know technically how to run both class so can communicate each other, and interchange between console you better read my earlier post link.

Firstly I will run the server :
shabbynote run server
Server Run
 
then I run the client 
shabbynote run client
run the client

 
after I wrote in console and I press enter and the console will show like bellow
shabbynote after click enter
after click enter
 
and we check the server console , to see that our message has been sent to server:
shabbynote server response
server response
 
the best thing for using TCP that you won’t lost your package data and the sequence that won’t be unordered like in using datagram/UDP.

Saturday, December 15, 2012

DataGram/ UDP Socket Programming In Java

DataGram(UDP) Socket Programming In Java

What socket is? Socket is an interface in network to communicate between device in internet protocol, the communication are data and information interchange. So what socket programming is?, socket programming is creation application using socket API(Application Programming Interface) for interchange data. Socket application can be divided in two category based on how data sent. Data can be sent use Datagram Socket( Using UDP) or Stream Socket (using TCP). There are different treatment between UDP and TCP, even both are the same function for data interchange.

UDP Datagram Sockects in Java

in UDP connection process first for sending data, data package can be sent without need to connect first between server and client, client can can straight send data to the server. When you create server class make sure that the port is not in conflict, such as for http, database or something else. In this I use port 3000

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

class UDPServer{
    public static void main(String args[]) throws Exception{

    // determine socket and the port
          DatagramSocket serverSocket = new DatagramSocket(3000);

         // variable put data for sending and receive
         byte[] receiveData = new byte[1024];
         byte[] sendData = new byte[1024];

         while(true){
     // for reading data packet that has been sent by client
    DatagramPacket receivePacket = new DatagramPacket(receiveData,
  receiveData.length);

     serverSocket.receive(receivePacket);
     String sentence = new String( receivePacket.getData());
     System.out.println("data received from client: " + sentence);

     // this how to send datapacket to client
     // i just send back data client has been sent

      InetAddress ip = receivePacket.getAddress();
      int port = receivePacket.getPort();

   sendData = sentence.getBytes();
       DatagramPacket sendPacket = new DatagramPacket(sendData, 
   sendData.length, ip, port);
       serverSocket.send(sendPacket);
     }
    }
}
 
Now let’s create client for sending data Data, the idea is user can type any sentences in console after he or she finish typed sentences and press enter the data will send,



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClientSecond {
   public static void main(String args[]) throws Exception{
   // for retrieve sentences that that
   // has user has typed in console
    BufferedReader userInput = new BufferedReader(new 
   InputStreamReader(System.in));


   // Create socket for sending data
   DatagramSocket clientSocket = new DatagramSocket();
   InetAddress ip = InetAddress.getByName("localhost");


  // determine variable for put
  // send data and receive data
   byte[] sendData = new byte[1024];
   byte[] receiveData = new byte[1024];

  // convert sentences to byte for sending
  // to server
  String sentence = userInput.readLine();
  sendData = sentence.getBytes();

  // create data packet and send using socket
  DatagramPacket sendPacket = new DatagramPacket(sendData, 
  sendData.length, ip, 3000);
  clientSocket.send(sendPacket);

  // retrieve data send from server
  DatagramPacket receivePacket = new DatagramPacket(receiveData, 
  receiveData.length);

  clientSocket.receive(receivePacket);

  String sentencesServer = new String(receivePacket.getData());
  System.out.println("sentences from server :" 
  + sentencesServer);
  clientSocket.close();
   }
}

for running both class, because I used eclipse for making both class, you just do right click in each classes and select run as → java application, perhaps we might give a little concern how to interchange console, the are icon for interchange console and show option which console you want to see.
shabbynote console interchange
Console Interchange


I run both class
first I run server first the second I run the client. Here the screen shot :


shabbynote client input
client input text


after I click enter

shabbynote after enter
after enter



the console of server
shabbynote server response
server response


the weakness of using UDP once you send message multiple sometime the sequence message that you have been send be unordered, you can try with with code above but you send mutiple message the data be mess up. This the screen shoot result my trial :

shabby note
for multiple messages