Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, 5 March 2014

Java Socket Example: Proxy server

This tool can be used for intercept services request and redirect or return error message for specified sources. Basically, reading and writing in same socket in java.


import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ProxyServerTest extends Thread {

    final static Logger logger = Logger.getLogger(ProxyServerTest.class);

    private ServerSocket serverSocket;
    private String wsServer;
    private int wsServerPort;
    private List ipList = new ArrayList();


    public ProxyServerTest(String hostName, int port, int timeout, String wsServer, int wsServerPort, List ipList) throws IOException {
        InetAddress ia = InetAddress.getByName(hostName);
        serverSocket = new ServerSocket(port, 50, ia);
        serverSocket.setSoTimeout(timeout);
        this.wsServer = wsServer;
        this.wsServerPort = wsServerPort;
        this.ipList = ipList;
    }

    public void run() {
        logger.info("Filter source ips: " + ipList);
        while (true) {
            try {
                logger.info("Waiting for client " + " LocalSocketAddress: " + serverSocket.getLocalSocketAddress()
                        + ", HostAddress: " + serverSocket.getInetAddress().getHostAddress() +
                        ", HostName: " + serverSocket.getInetAddress().getHostName() + " on port " + serverSocket.getLocalPort() + "...");
                Socket clientSocket = serverSocket.accept();

                logger.info("Just connected to " + clientSocket.getRemoteSocketAddress());

                String hostName = clientSocket.getInetAddress().getHostName();
                String hostAddress = clientSocket.getInetAddress().getHostAddress();

                logger.info("Filer IPs" + ipList + ", hostName:" + hostName + ", hostAddress:" + hostAddress);

                if (ipList.contains(hostAddress) || ipList.contains(hostName)) {
                    /** Return error message to client */
                    logger.info("Return error message to client");
                    ClientReadMessageThread cht = new ClientReadMessageThread(clientSocket);
                    Thread t = new Thread(cht);
                    t.start();
                    ClientSendMessageThread csmt = new ClientSendMessageThread(clientSocket);
                    Thread t2 = new Thread(csmt);
                    t2.start();
                    try {
                        t.join(1000);
                        t2.join(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        logger.error(e);
                    }

                } else {
                    /** Redirect to sighting WebService */
                    logger.info("Forwarding request to sighting web service :" + wsServer + ":" + wsServerPort);
                    Socket wsSocket = new Socket(wsServer, wsServerPort);

                    wsSocket.setKeepAlive(true);
                    clientSocket.setKeepAlive(true);
                    logger.info("isConnected wsSocket:" + wsSocket.isConnected());

                    OutputStream os = wsSocket.getOutputStream();
                    InputStream is = clientSocket.getInputStream();

                    Thread clientToWS = new Thread(new ClientReader(is, os, "ID1:" + clientSocket.getInetAddress().getHostName() + " to " + wsSocket.getInetAddress().getHostName()));
                    clientToWS.start();

                    InputStream wsIS = wsSocket.getInputStream();
                    OutputStream csOS = clientSocket.getOutputStream();

                    Thread wsToClient = new Thread(new ClientReader(wsIS, csOS, "ID2:" + wsSocket.getInetAddress().getHostName() + " to " + clientSocket.getInetAddress().getHostName()));
                    wsToClient.start();

                    try {
                        clientToWS.join(1000);
                        wsToClient.join(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        logger.error(e);
                    }
                }

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    logger.error(e);
                }
                logger.info("Close socket: " + clientSocket.getInetAddress());
                clientSocket.close();
            } catch (SocketTimeoutException s) {
                logger.error("Socket timed out!");
                logger.error(s);
                break;
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e);
                break;
            }
        }
    }

    public static class ClientReader implements Runnable {
        private InputStream is;
        private OutputStream os;
        private String id;

        public ClientReader(InputStream i, OutputStream o, String id) {
            this.is = i;
            this.os = o;
            this.id = id;
        }

        public void run() {
            try {
                logger.info(id + " start copying.");
                int x;
                x = is.read();
                while (x != -1) {
                    //    System.out.println(id);
                    os.write(x);
                    os.flush();
                    x = is.read();
                }
                logger.info(id + " data copied. x:" + x);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e);
            }
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println("Usage: HOST_NAME PORT_NO TIME_OUT WS_HOST_NAME WS_PORT_NO COMMA_SEPARATED_IP_ADDRESS_TO_SEND_ERROR");

            String hostName = String.valueOf(args[0]);
            int port = Integer.parseInt(args[1]);
            int timeout = Integer.parseInt(args[2]);
            String wsHostName = String.valueOf(args[3]);
            int wsPort = Integer.parseInt(args[4]);
            String ipAddressToIgnore = String.valueOf(args[5]);
            logger.info("hostName:" + hostName);
            logger.info("port:" + port);
            logger.info("timeout:" + timeout);
            logger.info("wsHostName:" + wsHostName);
            logger.info("wsPort:" + wsPort);
            logger.info("ipAddressToIgnore:" + ipAddressToIgnore);
            List ipList = Arrays.asList(ipAddressToIgnore.split(","));
            Thread t = new ProxyServerTest(hostName, port, timeout, wsHostName, wsPort, ipList);
            t.start();

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            System.out.println("Usage: HOST_NAME PORT_NO TIME_OUT WS_HOST_NAME WS_PORT_NO COMMA_SEPERATED_IP_ADDRESS_TO_SEND_ERROR");
        }
    }
}





