Thursday, June 28, 2012

Display tag library at Struts2

Strut2 filter configuration
http://www.displaytag.org/10/export_filter.html
Required jars 
http://sourceforge.net/projects/displaytag/files/displaytaglibrary/  (any version)
iText1.3(for pdf export)
<display:table name="clientList"(list) export="true"(enable export) pagesize="5"(how many to display)
 requestURI="#"(click o/p is same page) class="mars"(look style)  style="text-align:center;">
 <display:column property="clientId"(list contains attribute) title="Client Id"(displays at header) group="1"(give as a group)
  sortable="true"(sort is choice)  href="viewClient"(Action name)
  paramId="clientDetails.clientId" (giving param default value is properity)></display:column>
 <display:column property="companyName" title="Company Name" group="2" sortable="true">
 <display:column property="emailId" title="EmailId" />
 <display:column property="website" title="website" />
 <display:column title="Edit" href="editClient" paramId="clientDetails.clientId" paramProperty="clientId" media="pdf/html/excel"(display on which media decide by u)>Edit(user clicks action)</display:column>
 <display:column title="Delete" href="deleteClient" paramId="clientDetails.clientId" paramProperty="clientId" >Delete</display:column>
 <display:setProperty name="export.pdf" value="true"></display:setProperty>(export as a pdf)
 <display:setProperty name="export.excel.filename" value="ClientDetails.xls"/>(define xml  name by default jsp/ action name)
    <display:setProperty name="export.pdf.filename" value="ClientDetails.pdf"/>
 </display:table>

Sunday, June 3, 2012

How to Add Password Protection to PDF using iText in Java


iText is very powerful library. It is used extensively to create PDF files in Java applications. Although not free, iText is the de-fecto Java library for working with PDF files. It has been extensively used in different Java related products for generating and manipulating PDF files.
Let us see how iText can be used to set password protection (encryption) to a PDF file. Also how to read an encrypted PDF file in Java.
For this we are using our Generate PDF in Java using iText tutorial. You might want to have a look into that tutorial to have an overview of iText and its different APIs that can be used for PDF generation.
To set encryption in iText following API can be used.
?
1
2
3
4
5
6
7
8
String USER_PASS = "Hello123";
 
String OWNER_PASS = "Owner123";
 
PdfWriter writer = PdfWriter.getInstance(document, file);
 
writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),
        PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
Thus .setEncryption() method sets password protection to any PDF file.
Before we get started with code, we need few JAR files. iText internally uses bouncycastle.org library to encrypt the PDF files. We will need following JAR files in addition to iText JAR.
  • itextpdf-5.2.1.jar
  • bcmail-jdk16-1.46.jar
  • bcprov-jdk16-1.46.jar
  • bctsp-jdk16-1.46.jar
You can download all these JARs along with the demo source code at the end of this tutorial.
Now following is the Java code to Generate a PDF file and set Password protection to it.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package net.viralpatel.pdf;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
 
public class GeneratePDF {
 
    private static String USER_PASS = "Hello123";
 
    private static String OWNER_PASS = "Owner123";
 
    public static void main(String[] args) {
        try {
 
            OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));
 
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, file);
 
            writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),
                    PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
 
            document.open();
            document.add(new Paragraph("Hello World, iText"));
            document.add(new Paragraph(new Date().toString()));
 
            document.close();
            file.close();
 
        } catch (Exception e) {
 
            e.printStackTrace();
        }
    }
}
Thus we used the same steps to generate PDF file that we used in previous tutorial. Just added one line writer.setEncryption() to set password to generated PDF.
Note that in setEncryption() method, we passes several arguments. First two parameters are the password values in bytes. We passed Hello123 and Owner123 as password values. Also the next argument is permission you want to give to user. Following are several permission values.
?
1
2
3
4
5
6
7
8
PdfWriter.ALLOW_PRINTING
PdfWriter.ALLOW_ASSEMBLY
PdfWriter.ALLOW_COPY
PdfWriter.ALLOW_DEGRADED_PRINTING
PdfWriter.ALLOW_FILL_IN
PdfWriter.ALLOW_MODIFY_ANNOTATIONS
PdfWriter.ALLOW_MODIFY_CONTENTS
PdfWriter.ALLOW_SCREENREADERS
You can provide multiple permissions by ORing different values. For example PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY.
The last parameter is the type of encryption you want to use to encrypt PDF. Following are several allowed values.
?
1
2
PdfWriter.ENCRYPTION_AES_128
PdfWriter.ENCRYPTION_AES_256

