Saturday, July 28, 2012

Servlet File Upload

Hi,

html
-----
    <form action="UploadForm" enctype="multipart/form-data" method="POST">
            <input type="file" name="file1"><br>
            <input type="Submit" value="Upload File"><br>
        </form>
web.xml
--------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <servlet-name>UploadForm</servlet-name>
        <servlet-class>UploadFormServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadForm</servlet-name>
        <url-pattern>/UploadForm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


servlet
------

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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFormServlet extends HttpServlet {

    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "/files";
    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(realPath);
        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);
        }

    }
}

Jars Needed

http://mirrors.ibiblio.org/pub/mirrors/maven2/org/apache/commons/commons-io/1.3.2/commons-io-1.3.2.jar

http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-fileupload/commons-fileupload/1.2.1/commons-fileupload-1.2.1.jar

 


Thanks

Rajesh   Kumar Yuvaraj





Friday, July 27, 2012

use of identityHashCode() of System class

Hi,
    As we know that we can override the hashCode() method of Object class with our own representation,What if i want to get the original hashCode() of a specific object. For that jdk provides a method inside of System class. Please go through the following example.


public class HashCodeDemo {

    @Override
    public int hashCode() {
        return 20;
    }

    public static void main(String ar[]) {

        HashCodeDemo hashObj = new HashCodeDemo();
        System.out.println(hashObj);
        System.out.println(hashObj.toString());
        System.out.println(hashObj.hashCode());
        System.out.println(System.identityHashCode(hashObj));

    }
}

OutPut
--------
javaapplications.HashCodeDemo@14
javaapplications.HashCodeDemo@14
20
4072869


Thanks

Rajesh Kumar Yuvaraj

Thursday, July 26, 2012

usage of Map.Entry interface in java collections


Hi,

    
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
// TODO code application logic here
// Create a hash map
        HashMap hm = new HashMap();
// Put elements to the map
        hm.put("John Doe", new Double(3434.34));
        hm.put("Tom Smith", new Double(123.22));
        hm.put("Jane Baker", new Double(1378.00));
        hm.put("Todd Hall", new Double(99.22));
        hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
        Set set = hm.entrySet();
// Get an iterator
        Iterator i = set.iterator();
// Display elements
        while (i.hasNext()) {
            Map.Entry me = (Map.Entry) i.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        System.out.println();
// Deposit 1000 into John Doe's account
        double balance = ((Double) hm.get("John Doe")).doubleValue();
        hm.put("John Doe", new Double(balance + 1000));
        System.out.println("John Doe's new balance: "
                + hm.get("John Doe"));
    }
}


Friday, July 13, 2012

what is SQLite ?

                                          SQLite  is a tiny, embedded RDBMS (~275kb) which is used by the most of the local/client storage in  application software such as web browsers.Simply its a embedded data base for web browsers.
Ex.  Mozilla stores the cookies information inside a cookie.sqlite  file in the location C:\Users\Mypc\AppData\Roaming\Mozilla\Firefox\Profiles\gwj7th6j.default.
 This file is encrypted internally.We can explore this data base using a firefox plug in called SQLite.

https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

Thanks,

Rajesh Kumar Yuvaraj