Archive

Archive for the ‘JAVA’ Category

Logging in Java projects … Logback

Logging is as old as cave man writing on walls in Java community.

After using Log4j, SLF4J, today I got a opportunity to start using Logback.

It is very easy to use and configure. The features I liked much are as follows.

1. Default no configuration file required.

2. Option to merge different configuration files to one. (Inclusion of properties files)

3. Option to enable them quickly to check on web in web applications.

4. Supporting groovy style.

5. Better documentation. http://logback.qos.ch/manual/introduction.html

6. Developed by Log4j author. Assuming that he knows all the problems in Log4j and improved Logback a lot. Also a trusted source to use library.

for more check Logback site http://logback.qos.ch/index.html .

Only thing I didn’t like is the name “LogBack”.

-o-

Categories: Logging Tags:

Java – generate meaningful random id


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * This shows how to generate meaningful random id for application. If we need
 * to work in clustered environment, we need to add host name or IP address of
 * system.
 * 
 * @author Bhavani P Polimetla
 * @since May-03-2011
 * 
 */
public class TimeStampID {

	public static void main(String[] args) {

		Format formatter = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss:SSS a");
		System.out.println(formatter.format(new Date()));

		System.out.println("Use as random meaningful ID==>" + getTimeStampID());

		System.out.println("Get Unique ID==>" + getUniqueSystemInfo() + ":"
				+ getTimeStampID());

	}

	public static String getTimeStampID() {
		Format formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return formatter.format(new Date());
	}

	public static String getUniqueSystemInfo() {
		try {
			InetAddress thisIPConfig = InetAddress.getLocalHost();

			// System.out.println("Host Name==>"+thisIPConfig.getHostName());
			// System.out.println("IP Address==>"+thisIPConfig.getHostAddress());

			return thisIPConfig.getHostAddress();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return "";
	}

}

In multithreaded environment, add thread id to make it more unique.
-o-
Output:

2011-05-03,13:46:36:673 PM
Use as random meaningful ID==>20110503134636673
Get Unique ID==>112.243.32.43:20110503134636689

Consuming web service using Apache HTTPClient and SOAP message

April 27, 2011 1 comment

This code is used for quick testing purpose.

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

/**
* This program demonstrates consuming web service using Apache HTTPClient and SOAP message.
* Reference: http://www.webservicex.net/stockquote.asmx?op=GetQuote
* ClassPath: Keep these two files in class path: commons-httpclient-3.0.1.jar, commons-codec-1.4.jar
* @author Bhavani P Polimetla
* @since April-27-2011
*/
public class WSClient {

public static void main(String args[]) {

HttpClient httpClient = new HttpClient();
httpClient.getParams()
.setParameter("http.useragent", "Web Service Test Client");

BufferedReader br = null;
String data = "<?xml version=\"1.0\" encoding=\"utf-8\"?> "
+ "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">   "
+ "<soap12:Body>     "
+ "<GetQuote xmlns=\"http://www.webserviceX.NET/\">       "
+ "<symbol>INFY</symbol>     " + "</GetQuote>   "
+ "</soap12:Body> </soap12:Envelope>";
PostMethod methodPost = new PostMethod(
"http://www.webservicex.net/stockquote.asmx?op=GetQuote");

methodPost.setRequestBody(data);
methodPost.setRequestHeader("Content-Type", "text/xml");

try {
int returnCode = httpClient.executeMethod(methodPost);

if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.out
.println("The Post method is not implemented by this URI");
methodPost.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(methodPost
.getResponseBodyAsStream()));
String readLine;
while (((readLine = br.readLine()) != null)) {
System.out.println(readLine);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
methodPost.releaseConnection();
if (br != null)
try {
br.close();
} catch (Exception fe) {
fe.printStackTrace();
}
}

}
}

Output:

<!--?xml version="1.0" encoding="utf-8"?--><?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetQuoteResponse xmlns="http://www.webserviceX.NET/"><GetQuoteResult><StockQuotes><Stock><Symbol>INFY</Symbol><Last>65.99</Last><Date>4/27/2011</Date><Time>3:46pm</Time><Change>-0.27</Change><Open>66.25</Open><High>66.30</High><Low>65.31</Low><Volume>1689441</Volume><MktCap>37.701B</MktCap><PreviousClose>66.26</PreviousClose><PercentageChange>-0.41%</PercentageChange><AnnRange>53.28 - 77.92</AnnRange><Earns>2.62</Earns><P-E>25.29</P-E><Name>Infosys Technolog</Name></Stock></StockQuotes></GetQuoteResult></GetQuoteResponse></soap:Body></soap:Envelope>

Java Reverse Engineering – www.maintainj.com

March 25, 2011 Leave a comment

Many times we start on existing project.
First challenge is to understand existing code and flow.

The best tool I come across today is www.maintainj.com
Looked at the demos and they are really good.
License price is affordable as individual. 100$

Important Note:
Also generating diagrams at the end of the project helps us to find if there are any deviations by developers from given original design and architecture.

If you want to try free versions check my other post

http://polimetla.com/2011/02/04/generate-class-diagrams-sequence-diagrams-uml-using-maven/

Categories: Core Java

What are the best practices for Java development team?

March 18, 2011 2 comments

At individual level
In Eclipse IDE use following files and share with team to maintain consistency.

PMD-rules-eclipse.xml
Eclipse-Clean-Config.xml
Eclipse-Code-Formatter.xml
Eclipse-Code-Template.xml
Eclipse-Import-Order.importorder

TestNG Test Cases
Emma plug in to check code coverage
Tie the memory and performance numbers to test cases

At team level
What happens in Hudson?
Configure following in Hudson, so that it is easy to check after each build.

Code Coverage Report
Open Tasks Report
PMD Report
Surefire Test Report

At organizational level
How to compare different projects / modules in organization?
Use SONAR and use maven plug in to push the data to Sonar server.

Code Coverage
Comments
Complexity
Lines of Code
PMD
Test Success

References:
http://java.net/projects/hudson/
http://www.sonarsource.org/
http://pmd.sourceforge.net/
http://emma.sourceforge.net/

Java Memory Monitoring

March 1, 2011 Leave a comment

Check the following code. See the graph below.


public class MemTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Memory Test");