Friday, May 25, 2012

JDK Timer scheduler example


JDK Timer is a simple scheduler for a specified task for repeated fixed-delay execution. To use this, you have to extends the TimerTask abstract class, override the run() method with your scheduler function.
RunMeTask.java
package com.mkyong.common;
 
import java.util.TimerTask;
 
public class RunMeTask extends TimerTask
{
 @Override
 public void run() {
  System.out.println("Run Me ~");
 }
}
Now, you can schedule it by calling the schedule() method of Timer.
public void schedule(TimerTask task,
                     long delay,
                     long period)
App.java
package com.mkyong.common;
 
import java.util.Timer;
import java.util.TimerTask;
 
public class App 
{
    public static void main( String[] args )
    {
 
     TimerTask task = new RunMeTask();
 
     Timer timer = new Timer();
     timer.schedule(task, 1000,60000);
 
    }
}
In this example, the timer will print the “Run Me ~” message every 60 seconds, with a 1 second delay for the first time of execution.

How to check if Date is within a certain range in Java?


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class DateValidator {
 
 public boolean isThisDateWithin3MonthsRange(String dateToValidate,
   String dateFromat) {
 
  SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
  sdf.setLenient(false);
  try {
 
   // if not valid, it will throw ParseException
   Date date = sdf.parse(dateToValidate);
 
   // current date after 3 months
   Calendar currentDateAfter3Months = Calendar.getInstance();
   currentDateAfter3Months.add(Calendar.MONTH, 3);
 
   // current date before 3 months
   Calendar currentDateBefore3Months = Calendar.getInstance();
   currentDateBefore3Months.add(Calendar.MONTH, -3);
 
   /*************** verbose ***********************/
   System.out.println("\n\ncurrentDate : "
     + Calendar.getInstance().getTime());
   System.out.println("currentDateAfter3Months : "
     + currentDateAfter3Months.getTime());
   System.out.println("currentDateBefore3Months : "
     + currentDateBefore3Months.getTime());
   System.out.println("dateToValidate : " + dateToValidate);
   /************************************************/
 
   if (date.before(currentDateAfter3Months.getTime())
     && date.after(currentDateBefore3Months.getTime())) {
 
    //ok everything is fine, date in range
    return true;
 
   } else {
 
    return false;
 
   }
 
  } catch (ParseException e) {
 
   e.printStackTrace();
   return false;
  }
 
 }
 
}

Convert PNG to JPEG image file in Java


import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
 
public class ConvertImageFile {
 
   public static void main(String[] args) {
 
 BufferedImage bufferedImage;
 
 try {
 
   //read image file
   bufferedImage = ImageIO.read(new File("c:\\javanullpointer.png"));
 
   // create a blank, RGB, same width and height, and a white background
   BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
   bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
   newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
 
   // write to jpeg file
   ImageIO.write(newBufferedImage, "jpg", new File("c:\\javanullpointer.jpg"));
 
   System.out.println("Done");
 
 } catch (IOException e) {
 
   e.printStackTrace();
 
 }
 
   }
 
}

Output

A new jpg file is generated, with white background.
File : javanullpointer.jpg, 9kb

How to assign file content into a variable in Java


Most people will read the file content and assign to StringBuffer or String line by line. Here’s another trick that may interest you – how to assign whole file content into a variable with one Java’s statement, try it :)

Example

In this example, you will use DataInputStreamto convert all the content into bytes, and create a String variable with the converted bytes.
package com.mkyong.io;
 
import java.io.DataInputStream;
import java.io.FileInputStream;
 
