Sample Code Java Libraries

2008年1月12日土曜日

[Java>Flickrj]Flickr Java API(Flickrj Library)

Access to the Flickr's photo via Flickr Java API(Flickrj Library).
The Api spec is maintained by the Flickr, but this flickrj library kit is not maintained or supported by Flickr. Please read the attention carefully before using this library.

References
  • Flickr's API documents
    http://www.flickr.com/services/api/
  • Flickrj web site
    http://flickrj.sourceforge.net/
  • Flickrj javadoc
    http://flickrj.sourceforge.net/
Install and Setup
  1. Get Flickr API keys to use the Flickr's API
    http://www.flickr.com/services/api/keys/
  2. Download flickrj library and set jar file into the library directory
    http://sourceforge.net/projects/flickrj/
Import Classes
import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.photos.SearchParameters;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.photos.Photo;
Sample Program
  • Search photos with tag keywords and get result
         //Set api key
    String key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    String svr="www.flickr.com";
    REST rest=new REST();
    rest.setHost(svr);

    //initialize Flickr object with key and rest
    Flickr flickr=new Flickr(key,rest);
    Flickr.debugStream=false;

    //initialize SearchParameter object, this object stores the search keyword
    SearchParameters searchParams=new SearchParameters();
    searchParams.setSort(SearchParameters.INTERESTINGNESS_DESC);

    //Create tag keyword array
    String[] tags=new String[]{"Dog","Beagle"};
    searchParams.setTags(tags);

    //Initialize PhotosInterface object
    PhotosInterface photosInterface=flickr.getPhotosInterface();
    //Execute search with entered tags
    PhotoList photoList=photosInterface.search(searchParams,20,1);

    //get search result and fetch the photo object and get small square imag's url
    if(photoList!=null){
    //Get search result and check the size of photo result
    for(int i=0;i<photoList.size();i++){
    //get photo object
    Photo photo=(Photo)photoList.get(i);

    //Get small square url photo
    StringBuffer strBuf=new StringBuffer();
    strBuf.append("<a href=\"\">");
    strBuf.append("<img border=\"0\" src=\""+photo.getSmallSquareUrl()+"\">");
    strBuf.append("</a>\n");
    ....
    }
    }
  • Get photo and information with specified photo ID
         //Set api key
    String key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    String svr="www.flickr.com";
    REST rest=new REST();
    rest.setHost(svr);

    //initialize Flickr object with key and rest
    Flickr flickr=new Flickr(key,rest);
    Flickr.debugStream=false;

    //Initialize PhotosInterface object
    PhotosInterface photosInterface=flickr.getPhotosInterface();
    //Execute search with photo ID you want to get information
    Photo photo=photosInterface.getPhoto("[Photo ID]");
    if(photo!=null){
    StringBuffer strBuf=new StringBuffer();
    strBuf.append("<a href=\"\">");
    strBuf.append("<img border=\"0\" src=\""+photo.getThumbnailUrl()+"\">");
    strBuf.append("</a>\n");
    }

2008年1月10日木曜日

[Java>Apache File Uploader]Sample Program how to use Apache File Uploder

Sample Program how to use Apache File Uploder

References
  • Apache FileUploader
    http://commons.apache.org/fileupload/
  • JavaDoc
    http://commons.apache.org/fileupload/apidocs/index.html
Install and Setup
  1. Get latest jar file of Apache file uploader
    http://commons.apache.org/downloads/download_fileupload.cgi
  2. Get dependency library files
    http://commons.apache.org/fileupload/dependencies.html
  3. Put these files into the program library directory
Sample of HTML file to upload any file from the client's browser
Following sample program has 2 form parameters, one is a file type input parameter, other is a normal text parameter.We can get these 2 types parameter values in the same form.
The form part in HTML is needed the value "enctype="multipart/form-data" in form tag, and input type of the field for file upload has to be set to "file".
Following is a sample html of form part. The value of the action parameter in form tag is a sample method name related to the sample servlet program described below.
<form enctype="multipart/form-data" action="execFileUpload&mode=imageUpload" method="post">
<input size="60" type="file" name="fileName1" /><br>
<input type="text" name="comment" value="" /><br>
</textarea>

<input id="submit" name="submit" type="submit" value="Upload" />
</form>
Import Classes
//Apache FileUploader Classes
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import java.util.Iterator;

