Sunday, February 27, 2011

Listing the files from FTP order by modification date



Downloading the files from ftp order by modification date



Here we are using ftp4j for FTP operations.

Before going to listing FTP files let us see how to list the files from local filesystem.

But before going to do this you must know what is comparable interface and what it will do?


The Comparable Interface:

Objects of classes that implement Comparable can be ordered.
The Comparable interface declares one method 
that is used to determine the natural 
ordering of instances of a class.
The signature of the method is shown here:

int compareTo(Object obj)

This method compares the invoking object with obj.
It returns 0 if the values are equal.
A negative value is returned if the invoking 
object has a lower value. Otherwise, a positive value is returned.
		

This is an example of comparable interface with the modification date of local system files .

	import java.io.File;
	class FileComparator implements Comparable {
	    public long time;
	    public File filename;
	
	    public FileComparator(File file) {
	    	filename = file;
	    	time = file.lastModified().getTime();
	    }
	
		public int compareTo(Object o) {
	        long u = ((FileComparator) o).time;
	        return time < u ? -1 : time == u ? 0 : 1;
	    }
	};

And this is an example of comparable interface with the modification dates of FTP files .

	
	import it.sauronsoftware.ftp4j.FTPFile;		
	class FTPFileComparator implements Comparable {
	    public long time;
	    public FTPFile filename;
	
	    public FTpFileComparator(FTPFile file) {
	    	filename = file;
	    	time = file.getModifiedDate().getTime();
	    }
	
		public int compareTo(Object o) {
	        long u = ((FTpFileComparator) o).time;
	        return time < u ? -1 : time == u ? 0 : 1;
	    }
	};

This is an example for listing the files order by modification dates .

	import java.io.File;
	File inpDir=new File("/opt/directory");
	if(inpDir.isDirectory()){
		File files[]=inpDir.listFiles();
		FileComparator[] comp = new FileComparator[files.length];
		
	      for (int i = 0; i < files.length; i++)
	    	  comp[i] = new FileComparator(files[i]);
	      
	      Arrays.sort(comp);
	      
	      for (int i = 0; i < files.length; i++)
	          files[i] = comp[i].filename;  
	      
	      for (int i = 0; i < files.length; i++)
	    	  System.out.println(files[i]);
	}

This is an example for listing the FTP files order by modification dates .

	import it.sauronsoftware.ftp4j.FTPFile;
		
	FTPClient client=new FTPClient();
	client.connect(inpFtpUrl);
	client.login(inpFtpUserName, inpFtpPassword);
	client.changeDirectory(inpFtpDirPath);
	FTPFile[] files = client.list();                     
	FTpFileComparator[] comp = new FTpFileComparator[files.length];

	      for (int i = 0; i < files.length; i++)
	    	  comp[i] = new FileComparator(files[i]);
	      
	      Arrays.sort(comp);
	      
	      for (int i = 0; i < files.length; i++)
	          files[i] = comp[i].filename;  
	      
	      for (int i = 0; i < files.length; i++)
	    	  System.out.println(files[i]);   
    

Thursday, January 13, 2011

ISBN validation In Java

Use Jakarta-ORO for ISBN validation.

The Jakarta-ORO Java classes are a set of text-processing
 Java classes that provide Perl5 compatible regular
 expressions, AWK-like regular expressions, 
glob expressions, and utility classes 
for performing substitutions, 
splits, filtering filenames, etc.

Download Jakarta-ORO jar
import org.apache.oro.text.perl.Perl5Util;

public class ISBNValidator {

  private static final String SEP = "(\\-|\\s)";
  private static final String GROUP = "(\\d{1,5})";
  private static final String PUBLISHER = "(\\d{1,7})";
  private static final String TITLE = "(\\d{1,6})";
  private static final String CHECK_ISBN10 = "([0-9X])";
  private static final String CHECK_ISBN13 = "(\\d)";
  private static final String PREFIX = "(978|979)";

  private static final String ISBN10_PATTERN = "/^" + GROUP
                     + SEP + PUBLISHER + SEP + TITLE + SEP
                     + CHECK_ISBN10 + "$/";

  private static final String ISBN13_PATTERN = "/^" + 
           PREFIX + SEP + GROUP + SEP + PUBLISHER + SEP
           + TITLE + SEP + CHECK_ISBN13 + "$/";

  private static final String 
                       EAN13_PATTERN = "/^" + PREFIX + "\\d{10}$/";

  public ISBNValidator() {
    super();
  }

  public boolean isValid(String isbn) {
    return isValidISBN10(isbn) || isValidISBN13(isbn);
  }

  public boolean isValidISBN10(String isbn) {
    if (isbn == null || isbn.length() < 10 || isbn.length() > 13) {
      return false;
    }

    if (isFormatted(isbn) && !isValidPatternISBN10(isbn)) {
      return false;
    }

    isbn = cleanISBN10(isbn);
    if (isbn.length() != 10) {
      return false;
    }

    return (sumISBN10(isbn) % 11) == 0;
  }

  public boolean isValidISBN13(String isbn) {
    if (isbn == null || isbn.length() < 13 || isbn.length() > 17) {
      return false;
    }

    if (isFormatted(isbn)) {
      if (!isValidPatternISBN13(isbn)) {
        return false;
      }
      isbn = toEAN13(isbn);
    }
    return isValidEAN13(isbn);
  }

  public boolean isValidEAN13(String ean13) {
    if (ean13 == null || ean13.length() != 13 || !isValidPatternEAN13(ean13)) {
      return false;
    }

    return (sumEAN13(ean13) % 10) == 0;
  }