import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientSendMessageThread implements Runnable {

    final static Logger logger = Logger.getLogger(ClientSendMessageThread.class);
    private Socket clientSocket;

    public ClientSendMessageThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public void run() {
        try {
            String errorResponse = "soap:ServerObject \"org.mule.transport.NullPayload\" not of correct type. It must be of type \"java.util.List\"";
            logger.info("Sending error response:" + clientSocket.getLocalSocketAddress());
            logger.info("Error response:" + '\n' + errorResponse);

            PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
            /** Set header details */
            pw.println("HTTP/1.1 500 Internal Server Error");
            pw.println("Content-Type: text/xml");
            pw.println("http.status: 500");
            pw.println("http.method: POST");
            pw.println("Content-Length: " + errorResponse.length());
            pw.print("\r\n");
            pw.println(errorResponse);
            pw.flush();
            // pw.close();
            logger.info("Response send to client:" + clientSocket.getLocalSocketAddress());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e);
        }

    }
}




import org.apache.log4j.Logger;

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

public class ClientReadMessageThread implements Runnable {

    final static Logger logger = Logger.getLogger(ClientReadMessageThread.class);
    private Socket clientSocket;

    public ClientReadMessageThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public void run() {
        try {
            logger.info("Reading data :" + clientSocket.getLocalSocketAddress());
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String tmp;
            StringBuffer inputLine = new StringBuffer();
            while ((tmp = in.readLine()) != null) {
                inputLine.append(tmp);
                logger.info(tmp);
            }
            logger.info("Finished reading data :" + clientSocket.getLocalSocketAddress());
        } catch (SocketException se) {
            // se.printStackTrace();
            logger.warn(se);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e);
        }
    }
}



Saturday, 18 January 2014

JMX Remote connection & VisualVM

JMX - Java Management Extensions

Enable remote access in tomcat. Include following options with JAVA_OPTS environment variables in tomcat start-up script.
  • -Dcom.sun.management.jmxremote 
  • -Dcom.sun.management.jmxremote.port=8999 
  • -Dcom.sun.management.jmxremote.authenticate=false 
  • -Dcom.sun.management.jmxremote.ssl=false 
  • -Dcom.sun.management.jmxremote.password.file=pw file path  
  • -Dcom.sun.management.jmxremote.access.file=access file path 
  • -Djava.rmi.server.hostname=(Optional)
You can place the password and permissions files in any location, such as "$CATALINA_HOME/conf/". Make sure to modify the permissions of these files so that they can only be viewed by users with appropriate access :
  • $ chmod 600 /path/to/pw/file
  • $ chmod 600 /path/to/access/file
Include in start-up scipt start_admin.sh