//Image Utility
import javax.imageio.ImageIO;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
Sample Program
public Template execFileUpload(HttpServletRequest request,HttpServletResponse response)
{
/*
Check whether the received HttpServletRequest object is multipart or not.
Normally, the HttpServletRequest of servlet program is not multipart.
If the HttpServletRequest is not multipart, the request doesn't include file data.
Check whether the request is multipart or not by using the ServletFileUpload.isMultipartContent.
*/
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart){
/*
If the request is multipart, get file data
Initialize FileItemFactory and ServletFileUpload objects
*/
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);

/*
Get the List object including the file and other values of form parameters,
and then create and get List's iterator object.
We can only use this Iterator object for Multipart List object once.
*/
List items=upload.parseRequest(request);
Iterator itemsIterator=items.iterator();

/*
How to get form parameters.
*/
/*
We can get the value of parameters included into the action method which is not
input parameter. This is a normal parameter.
In this case above, action method in form tag is including the "mode" parameter.
This parameter which is not a form's input parameter can be get the value by using the
HttpServletRequest.getParameter() method.
*/
String mode=request.getParameter("mode");

/*
Get item from the list
*/
while(itemsIterator.hasNext()){
/*
Get parameters in form tags, input text, hidden, submit parameters.
We can get any input parameters as the FileItem object.
*/
FileItem item=(FileItem)itemsIterator.next();

/*
Get the value of ContentType.
If the input type is defined as "file", the value of ContentType is set to the
Image type like "image/jpeg".
If the intput type is not "file", the value of ContentType is set to null.
*/
String itemContentType=item.getContentType();

/*
Get the value of the file name
If the input type is defined as "file", the getName() method of FileItem object
returns the file name specified by the client when uploading the file.
If the intput type is not "file", the value of getName() is set to null.
*/
String itemFileName=item.getName();

/*
Get the value of intput attribute name.
*/
String itemFieldName=item.getFieldName();

/*
Get and check the form's field type.
If the input type is defined as "file", the isFormField() method of FileItem object
returns false.
If the intput type is not "file", the value of isFormField() returns true.
*/
if(item.isFormField()){
/*
Get the value of normal input parameter.
If the intput type is not "file", get the value by using FileItem's getString() method.
*/
String itemFieldValue=item.getString();
}
else{
/*
Get and check the file's field name.
We defines the name of "fileName1" for Intput form attribute.
*/
if(itemFieldName!=null && itemFieldName.equals("fileName1")){
/*
Get byte arrays for the file sent from the client.
*/
byte[] itemBytes=item.get();
/*
Get InputStream object
*/
InputStream itemInputStream=item.getInputStream();

/*
Convert InputStream object to BufferedImage object if you need.
In this case, put the image file to the disk storage.
*/
BufferedImage bufferedImage=ImageIO.read(itemInputStream);
/*
Create File object and output BufferedImage object to the File.
*/
File imageFile=new File("/tmp/test.jpg");
boolean outResult=ImageIO.write(bufferedImage,"jpg",imageFile);
......
}
}
}
}
}

2008年1月9日水曜日

[Java>WhirlyCache]Object Cache Mechanism(Whirlycache)

EHCache or OSCache is a very famous libraries for java object cache, but Whirlycache is a simple and fast cache mechanism stored object on local JVM memory. Whirlycache doesn't have a cache replication mechanism or other complex mechanism, but this cache is very simple, useful and easy to use, and lightweight library.
Whirlycache maintenances the objects stored into the Cache instance by using the Tuner Thread. Tuner Thread is started up if the Cache instance is created. and Tuner thread loops and maintenances the stored objects.For example, if the object stored into the cache is expired, Tuner thread removes the expired object from cache instance.(Normally cache logic maintenances the stored objects when System triggers putting the object into the cache instance.)

References
  • Whirlychache home
    https://whirlycache.dev.java.net/
  • About whirlycache
    http://www.theserverside.com/news/thread.tss?thread_id=29290
Install and Setup
  1. download whirlycache library from https://whirlycache.dev.java.net/
    all of files and dependency libraries are included into the whirlycache-1.0.1.zip.
  2. unzip whirlycache-1.0.1.zip
  3. get jar files
    get 4 files(commons-collections-3.1.jar, commons-logging-1.1.jar, concurrent-1.3.4.jar, whirlycache-1.0.1.jar) at least. These files are included into the lib directory.
  4. create xml file for cache setup, cache size, cache policy class and tuner's sleeptime.
    sample xml file is https://whirlycache.dev.java.net/sample-whirlycache-xml-file.html
    default xml file including the default parameter values are included into the whirlycache's jar file(whirlycache-default.xml)
    If you need to customize the value of parameters, create a new xml file and put it into the classpath directory.
