Java Decompiler is a compiler it converts byte code form of java source file (.class file) into actual java source file. JD is a powerful decompiler tool and it converts the .class files into source file accurately.
Sunday, January 31, 2010
Java Decompiler Download
Posted by Mohan at View blog reactions 6:08 AM 0 comments
Labels: CoreJava
Tuesday, December 22, 2009
How to Execute Shell Script From Java
Here is an example shows how to execute the shell scripts from java programs.
If you want to execute the below program set the java path in Unix environment.
export PATH=$PATH:/usr/jdk1.5.0/bin
export CLASSPATH=$CLASSPATH:/usr/jdk1.5.0/bin
create a shell script like shellscript.sh
#!/bin/bash
clear
echo "Good morning, world."
then change the permission for this script.if you execute the shell script you need execute permission.
chmod 777 shellscript.sh
try
./shellscript.sh
From java program
import java.io.IOException;
public class JavaScript {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("/root/shellscript.sh");
System.out.println("Working Fine");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Posted by Mohan at View blog reactions 9:09 AM 0 comments
Labels: CoreJava
Saturday, December 19, 2009
Java Date Format
SimpleDateFormat Example
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String args[]) {
Date date = new Date();
String DATE_FORMAT = "MM:dd:yyyy";
// or
// String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat simDateFormat = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + simDateFormat.format(date));
// or If you want display time with AM/PM
String TIME_FORMAT = "HH:mm:ss a";
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
System.out.println("Now time is " + timeFormat.format(date));
// Today date and Time
System.out.println("Date and time is " + simDateFormat.format(date)
+ " " + timeFormat.format(date));
}
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StrToDate {
public static void main(String[] args) {
String stri = "18/12/2009";
DateFormat simDateForm = new SimpleDateFormat("dd/MM/yyyy");
Date dstr;
try {
dstr = (Date) simDateForm.parse(stri);
System.out.println("Date is" + dstr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Posted by Mohan at View blog reactions 2:11 AM 0 comments
Labels: CoreJava
Thursday, December 17, 2009
Java Usb Communication
Like a serial port we can communicate with USB from java application
Each USB port on a computer is assigned a unique identification number (port ID) by the USB controller. When a USB device is attached to a USB port, this unique port ID is assigned to the device.
Communication on the USB network can use any one of four different data transfer types:
Control transfers: These are short data packets for device control and configuration, particularly at attach time.
Bulk transfers: These are data packets in relatively large quantities. Devices like scanners or SCSI adapters use this transfer type.
Interrupt transfers: These are data packets that are polled periodically. The host controller will automatically post an interrupt at a specified interval.
Isochronous transfers: These are data streams in real time with higher requirements for bandwidth than for reliability. Audio and video devices generally use this transfer type.
JSR80 API for java USB communication
Download the above api from the following location.
http://jcp.org/aboutJava/communityprocess/final/jsr080/index.htmhttp://javax-usb.org/
LibUSB
LibusbJava is a Java wrapper for the libusb 0.1 and libusb-win32 USB library.
Download the library from the following location
http://sourceforge.net/projects/libusbjava/
Posted by Mohan at View blog reactions 8:09 AM 1 comments
Labels: CoreJava
Wednesday, December 9, 2009
Java GUI Hanging Issue
The problem shall be because of the following reasons.
- Not using of Event Dispatching Thread (EDT) properly for the events triggered from the operator.
- Usually event dispatching thread should not contain the long running operations.
- And unwanted usage of threads which leads to high CPU usage some times might leads to hang USM.
- Unused objects are not set for garbage collection.Which leads to high heap usage and throws OutofMemory exception.
- Unnecessary usage of Collection classes leads to heap memory occupation.
- Critical operations if not synchronized may lead to deadlock and resulting the Java UI to hang.
- And costly operation like Cell Renderer used for the JTables, which will be triggered to paint the GUI very frequently which takes the EDT thread. So that Java UI will hang most very often.
- And also when the NEs are dragged and dropped to the working view the getValueAt() method will be called for each cell of the JTable. So this again takes significant amount of time in painting the value at each cell of the JTable. So this leads to block the Java GUI.
Solutions:-
The problem can be solved by removing unwanted usage of Collection classes (Vector, Hashtable etc…) and avoiding usage of loops in the run method of threads which leads to high CPU usage.
Posted by Mohan at View blog reactions 9:46 AM 0 comments
Labels: CoreJava
Friday, December 4, 2009
How To Set Environment Variable In Java
( . indicates current path )
Posted by Mohan at View blog reactions 8:45 AM 0 comments
Labels: CoreJava
Wednesday, December 2, 2009
Java Native Interface
import java.util.StringTokenizer;
public class PINGMain {
String ipaddress = null;
boolean defragment = false;
int num = 2;
String success ="success";
private String destination;
private String packetSize;
private String bytes;
private String time;
private String ttl;
protected native String ping(String[] ipaddress);
public PINGMain() {
super();
try {
System.loadLibrary("ping");
} catch (UnsatisfiedLinkError e) {
e.printStackTrace();
}
singlePing();
}
private void singlePing() {
int a = 10;
int b = 20;
String string=null;
while(true) {
string = ping(ipaddr);
//System.out.println(string);
StringTokenizer strToken = new StringTokenizer(string);
int numToken = strToken.countTokens();
destination = strToken.nextToken();
bytes = strToken.nextToken();
time= strToken.nextToken();
ttl = strToken.nextToken();
System.out.println("\n Reply from"+" "+destination+" "+"bytes"+" "+bytes+" "+"Time"+" "+time+" "+"TTL"+" "+ttl);
}
}
private String continuousPing() {
return null;
}
private String disconnect() {
//unLoadPing();
//System.out.println("Unloaded SuccessFully");
return success;
}
private void unLoadPing() {
// unLoad();
}
/**
* @return
*/
private String getStatistics() {
return null;
}
public static void main(String ar[]) {
new PINGMain();
}
}
javac PINGMain.java
This command will generate a PINGMain.class file in the current directory.
Next we will use the javah tool to generate a JNI-style header file that is useful when implementing the native method in C. You can run javah on the PINGMain class as follows:
javah -jni PINGMain
The command shown above generates a file named PINGMain.h.
Step 4:
Writing the C implementation (PINGMain.c) of the native method
The JNI-style header file generated by javah helps you to write C or C++ implementations for the native method. The function that you write must follow the -prototype specified in the generated header file.
#pragma comment(lib, "wsock32.lib")
#include "jni.h"
#include "com_dtt_traffic_ping_PINGMain.h"
#include "stdlib.h"
#include "StdAfx.h"
#include <windows.h>
#include <winsock.h>
#include <stdio.h>
#include <string.h>
int packetsize;
int count;
char *data;//Ping info
typedef struct tagIPINFO
{
u_char Ttl; // Time To Live
u_char Tos; // Type Of Service
u_char IPFlags; // IP flags
u_char OptSize; // Size of options data
u_char FAR *Options; // Options data buffer
}IPINFO, *PIPINFO;
typedef struct tagICMPECHO
{
u_long Source; // Source address
u_long Status; // IP status
u_long RTTime; // Round trip time in milliseconds
u_short DataSize; // Reply data size
u_short Reserved; // Unknown
void FAR *pData; // Reply data buffer
IPINFO ipInfo; // Reply options
}ICMPECHO, *PICMPECHO;
// ICMP.DLL Export Function Pointers
HANDLE (WINAPI *pIcmpCreateFile)(VOID);
BOOL (WINAPI *pIcmpCloseHandle)(HANDLE);
DWORD (WINAPI *pIcmpSendEcho)
(HANDLE,DWORD,LPVOID,WORD,PIPINFO,LPVOID,DWORD,DWORD);
//
//
char *pingFun(char *dest[])
{
int timeout;
char ping_Resp[2048];
WSADATA wsaData; // WSADATA
ICMPECHO icmpEcho; // ICMP Echo reply buffer
HANDLE hndlIcmp; // LoadLibrary() handle to ICMP.DLL
HANDLE hndlFile; // Handle for IcmpCreateFile()
LPHOSTENT pHost; // Pointer to host entry structure
struct in_addr iaDest; // Internet address structure
DWORD *dwAddress; // IP Address
IPINFO ipInfo; // IP Options structure
int nRet; // General use return code
DWORD dwRet; // DWORD return code
int x;
packetsize = atoi(dest[2]);
count = atoi(dest[5]);
timeout = atoi(dest[4]);
// Dynamically load the ICMP.DLL
hndlIcmp = LoadLibrary("ICMP.DLL");
if (hndlIcmp == NULL)
{
fprintf(stderr,"nCould not load ICMP.DLLn");
return;
}
// Retrieve ICMP function pointers
pIcmpCreateFile = (HANDLE (WINAPI *)(void))
GetProcAddress(hndlIcmp,"IcmpCreateFile");
pIcmpCloseHandle = (BOOL (WINAPI *)(HANDLE))
GetProcAddress(hndlIcmp,"IcmpCloseHandle");
pIcmpSendEcho = (DWORD (WINAPI *)
(HANDLE,DWORD,LPVOID,WORD,PIPINFO,LPVOID,DWORD,DWORD))
GetProcAddress(hndlIcmp,"IcmpSendEcho");
// Check all the function pointers
if (pIcmpCreateFile == NULL ||
pIcmpCloseHandle == NULL ||
pIcmpSendEcho == NULL)
{
fprintf(stderr,"nError getting ICMP proc addressn");
FreeLibrary(hndlIcmp);
return;
}
// Init WinSock
nRet = WSAStartup(0x0101, &wsaData );
if (nRet)
{
fprintf(stderr,"nWSAStartup() error: %dn", nRet);
WSACleanup();
FreeLibrary(hndlIcmp);
return;
}
// Check WinSock version
if (0x0101 != wsaData.wVersion)
{
fprintf(stderr,"nWinSock version 1.1 not supportedn");
WSACleanup();
FreeLibrary(hndlIcmp);
return;
}
// Lookup destination
// Use inet_addr() to determine if we're dealing with a name
// or an address
iaDest.s_addr = inet_addr(dest[1]);
if (iaDest.s_addr == INADDR_NONE)
pHost = gethostbyname(dest[1]);
else
pHost = gethostbyaddr((const char *)&iaDest,
sizeof(struct in_addr), AF_INET);
if (pHost == NULL)
{
fprintf(stderr, "n%s not foundn", dest[1]);
WSACleanup();
FreeLibrary(hndlIcmp);
return;
}
// Tell the user what we're doing
/*printf("nPinging %s [%s]", pHost->h_name,
inet_ntoa((*(LPIN_ADDR)pHost->h_addr_list[0])));*/
// Copy the IP address
dwAddress = (DWORD *)(*pHost->h_addr_list);
// Get an ICMP echo request handle
hndlFile = pIcmpCreateFile();
// for (x = 0; x < 4; x++)
// Set some reasonable default values
ipInfo.Ttl =dest[3];
ipInfo.Tos = 0;
ipInfo.IPFlags = 0;
ipInfo.OptSize = 0;
ipInfo.Options = NULL;
//icmpEcho.ipInfo.Ttl = 256;
// Reqest an ICMP echo
dwRet = pIcmpSendEcho(
hndlFile, // Handle from IcmpCreateFile()
*dwAddress, // Destination IP address
packetsize, // Pointer to buffer to send
0, // Size of buffer in bytes
&ipInfo, // Request options
&icmpEcho, // Reply buffer
sizeof(struct tagICMPECHO),
timeout); // Time to wait in milliseconds
// Print the results
iaDest.s_addr = icmpEcho.Source;
/* printf("\n Reply from %s Time=%ldms TTL=%d",
inet_ntoa(iaDest),
icmpEcho.RTTime,
icmpEcho.ipInfo.Ttl);*/
sprintf(ping_Resp,"%s %d %ld %d",
inet_ntoa(iaDest),
packetsize,
icmpEcho.RTTime,
icmpEcho.ipInfo.Ttl);
if (icmpEcho.Status)
{
// printf("nError: icmpEcho.Status=%ld",
// icmpEcho.Status);
printf("\n Request timed out");
//break;
}
//printf("\n");
// Close the echo request file handle
pIcmpCloseHandle(hndlFile);
FreeLibrary(hndlIcmp);
WSACleanup();
return ping_Resp;
}
JNIEXPORT jstring JNICALL Java_com_dtt_traffic_ping_PINGMain_ping
(JNIEnv *env, jclass job, jobjectArray oarr)
{
jsize argc = (*env)->GetArrayLength(env, oarr);
/* Declare a char array for argv */
int i;
char const* argv[128];
for (i = 1; i < 6; i++)
{
/* obtain the current object from the object array */
jobject myObject = (*env)->GetObjectArrayElement(env, oarr, i-1);
/* Convert the object just obtained into a String */
const char *str = (*env)->GetStringUTFChars(env,myObject,0);
/* Build the argv array */
argv[i] = str;
}
data=(char *)malloc(sizeof(char) * 2048);
sprintf(data,"%s",pingFun(argv),"-10000");
// printf("Data %s ",data);
return ((*env)->NewStringUTF(env,data));
}
Step5:
Compiling the C implementation into a native library, creating ping.dll or libPINGMain.so
On Solaris or Linux, the following command builds a shared library called libPINGMain.so:
cc -G -I/java/include -I/java/include/solaris
PINGMain.c -o libPINGMain.so
On Win32, the following command builds a dynamic link library (DLL) ping.dll using the Microsoft Visual C++ compiler:
cl -Ic:\java\include -Ic:\java\include\win32
-MD -LD PINGMain.c -ping.dll
Step 6: Running the PINGMain.java
java PINGMain
If you get the following error put the dll file in the java path
java.lang.UnsatisfiedLinkError: no PINGMain in library path
at java.lang.Runtime.loadLibrary(Runtime.java)
at java.lang.System.loadLibrary(System.java)
at PINGMain .main(PINGMain.java)
Posted by Mohan at View blog reactions 9:25 AM 0 comments
Labels: CoreJava
Tuesday, December 1, 2009
Java Oracle Connection
goto Projectmenu--->properties--->Click Java Build Path ---> Libraries Tab—> Add External JARs
Example Program for JavaWithOracleConnection
Replace the bold values with your settings.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestOracleConnection {
public static void main(String[] args) {
try {
Connection con = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@ipaddressoforacleinstalledmachine:1521:databasename", "username",
"password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("SELECT * from tablename");
while (rs.next()) {
System.out.println("Values------>" + rs.getString("columnname"));
}
s.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Posted by Mohan at View blog reactions 9:00 AM 0 comments
Labels: CoreJava
Saturday, November 21, 2009
Java and XML
Posted by Mohan at View blog reactions 10:27 PM 0 comments
Labels: CoreJava
Thursday, November 19, 2009
Java - Card Layout
number of panels(or components) in same dialog that share the same display space.Next
, Back
, and Cancel
buttons in the same dialog to see number of panels with same or different components.import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CardLayExample extends JFrame {
private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
public CardLayExample() {
setTitle("Card Layout Example");
setSize(300, 150);
cardPanel = new JPanel();
// getContentPane().add(cardPanel);
cl = new CardLayout();
cardPanel.setLayout(cl);
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JPanel jp3 = new JPanel();
JPanel jp4 = new JPanel();
JLabel jl1 = new JLabel("Label1");
JLabel jl2 = new JLabel("Label2");
JLabel jl3 = new JLabel("Label3");
JLabel jl4 = new JLabel("Label4");
jp1.add(jl1);
jp2.add(jl2);
jp3.add(jl3);
jp4.add(jl4);
cardPanel.add(jp1, "1");
cardPanel.add(jp2, "2");
cardPanel.add(jp3, "3");
cardPanel.add(jp4, "4");
JPanel buttonPanel = new JPanel();
JButton firstBtn = new JButton("First");
JButton nextBtn = new JButton("Next");
JButton previousBtn = new JButton("Previous");
JButton lastBtn = new JButton("Last");
buttonPanel.add(firstBtn);
buttonPanel.add(nextBtn);
buttonPanel.add(previousBtn);
buttonPanel.add(lastBtn);
firstBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.first(cardPanel);
currentCard = 1;
}
});
lastBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.last(cardPanel);
currentCard = 4;
}
});
nextBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (currentCard < 4) {
currentCard += 1;
cl.show(cardPanel, "" + (currentCard));
}
}
});
previousBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (currentCard > 1) {
currentCard -= 1;
cl.show(cardPanel, "" + (currentCard));
}
}
});
getContentPane().add(cardPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
CardLayExample cl = new CardLayExample();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.setVisible(true);
}
}
Posted by Mohan at View blog reactions 8:10 AM 0 comments
Labels: CoreJava
Wednesday, November 18, 2009
Java Communication API - Serial Port Communication
This package contains following files.
1. comm.jar
2. win32com.dll
3. javax.comm.properties
Place the above files in below location.
comm.jar should be placed in:
%JAVA_HOME%/lib
%JAVA_HOME%/jre/lib/ext
win32com.dll should be placed in:
%JAVA_HOME%/bin
%JAVA_HOME%/jre/bin
%windir%System32
javax.comm.properties should be placed in:
%JAVA_HOME%/lib
%JAVA_HOME%/jre/lib
import java.io.*;
import java.util.*;
import javax.comm.*;
public class ReadData implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
boolean portFound = false;
String defaultPort = "/dev/term/a";
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
ReadData reader = new ReadData();
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}
public ReadData() {
try {
serialPort = (SerialPort) portId.open("ReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}
import java.io.*;
import java.util.*;
import javax.comm.*;
public class WriteData {
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "Hello, world!";
static SerialPort serialPort;
static OutputStream outputStream;
static boolean outputBufferEmptyFlag = false;
public static void main(String[] args) {
boolean portFound = false;
String defaultPort = "/dev/term/a";
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port " + defaultPort);
portFound = true;
try {
serialPort =
(SerialPort) portId.open("WriteData
", 2000);
} catch (PortInUseException e) {
System.out.println("Port in use.");
continue;
}
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
try {
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
}
System.out.println(
"Writing \""+messageString+"\" to "
+serialPort.getName());
try {
outputStream.write(messageString.getBytes());
} catch (IOException e) {}
try {
Thread.sleep(2000); // Be sure data is xferred before closing
} catch (Exception e) {}
serialPort.close();
System.exit(1);
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}
}
Posted by Mohan at View blog reactions 1:28 AM 0 comments
Labels: CoreJava