Code I/O

A topnotch WordPress.com site


Leave a comment

5 Minutes on Java : JSON to XML

You’ve hit this page because you are looking for this utility as I did today.  I wanted to convert JSON to XML in an easier way.  Thanks to http://openjsan.org/src/k/ka/kawasaki, who has implemented XML.ObjTree for performing JSON2XML conversion very elegantly.  All, I needed to do was to put in a Java wrapper.  Here is the XMLObjTree.java, a java wrapper for Kawasaki’s implementation.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

// A Java wrapper for XML.ObjTree
// Thanks to - http://openjsan.org/src/k/ka/kawasaki/XML.ObjTree-0.24/README
public class XMLObjTree {
    public static ScriptEngine getJsengine() {
		return jsEngine;
	}

	private static ScriptEngine jsEngine;

    static {
        try {
        	jsEngine = new ScriptEngineManager().getEngineByExtension("js");

        	InputStream is = XMLObjTree.class.getResourceAsStream("/scripts/js/XML/ObjTree.js");
        	InputStreamReader reader = new InputStreamReader(is);

        	jsEngine.eval(reader);

			is.close();
			reader.close();
		} catch (ScriptException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    public String jsonToXml(final File jsonFile) throws FileNotFoundException, IOException {
    	return (jsonToXml(StreamUtils.streamToString(jsonFile)));
    }

    public String jsonToXml(final InputStream is){
    	String input = StreamUtils.streamToString(is);

    	return (jsonToXml(input));
    }

    public String jsonToXml(final String jsonText) {
        try{
            return (String) jsEngine.eval("(new XML.ObjTree()).writeXML(" + jsonText + ");");
        }
        catch(ScriptException ex) {
            throw new RuntimeException(ex);
        }
    }
}

Here is the StreamUtils  you’ll need

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

public class StreamUtils {
	public static String streamToString(InputStream is) {
		try
		{
			final char[] buffer = new char[4096];
			StringBuilder out = new StringBuilder();

			Reader in = new InputStreamReader(is, "UTF-8");

			int read;
			do
			{
				read = in.read(buffer, 0, buffer.length);
				if (read > 0)
				{
					out.append(buffer, 0, read);
				}
			} while (read >= 0);

			in.close();

			return out.toString();
		} catch (IOException ioe)
		{
			throw new IllegalStateException("Error while reading input stream", ioe);
		}
	}

	public static String streamToString(File file) throws FileNotFoundException, IOException {
		FileInputStream fis = new FileInputStream(file);

		String string = streamToString(fis);
		fis.close();

		return string;
	}

	public static void write(final String data, final Writer writer) throws IOException{
		writer.write(data);

		writer.flush();

		writer.close();
	}

	public static void write(final String data, final File file) throws IOException{
		try{
			FileOutputStream fos = new FileOutputStream(file);

			Writer writer = new OutputStreamWriter(fos, "UTF-8");
			write(data, writer);

			fos.close();
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
		}
	}
}

Let’s put it to use using some sample JSON text

    public static void main(String[] args){
		final String filePath = "/Shared/test-data/test-data.json";
		final File jsonFile = new File(filePath);

		try {
			XMLObjTree xmlObjTree = new XMLObjTree();

			System.out.println("XMLnn" + xmlObjTree.jsonToXml(jsonFile));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


Leave a comment

5 minutes on Adobe Flex: A service proxy pattern for applications

The process of communication involved between Rich Internet Applications and Server components is very repeatable:

  • Sending request to server
  • handling its result or fault, and
  • finally processing the result for the application to provide desired functionality

The process involves invoking services and handling responses individually, One can think of simplifying the process by introducing the Service Proxy pattern, which becomes handy to manage the entire application specific communications.

The benefit of this pattern is that, one can process results specifically with respect to business logic at the same time having a unified interface to manage server side interactions.

package service
{
 import mx.controls.Alert;
 import mx.rpc.events.FaultEvent;
 import mx.rpc.events.ResultEvent;
 import mx.rpc.http.HTTPService;

 public class ServiceProxy
 {
 private static var SERVICE_URL:String;
 public static function getURL():String{
 return SERVICE_URL;
 }
 public static const TERMS_AND_CONDITIONS_PAGE:String = "/sub_tac.html";

 public function ServiceProxy()
 {
 throw new Error("ServiceProxy cannot be instantiated");
 }

 public static const CHECK_SUBSCRIBER:String     = "CHECK_SUBSCRIBER";
 public static const LOAD_DICTIONARY:String         = "LOAD_DICTIONARY";
 public static const SUBSCRIBE:String             = "SUBSCRIBE";
 public static const UNSUBSCRIBE:String             = "UNSUBSCRIBE";
 public static const CHANGE_SUBSCRIPTIONS:String = "CHANGE_SUBSCRIPTIONS";

 private static function init():void {
 register(LOAD_DICTIONARY,
 {script:"/php/load_dictionary.php",         method:"GET",    success:"", failure:""});

 register(CHANGE_SUBSCRIPTIONS,
 {script:"/php/change_subscriptions.php",     method:"POST",    success:"/sub_success.html", failure:""});

 register(CHECK_SUBSCRIBER,
 {script:"/php/check_subscriber.php",         method:"POST",    success:"", failure:""});

 register(SUBSCRIBE,
 {script:"/php/subscribe.php",                 method:"POST",     success:"/sub_success.html", failure:""});

 register(UNSUBSCRIBE,
 {script:"/php/unsubscribe.php",             method:"POST",    success:"/unsub_success.html", failure:""});
 }

 private static var registry:Object = null;
 public static function getObjectByTag(tag:String):Object{
 if(registry == null){
 registry = {};

 init();
 }

 return registry[tag];
 }

 public static function register(handle:String, object:Object):Boolean {
 if(!registry[handle]){
 registry[handle] = object;
 return true;
 }

 return false;
 }

 public static function execute(tag:String, xml:XML=null, callback:Function=null):void {
 var o:Object = getObjectByTag(tag);
 if(o == null){
 throw new Error(tag + " is not supported currently!!");
 return;
 }

 var s:HTTPService = new HTTPService();

 s.url = SERVICE_URL + o.script;
 s.method = o.method;
 s.contentType = HTTPService.CONTENT_TYPE_XML;
 s.resultFormat = HTTPService.RESULT_FORMAT_E4X;

 if(xml != null){
 s.request = xml;
 }

 s.addEventListener(ResultEvent.RESULT,
 function resultHandler(event:ResultEvent):void
 {
 var xml:XML = XML(event.result);

 trace("RESULTn" + xml);
 if(callback != null){
 callback(xml);
 }
 }
 );

 s.addEventListener(FaultEvent.FAULT,
 function faultHandler(event:FaultEvent):void
 {
 trace("ERROR: " + event.message);
 Alert.show("Error communicating to server, try again later", "Communication Fault");
 }
 );

 s.send();
 }

 public static function initFromURL():void
 {
 var url:String = FlexGlobals.topLevelApplication.url;
 var protocol:String = "http";
 var server:String = "192.168.1.100";
 var port:String = "8085";
 var prefix:String = "/referral-network";

 if (url.search("file://") >= 0)
 {
 }
 else
 {
 var i:int = url.indexOf("://");
 if (i >= 0) {
 protocol = url.substring(0, i);
 }

 url = url.replace(protocol + "://", "");
 url = url.substring(0, url.search("/"));

 var array:Array = url.split(":");
 if (array.length >= 1)
 {
 server = array[0];
 }
 if (array.length >= 2)
 {
 port = array[1];
 }
 else
 {
 if (protocol != null && protocol == "https")
 port = "443";
 else
 port = "80";
 }
 }

 SERVICE_URL = protocol + "://" + server + ":" + port + prefix;
 }
 }
}

Here is a simple usage of the pattern

public function unSubscribe():void{
	var xml:XML = <input />;

	var profile:XML = <profile />;
	xml.appendChild(profile);

	trace("DATA TO SEND: " + xml);
	ServiceProxy.execute(ServiceProxy.UNSUBSCRIBE, xml, unsubscribeResultHandler);
}

private function unsubscribeResultHandler(xml:XML):void{
	// Your Business Logic Here ...
}


Leave a comment

5 Minutes on Adobe Flex – A reusable XMLFile class

Handling files in Flex is something each application will do, I hope this XMLFile class can be useful out there.  Further this class can be extend to handle specific objects like Application preferences.   The listing of PreferencesFile source is here

XMLFile.as


package foss.afxtionlib.files
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;

	public class XMLFile
	{
		protected var _directory:File = null;
		protected var _file:File = null;
		protected var _data:XML = null;

		public function XMLFile(fileName:String, storageDirectory:File=null)
		{
			if(storageDirectory == null)
			{
				_directory = File.documentsDirectory;
			}
			else
			{
				_directory = storageDirectory;
			}

			if(_file == null)
			{
				_file = _directory.resolvePath(fileName);
			}

			if (_file.exists) {
			    _data = readXML();
			}
		}

		public function get file():File
		{
			return(_file);
		}

		public function set file(file:File):void
		{
			_file = file;
		}

		public function get data():XML
		{
			return(_data);
		}

		public function set data(xml:XML):void
		{
			_data = xml;
		}

		public function set directory(storageDirectory:File):void
		{
			_directory = storageDirectory;
		}

		public function get directory():File
		{
			return(_directory);
		}

		public function saveXML():void
		{
			var outputString:String = '<?xml version="1.0" encoding="utf-8"?>n';
			outputString += data.toXMLString();
			outputString = outputString.replace(/n/g, File.lineEnding);

			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.WRITE);
			stream.writeUTFBytes(outputString);
			stream.close();
		}

		public function readXML():XML
		{
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.READ);

			data = XML(stream.readUTFBytes(stream.bytesAvailable));
			stream.close();

			return(data);
		}
	}
}

PreferencesFile.as


package foss.afxtionlib.files
{
	import flash.filesystem.File;

	public class PreferencesFile extends XMLFile
	{
		private var _templateXML:XML = null;

		public function PreferencesFile(tx:XML)
		{
			_templateXML = tx;
			super("Preferences.xml", File.applicationStorageDirectory);

			if(file.exists == false || data == null)
			{
				setPreferences();
			}
			trace("PSP=" + file.nativePath + "ndata=" + data);
		}

		public function setPreferences(d:XML=null):void
		{
			if(d == null)
			{
				data = _templateXML;
			}
			else
			{
				data = d;
			}
		}

		public function getPreferences():XML
		{
			if(data == null)
			{
				return(_templateXML);
			}

			return(data);
		}
	}
}


Leave a comment

5 Minutes on Adobe Flex – Binding XML to DataGrid

I’ve been curious to bind XML directly to a data-grid, and here is a way I found to do so.

Assume the following XML data which is defined using attributes as.

var baXml:XML = new XML("<BankAccounts />");
baXml.appendChild(XML('<BankAccount bankName="Bank ABC" accountNumber="12345" />'));
baXml.appendChild(XML('<BankAccount bankName="Bank 123" accountNumber="66666" />'));
baXml.appendChild(XML('<BankAccount bankName="Bank XYZ" accountNumber="77777" />'));

baDG.dataProvider = (xml.BankAccount);

The easiest way to bind this XML directly is better such that I don’t have to build any intermediate arrayCollection or other data structure.

Since we know that the rows are of interest in this scenario, we can bind data directly as data provider elements.

Once it is done, the datagrid uses the XML attribute names directly to render the values

<mx:DataGrid id="baDG" x="25" y="20" width="544" height="156" >
    <mx:columns>
        <mx:DataGridColumn headerText="Bank Name" dataField="@bankName"/>
        <mx:DataGridColumn headerText="Account Number" dataField="@accountNumber"/>
    </mx:columns>
</mx:DataGrid>

The same is not possible when the XML data is defined as elements.  Lets describe the above data as elements now.

var baXml:XML = <BankAccounts>
    <BankAccount>
        <bankName>Bank ABC</bankName>
        <accountNumber>12345</accountNumber>
    </BankAccount>
    <BankAccount>
        <bankName>Bank 123</bankName>
        <accountNumber>66666</accountNumber>
    </BankAccount>
    <BankAccount>
        <bankName>Bank XYZ</bankName>
        <accountNumber>77777</accountNumber>
    </BankAccount>
</BankAccounts>;

Once the elements are defined, the datagrid uses the element names directly to render the values

<mx:DataGrid id="baDG" x="25" y="20" width="544" height="156">
    <mx:columns>
        <mx:DataGridColumn headerText="Bank Name" dataField="bankName"/>
        <mx:DataGridColumn headerText="Account Number" dataField="accountNumber"/>
    </mx:columns>
</mx:DataGrid>

All of this can be done in just 5 minutes 🙂


12 Comments

5 Minutes on Java – A quick tutorial on JAXB

New: You can get entire source code for this post from git-hub: http://github.com/udy/lifencode-samples/tree/master/java/jaxb-in-5-minutes/

This is my first post on 5 minutes series of articles on technology and it’s on JAXB.

Read about JAXB at:

http://java.sun.com/developer/technicalArticles/WebServices/jaxb

http://en.wikipedia.org/wiki/JAXB

My simple approach: Create the XML using bottom up approach, once you know how the XML representation is, things can be easy. Let’s say we want to process a email list and take some actions.

&lt;items&gt;
	&lt;item&gt;
		&lt;firstname&gt;George&lt;/firstname&gt;
		&lt;lastname&gt;Cross&lt;/lastname&gt;
		&lt;email&gt;George.Cross@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
	&lt;item&gt;
		&lt;firstname&gt;Lisa&lt;/firstname&gt;
		&lt;lastname&gt;Monroe&lt;/lastname&gt;
		&lt;email&gt;Lisa.Monroe@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
	&lt;item&gt;
		&lt;firstname&gt;Udy&lt;/firstname&gt;
		&lt;lastname&gt;Udy&lt;/lastname&gt;
		&lt;email&gt;Udy@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
	&lt;item&gt;
		&lt;firstname&gt;Nitha&lt;/firstname&gt;
		&lt;lastname&gt;Udy&lt;/lastname&gt;
		&lt;email&gt;Nitha.Udy@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
	&lt;item&gt;
		&lt;firstname&gt;Balaji&lt;/firstname&gt;
		&lt;lastname&gt;Krishna&lt;/lastname&gt;
		&lt;email&gt;Balaji.Krishna@somedomain.com&lt;/email&gt;
	&lt;/item&gt;
&lt;/items&gt;

Once you know the data, you can submit it to some online tools to generate XML schema.  The one that’s cool and fast is

http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx

For the above above XML the following XSD schema is generated

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot;?&gt;
&lt;xsd:schema attributeFormDefault=&quot;unqualified&quot;
	elementFormDefault=&quot;qualified&quot; version=&quot;1.0&quot;
	xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;

