Spring MVC with Annotations , JPA , Derby , Fileupload, SWFUpload CRUD Example

This is my attempt to create a clear tutorial on Spring MVC CRUD using JPA and Derby and a sample FileUpload with SWFUpload

I have tried to use standard file structure and naming patterns so that it will be useful in proceeding further on this base

First of all To create any Spring Application we need to configure DispatcherServlet in Servlet in Web.xml of Application so that all SpringMVC related requests goto to that servlet

Here is sample code snippet of web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Use this definition if using a Java EE 6 container This also stops Eclipse
	from complaining that 3.0 is not a valid version <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
	http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

	<!-- The definition of the Root Spring Container shared by all Servlets
		and Filters -->

	<!-- Creates the Spring Container shared by all Servlets and Filters -->

	<!-- Processes application requests -->



Now that we have defined DispatcherServlet in Web.xml, let me define each file and its usage so that you can download and change what ever us required for you

│ web.xml : Servlet Configuration Defined Here

│ │ db.xml : DB related Beans Configured Here
│ │ root-context.xml
│ │
│ └───app
│ controllers.xml : Contrller Configuration defined here. We are using annotation so we just tell spring that use annotation handler to indefiy files
I also added a multipart resolver to handle multipart request here.
│ servlet-context.xml: Core Spring MVC Configuration file which is root file where spring MVC reads. I defined resources/view resolver/validator/and controller here

│ edit.jsp : Sample page to show edit functionaly
│ home.jsp : Welcome Page
│ list.jsp : List records page
│ upload.jsp : Simple Upload Functionality using SWFUpload is defined here


│ │
│ ├───resources
│ │ │ db.properties : DB connectivity Properties to connect
│ │ │ log4j.xml : Logiing related xml
│ │ │
│ │ └───META-INF
│ │ persistence.xml : JPA Configuration file
│ │

Here is code of my File Upload Controller

package com.linkwithweb.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.linkwithweb.spring.model.UploadBean;

 * @author Ashwin Kumar

public class UploadController {

	public UploadController() {

	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute("uploadbean", new UploadBean());
		return "forms/upload";

	@RequestMapping(method = RequestMethod.POST)
	public String Uploadcreate(UploadBean uploadbean, BindingResult result) {
		System.out.println("started uploading");
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error in uploading: " + error.getCode()
						+ " - " + error.getDefaultMessage());
			return "forms/upload";

		// Some type of file processing...

		System.err.println("Test uploading file: "
				+ uploadbean.getFiledata().getOriginalFilename());
		System.err.println("-------------------------------------------");		return "forms/success";

Note: You have define Multipart resolver bean of commons file upload inorder to parse file upload requests

	<bean id="multipartResolver"
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="100000" />

Code can be found at following SVN location

Once downloaded run ” mvn jetty:run” to test the application at follwoing URL



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 });

Here is sample screenshot


Try downloading code from SVN from follwong location


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 {
		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();
				.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");

		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.

		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());
		} 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

Find Codec of Media File Programatically

Recently while working in some Media related project i had a task of finding which media i’m working on. I mean to find out if my player supports running that media. For that i need to work on a solution which can find a media type by reading file headers etc…

I have been shuffling between GSpot Codec Library / VLC / Mediainfo but i found out that Mediainfo is more Developer Friendly and can be easily Integrated into the application

Here is sample code which read details about media

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using MediaInfoLib;

 * Ashwin Kumar
 * 4/12/2011
 * ashwin.rayaprolu@gmail.com
 * Sample Command Line program to read and display Media type
 * Usage MediaInfoRead 
 * */
namespace MediaInfoRead
    class MediaInfoRead
        public static void Main(string[] args)
            String ToDisplay = "";
            MediaInfo MI = new MediaInfo();
            //An example of how to use the library
            ToDisplay += "\r\n\r\nOpen\r\n";

            ToDisplay += "\r\n\r\nInform with Complete=false\r\n";
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nInform with Complete=true\r\n";
            MI.Option("Complete", "1");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nCustom Inform\r\n";
            MI.Option("Inform", "General;File size is %FileSize% bytes");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='FileSize'\r\n";
            ToDisplay += MI.Get(0, 0, "FileSize");

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter=46\r\n";
            ToDisplay += MI.Get(0, 0, 46);

            ToDisplay += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n";
            ToDisplay += MI.Count_Get(StreamKind.Audio);

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n";
            ToDisplay += MI.Get(StreamKind.General, 0, "AudioCount");

            ToDisplay += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n";
            ToDisplay += MI.Get(StreamKind.Audio, 0, "StreamCount");

            ToDisplay += "\r\n\r\nClose\r\n";


