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

Tuesday, July 29, 2014

Excel Generator in Java using POI and Reflection

Excel Generator in JAVA using apache POI and Reflection


Code Snippet:


    @SuppressWarnings("unchecked")
    public HSSFWorkbook exportToCSV(Object srcDtos, String[] columnList,
            String[] valueIdList, String title
) {
       
        try {
           
            List<Object> dtoList = null;
            HSSFRow reportRow = null;
            int rowNum = 1;
            int colIndex = 0;
            String reportRowValue = "";
           
            if (srcDtos == null){
                return null;
            } else {
                dtoList = (ArrayList<Object>)srcDtos;
            }
           
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(title);
                       
            /**
             * setting up the report header
             */
            HSSFRow reportHeader = sheet.createRow(0);

            for (String column : columnList) {
                reportHeader.createCell(colIndex++).setCellValue(column);
            }

            Method invokeMethod = null;
            Class<?> reqClass = null;
            // Loading methods parameters
            Class[] parameter = new Class[1];
            String getColumn = "";
            try { 
               
                for (Object srcClassObj : dtoList) {

                    /**
                     * creating the report row content
                     */
                    reportRow = sheet.createRow(rowNum++);
                    reportRowValue = "";
                    int rowColIndex = 0;
                   
                    Class dtoClzName =srcClassObj.getClass();
                   
                    reqClass = Class.forName(dtoClzName.getName());
               

                    for (String columnField : valueIdList) {
                         
                        getColumn = "get" + initCapString(columnField);

                        parameter[0] = String.class;

                        invokeMethod = reqClass.getMethod(getColumn);

                        Object tmpObj = invokeMethod.invoke(srcClassObj);

                        reportRowValue = (tmpObj == null ? "" : tmpObj
                                .toString());

                        reportRow.createCell(rowColIndex++).setCellValue(reportRowValue);

                    }

                }

            } catch (ClassNotFoundException e) {
                logger.error("Error during the CSV generation --->" +
                        e.getMessage());
            }
           
            return workbook;

        } catch (Exception e) {
            logger.error("Error during the CSV generation --->"
                    +   e.getMessage());
        }
        return null;
    }



    /**
     * method to init capitalize the given string(first letter as CAPITAL)
     * @param srcString
     * @return
     */
    public static String initCapString(String srcString) {
        String[] arr = srcString.split(" ");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            sb.append(Character.toUpperCase(arr[i].charAt(0)))
                    .append(arr[i].substring(1)).append(" ");
        }
        return sb.toString().trim();
    }



public class VelsErrorMsgDTO implements Serializable {

    private Long errorMsgID;
    private String institutionID;
    private String errorMsgTitle;
    private String errorMsgDescription;
    private String lastUpdtTime;

    public Long getErrorMsgID() {
        return errorMsgID;
    }


    public void setErrorMsgID(Long errorMsgID) {
        this.errorMsgID = errorMsgID;
    }


    public String getInstitutionID() {
        return institutionID;
    }


    public void setInstitutionID(String institutionID) {
        this.institutionID = institutionID;
    }


    public String getErrorMsgTitle() {
        return errorMsgTitle;
    }


    public void setErrorMsgTitle(String errorMsgTitle) {
        this.errorMsgTitle = errorMsgTitle;
    }


    public String getErrorMsgDescription() {
        return errorMsgDescription;
    }


    public void setErrorMsgDescription(String errorMsgDescription) {
        this.errorMsgDescription = errorMsgDescription;
    }


    public String getLastUpdtTime() {
        return lastUpdtTime;
    }


    public void setLastUpdtTime(String lastUpdtTime) {
        this.lastUpdtTime = lastUpdtTime;
    }
   
}


Here the arguements