	&lt;xsd:element name=&quot;items&quot; type=&quot;itemsType&quot; /&gt;
	&lt;xsd:complexType name=&quot;itemsType&quot;&gt;
		&lt;xsd:sequence&gt;
			&lt;xsd:element maxOccurs=&quot;unbounded&quot; name=&quot;item&quot; type=&quot;itemType&quot; /&gt;
		&lt;/xsd:sequence&gt;
	&lt;/xsd:complexType&gt;
	&lt;xsd:complexType name=&quot;itemType&quot;&gt;
		&lt;xsd:sequence&gt;
			&lt;xsd:element name=&quot;firstname&quot; type=&quot;xsd:string&quot; /&gt;
			&lt;xsd:element name=&quot;lastname&quot; type=&quot;xsd:string&quot; /&gt;
			&lt;xsd:element name=&quot;email&quot; type=&quot;xsd:string&quot; /&gt;
		&lt;/xsd:sequence&gt;
	&lt;/xsd:complexType&gt;

&lt;/xsd:schema&gt;

AFter the schema definition is generated, JAXB plugin can be bought into action to generate code.

Install the JAXB plugin for eclipse from https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html (looks like this plug-in is no longer supported).  I recommend you try it from http://sourceforge.net/projects/jaxb-builder/

Ccreate a XSD file under a eclipse project, and generate code using JAXB (the above URL should show you how to do so).  Make sure you choose the right package names and folder to put the code in.  The package name given here will be used later, I chose “org.onesun.blog.jaxb” as the package name, and chose “src” folder as the destination to generate JAXB classes.  The following source files should now be generated:

ItemsType.java, ItemType.java and ObjectFactory.java

I personally prefer writing an accessor to work the elements generated.  This way working with your email list becomes easy.   Lets examine the EmailListManager.java

While creating JAXB context, just make sure that the package name generated above is the one used, failing which, the application will fail during runtime.  The purpose of this class is just to load the file and unmarshall it, after which you can process the list and take some concrete actions.  Lets discuss about that in another post (say for instance using JavaMail to send HTML email to this users).

EmailListManager.java

package org.onesun.blog;

import java.io.InputStream;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.onesun.blog.jaxb.*;

public class EmailListManager {
	private ItemsType items = null;
	private JAXBContext jaxbContext = null;
	private Unmarshaller unmarshaller = null;

