Saturday, September 27, 2008

Setting Look And Feel when start up

This is how you can set the look and feel style for your java pplication.
It'll set the look and feel according to the platform regardless of java default style.
This is very useful when you want to start java application from another application and to make the same style with window default.
This method must have called when start the application. Just call this in main implementation

public static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(getPreferredLookAndFeelForOS());
} catch (ClassNotFoundException e) {

} catch (InstantiationException e) {

} catch (IllegalAccessException e) {

} catch (UnsupportedLookAndFeelException e) {

}
}



private static String getPreferredLookAndFeelForOS() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.indexOf("mac") || osName.indexOf("win"){
return UIManager.getSystemLookAndFeelClassName();
} else {
return UIManager.getCrossPlatformLookAndFeelClassName();
}
}

Thursday, September 25, 2008

Parsing xml string to dom4j Document

This is how to parse xml message to dom4j Document object

public static Document parseXml(String xmlRequest) throws DocumentException {
Reader source = new StringReader(xmlRequest);
SAXReader reader = new SAXReader();
return reader.read(source);
}

Reading value from Properties File

This method shows you how to read value from the properties file from java. We need to read some parameter from the properties file in order to allow user to customize the functionalities such as socket host and port number, user define error message, UI messages and so on.

You may have a singleton class to handle the specific properties file and have the public method to get the value by the key.

public String readFromProperties(String filePath, String keyName) {
Properties properties;
String value = null;
try {

properties = new Properties();
FileInputStream fis = new FileInputStream(filePath);
if (fis != null) {
properties.load(fis);
value = properties.getProperty(keyName);
fis.close();
}
} catch (FileNotFoundException e) {
// handle if file not found
} catch (IOException e) {
// handle reading properties files errors
}
return value;
}

Testing server performance with multiple connection

Continues from previous post, this method is very useful to test the server performance with multiple request at the same time.

public void testMultiConnection(final String host, final int port,
final List messages, int noOfThread) {
// testing multiple request with different thread
for (int i = 0; i <>
final int threadNumber = i;
Thread connector = new Thread(new Runnable() {
@Override
public void run() {
for (String msg : messages) {
System.out.println("response from Thread["
+ threadNumber + "]:"
+ getResponse(host, port, msg));
}
}
});
connector.start();
}
}

Sending request message to server

public String getResponse(String host, int port, String requestString) {

Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
StringBuilder sb = new StringBuilder();
try {
socket = new Socket(host, port);
socket.setTcpNoDelay(true);
socket.setSoTimeout(6000);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));

out.println(requestString);
out.flush();
String line = null;
do {
line = in.readLine();
if (line != null) {
sb.append(line);
}
} while (line == null);

} catch (Exception e) {
// handle error during sending request
} finally {
if (out != null) {
out.close();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {

}
}
}
return sb.toString();
}

Wednesday, September 24, 2008

Creating Java Socket Server

public void startSocket(int port) {
//this is the request handler class
MessageHandler handler = new MessageHandler();
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
//handle error when socket is not available
}
while (true) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
//handle error when receiving request
}
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String request = getRequest(in);
//perform the request with handler
String result = handler.execute(request);
out.println(result);
} catch (SocketException ex) {
//handle error for process request
} catch (Exception e) {
//handle error for any kind of error
} finally {
try {
if (out != null)
out.flush();
out.close();
} catch (Exception ex) {
}
try {
in.close();
} catch (IOException e) {
}
try {
clientSocket.close();
} catch (Exception e) {
}
}//end of processing
}//end of one request processing
}

Installer: to overwite files from one place to another

package com.awy.util.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This is the utility class to copy file from one place to another
 * 
 * @author awayyout
 * 
 */
public class FileInstaller {
private String sourceFolderPath;
private String targetFolderPath;

/**
* To construct file installer
* @param sourcePath,
*            the path of source files
* @param targetPath,
*            the target path to copy files to
*/
public FileInstaller(String sourcePath, String targetPath) {
this.sourceFolderPath = sourcePath;
this.targetFolderPath = targetPath;
}

/**
* Copy all the file from source to target
* @throws IOException,
*             if file not found or any problem during copy files
*/
public void copyAll() throws IOException {
File targetDir = new File(this.targetFolderPath);
File sourceDir = new File(this.sourceFolderPath);
copyDirectory(sourceDir, targetDir);
}

private void copyDirectory(File srcPath, File dstPath) throws IOException {

if (srcPath.isDirectory()) {
if (!dstPath.exists()) {
dstPath.mkdir();
}
String files[] = srcPath.list();
for (int i = 0; i <>
copyDirectory(new File(srcPath, files[i]), new File(dstPath,
files[i]));
}
}
else {

InputStream in = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}