Showing posts with label Java SE. Show all posts
Showing posts with label Java SE. Show all posts

Friday, March 20, 2015

How to call JBPM6's RESTFul API with athentication details

In JBPM 6 the inbuilt RESTFul API is a great feature which makes our lives easier.
In order to use these APIs, you have to provide authentication details with the request in request header.
First join the username and the password with a colon and encode it using Base64 encoder. Then append the word "Basic " (note the space) and put as "Autorization" header.
Ex:-
  "Basic " + Base64Encode(<username> + ":" + <password>)

See below working complete code written in java to get the task list of krisv.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class JBPMRest {
  public static void getTaskSummaryList() throws Exception {
    String status = "Reserved";
    String actor = "krisv";

    String addr = "http://localhost:8080/jbpm-console/rest/task/query?status=" + status + "&potentialOwner=" + actor;
    try {
      HttpClient client = HttpClientBuilder.create().build();
      HttpGet get = new HttpGet(addr);

      String authData = "krisv" + ":" + "krisv";
      String encoded = new sun.misc.BASE64Encoder().encode(authData.getBytes());
      get.setHeader("Authorization", "Basic " + encoded);
      get.setHeader("Content-Type", "application/json");
      get.setHeader("ACCEPT", "application/xml");

      HttpResponse cgResponse = client.execute(get);
      String content = EntityUtils.toString(cgResponse.getEntity());
      System.out.println(content);
    } catch (Exception e) {
      throw new Exception("Error consuming service.", e);
    }
  }
}

Thursday, March 19, 2015

How to pass parameters to a Quartz job

In your Job class(implementation of org.quartz.Job interface) you don't have a way to set external parameters. What you can do is putting parameters in to the SchedulerContext when scheduling the job and get them back in the execute() method of the job.
See below example.

This is your main class where you set the scheduler.
import java.util.Date;
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 TestQuartz {

  public static void main(String[] args) throws Exception {
    JobBuilder jobBuilder = JobBuilder.newJob(MyJob.class);
    JobDetail job = jobBuilder.withIdentity("myJob", "group1").build();
    Date sheduleTime = new Date(new Date().getTime() + 5000);
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startAt(sheduleTime).build();
    Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    //Below line sets a variable named myContextVar in SchedulerContext.
    //Not only strings, you can set any type of object here.
    scheduler.getContext().put("myContextVar", "Hello, this text is from context.");
    scheduler.start();
    scheduler.scheduleJob(job, trigger);
  }
}

Now in your Job class you can get that variable from the SchedulerContext as below.
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;

public class MyJob implements Job {

  @Override
  public void execute(JobExecutionContext arg0) throws JobExecutionException {
    try {
      SchedulerContext schedulerContext = arg0.getScheduler().getContext();
      //Below line gets the value from context.
      //Just get it and cast it in to correct type
      String objectFromContext = (String) schedulerContext.get("myContextVar");
      System.out.println(objectFromContext);
    } catch (SchedulerException e1) {
      e1.printStackTrace();
    }
  }
}

Tuesday, March 17, 2015

Creating a web service client using apache Cxf

In this tutorial you will see how to create a web service client(synchronous) using apache Cxf.
First download the apache cxf  binary distribution from cxf download page.
http://cxf.apache.org/download.html
Extract the downloaded archieve and it will create a folder named like apache-cxf-x.x.x.

Now create a new Java project. I name it as CXFClient.
In this tutorial I am going to write a client to consume cdyne.com's Weather service.
This is the WSDL for that service.
http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL

Now you can create the stub for the above web service as below.
Open command window and point to apache-cxf-x.x.x\bin.
Below command will generate the stub for the above web service in to a folder named mystub inside bin folder.

wsdl2java -ant -client -p com.example.stub -d mystub http://wsf.cdyne.com/Weather.asmx?WSDL

You will see the stub is generated inside the apache-cxf-x.x.x\bin\mystub folder. Open the stub folder and copy the content in to the src(java source) folder of your project.
Now I am going to create my client class to consume the web service. Create a new java class in com.example.client package and name it as WeatherClient.

If you are using eclipse, your project structure will look like this now.


























This is my client class to invoke the weather service. Run this class and you will see the the data is retrieved through the web service.
package com.example.client;