export CATALINA_OPTS="-XX:MaxPermSize=512m -Xms1024M -Xmx2048M -XX:NewRatio=3 -XX:MaxNewSize=700M -XX:-UseConcMarkSweepGC -XX:+UseParNewGC -XX:+CMSParallelRemarkEnabled -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.password.file=$TOMCAT_HOME/conf/jmxremote.password -Dcom.sun.management.jmxremote.access.file=$TOMCAT_HOME/conf/jmxremote.access -Djava.rmi.server.hostname=$TOMCAT_HOST"



Process arguments



test@[49]/log% pargs -a 2288
2288:   /usr/java1.6/bin/java -Djava.util.logging.config.file=/opt/ITREfdsc/tomcat/conf
argv[0]: /usr/java1.6/bin/java
argv[1]: -Djava.util.logging.config.file=/opt/ITREfdsc/tomcat/conf/logging.properties
argv[2]: -DthisProcess=CEPServer
argv[3]: -Djava.awt.headless=true
argv[4]: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
argv[5]: -XX:MaxPermSize=512m
argv[6]: -Xms1024M
argv[7]: -Xmx2048M
argv[8]: -XX:NewRatio=3
argv[9]: -XX:MaxNewSize=700M
argv[10]: -XX:-UseConcMarkSweepGC
argv[11]: -XX:+UseParNewGC
argv[12]: -XX:+CMSParallelRemarkEnabled
argv[13]: -Dcom.sun.management.jmxremote
argv[14]: -Dcom.sun.management.jmxremote.port=8999
argv[15]: -Dcom.sun.management.jmxremote.ssl=false
argv[16]: -Dcom.sun.management.jmxremote.authenticate=true
argv[17]: -Dcom.sun.management.jmxremote.password.file=/opt/ITREfdsc/tomcat/conf/jmxremote.password
argv[18]: -Dcom.sun.management.jmxremote.access.file=/opt/ITREfdsc/tomcat/conf/jmxremote.access
argv[19]: -Djava.rmi.server.hostname=ceb-zone
argv[20]: -Djava.endorsed.dirs=/opt/ITREfdsc/tomcat/endorsed
argv[21]: -classpath
argv[22]: /opt/ITREfdsc/tomcat/bin/bootstrap.jar
argv[23]: -Dcatalina.base=/opt/ITREfdsc/tomcat
argv[24]: -Dcatalina.home=/opt/ITREfdsc/tomcat
argv[25]: -Djava.io.tmpdir=/opt/ITREfdsc/tomcat/temp
argv[26]: org.apache.catalina.startup.Bootstrap
argv[27]: start
fdsc@ceb-zone[50]/opt/ITREfdsc/log%


Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

Java HotSpot VM Options

--------------------------------------------------------------------------------------------------------------------------
-Djava.awt.headless=true
To use any AWT libraries in your server code on a machine that's not running a windowing interface
CATALINA_OPTS is immensely useful for setting debug parameters, Java memory settings, etc. One very common use is to set the system property java.awt.headless to true. Most graphical applications (like Jasper, JFreechart, LiquidOffice, StyleReport, etc.) will halt Tomcat when they render if something isn't done to disable display rendering, and this is by far the easiest method. (This problem occurs with most J2EE servers, not just Tomcat). Here's how to make this setting in UNIX.
--------------------------------------------------------------------------------------------------------------------------
-Djava.util.logging.config.file=/opt/ITREfdsc/tomcat/conf/logging.properties
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
To provide customised log file config. It is default behaviour of Tomcat and included in catalina.sh
--------------------------------------------------------------------------------------------------------------------------
-XX:MaxPermSize=512m
The permanent space is where are stored the class, methods, internalized strings, and similar objects used by the VM and never deallocated.
-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.
For most applications the permanent generation is not relevant to GC performance. However, some applications dynamically generate and load many classes. For instance, some implementations of JSPs do this. If necessary, the maximum permanent generation size can be increased with MaxPermSize.
--------------------------------------------------------------------------------------------------------------------------
-Xms1024M
-Xmx2048M
-Xms defines the initial size of the heap and -Xmx defines the maximum size of the heap.