You Can checkout Sample C# project from following SVN location


xCmd an Alternative to PsExec

I recently had to use PsExec for one of my project and it had to integrated into program. I mean invocation of PsExec had to be done from a coding language. Then i faced problem of application getting hanged. To verify my code i did call PsExec from Java, Csharp, VB.net. None of them worked and program hanged on calling PSExec.

There is a problem with PsExec OutputStream when it is called from a programming language. None of the versions of PsExec looked good with this bug. So i had tpo find out an alternative,  Here is one good tool named XCmd by “Zoltan Csizmadia

Execute Applications on Remote Systems

  • Overview

This program allows you to execute applications on remote systems without installing any client software. You can start a command prompt or just execute a command or exe  on a remote machine. The only restriction is you must be an administrator 😦

Everybody knows the cool tools from Sysinternals (www.sysinternals.com). One of my favorites are PSEXEC, PSKILL and PSLIST,… 🙂
I was always wonder how they could query every kind of information or execute commands on a remote machine without installing any client software.


  • With this program you can run as many remote commands on the remote machine as you want.  (PSEXEC supports only one remote command on the remote machine at the same time)
  • You can execute internal commands (dir,..) directly.
    xCmd.exe \\remote dir
  • You can start a light “telnet” connection with a remote machine without any telnet server
    xCmd.exe \\remote cmd


xCmd v1.0 for NT4/2000 – executes commands remotely
Freeware! 2001 Zoltan Csizmadia, zoltan_csizmadia@yahoo.com

Usage: xCmd.exe \\computer [options] command/exe arguments

/D:directory         Set working directory
Default: Remote “%SystemRoot%\System32”
/IDLE                Idle priority class
/NORMAL              Normal priority class
/HIGH                High priority class
/REALTIME            Realtime priority class
/C                   Copy the specified program to the remote machine’s
“%SystemRoot%\System32” directory
Commands’s exe file must be absolute to local machine
/USER:user           User for remote connection
/PWD:{password|*}    Password for remote connection
/NOWAIT              Don’t wait for remote process to terminate

xCmd.exe \\remote cmd
xCmd.exe \\remote /user:administrator dir c:\ 
xCmd.exe \\remote /user:somebody /pwd:* /d:d:\ test1.exe /p1 /p2
xCmd.exe \\remote /c /user:somebody /pwd:* /d:d:\ test2.exe /whatever

– Input is passed to remote machine when you press the ENTER.
– Ctrl-C terminates the remote process
– Command and file path arguments have to be absolute to remote machine
If you are using /c option, command exe file path must be absolute to
local machine, but the arguments must be absolute to remote machine

