Tuesday, November 29, 2011

Sample batch file (.bat) to run jar package

Here is a sample batch file to run a jar file. Just include the classpath of jars needed and replace the name of jar and the class name to run. All the classpath are declared here much simpler than changing the MANIFEST file in jar. For instance the below is to run MyApp.jar class of MyAppScreen. Also useful to run an application that need additional memory by declaring  -Xms512M -Xmx1024M displayed at the bottom of the script.


@echo off
if "x%JAVA_HOME%" == "x" (
  set  JAVA=java
  echo JAVA_HOME is not set. Unexpected results may occur.
  echo Set JAVA_HOME to the directory of your local JDK to avoid this message.
) else (
  set "JAVA=%JAVA_HOME%\bin\java"
  echo %JAVA%
)


set CURRENT_DIR=%cd%


rem cd ..


set HOME=%cd%


cd %CURRENT_DIR%


rem set HOME=%CURRENT_DIR%


echo home %HOME%
echo current %CURRENT_DIR%


set MY_CLASSPATH=%HOME%\MyApp.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\arq.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\antlr-2.7.6.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\arq-extra.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\asm-3.3.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\cglib-2.2.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\concurrent.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\commons-beanutils-1.7.0.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\commons-collections-3.1.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\commons-fileupload-1.2.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\commons-io-1.3.1.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\commons-lang-2.4.jar
set MY_CLASSPATH=%MY_CLASSPATH%;%HOME%\lib\dom4j-1.6.1.jar




echo ========================================================================
echo.
echo   My App Utility
echo.
echo   HOME: %HOME%
echo.
echo   JAVA: %JAVA%
echo.
echo   JAVA_OPTS: %JAVA_OPTS%
echo.
echo   CLASSPATH: %MY_CLASSPATH%
echo.
echo ========================================================================
echo.




"%JAVA%" -Xms512M -Xmx1024M %JAVA_OPTS% ^
   -cp "%MY_CLASSPATH%" my.com.app.MyAppScreen %*
pause

Friday, November 25, 2011

Webservice deploy error in jboss 5

If during deployment of webservice jars into jboss 5 it is unable to deploy and the error is something as below

ERROR [[WorkflowServiceImpl]] Servlet.service() for servlet Workflo
wServiceImpl threw exception
java.lang.UnsupportedOperationException: setProperty must be overridden by all s
ubclasses of SOAPMessage
        at javax.xml.soap.SOAPMessage.setProperty(SOAPMessage.java:445)
        at org.jboss.ws.core.soap.SOAPMessageImpl.<init>(SOAPMessageImpl.java:87
)

Means there are jars missing in the server that is essential to deploying the service. Make sure in the jboss server path
<jboss>\lib\endorsed
the following jars existed
jbossws-native-jaxrpc, 
jbossws-native-jaxws,
jbossws-native-jaxws-ext 
jbossws-native-saaj

The jars can be found in the latest jboss 6 version. Jboss version 6 and 7 , no such issue with the deployment of  web service.

Tuesday, November 8, 2011

Creating a runnable jar file

Creating a runnable jar requires creating a manifest file. Package the classes files into a jar file. Inside the jar create folder META-INF and create file MANIFEST.MF.
The structure is abc.jar/META-INF/MANIFEST.MF
Edit the manifest file by adding the file to run and library jars required for the program as below example.
Main-Class is the class file to run. Make sure it has public static void main(String[] args) in the class to enable it to run.
Class-Path are the library jars.

Manifest-Version: 1.0
Created-By: 1.6.0_07 (Sun Microsystems Inc.)
Main-Class: my.program.gen.GeneratorProcess
Class-Path: lib/antlr-2.7.6.jar lib/cglib-2.2.jar lib/poi-3.7-20101029.jar lib/poi-examples-3.7-20101029.jar lib/poi-ooxml-3.7-20101029.jar lib/poi-ooxml-schemas-3.7-20101029.jar lib/poi-scratchpad-3.7-20101029.jar lib/xml-apis.jar lib/xmlbeans-2.3.0.jar lib/commons-logging.jar lib/xercesImpl.jar lib/iri.jar lib/jaws-bin.jar lib/icu4j_3_4.jar lib/concurrent.jar lib/dom4j-1.6.1.jar