import java.util.List;
import com.example.stub.ArrayOfWeatherDescription;
import com.example.stub.Weather;
import com.example.stub.WeatherDescription;
import com.example.stub.WeatherSoap;

public class WeatherClient {
  public static void main(String[] args) {
    try {
      Weather weatherService = new Weather();
      WeatherSoap weatherSoap = weatherService.getWeatherSoap();
      ArrayOfWeatherDescription forecastReturn = weatherSoap.getWeatherInformation();
      List forecasts = forecastReturn.getWeatherDescription();
      for (WeatherDescription forecast : forecasts) {
        short weatherID = forecast.getWeatherID();
        String description = forecast.getDescription();
        System.out.println("weatherID : " + weatherID);
        System.out.println("description : " + description);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Monday, February 16, 2015

How to use ExecutorService to create and maintain a thread pool in java

The ExecutorService interface and its implementations which are found in java.util.concurrent package are very useful when you need to maintain a thread pool in your application.

What is a thread pool and why it is used? 
Well, first of all think that a thread pool as a collection of threads. Assume that you have a runnable class and assume that you need 'n' number of threads of this class run in parallel. If one thread finished its task and exit you may need to start another thread to make sure that 'n' number of threads are running in parallel.
The ExecutorService can do this and more other stuff for you.
You can add any number of threads in to the ExecutorService. You can tell the ExecutorService how many threads that you want to run in parallel. The ExecutorService is responsible of keeping the given number of threads running in parallel. If one thread went down by finishing its task, the ExecutorService starts another thread to guarantee that given number of threads are running in parallel. ExecutorService does this until all the threads in its pool are executed or until we signal it to stop.
Below example will show you how to create a thread pool using ExecutorService.

As I mentioned earlier you need to have a runnable class which acts as a thread. My runnable class is as below.

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyThread implements Runnable {
  @Override
  public void run() {
    System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      System.out.println("Interrupted.......");
    }
  }
}

This is my code which creates and executes the thread pool.

 java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PoolTest {
  public static void main(String[] args) throws InterruptedException {
    int poolSize = 5;
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < 20; i++) {
      MyThread thread = new MyThread();
      threadPool.execute(thread);
    }
    System.out.println("All threads are added to the pool....");
    threadPool.shutdown();
    System.out.println("All Executed....");
  }
}

Run and inspect the output of the above method and you will see that five threads have been executed at the same time.
I'll explain the above code line by line.
ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
This line creates the thread pool. The integer value passed to this method is the number of threads run in parallel.

threadPool.execute(thread);
The execute() method is used to add threads in to the thread pool. As soon as the execute() method is called first time, the ExecutorService starts execution of threads.

threadPool.shutdown();
After adding all the elements in to the thread pool, we calls this method to tell the ExecutorService, that we are not goint to add more threads in to the pool and it may gracefully shuts down after all the threads provided are executed. It should be noted that, this line does not shuts the thread pool down immediately. Instead it permits the thread pool to shuts down after it completely executed all the threads provided. Another thing to keep in mind is that you can't add more threads in to this thread pool after the shutdown() method is called. It will throw a runtime exception.

If you want to tell the ExecutorService to abort all the tasks and shuts down immediately, you can call threadPool.shutdownNow().

If you inspect the output of the above code carefully, you will see that the line "All Executed...." has been printed before the execution of all threads are finished. What is the reason for that. Yes, as you have already understood the thread pool does its job in background and the main thread which contains the line System.out.println("All Executed...."); gets executed in parallel.

What we can do if we need to print this line after all the threads were executed?
The easiest way is to call awaitTermination() after the shutdown() method. This method blocks the main thread until all tasks have completed execution after a shutdown request(or the given timeout occurs, or the current thread is interrupted, whichever happens first).
After adding the awaitTermination() method, the last lines of the above code will be as below.

System.out.println("All threads are added to the pool....");
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("All Executed....");

Now run the code and you will see that the line "All Executed...." is printed after all the threads are executed.

The other way is to use the ExecutorService.isTerminated() together with Thread.sleep() to check and wait until ExecutorService has been shut down. For an example you can replace the line threadPool.awaitTermination(1, TimeUnit.MINUTES); with below lines.

while (!threadPool.isTerminated()) {
  try {
Thread.sleep(500);
  } catch (InterruptedException e) {
e.printStackTrace();
  }
}

Working with multiple threads is some what tricky and you should act carefully. This tutorial demonstrated the basic usage of ExecutorService to handle thread pools. I think that would help you to design your next multi threaded program in more efficient way.

How to use dynamic parameters in strings in java

In programming it is common to keep commonly used strings in a properties file or as constants and use them in multiple places in your code.

For an example below message can be put in a properties file to be used in different places.
message=The user is not authorized for this operation.

Then you can use this in various places.
But what happens if you need to include the "username" of the user in to this message?
For an example if the username is "john", the message should be

"The user john is not authorized for this operation."

If the username is "tom", the message should be

"The user tom is not authorized for this operation."

In this kind of situations you can use a parametrized messages in your property file as below.
message = The user {0} is not authorized for this operation.

In the places where you use this message you can use java.text.MessageFormat class to replace the parameter with the proper value as below.

String message = properties.getProperty("message");
String formattedMessage = MessageFormat.format(message, "john");

This will print
The user john is not authorized for this operation.

Similarly if you want you can have multiple parameters in the string.
String message = "The user {0} is not authorized for {1} operation.";
String formattedMessage = MessageFormat.format(message, "john", "billing");
System.out.println(formattedMessage);

This will print
The user john is not authorized for billing operation.

Wednesday, October 15, 2014

Log4j in 1 minute - Log4j Quick Start Guide

In this tutorial I am showing you the minimum steps you need to use log4j in your project.

Note:-
In this example I am using RollingFileAppender as the appender. RollingFileAppender lets you to write logs in to a log file. The default maximum size of the file is 10MB. You can change this value in log4j.properties file.

1. Create a new java project.
2. Download log4j-2.x.xx.jar from http://logging.apache.org/log4j/2.x/download.html and add it to your project(Im using log4j-1.2.12.jar).
3. Create a new property file in your source folder(src) and name it as log4j.properties. Then add below content to it.

log4j.rootLogger = debug, myFileAppender
log4j.appender.myFileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.myFileAppender.File=D://log.log
log4j.appender.myFileAppender.layout=org.apache.log4j.PatternLayout

4. Now you can use various logging methods in your classes as below.
import org.apache.log4j.Logger;

public class Log4jExample{

  static Logger log = Logger.getLogger(Log4jExample.class.getName());

  public static void main(String[] args) {
     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");
     log.warn("Hello this is an warn message");
     log.error("Hello this is an error message");
     log.fatal("Hello this is an fatalmessage");
    }
}

One minute tutorial is over. Now you know how to use log4j.
Happy logging with log4j...!!




Below I will include some extra information.

If you want to change the maximum size of the log file you can do it as below.
log4j.appender.myFileAppender.MaxFileSize=200KB

If you want to bakup the old log files after max file size reached, use MaxBackupIndex property as below. The MaxBackupIndex is the nuber of bakup files you need to keep.
log4j.appender.myFileAppender.MaxBackupIndex=3

If you want to print the log messages in console too, you need to configure a ConsoleAppender too. Then your complete property file would looks like below. Newly added content has been marked with different color.

log4j.rootLogger = debug, myFileAppender, myConsole
log4j.appender.myConsole=org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.layout=org.apache.log4j.PatternLayout
log4j.appender.myFileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.myFileAppender.MaxFileSize=2GB
log4j.appender.myFileAppender.MaxBackupIndex=3
log4j.appender.myFileAppender.File=D://log.log
log4j.appender.myFileAppender.layout=org.apache.log4j.PatternLayout

Even though you have set the log level of the rootLogger to debug you can set the log level of an appender to a higher level. For an exemple you can set the log level of the appender myFileAppender to Error level like this.
log4j.appender.myFileAppender.Threshold=ERROR

There are lot more properties that you can use to customize the output. Just google and you could find them.

NOTE:In above example we used log4js RootLogger with multiple appenders. If you want you can define your own loggers like this.

log4j.logger.myLogger = info, myFileAppender2

In this case myFileAppender2 prints only the logs which come through myLogger logger. The appenders bound to root logger prints all the logs come through root logger and myLogger.

Monday, September 15, 2014

JUnit Hello World example with Eclipse

This kick start guide will show you how to create and execute JUnit test cases with eclipse.

First create a new project in Eclipse. Then create a new class. I name the class as HelloWorld.java and create it inside the package com.example. I modify the HelloWorld class so that it looks like below.

package com.example;
public class HelloWorld {
  private String helloMessage;

  public HelloWorld(String message) {
    this.helloMessage = message;
  }

  public String sayHello() {
    return helloMessage;
  }
}

Right. Now what we need to do is create a JUnit test case to verify the functionality of this class.
Create another package in src folder and name it as com.tests(You may use any name).
Now right click on the newly created package and point to New ⇨ JUnit Test Case.

Set the name as HelloWorldTest. In "Class under test" text box browse and select the class HelloWorld which we created before. Click Next. Select the sayHello() method as below and click Finish. Note that test methods are generated only for the methods that you select here. If you want you can also select the HelloWord() also.



Now the generated test class will look like this.
package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;

public class HelloWorldTest {
  @Test
  public void testSayHello() {
    fail("Not yet implemented");
  }
}

Now we can modify above auto generated method to add out  testing logics. I modify my HelloWorldTest class as below.

package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;
import com.example.HelloWorld;

public class HelloWorldTest {
  String helloMessage = "Hello JUnit World!"; 
  HelloWorld hello = new HelloWorld(helloMessage);

  @Test
  public void testPrintMessage() {
     assertEquals(helloMessage, hello.sayHello());
  }
}

Ok, I have completed my test class now. Please take a look at testPrintMessage() method. What it does is, compares the String returned by the hello.sayHello() method with the String we set in constructor. As we know those should be the same. If those were different it means something has gone wrong.
assertEquals() method throws an error if the results were not the same.

Now right click the HelloWorldTest class and select Run As ⇨ JUnit Test. You will see that a tab like below will be opened and show the result of the test.



If we had multiple methods in our HelloWorldTest class there would be more lines in this report.If any of the methods failed those will be marked in red.
We can fail the test by modifying our class as below.

package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;
import com.example.HelloWorld;

public class HelloWorldTest {
  String helloMessage = "Hello JUnit World!"; 
  HelloWorld hello = new HelloWorld(helloMessage + "abc");

  @Test
  public void testPrintMessage() {
     assertEquals(helloMessage, hello.sayHello());
  }
}

Now run the test again and the output will look like this.



The JUnit API class org.junit.Assert consists with lot more other important methods such as
     ● assertNotEquals();
     ● assertTrue();
     ● assertFalse();
     ● assertThat();

You can find the complete list in API documentation.
http://junit.sourceforge.net/javadoc/org/junit/Assert.html

Wednesday, April 9, 2014

Quartz - Quick guide

Quartz is an easy to use open source job scheduling library.
In this tutorial I am going to show you how to use this great tool to
  1. Schedule a job to run at a given time
  2. Repetitively run a job at given intervals

In this tutorial I'm using quartz-2.2.1.jar because currently it is the laterst stable version. You can download the library from http://quartz-scheduler.org/downloads.

Create a new Java project and add the quarts library to it. Since this version of Quartz depends on slf4j-1.6.6, you should add the slf4j-api-1.6.6.jar to your project as well. You can find this jar inside the zip file you downloaded from Quartz download page.
First I am going to write the method which should be run at the scheduled time. In order to do this we need to create a class which implements the org.quartz.Job interface. Then we should override the execute() method and include our logic there.

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;

public class PrintJob implements Job {
  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    System.out.println("Job Started at " + new Date());
  }
}

Below is the class which schedule the above job at a future time.
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class PrintSchedule {
  public static void main(String[] args) throws SchedulerException {
    JobBuilder jobBuilder = JobBuilder.newJob(PrintJob.class);
    JobDetail job = jobBuilder.withIdentity("myJobName", "myGroup1").build();
    Date sheduleTime = getSheduleTime();
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTriggerName",
                  "myGroup1").startAt(sheduleTime).build();
    Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    scheduler.start();
    scheduler.scheduleJob(job, trigger);
  }