public class App{
 
 public static void main (String args[]) {
 
 try{
 
          DataInputStream dis = 
      new DataInputStream (
        new FileInputStream ("c:\\logging.log"));
 
   byte[] datainBytes = new byte[dis.available()];
   dis.readFully(datainBytes);
   dis.close();
 
   String content = new String(datainBytes, 0, datainBytes.length);
 
   System.out.println(content);
 
 }catch(Exception ex){
  ex.printStackTrace();
 }
 
  }
}

Output

This will print out all the “logging.log” file content.
10:21:29,425  INFO Version:15 - Hibernate Annotations 3.3.0.GA
10:21:29,441  INFO Environment:509 - Hibernate 3.2.3
10:21:29,441  INFO Environment:542 - hibernate.properties not found
10:21:29,456  INFO Environment:676 - Bytecode provider name : cglib
10:21:29,456  INFO Environment:593 - using JDK 1.4 java.sql.Timestamp handling
............

How to convert XML file into properties file – Java


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
   <properties>
 <comment>Support Email</comment>
 <entry key="email.support">donot-spam-me@nospam.com</entry>
   </properties>
In this example, we show you how to use loadFromXML() method to load above XML file into a properties object, and get the key “email.support” value via getProperty() method.
package com.mkyong;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    { 
     Properties props = new Properties();
 
     InputStream is = new FileInputStream("c:/email-configuration.xml");
     //load the xml file into properties format
     props.loadFromXML(is);
 
     String email = props.getProperty("email.support");
 
     System.out.println(email);
 
    }
}
Output
The above example will print out the value of properties key : “email.support” :
donot-spam-me@nospam.com

How to convert properties file into XML file – Java


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
 
public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    { 
     Properties props = new Properties();
     props.setProperty("email.support", "donot-spam-me@nospam.com");
 
     //where to store?
     OutputStream os = new FileOutputStream("c:/email-configuration.xml");
 
     //store the properties detail into a pre-defined XML file
     props.storeToXML(os, "Support Email","UTF-8");
 
     System.out.println("Done");
    }
}
The above example will write the properties detail into a XML file “c:/email-configuration.xml“.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
 <properties>
  <comment>Support Email</comment>
  <entry key="email.support">donot-spam-me@nospam.com</entry>
 </properties>

Execute java program based on your specified time using Quartz schedular


Quartz is a powerful and advance scheduler framework, as it can specify the exact date and time to run your scheduler job.
Firstly, try to understand the Quartz work sequence… Quartz Task, Job, JobDetail, Trigger, Scheduler
  1. Scheduler Task – Pure Java class, the task you want to schedule.
  2. Scheduler Job – Get the “Scheduler Task” from “JobDetail” via “task name“, and specify which schedule task (method) to run.
  3. Scheduler JobDetail – Define a “task name” and link it with “Scheduler Job”.
  4. Trigger – When will run your “Scheduler JobDetail”.
  5. Scheduler – Link “JobDetail” and “Trigger” together and schedule it.

1. Download Quartz

You can get the Quartz library from official website – http://www.quartz-scheduler.org/download/ or Maven central repository
<dependency>
    <groupId>opensymphony</groupId>
    <artifactId>quartz</artifactId>
    <version>1.6.3</version>
</dependency>
 
<!-- Quartz dependency library-->
<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.1</version>
</dependency>

2. Scheduler Task

Create a pure Java class, this is the class you want to schedule.
package com.mkyong.common;
 
public class RunMeTask 
{
 public void printMe() {
  System.out.println("Run Me ~");
 }
}

3. Scheduler Job

Create a ‘job’ to implement the Quartz Job interface, and also the execute() method. Get the scheduler task from Job Details via “task name”, and specify which schedule task (method) to run.
package com.mkyong.common;
 
import java.util.Map;
 
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
public class RunMeJob implements Job
{
 public void execute(JobExecutionContext context)
 throws JobExecutionException {
 
  Map dataMap = context.getJobDetail().getJobDataMap();
  RunMeTask task = (RunMeTask)dataMap.get("runMeTask");
  task.printMe();
 }
}