--------------------------------------------------------------------------------------------------------------------------
 -XX:NewRatio=3
By default, the young generation size is controlled by NewRatio. For example, setting -XX:NewRatio=3 means that the ratio between the young and tenured generation is 1:3. In other words, the combined size of the eden and survivor spaces will be one fourth of the total heap size.
--------------------------------------------------------------------------------------------------------------------------

-XX:MaxNewSize=700M
-XX:NewSize

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

Run Visualvm


Create remote connection


View remote process details

References:

Thursday, 15 September 2011

Java File path difference between getPath(), getAbsolutePath(), and getCanonicalPath()




https://docs.oracle.com/javase/1.5.0/docs/api/java/io/File.html

public class FilePathTest {



 public static void main(String[] args) {



  try {







   File f = new File("test.xml");



   System.out.println("----------File set to :test.xml----------");



   System.out.println("getAbsolutePath:" + f.getAbsolutePath());



   System.out.println("getCanonicalPath:" + f.getCanonicalPath());



   System.out.println("getName:" + f.getName());



   System.out.println("getPath:" + f.getPath());



   System.out.println("getParent:" + f.getParent());



   System.out.println("getParentFile:" + f.getParentFile());



   if (f.getParentFile() != null) {



    System.out.println("getParentFile().getAbsolutePath():" + f.getParentFile().getAbsolutePath());



    System.out.println("getParentFile().getCanonicalPath():" + f.getParentFile().getCanonicalPath());



   }







   f = new File("D:\\eclipse-ws\\20130307_WEB\\TestJava\\test.xml");



   System.out.println("\n" + "----------File set to :D:\\eclipse-ws\\20130307_WEB\\TestJava\\test.xml----------");



   System.out.println("getAbsolutePath:" + f.getAbsolutePath());



   System.out.println("getCanonicalPath:" + f.getCanonicalPath());



   System.out.println("getName:" + f.getName());



   System.out.println("getPath:" + f.getPath());



   System.out.println("getParent:" + f.getParent());



   if (f.getParentFile() != null) {



    System.out.println("getParentFile().getAbsolutePath():" + f.getParentFile().getAbsolutePath());



    System.out.println("getParentFile().getCanonicalPath():" + f.getParentFile().getCanonicalPath());



    System.out.println("getParentFile().getName():" + f.getParentFile().getName());



    System.out.println("getParentFile().getPath():" + f.getParentFile().getPath());



    System.out.println("getParentFile().getParent():" + f.getParentFile().getParent());



   }







   f = new File("test\\..\\.\\test.xml");



   System.out.println("\n" + "----------File set to :test\\..\\.\\test.xml----------");



   System.out.println("getAbsolutePath:" + f.getAbsolutePath());



   System.out.println("getCanonicalPath:" + f.getCanonicalPath());



   System.out.println("getName:" + f.getName());



   System.out.println("getPath:" + f.getPath());



   System.out.println("getParent:" + f.getParent());



   if (f.getParentFile() != null) {



    System.out.println("getParentFile().getAbsolutePath():" + f.getParentFile().getAbsolutePath());



    System.out.println("getParentFile().getCanonicalPath():" + f.getParentFile().getCanonicalPath());



    System.out.println("getParentFile().getName():" + f.getParentFile().getName());



    System.out.println("getParentFile().getPath():" + f.getParentFile().getPath());



    System.out.println("getParentFile().getParent():" + f.getParentFile().getParent());



   }



  } catch (IOException e) {



   // TODO Auto-generated catch block



   e.printStackTrace();



  }



 }



}


