Archive

Archive for the ‘JAVA’ Category

Java Reflection – Print all fields in VO / DT class

May 15, 2012 Leave a comment

VO: Value Object Class
DT: Data Transfer Class

Many times we end up writing too lengthy code to print all fields of above classes.

public String toString() {
		StringBuffer sb = new StringBuffer();
		for (Field field : this.getClass().getDeclaredFields()) {
			try {
				field.setAccessible(true);
				String name = field.getName();
				Object value = field.get(this);
				sb.append("#").append(name).append("=>").append(value);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return sb.toString();
	}

Categories: Core Java

Java JMX Client


import java.io.IOException;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class JMXClient {
public static void main(String[] args) {
try {
HashMap env = new HashMap();

String[] credentials = new String[] { "userid", "password" };
env.put("jmx.remote.credentials", credentials);

JMXServiceURL url = new JMXServiceURL(
"service:jmx:rmi:///jndi/rmi://server:1234/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
String domains[] = mbsc.getDomains();
for (int i = 0; i < domains.length; i++) {
System.out.println("Domain[" + i + "] = " + domains[i]);
}

listMBeans(mbsc, "ABC:type=TYPENAME,name=name2");

jmxc.close();
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* List all MBeans and their attributes.
*/
public static void listMBeans(MBeanServerConnection server, String path)
throws Exception {
javax.management.ObjectName on = new javax.management.ObjectName(path);
final Set names = server.queryNames(on, null);
for (final Iterator i = names.iterator(); i.hasNext();) {
ObjectName name = (ObjectName) i.next();
System.out.println("Got MBean: " + name);

try {
MBeanInfo info = server.getMBeanInfo((ObjectName) name);
MBeanAttributeInfo[] attrs = info.getAttributes();
if (attrs == null)
continue;
for (int j = 0; j < attrs.length; j++) {
if (attrs[j].isReadable()) {
try {

Object o = server.getAttribute(name, attrs[j]
.getName());
System.out.println("==>" + attrs[j].getName()
+ " = " + o);
} catch (Exception x) {
System.err.println("JmxClient failed to get "
+ attrs[j].getName());
}
}
}
} catch (Exception x) {
System.err.println("JmxClient failed to get MBeanInfo: " + x);
// x.printStackTrace(System.err);
}
}
}

public static void listMBeanAttributes_all(MBeanServerConnection server)
throws IOException {
final Set names = server.queryNames(null, null);
for (final Iterator i = names.iterator(); i.hasNext();) {
ObjectName name = (ObjectName) i.next();
System.out.println("Got MBean: " + name);

try {
MBeanInfo info = server.getMBeanInfo((ObjectName) name);
MBeanAttributeInfo[] attrs = info.getAttributes();
if (attrs == null)
continue;
for (int j = 0; j < attrs.length; j++) {
if (attrs[j].isReadable()) {
try {

Object o = server.getAttribute(name, attrs[j]
.getName());
System.out.println("==>" + attrs[j].getName()
+ " = " + o);
} catch (Exception x) {
System.err.println("JmxClient failed to get "
+ attrs[j].getName());
// x.printStackTrace(System.err);
}
}
}
} catch (Exception x) {
System.err.println("JmxClient failed to get MBeanInfo: " + x);
x.printStackTrace(System.err);
}
}
}
}

Categories: J2EE Tags: ,

Dozer – boolean mapping issue – resolved

March 8, 2012 Leave a comment

Problem Statement:

http://sourceforge.net/tracker/index.php?func=detail&aid=2893120&group_id=133517&atid=727368

================================================================================================

Here is a statement from wsdl2java that may help.

http://www.coderanch.com/t/550457/Web-Services/java/wsdl-java-replace-primitives

If the WSDL says that an object can be nillable, that is the caller may choose to return a value of nil, then the primitive data types are replaced by their wrapper classes, such as Byte, Double, Boolean, etc.

http://ws.apache.org/axis/java/user-guide.html#HowYourJavaTypesMapToSOAPXMLTypes

================================================================================================

This is not working as specified

http://dozer.sourceforge.net/documentation/simpleproperty.html

Recursive Mapping (bi-directional)

Dozer supports full Class level mapping recursion. If you have any complex types defined as field level mappings in your object, Dozer will search the mappings file for a Class level mapping between the two Classes that you have mapped. If you do not have any mappings, it will only map fields that are of the same name between the complex types.

================================================================================================

Final Solution

<field>
<a is-accessible=”true”>fieldName</a>
<b is-accessible=”true”>fieldName</b>
</field>

OR

<!–
<field>
<a get-method=”getfieldName”>fieldName</a>
<b set-method=”setfieldName”>fieldName</b>
</field>
–>

================================================================================================

Categories: JAVA

Spring Web Services 2 Cookbook

February 24, 2012 Leave a comment

Spring Web Services 2 Cookbook
Paperback: 322 pages
Publisher: Packt Publishing (May 13, 2012)
Language: English
ISBN-10: 1849515824
ISBN-13: 978-1849515825
Books is available at Amazon.com

Spring Web Services 2 Cookbook

This is very nice book on Spring Web Services.

Java – USB – Lights

November 30, 2011 Leave a comment

Problem Statement:

We need to display lights and play sounds for different activities in IT Departments.

Example: Specific production server went down. Or Build failed. Or Too much traffic on network, got email from xyz….etc

Solution 1:

DelCom Product: This comes with DLL and we need to write Java JNI.

http://www.delcomproducts.com/products_USBLMP.asp

Solution 2:

Arduino Micro Controller

http://joe.blog.freemansoft.com/2011/04/extreme-feedback-aka-status-lights-das.html

http://arduino.cc/en/

http://cweiske.de/tagebuch/usblamp-monitoring.htm

Writing simple USB Driver: http://www.linuxjournal.com/article/7353

Hudson Build Lights: http://www.rallydev.com/engblog/tag/indicator-lights/

-o-

Categories: Hardware, Hudson, JAVA

Java – Graphs and Charts

August 22, 2011 Leave a comment

How to draw graphs and charts

1. If you want to generate bmp, jpg formats better to use

http://www.jfree.org/jfreechart/ Better with Swing or to email images.
http://cewolf.sourceforge.net/new/index.html Better for JSP/Servlet integration.

2. For more detailed research, Excel is best. Create template with graphs and fill the data using Apache POI API.
http://poi.apache.org/

3. For better quick online graphs try following
http://code.google.com/apis/chart/interactive/docs/gallery/linechart.html

http://code.google.com/apis/ajax/playground/?type=visualization#line_chart

http://webdesignledger.com/resources/13-useful-javascript-solutions-for-charts-and-graphs

-o-

Categories: J2EE, J2SE Tags:

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: ,

Jetty JSP with Java 1.6

June 23, 2011 Leave a comment

Problem statement: JSPs are not working in embedded Jetty.

http://docs.codehaus.org/display/JETTY/Jsp+Configuration

Add following to web.xml file

<servlet id="jsp">
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>logVerbosityLevel</param-name>
        <param-value>DEBUG</param-value>
    </init-param>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>keepgenerated</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.jsp</url-pattern>
    <url-pattern>*.jspf</url-pattern>
    <url-pattern>*.jspx</url-pattern>
    <url-pattern>*.xsp</url-pattern>
    <url-pattern>*.JSP</url-pattern>
    <url-pattern>*.JSPF</url-pattern>
    <url-pattern>*.JSPX</url-pattern>
    <url-pattern>*.XSP</url-pattern>
  </servlet-mapping>

Add following to support JSP with Java 1.6

	<dependency>
		<groupId>org.mortbay.jetty</groupId>
		<artifactId>jetty</artifactId>
		<version>6.1.26</version>
	</dependency>       
	<dependency>
		<groupId>org.mortbay.jetty</groupId>
		<artifactId>jetty-util</artifactId>
		<version>6.1.26</version>
	</dependency>
	<dependency>
		<groupId>org.mortbay.jetty</groupId>
		<artifactId>servlet-api-2.5</artifactId>
		<version>6.1.14</version>
	</dependency>
	<dependency>
		<groupId>org.mortbay.jetty</groupId>
		<artifactId>jsp-2.1</artifactId>
		<version>6.1.14</version>
	</dependency>
	<dependency>
		 <groupId>org.mortbay.jetty</groupId>
		 <artifactId>jsp-api-2.1</artifactId>
		 <version>6.1.14</version>
	</dependency>
	<dependency>
		<groupId>org.apache.ant</groupId>
		<artifactId>ant</artifactId>
		<version>1.8.1</version>
	</dependency>

Categories: J2EE 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
Follow

Get every new post delivered to your Inbox.