Thursday, May 15, 2014

System.out.println



System           

final class
out      

static member of final class and of type printStream
println 
method  of class printStream


System

 System is a Final class from java.lang package

public final class System extends object

Since it is a final class it  can’t be instantiated and inherited by other classes
err,in and out are some static fields in System class.


Out [public static final PrintStream out]
Of type printStream,  already open and ready to accept output data and print data to outputstream [console]
In  [public static final InputStream in]
Of type inputStream, open and ready to supply input data ,generally keyboard
err  [public static final PrintStream err]
Of type printStream, already open and ready to accept output data, and print data to standard error output stream[error console in eclipse]


Out

  A static member of  final System class  and type of PrintStream (standard output stream)

public static final PrintStream out

This stream is already opened by JVM during start-up and ready to accept output data. It is mapped to standard O/P console host.

When JVM is initialized it will call initializeSystemClass() and will initialize the system class and the out variable.  This will use the setout() to set the output to console.

println

A method of class PrintStream . Used to print on standard output. It will print the data to console and a newline. Internally it will call print()and then write() + newLine()

User can customize the out object setout() method. By default the O/P the data to console,  we can redirect it to any file using this setout()

      System.setOut(new PrintStream(new FileOutputStream("print.txt")));
      System.out.println(" output from console ");

In the above example, all the contents of the println will be written to the file “print.txt”




Disadvantage:

Use System.out.println only for our learning and internal debugging purpose. It will degrade performance . Since just println will call a sequence of print + write+ newline. Also system.out is not synchronized , implementing synchronization is very complex and that will degrade performance.
Use  Log4J for debugging purpose in your code , it has multiple levels of debugging options. Also Loggers are synchronized.




Wednesday, May 14, 2014

Developing simple Webservices using Jersey


Jersey is an open source RESTful webservice framework in Java. It provides lots of utilities and features to simplify the RESTful service development. Here, I will explain how to develop a simple hello world program using Jersey 2.x. 

1. Download the Jersey JAX-RS 2.0 RI bundle from https://jersey.java.net/download.html

2. Create a dynamic web project in Eclipse. Keep all the JAR files downloaded in step 1 in the WebContent/WEB-INF/lib folder.

3. Create a web.xml file inside WebContent/WEB-INF directory as follows.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  
<servlet>
    <servlet-name>myAction</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.test.jersey.action</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet> 
<servlet-mapping>
    <servlet-name>myAction</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>


In the above web.xml, any requests coming to this application will be routed to the servlet class org.glassfish.jersey.servlet.ServletContainer which will redirect the request to appropriate Java class present inside the package com.test.jersey.action. 

If you are using Jersey 1.x version, the servlet class name and init param to be used is,


<servlet-name>myAction</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.test.jersey.action</param-value>
 </init-param>



4. Create a Java file inside the package com.test.jersey.action (or in its subpackage) which will map the request to corresponding action


package com.test.jersey.action;

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;

@Path("/hello")
public class HelloWorldProgram {

@GET
@Produces("text/html")
public String getHelloMessage() {
return "<html><body>Hello World</body></html>";
}
}




5. Build the application and deploy it in any server. Now if you hit the url http://localhost:8080/hello you will get the message "Hello World". (The portnumber may differ based on your server setup).


If you need to accept input parameters from client, you can do so by using @PathParam annotation as below.


@GET
@Path("/user/{id}")
@Produces("text/html")
public String getHelloMessage(@PathParam("id") String name) {
return "<html><body>Hello "+name+"</body></html>";
}


If you hit the service using the url  http://localhost:8080/hello/user/ABC, it will return a text "Hello ABC".

Jersey is one of the best choice to develop simple light weight Webservices in Java.

Tuesday, May 13, 2014

Writing to multiple log files in Java

   In Java, normally we use log4j or java.util.Logger to create log files. Log4j uses the attributes mentioned in log4j.properties file for this. By default, log4j will look in to the WebContent/WEB-INF/classes directory for the properties file. A sample log4j property file is given below.

log.dir=/mylogs

rrd.dir=${log.dir}/rrd
datestamp=yyyy-MM-dd HH:mm:ss.SSS
roll.pattern.hourly=.yyyy-MM-dd.HH
roll.pattern.daily=.yyyy-MM-dd


log4j.rootLogger=DEBUG,testlogger
log4j.appender.testlogger=org.apache.log4j.DailyRollingFileAppender
log4j.appender.testlogger.File=${log.dir}/test.log
log4j.appender.testlogger.DatePattern=${roll.pattern.daily}
log4j.appender.testlogger.layout=org.apache.log4j.PatternLayout