To run the jar an executable .bat file is useful. A sample content of .bat file are as below

java -Xms512M -Xmx1024M -jar Generator.jar

Monday, October 17, 2011

Multithread java class

Here is a sample class to run multiple thread in a class. All threads are started in a for loop and after all threads are finished thread join function will wait for all thread to finish.

public class MultiThreadRules {

class MultiThreads implements Runnable {
   private String rulePath;
   public MultiThreads(String rulePath){
                this.rulePath = rulePath;



for(int i=0; i<=5, i++){ //number of threads
this.inputValue = inputValue;
Thread t = new Thread(this);
t.start(); //all threads started
threads.add(t);  
}

try {
for(Thread tt:threads){
tt.join(); //all threads are done
}

} catch (InterruptedException e) {
logger.error(e.getMessage());
}




     }
     public void run() {
      //perform action here
     }
  }


}

Monday, October 10, 2011

Create excel file report with multiple sheets using poi

Previously have done a program to generate and populate excel file on multiple sheets. Firstly download the poi framework jar files from their website http://poi.apache.org/.
Then using array of strings, populate the array according to where the location the cell is. Example below, first array is the row and second array is the column.

String[][] excelData = new String[2000][50];

excelData[0][0] = "Title";
excelData[0][1] = "Name";
excelData[0][2] = "Code";
excelData[0][3] = "Description";


excelData[1][0] = "title 1";
excelData[1][1] = "mike";
excelData[1][2] = "code 1";
excelData[1][3] = "Description 1";


Depending on the number of sheets to generate in the excel file, add the array of strings into an arraylist.

Then pass the list of string of array to the method below together with the file name of excel to generate.
The sheet name to generate is declared in variable sheetName.


private static void writeDataToExcelFile(String fileName,
List<String[][]> resList) {
HSSFWorkbook myWorkBook = new HSSFWorkbook();
String sheetName = "";
for (int i = 0; i < resList.size(); i++) {
sheetName = "Document-" + i;
HSSFSheet mySheet = myWorkBook.createSheet(sheetName);
HSSFRow myRow = null;
HSSFCell myCell = null;
String[][] excelData = resList.get(i);
for (int rowNum = 0; rowNum < excelData.length; rowNum++) {
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < excelData[0].length; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData[rowNum][cellNum]);
}
}
}


try {
FileOutputStream out = new FileOutputStream(fileName + ".xls");
myWorkBook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}


myWorkBook = null;

}

Saturday, October 1, 2011

Reading properties file in java

Reading properties file is straightforward using ResourceBundle java util. Below are the codes. ResourceBundle will get the information from the setting-config.properties file. Make sure the properties file is  in the same path as the java class. The data obtained is passed into a map for easy retrieval using key value later.

private HashMap<String, String> propertiesMap = new HashMap<String, String>();

private ResourceBundle resourceBundle = null;


protected void readProperties() {
List<String> propList = new ArrayList<String>();
try {
resourceBundle = ResourceBundle.getBundle("setting-config");
for (Iterator<String> iterator = resourceBundle.keySet().iterator(); iterator.hasNext();) {
String keyString = iterator.next();
propertiesMap.put(keyString, resourceBundle.getString(keyString));
}
}catch (Exception exception) {
System.out.print(exception.getLocalizedMessage());
}
}

Wednesday, September 21, 2011

Simple program to tail a log file

Recently I came across a requirement to develop a a logging program that tails the log file, similar to a tail log program. I need to tail the specific number of lines of a log file. After some research I decided to go with RandomAccessFile method of getting the check the last number of lines. Then I need something to keep on reading the log file and print it out. Try to use RandomAccessFile but it keeps locking the log file and unable to read it in real time. Then I try the BufferedReader with threading approach although the end result of printing out the output is there will be an extra new line as it prints out the values in the console.
Tried to resolve this extra new line but can't find any solution to it. Anyway the code is as below.