	public EmailListManager(String packageName) {
		try {
			jaxbContext = JAXBContext.newInstance(packageName);
			unmarshaller = jaxbContext.createUnmarshaller();
		} catch (JAXBException e) {
		}
	}

	@SuppressWarnings(&quot;unchecked&quot;)
	public List loadXML(InputStream istrm) {
		try {
			Object o = unmarshaller.unmarshal(istrm);
			if (items == null) {
				items = (ItemsType) (((JAXBElement) o).getValue());
				return (items.getItem());
			}
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}
}

Finally the application can be validated with the xml document used for generating XSD, which will parse through the list of items and print them to stdout.
Main.java

package org.onesun.blog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.onesun.blog.jaxb.*;

public class Main {
	public static void main(String[] args) {
		EmailListManager xmgr = new EmailListManager(&quot;org.onesun.blog.jaxb&quot;);
		File file = new File(&quot;etc/data.xml&quot;);
		List rtList = new ArrayList();
		try {
			FileInputStream fis = new FileInputStream(file);

			if(fis == null) {
				return;
			}
			rtList = xmgr.loadXML(fis);
			Iterator rtItr = rtList.iterator();
			while (rtItr.hasNext()) {
				ItemType item = (ItemType) rtItr.next();
				System.out.println(&quot;First Name = &quot; + item.getFirstname().trim()
						+ &quot;ttLast Name = &quot; + item.getLastname().trim()
						+ &quot;ttEmail = &quot; + item.getEmail().trim());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

With this you’re set to use XML you generated for anything you like to do.  Hope this was helpful to you in some way, and believe that you enjoyed the simplicity of it


1 Comment

5 Minutes on Adobe Flex – sending XML from Flex to Servlet

Many developers have asked how to take XML, Images and other objects and send it to Servlets … I did some research on the web, it seemed like many wanted to do so, but there were some or the other glitches, and here is an overview on how it can be done …

My use case was to get images for URLs given and save them locally, after a struggle and have a learning curve with Flex, here is what I did, hope this will be useful to others as well.

I found this to be easy, exciting to learn and cool to send a bulk of Images from anywhere to a common store.

The crack to do so is as follows … if there are better ways, please feel free to share with me.
How to use?

loadImage(&quot;http://imagecache2.allposters.com/images/pic/ADVG/741~Donald-Duck-Posters.jpg&quot;);
// Snippet to get URL as Bitmap
private var _bitmapData:BitmapData;
private var _urlLoader:URLLoader = new URLLoader();
public function loadImage(urlString:String):void
{
if(urlString != null)
{
_urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
_urlLoader.load(new URLRequest(urlString));
_urlLoader.addEventListener(Event.COMPLETE, completeHandler);
}
}
private function completeHandler(event:Event):void
{
var imageData:ByteArray = URLLoader(event.target).data;
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
loader.loadBytes(imageData);
}
private function loaderCompleteHandler(event:Event):void
{
_bitmapData = Bitmap(event.target.content).bitmapData;
}

There was a need to turn the image to JPEG Encoded bytes and save as XML, here is what I did …

// Snippet to Save JPEG Bytes as XML
private function onSave():void
{
var fileToSave:File = File.documentsDirectory;
try
{
fileToSave.browseForSave(“Save Image as XML”);
fileToSave.addEventListener(Event.SELECT, fileSelectedForSave);
}
catch (error:Error)
{
trace(“Failed:”, error.message);
}
}

private function fileSelectedForSave(event:Event):void
{
var selectedFile:File = (event.target as File);
var xmlData:XML = new XML(“<EncodedJPEGBytes>” +bitmapToString(_bitmapData) + “</EncodedJPEGBytes>”);
var xmlStr:String = “<?xml version=”1.0″ encoding=”UTF-8″?>”
+ xmlData.toXMLString();
var fs:FileStream = new FileStream();
fs.open(selectedFile, FileMode.WRITE);
fs.writeUTFBytes(xmlStr);
fs.close();
}

private function bitmapToString(bitmapData:BitmapData):String
{
var encodedJPEG:JPEGEncoder = new JPEGEncoder(100);
var baJPEG:ByteArray = encodedJPEG.encode(bitmapData);
var be:Base64Encoder = new Base64Encoder();
be.encodeBytes(baJPEG);
var jpegToString:String = be.flush();
return(jpegToString);
}

Once the file is saved locally as encoded XML String, this can be sent over to a Servlet for processing, this can further be used for something else …

// Snippet upload XML to Servlet
private function onUpload():void
{
var fileToSave:File = File.documentsDirectory;
var xmlFilter:FileFilter = new FileFilter("Select an XML file", "*.xml");
try
{
fileToSave.browseForOpen("Upload JPEG Bytes to Server", [xmlFilter]);
fileToSave.addEventListener(Event.SELECT, doFileUpload);
}
catch (error:Error)
{
trace("Failed:", error.message);
}
}
private function doFileUpload(event:Event):void
{
var selectedFile:File = (event.target as File);
var uploadReq:URLRequest = new URLRequest("http://localhost:8080/JpegXML/FileUploadServlet");
uploadReq.method = "POST";
selectedFile.upload(uploadReq);
}

Now the interesting part … how to receive this data in Servlet?  Here is a code snippet that will help you understand how it can be done.

	public static void uploader(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String imgStoreDir = ServletPreferences.getImageStoragePath() + File.separator + UUID.randomUUID().toString();
		Utility.createNonExistantDirs(imgStoreDir);

		try
		{
			FileItemFactory fileItemFactory = new DiskFileItemFactory();
			ServletFileUpload uploadServlet = new ServletFileUpload(fileItemFactory);

			List<FileItem> fileItems = uploadServlet.parseRequest(request);
			Iterator<FileItem> fileIterator = fileItems.iterator();

			while(fileIterator.hasNext())
			{
				FileItem fileItem = (FileItem)fileIterator.next();

				if(!fileItem.isFormField()) {
					File filePathName = new File(imgStoreDir + File.separator + fileItem.getName());
					logger.debug("uploader: fileStorageDir = " + filePathName.getAbsolutePath());
					fileItem.write(filePathName);

					Utility.extractJPEG(filePathName, fileItem.getName());
				}
			}

			fileItemFactory = null;
			uploadServlet = null;
		}
		catch( Exception e ) {
			logger.error("uploader: Exception during UPLOAD: " + e.getMessage());
		}

		FileUtils.deleteDirectory(new File(imgStoreDir));
	}

After receiving the Images on the servlet, one can parse and decode the file using Base64Decoder, then use JPEGDecoder to decode the bytes to images … I’m still writing this up, I’ll update the blog once that’s done!