Import classes
import com.whirlycott.cache.CacheManager;
import com.whirlycott.cache.Cache;
import com.whirlycott.cache.CacheException;
Sample Program
public class CacheTest{
//define whirlycache Cache object
static Cache whirlycache=null;
//initialize whirlycache's cache instance
static{
try{
whirlycache=CacheManager.getInstance().getCache();
}catch(CacheException eCache){
//if system fails to initialize the cache instance, set null
whirlycache=null;
}
}

//check logic whether the Cache instance is initialized properly or not and
//cache key is eligible or not.
private boolean checkCache(String pKey){
if(whirlycache==null){
return false;
}
if(pKey==null || pKey.equals("")){
return false;
}
return true;
}

//get object from cache instance based on specified argument value.
private Object getObjectFromCache(String pKey){
if(checkCache(pKey)==false){
return null;
}
return whirlycache.retrieve(pKey);
}

//store object into the cache object with expire long value
private void storeObjectIntoCache(String pKey,Object pObject,long pExpireDateLong){
if(checkCache(pKey)==false){
return;
}
if(pExpireDateLong < 0){
//cache object with no expire date
whirlycache.store(pKey,pObject);
}
else{
//cache object with expire date, this object will cleanup automatically after expire date
whirlycache.store(pKey,pObject,pExpireDateLong);
}
}

//remove cached object from cache instance.
private void removeObjectFromCache(String pKey){
if(checkCache(pKey)==false){
return;
}
whirlycache.remove(pKey);
}

//check whether the object related to the key is existed into the cache instance or not.
private boolean containObjectInCache(String pKey){
if(checkCache(pKey)==false){
return false;
}
Object cachedObject=getObjectFromCache(pKey);
if(cachedObject==null){
return false;
}
return true;
}

//program main method
public static void main(String[] args){
//test cache key
String cacheKey="cache_test_date";
//get object from cache instance
Date cacheDate=getObjectFromCache(cacheKey);
if(cacheDate==null){
//if misscache, set new value to variable
cacheDate=new Date();
storeObjectIntoCache(cacheKey,cacheDate);
System.out.println("initialize new date object and put it into cache, date="+cacheDate);
}
else{
//could find and get value from cache instance
System.out.println("get date object from cache, date="+cacheDate);
}
}
}

2008年1月5日土曜日

[JAVA>Diff]Sample program how to use Java's diff Library(JRCS Library)

Sample program how to use Java's diff Library and output difference between 2 arrays.
(There are some diff libraries written in Java, but in this case, I use JRCS diff library.)

Java Diff Library References
  • JRCS Home
    http://www.suigeneris.org/kb/display/jrcs/JRCS+Home
  • Other Diff Libraries written in Java
    http://www.incava.org/projects/java/
  • Diff Libraries written in JavaScript
    http://ejohn.org/projects/javascript-diff-algorithm/
  • Other References
    • http://amateras.sourceforge.jp/cgi-bin/fswiki/wiki.cgi/free?page=JRCS
    • Wikipedia Diff
      http://ja.wikipedia.org/wiki/Diff
Installations
  1. Download the latest JRCS Library jar file.
    http://www.suigeneris.org/kb/display/jrcs/JRCS+Home#JRCSHome-Downlodables
  2. Unzip the latest zip file
  3. get org.suigeneris.jrcs.diff-(version number).jar file from unzipped files.

