Tuesday, June 5, 2012

Google Guava Collections are awesome

Guava introduces a number of new collection types that are not in the JDK, but that we have found to be broadly useful. These are all designed to coexist happily with the JDK collections framework, without shoehorning things into the JDK collection abstractions.


1 line joiner : String groupConfiguration = Joiner.on(SMSConstants.commaDelimiter).join(uniqGroupConcats);
1 line splitter : String ilcId = Lists.newArrayList(Splitter.on(SMSConstants.rowidFieldDelimiter).split(Bytes.toString(values.getRow()))).get(1);

1 line to print the map values : Joiner.on("\n").withKeyValueSeparator("=>").join(defaultExpectedPS)

MultiMap : A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

List Partition : Lists.partition is again easy to split list into multiple list and loop it.

http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table

In our application i am trying to use Table from guava. Below is the example :


             // We can create a table in java memory using guava ;)
Table> ilcGroupConfiguration =   HashBasedTable.create();

ilcGroupConfiguration.put("SCID 1", "G1+G2", Arrays.asList("Zigbee1", "Zigbee2"));
ilcGroupConfiguration.put("SCID 2", "G1+G2+G3", Arrays.asList("Zigbee3", "Zigbee4"));

// RowKeySet() :  Returns a set of row keys that have one or more values in the table.
for (String ilcGroup1 : ilcGroupConfiguration.rowKeySet()) {

System.out.println("Keys SC : " + ilcGroup1);
// row(rowKey) : Returns a view of all mappings that have the given row key.
Map> ilcGroupCommand = new HashMap>();
ilcGroupCommand = ilcGroupConfiguration.row(ilcGroup1);

for (String ilcGroupCommandgc : ilcGroupCommand.keySet()) {
System.out.println("Keys GC : " + ilcGroupCommandgc);
List ilcIds = ilcGroupCommand.get(ilcGroupCommandgc);
System.out.println("Keys ILC Ids : " + ilcIds);
}
}

Lists.partition is again easy. If you want to split the for loop every 1000 use lists.partition
for (List devices : Lists.partition(devicesLists, 1000) {
    for (Device device : devices) {
    }
}

Amazing Things mentioned about guava examples : http://blog.solidcraft.eu/2010/10/googole-guava-v07-examples.html
OrderingExplainedGood 

Monday, June 4, 2012

Creating XML's / Email using Template in Java

If you want to create a simple xml with template StringTemplate is good to use it. It's same like JSP. http://www.antlr.org/wiki/display/ST/Five+minute+Introduction is very nice to use it.

If you have collections, Map and more string operation to create xml using template go for Apache Velocity its very nice. Good tutorial about the velocity examples :
http://today.java.net/pub/a/today/2003/12/16/velocity.html
http://www.java2s.com/Code/Java/Velocity/ShowbasicXMLhandlinginatemplate.htm

Friday, May 11, 2012

Install Apache Ant, build and write Script

Install ant in linux :

a. Download apache ant latest release always : http://ant.apache.org/bindownload.cgi

b. Extract the zip folder or .tar.gz

c. Set environment variable for ANT_HOME and JAVA_HOME in .bashrc file. Add ANT_HOME/bin into PATH Env variable.

  i) which java (This command in terminal tells you the java installed path)
export JAVA_HOME="/usr/lib/jvm/java-6-openjdk"
export ANT_HOME="/home/gubendran/java/apache-ant-1.8.3"
export PATH="${PATH}:${ANT_HOME}/bin"

d. Execute the .bashrc file. source ~/.bashrc

e. Just Read manual from apache  (Click tutorial to do Hello World using Apache Ant. Its simple and excellent : http://ant.apache.org/manual/)

f. Create build.xml file
g. Run the ant script using target name : ant clean compile jar run





Tuesday, May 8, 2012

Websites you should bookmark

Business News
businessinsider.com

Geek
howtogeek.com
theserverside.com

Movie Ratings
http://www.rottentomatoes.com/

Find out crime info. in US street wise
http://www.trulia.com/

News
ndtv.com

Good forum site
stackoverflow.com

Best Website to buy anything 
amazon.com

Free Diet Plans
http://www.sparkpeople.com/

Order kids things in India
http://www.hoopos.com/

Car Websites (Rental cars App)
http://www.zipcar.com/ (Good web-site. You will get car for an hourly basis in nearby location for cheap)
http://www.enterprise.com/car_rental/home.do
getaround.com (Peer-to-Peer rental cars)

Friday, April 13, 2012

Java Code Snippets

1. Convert Set into List in Java 1 liner :
Convert Set to array and convert array to list
Set Ids = new HashSet();
Arrays.asList(Ids.toArray())

Enum Class :

public enum DeviceStates {
SHIPPED ("SHIPPED", 1),
INSTALLED_NOT_REPORTING("INSTALLED_NOT_REPORTING", 2),
NWKDESIGNED_NOT_REPORTING("NWKDESIGNED_NOT_REPORTING", 3),
NOT_INSTALLED_REPORTING("NOT_INSTALLED_REPORTING", 4),
NOT_DESIGNED_REPORTING("NOT_DESIGNED_REPORTING", 5),
REPORTING("REPORTING", 6),
RMA("RMA", 7),
SCRAPPED("SCRAPPED", 8);

private long deviceStateId;
private String deviceStateName;

public long getDeviceStateId() {
return deviceStateId;
}

DeviceStates(String deviceStateName, long deviceStateId) {
this.deviceStateId = deviceStateId;
this.deviceStateName = deviceStateName;
}

public String getDeviceStateName() {
return deviceStateName;
}

public void setDeviceStateName(String deviceStateName) {
this.deviceStateName = deviceStateName;
}
}

public enum status {
         ACTIVE,
         INACTIVE
}

Saturday, April 7, 2012

Make your linux work with skype using Cheese and shell

Follow this link for detailed : http://pkill-9.com/logictech-quick-cam-work-skype-linux/

Ubuntu has the video driver installed by default.

1) Connect your USB WebCam on laptop / desktop
2) Install cheese (apt-get install cheese)
3) Open the cheese and check your video. You should be good. Cheese picks output of (/dev/video0). The video driver for the webcam installed under (ls /dev/video*)
4) Make sure you install skype 32-bit. Since, windows not allowing skype to release latest version and latest bit for linux.
5) Open your skype and in options 'Video' test your video. If not don't panic. Wait to reload the driver for skype.
6) In your $HOME directory create a shell script called skype.sh  with below context (vi $HOME/skype.sh) and save

