Archive

Archive for the ‘Core Java’ Category

JSch – Java – Telnet Example

July 20, 2011 1 comment

Problem Statement: We have one application running in 10 servers. How to grep for exception or key word in all of them with one single command?
Solution: Use JSch and pass the command to all 10 servers and print the data on java console.
Download JSch jar from following site and put it in classpath.
http://www.jcraft.com/jsch/

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

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class JavaTelnetExample {

	public static void main(String[] arg) {
		try {
			JSch jsch = new JSch();
			Session session = jsch.getSession("userid", "hostname", 22);
			session.setPassword("password");
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);

			session.connect();
			System.out.println("==>" + executeCommand(session, "date"));
			System.out.println("==>" + executeCommand(session, "ls"));
			System.out.println("==>" + executeCommand(session, "who"));
			System.out.println("==>" + executeCommand(session, "tail -50 /path/abcd.log"));

			session.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String executeCommand(Session session, String command)
			throws Exception {
		ChannelExec channel = (ChannelExec) session.openChannel("exec");
		channel.setCommand(command);
		channel.setInputStream(null);
		channel.setErrStream(System.err);
		channel.connect();

		InputStream in = channel.getInputStream();

		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String line;
		StringBuffer sb = new StringBuffer();
		while ((line = br.readLine()) != null) {
				sb.append(line + '\n');
		}
		channel.disconnect();

		return sb.toString();
	}
}

Categories: Core Java Tags: ,

Java – Working with Maven POM through java code.

June 14, 2011 Leave a comment

import java.io.File;
import java.io.FileReader;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;

/**
 * Add these files in classpath
 * maven-artifact-2.0.6.jar,maven-core-2.0.6.jar,
 * maven-model-2.0.6.jar,maven-project-2.0.6.jar,
 * plexus-utils-2.0.7.jar
 * 
 * @author polimeb
 * 
 */
public class ParseMavenPOM {

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

		String fileName = "c:/project/abcd/pom.xml";

		try {
			Model model = null;
			FileReader reader = null;
			MavenXpp3Reader mavenreader = new MavenXpp3Reader();

			File pomfile = new File(fileName);
			reader = new FileReader(pomfile);
			model = mavenreader.read(reader);

			MavenProject project = new MavenProject(model);
			System.out.println(project.getVersion());

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}

How to find character encoding of a text file (.properties, .xml, …etc)

May 27, 2011 Leave a comment

We need to make sure that all .properties, xml files are are in same encoding. Other wise app servers give trouble in starting and it is difficult to find out.
Note: Download and add jar in classpath from http://site.icu-project.org/

import java.io.File;

import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;

/**
 * This program provides file encoding for given file.
 *
 * Make sure that all files are using same encoding as parameter passed to JVM.
 *
 * http://userguide.icu-project.org/conversion/detection#TOC-CharsetDetector
 *
 */
public class EncodingUtil {

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

		String PATH = "e://folder_name//";

		try {
			printFileEncoding(PATH + "a.properties");
			printFileEncoding(PATH + "b.properties");
			printFileEncoding("D://path2//asdf.xml");
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	private static void printFileEncoding(String fileName) {
		try {
			File file = new File(fileName);
			file = new File(fileName);
			byte fileContent[] = new byte[(int) file.length()];
			checkEncoding(fileName, fileContent);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private static void checkEncoding(String fileName, byte[] byteData) {
		CharsetDetector detector;
		CharsetMatch match;

		detector = new CharsetDetector();

		detector.setText(byteData);
		match = detector.detect();

		StringBuffer sbData = new StringBuffer();
		sbData.append("fileName==>").append(fileName);
		sbData.append(" Confidence==>").append(match.getConfidence());
		sbData.append(" Encoding==>").append(match.getName());
		System.out.println(sbData.toString());
	}

}

Categories: Core Java

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

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

Java ex.printStackTrace() vs LOG.error(“message”,ex)

August 13, 2010 Leave a comment

Problem Statement: Which one is best ex.printStackTrace() or LOG.error(“”,ex);

As good practice it is better to use LOG.error.
Performance wise LOG is performing better when number of calls are increased.

import java.io.IOException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;

public class LogTest {

	private static final Logger LOG = Logger.getLogger(LogTest.class);

	public static void loadLogConfig() {
		// BasicConfigurator.configure();
		Logger rootLogger = Logger.getRootLogger();
		rootLogger.setLevel(Level.INFO);
		PatternLayout layout = new PatternLayout(
				PatternLayout.DEFAULT_CONVERSION_PATTERN);
		rootLogger.addAppender(new ConsoleAppender(layout));
		try {
			RollingFileAppender rfa = new RollingFileAppender(layout,
					"performancetest.log");
			// rfa.setMaximumFileSize(1000);
			rootLogger.addAppender(rfa);

		} catch (IOException e) {
			LOG.error("", e);
		}
	}

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

		long start = System.currentTimeMillis();
		calc1();
		long stop = System.currentTimeMillis();

		long start2 = System.currentTimeMillis();
		calc2();
		long stop2 = System.currentTimeMillis();

		LOG.info("Total Time Took ex.printStackTrace():" + (stop - start));
		LOG.info("Total Time Took LOG.error(\"\",ex):" + (stop2 - start2));

		// Result 1 for LOOP_SIZE = 99000;
		// Total Time Took ex.printStackTrace():13484
		// Total Time Took LOG.error("",ex):12969

		// Result 2 for LOOP_SIZE = 99000;
		// Total Time Took ex.printStackTrace():13453
		// Total Time Took LOG.error("",ex):13171

	}

	private static int LOOP_SIZE = 100;

	public static void calc1() {
		int k;
		for (int i = 0; i < LOOP_SIZE; i++) {
			try {
				k = i / 0;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	public static void calc2() {
		int k;
		for (int i = 0; i < LOOP_SIZE; i++) {
			try {
				k = i / 0;
			} catch (Exception ex) {
				LOG.error("", ex);
			}
		}
	}

}

Java name clash … have the same erasure

August 11, 2010 Leave a comment

Java 1.5 Compilation Error
name clash: add(java.util.List<Company>) and add(java.util.List<Long>) have the same erasure

Before
public List<Long> getCompanyIds(List<Company> comp)
public String getCompanyIds(List<Long> compIds)

After
public List<Long> getCompanyIdsList(List<Company> comp)
public String getCompanyIds(List<Long> compIds)

-o-

Java Currency Format -1234.34 to -$1,234

Question: How to format currency. Example: -1234.34 to -$1,234

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

public class CurrencyTest {

	public static void main(String[] test) {
		double currency = -1234;
		NumberFormat dollarFormatter;
		dollarFormatter = NumberFormat.getCurrencyInstance(Locale.US);

		if (dollarFormatter instanceof DecimalFormat) {
			((DecimalFormat) dollarFormatter).setMaximumFractionDigits(0);
			((DecimalFormat) dollarFormatter).setNegativePrefix("-$");
			((DecimalFormat) dollarFormatter).setNegativeSuffix("");
		}

		String text = dollarFormatter.format(currency);
		System.out.println(text);
	}
}

Input: -1234.34
Output: -$1,234

com.sun.tools.javac.code.Symbol$CompletionFailure

April 21, 2010 Leave a comment

Problem:
[INFO] ————————————————————-
[ERROR] COMPILATION ERROR :
[INFO] ————————————————————-
[ERROR] Failure executing javac, but could not parse the error:
An exception has occurred in the compiler (1.5.0_14). Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport) after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report. Thank you.
com.sun.tools.javac.code.Symbol$CompletionFailure: file javax\ejb\TransactionAttribute.class not found

Solution:
Add respective jar file to script.

jboss
jboss-ejb-api
4.2.1.GA

Reference: http://bugs.sun.com/view_bug.do?bug_id=6550655

Categories: Core Java

Java Split String with Pipe (|) Parameter

March 31, 2010 1 comment

Problem: Try to split String which is having delimiter as pipe(|)

public class TestSplit
{
  public static void main( String[] args )
  {
     String DELIMETER = "@";
    // String DELIMETER = "|";
    

    String line = "field1" + DELIMETER + "field2";

    String[] tempList = line.split( DELIMETER );
    int sizeOfArray = tempList.length;

    System.out.println( "sizeOfArray==>" + sizeOfArray );

    for( int i = 0; i < tempList.length; i++ ) {
      System.out.println( i + "==>" + tempList[i] );
    }
  }
}

Why Pipe(|) wont work as delimeter?

Java Syntax
String[] split(String regex)
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
Logical operators
X|Y Either X or Y

-o-

Follow

Get every new post delivered to your Inbox.