4. Scheduler JobDetail

Initialize a JobDetail object, link your scheduler job with setJobClass(RunMeJob.class); method, define a task name and put it into Job data map, dataMap.put(“runMeTask”, task);. This “task name” is the only link between your Job and JobDetail.
P.S : job.setName(“runMeJob”) has no special function, just a descriptive name, you can put anything.
        RunMeTask task = new RunMeTask();
 
     //specify your sceduler task details
     JobDetail job = new JobDetail();
     job.setName("runMeJob");
     job.setJobClass(RunMeJob.class);
 
     Map dataMap = job.getJobDataMap();
     dataMap.put("runMeTask", task);

5. Quartz Triggers

Quartz triggers are used to define when the Quartz will run your declared scheduler job. There are two types of Quartz triggers :
  • SimpleTrigger – allows to set start time, end time, repeat interval to run yout job.
  • CronTrigger – allows Unix cron expression to specify the dates and times to run your job.
Code snippet – SimpleTrigger
        SimpleTrigger trigger = new SimpleTrigger();
     trigger.setName("runMeJobTesting");
     trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
     trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
     trigger.setRepeatInterval(30000);
Code snippet – CronTrigger
       //configure the scheduler time
     CronTrigger trigger = new CronTrigger();
     trigger.setName("runMeJobTesting");
     trigger.setCronExpression("0/30 * * * * ?");

6. Scheduler

Link the “JobDetail” and “Trigger” together and schedule it.
        //schedule it
     Scheduler scheduler = new StdSchedulerFactory().getScheduler();
     scheduler.start();
     scheduler.scheduleJob(job, trigger);

7. Full Example

Here’s two examples to show how to integrate the JobDetail, Triggers and Scheduler together.
SimpleTrigger example
In this Quartz SimpleTrigger example, it will run the printMe() method, every 30 seconds with a 1 second delay for the first time of execution.
package com.mkyong.common;
 
import java.util.Date;
import java.util.Map;
 
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
 
public class QuartzAppSimpleTrigger 
{
    public static void main( String[] args ) throws Exception
    {
     RunMeTask task = new RunMeTask();
 
     //specify your sceduler task details
     JobDetail job = new JobDetail();
     job.setName("runMeJob");
     job.setJobClass(RunMeJob.class);
 
     Map dataMap = job.getJobDataMap();
     dataMap.put("runMeTask", task);
 
     //configure the scheduler time
     SimpleTrigger trigger = new SimpleTrigger();
     trigger.setName("runMeJobTesting");
     trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
     trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
     trigger.setRepeatInterval(30000);
 
     //schedule it
     Scheduler scheduler = new StdSchedulerFactory().getScheduler();
     scheduler.start();
     scheduler.scheduleJob(job, trigger);
 
    }
}
CronTrigger example
In this Quartz CronTrigger example, it will run the printMe() method, every 30 seconds.
package com.mkyong.common;
 
import java.util.Map;
 
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
 
public class QuartzAppCronTrigger 
{
    public static void main( String[] args ) throws Exception
    {
     RunMeTask task = new RunMeTask();
 
     //specify your sceduler task details
     JobDetail job = new JobDetail();
     job.setName("runMeJob");
     job.setJobClass(RunMeJob.class);
 
     Map dataMap = job.getJobDataMap();
     dataMap.put("runMeTask", task);
 
     //configure the scheduler time
     CronTrigger trigger = new CronTrigger();
     trigger.setName("runMeJobTesting");
     trigger.setCronExpression("0/30 * * * * ?");
 
     //schedule it
     Scheduler scheduler = new StdSchedulerFactory().getScheduler();
     scheduler.start();
     scheduler.scheduleJob(job, trigger);
    }
}
The Unix cron expression is highly flexible and powerful, you can learn and see many advance cron expression examples in following website.
  1. http://en.wikipedia.org/wiki/CRON_expression
  2. http://www.quartz-scheduler.org/docs/examples/Example3.html