public class Tailog implements Runnable {
boolean execute = true;
BufferedInputStream reader;
BufferedReader in;
File file;
RandomAccessFile raf;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
PrintWriter pwriter;
public Tailog() {
}
public Tailog(long numLine, String fileName, PrintWriter pw) {
try {
file = new File(fileName);
try {
//get last n lines
raf = new RandomAccessFile(file, "rw");
List<Long> seekPosi = new ArrayList<Long>();
long fileLength = file.length();
long tailrow = 0;
for (long i = fileLength - 2; i >= 0; i--) {
raf.seek(i);
String readLine = raf.readLine();


if (readLine.equals("")) {
seekPosi.add(i - 1);
tailrow++;
i--;
}
if (tailrow == numLine)
break;
}


Collections.sort(seekPosi);
for (long x : seekPosi) {
raf.seek(x + 2);
String printLine = raf.readLine();
pw.println(printLine);


}
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}


// start read line by line
inputStreamReader = new InputStreamReader(new FileInputStream(
fileName));
bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
line = bufferedReader.readLine();
}
pwriter = pw;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


public void run() {
while (execute) {
try {
String line = bufferedReader.readLine();
if (line != null) {
pwriter.println(line);
pwriter.flush();
} else {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
execute = false;
}
}


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


public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter(System.out, true);
String numLineStr = "";
String fileName = "";
try {
numLineStr = args[0];
fileName = args[1];
} catch (Exception e) {
e.printStackTrace();
}

long numLine = 0;
try {
numLine = Long.parseLong(numLineStr);
File file = new File(fileName);
if(file.exists()){
Tailog tailog = new Tailog(numLine, fileName, pw);
tailog.run();
}
else{
pw.println("Please specify correct file name: eg C:/server/log/server.log");
}
} catch (Exception e) {
e.printStackTrace();
pw.println("Please specify correct command: java -jar Tailog.jar <number of lines> <file name>");
}
}
}

Monday, September 12, 2011

Html 5 upload and display image on canvas - Firefox and Chrome

Tried html5 to upload and display image on canvas. Mostly example only works on Firefox. After looking around tried the FileReader method. Both Firefox and Chrome supports the FileReader object. IE still not supporting this object at the moment. Maybe in the next IE version. Anyway below is the javascript to upload and display image on canvas. Tested on jboss 7 server. Won't work if not run on server though.




<script>
function handleFileSelect(files) {


for ( var i = 0, f; f = files[i]; i++) {


// Only process image files.
if (!f.type.match('image.*')) {
continue;
}


var reader = new FileReader();


// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var img = document.createElement("img");
img.src = e.target.result;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
context.drawImage(img, 0, 0);


}
};
})(f);


// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
</script>



<body>
       <input type="file" id="files" name="files[]" multiple onchange="handleFileSelect(this.files)"/>
       <canvas id="myCanvas" width="778" height="600"></canvas>  
</body>



Tuesday, September 6, 2011

Getting data from json format using json tokener

I was asked to use extJs grid to display some info on the data grid component. Fine but the component uses json format to display its data on the grid. So deleting data from the grid need to pass in data as json format. Anyway here is the method to retrieve the id from the json data to perform deletion in the grid using JsonTokener. Need to download the net.sf.json jar files from the json website.

import net.sf.json.JSONArray;import net.sf.json.util.JSONTokener;   
public String delJson(String delData, int total, int start){
        ProjectService projService = (ProjectService) SpringApplicationContext.getBean("projectService");
         
        String returnJson = "";
        String delId = "";
        try {
            JSONArray ja = new JSONArray();
            ja = JSONArray.fromObject(delData);
            int jsize = ja.size();
            
            while(jsize!=0){
                String jstr = ja.getString(jsize - 1);
                JSONTokener jt = new JSONTokener(jstr);
                jt.skipPast("id\":");
                delId = jt.nextValue().toString();
                
                if(delId!=null && !"".equals(delId)){
                    try {
                        
                        projService.delete(delId);
                    } catch (NumberFormatException e) {
                        
                        logger.error("error ProjectBean.delJson",e);
                    } catch (Exception e) {
                        
                        logger.error("error ProjectBean.delJson",e);
                    }
                }
                jsize--;
            }
            
        } catch (Exception e) {
            
            logger.error("error ProjectBean.delJson",e);
        }
        return returnJson;
    }




