Example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest.

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.zjl.oa.fckeditor.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*from  w  ww  .ja v a  2  s. com*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            //??
            upload.setHeaderEncoding("UTF-8");
            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                //???
                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.ephesoft.gxt.admin.server.ImportIndexFieldUploadServlet.java

/**
 * This API is used to process uploaded file and unzip file in export-batch-folder .
 * //from   w  w w  .  java 2 s . c  o m
 * @param upload {@link ServletFileUpload} uploaded file.
 * @param req {@link HttpServletRequest}.
 * @param printWriter {@link PrintWriter}.
 * @param parentDirPath {@link String} to create absolute unzip directory path.
 * @return {@link File} temporary file after unzip.
 */
private String processUploadedFile(final ServletFileUpload upload, final HttpServletRequest req,
        final PrintWriter printWriter, final String parentDirPath) {
    String tempUnZipDir = "";
    String zipFileName = "";
    String zipPathname = "";
    File tempZipFile = null;
    List<FileItem> items;

    try {
        items = upload.parseRequest(req);
        for (final FileItem item : items) {

            if (!item.isFormField()) {// && "importFile".equals(item.getFieldName())) {
                zipPathname = getZipPath(item, parentDirPath);

                zipFileName = getZipFileName(item);

                tempZipFile = copyItemContentInFile(item, zipPathname, printWriter);

            }
        }
    } catch (final FileUploadException e) {
        printWriter.write("Unable to read the form contents.Please try again.");
    }

    tempUnZipDir = parentDirPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.'))
            + System.nanoTime();

    try {
        FileUtils.unzip(tempZipFile, tempUnZipDir);
        if (!FileUtils.isDirectoryHasAllValidExtensionFiles(tempUnZipDir, SERIALIZATION_EXT)) {
            FileUtils.deleteQuietly(tempZipFile);
            FileUtils.deleteDirectoryAndContentsRecursive(new File(tempUnZipDir), true);
            tempUnZipDir = "";
            log.error("Invalid zip file.");
            //throw new Exception();
        }
    } catch (final Exception e) {
        printWriter.write("Unable to unzip the file.Please try again.");
        tempZipFile.delete();
    }
    return tempUnZipDir;
}

From source file:hudson.PluginManager.java

/**
 * Uploads a plugin./*from   w w w . ja va 2s .com*/
 */
public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException {
    try {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);

        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

        // Parse the request
        FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);
        String fileName = Util.getFileName(fileItem.getName());
        if (!fileName.endsWith(".hpi"))
            throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName));
        fileItem.write(new File(rootDir, fileName));
        fileItem.delete();

        pluginUploaded = true;

        return new HttpRedirect(".");
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {// grrr. fileItem.write throws this
        throw new ServletException(e);
    }
}

From source file:com.jl.common.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*  w ww . j a  v  a2 s  .c  o m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");//

            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;//

                //
                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                }

                //
                else if (uplFile.getSize() > 50 * 1024) {
                    //
                    ur = new UploadResponse(204);
                }
                // 
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }
    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.laijie.fckeditor.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from   w  w w.  j  a  va2  s  .c  om
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            //
            upload.setHeaderEncoding("UTF-8");
            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                //
                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.aplos.core.listeners.MultipartRequest.java

@SuppressWarnings("unchecked")
private void parseRequest(HttpServletRequest request, ServletFileUpload servletFileUpload) throws IOException {
    try {/*  w  w w.ja  v  a  2  s.  c o  m*/
        AplosRequestContext aplosRequestContext = (AplosRequestContext) request
                .getAttribute(AplosScopedBindings.APLOS_REQUEST_CONTEXT);
        if (!(aplosRequestContext != null && aplosRequestContext.getDynamicViewEl() != null
                && !aplosRequestContext.isDynamicViewProcessed())) {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);

            for (FileItem item : fileItems) {
                if (item.isFormField()) {
                    addFormParam(item);
                } else {
                    addFileParam(item);
                }
            }
        }
    } catch (FileUploadException e) {
        logger.severe("Error in parsing fileupload request");

        throw new IOException(e.getMessage());
    }
}

From source file:com.google.zxing.web.DecodeServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        log.info("File upload was not multipart");
        response.sendRedirect("badimage.jspx");
        return;/*from  www.  j a  v a 2s.co m*/
    }

    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
    upload.setFileSizeMax(MAX_IMAGE_SIZE);

    // Parse the request
    try {
        for (FileItem item : upload.parseRequest(request)) {
            if (!item.isFormField()) {
                if (item.getSize() <= MAX_IMAGE_SIZE) {
                    log.info("Decoding uploaded file");
                    try (InputStream is = item.getInputStream()) {
                        processStream(is, request, response);
                    }
                } else {
                    log.info("Too large");
                    response.sendRedirect("badimage.jspx");
                }
                break;
            }
        }
    } catch (FileUploadException fue) {
        log.info(fue.toString());
        response.sendRedirect("badimage.jspx");
    }

}