Here, the logs will be generated in a log file named test.log inside the directory mylogs.


Using log4j, it is possible to write logs to different files based on the package name. For that, we need to mention different log handler based on the package name. For eg: suppose you want to print all the logs generated by the java classes present under the package com.test. For this, you need to define a handler as follows.


log4j.logger.com.test=DEBUG, testpackageLogger

Now you can mention the file where the logs from com.test package needs to be printed as below.

log4j.appender.testpackageLogger.File=${log.dir}/testpackage.log


Similarly, for different package named com.temp, you can define a new handler similar to above in the same log4j.properties file


log4j.logger.com.temp=DEBUG, temppackageLogger

log4j.appender.temppackageLogger.File=${log.dir}/temppackage.log


The logs generated by the classes which are not present in these packages will get printed in the log file mentioned under rootLogger configuration mentioned above.


Please note that the logs generated by the classes present under com.test and com.temp will also get generated inside the log file mentioned in rootLogger. To avoid that, you can use log4j additivity property


log4j.additivity.com.test=false

By setting its value as false, the logs will get printed only inside the package specific log file.

Friday, September 27, 2013

HashMap Vs HashTable


HashMap
HashTable
HashMap & HashTable
Implements Map interface
Implements Map interface
Both Implements  Map interface
HashMap is not  Synchronized.

HashTable is Synchronized .


Not thread-safe, need to implement proper synchronization for multithreading.
In Java 5 we have ConcurrentHashMap, which is thread safe.
HashTable is Thread-safe, shared between multiple threads.

Faster than HashTable.
Better for non-threaded applications.
Much Slower than HashMap for single thread use.
(Synchronization makes HashTable slow)

HashMap allows null.
One  null Key and any number of  null values.
(so do the correct null check for HashMap. See the Null pointer exception in HashMap for details)
HashTable Doesn’t allow null keys or values.

Iterator in the HashMap is fail-fast iterator.


Enumerator in the HashTable is not fail-fast.

Doesn’t retain order.
Java.util.HashMap is unordered
Need to use  LinkedHashMap to maintain order.
Doesn’t retain order.
Both are using hash function  to store and retrieve values from the map.

HashMap is not Synchronized

HashMap is not synchronized. 
If  your code is executing in Single threaded environment it is better to use  HashMap.
But in the case of multi-threaded environment, your code will be shared among multiple threads.Here we need some way to ensure that the resource will be used  by only one thread at a time.Here we need synchronization of objects.
If your code is synchronized, it will executed by only one thread at a time.
In this case if your using HashMap, you need to do something to synchronize the HashMap.

Or you can use HashTable or ConcurrnetHashMap(From Java 5 onwards).

Synchronzing the HashMap
To synchronize HashMap we can use a method from collection API Collections.synchronizedMap().
  Map map = Collections.synchronizedMap(new HashMap());

HashMap is fail-fast

Fail-fast means when you try to modify the contents of HashMap when you are iterating through it, it will fail and throw ConcurrentModificationException.

       HashMap hm = new HashMap<String, String>();
        hm.put("A","1");
        hm.put("B","2");
        hm.put("C","3");
       String i;
       Set Keys = hm.keySet();
       for(Object key:Keys) {
              m.put("D", "4"); // it will throw ConcurrentModificationException
      
}
O/P:
Exception in thread "main" java.util.ConcurrentModificationException

To avoid this we have to use fail-safe iterator (ConcurrentHashMap)

HashTable is not fail-fast

HashTable it is using Enumeration for Keys access.

Enumerator is introduced in older version of java, so there is no way to remove items when ever we are accessing through enumerator.
For HashTable enumeration it will not throw ConcurrentModificationException exception

HashTable hm = new Hashtable<String, String>();
               hm.put("A","1");
               hm.put("B","2");
               hm.put("C","3");
              String i;
               for (Enumeration e = hm.elements() ; e.hasMoreElements() ; e.nextElement()) {
                     hm.put("D", "4"); // will not throw any exception

              }

Friday, August 9, 2013

Null pointer exception in HashMap

1.     Don’t forget to set the hash map before using it.

 Below code will through NullPointerException
import java.util.HashMap;

public class hashnull1 {
static HashMap<String,String>hm;

  public static void main(String[] args)
   {  
      hm.put("1","Apple");
      // the hashmap ‘hm’ is not defined
   }
}

