Tuesday, December 4, 2012

Windows Username in JAVA

This is a simple code to retrieve windows username in JAVA.

public class getWindowUsername {
    public static final void main( String args[] ) {
      String userName = System.getProperty("user.name");
      System.out.println("Window's Username: "+userName);

Monday, December 3, 2012

List files contains 'WORD' word

In Linux, grep command can be used to find files that contain specific word.

Change directory first to location where files are located.
Use following command to get file list

grep -l WORD *.*

Above command will list all files that contains word "WORD".

To get word location in file remove -l flag.

Thursday, November 29, 2012

AutoCommit enabled in MySQL DB

In MySQL default engine is set to "MyISAM". In  "MyISAM" engine, auto commit doesn't work. That means, you can't change commit time in application level. And, you can't roll back connections when needed when using "MyISAM" engine.

If you need to set auto commit enabled/ disabled in application level change MySQL DB engine to "INNODB" engine. In "INNODB" engine, you can roll back connection as needed.

  refNo varchar(10) default NULL,

  refNo varchar(10) default NULL,

Tuesday, November 27, 2012

Linux command hard disk space

Following command can be used to find hard disk space in Linux environment.

df -h

Wednesday, November 21, 2012

Copy data from one table to another table

You can copy data from one table to another table using following SQL command. This worked fine in informix database.

insert into TableA (field1, field2,field3)
select  field1, field2,field3 from TableB where added_on=today

Tuesday, November 20, 2012

Words matching in two FILES

Suppose you have to check two files with having same words in both files, you can use the following command in Linux.

fgrep -wf file1 file2 | wc -l

This will return word count in both file1 & file2.

For more details, man fgrep in Linux.

Java Trigger ( Quartz )

Quartz  is a library that can be used to implement scheduler in JAVA application.

This library supports for modify Triggering in many variations.
You have to implement your class implementing Job class as "TestJob.java".


import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class TestJob implements Job {
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        System.out.println("Hello Quartz!");

This "Schedule.java" will be triggered by 5 seconds.


import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class Schedule {

    public static void main(String[] args) throws Exception {
        JobDetail job = JobBuilder.newJob(TestJob.class).withIdentity("testJob", "group1").build();

        Trigger trigger = TriggerBuilder
                .withIdentity("dummyTriggerName", "group1")

        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.scheduleJob(job, trigger);


And you can use Quartz as a cron job.


import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class Cron 
    public static void main( String[] args ) throws Exception
    JobDetail job = JobBuilder.newJob(TestJob.class)
.withIdentity("testJobName", "group1").build();

    Trigger trigger = TriggerBuilder
.withIdentity("dummyTriggerName", "group1")
CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))

    Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    scheduler.scheduleJob(job, trigger);


Following libraries must be added to the projects.

  • quartz-2.1.6.jar
  • log4j-1.2.16.jar
  • c3p0-
  • slf4j-log4j12-1.6.1.jar
  • slf4j-api-1.6.1.jar

Split large TEXT file in JAVA

In some cases, large files has to be split into smaller ones for the fast processing. In my case, file contained about 10 million records. Processing 10 million is bit low than parallel processing smaller files.

Split.java can be used to create files with number of predefined lines.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Split {

    private final static String NEWLINE = System.getProperty("line.separator");

    public static void readFileData(String filename, int lines) throws IOException {
try {
   BufferedReader bufferedReader = new BufferedReader(new FileReader(
   StringBuffer stringBuffer = new StringBuffer();

   String line;
   int i = 0;
   int counter = 1;
   while ((line = bufferedReader.readLine()) != null) {
if (i >= lines) {
   saveFile(stringBuffer, filename + counter);
   stringBuffer = new StringBuffer();
   i = 0;
} catch (IOException e) {
   throw new IOException("read file error " + filename);

    private static void createFile(StringBuffer stringBuffer, String filename) {
String path = (new File("")).getAbsolutePath();
File file = new File(path + "/" + filename);
FileWriter output = null;
try {
   output = new FileWriter(file);
   System.out.println("file " + path + filename + " written");
} catch (IOException e) {
} finally {

   try {
   } catch (IOException e) {

    public static void main(String[] args) {

String fileName = "/usr/sujith/filename.txt"
int lines = 1000000;

try {
    readFileData(fileName, lines);
} catch (IOException e) {
   // TODO Auto-generated catch block

Monday, November 19, 2012

No. of lines in file Linux

Following command can be used to count number of lines in the file using Linux command.

cat fileName | wc -l

wc -l is used to count & list down number.

Call AXIS web service with security

AXIS web service uses .wsdd XML file to read username & passwordCallbackClass. Here, it shown sample .wsdd file.


<deployment xmlns="http://xml.apache.org/axis/wsdd/"
<transport name="http" pivot="java:org.apache.axis.transport.http.HTTPSender"/>
<globalConfiguration >
<requestFlow >
<handler type="java:org.apache.ws.axis.security.WSDoAllSender" >
<parameter name="action" value="UsernameToken"/>
<parameter name="user" value="M_TICKET"/>
<parameter name="passwordType" value="PasswordText" />
<parameter name="passwordCallbackClass"
</requestFlow >
</globalConfiguration >

Then you have to implement "PWCallBackClass" class as below.

PWCallBackClass .java

public class PWCallBackClass implements CallbackHandler {

     private static final byte[] key = {
   (byte)0x31, (byte)0xfd, (byte)0xcb, (byte)0xda,
   (byte)0xfb, (byte)0xcd, (byte)0x6b, (byte)0xa8,
   (byte)0xe6, (byte)0x19, (byte)0xa7, (byte)0xbf,
   (byte)0x51, (byte)0xf7, (byte)0xc7, (byte)0x3e,
   (byte)0x80, (byte)0xae, (byte)0x98, (byte)0x51,
   (byte)0xc8, (byte)0x51, (byte)0x34, (byte)0x04,
public void handle(Callback[] callbacks)
   throws IOException, UnsupportedCallbackException {
   for (int i = 0; i < callbacks.length; i++) {
     if (callbacks[i] instanceof WSPasswordCallback) {
       WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
        * here call a function/method to lookup the password for
        * the given identifier (e.g. a user name or keystore alias)
        * e.g.: pc.setPassword(passStore.getPassword(pc.getIdentfifier))
        * for testing we supply a fixed name/fixed key here.
       if (pc.getUsage() == WSPasswordCallback.KEY_NAME) {
       else {
     } else {
       throw new UnsupportedCallbackException(
         callbacks[i], "Unrecognized Callback");

Following code can be used to call web service with security implemented with AXIS.


import java.rmi.Remote;
import java.rmi.RemoteException;

import javax.xml.rpc.ServiceException;

import org.apache.axis.AxisFault;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.client.Stub;
import org.apache.axis.configuration.FileProvider;

import com.comverse_in.prepaid.ccws.ServiceLocator;
import com.comverse_in.prepaid.ccws.ServiceSoap;
import com.comverse_in.prepaid.ccws.ServiceSoapProxy;
import com.comverse_in.prepaid.ccws.ServiceSoapStub;

import org.apache.ws.security.WSConstants;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.apache.ws.security.message.token.UsernameToken;

public class TestWS {

public static void main(String args[]) throws ServiceException, RemoteException{

EngineConfiguration config = new FileProvider("client_deploy.wsdd");
ServiceLocator locator = new ServiceLocator(config);
Remote remote = locator.getPort(ServiceSoap.class);
Stub axisPort = (Stub)remote;

axisPort._setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
axisPort._setProperty(UsernameToken.PASSWORD_TYPE, WSConstants.PASSWORD_TEXT);
axisPort._setProperty(WSHandlerConstants.USER, "sujith");

axisPort._setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, "PWCallBackClass");

ServiceSoap service = (ServiceSoapStub)axisPort;
System.out.println("Calling service...");
int ver = service.getVersionId();
System.out.println("get version id service returned " + ver);

Reference :- http://ws.apache.org/wss4j/package.html

Following jars needed to run web service client than AXIS jars.

  1. opensaml-1.0.1.jar
  2. wss4j-2.1.jar
  3. ws-security-5.1.0-M1.jar
  4. xmlsec-1.3.0.jar

Thursday, October 18, 2012

Multiple schedules in CRONTAB

CRONTAB can be used to schedule applications.

There are some situations, you have to run application for a few times for a day.

Following example, demonstrates the sample crontab to run two schedules.

0 10,18 * * * /home/sujith/apps/app_schedule.sh

Above crontab will run the schedule(app_schedule.sh) twice a day. (10 AM & 18 PM)

JAVA relative path issue in CRONTAB

It can be occurred issues relative to files access when you have used relative path in JAVA application which are used by crontab in linux. crontab cannot be used in relative paths. One solution is to change JAVA application file access to FULL paths. Another solution is to create shell script as follows. Then, this script can be used by crontab without issues.

cd /home/sujith/app_location
/usr/jdk1.7.0_07/bin/java -jar -Xms512m -Xmx1024m app_name.jar

Tuesday, October 9, 2012

mysqldump Command Usage

It is used mysqldump command to get a backup of existing tables.

Simply, run the following command to get the backup.

mysqldump -usujith -psujith database_name table_name  > /home/sujith/backup.sql

NOTE :- This dump contains all the table structure and data in table.

Thursday, October 4, 2012

Random String (ID) generate in JAVA

java.util.UUID package contains random String generation feature.

Refer below code.

UUID uuid = UUID.randomUUID();

Generated Strings


Wednesday, October 3, 2012

MySQL outfile write permission

When unloading data from MySQL database, it is needed to given special WRITE permission for user to write files.

Refer below command.

SQL command for unload data

  • select * into outfile '/tmp/testfile.txt' fields terminated by '|' from recharge where req_date<'2012-10-03';

SQL command to grant write permission

  • GRANT FILE ON *.* TO 'sujith'@'localhost';
  • flush privileges;

Tuesday, October 2, 2012

MySQL grant permission

It is needed to grant permission in MySQL server for users of the database. Below MySQL commands can be used to grant permissions.

  1. grant all privileges on database.* to 'sujith'@'localhost';
  2. flush privileges;
Refer MySQL documentation for more details.

Monday, October 1, 2012

export EDITOR=vi

In some cases, it is not shown data in Linux terminal window. In that case, you can use "vi editor" to view hidden data.

Following command can be used to export data to vi editor.

export EDITOR=vi   

This is most commonly used for crontab edition.

Tuesday, September 25, 2012

byte[] to Object in java

If data must be sent over network, it is needed to send  data as byte stream. In these cases, it can be used object serialize method as follows. Below method can be used to convert Object to byte stream. 

public static byte[] serialize(Object obj) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    return out.toByteArray();

Below deserialize method can be used to converted stream back to Object. If Object is specific use Object casting methods further.

public static Object deserialize(byte[] data) {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();

NOTE :- This can be avoided by using Java RMI technology.

Wednesday, September 12, 2012

RedHat Server IP Address configuration

In RedHat Linux, following steps can be used for configuring IP address of the machine. For modifying files, you must be logged as root user.

1) Log as root
2) Change directory to "/etc/sysconfig/network-scripts"
3) vi ifcfg-eth0 file & add following parameters

    IPADDR =

4) Restart network adapter using following command.

    /etc/init.d/network restart

5) Check IP address using ifconfig command.

Change file permission for execution

In Linux, it can be used chmod command to change permission of the file.

Simply, this can be done using as follows.

 chmod +x application.bin

Above +x means, file is grated for execution.

Tuesday, September 11, 2012

Linux crontab Command

crontab is used for executing scheduled processes. For example, you can run database backup everyday using schell script.

crontab -l 

Above command list the all available crontab command.

crontab -e

This command can be used to edit crontab command fro your preference.

Sample crontab command is shown below. This script.sh script is executed every day at midnight.
0 0 means zero minute at zero hours(midnight).

0 0 * * * /home/sujith/script.sh

Wednesday, September 5, 2012

MySQL days between SQL Syntax (Between Days)

In MySQL, there is a special ways to get data between two days.

select * from ret_bonus where DATE(start_time) between date_sub(curdate(), interval 5 day) and CURDATE()

Above SQL returns data between today and 5days before today. 

date_sub(curdate(), interval 5 day)

This MySQL command returns 5days before today. 

Tuesday, August 21, 2012

SQL Joins Graphical Illustration


Oracle Toad database configuration

# tnsnames.ora Network Configuration File: C:\Oracle\product\11.2.0\client_1\network\admin\tnsnames.ora
# Generated by Oracle configuration tools.


In Oracle Toad, it needs to configure Toad to connect to Oracle database. Store "tnsnames.ora" file at "C:\Oracle\product\11.2.0\client_1\network\admin\" directory. Then connect via Oracle Toad.

Wednesday, August 8, 2012

Jasper subreport duplicate values

When you printing a collection of data, you have to use a subreport to print data.

There are parameters, that you can use to customize your printing.

But, default parameters set subreport to print duplicate values. To avoid that change following parameters as mentioned below.

In subreport component,

Print When Detail Overflows true
Stretch Type Relative to Tallest Object

In the components inside the subreport,

Print Repeated Values true
Remove Line When Blank  false
Print In First Whole Band         false
Print When Detail Overflows false
Blank When Null    true
Stretch With Overflow true
Stretch Type Relative to Tallest Object

This changes works fine in both iReport 3.5 & 3.7 versions.

Monday, July 30, 2012

Jasper Report Groovy Error

In .jrxml file, it is created using "groovy" language. It occurs error while converting .jrxml file to .jasper file.

Following is shown a error message occurs while converting to .jasper file.

Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException        
at java.lang.Class.forName0(Native Method)       
at java.lang.Class.forName(Class.java:247)        
at net.sf.jasperreports.engine.util.JRClassLoader.loadClassForRealName(JRClassLoader.java:157)        
at net.sf.jasperreports.engine.util.JRClassLoader.loadClassForName(JRClassLoader.java:115)       
at net.sf.jasperreports.engine.JasperCompileManager.getCompiler(JasperCompileManager.java:511)        
at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:215)       
at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:148)        
at src.JasperCheck.main(JasperCheck.java:31)Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.control.CompilationFailedException        
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)       
at java.security.AccessController.doPrivileged(Native Method)        
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)        
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)        
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)        
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)        
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)        ... 8 moreJava Result: 1

Solution to above error is to change .jrxml language type from "groovy" to "java"

Friday, July 27, 2012

Informix Database LOCK Transaction for UPDATE

In some cases, we have to lock records for update. Below code segments can be used for locking table and update desired record in informix database server.

  • statement.executeUpdate("Begin Work");
  • statement.executeUpdate("set transaction isolation level serializable");

Above code must be used be before the SELECT statement execution which must be UPDATE.
  • String sql_1="select * from table where name='sujith' FOR UPDATE";

Execute the sql and proceed with the business logic. When you want to UPDATE the table do the following.
  • String sql_2=update table set name="delp" where name="sujith";

Execute the UPDATE statement, like above statement.

Then use below command for commiting transaction to database.
  • statement.executeUpdate("commit");

Tuesday, July 24, 2012

Print When Expression in Jasper Report

In some cases, we need to filter data values while printing in the report.

There is a special feature in iReport for this called as "Print When Expression".
In this expression, you have to insert Boolean function to the iReport.

For example :-

new Boolean($P!(var_name).toString.equals("5"))

Suppose the parameter variable is "var_name". If the value of the "$P!(var_name)" is equal to "5", it will print the value. Else, it will print null/blank value.

Jasper report Pass SQL to report as parameter

In jasper report, parameters can be categorized into a few data types. According to the data type, parameter  value is attached single quote.

For example, parameter data type is String, it is attached single quote (') between parameter value.
In some cases, we have to pass whole SQL to jasper report to generate report.

If we sent the SQL as a parameter it will return error, because of adding single quotes to parameter.
Solution is to have a ! sign before the parameter value as shown is below.

If the parameter value is "Query", it can be avoided adding single quote to parameter like below.


NOTE :- SQL can be a normal SQL statement

Friday, June 1, 2012

Oracle data format

When inserting data into Oracle Database it is needed to format data. Here, it is shown, how is TIMESTAMP is used in Oracle.

id_ref_no_seq.nextval call the sequence created before. It will increase ref_no value by one and insert back into database.

insert into TABLE_NAME(ref_no,start_time) values(id_ref_no_seq.nextval,TO_TIMESTAMP('2012-06-01 11:41:20.061', 'YYYY-MM-DD HH.MI.SSXFF'))

Wednesday, May 30, 2012

Create SEQUENCE in Oracle

In Oracle DB, there is no AUTO_INCREMENT field like MySQL. Oracle has SEQUENCE instead of this. Below command can be used to create SEQUENCE in Oracle.


Monday, April 2, 2012

Create HTTPS Web Service Client

HTTPS web services uses certificate authentication. So, web service clients must be created with SSL.

In netbeans, you can create HTTPS web service client. Follow the steps.

1) Create Java project in Netbeans
2) Copy certificate into project root directory
3) Use Netbeans Web Service Client wizard to create client 

This will create web service clients successfully. But, when calling service, it is again needed to create SSL session with service.

Before calling service, certificate needs to be stored in java key store. 

Refer article on seguide :- http://seguide.blogspot.com/2009/12/use-keytool-to-generate-keys-in-java.html

Use following code before calling service methods.

System.setProperty("javax.net.ssl.trustStore", "export/home/myTrustStore"); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); 
System.setProperty("javax.net.ssl.trustStoreType", "JKS"); System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 

URL url = new URL("https://~~~~~~~~~~~~~~~~~~~/service.asmx?wsdl");
Service service = new Service(url); service.getServiceSoap().getData();

Monday, March 26, 2012

USSD menu termination value

Unstructured Supplementary Service Data (USSD) menu designing is more considerable. Since, having issues will lead the USSD server to unstable status.

while submitting menu to mobile, these parameter values must be used.

17 - mobile created session termination 
2 - application session creation
3 - application session termination 

Sunday, March 25, 2012

Remove log files created by log4j

Add following code segment to configure file in log4j.

log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
MaxBackupIndex will hold maximum number of 7 files in the location that files are created.

Thursday, March 22, 2012

Wireshark packet filtering

Wireshark is a tool for packet filtering in network adapter.

Use following steps to capture packets in Wireshark.

1) Start network interface for capturing for Wireshark Capture/Interfaces
2) Enter filtering in Wireshark filtering option under menu bar

    Ex :- ip.addr==
    Above is a filtering packets for ip ""

3) Right-click on a packet and Follow TCP stream. This gives packet contents.

Thursday, March 1, 2012

This is a code that can be used to get birth day from National Identity Card in Sri Lanka.  

public Calendar getBirthDate(String nic) {
        int date = Integer.valueOf(nic.substring(2, 5));
        int bdate = 0;
        int bmonth = 0;
        int byear = Integer.valueOf(nic.substring(0, 2));
        if (date > 500) {
            date = date - 500;
        if (date <= 31) {
            bdate = date;
            bmonth = 1;
        if (31 < date & date <= 60) {
            bdate = date - 31;
            bmonth = 2;
        if (60 < date & date <= 91) {
            bdate = date - 60;
            bmonth = 3;
        if (91 < date & date <= 121) {
            bdate = date - 91;
            bmonth = 4;
        if (121 < date & date <= 152) {
            bdate = date - 121;
            bmonth = 5;
        if (152 < date & date <= 182) {
            bdate = date - 152;
            bmonth = 6;
        if (182 < date & date <= 213) {
            bdate = date - 182;
            bmonth = 7;
        if (213 < date & date <= 244) {
            bdate = date - 213;
            bmonth = 8;
        if (244 < date & date <= 274) {
            bdate = date - 244;
            bmonth = 9;
        if (274 < date & date <= 305) {
            bdate = date - 274;
            bmonth = 10;
        if (305 < date & date <= 335) {
            bdate = date - 305;
            bmonth = 11;
        if (335 < date & date <= 366) {
            bdate = date - 335;
            bmonth = 12;
        Calendar calendar = Calendar.getInstance();
        byear = getYear(byear);
        calendar.set(Calendar.YEAR, byear);
        calendar.set(Calendar.MONTH, bmonth);
        calendar.set(Calendar.DATE, bdate);
        return calendar;

Calculate age in java

Use following code to calculate the age in java. Input parameter is calendar which contains b'day year, month, day.

public int calculateAge(Calendar bcalendar) {
        Calendar today = Calendar.getInstance();
        int age = today.get(Calendar.YEAR) - bcalendar.get(Calendar.YEAR);
        if (today.get(Calendar.DAY_OF_YEAR) < bcalendar.get(Calendar.DAY_OF_YEAR)) {
        return age;

Leaf year in java

Following code can be used to find Leaf Year in java.

public boolean isLeafYear(int year) {
        boolean leaf = false;
        if (year < 100) {
            if (year > 40) {
                year = year + 1900;
            } else {
                year = year + 2000;
        if (year % 4 == 0) {
            if (year % 100 != 0) {
                leaf = true;
            } else if (year % 400 == 0) {
                leaf = true;
        return leaf;

Monday, January 30, 2012

Embed Image in Email Using java

Following code snippet can be used to send email with image in the HTML body.

Note :- HTML body must be contain image tag as follows.

<img height="55" src="cid:image-id" width="65" />

Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp host ip ");

Session session = Session.getDefaultInstance(properties, null);

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSentDate(new Date());

MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "text/html")));

Multipart multipart = new MimeMultipart("related");

MimeBodyPart imagePart = new MimeBodyPart();
DataSource fds = new FileDataSource("image path ");
imagePart.setDataHandler(new DataHandler(fds));
imagePart.setHeader("Content-ID", "<


Tuesday, January 24, 2012

dwr mapping filter



This filter can be used to redirect request for DWR servlet.