		long longTest = 1;
		String sb = null;
		for (long lCount = 1; lCount < Long.MAX_VALUE; lCount++) {

			if (longTest <= 0) 	
			longTest = 1; 			
                        
                       longTest = longTest * lCount; 			
                       sb = "\n" + sb + "MemoryTest loop==>" + lCount + " long==>"
					+ longTest;
			System.out.println("lCount==>" + lCount);
		}

	}

}

System will hang in next couple of minutes…if the memory consumption continuous like this.

Now the code is improved….


public class MemTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Memory Test");

		long longTest = 1;
		String sb = null;
		for (long lCount = 1; lCount < Long.MAX_VALUE; lCount++) {

			if (longTest <= 0) 				
                         longTest = 1; 			
                         
                          //Using this number to show difference in graph in beginning and later
                          if (lCount > 10000)
				sb = null;

			longTest = longTest * lCount;
			sb = "\n" + sb + "MemoryTest loop==>" + lCount + " long==>"
					+ longTest;
			System.out.println("lCount==>" + lCount);
		}

	}

}

Monitor the application CPU / Memory while running for couple of hours (Min 24 hours to 48 hours) before going to release (QA/Production).
If the line is going up …it is going to blow up……

Thank you,
Bhavani P Polimetla

Java – how to measure time in Java efficiently

February 9, 2011 Leave a comment

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * This program demonstrates how to measure time in Java efficiently.
 *
 * @author Bhavani P Polimetla
 * @since Feb-09-2011
 *
 */