When you run the above code it will through java.lang.NullPointerException.
In the above code we declare the HashMap hm but forgot to define it,
On declaration the HashMap will be having null value without any memory allocation.

HashMap<String,String>hm equal to HashMap<String,String>hm = null;

On the defining part only the memory allocation is happening to hm.

So we need to set hm before using this.
hm = new HashMap<String, String>();

Correct code:

public class hashnull1 {
       static HashMap<String,String>hm;
          public static void main(String[] args)
          {  
                 hm = new HashMap<String, String>();
              hm.put("1","Apple");
          }

}

2.      Do the null check before using HashMap.

 In the above example we can avoid null pointer exception if we might have done null check for hm.

public class hashnull1 {
       static HashMap<String,String>hm;
          public static void main(String[] args)
          {  
                if(hm != null) //checking for null, it can avoid nullpointer ex
              hm.put("1","Apple");
          }

}

3.      Do the Null check for values from the hash map

See the below code.
public class hashnull1 {
       static HashMap<String, String> hm;

       public static void main(String[] args) {
              hm = new HashMap<String, String>();
              String a = hm.get("2"); // value of ‘a’ will be ‘Null’ since key is not there in ‘hm’
              if(a.equals("apple")) { // Since ‘a’ is null it will lead ‘Null pointer’
                     System.out.println("Apple");
              }
       }

}

In the above code try to get the value for  key “2” which is not there in hm, it will always return “null”
Also HashMap will allow null values, so always do the null check for values from the HashMap

Corrected code:
public class hashnull1 {
       static HashMap<String, String> hm;

       public static void main(String[] args) {
              hm = new HashMap<String, String>();
              String a = hm.get("2");
              if(a != null && a.equals("apple")) {
                     System.out.println("Apple");
              }
       }

}
Null values are allowed in hashmap so do the null check for values
hm.put("1", null);
a = hm.get("1");
System.out.println("a>>>"+a); // print “null”

4.     Check for the key existence in hasmap using “containsKey”

map.containsKey(key)
In the above code we can also add a check for key existence in the “HashMap” 
public class hashnull1 {
       static HashMap<String, String> hm;

       public static void main(String[] args) {
              hm = new HashMap<String, String>();
              if (hm.containsKey("2")) { // check whether the key ‘2’ is present in the ‘hm’
                     String a = hm.get("2");
                     if (a != null && a.equals("apple")) {
// hm can contain null values so need to do the null check for values
                           System.out.println("Apple");
                     }
              }
       }

}
 


Sunday, July 14, 2013

USERS in WebSphere Commerce

USERS in WebSphere Commerce

If you are working in WCS, you might have heard about registered users, guest users and generic users. Do you the difference between these users’ types?

Generic User:
When a customer accesses the website to browse the home pages and other product pages without signing in, the user will be assigned as a generic user. Normally in WCS, the user id -1002 refers to the generic user. This user id will be shared across the entire application. This approach minimizes the resource usage in WCS as the same context can be used for multiple users.

Guest User:
When the user adds an item to cart or do some activity which requires a unique identity the user will be converted to a guest user. A guest user will be assigned with a unique member id. Based on the business model and the access policies defined, a guest user will have more privileges in the site rather than a generic user.
The registrationType present in USERS table for both guest and generic user will be “G”. But in WCS by default, a generic user cannot purchase an item through the website. He should register with the site to place an order in the system. A guest user can place order in the site, if guest checkout is enabled in the system.

Registered User:
If the guest user registers to the site, the user will get converted to a registered user, and any assets that the guest user owned will be migrated to the registered user. As part of registration process, the user has to provide a unique user name and password. This will create a profile for the user and will create an entry in USERS table with profile type ‘R’. This username will be always tied up with the member id which is created during registration. Based on the customization implemented, user can store his personal, address and payment details in his profile. Also it will provide additional functionality to the user such as order history, checkout later, personalization, reminder emails etc.

The term “registered user” not only refers the customers who signin to purchase the items, but includes the site administrators, customer care representatives etc. But the registration type present in USERS table will be different for these users.  For eg. The user type of a site administrator will be ‘A’ where as for an administrator, it will be ‘S’. Based on the configuration and customization, the functionalities provided to each of these users may differ. 


How to identify different users from USERS table:



Member Id
Registration Type
Description
-1002
G
The user is a generic user
<any member id>
G
The user is a guest user
<any member id>
R
Registered customer
<any member id>
S
Site Administrator
<any member id>
A
Administrator