Sample Program
  • Import classes
    import org.suigeneris.jrcs.diff.simple.SimpleDiff;
    import org.suigeneris.jrcs.diff.DiffAlgorithm;
    import org.suigeneris.jrcs.diff.Diff;
    import org.suigeneris.jrcs.diff.Revision;
    import org.suigeneris.jrcs.diff.delta.Delta;
    import org.suigeneris.jrcs.diff.delta.Chunk;
    import org.suigeneris.jrcs.diff.DifferentiationFailedException;
    import org.suigeneris.jrcs.util.ToString;
  • Program
    public void DiffTest(){
    try{
    //Initializing diff algorithm, in this sample, use SimpleDiff Algorithm
    DiffAlgorithm algorithm=new SimpleDiff();

    //Create 2 arrays to output sample difference
    String[] origs=new String[]{"one","two","three","four","five"};
    String[] revised=new String[]{"two","four"};

    //Create new Diff Object
    //first argument is original array, second argument is algorithm object.
    Diff difference=new Diff(origs,algorithm);
    //Call diff() method for Diff Object with new array you want to get difference between original
    Revision rev=difference.diff(revised);

    //Output difference between original and revised arrays to use Revision's toString()
    System.out.println(rev.toString());
    /*
    Sample output of revision's toString()
    1d0
    < one
    3d1
    < three
    5d2
    < five
    */

    System.out.println(rev.toRCSString());
    /*
    Sample Output of revision's toRCSString()
    d1 1
    d3 1
    d5 1
    */

    //get all positions and information existing the difference
    System.out.println("**********Diff Delta**********");
    for(int i=0;i<rev.size();i++){
    Delta delta=rev.getDelta(i);
    Chunk origChunk=delta.getOriginal();
    Chunk revisedChunk=delta.getRevised();
    System.out.println("delta="+delta.toString());
    System.out.println("orig range ="+origChunk.rangeString());
    System.out.println("revised range="+revisedChunk.rangeString());
    }
    /*
    Sample Output of delta
    **********Diff Delta**********
    delta=1d0
    < one

    orig range =0
    revised range=0

    delta=3d1
    < three

    orig range =2
    revised range=1

    delta=5d2
    < five

    orig range =4
    revised range=2
    */
    }catch(DifferentiationFailedException eDifferentiationFailed){
    //sometimes throw Exception in Diff.diff() method
    System.out.println("Exception occured, pos:1, e="+eDifferentiationFailed);
    }
    }

2007年12月29日土曜日

How to convert InputStream to others, BufferedImage to othres.

How to convert InputStream to others, BufferedImage to othres.
  • References
    • Java API Doc http://java.sun.com/j2se/1.5.0/docs/api
  • InputStream to BufferedImage
    InputStream inputStream;
    ........
    BufferedImage bufferedImage=javax.imageio.ImageIO.read(inputStream);
  • BufferedImage to File
    File outputFile=new File("/tmp/test.jpg");
    BufferedImage bufferedImage;
    String formatName="jpeg";
    .....
    boolean result=javax.imageio.ImageIO.write(bufferedImage,formatName,outputFile);
  • InputStream to File
    InputStream inputStream;
    File outputFile=new File("/tmp/test.jpg");
    BufferedImage bufferedImage;
    String formatName="jpeg";
    ........
    BufferedImage bufferedImage=ImageIO.read(inputStream);
    ImageIO.write(bufferedImage,formatName,outputFile);
  • InputStream to OutputStream
    InputStream inputStream;
    OutputStream outputStream;
    .....
    byte[] streamBytes=new byte[1024];
    int ch=0;
    while((ch=inputStream.read(streamBytes)) != -1) {
    outputStream.write(streamBytes, 0, ch);
    }
    outputStream.flush();

  • BufferedImage to ByteArrayInputStream
    BufferedImage bufferedImage;
    String formatName="jpeg";
    ......
    ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
    ImageIO.write(bufferedImage,formatName,byteArrayOutputStream);
    byte[] imageBytes=byteArrayOutputStream.toByteArray();
    ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(imageBytes);
  • ByteArrayOutputStream to BufferedImage
    ByteArrayOutputStream byteArrayOutputStream=null;
    byte[] bytes=byteArrayOutputStream.toByteArray();
    ...
    ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
    BufferedImage bufferedImage=ImageIO.read(byteArrayInputStream);
  • Resize and Scale BufferedImage
    BufferedImage bufferedImage;
    .....
    //scale buffered image and create new Image Object
    Image tmpImage=bufferedImage.getScaledInstance((int)newImageWidth,(int)newImageHeight,Image.SCALE_AREA_AVERAGING);
    //create new BufferedImage object
    BufferedImage resizeImage=new BufferedImage((int)newImageWidth,(int)newImageHeight,bufferedImage.getType());
    //create new Graphics for BuffereImage and output Temporary Image object into it.
    Graphics2D resizeImageGraphics=resizeImage.createGraphics();
    resizeImageGraphics.drawImage(tmpImage,0,0,null);