public class TimeTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// Test 1: Measure Time. (Can't measure methods which take very small
		// time in nano seconds.)
		long start = System.currentTimeMillis();
		workingHard();
		long end = System.currentTimeMillis();
		System.out.println("Test 1 Time==>" + (end - start) + " milli seconds");

		// Test 2: Measure Time. Date constructor uses
		// System.currentTimeMillis()
		// This is not good way
		start = (new Date()).getTime();
		workingHard();
		end = (new Date()).getTime();
		System.out.println("Test 2 Time==>" + (end - start) + " milli seconds");

		// Test 3: Measure Time in Nano seconds
		start = System.nanoTime();
		workingHard();
		end = System.nanoTime();
		System.out.println("Test 3 Time==>" + (end - start) + " nano seconds");

		// Conversion
		long duration = TimeUnit.NANOSECONDS.toMicros((end - start));
		System.out.println("Test 4 Time==>" + duration + " micro seconds");

	}

	public static void workingHard() {
		long k = 0;
		for (int i = 0; i < 1000; i++) { 			k = k + i; 		} 		System.out.println("I did big addition. : ) Final Total==>" + k);
	}

}

Result:
Test 1 Time==>0 milli seconds
I did big addition. : ) Final Total==>499500
Test 2 Time==>0 milli seconds
I did big addition. : ) Final Total==>499500
Test 3 Time==>462671 nano seconds
Test 4 Time==>462 micro seconds

JAMON API Setup – Notes

February 9, 2011 Leave a comment

http://jamonapi.sourceforge.net/

Download latest copy and install the jar file to maven repository
mvn install:install-file -Dfile=x:\download\jamon\jamonapi_2.7\jamon-2.7.jar -DgroupId=com.jamonapi -DartifactId=jamon -Dversion=2.7 -Dpackaging=jar -DgeneratePom=true

Add this dependency to pom file

<dependency>
	<groupId>com.jamonapi</groupId>
	<artifactId>jamon</artifactId>
	<version>2.7</version>
	<scope>provided</scope>
</dependency>

Add this to .java file where you want to measure the performance

import com.jamonapi.Monitor;
import com.jamonapi.MonitorFactory;

In method begenning add

Monitor mon = MonitorFactory.start("XYZ:Method Name");

In method ending add

mon.stop();

Identify place to get all above times and print them at the end of program
Print in .html file to see nice report.

String fileData = MonitorFactory.getReport();
Log.info("Performance Report==>"+fileData);

-end-

Generate Class Diagrams, Sequence Diagrams (UML) using Maven

February 4, 2011 Leave a comment

——————————————————
CLASS DIAGRAMS

Note: Graphviz ‘dot’ binary must be available in PATH, or the images wont be generated.

Download and install Graphviz from http://www.graphviz.org/

<build>
    <plugins>

      <!-- mvn javadoc:javadoc will generate java docs along with UML Diagrams -->
	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-javadoc-plugin</artifactId>
		<version>2.7</version>
		<configuration>
		  <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
		  <docletArtifact>
		    <groupId>org.umlgraph</groupId>
		    <artifactId>doclet</artifactId>
		    <version>5.1</version>
		  </docletArtifact>
		  <additionalparam>-views</additionalparam>
		  <useStandardDocletOptions>true</useStandardDocletOptions>
		</configuration>
	</plugin>

    </plugins>
  </build>

Conclusion: Finally it looks like showing images on top of java docs. But those are already available as part of java docs in text format.
I didn’t felt that this is much useful at this time.

http://www.umlgraph.org/

http://wiki.wsmoak.net/cgi-bin/wiki.pl?UMLGraph

http://maven.apache.org/plugins/maven-javadoc-plugin/examples/alternate-doclet.html

http://maven.apache.org/maven-1.x/plugins/javadoc/faq.html#classdiagrams

——————————————————

SEQUENCE DIAGRAMS

http://code.google.com/p/jtracert/wiki/GeneratingSequenceDiagramsFromUnitTests

**** Best tool to generate sequence diagram from Unit Tests
This will help to understand code easily.

http://www.jsonde.com/

——————————————————

FREE UML Modeling Tool: Astah community edition

Maven, Restlet and Spring Framework

January 19, 2011 Leave a comment
Categories: Restlet
Follow

Get every new post delivered to your Inbox.