Capture picture on Webpage with Java Backend

In most of the projects we try to capture user’s face on web page. Till recently many projects have been implementing this using either Activex objects or Using Java Plugin’s or some other media plugin’s. With advent of flash and it’s related technologies this and it’s increase in presence over the web flash has become favorite technology to build such application.  Thus making it browser agnostic as compared to ActiveX Objects.

There is a project on web named JPEGCam which is free and opensource which has capability to do that.

http://code.google.com/p/jpegcam/

My effort is to create a java backend to it’s frontend ( Default one comes with php backend). Following example explains my effort

I have created a mavenized application to make it run without any extra server deployment. Here is the description

I’ve created a simple servlet which just capture’s input stream

Stores data in a folder named uploads

Send the file url back to Client to display

Here is the code

package com.linkwithweb.jpegcam;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Ashwin Kumar
 * Servlet implementation class PictureCaptureServlet
 */
public class PictureCaptureServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String fileStoreURL = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PictureCaptureServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		fileStoreURL = config.getServletContext().getRealPath("") + "/uploads";
		try {
			File f = new File(fileStoreURL);
			if (!f.exists()) {
				f.mkdirs();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			long time = new Date().getTime();
			
			FileOutputStream fileOutputStream = new FileOutputStream(
					fileStoreURL + "/"+time+".jpg");
			int res;
			while ((res = request.getInputStream().read()) != -1) {
				fileOutputStream.write(res);
			}
			fileOutputStream.close();
			/**
			 * To make sure each url is differeent and not cached added time to tit
			 */
			response.getWriter().append(
					"http://localhost:8080/uploads/" + time
							+ ".jpg");

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

		}
	}

}

Below is sample javascript which handles frontend

	<!-- First, include the JPEGCam JavaScript Library -->
	<script type="text/javascript" src="webcam.js"></script>
	
	<!-- Configure a few settings -->
	<script language="JavaScript">
		webcam.set_api_url( '/capture' );
		webcam.set_quality( 90 ); // JPEG quality (1 - 100)
		webcam.set_shutter_sound( true ); // play shutter click sound
	</script>
	
	<!-- Next, write the movie to the page at 320x240 -->
	<script language="JavaScript">
		document.write( webcam.get_html(320, 240) );
	</script>
	<!-- Code to handle the server response (see test.php) -->
	<script language="JavaScript">
		webcam.set_hook( 'onComplete', 'my_completion_handler' );
		
		function take_snapshot() {
			// take snapshot and upload to server
			document.getElementById('upload_results').innerHTML = '<h1>Uploading...</h1>';
			webcam.snap();
		}
		
		function my_completion_handler(msg) {
			// extract URL out of PHP output
			if (msg.match(/(http\:\/\/\S+)/)) {
				var image_url = RegExp.$1;
				// show JPEG image in page
				document.getElementById('upload_results').innerHTML = 
					'<h1>Upload Successful!</h1>' + 
					'<h3>JPEG URL: ' + image_url + '</h3>' + 
					'<img src="' + image_url + '">';
				
				// reset camera for another shot
				webcam.reset();
			}
			else alert("Java Error: " + msg);
		}
	</script>

Now let me paste my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.linkwithweb.browsercam</groupId>
	<artifactId>JPEGCamIntegration</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>JPEGCamIntegration Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>JPEGCamIntegration</finalName>
		<plugins>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>8.0.0.M2</version>
				<configuration>
					<scanIntervalSeconds>3</scanIntervalSeconds>
				</configuration>
			</plugin>

			<!-- Facilitates downloading source and javadoc in Eclipse -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.8</version>
				<configuration>
					<wtpversion>2.0</wtpversion>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>


			<!-- Ensures we are compiling at 1.6 level -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Here is how you run this and test

mvn jetty:run-exploded

and click this URL

http://localhost:8080

Code has been checked in to following location

http://code.google.com/p/linkwithweb/source/browse/trunk/Utilities/JPEGCamIntegration.rar