#!/bin/bash
#
# script preloads the video for linux (v4l) libs needed by skype
#
LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so /usr/bin/skype

 
7) Quit and close  your skype
8) Go to skype properties and in command provide "sh skype.sh"

9) Star your skype and in options 'Video' test your video. you should be good. Since, skype pre-loads.



Thursday, March 22, 2012

java.lang.OutOfMemory in Java

There are 3 OutOfMemory error cases in java we can see frequently in production with default parameters.

1) Java.lang.OutOfMemoryError: Java heap space
2) Java.lang.OutOfMemoryError: PermGen space
3) java.lang.OutOfMemoryError: GC overhead limit exceeded

1) Java.lang.OutOfMemoryError: Java heap space : 

What is java heap space ?

while you try to create an object and there is not enough space in heap to allocate that object you will get this error. 

How to solve ? 

Increase the heap size memory. Use : -Xms512m  -Xmx1024m

a) In production server / linux by adding parameter in JAVA_OPTS 
b) for eclipse add in eclipse.ini file under vmargs
c) In standalone program pass in vm Arguments. 

Note : Xms represent heap size minimum. Xmx represent heap size maximum. Based on the ram you have you can allocate. 


Read more: http://javarevisited.blogspot.com/2011/09/javalangoutofmemoryerror-permgen-space.html#ixzz2KEV0BOiK

2) Java.lang.OutOfMemoryError: PermGen space

what is PermGen Space ? 

PermGen Space of heap is used to store classes and Meta data about classes in Java. When a class is loaded by a classloader it got stored in PermGen space, it gets unloaded only when the classloader which loaded this class got garbage collected. If any object retains reference of classloader than its not garbage collected and Perm Gen Space is not freed up. This causes memory leak in PermGen Space and eventually cause java.lang.OutOfMemoryError: PermGen space

How to Solve ?

Increase the permSize memory. Use : -XX:MaxPermSize=256m

By default JVM allocates 64M for perm space. You can increase it by passing argument. 

a) In production server / linux by adding parameter in JAVA_OPTS 
b) for eclipse add in eclipse.ini file under vmargs
c) In standalone program pass in vm Arguments. 

For tomcat in bin/catalina.sh add options in CATALINA_OPTS for setting the heap and perm space. You can also add below options.
-XX:+UseParallelGC -XX:+UseParallelOldGC -Xloggc:gc.log  -XX:HeapDumpPath=DumpPath -XX:+UseCompressedOops


Read more: http://javarevisited.blogspot.com/2012/01/tomcat-javalangoutofmemoryerror-permgen.html#ixzz2KEWjRaC1

3) java.lang.OutOfMemoryError: GC overhead limit exceeded

Mostly when you use HashMap objects to dump the data you may get this above error. There are 4 ways to avoid the same.

  1. Specify more memory, try something in between like -Xmx1024m first
  2. Work with smaller batches of HashMap objects to process at once if possible
  3. If you have a lot of duplicate strings, use String.intern() on them before putting them into the HashMap (String.intern will save lot of spaces on blank strings and duplicate strings).This will slow down your process. Having said memory utilization on the heap will be very less. Refer article : https://blog.codecentric.de/en/2012/03/save-memory-by-using-string-intern-in-java/ for more 
  4. Use the HashMap(int initialCapacity, float loadFactor) or HashMap(initialCapacity) constructor to tune for your case ex : new HashMap(100000).
You can Disable the error check altogether, via "-XX:-UseGCOverheadLimit". But, you will end up getting heap space OOM error. So, try to use the above methodologies to avoid or tweak your logic to avoid storing huge contents in hashMap objects.

Refer for more OOM : http://www.theserverside.com/news/thread.tss?thread_id=79323 

Eclipse Out Of Memory Error : 
If you use eclipse update memory configuration in JRE
Eclipse -> Window -> Preference -> Java-> Installed JREs -> select the running JRE -> Default VM arguments pass the arguments
"-Xms512m  -Xmx1024m -XX:MaxPermSize=256m"


4 types of Garbage Collectors : Refer : 
http://www.takipiblog.com/garbage-collectors-serial-vs-parallel-vs-cms-vs-the-g1-and-whats-new-in-java-8/
// Below script tag for SyntaxHighLighter