  private static Date getSheduleTime() {
    //job will run after 5 seconds from current time
    return new Date(new Date().getTime() + 5000);
  }
}

Now run the PrintSchedule class and wait for 5 seconds. You will see a line similar to this printed on console.
Job Started at Wed Apr 09 17:30:42 IST 2014

Now we see how to shedule a job to run at certain intervals. Its very simple. Assume that you need to print the above line in every five seconds. Then just replace the below line in above code with
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTriggerName",
                  "myGroup1").startAt(sheduleTime).build();
with
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTriggerName", "myGroup1").withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever()).build();

That is all. Now run the PrintSchedule class again and you will see the the above line printed on console in every five seconds.

Thursday, September 5, 2013

How to Read and Write to a Property File In Java -Simple example

In java.util package there is a class called Properties which easily allow you to do read and write operations with Property files. The get() method reads from the file and the store() method writes to the file. If the property is already available in the file, the value will be overridden. Using this class is very simple.

First of all you have to initialize the Properties object by loading a ".properties" file.

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class PropertyTest {
  private static Properties properties;
  private static File propertyFile;

  public PropertyTest() {
    initProperties();
  }

  private static void initProperties() {
    try {
      propertyFile = new File("D:/test.properties");
      if (!propertyFile.exists()) {
        propertyFile.createNewFile();
      }
      FileInputStream in = new FileInputStream(propertyFile);
      properties = new Properties();
      properties.load(in);
      in.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Note the properties.load() method in above code. That method loads the existing properties to properties Object.

Now your properties object is ready to use. You can save or load data now.
Below code add a property called "testProperty" to the file.
  private static void addProperty() {
    try {
      FileOutputStream out = new FileOutputStream(propertyFile);
      properties.setProperty("testProperty", "This is test property");
      properties.store(out, "This is comment");
      out.close();
    } catch (Exception ex) {
    }
  }


Note that we have used the properties.store() method to save the value.

In below method you can see how to retrieve data from file.
  private static void readProperty() {
    String testProperty = (String) properties.get("testProperty");
    System.out.println(testProperty);
  }

Note that if the property does not exist in the file it returns null.
That is all.

The following is a full working code.
package testing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class PropertyTest {
  private static Properties properties;
  private static File propertyFile;
 
  public PropertyTest() {
    initProperties();
  }
 
  public static void main(String[] args) {
    initProperties();
    addProperty();
    readProperty();
  }
 
  private static void addProperty() {
    try {
      FileOutputStream out = new FileOutputStream(propertyFile);
      properties.setProperty("testProperty", "This is test property");
      properties.store(out, "This is comment");
      out.close();
    } catch (Exception ex) {
    }
  }

  private static void readProperty() {
    String testProperty = (String) properties.get("testProperty");
    System.out.println(testProperty);
  }
 
 
  private static void initProperties() {
    try {
      propertyFile = new File("D:/test.properties");
      if (!propertyFile.exists()) {
        propertyFile.createNewFile();
      }
      FileInputStream in = new FileInputStream(propertyFile);
      properties = new Properties();
      properties.load(in);
      in.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Wednesday, July 17, 2013

How To Encrypt and Decrypt With AES Algorithm in JAVA

AES (Advanced Encryption Standard) is one of the most commonly used encryption algorithm among Symmetric Encryption algorithms. As you know Symmetric Encryption algorithms use the same key for encryption and decryption. In other words, the key you used to encrypt the data should be used to decrypt the data again. (As you may already know in Asymmetric Encryption algorithms, a combination of private and public key are used.)

In AES the length of the key should be 128-bit(16 bytes), 192-bit(24 bytes) or 256-bit(32 bytes).

Following code shows you how to encrypt with AES.
  private static byte[] encrypt(String message) throws Exception {
    byte[] keyBytes = "ThisIs128bitSize".getBytes();
    Key key = new SecretKeySpec(keyBytes, "AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE, key);
    return c.doFinal(message.getBytes());
  }


Following code decrypts the encrypted bytes back in to the original String.
  private static String decrypt(byte[] encryptedText) throws Exception {
    byte[] keyBytes = "ThisIs128bitSize".getBytes();
    Key key = new SecretKeySpec(keyBytes, "AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decValue = c.doFinal(encryptedText);
    String decryptedValue = new String(decValue);
    return decryptedValue;
  }

As you may have already noticed in above samples I have used a 128-bit key("ThisIs128bitSize"). Did you try a 192-bit or 256-bit key such as "LengthOfThisTextIs192bit". Sometimes you may get this kind of a error.

java.security.InvalidKeyException: Illegal key size or default parameters

If you get this error it means that your security policies do not allow you to use keys with more than 128-bit length. You can check this length by using 'getMaxAllowedKeyLength()' method as below.
int length = Cipher.getMaxAllowedKeyLength("AES");
System.out.println(length);//prints the max key length

Do following steps to override these settings.

☛ Download Java Cryptography Extension (JCE) Unlimited Strength zip file from following links and unzip     it.
    For Java 7 :
    http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

    For Java 6 :
    http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

☛ Copy all the .jar files from unzipped folder to /jre/lib/security folder. In any case you later need to
    switch to the original version, please keep a backup of original files before overwriting.

☛ Now run your code with 192-bit or 256-bit key. It will work.

If you get following error it means you have copied incorrect version of policy files. In other words your java version and policy file version are not matched. So make sure to add relevant version of policy files. Then it will work.

java.lang.SecurityException: Jurisdiction policy files are not signed by trusted signers!

How to configure Log4j ConsoleAppender

Log4j ConsoleAppender is used to print logs in application console. You can configure this in log4j.properties file or by java code.

 Configuring ConsoleAppender in log4j.properties file


Following is the basic configuration for ConsoleAppender.
log4j.rootLogger = DEBUG, myConsole
log4j.appender.myConsole = org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.layout = org.apache.log4j.PatternLayout
log4j.appender.myConsole.layout.ConversionPattern = %-5p %m%n

In first line we set the logging level of rootLogger to DEBUG, and define the name for a Appender.
You can use any logging level such as INFO, WARN, ERROR etc. instead of DEBUG according to your requirement. For an example if you set the level to WARN, only the log entries with level equal or higher than WARN will be printed. The default level of rootLogger is DEBUG.
'myConsole' is the name of the Appender you are going to create. You can define more Appenders by adding them by separating with commas.

Example:
log4j.rootLogger = INFO, myConsole, myInfoFile,....

In second line we register 'myConsole' as a ConsoleAppender.

Third and fourth lines define the pattern for the log entry.

Now in your Java class you can access this Appender as below.
import org.apache.log4j.*;
public class LogTest {
  static Logger logger = Logger.getLogger(LogTest.class);
  public static void main(String[] args) {
    logger.info("This is info.");
    logger.error("This is error.");
  }
}


 Configuring ConsoleAppender from java code


import org.apache.log4j.*;

public class LogTest {
  static Logger logger = Logger.getLogger(LogTest.class);

  public static void main(String[] args) {
    PatternLayout layout = new PatternLayout("%-5p %d %m%n");
    ConsoleAppender appender = new ConsoleAppender(layout);
    appender.setName("consoleLog");
    appender.activateOptions();
    Logger.getRootLogger().addAppender(appender);

    logger.setLevel(Level.WARN);
    logger.info("This is info.");
    logger.error("This is error.");
  }
}

Tuesday, July 16, 2013

How to use SQLite with java

This tutorial is a quick guide to use SQLite in your java application. In this tutorial you will learn to create a database, to create a table,  insert data in to the table and to retrieve data from the table.

Before using SQLite with your java project, as with any database first you have to add the SQLite JDBC driver to the project. 

You can download SQLite JDBC driver from the below link
https://bitbucket.org/xerial/sqlite-jdbc/downloads

Create a new Java project and add this jar to your project as a normal library. Now you are ready to use SQLite with your application.

Look at following code samples and you will easily understand how to use SQLite with Java.

Create a new folder in your project and name it as 'dataFolder'. 
Below code creates a database names 'myDatabase.db' in that folder.
  public void createDatabase {
    try {
      Class.forName("org.sqlite.JDBC");
      //Following line creates a database named 'myDatabase.db' in 'dataFolder' folder.
      Connection con =
              DriverManager.getConnection("jdbc:sqlite:dataFolder/myDatabase.db");
      Statement stmt = con.createStatement();
     
     //Following line creates a table named 'employee' indatabase.
      String query = "CREATE TABLE employee(id INTEGER, name TEXT)";
      stmt.executeUpdate(query);
      stmt.close();
      con.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


Below method inserts two rows in to the employee table that we created in above method.
 private void insert() throws SQLException {
    Connection con =
             DriverManager.getConnection("jdbc:sqlite:dataFolder/myDatabase.db");
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("insert into employee (id, name) values(1, 'john')");
    stmt.executeUpdate("insert into employee (id, name) values(2, 'william')");
    stmt.close();
    con.close();
 }


Below method retrieves all the records from employee table and prints the id and the name.
  private static void read() throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:sqlite:dataFolder/myDatabase.db");
    Statement s = conn.createStatement();
    ResultSet rs = s.executeQuery("SELECT id, name FROM employee");
    while (rs.next()) {
      Integer id = rs.getInt("id");
      String name = rs.getString("name");
      System.out.println(id + ":" + name);
    }
  }

Tuesday, July 9, 2013

How to use log4j without log4j.properties file

Usually when using log4j for logging log4j.properties file is used to configure log4j properties. But sometimes you may need to change these properties by your code. This tutorial simply show you how to set log4j properties through java code.
Download log4j-1.2.17.jar from Apache website and add it to your project.
Create a new java class and name it as LoggerTest. Create another java class and name it as LoggerUtil. Add following method to your LoggerUtil class so you don't need to have a log4j.properties file.

public static void initLogger() {
    try {
      String filePath = "D:/mylog.log";
      PatternLayout layout = new PatternLayout("%-5p %d %m%n");
      RollingFileAppender appender = new RollingFileAppender(layout, filePath);
      appender.setName("myFirstLog");
      appender.setMaxFileSize("1MB");
      appender.activateOptions();
      Logger.getRootLogger().addAppender(appender);
    } catch (IOException e) {
      e.printStackTrace();
    }
}

Explaining the method:
✪  First we define the log file path.
✪  Then we create a PatternLayout object by passing the pattern of the log entry.
✪  Note that here are using a RollingFileAppender. RollingFileAppender automatically rename the log files
    when they reach a certain size and create a new log file. By default it create a new log file when
    the current log file come to the size of 10MB. You can change this size by using one of
    appender.setMaximumFileSize() or appender.setMaxFileSize() methods.
✪  activateOptions() is an internal method and which throws an exception or give you warnings if it
    couldn't execute this methods correctly, for an example if file name is not set.
✪  Finally we append the appender to Root Logger.

Note that within the application running time you need to call this method only once.

We have almost finished our work. Now add a main method to your LoggerTest class as below and run it.
  public static void main(String[] args) {
    //calling initLogger() method to initialize properties. 
    //You need to call this method only once.
    LoggerUtil.initLogger(); 
    
    //Getting the already registered logger 'myFirstLog'
    Logger accessLog = Logger.getLogger("myFirstLog");
 
    accessLog.info("This is my first info message.");
    accessLog.warn("This is my first warn message.");
    accessLog.error("This is my first error message.");
    accessLog.fatal("This is my first fatal message.");
  }

Now open the log file(D:/mylog.log) and you will see the output.

Wednesday, July 3, 2013

Creating Axis1 Simple Web Service and a Client Using Eclipse IDE

Creating a web service or a web service client using Eclipse IDE is really simple and doesn't take more than several minutes. Following is a quick and easy guide for that. I am using Eclipse Indigo for this.

1. Create a new Dynamic Web Project.

2. Select Apache Tomcat as the target runtime.

3. Right click on src folder, create a new java class and name it as 'Clock'.

4. Add getDate() method to the 'Clock' class as below. The method should be public.

5. Now we are going to create the web service based on this class. Right click on the 'Clock' class, then select -> Web Services -> Create Web Service

6. You will see the following screen. Click 'Next' to see what methods are going to be in Web Service or simply click 'Finish'.

7. If you clicked 'Next', you will see a page like below where you can select methods to be visible in Web Service. Click 'Finish'.

8. This will create Clock.wsdl, web.xml and some other important files. See below image.

9. And your application is now automatically deployed in Tomcat server.
To check this, in your web browser go to http://localhost:8080/TimeService/services/Clock
You will see a page like this.
Congratulations!! You have successfully published the web service.

Now we are going to create a client which consumes this web service.
(Note that the client should not necessarily be a web application.)

10. Create a new Java Project. Name it as 'TimeClient'.

11. We need the WSDL file to create the Web Service Client. So copy the WSDL file from your TimeServer project to TimeClient project.

12. Now right click on this WSDL file -> Web Services -> Generate Client

You will get following screen.
Click 'Finish'.
13. Now right click on the src folder and create a new class. This is the class to which you are going to add your methods which calls the Web Service.
Name the class as 'ClockClient'.

14. Add a main method to 'ClockClient' class as below and run it.

15. You will get an output printed on your console as below.

Your client has successfully consumed the web service you created...