SWFUpload and Java Servlet Example

I have been trying to find out one good upload client over the web and it really took 3 days to me to nail down one which one best.

SWFUpload seems to be best library available as of today. I dont see they implementing java examples. Here is my attempt provide a java sample for it

This example will implement basic file upload with cancel and manual upload trigger functionality with servlet in backend

Here is sample client code

		

var swfu;

window.onload = function() {
	var settings = {
		flash_url : "swfupload/swfupload.swf",
		upload_url: "Upload",
		file_size_limit : "100 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 100,
		file_queue_limit : 0,
		custom_settings : {
			progressTarget : "fsUploadProgress",
			cancelButtonId : "btnCancel"
		},
		debug: false,

		// Button settings
		button_image_url: "swfupload/TestImageNoText_65x29.png",
		button_width: "95",
		button_height: "29",
		button_placeholder_id: "spanButtonPlaceHolder",
		button_text: 'Browse Files',
		button_text_style: ".theFont { font-size: 22; }",
		button_text_left_padding: 2,
		button_text_top_padding: 3,
		
		// The event handler functions are defined in handlers.js
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess
	};

	swfu = new SWFUpload(settings);
    };


    function handleUpload(){
     var emailid = document.getElementById("email").value;
   	 swfu.setPostParams({ email:emailid });
   	 //swfu.setUploadURL("CommonsFileUploadServlet?test=234");
   	 swfu.startUpload();
 }

Here is sample screenshot

SWFUploadExample

Try downloading code from SVN from follwong location

https://linkwithweb.googlecode.com/svn/trunk/Utilities/FlashFileUpload

Make sure you have maven installed on machine before executing the below command
After downloading just run “mvn jetty:run”

and open this URL to test http://localhost:8080/FileUpload/

File Upload in J2ee / Servlet

Lots of people try to find some good working examples for file upload in J2ee but i rarely find any working example which can be run immedialty after downloading. Here is my Effort to create one such example which uses maven as build/test environment

/**
 * 
 */
package com.northalley.upload;

/**
 * @author ashwin kumar
 *
 */
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @author ashwin kumar
 * 
 */
public class CommonsFileUploadServlet extends HttpServlet {
	private static final String TMP_DIR_PATH = "c:\\test";
	private File tmpDir;
	private static final String DESTINATION_DIR_PATH = "c:\\test";
	private File destinationDir;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if (!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}
		//String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(DESTINATION_DIR_PATH);
		if (!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH
					+ " is not a directory");
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/plain");
		out
				.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
		out.println();

		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		/*
		 * Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above
		 * threshold.
		 */
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				/*
				 * Handle Form Fields.
				 */
				if (item.isFormField()) {
					out.println("File Name = " + item.getFieldName()
							+ ", Value = " + item.getString());
				} else {
					// Handle Uploaded files.
					out.println("Field Name = " + item.getFieldName()
							+ ", File Name = " + item.getName()
							+ ", Content type = " + item.getContentType()
							+ ", File Size = " + item.getSize());
					/*
					 * Write file to the ultimate location.
					 */
					File file = new File(destinationDir, item.getName());
					item.write(file);
				}
				out.close();
			}
		} catch (FileUploadException ex) {
			log("Error encountered while parsing the request", ex);
		} catch (Exception ex) {
			log("Error encountered while uploading file", ex);
		}

	}

}


You can download code from
SVN Link for working code

Click Framework

Recently i was looking at some framework which can be of help to me in Java Web World that can create UI dynamically using component driven architecture. Most of the projects these days are Metadata Driven. When we talk about metadata driven UI we need some component like framework where we can map metadata to some component. I had work on heavyweights like JSF but i dont think it gives whole lots of control to user to do what ever a developer wants that easily. Then i have come across this wonderful click framework.

We started building an application (Around september 2008) using this framework to one of our client where we define just some metadata and while website is built dynamically. Click framework made that possible. And i’m really happy to see that click has now be incorporated into apache.

Three cheers to click.