-------------------OUTPUT------------------------------------ ----------File set to :test.xml---------- getAbsolutePath:D:\eclipse-ws\20130307_WEB\TestJava\test.xml getCanonicalPath:D:\eclipse-ws\20130307_WEB\TestJava\test.xml getName:test.xml getPath:test.xml getParent:null getParentFile:null ----------File set to :D:\eclipse-ws\20130307_WEB\TestJava\test.xml---------- getAbsolutePath:D:\eclipse-ws\20130307_WEB\TestJava\test.xml getCanonicalPath:D:\eclipse-ws\20130307_WEB\TestJava\test.xml getName:test.xml getPath:D:\eclipse-ws\20130307_WEB\TestJava\test.xml getParent:D:\eclipse-ws\20130307_WEB\TestJava getParentFile().getAbsolutePath():D:\eclipse-ws\20130307_WEB\TestJava getParentFile().getCanonicalPath():D:\eclipse-ws\20130307_WEB\TestJava getParentFile().getName():TestJava getParentFile().getPath():D:\eclipse-ws\20130307_WEB\TestJava getParentFile().getParent():D:\eclipse-ws\20130307_WEB ----------File set to :test\..\.\test.xml---------- getAbsolutePath:D:\eclipse-ws\20130307_WEB\TestJava\test\..\.\test.xml getCanonicalPath:D:\eclipse-ws\20130307_WEB\TestJava\test.xml getName:test.xml getPath:test\..\.\test.xml getParent:test\..\. getParentFile().getAbsolutePath():D:\eclipse-ws\20130307_WEB\TestJava\test\..\. getParentFile().getCanonicalPath():D:\eclipse-ws\20130307_WEB\TestJava getParentFile().getName():. getParentFile().getPath():test\..\. getParentFile().getParent():test\..

  • getPath() :will return the absolute or relative path of the File object, depending on which it was constructed with.
  • getAbsolutePath(): will return the current directory name concatenated with the file separator character and the path name of the file
  • getCanonicalPath(): will return a path name with the relative references resolved.




Tuesday, 15 December 2009

Maven


Apache Maven

Setup maven:

  1. Create a JAVA_HOME system variable.
  2. Create an M2_HOME system variable.
  3. Add %JAVA_HOME%\bin;%M2_HOME%\bin; to your system path.
  4. (Optional) Create a %MAVEN_OPTS% system variable. This variable name specified as java options in mvn.bat and mvn.sh. "-Xms512m -Xmx6024m"

Set configurations:

Configuration file (setting.xml) cab be found in two places:

  • The Maven install: $M2_HOME/conf/settings.xml (Global setting)
  • A user’s install: ${user.home}/.m2/settings.xml (User setting)

If both files configured then configuration in both will be merged and user setting will override global setting. 

Set the location for local maven repository:

Default local repository configuration details in setting.xml.

 

Include the following to entry to point to the local repository C:/maven/m2repository


/maven/m2repository








Tuesday, 24 November 2009

ORA-29541: class could not be resolved

Load/Drop java

dropjava -verbose -user test/test@test_1  test.jar
loadjava -resolve -verbose -grant public -user test/test@test_1  test.jar


loadjava -verbose -user test/test@test_1 JavaTest.class ??
loadjava -verbose -user test/test@test_1 c:\JavaTest.java


CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "JavaTest" AS
   public class JavaTest {
   public static String sayHello (String  name) {
   return "Hello, " + name+ "!";
     }
  };



check the status of object

select * from all_objects where object_type like '%JAVA%';

Tuesday, 27 October 2009

JAXB & Ant : package-info.java compilation problem of JAXB generated classes.

 package-info.class not generated

1.Generate the class
  xjc -p test.xsd -d C:/workspace/Test/src
2. Compile the project . package-info.class is generated.
3. Then call the clean task to remove .class files and rebuild the project. package-info.class is not generated.