srcDtos      ------> actual  java DTO objects which carries your data
columnList  ------> Column header list
valueIdList  ------> java property names need to be invoked from DTO object(getter method of the
                                given  java field(example userName , address ..) would be  invoked to get the actual
                                value  that need to be displayed in excel file)
 title ---------------> Report title




    public static void main(String[] args) {
        List<VelsErrorMsgDTO > dtoList = new ArrayList<VelsErrorMsgDTO >();
        VelsErrorMsgDTO dto = new VelsErrorMsgDTO ();
        dto.setErrorMsgID(1L);
        dto.setErrorMsgTitle("Test errror");
        dto.setErrorMsgDescription("Test errror");
        dto.setInstitutionID("101");
        dtoList.add(dto);
       
        dto = new CIErrorMsgDTO();
        dto.setErrorMsgID(2L);
        dto.setErrorMsgTitle("Test errror");
        dto.setErrorMsgDescription("Test errror");
        dto.setInstitutionID("608");
        dtoList.add(dto);
       
        String[] columnList={ "Error Msg","Description","Institution"};
        String[] valueIdList={ "errorMsgTitle","errorMsgDescription","institutionID"};
        try {
          
            FileOutputStream fileOut = new FileOutputStream("C:\\temp\\TestXcel1.xls");
            workbook.write(fileOut);
            fileOut.close();

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



Tuesday, February 15, 2011

ClassFinder in java

How to find out a class file in a JAR/WAR/ZIP files using java

ClassFinder program to findout "simulator.class" in a dwr.jar file
 
package com.vels.sms.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
 /**
 * @author velmurugan pousel
 * @project SMS
 * created on Feb 14, 2011
 */
public class ClassNameFinder {
 

 public static List<String> findClass(String srcJarPath, String srcJar) throws IOException{
  List<String> nameList = new ArrayList<String>();

  ZipFile zip = new ZipFile(srcJarPath);  
  // Process the zip file. Close it when the block is exited.
  try {
      
    String searchFileC = srcJar+".class";
    String searchFileJ = srcJar+".java";
  
   // Loop through the zip entries and print the name of each one.

   for (Enumeration list = zip.entries(); list.hasMoreElements();) {
         ZipEntry entry = (ZipEntry) list.nextElement();
        String srcFile = entry.getName();

    // filters only .class and java files..avoids unnecesaary checking

       if (srcFile.endsWith(".class") || srcFile.endsWith(".java")) {
                   int c = srcFile.lastIndexOf("/");
                  String fName = srcFile.substring(c + 1);
                 if (searchFileC.equalsIgnoreCase(fName) || searchFileJ.equalsIgnoreCase(fName)) {     
                     nameList.add(srcFile);
                  }
        }
   }

//   if(!fileFound){
//    System.out.println(" File" + srcJar +"  not found on the "+ srcJarPath);
//   }
        
  } catch (Throwable e) {
            e.printStackTrace();
  } finally {
            zip.close();
  }
            return nameList;
 }

 public static void main(String[] args) {
  try {
          String srcPath = "D:\\bak\\dwr.war";
          String searchFile = "simulator";
  
         List<String> classList = findClass(srcPath, searchFile);
  
        if (classList.size()>0){
            System.out.println(" Class Find..."+ classList);
       } else {
            System.out.println(" File" + srcPath +"  not found on the "+ searchFile);
       }
     
  } catch (Throwable e){
       e.printStackTrace();
  }
  
 }

}

.....
....

Tuesday, February 8, 2011

Writing A text/xml file into a Tomcat WEB-INF folder

How to write a file(text or xml) file into a TOMCAT WEB-INF folder


code snippet  for writing a text file into the Tomcat WEB-INF folder:

...
...
String realPath = getServletContext().getRealPath("/WEB-INF/log");
// it returns  D:\apps\apache-tomcat-6.0.24\webapps\CodeAnalyser\WEB-INF\log  as realPath value

File curFile = File.createTempFile("SopOut", ".txt", new File(realPath));

// it will creat a file SopOUt.txt in to the  D:\apps\apache-tomcat-6.0.24\webapps\CodeAnalyser\WEB-INF\log  folder

// write to file
FileWriter fw = new FileWriter(curFile);

try {
      fw.write(sb); // sb contains the content to be written into the file
} finally {
    fw.flush();
    fw.close();
}

...
...

Wednesday, February 2, 2011

Alarm Clock using Java Schedular

How to implement alarm clock functionality to alarm sound at 7 am on week days and 10 am on weekends using java schedular

Steps to schedule a alarm clock during the week days or week ends

Step1. Write an abstract class wich implements Runnable and has the method to implement the logic to alarm sound.

package com.vels.test;

import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public abstract class SchedulerTask implements Runnable {

final Object lock = new Object();

int state = VIRGIN;
static final int VIRGIN = 0;
static final int SCHEDULED = 1;
static final int CANCELLED = 2;

TimerTask timerTask;

protected SchedulerTask() {
}

public abstract void run();

public boolean cancel() {
synchronized(lock) {
if (timerTask != null) {
timerTask.cancel();
}
boolean result = (state == SCHEDULED);
state = CANCELLED;
return result;
}
}

public long scheduledExecutionTime() {
synchronized(lock) {
return timerTask == null ? 0 : timerTask.scheduledExecutionTime();
}
}

}
Stpe 2 : Write a schedular to schedule tha alarm clock to sound


package com.vels.test;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class Scheduler {

class SchedulerTimerTask extends TimerTask {
private SchedulerTask schedulerTask;
private ScheduleIterator iterator;
public SchedulerTimerTask(SchedulerTask schedulerTask,
ScheduleIterator iterator) {
this.schedulerTask = schedulerTask;
this.iterator = iterator;
}
public void run() {
schedulerTask.run();
reschedule(schedulerTask, iterator);
}
}

private final Timer timer = new Timer();

public Scheduler() {
}

public void cancel() {
timer.cancel();
}

public void schedule(SchedulerTask schedulerTask,
ScheduleIterator iterator) {

Date time = iterator.next();
if (time == null) {
schedulerTask.cancel();
} else {
synchronized(schedulerTask.lock) {
if (schedulerTask.state != SchedulerTask.VIRGIN) {
throw new IllegalStateException("Task already scheduled " + "or cancelled");
}
schedulerTask.state = SchedulerTask.SCHEDULED;
schedulerTask.timerTask =
new SchedulerTimerTask(schedulerTask, iterator);
timer.schedule(schedulerTask.timerTask, time);
}
}
}

private void reschedule(SchedulerTask schedulerTask,
ScheduleIterator iterator) {

Date time = iterator.next();
if (time == null) {
schedulerTask.cancel();
} else {
synchronized(schedulerTask.lock) {
if (schedulerTask.state != SchedulerTask.CANCELLED) {
schedulerTask.timerTask =
new SchedulerTimerTask(schedulerTask, iterator);
timer.schedule(schedulerTask.timerTask, time);
}
}
}
}

}


Step 3 : Write an Schedule iterator


package com.vels.test;

import java.util.Date;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public interface ScheduleIterator {
public Date next();

}

Step 4 : Write a Restricted Daily Iterator - it is restricted to run a job on particular days of the week;


package com.vels.test;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

/**
* @author velmurugan pousel
* @project EmailScheduler
* created on Feb 2, 2011
*/
public class RestrictedDailyIterator implements ScheduleIterator {

private final int hourOfDay;
private final int minute;
private final int second;
private final int[] days;
private final Calendar calendar = Calendar.getInstance();

public RestrictedDailyIterator(int hourOfDay, int minute, int second, int day) {
this(hourOfDay, minute, second, new int[]{day});
}

public RestrictedDailyIterator(int hourOfDay, int minute, int second, int[] days) {
this(hourOfDay, minute, second, days, new Date());
}

public RestrictedDailyIterator(int hourOfDay, int minute, int second, int[] days, Date date) {
this.hourOfDay = hourOfDay;
this.minute = minute;
this.second = second;
this.days = (int[]) days.clone();
Arrays.sort(this.days);

calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, 0);
if (!calendar.getTime().before(date)) {
calendar.add(Calendar.DATE, -1);
}
}

public Date next() {
do {
calendar.add(Calendar.DATE, 1);
} while (Arrays.binarySearch(days, calendar.get(Calendar.DAY_OF_WEEK)) < 0);
return calendar.getTime();
}
}

Step 5 : Write Composit iterator class - takes a set of ScheduleIterators and correctly orders the dates into a single schedule.


package com.vels.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Date;

/**
* @author velmurugan pousel
* @project EmailScheduler
* created on Feb 2, 2011
*/
public class CompositeIterator implements ScheduleIterator {

private List orderedTimes = new ArrayList();
private List orderedIterators = new ArrayList();

public CompositeIterator(ScheduleIterator[] scheduleIterators) {
for (int i = 0; i < scheduleIterators.length; i++) {
insert(scheduleIterators[i]);
}
}

private void insert(ScheduleIterator scheduleIterator) {
Date time = scheduleIterator.next();
if (time == null) {
return;
}
int index = Collections.binarySearch(orderedTimes, time);
if (index < 0) {
index = -index - 1;
}
orderedTimes.add(index, time);
orderedIterators.add(index, scheduleIterator);
}

public synchronized Date next() {
Date next = null;
while (!orderedTimes.isEmpty() && (next == null || next.equals((Date) orderedTimes.get(0)))) {
next = (Date) orderedTimes.remove(0);
insert((ScheduleIterator) orderedIterators.remove(0));
}
return next;
}
}

Step 6 : Write an alarm clock class - it will alarm sound at 7am on week days and 9 am on weekend


package com.vels.test;

import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;


/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class AlarmClock {

private final Scheduler scheduler = new Scheduler();
private final SimpleDateFormat dateFormat =
new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS");


public AlarmClock() {
}

public void start(ScheduleIterator iterator) {

scheduler.schedule(new SchedulerTask() {
public void run() {
soundAlarm();
}
private void soundAlarm() {
System.out.println("Wake up! " +
"It's " + dateFormat.format(new Date()));
// Start a new thread to sound an alarm...
}
}, iterator);

}

public static void main(String[] args) {

int[] weekdays = new int[] {
Calendar.MONDAY,
Calendar.TUESDAY,
Calendar.WEDNESDAY,
Calendar.THURSDAY,
Calendar.FRIDAY
};
int[] weekend = new int[] {
Calendar.SATURDAY,
Calendar.SUNDAY
};
ScheduleIterator i = new CompositeIterator(
new ScheduleIterator[] {
new RestrictedDailyIterator(7, 0, 0, weekdays),
new RestrictedDailyIterator(9, 0, 0, weekend)
}
);

AlarmClock alarmClock = new AlarmClock();
alarmClock.start(i);
}


}
......


Wake up! It's 02 Feb 2011 12:28:00.011
.....




Reference : http://www.ibm.com/...

Tuesday, February 1, 2011

Job Scheduling in Java

How to Schedule a Job or Task in Java

To schedule a job to occur at a certain time or to be excuted at repeated time interval
we can use TimerTask and Timer class in java to accomplish this.


A TimerTask is “A task that can be scheduled for one-time or repeated execution by a Timer.”
A TimerTask is similar to a Thread. Both classes implement the Runable interface.
Thus both classes need to implement the public void run() method. The code inside the run() method is will be executed by a thread

A Timer is facility to schedule TimerTasks.
"Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.
Timer tasks should complete quickly."
The constructor of the Timer class starts the background thread.



package com.vels.test;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class EmailTask extends TimerTask {

/**
* method will be called at every scheduled time(ex ..1 minute)
*/
public void run() {
System.out.println(" start to send mail...." + new Date());
sendMail();
System.out.println(" after mail sent...." +
System.currentTimeMillis());
}

public void sendMail() {
System.out.println(" email send.....");
}

public static void main(String[] args) {

int DELAY = 60*1000; // one minute delay

Timer t1 = new Timer();
t1.schedule(new EmailTask(),DELAY, DELAY);
//calls the run method to send mail after one minute and
repeat every one minute.

// task - task to be scheduled.
// delay - delay in milliseconds before task is to be
executed.
// period - time in milliseconds between successive task
executions.
}
}


To cancel the Scheduled task we need to call cancel method of the TimerTask( we can override the cancel method).

Tuesday, January 18, 2011

How To Install and run MySQL

How to install and run the MySQL


Step to install and work on the MySQL Server


Step 1 : Download the MYSQL

Download the MySQL and install the MySQL into C:\mysql.
Extract the ZIP to your C: drive and rename the folder from “mysql- x.x.xx-win32″ to “mysql”. MySQL can be installed anywhere on your
system.

Step 2 : Move the data folder(optional)


I recommend placing the data folder on another drive or
partition to make backups and re-installation easier. For the
purposes of this example, we will create a folder called
D:\MySQLdata and move the contents of C:\mysql\data into it.

You should now have two folders, D:\MySQLdata\mysql and
D:\MySQLdata\test. The original C:\mysql\data folder can be
removed.

Step 3 : Create the configuration file

MySQL provides several configuration methods but, in general, it
is easiest to to create a my.ini file in the mysql folder. There
are hundreds of options to tweak MySQL to your exact
requirements,

but the simplest my.ini file is:

[mysqld]
# installation directory
basedir="C:/mysql/"
# data directory
datadir="C:/MySQLdata/"


Step 4 : Test your MySQL Server

Open the command prompt and run the following command

C:\mysql\bin\mysqld.exe
This will start the MySQL server which listens for requests on
localhost port 3306.
Open another command window and run the following command

cd c:\mysql\bin
mysql –u root

This will show a welcome message and the mysql> prompt.
Enter “show databases;” to view a list of the pre-defined
databases

Step 5: Change the root password

The MySQL root user is an all-powerful account that can create and
destroy databases. If you are on a shared network, it is advisable
to change the default (blank) password. From the mysql> prompt,
enter:

UPDATE mysql.user SET password=PASSWORD("my-new-password") WHERE
User='root';

FLUSH PRIVILEGES;

You will be prompted for the password the next time you start the
MySQL command line.

Enter “exit” at the mysql> prompt to stop the command line client.
You should now shut down MySQL with the following command:

Step 6 : Create Table in database velsDB

First we need to Create a database :

mysql> create database velsDB ;
mysql>use database velsDB;

create table resource_vacation_plan(
employee_id varchar(36) not null,
employee_name varchar(32) not null,
start_date date,
end_date date,
no_of_days integer(3)
);

Commit;

If you are going to use my sql in your code the use the following
to create the DB connection:

String DB_MYSQL_DRIVER_NAME = "com.mysql.jdbc.Driver";
String DB_URL_STRING_MYSQL = "jdbc:mysql://localhost:3306/velsDB";
String DB_URL_MYSQL_USERID = "root";
String DB_URL_MYSQL_PASSWORD = "root";
..................

Tuesday, December 21, 2010

How to Read Data from DB and write into Excel sheet using Apache POI

Read Data from DB and write into Excel sheet using Apache POI

...
method to read data from the "resource_rbac_status" table and write into the excel sheet using apache POI HSSF API
...

public static HSSFWorkbook generateExcel(){
Connection dbconn = null;
HSSFWorkbook wb = null;
try{
dbconn = RmsDBUtil.getDBConnection(); /// get the connection
Statement stmt= dbconn.createStatement();;
ResultSet rs= stmt.executeQuery ("SELECT * FROM resource_rbac_status");
ResultSetMetaData rsmd = rs.getMetaData ();

int columnCount = rsmd.getColumnCount ();

wb = new HSSFWorkbook();

HSSFSheet sheet = wb.createSheet("Excel Sheet");

HSSFRow rowhead = sheet.createRow((short) 0);

for (int j = 1; j <= columnCount; ++j) {
rowhead.createCell((short) ((short) j-1)).setCellValue(rsmd.getColumnLabel(j));
}

int index = 1;
while (rs.next()) {

HSSFRow row = sheet.createRow((short) index);
for (int j = 1; j <= columnCount; ++j){

String a=rsmd.getColumnTypeName(j);

if (a.equals("INTEGER")){

row.createCell((short) ((short) j-1)).setCellValue(rs.getInt(j));
} else {

row.createCell((short) ((short) j-1)).setCellValue(rs.getString(j));
}

}

index++;
}

System.out.println("Data is saved in excel file.Please check the excel file ");

//close the connection and statement

}
catch (Exception e) {
System.out.println(e);
}
finally{
// close the connection
}

return wb;

}
...
....
....

How to Read an Excel sheet using Apache POI HSSF

How to read an excel sheet using POI API(HSSF)

....
method to read the excel sheet and prepares the list(of Holiday DTOs) using apache POI API
.....

public static List parseHolidayExcel(String xlsPath) {

List holidayList = new ArrayList();
FileInputStream fis = null;
POIFSFileSystem fileSystem = null;

try {
fis = new FileInputStream(xlsPath);
fileSystem = new POIFSFileSystem(fis);

HSSFWorkbook workBook = new HSSFWorkbook(fileSystem);
HSSFSheet sheet = workBook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
HolidayListDTO dto = null;
while (rows.hasNext()) {
HSSFRow row = rows.next();

if (row.getRowNum() == 0)
continue;

// System.out.println("Row no:"+row.getRowNum());
dto = new HolidayListDTO();
dto.setSiteStatus(row.getCell((short) 0).getStringCellValue());
dto.setCountry(row.getCell((short) 1).getStringCellValue());
dto.setLocation(row.getCell((short) 2).getStringCellValue());
dto.setHoliday_date((Date) (row.getCell((short) 3)
.getDateCellValue()));
dto.setDay(row.getCell((short) 4).getStringCellValue());
dto.setOccasion(row.getCell((short) 5).getStringCellValue());

holidayList.add(dto);

}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return holidayList;
}


To read an Excel sheet using POI API(HSSF) : Data Holder to hold details about the holidays....

import java.io.Serializable;
import java.util.Date;

public class HolidayListDTO implements Serializable{

public String siteStatus;
public String country;
public String location;
public Date holiday_date;
public String day;
public String occasion;
public String getSiteStatus() {
return siteStatus;
}
public void setSiteStatus(String siteStatus) {
this.siteStatus = siteStatus;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getHoliday_date() {
return holiday_date;
}
public void setHoliday_date(Date holidayDate) {
holiday_date = holidayDate;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getOccasion() {
return occasion;
}
public void setOccasion(String occasion) {
this.occasion = occasion;
}


}

Sample Excel file(sheet) to be read by the above code using POI HSSF API....

SiteStatus country location date day occasion
offsite india chennai 10/12/2010 Monday Ramzan
onsite us new jersy 11/12/2010 Tuesday Rangoli
offsite india delhi 9/11/2010 Wednesday deepavali

Thursday, December 2, 2010

Find out Number of Holidays in a month or date range using Java

To findout the number of Holidays in a given date range or in a month

Calendar format should be year, month-1, day

Here is java class to findout the number of holidays of a given data range(two dates)

//HolidayFinder class

package com.hbd.rms.util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
* @author velmurugan pousel
* created on Sep 2, 2010 for RMS
* WorkingDaysFinder.java on Sep 2, 2010
*/
public class HolidaysFinder {

/**
* holidaylist holds the list of national/local holidays for the date range
* the format of the calender is (year,month-1,date)
*/
static List holidayList = new ArrayList();

// holiday list
static {
//holidayList.add(new GregorianCalendar(2010, 8, 18));// holiday on the given month
holidayList.add(new GregorianCalendar(2010, 11, 24));// holiday on the given month
}

/**
* check the given date is on holiday list
* @param calendardate
* @return
*/
public static boolean isHoliday(Calendar cal) {
return holidayList.contains(cal);
}

/**
* method to find out number of holidays between the given date range
* @param first
* @param second
* @return
*/
public static int countNumberOfSaturdaysAndSundays(GregorianCalendar first,
GregorianCalendar second) {

int count = 0;
GregorianCalendar currentcalendarday = first;
GregorianCalendar lastcalendarday = second;

while (currentcalendarday.getTime().getTime() < lastcalendarday.getTime().getTime()) {
if (isOnSaturday(currentcalendarday)) {
count++;
} else if (isOnSunday(currentcalendarday)) {
count++;
} else if (isHoliday(currentcalendarday)) {
count++;
}
currentcalendarday.add(Calendar.DATE, 1);
}

if (isSameDay(currentcalendarday, lastcalendarday)) {

if (isOnSaturday(currentcalendarday)) {
count++;
} else if (isOnSunday(currentcalendarday)) {
count++;
} else if (isHoliday(currentcalendarday)) {
count++;
}
}
return count;
}


/**
* check the given date is saturday
* @param calendardate
* @return
*/
public static boolean isOnSaturday(Calendar calendardate) {

if (calendardate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
System.out.println("Debug: "
+ String.valueOf(calendardate.get(Calendar.DATE)) + "-"
+ String.valueOf(calendardate.get(Calendar.MONTH) + 1)
+ "-" + String.valueOf(calendardate.get(Calendar.YEAR))
+ " is a SATURDAY.");
} else {
System.out.println("Debug: "
+ String.valueOf(calendardate.get(Calendar.DATE)) + "-"
+ String.valueOf(calendardate.get(Calendar.MONTH) + 1)
+ "-" + String.valueOf(calendardate.get(Calendar.YEAR))
+ " is not a SATURDAY.");
}

return (calendardate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY);
}


/**
* check the given date is sunday
* @param calendardate
* @return
*/
public static boolean isOnSunday(Calendar calendardate) {

if (calendardate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println("Debug: "
+ String.valueOf(calendardate.get(Calendar.DATE)) + "-"
+ String.valueOf(calendardate.get(Calendar.MONTH) + 1)
+ "-" + String.valueOf(calendardate.get(Calendar.YEAR))
+ " is a SUNDAY.");
} else {
System.out.println("Debug: "
+ String.valueOf(calendardate.get(Calendar.DATE)) + "-"
+ String.valueOf(calendardate.get(Calendar.MONTH) + 1)
+ "-" + String.valueOf(calendardate.get(Calendar.YEAR))
+ " is not a SUNDAY.");
}

return (calendardate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY);
}


public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}

public static void main(String args[]) {
// to findout the number of holidays between these two dates
GregorianCalendar firstdate = new GregorianCalendar();
GregorianCalendar seconddate = new GregorianCalendar(2010, 11, 30);
System.out.println(" year..."+ seconddate.get(Calendar.YEAR));
System.out.println("holiday conunt = " + countNumberOfSaturdaysAndSundays(firstdate, seconddate));
}

}

Here is the code to test with two dates(date1,date2)...

To Find out the holidays between these dates

convert the dates into calendar

GregorianCalendar firstdate = new GregorianCalendar();
GregorianCalendar seconddate = new GregorianCalendar();
firstdate.settime(date1);
seconddate .settime(date2);
// call the method

countNumberOfSaturdaysAndSundays(firstdate, seconddate));
...
...

Tuesday, November 16, 2010

Create a Hello World Webservice Using Axis2


Steps involved in creating Hello World Webservice using axis2
Steps :
1.       Develop a service class(the one you are going to expose as a service)
2.       Write a service descriptor e.g  services.xml
3.       Compile the service class and create web services archieve file
4.       Deploy into axis server(copy the aar file into services folder).


Step 1:      Create the Service class


Package vels.test.ws;

public class HelloWorldService 
{
  public String sayHello(String name) {
    
      out.println("Hello World Service called");
    return "Hello : " + name;
  }
}


Step 2 : Write a Webservice descripttor (service configuration file)

In Axis2 the service configuration (descriptor) file used is services.xml.
The services.xml file must present in the META-INF directory of the service achieve.

services.xml  :
  <service>
 <parameter name="ServiceClass" locked="false">  
                      vels.test.ws.HelloWorldService</parameter>
 <operation name="sayHello">
 <messageReceiver 
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
</service>


                 Here  our  service class is vels.test.ws.HelloWorldService  and
                 the message receiver is org.apache.axis2.rpc.receivers.RPCMessageReceiver.
                 The operation we are exposing is sayHello.

Step 3 :  Creating the archive file for the deployment


  •   Compile all the java files and make it as jar(aar)
  •     For example you have placed all the class files into the following  folder D:\dev\HelloWorld\bin
  •    Run the following command(before that set the java class path )D:\dev\HelloWorld\bin>jar cvf HelloWorldService.aar *(it will take all  the class files and services.xml files and make it as HelloWorldService.aar file)

Deploy the Webservice :    


Creating Client program to access the deployed webservice :

1.   Generate the client side java class From WSDL using axis  WSDLToJava     This will create client specific java files
      
        Place all these jars into class path
        set CLASSPATH=.;D:\lib\axis\axis-1.3.jar;
                   D:\lib\axis\commons-logging-1.0.4.jar;
                   D:\lib\axis\commons-discovery-0.2.jar;
                   D:\lib\axis\jaxrpc.jar;
                   D:\lib\axis\log4j-1.2.8.jar;
                   D:\lib\axis\wsdl4j-1.5.1.jar;D:\lib\axis\saaj.jar;

     java org.apache.axis.wsdl.WSDL2Java ..\res\wsdl\Hello.wsdl -o ..\src –W


2. write a client to test the service

public class Test {
    public static void main(String[] args) throws Exception {
      HelloSOAP11BindingStub stub = new HelloSOAP11BindingStub(new java.net.URL("http://localhost:8080/axis2/services/hello"),null);
        //Create the request
       
       SayHello  request = new
  SayHello();

       request.setName("vels");
        //Invoke the service
        SayHelloResponse response
           = stub.sayHello(request);
       System.out.println("Response : " + response.get_return());
   }
}


Hope u guys got come idea abt webservices.........

Monday, November 15, 2010

How to create JaxWs Webservice with ant and Jboss4.2.2

Simple Steps To create JaxWs Webservice using JBOSS 4.2.2


Pre- Requirement :

1.Jdk1.6
2.Jboss 4.2.2GA
3.Ant
4.Eclipse

Step1 :

Write the service which is going to be exposed as a webservice

package com.vels.test.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class HelloJaxWs {

@WebMethod
public String sayHello(String message) {
System.out.println("sayHello:" + message);
return "You said '" + message + "'";
}
}

Step 2: Create the deployment descriptor (web.xml)

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">


           <servlet>
                     <servlet-name>helloJaxWS</servlet-name>
                    <servlet-class>com.vels.test.ws.HelloJaxWs</servlet-class>
             </servlet>

            <servlet-mapping>
                       <servlet-name>helloJaxWS</servlet-name>
                        <url-pattern>/helloJaxWS</url-pattern>
           </servlet-mapping>
</web-app>

Step 3:

Compile the java source and place class file in to /WebContent/WEB-INF/classes

Step 4:  
               Run the Build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="project" default="deploy">
<property name="jsp.dir.name" value="myapp" />

<property name="WAR_FILE" value="HelloJaxWs.war" />
<property name="JBOSS_HOME" value="D:\apps\jboss\jboss-4.2.2" />
<property name="WS_DEPLOY_DIR" value="${JBOSS_HOME}\server\default\deploy" />

<target name="deploy" description="war file creation">
<war destfile="${WAR_FILE}" webxml="../WebContent/WEB-INF/web.xml">
<classes dir="../WebContent/WEB-INF/classes"/>
</war>
<copy file="${WAR_FILE}" todir="${WS_DEPLOY_DIR}" overwrite="true" />
</target>

</project>



This script will create the War file and deploy into the server deploy folder

Your service is published on the server and u can get the WSDL URL.....http://www.blogger.com/=



Creating a Client to acces the exposed service
Step 1: Write the ant script to create the client spesific Java classes


<?xml version="1.0" encoding="UTF-8"?>
<project name="project" default="wsdltojava">

<property name="JAVA_HOME" value="D:\tools\Java\jdk1.6.0_05" />
<property name="JBOSS_HOME" value="D:\apps\jboss\jboss-4.2.2" />

<target name="init">
<path id="web.services.classpath">
<fileset dir="${JAVA_HOME}\lib" includes="*.jar" />
<fileset dir="${JBOSS_HOME}\lib\endorsed\" includes="*.jar" />
<fileset dir="${JBOSS_HOME}\lib\" includes="*.jar" />
<fileset dir="${JBOSS_HOME}\client">
<include name="activation.jar" />
<include name="getopt.jar" />
<include name="wstx.jar" />
<include name="jbossall-client.jar" />
<include name="log4j.jar" />
<include name="mail.jar" />
<include name="jbossws-spi.jar" />
<include name="stax-api.jar" />
<include name="jaxb-api.jar" />
<include name="jaxb-impl.jar" />
<include name="jaxb-xjc.jar" />
<include name="streambuffer.jar" />
<include name="stax-ex.jar" />
<include name="javassist.jar" />
<include name="jboss-xml-inding.jar" />
<include name="jbossws-client.jar" />
<include name="jboss-jaxws.jar" />
<include name="jboss-jaxrpc.jar" />
<include name="jboss-saaj.jar" />
<include name="jboss-srp-client.jar" />
<include name="jbossws-common.jar" />
<include name="jaxws-tools.jar" />
<include name="jaxws-rt.jar" />
</fileset>

</path>
</target>

<target name="wstaskdef">
<taskdef name="wsconsume"
classname="org.jboss.wsf.spi.tools.ant.WSConsumeTask">
<classpath>
<path refid="web.services.classpath" />
</classpath>
</taskdef>
</target>

<target name="wsdltojava" depends="init,wstaskdef">
  <wsconsume fork="true"
    verbose="true"
   sourcedestdir="../src"
      keep="true" package="com.vels.ws.test.wsclient"
   wsdl="http://127.0.0.1:8080/HelloJaxWs/helloJaxWS?wsdl"
/>
</target>
</project>



It will create all client specific java files and skeletons using WsConsume tool.


Step 2: Write the Client to access the exposed service


package com.vels.ws.test.wsclient;

import javax.xml.ws.BindingProvider;

public class TestClient {
public static void main (String[] a){
try{
System.out.println(" before execution..........");
HelloJaxWsService ws= new HelloJaxWsService();

System.out.println(" before calling
service.........");
HelloJaxWs port = (HelloJaxWs)ws.getHelloJaxWsPort();
System.out.println(port.sayHello(" good evening"));

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

}
}


Output : You said good evening




I will work on some other webservice samples get back to u guys.........c u ....