Thursday, October 23, 2008

Java Design Pattern - Creation Pattern

Design Patten is the pattern of problem solving solution where the problem can be found very often for the complex systems.

There are three group of design pattern such as Creation Patterns, Structural Patterns and Behavioral Patterns.

Creation Patterns
Factory Pattern: In order to create the objects that use the same interface with different implementation.

Abstract Factory Pattern: When we need to decide which class to instantiate from a set of different implementation. This patten can decide from a group of different implementation.

Singleton Pattern: Very useful patten when we want to have only one single instance of the class for the whole process.


Builder Pattern:
To build the complex objects by combination of simple objects step by step.


Prototype Pattern: Use the existing object instead of creating new one. This is not very popular since it would affect the performance.

Principle for Java Dev

Simplicity
Build simple classes and simple methods. Determine how much you need to do to meet the expectations of your users.


Clarity
Ensure each class, interface, method, variable and objects has clear purpose. Explain where, when, why and how to use each.


Completeness
Provide the minimum facilities that any reasonable user would expect to find and use. Create complete documentation: document all features and functionalities.


Consistency
Similar entities should look and behave the same, dissimilar entities should look and behave differently. Create and apply standard whenever possible.


Robustness
Provide predictable documented behavior in response to error and exceptions. Do not hide error and do not force client to detect the errors.

Saturday, October 18, 2008

How to modify the contents of file?

When we went to replace the specific information in the file. This method will help.

public void modifyFile(String filePath, String textToFind,String textToReplace) {
PrintWriter outputStream = null;
try {
File tmpFile = new File(filePath);
String newText = readAndReplace(tmpFile, textToFind, textToReplace);
outputStream = new PrintWriter(new FileWriter(tmpFile));
outputStream.print(newText);
outputStream.flush();
} catch (IOException ioe) {
// handle exception here
} catch (Exception ioe) {
// handle exception here
} finally {
if (outputStream != null) {
outputStream.close();
}
}

}

private String readAndReplace(File file, String textToFind,String textToReplace) throws Exception {
StringBuffer sb = new StringBuffer();
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(file));
String line = "";
while ((line = inputStream.readLine()) != null) {
if (line.contains(textToFind)) {
line = line.replace(textToFind, textToReplace);
}
sb.append(line);
}
} catch (IOException ioe) {
// handle exception
} finally {
try {
inputStream.close();
} catch (IOException e) {
}
inputStream = null;
}

return sb.toString();
}

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();
}
}
}