How does it work?

  1. The xCmd.exe is console application and when you start it, the program will extract a xCmdSvc.exe from its resources.
  2. xCmd.exe creates a service on the remote machine (that’s the reason, you must be an administrator
  3. xCmd.exe starts the remote service (#2)
  4. xCmd.exe and xCmdSvc.exe will communicate via named pipes
  5. xCmd.exe send a packet to the service what to execute
  6. xCmdSvc.exe starts the command and redirect stdout, stderr, stdin to 3 named pipes.
  7. xCmd.exe listens these 3 named pipes (#6), redirect them to its stdout, stderr, stdin

I have downloaded his code and converted to Visual Studio 2008 Solution and fixed a small bug which comes with iostream.h inclusion in new version of C++.

Here is the link to original Article which i copied


And here is modified C++ Solution which gets compiled in Visual Studio. Checkout from svn


Call Executable from C# Program

I had a requirement where in i should call an executable to find out all files that are getting modified/created while in run my application. I had to work on windows so chose to write a program in Dotnet which does that.

Here is the sample code which does that

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace MediaController.Controller
    class MediaController

        static void Main()

        public void execBasicCommand(string command)
            // Setup the process with the ProcessStartInfo class.
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:\development\Ashwin\Streaming\FindModified\DirectoryChangeListener.exe"; // Specify exe name.
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            // Start the process.
            using (Process process = Process.Start(start))
                // Read in all the text from the process with the StreamReader.
                using (StreamReader reader = process.StandardOutput)
                    string result = reader.ReadToEnd();

        public static void execCommand(string command)
                Process process = new Process();
                ProcessStartInfo start = new ProcessStartInfo();
                // Set up process to redirect standard output and standard error to
                // a file.
                //process.StartInfo.FileName = @"C:\development\Ashwin\Streaming\FindModified\DirectoryChangeListener.exe"; ;
                process.StartInfo.FileName = command;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                //FileInfo ofi = new FileInfo("test.txt");
                //FileStream ofs = ofi.OpenWrite();
                //StreamWriter sw = new StreamWriter(ofs);
                WriteToTextWriterEventHandler wtsweh = new WriteToTextWriterEventHandler();
                DataReceivedEventHandler handler = wtsweh.HandleDataReceived;
                process.OutputDataReceived += handler;
                process.ErrorDataReceived += handler;

                int processExitCode = process.ExitCode;
            catch (Exception e)

        private class WriteToTextWriterEventHandler
            private TextWriter tw;

            public WriteToTextWriterEventHandler(TextWriter tw)
                this.tw = tw;

            public WriteToTextWriterEventHandler()
                //this.tw = tw;

            public void HandleDataReceived(object sendingProcess,
               DataReceivedEventArgs outLine)
                // Collect the sort command output.
                if (!String.IsNullOrEmpty(outLine.Data))
                    //tw.Write(Environment.NewLine + outLine.Data);

        /// Executes a shell command synchronously.
        /// string command
        /// string, as output of the command.
        public void ExecuteCommandSync(object command)
                // create the ProcessStartInfo using "cmd" as the program to be run,
                // and "/c " as the parameters.
                // Incidentally, /c tells cmd that we want it to execute the command that follows,
                // and then exit.
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                // Get the output into a string
                string result = proc.StandardOutput.ReadToEnd();
                // Display the command output.
            catch (Exception objException)
                // Log the exception

        /// Execute the command Asynchronously.
        /// string command.
        public void ExecuteCommandAsync(string command)
                //Asynchronously start the Thread to process the Execute command request.
                Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
                //Make the thread as background thread.
                objThread.IsBackground = true;
                //Set the Priority of the thread.
                objThread.Priority = ThreadPriority.AboveNormal;
                //Start the thread.
            catch (ThreadStartException objException)
                // Log the exception
            catch (ThreadAbortException objException)
                // Log the exception
            catch (Exception objException)
                // Log the exception


Build Flowplayer From Source

There is no direct Link which gives proper instructions on how to build flowplayer. Here is my effort to build one

First goto flowplayer website and download source .Below is instruction

Once downloaded extract it to a folder

Rather than from website you can also get flowplayer-core source from


Now in folder above checkout following code base


Flowplayer build is dependent on the above plugins you download

now goto to flowplayer you downloaded from website and open build.properties

Make sure you update you flex installation Directory

# you need to adjust following to point to your Flex SDK


# change following to point to .exe files when running on Windows

mxmlc_bin= ${flex3bindir}/mxmlc.exe

compc_bin= ${flex3bindir}/compc.exe

asdoc_bin= ${flex3bindir}/asdoc.exe

Now Make sure you update the path for all plugins

plugin.buildfiles=bwcheck/build.xml,controls/build.xml,controls/build-air.xml,controls/build-tube.xml,controls/build-skinless.xml, \

for plugins that can be built inside the player

plugin-classes=${plugins.dir}controls/trunk/src/actionscript ${plugins.dir}content/trunk/src/actionscript  \
  ${plugins.dir}akamai/trunk/src/actionscript ${plugins.dir}rtmp/trunk/src/actionscript ${plugins.dir}pseudostreaming/trunk/src/actionscript \
  ${plugins.dir}audio/trunk/src/actionscript ${plugins.dir}bwcheck/trunk/src/actionscript ${plugins.dir}cluster/trunk/src/actionscript \
  ${plugins.dir}captions/trunk/src/actionscript ${plugins.dir}securestreaming/trunk/src/actionscript ${plugins.dir}smil/trunk/src/actionscript \

plugin-swc=${plugins.dir}controls/trunk/src/flash ${plugins.dir}content/trunk/src/flash ${plugins.dir}/viralvideos/trunk/src/flash ${plugins.dir}/pseudostreaming/trunk/libcontrols-dir=${plugins.dir}controls/trunk

Once configuration is updated you just goto to the directory where you unzipped downloaded flowplayer and then type “ant”

It Will automatically build all stuff for you

Make sure you have following in your machine before you build

ANT: http://ant.apache.org/bindownload.cgi

Flex SDK: http://opensource.adobe.com/wiki/display/flexsdk/

Next tutorial is on adding our custom component to flowplayer……………………..