From source file:com.bruce.gogo.utils.JakartaMultiPartRequest.java

/**
 * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
 * multipart classes (see class description).
 *
 * @param saveDir        the directory to save off the file
 * @param servletRequest the request containing the multipart
 * @throws java.io.IOException  is thrown if encoding fails.
 *///from www.j  av  a 2  s .co m
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }

    // Parse the request
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        ProgressListener myProgressListener = new MyProgressListener(servletRequest);
        upload.setProgressListener(myProgressListener);
        List items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (LOG.isDebugEnabled())
                LOG.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                LOG.debug("Item is a normal form field");
                List<String> values;
                if (params.get(item.getFieldName()) != null) {
                    values = params.get(item.getFieldName());
                } else {
                    values = new ArrayList<String>();
                }

                // note: see http://jira.opensymphony.com/browse/WW-633
                // basically, in some cases the charset may be null, so
                // we're just going to try to "other" method (no idea if this
                // will work)
                String charset = servletRequest.getCharacterEncoding();
                if (charset != null) {
                    values.add(item.getString(charset));
                } else {
                    values.add(item.getString());
                }
                params.put(item.getFieldName(), values);
            } else {
                LOG.debug("Item is a file upload");

                // Skip file uploads that don't have a file name - meaning that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (FileUploadException e) {
        LOG.error("Unable to parse request", e);
        errors.add(e.getMessage());
    }
}

From source file:agent_update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w  w. ja va  2s  .  co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession hs = request.getSession();
    PrintWriter out = response.getWriter();

    try {

        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");
            System.out.println(ln.getUId());

            String fn = "";
            String lastn = "";
            String un = "";
            String state = "";
            String city = "";
            String area = "";
            String e = "";
            String ad1 = "";
            String ad2 = "";
            String num = "";
            String p = "";
            String des = "";
            String cmp = "";
            String work = "";
            String agentphoto = "";
            String agentname = "";
            int id = 0;

            // creates FileItem instances which keep their content in a temporary file on disk
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //get the list of all fields from request
            List<FileItem> fields = upload.parseRequest(request);
            // iterates the object of list
            Iterator<FileItem> it = fields.iterator();
            //getting objects one by one
            while (it.hasNext()) {
                //assigning coming object if list to object of FileItem
                FileItem fileItem = it.next();
                //check whether field is form field or not
                boolean isFormField = fileItem.isFormField();

                if (isFormField) {
                    //get the filed name 
                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("fname")) {
                        fn = fileItem.getString();
                    } else if (fieldName.equals("id")) {
                        id = Integer.parseInt(fileItem.getString());
                    } else if (fieldName.equals("lname")) {
                        lastn = fileItem.getString();
                    } else if (fieldName.equals("uname")) {
                        un = fileItem.getString();
                    } else if (fieldName.equals("state")) {
                        state = fileItem.getString();
                    } else if (fieldName.equals("city")) {
                        city = fileItem.getString();
                    } else if (fieldName.equals("area")) {
                        area = fileItem.getString();
                    } else if (fieldName.equals("email")) {
                        e = fileItem.getString();
                    } else if (fieldName.equals("address1")) {
                        ad1 = fileItem.getString();
                    } else if (fieldName.equals("address2")) {
                        ad2 = fileItem.getString();
                    } else if (fieldName.equals("number")) {
                        num = fileItem.getString();

                    } else if (fieldName.equals("pwd")) {
                        p = fileItem.getString();
                    }

                    else if (fieldName.equals("descrip")) {
                        des = fileItem.getString();
                    } else if (fieldName.equals("compname")) {
                        cmp = fileItem.getString();
                    } else if (fieldName.equals("workx")) {
                        work = fileItem.getString();
                    }

                } else {

                    agentphoto = new File(fileItem.getName()).getName();

                    System.out.println(agentphoto);
                    try {

                        // FOR UBUNTU add GETRESOURCE  and GETPATH

                        String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/profilepic/";
                        //                    String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"//";
                        System.out.println("====" + fp);
                        fileItem.write(new File(fp + agentphoto));
                    } catch (Exception ex) {
                        out.println(ex.toString());
                    }

                }

            }
            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();
            //            
            //           String state="";
            //            Criteria cr = ss.createCriteria(StateMaster.class);
            //            cr.add(Restrictions.eq("sId", Integer.parseInt(stateid)));
            //            ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list();
            //            System.out.println("----------"+ar.size());
            //            if(ar.isEmpty()){
            //                
            //            }else{
            //                state = ar.get(0).getSName();
            //                System.out.println("-------"+ar.get(0));
            //            }
            //            
            //            String city="";
            //            Criteria cr2 = ss.createCriteria(CityMaster.class);
            //            cr2.add(Restrictions.eq("cityId", Integer.parseInt(cityid)));
            //            ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>)cr2.list();
            //            System.out.println("----------"+ar2.size());
            //            if(ar2.isEmpty()){
            //                
            //            }else{
            //                city = ar2.get(0).getCityName();
            //                System.out.println("-------"+city);
            //            }
            //            
            //            String area="";
            //            Criteria cr3 = ss.createCriteria(AreaMaster.class);
            //            cr3.add(Restrictions.eq("areaId", Integer.parseInt(areaid)));
            //            ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>)cr3.list();
            //            System.out.println("----------"+ar3.size());
            //            if(ar3.isEmpty()){
            //                
            //            }else{
            //                area = ar3.get(0).getAreaName();
            //                System.out.println("-------"+area);
            //            }
            //            

            //       Criteria crr=ss.createCriteria(AgentDetail.class);
            //       crr.add(Restrictions.eq("uId", ln.getUId()));
            //       ArrayList<AgentDetail> arr=(ArrayList<AgentDetail>)crr.list();
            //       if(arr.isEmpty())
            //       {
            //           out.print("array empty");
            //       }
            //       else
            //       {
            //           AgentDetail agd=arr.get(0);
            AgentDetail agd2 = (AgentDetail) ss.get(AgentDetail.class, id);
            AgentDetail agd = new AgentDetail();

            agd.setUId(agd2.getUId());
            agd.setAId(agd2.getAId());
            agd.setACompanyname(cmp);
            agd.setADescription(des);
            agd.setAEmail(e);
            agd.setAFname(fn);
            agd.setAImg(agentphoto);
            agd.setALname(lastn);
            agd.setANo(num);
            agd.setAWorkx(work);
            agd.setACity(city);
            agd.setAArea(area);
            agd.setAState(state);
            agd.setAAddress1(ad1);
            agd.setAAddress2(ad2);
            agd.setAStatus(null);
            agd.setARating(null);
            agd.setAStatus("Accepted");
            // agd.getUId().setPwd(p);
            // agd.getUId().setUName(un);

            ss.evict(agd2);
            ss.update(agd);
            tr.commit();
            //       }

            RequestDispatcher rd = request.getRequestDispatcher("agentprofile.jsp");
            rd.forward(request, response);

        }
    }

    catch (HibernateException e) {
        out.println(e.getMessage());
    }
}