Note on package-info.java from Ant Manual [http://ant.apache.org/manual/CoreTasks/javac.html]

 package-info.java files were introduced in Java5 to allow package level annotations. On compilation, if the java file does not contain runtime annotations, there will be no .class file for the java file. Up to Ant 1.7.1, when the task is run again, the task will try to compile the package-info java files again.

In Ant 1.7.1 the package-info.java will only be compiled if:

   1. If a package-info.class file exists and is older than the package-info.java file.
   2. If the directory for the package-info.class file does not exist.
   3. If the directory for the package-info.class file exists, and has an older modification time than the the package-info.java file. In this case will touch the corresponding .class directory on successful compilation.
  


Related Links
http://ant.apache.org/manual/CoreTasks/javac.html
http://article.gmane.org/gmane.comp.jakarta.ant.devel/52586
http://www.javalinux.it/wordpress/?p=261

Monday, 26 October 2009

JAVA Compiler error : class file has wrong version 49.0, should be 48.0

Compiler error message :

    [javac] class file has wrong version 49.0, should be 48.0
    [javac] Please remove or make sure it appears in the correct subdirectory of the classpath.
    [javac] import com.common.dao.QueueDAO;
    [javac]                         ^
    [javac] 1 error

Reason :

Java 1.4 creates class files labeled with version 48.0
Java 1.5 creates class files labeled with version 49.0
Check the java compiler versions


Related links :
http://forums.sun.com/thread.jspa?threadID=644158
http://www.dreamincode.net/forums/showtopic49155.htm

Monday, 7 September 2009

How To Override Hibernate Configuration Settings?

 The following code segment will override the some properties. [hibernate.connection.driver_class, hibernate.connection.url ,hibernate.connection.url, hibernate.connection.password]


    public static void createSessionFactory(String driverclass,String url, String username, String password, String configFile) throws HibernateException {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
        Configuration cfg = new AnnotationConfiguration().addResource(configFile);
        cfg.configure(configFile);
        cfg.setProperty("hibernate.connection.driver_class", driverclass);
        cfg.setProperty("hibernate.connection.url", url);
        cfg.setProperty("hibernate.connection.url", username);
        cfg.setProperty("hibernate.connection.password", password); 
        sessionFactory = cfg.buildSessionFactory();
    }

       Hibernate configuration files properties used in following implementation.

    public static void createSessionFactory(String driverclass,String url, String username, String password, String configFile) throws HibernateException {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
        Configuration cfg = new AnnotationConfiguration().addResource(configFile);     
        cfg.setProperty("hibernate.connection.driver_class", driverclass);
        cfg.setProperty("hibernate.connection.url", url);
        cfg.setProperty("hibernate.connection.url", username);
        cfg.setProperty("hibernate.connection.password", password); 
        cfg.configure(configFile);
        sessionFactory = cfg.buildSessionFactory();
    }

Wednesday, 26 August 2009

Packge once. Deploy everywhere

I was looking for a software to bundle my application as one installer. So it can deploy it any where. I found open source product IzPack. It requires only a Java virtual machine to deploy.

IzPack : http://izpack.org/

There are some commercial product available, Following products are used to create windows installer (msi) package.

InstallShield
Advanced Installer

Some more free tools ..

Windows Installer XML (WiX)
InstEd
NSIS

Saturday, 22 August 2009

Eclipse Plug-In - Easy Explorer

Easy Explorer is a very useful plug in, Which helps you to browse resources with the native Operating system explorer. In the Eclipse, select a file, right-mouse click, and select the 'Easy Explore...'

I am using Galileo & easy-explore-1.0.4.

Image Magnification Testing :(






Plug-In details links

Easy Explorer Home
Download Plug-in

Tuesday, 2 June 2009

Daemon Thread in Java


  • Any thread created by main thread is by default user thread. Because when a new thread is created it inherits the daemon status of its parent. (Check output result)
  • Need to explicitly set daemon (setDaemon(true)) but this can only be called before starting thread otherwise it will throw IllegalThreadStateException if the related thread already started.  (Check output result) 
  • Normal thread and daemon threads differ in what happens when they exit. When the JVM halts any remaining daemon threads are abandoned: Finally blocks are not executed. Stacks are not unwound and JVM just exits. (Check output result)
  •  Main different is that as soon as all user thread finish execution java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution. As soon as last non daemon thread finished JVM terminates no matter how many Daemon thread exists or running inside JVM. (Check output result)


Sample Code

public class DaemonTest {

    public static void main(String[] args) {
        System.out.println("Entering main Method");
        WorkerThread wt = new WorkerThread();

        // When false, (i.e. when it's a user thread),
        // the Worker thread continues to run. finally block will run
        // When true, (i.e. when it's a daemon thread),
        // the Worker thread terminates when the main thread terminates. finally block doesn't run
        /** Set daemon flag */
        wt.setDaemon(true);
        wt.start();
        try {
            Thread.sleep(7500);
            System.out.println("Main Thread wake up");
        } catch (InterruptedException e) {
        }
        System.out.println("Main Thread ending");
    }

}

class WorkerThread extends Thread {

    public void run() {
        System.out.println("Entering WorkerThread run method IsDaemon:" + Thread.currentThread().isDaemon());
        try {
            System.out.println("In run Method: currentThread() is" + Thread.currentThread());
            int count = 0;
            while (count < 10) {
                System.out.println("Hello from Worker " + count++);
                try {
                    sleep(2000);
                } catch (InterruptedException e) {
                }
                System.out.println("In run method: woke up again");
            }
        } finally {
            System.out.println("NOTE : Leaving Worker run Method running finally block");
        }
    }
}


Output: User thread / Non-Daemon thread
Entering main Method
Entering WorkerThread run method IsDaemon:false
In run Method: currentThread() isThread[Thread-0,5,main]
Hello from Worker 0
In run method: woke up again
Hello from Worker 1
In run method: woke up again
Hello from Worker 2
In run method: woke up again
Hello from Worker 3
Main Thread wake up
Main Thread ending
In run method: woke up again
Hello from Worker 4
In run method: woke up again
Hello from Worker 5
In run method: woke up again
Hello from Worker 6
In run method: woke up again
Hello from Worker 7
In run method: woke up again
Hello from Worker 8
In run method: woke up again
Hello from Worker 9
In run method: woke up again
NOTE : Leaving Worker run Method running finally block

Process finished with exit code 0



Output: Daemon thread
Entering main Method
Entering WorkerThread run method IsDaemon:true
In run Method: currentThread() isThread[Thread-0,5,main]
Hello from Worker 0
In run method: woke up again
Hello from Worker 1
In run method: woke up again
Hello from Worker 2
In run method: woke up again
Hello from Worker 3
Main Thread wake up
Main Thread ending

Process finished with exit code 0



Output: Setting daemon flag after starting thread
Entering main Method
Exception in thread "main" java.lang.IllegalThreadStateException
 at java.lang.Thread.setDaemon(Thread.java:1275)
 at com.java.concurrency.c1.DaemonTest.main(DaemonTest.java:16)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Entering WorkerThread run method IsDaemon:false
In run Method: currentThread() isThread[Thread-0,5,main]
Hello from Worker 0
In run method: woke up again
Hello from Worker 1
In run method: woke up again
Hello from Worker 2
In run method: woke up again
Hello from Worker 3
In run method: woke up again
Hello from Worker 4
In run method: woke up again
Hello from Worker 5
In run method: woke up again
Hello from Worker 6
In run method: woke up again
Hello from Worker 7
In run method: woke up again
Hello from Worker 8
In run method: woke up again
Hello from Worker 9
In run method: woke up again
NOTE : Leaving Worker run Method running finally block

Process finished with exit code 1


NOTES:
Daemon thread which runs in background and mostly created by JVM for performing background tasks such as

  • Garbage collection
  • Performing asynchronous I/O task. ????
  • Listening for incoming connections ????
  • Collecting statistics and performing the status monitoring tasks
    • Sending and receiving network heartbeats , supplying the service monitoring tools
  • House keeping jobs


Saturday, 22 November 2008

How to enable Log4j logging in Eclipse console window?

Problems:

Could not see the log message in eclipse console window but it shows following warning message


log4j:WARN No appenders could be found for logger (com.test.HelloWorld).

log4j:WARN Please initialize the log4j system properly.

Reasons:
Log4j is not initialised.


Solution:
Add a ConsoleAppender or Appender

Code Sample:
BasicConfigurator.configure();
or
PropertyConfigurator.configure("log4j.xml");


Ref:

Log4j Manual
Log4j API
BasicConfigurator
PropertyConfigurator

Thursday, 20 November 2008

Log4j warning message [log4j:WARN No appenders could be found for logger]

Log4j:

Log4j is a logging or tracing API, large number of applications and framework use Log4j for logging.


Problems:

Sometimes application do not generate log files and generate the following warning message.

log4j:WARN No appenders could be found for logger (com.test.HelloWorld).
log4j:WARN Please initialize the log4j system properly.


Reasons:

Log4j is not initialised properly. The Log4j library files are in application class path but Log4j configuration file is not in application class path.


Solution:

Add log4j configuration file [log4j.properties or log4j.xml] to class path.


More Info:

Log4j priority order,
FATAL: 50000
ERROR: 40000
WARN: 30000
INFO: 20000
DEBUG: 10000

Ref:
log4j Manual
log4j API

Tuesday, 30 September 2008

Java Enumeration Testing


public enum DirectionEnum {
 NORTH("N", "North", 1), NORTH_EAST("NE", "North-East", 2), EAST("E", "East", 3), SOUTH_EAST("SE", "South-East", 4), SOUTH("S", "South", 5), SOUTH_WEST(
   "SW", "South-West", 6), WEST("W", "West", 7), NORTH_WEST("NW", "North-West", 8);

 private final String code;
 private final String description;
 private final short id;

 private DirectionEnum(String code, String description, int id) {
  this.code = code;
  this.description = description;
  this.id = (short) id;
 }

 public String getCode() {
  return code;
 }

 public String getDescription() {
  return description;
 }

 public short getId() {
  return id;
 }

 public static DirectionEnum findById(int id) {
  for (DirectionEnum dir : DirectionEnum.values()) {
   if (dir.getId() == id) {
    return dir;
   }
  }
  return null;
 }
}


public enum VehicleClassEnum {
 H("Heavy"), L("Light"), N("Not Specified");

 private String description;

 private VehicleClassEnum(String description) {
  this.description = description;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

}



import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

 public static void main(String args[]) {
  System.out.println(VehicleClassEnum.valueOf("H"));
  System.out.println(VehicleClassEnum.valueOf("H").toString());
  System.out.println(VehicleClassEnum.valueOf("H").getDescription());
  System.out.println(VehicleClassEnum.valueOf(VehicleClassEnumTest.class, VehicleClassEnum.L.getDescription()));
  System.out.println(VehicleClassEnum.values());
  for (VehicleClassEnum classEnum : VehicleClassEnum.values()) {
   System.out.println("VehicleClassEnum:" + classEnum + ", VehicleClassEnum.toStirng()" + classEnum.toString() + ", VehicleClassEnum.name():"
     + classEnum.name() + ", VehicleClassEnum.ordinal():" + classEnum.ordinal() + ", getDeclaringClass:" + classEnum.getDeclaringClass()
     + ", getDescription():" + classEnum.getDescription() + ", compareTo:" + classEnum.compareTo(VehicleClassEnum.L));
  }

  Enumeration days;
  Vector dayNames = new Vector();
  dayNames.add("Sunday");
  dayNames.add("Monday");
  dayNames.add("Tuesday");
  dayNames.add("Wednesday");
  dayNames.add("Thursday");
  dayNames.add("Friday");
  dayNames.add("Saturday");
  days = dayNames.elements();
  while (days.hasMoreElements()) {
   System.out.println(days.nextElement());
  }
 }
}



---------------OUTPUT---------------

H
H
Heavy
Light
[LVehicleClassEnum;@3ce53108
VehicleClassEnum:H, VehicleClassEnum.toStirng()H, VehicleClassEnum.name():H, VehicleClassEnum.ordinal():0, getDeclaringClass:class VehicleClassEnum, getDescription():Heavy, compareTo:-1
VehicleClassEnum:L, VehicleClassEnum.toStirng()L, VehicleClassEnum.name():L, VehicleClassEnum.ordinal():1, getDeclaringClass:class VehicleClassEnum, getDescription():Light, compareTo:0
VehicleClassEnum:N, VehicleClassEnum.toStirng()N, VehicleClassEnum.name():N, VehicleClassEnum.ordinal():2, getDeclaringClass:class VehicleClassEnum, getDescription():Not Specified, compareTo:1
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday