Archive for the ‘java’ Category

using datetimepicker with struts2 and theme qxhtml

Friday, August 20th, 2010

It is very simple to create a form using struts2. Default theme is xhtml which supports errorfields and tooltips. I think the main disadvantage is that each textfield is placed in a separate row by default.

Label1: TextField1
Label2: TextField2

I would like to have many columns in one row.

Label1: TextField1 Label2: TextField2

I tried to use simple theme at the beginning but I found out that tooltips are not supported with a simple theme. I found the solution at http://www.vitarara.org/cms/struts_2_cookbook/creating_a_theme. It is a great page but the page is a little bit outdated,

I am using struts2 2.0.11. I copied qxhtml theme from sample application on vitavara page into my project. I succeed to put many columns in one row but there was a problem with datetimepicker. I found out that I have to modified the file datepicker.ftl to make things working. There is a change in a second row. It looks like in the old struts2 version there was a /simple/datepicker.ftl instead of /simple/datetimepicker.ftl.

<#include “/${parameters.templateDir}/${parameters.theme}/controlheader.ftl” />
<#include “/${parameters.templateDir}/simple/datetimepicker.ftl” />
<#include “/${parameters.templateDir}/qxhtml/controlfooter.ftl” />

You can use labelcolspan and inputcolspan to control the size of particular object. Example: the number of columns in a separate row is 8 columns. If we would like to put only one textfield in this row and if the label should take 1/4 then we would put 2 (2/8=1/4) for labelcolspan and 6 (6/8=3/4) for inputcolspan. Please check the code below.
IMPORTANT: Do not forget to use template=”datepicker” inside s:datetimepicker tag.

<s:datetimepicker template=”datepicker” label=”MyDate” theme=”qxhtml”>
<s:param name=”labelcolspan” value=”%{3}”/>
<s:param name=”inputcolspan” value=”%{4}”/>
</s:datetimepicker>

Summary row in jTable (Swing/Java)

Monday, August 31st, 2009

Summary row is used to present a total sum at the bottom of the jTable.

I have developed a grid component consists from the following components: JPanel is a basic container, jScrollPaneBasic is used to display horizontal scrollbar to handle a summary table and a data table. A data table (zebraJTable1) has another scrollPabe called jScrollPaneTabel used to display vertical scrollbar.

Picture below presents the summary row from the application.

Do not hesitate to run a demo at http://www.javanus.com/AssistWeb. Here are the steps needed to display summary rows in the application:

Manual: 
1.start the demo  
2.login as a GUEST username, password is empty 
3.select Invoices in the menu and after that select the menu item Review of cash accounts (Invoices->Review of cash accounts) 
4.click Search button to display data

PivotTable in java (Swing)

Sunday, June 21st, 2009

I was looking for a PivotTable in java(swing) for a long time. I found out three different libraries for PivotTables. Lets check out each one:

1.JIDE – http://www.jidesoft.com/products/pivot.htm

JIDE software looks amazing but it is not an open source project. At the moment I am strictly “opensource” oriented so the JIDE is not the right choice. I would be very glad if they will decided to opensource their libraries. The screenshots looks great.

2.JMAGALLANES – http://sourceforge.net/projects/jmagallanes

It is an opensource project but the project is not active at the moment. The last update is from 2006. I have written an email to the authors and I have got a reply. They have told me they are planning the next release in a few months.

3.OPENSWING – http://oswing.sourceforge.net/

It is an opensource project. The project is active. I have downloaded the opensource library and the pivotTable worked fine. After a while I found a bug (http://sourceforge.net/forum/forum.php?thread_id=3296825&forum_id=572329) but Mcarniel did his job fast and well. The bug was corrected in the next week.

Below is a picture from my application which presents the use of pivotTable.

The above screen shot is from the hotel reservation software. You are free to launch a demo from http://www.javanus.com/AssistWeb/. Below are the steps used to test a PivotTable:

1.Select “Reports->Reservations” in the menu

2.Select “Search” button

Serialization, Timezones and Java Dates

Saturday, June 6th, 2009

Timezone has not been kept while transfering over http.

The data are stored in the tableModel on the client side. TableModel is serialized and sent over the http to the server. The servlet on the server deserializes the data into the tableModel. TableModel is stored into the database.

My client is located in the central Europe and the server is located in the USA. The client time was Jun 06 00:00:00 CEST 2009. The data was transferred over the http and the same date on the server was Jun 05 17:00:00 CDT 2009.

Solution:

I set GMT timezone on both sides.

TimeZone tz = TimeZone.getDefault();
tz.setDefault(TimeZone.getTimeZone(“GMT”));

The client and the server date time are the same after setting default timezone: Jun 06 00:00:00 GMT 2009.

 Do not hesistate to check out a hotel reservation software using the described technology.
 

 

How to get default Locale Date Format Pattern?

Thursday, May 14th, 2009

I am using a JXDatePicker component to present date fields in my application(http://www.javanus.com/AssistWeb). The application supports seven different languages at the moment. Translation is using resource bundles and it works fine. I also want to localize date fields to present date in a localized format.

It is very easy to convert a date in a paricular format in java. SimpleDateFormat is easy to use, programmer should only pass a particular date format  (dd/MM/yy or dd.MM.yyyy).

The problem arise when I want to provide a date format for a jXDatePicker component. I did not know how to set the proper format for JXDatePicker according to selected language. I just need a localized date format pattern to set the format for jXdatePicker. After a few hours I found the solution I would like to share you.

//inicialization

jXDatePickerDateField.setDate(new java.util.Date());

Solution:

Locale locale = Locale.getDefault();

String datePattern = ((SimpleDateFormat)DateFormat.getDateInstance(SimpleDateFormat.MEDIUM,locale)).toPattern();

jXDatePickerDatum.setFormats(datePattern);

The big three: JDeveloper, Eclipse and Netbeans. Which one do you prefer?

Sunday, January 11th, 2009

I would like to get your opinion on choosing an IDE to develop Java applications.

At the moment I am using Netbeans and I am very satisfied with it. I tried to get a good comparison between them with google. There are a lot of old articles about “The big Three” but I could not get a good answer because they evolve a lot in the recent time. It is time to get an up to date situation!

Here is my opinon:

JDeveloper Pro – if you would like to migrate from oracle forms to java -> use ADF (application development framework), support all phases of software development

JDeveloper Contra – it is not independent (developed by Oracle), does not have future in open source world, slow startup

Netbeans Pro – strong community, open source, independent

Netbeans Contra – bad reputation from the past, I am missing a plug-in for data modelling

Eclipse Pro – a lot of people using it, it is fast

Eclipse Contra – I think it is losing market share, no clear vision

I would be very glad to get your opinion! Do you agree or disagree with my statements? Do not hesitate to put your comment!

Do you find this post useful? Do not hesitate to leave a reply! Go to the bottom of this page.

Zombie killer on linux or how to end the financial crisis?

Monday, January 5th, 2009

Have you ever tried to identify zombie processes on your server? The zombie identification application is written in java and could be used on linux. It is very easy to adopt the code for other operating systems. The zombie killer has been originally written to kill zombie processes on Oracle Application Server.

Go to the end if you are only interested how to end the financial crisis…;)

Application has two parameters:

  • the process name is used to find out only the specific processes. In my example the parameter value is frmweb. Parameter value frmweb is used to limit the application to check only the cpu time spent by oracle forms processes
  • the cpu time used by process is used to define the maximum allowed cpu time spent by particular process

How does it works:

  1. Application first get all the processes in desired format.
    1. ps -eo (to see every process with a user defined format)
    2. ps -eo user, pid, time, command (to see every process in format user, process id, time spent by process and command)
  2. Application checks only the processes where the parameter value for process name match the command (parameter value is in command string)
  3. Application parses the process values and check the cpu time spent by the process. Process is terminated if the cpu time spent is greater than the parameter value for cpu time.

Application could be run using crontab each 15 minutes. Example below shows how to kill oracle forms sessions which exceeds more than 1000 seconds of cpu time
0,15,30,45 * * * * /usr/java/jdk1.6.0_11/bin/java -cp . ZombieKiller frmweb 1000


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
*
* @author http://www.javanus.com/blogs
*/

public class ZombieKiller {
public static String getUnparsedProcessList() {
InputStream in = null;
InputStream buffer = null;
Reader reader = null;
try {
//get all processes
Process p = Runtime.getRuntime().exec("ps -eo user,pid,time,command --sort stime");
in = p.getInputStream();
buffer = new BufferedInputStream(in);
reader = new InputStreamReader(buffer);
char[] charr = new char[1024];
StringBuffer strbuff = new StringBuffer();
while(true) {
int r = reader.read(charr);
if(r<=0) {
break;
}
strbuff.append(charr, 0, r);
}
return strbuff.toString();
}catch(IOException e) {
//todo - error handling
e.printStackTrace();
}
return null;
}


/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
System.out.println("Check out http://www.javanus.com/blogs && http://www.javanus.com/blog");
if (args.length==0) {
System.out.println("Usage: java -classpath . ZombieKiller ");
return;
}
String ls_processName = args[0];

int li_maxSecAllow = 9999;
//Is the maximum number of seconds defined
if (args.length>1 && args[1] != null) {
li_maxSecAllow = Integer.parseInt(args[1]);
}
String ls_procesi = getUnparsedProcessList();
while (ls_procesi.indexOf("\n")>=0) {
String ls_rowValue = ls_procesi.substring(0, ls_procesi.indexOf("\n"));
//parse row if process name match
if (ls_rowValue.indexOf(ls_processName)>=0) {
//user
String ls_user = ls_rowValue.substring(0, ls_rowValue.indexOf(" "));
ls_rowValue = ls_rowValue.substring(ls_rowValue.indexOf(" ")+1, ls_rowValue.length()).trim();
//pid
String ls_pid = ls_rowValue.substring(0, ls_rowValue.indexOf(" "));
ls_rowValue = ls_rowValue.substring(ls_rowValue.indexOf(" ")+1, ls_rowValue.length()).trim();
//time
String ls_time = ls_rowValue.substring(0, ls_rowValue.indexOf(" "));
//System.out.println(ls_time);
ls_time = ls_time.substring(ls_time.indexOf(":")+1, ls_time.length()).trim();
String ls_minute = ls_time.substring(0, ls_time.indexOf(":"));
//System.out.println("ls_minute="+ls_minute);
ls_time = ls_time.substring(ls_time.indexOf(":")+1, ls_time.length()).trim();
String ls_sek = ls_time;
//cmd
ls_rowValue = ls_rowValue.substring(ls_rowValue.indexOf(" ")+1, ls_rowValue.length()).trim();
String ls_cmd = ls_rowValue;//.substring(0, ls_rowValue.indexOf(" "));
//ali je noter ip adressa
int li_spentCputTime = Integer.parseInt(ls_minute)*60+Integer.parseInt(ls_sek);
//System.out.println(ls_cmd);
ls_rowValue = ls_rowValue.substring(ls_rowValue.indexOf(" ")+1, ls_rowValue.length()).trim();
//should I terminate this session?
if (li_spentCputTime>li_maxSecAllow) {
Process p = Runtime.getRuntime().exec("kill -9 " + ls_pid);
System.out.println("Process " + ls_pid + " has been successfully terminated!");
}
}
ls_procesi = ls_procesi.substring(ls_procesi.indexOf("\n")+1, ls_procesi.length());
}

}
}

It would be nice to end the financial crisis on the same way. I suggest to use kill -9 42 to end the economic depression. 42???

Do you find this post useful? Do not hesitate to leave a reply! Go to the bottom of this page.

Multi language reports using java

Friday, November 28th, 2008

I had to develop a multi language report. The report must support four languages: English, French, German and Slovenian. I decided to use Jasper reports. First I checked out the standard jasper example (“jasperreports-2.0.2\demo\samples\i18n). I have tested the example and I was very satisfied with the solution.
After that I developed my first multi language report. Below are the steps needed to achieve this functionality:
1.Create 4 properties files and use local language. In this example I will explain how to translate the word “OFFER”

i18n.properties
text.offer_number=OFFER No.:

i18n_de_DE.properties
text.offer_number=Anbieten:

i18n_fr_FR.properties
text.offer_number=Offre:

i18n_sl_SI.properties
text.offer_number=Ponudba Št:

2.Open Ireport and add a new text field
Add $R{text.ponudba_stevilka} into the expression editor

3.In the main menu select Edit->Report Properties
Select i18n tab
Put i18n into the Resource Bundle base name field

4.Put all four i18n*.properties files into the root directory!!! This MUST BE done when you try to call the report from application. In my case I have jasper reports in C:\development\MyApp\build\classes\reporti\reports and I have to put i18n file into C:\development\MyApp\build\classes.

Translation worked after that but I spend another two hours solving the problem described below.

I have a lot of problems with cp1250 fonts. Central european fonts were not displayed when i used i18n. I put a textField on the report. In the expression editor I defined the value as: $R{text.offer_number}+”Š”.
In the resource file I have defined text.offer_number=\u006F\u008A\u006E. Total expected length should be 4 characters (3characters are in i18n file and one character is concatenated).
I expected to get oŠnŠ but i get o?nŠ  (first three characters are unicode, so the problem is, that central european characters are lost during translation.

I found the solution after long hours. In http://unicode.coeurlumiere.com/ I found out that some characters are marked as “Invalid characters”. Character Š has two unicode numbers: 008A and 0160. The first one is invalid. I got the expected result when I replaced the text.offer_number=\u006F\u0160\u006E.

Do you find this post useful? Do not hesitate to leave a reply! Go to the bottom of this page.

how to get a ProxyEnable value from windows registry in java

Thursday, October 9th, 2008
I have developed a webservice which checks if a new version of software exists. Webservice works fine if the user does not use a proxy otherwise it raises an error “connection timeout….”.
 
If the user uses a proxy then the program should read a proxy settings first. I have found a lot of examples how to read a proxy settings from windows registry and this is not a problem at all (search for JavaRegistryHack).
 
The problem occurs when a user has VPN. In my example I use a proxy when I am connected to VPN but I do not have a proxy when I do not use VPN. I always get proxy address and proxy port regardless of the value in check box “Use a proxy server for your LAN”.
 
 
How to find out if the value of upper checkbox is selected? The answer is in a registry value ProxyEnable. ProxyEnable is set to 0 if a proxy is not selected and it has a value 1 if the proxy is used.
 
But there is another problem. There are two different types of values in registry: REG_SZ and REG_DWORD. It is very easy to read a value for REG_SZ but I have wasted a lot of time to find out how to read a value for REG_DWORD type. Below is a function which is used to read a ProxyEnable. You can use this function also for other REG_DWORD values.
import java.io.*;
public class ProxyEnable {
  private static final String REGQUERY_UTIL = “reg query “;
  private static final String REGDWORD_TOKEN = “REG_DWORD”;
  private static final String PROXYENABLE = REGQUERY_UTIL +
   “\”HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\”" 
   + ” /v ProxyEnable”;
  public static String getProxyEnable() {
    try {
      Process process = Runtime.getRuntime().exec(PROXYENABLE);
      StreamReader reader = new StreamReader(process.getInputStream());
      reader.start();
      process.waitFor();
      reader.join();
      String result = reader.getResult();
      int p = result.indexOf(REGDWORD_TOKEN);
      if (p == -1)
         return null;
      // value is 0×0 or 0×1
      String temp = result.substring(p + REGDWORD_TOKEN.length()).trim();
      temp = temp.substring(2, temp.length());
      return Integer.toString
          ((Integer.parseInt(temp)));
    }
    catch (Exception e) {
      return null;
    }
  }
  static class StreamReader extends Thread {
    private InputStream is;
    private StringWriter sw;
    StreamReader(InputStream is) {
      this.is = is;
      sw = new StringWriter();
    }
    public void run() {
      try {
        int c;
        while ((c = is.read()) != -1)
          sw.write(c);
        }
        catch (IOException e) { ; }
      }
    String getResult() {
      return sw.toString();
    }
  }
  public static void main(String s[]) {
    System.out.println(“Proxy Enable : ” + getProxyEnable());
  }
}
I hope this will help someone oneday somewhere…

Do you find this post useful? Do not hesitate to leave a reply! Go to the bottom of this page.

Fisher’s Exact Test in java version

Friday, August 29th, 2008

Today I will present a java version of Fisher’s exact test. You can read more about Fisher’s exact test  http://en.wikipedia.org/wiki/Fisher’s_exact_test.

I spend a lot of hours to find the source code in java. I became very frustrated. I could not find nothing useful with google. I found www.users.zetnet.co.uk/hopwood/tools/StatTests.java but I did not know how to use it. I send a mail to StatTests.java author but the email is not available anymore. I decided to develop a java class for Fisher’s exact test from the scratch. I found very nice page where Fisher probability test is explained in detail -> http://faculty.vassar.edu/lowry/ch8a.html.

The formula for Fisher probability is quite simple: (a+b)!*(c+d)!*(a+c)!*(b+d)! / n!*a!*b!*c!*d!

First I developed a factorical function to calculate factorial.

    public static BigInteger factorial(int n) {
        if (n <= 1) {
          return(new BigInteger(“1″));
        } else {
          BigInteger bigN = new BigInteger(String.valueOf(n));
          return(bigN.multiply(factorial(n – 1)));
        }
    } 

After that I started to write down the program, line by line….the code is below.

        BigInteger bigAB = factorial(a+b);
        BigInteger bigCD = factorial(c+d);
        BigInteger bigAC = factorial(a+c);
        BigInteger bigBD = factorial(b+d);
        int n = a+b+c+d;
       
        BigInteger dividend = bigAB.multiply(bigCD).multiply(bigAC).multiply(bigBD);
        BigInteger divisor = factorial(n);
        divisor = divisor.multiply(factorial(a));
        divisor = divisor.multiply(factorial(b));
        divisor = divisor.multiply(factorial(c));
        divisor = divisor.multiply(factorial(d));
       
        double ld_value = dividend.doubleValue()/divisor.doubleValue();

I took a cold shower to cool down a bit… I always get Nan for ld_value??? The example above works only for small numbers. I was disappointed with the result. I spend another three hours, googling around, the only result was: http://www.jsc.nildram.co.uk/api/. This api includes a class for Fisher exact test but it is not free for a commercial use and the source code is not available.

I was obstinated as a mule. I struck the oil at 11.30PM. I found http://sourceforge.net/projects/tassel/. I downloaded the project, unzipped it and I found FisherExact.java.

I did the following:

        FisherExact fisherExact = new FisherExact(a+b+c+d+10);
        double twoTailedP = fisherExact.getTwoTailedP(a, b, c, d);

The result was the same as I would use online Fisher’s Exact Test (http://www.langsrud.com/fisher.htm).

I hope one day someone will be more lucky as I was and this blog will save him a lot of frustration.

Do you find this post useful? Do not hesitate to leave a reply! Go to the bottom of this page.