Wednesday, February 16, 2011

How to Extract ZIP/JAR/WAR/TAR/RAR file Using Java

Extracting ZIP/JAR/WAR/TAR/RAR file using java

Using ZipEntry and ZipInputstream classes we can extract the zip/jar/war/tar files.

here is the code snippet....


 public static void extractZipFiles(String filename) {
   try {
             // destination folder to extract the contents         
             String destinationname = "d:\\temp\\testZip\\";          

             byte[] buf = new byte[1024];
             ZipInputStream zipinputstream = null;
             ZipEntry zipentry;
             zipinputstream = new ZipInputStream(new FileInputStream(filename));
            zipentry = zipinputstream.getNextEntry();
 
           while (zipentry != null) {

                 // for each entry to be extracted
                 String entryName = zipentry.getName();
    
                 int n;
                FileOutputStream fileoutputstream;
                File newFile = new File(entryName);

              String directory = newFile.getParent();

              // to creating the parent directories
              if (directory == null) {
                   if (newFile.isDirectory()){
                         break;
                      }
             } else {
                 new File(destinationname+directory).mkdirs();
              }
    

            if(!zipentry.isDirectory()){
                       System.out.println("File to be extracted....."+ entryName);
                       fileoutputstream = new FileOutputStream(destinationname  + entryName);
                      while ((n = zipinputstream.read(buf, 0, 1024)) > -1){
                              fileoutputstream.write(buf, 0, n);
                       }
                      fileoutputstream.close();
            }
             
           zipinputstream.closeEntry();
           zipentry = zipinputstream.getNextEntry();
          }// while
  
     zipinputstream.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();
}

...
...

Thursday, February 3, 2011

Hacking a Website using Javascript

How to Hack a website.....
Hack instructions:
1. Go to the website which has more number images like
www.myspace.com,google
2. Wait for the page to fully load
3. In your browser’s address bar, enter the code below (copy and paste all in one line)
4. Hit enter
5. Wait a second and See what happens ...coool

script need to be copied..

javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24;x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length;function A(){for(i=0; i<dil ; i++){DIS=DI[ i ].style;DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5;DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++ }setInterval('A()',5); void(0);

................

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).