From source file:at.gv.egovernment.moa.id.auth.servlet.AuthServlet.java

/**
 * Parses the request input stream for parameters, assuming parameters are
 * encoded UTF-8 (no standard exists how browsers should encode them).
 * /*w  ww . j  a va 2 s . co  m*/
 * @param req
 *            servlet request
 * 
 * @return mapping parameter name -> value
 * 
 * @throws IOException
 *             if parsing request parameters fails.
 * 
 * @throws FileUploadException
 *             if parsing request parameters fails.
 */
protected Map<String, String> getParameters(HttpServletRequest req) throws IOException, FileUploadException {

    Map<String, String> parameters = new HashMap<String, String>();

    if (ServletFileUpload.isMultipartContent(req)) {
        // request is encoded as mulitpart/form-data
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = null;
        upload = new ServletFileUpload(factory);
        List items = null;
        items = upload.parseRequest(req);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                // Process only form fields - no file upload items
                String logString = item.getString("UTF-8");

                // TODO use RegExp
                String startS = "<pr:Identification><pr:Value>";
                String endS = "</pr:Value><pr:Type>urn:publicid:gv.at:baseid</pr:Type>";
                String logWithMaskedBaseid = logString;
                int start = logString.indexOf(startS);
                if (start > -1) {
                    int end = logString.indexOf(endS);
                    if (end > -1) {
                        logWithMaskedBaseid = logString.substring(0, start);
                        logWithMaskedBaseid += startS;
                        logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx";
                        logWithMaskedBaseid += logString.substring(end, logString.length());
                    }
                }
                parameters.put(item.getFieldName(), item.getString("UTF-8"));
                Logger.debug("Processed multipart/form-data request parameter: \nName: " + item.getFieldName()
                        + "\nValue: " + logWithMaskedBaseid);
            }
        }
    }

    else {
        // request is encoded as application/x-www-urlencoded
        InputStream in = req.getInputStream();

        String paramName;
        String paramValueURLEncoded;
        do {
            paramName = new String(readBytesUpTo(in, '='));
            if (paramName.length() > 0) {
                paramValueURLEncoded = readBytesUpTo(in, '&');
                String paramValue = URLDecoder.decode(paramValueURLEncoded, "UTF-8");
                parameters.put(paramName, paramValue);
            }
        } while (paramName.length() > 0);
        in.close();
    }

    return parameters;
}