  private int sumISBN10(String isbn) {
    int total = 0;
    for (int i = 0; i < 9; i++) {
      int weight = 10 - i;
      total += (weight * toInt(isbn.charAt(i)));
    }
    total += toInt(isbn.charAt(9)); // add check digit
    return total;
  }

  private int sumEAN13(String isbn) {
    int total = isbn.charAt(0);
    for (int i = 1; i < 13;) {
      total += (3 * isbn.charAt(i++)) + isbn.charAt(i++);
    }

    return total;
  }

  private String cleanISBN10(String isbn) {
    StringBuffer buf = new StringBuffer(10);

    for (int i = 0; i < isbn.length(); i++) {
      char digit = isbn.charAt(i);
      if (Character.isDigit(digit) || (digit == 'X')) {
        buf.append(digit);
      }
    }

    return buf.toString();
  }

  private String toEAN13(String isbn) {
    StringBuffer buf = new StringBuffer(13);

    for (int i = 0; i < isbn.length(); i++) {
      char digit = isbn.charAt(i);
      if (Character.isDigit(digit)) {
        buf.append(digit);
      }
    }

    return buf.toString();
  }

  private int toInt(char ch) {
    return (ch == 'X') ? 10 : Character.getNumericValue(ch);
  }

  private boolean isFormatted(String isbn) {
    return ((isbn.indexOf('-') != -1) || (isbn.indexOf(' ') != -1));
  }


  private boolean isValidPatternISBN10(String isbn) {
    return new Perl5Util().match(ISBN10_PATTERN, isbn);
  }

  private boolean isValidPatternISBN13(String isbn) {
    return new Perl5Util().match(ISBN13_PATTERN, isbn);
  }


  private boolean isValidPatternEAN13(String isbn) {
    return new Perl5Util().match(EAN13_PATTERN, isbn);
  }

}

ISBN-10 to ISBN-13 Conversion in Java

public class ISBNConvertor {

  private static String CheckDigits = new String("0123456789X0");

  ///////////////////////////////// Main /////////////////////
  public static void main(String[] args) {
    String ISBN = new String();
    if (args.length==1) {
      ISBN = args[0];
      if (ISBN.length()==10) 
                System.out.println(ISBN1013(ISBN));
      else if (ISBN.length()==13) 
                 System.out.println(ISBN1310(ISBN));
      else ISBN = "Invalid ISBN";
    }
  }

  /////////////// Change a character to its integer value ///////
  static int CharToInt(char a) {
    switch (a) {
      case '0':   return 0;
      case '1':   return 1;  
      case '2':   return 2;
      case '3':   return 3;  
      case '4':   return 4;
      case '5':   return 5;
      case '6':   return 6;
      case '7':   return 7;
      case '8':   return 8;
      case '9':   return 9;
      default:    return -1;
    }
  }

  ////////////////////// Convert ISBN-13 to ISBN-10 //////
  public static String ISBN1310(String ISBN) {
    String s9;
    int i, n, v;
    boolean ErrorOccurred;
    ErrorOccurred = false;
    s9 = ISBN.substring(3, 12);
    n = 0;
    for (i=0; i<9; i++) {
      if (!ErrorOccurred) {
        v = CharToInt(s9.charAt(i));
        if (v==-1) ErrorOccurred = true;
        else n = n + (10 - i) * v; 
      }
    }
    if (ErrorOccurred) return "ERROR";
    else {
      n = 11 - (n % 11);
      return s9 + CheckDigits.substring(n, n+1); 
    }
  }

  ////////////////////// Convert ISBN-10 to ISBN-13 //////
  public static String ISBN1013(String ISBN) {
    String s12;
    int i, n, v;
    boolean ErrorOccurred;
    ErrorOccurred = false;
    s12 = "978" + ISBN.substring(0, 9);
    n = 0;
    for (i=0; i<12; i++) {
      if (!ErrorOccurred) {
        v = CharToInt(s12.charAt(i));
        if (v==-1) ErrorOccurred = true;
        else {
          if ((i % 2)==0) n = n + v;
          else n = n + 3*v;
        }
      }
    }
    if (ErrorOccurred) return "ERROR";
    else {
      n = n % 10;
      if (n!=0) n = 10 - n;
      return s12 + CheckDigits.substring(n, n+1);
    }
  }
}

Friday, January 7, 2011

How to replace Doctype of xml using sax ?

Using SAX Entity Resolver you can change the DOCTYPE of xml .

Example :

String OnixFile=onixfilename; 
   
XMLReader readers = XMLReaderFactory.createXMLReader();
   
readers.setContentHandler(this);
readers.setErrorHandler(this);

readers.setEntityResolver(new Resolver()); 
FileReader filereader=new FileReader(OnixFile);
InputSource is=new InputSource(filereader);
is.setEncoding("UTF-8");
readers.parse(is);


class Resolver implements EntityResolver{

@Override
public InputSource resolveEntity(String publicId,String systemId)
   throws SAXException, IOException {
  if(systemId.equalsIgnoreCase(
    "http://www.editeur.org/onix/2.1/short
                     /onix-international.dtd")){

   String path="/ONIX 2.1 Revision 03 
                        reference/onix-international.dtd";
       return new InputSource(path);
 }
  return null;
 }
 
}

How to get currently executing jobs In Quartz Schedular ?

Example:

import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

Scheduler sch=new StdSchedulerFactory().getScheduler();
List jobsList=sch.getCurrentlyExecutingJobs();
Iterator jobsIterator=jobsList.listIterator();

while(jobsIterator.hasNext()){
 JobExecutionContext context = 
                 (JobExecutionContext) jobsIterator.next();
 System.out.println(context.getJobDetail().getName());
}