Wednesday, August 31, 2011

Generating a number of tables dynamically in jsp

Recently got a requirement to do generation of dynamic tables based on data output. Used jsp to perform the generation of table from data format of list of multidimensional string arrays List<String[][]>. This will enable generation of multiple tables by looping number of String[][] with the first string array as number of rows and the second string array as number of columns. The jsp code is as below.

<%
        List<String[][]> processLst = new ArrayList<String[][]>();
processLst = //-- call method to get the list
String outstr = "";
int i = 0;
for (i = 0; i < processLst.size(); i++) {
String[][] outputData = processLst.get(i);
%>
<div>


<table border="1" width="450" >
<tr class="font-white">
<th bgcolor="#000000" colspan="<%=outputData[i].length %>"><%=outputData[0][0] %>
</th>
</tr>
<%
for (int rowNum = 1; rowNum < outputData.length; rowNum++) {
%>
<tr>
<% 
for (int cellNum = 0; cellNum < outputData[0].length; cellNum++) {
outstr="";
if(outputData[rowNum][cellNum]!=null)
outstr = outputData[rowNum][cellNum];
%>
<td bgcolor="white">
<%=outstr %>
</td>
<%
}
%>
</tr>
<%
}
%>
</table>
        </div>

Sunday, August 21, 2011

Hotdeploy in jboss 7.0.1

The new Jboss 7 server is blazing fast starting up and shutting down. To perform hot deploy or doing development on exploded war, there are setting in the  configuration folder that needs changing.
For standalone deployment, go to standalone/configuration directory and open standalone.xml. Look for the line below.


        <subsystem xmlns="urn:jboss:domain:deployment-scanner:1.0">
            <deployment-scanner name="default" path="deployments" scan-enabled="true" scan-interval="5000" relative-to="jboss.server.base.dir" deployment-timeout="60"/>
        </subsystem>

Add this param to enable hot deploy  auto-deploy-exploded="true" 
Changes are as below:

        <subsystem xmlns="urn:jboss:domain:deployment-scanner:1.0">
            <deployment-scanner name="default" path="deployments" scan-enabled="true" scan-interval="5000" relative-to="jboss.server.base.dir" auto-deploy-exploded="true" deployment-timeout="60"/>
        </subsystem>


Saturday, July 30, 2011

Creating a webservice in 5 minutes

One day the boss ask you to create a webservice for a method and have it deployed immeadiately. What do you do? Don't panic. The quick way to deploy a webserviceis just a few annotations away. Firstly download the latest version of jboss preferably version 6 from the Jboss website. 


Then you annotate the bean you need to expose as webservice.
Create an interface for the bean first. Then annotate with @Remote and @WebService on the class. 
eg.


import javax.ejb.Remote;
import javax.jws.WebService;
@Remote
@WebService
public interface TestWebService {
    public void getTestCodes(List<String> qualification, String local) throws Exception;
}



Put @Stateless and @WebService on the implementation class.
eg.


import javax.ejb.Stateless;
import javax.jws.WebService;
@Stateless
@WebService
public class TestWebServiceImpl implements TestWebService{
    public void getTestCodes(List<String> qualification, String local) throws Exception{
        try {
            //perform method implementation here
        } catch (Exception e) {
        }
    }
}


After compiling and build the codes, package it into a jar file. You can do it by clicking File menu -> export on eclipse.
Copy the jar file into jboss deploy folder at server/default/deploy.
Start jboss.
You can see your webservice is running by going to your localhost url  http://localhost:8080/jbossws/services
If you want to expose it to be accessible by other pc within same network for testing remember to run jboss with command run.bat -b <your ip address>. Can only access the webservice locally only using the default jboss run.bat. 
Testing the webservice, use soapui client available for download at http://www.soapui.org/