Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository.

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

Usage

From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java

/**
 * Parses a HTTP request. Returns an array containing maps for upload
 * controls, other controls, repeat indices, and trigger. The individual
 * maps may be null in case no corresponding parameters appear in the
 * request.//w w  w.jav a 2  s. c  o m
 *
 * @param request a HTTP request.
 * @return an array of maps containing the parsed request parameters.
 * @throws FileUploadException          if an error occurred during file upload.
 * @throws UnsupportedEncodingException if an error occurred during
 *                                      parameter value decoding.
 */
protected Map[] parseRequest(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    Map[] parameters = new Map[4];

    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        UploadListener uploadListener = new UploadListener(request, this.sessionKey);
        DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(uploadListener);
        factory.setRepository(new File(this.uploadRoot));
        ServletFileUpload upload = new ServletFileUpload(factory);

        String encoding = request.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }

        Iterator iterator = upload.parseRequest(request).iterator();
        FileItem item;
        while (iterator.hasNext()) {
            item = (FileItem) iterator.next();
            if (LOGGER.isDebugEnabled()) {
                if (item.isFormField()) {
                    LOGGER.debug(
                            "request param: " + item.getFieldName() + " - value='" + item.getString() + "'");
                } else {
                    LOGGER.debug("file in request: " + item.getName());
                }

            }
            parseMultiPartParameter(item, encoding, parameters);
        }
    } else {
        Enumeration enumeration = request.getParameterNames();
        String name;
        String[] values;
        while (enumeration.hasMoreElements()) {
            name = (String) enumeration.nextElement();
            values = request.getParameterValues(name);

            parseURLEncodedParameter(name, values, parameters);
        }
    }

    return parameters;
}

From source file:com.gwtcx.server.servlet.FileUploadServlet.java

@SuppressWarnings("rawtypes")
private void processFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // set the size threshold, above which content will be stored on disk
    factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB

    // set the temporary directory (this is where files that exceed the threshold will be stored)
    factory.setRepository(tmpDir);

    // create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {/*from   ww  w  .ja  v a  2  s.  c om*/
        String recordType = "Account";

        // parse the request
        List items = upload.parseRequest(request);

        // process the uploaded items
        Iterator itr = items.iterator();

        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // process a regular form field
            if (item.isFormField()) {
                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getString());

                if (item.getFieldName().equals("recordType")) {
                    recordType = item.getString();
                }
            } else { // process a file upload

                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getName()
                        + ", Content Type: " + item.getContentType() + ", In Memory: " + item.isInMemory()
                        + ", File Size: " + item.getSize());

                // write the uploaded file to the application's file staging area
                File file = new File(destinationDir, item.getName());
                item.write(file);

                // import the CSV file
                importCsvFile(recordType, file.getPath());

                // file.delete();  // TO DO
            }
        }
    } catch (FileUploadException e) {
        Log.error("Error encountered while parsing the request", e);
    } catch (Exception e) {
        Log.error("Error encountered while uploading file", e);
    }
}

From source file:com.wabacus.WabacusFacade.java

public static void uploadFile(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;//from   w  w w .  j a v  a  2s  .c  o  m
    try {
        out = response.getWriter();
    } catch (IOException e1) {
        throw new WabacusRuntimeException("response?PrintWriter", e1);
    }
    out.println(
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + Config.encode + "\">");
    importWebresources(out);
    if (Config.getInstance().getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog")) {
        out.print("<script type=\"text/javascript\"  src=\"" + Config.webroot
                + "webresources/component/artDialog/artDialog.js\"></script>");
        out.print("<script type=\"text/javascript\"  src=\"" + Config.webroot
                + "webresources/component/artDialog/plugins/iframeTools.js\"></script>");
    }
    /**if(true)
    {
    out.print("<table style=\"margin:0px;\"><tr><td style='font-size:13px;'><font color='#ff0000'>");
    out.print("???WabacusDemo????\n\rWabacusDemo.war?samples/");
    out.print("</font></td></tr></table>");
    return;
    }*/
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    String repositoryPath = FilePathAssistant.getInstance().standardFilePath(Config.webroot_abspath
            + File.separator + "wxtmpfiles" + File.separator + "upload" + File.separator);
    FilePathAssistant.getInstance().checkAndCreateDirIfNotExist(repositoryPath);
    factory.setRepository(new File(repositoryPath));
    ServletFileUpload fileUploadObj = new ServletFileUpload();
    fileUploadObj.setFileItemFactory(factory);
    fileUploadObj.setHeaderEncoding(Config.encode);
    List lstFieldItems = null;
    String errorinfo = null;
    try {
        lstFieldItems = fileUploadObj.parseRequest(request);
        if (lstFieldItems == null || lstFieldItems.size() == 0) {
            errorinfo = "??";
        }
    } catch (FileUploadException e) {
        log.error("?", e);
        errorinfo = "?";
    }
    Map<String, String> mFormFieldValues = new HashMap<String, String>();
    Iterator itFieldItems = lstFieldItems.iterator();
    FileItem item;
    while (itFieldItems.hasNext()) {//??mFormFieldValues??
        item = (FileItem) itFieldItems.next();
        if (item.isFormField()) {
            try {
                mFormFieldValues.put(item.getFieldName(), item.getString(Config.encode));
                request.setAttribute(item.getFieldName(), item.getString(Config.encode));
            } catch (UnsupportedEncodingException e) {
                log.warn("??????" + Config.encode
                        + "?", e);
            }
        }
    }
    String fileuploadtype = mFormFieldValues.get("FILEUPLOADTYPE");
    AbsFileUpload fileUpload = getFileUploadObj(request, fileuploadtype);
    boolean isPromtAuto = true;
    if (fileUpload == null) {
        errorinfo = "";
    } else if (errorinfo == null || errorinfo.trim().equals("")) {
        fileUpload.setMFormFieldValues(mFormFieldValues);
        errorinfo = fileUpload.doFileUpload(lstFieldItems, out);
        if (fileUpload.getInterceptorObj() != null) {
            isPromtAuto = fileUpload.getInterceptorObj().beforeDisplayFileUploadPrompt(request, lstFieldItems,
                    fileUpload.getMFormFieldValues(), errorinfo, out);
        }
    }
    out.println("<script language='javascript'>");
    out.println("  try{hideLoadingMessage();}catch(e){}");
    out.println("</script>");
    if (isPromtAuto) {
        if (errorinfo == null || errorinfo.trim().equals("")) {
            out.println("<script language='javascript'>");
            fileUpload.promptSuccess(out, Config.getInstance()
                    .getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog"));
            out.println("</script>");
        } else {
            out.println("<table style=\"margin:0px;\"><tr><td style='font-size:13px;'><font color='#ff0000'>"
                    + errorinfo + "</font></td></tr></table>");
        }
    }
    if (errorinfo != null && !errorinfo.trim().equals("")) {
        if (fileUpload != null) {
            request.setAttribute("WX_FILE_UPLOAD_FIELDVALUES", fileUpload.getMFormFieldValues());
        }
        showUploadFilePage(request, out);
    } else if (!isPromtAuto) {//???????????
        out.println("<script language='javascript'>");
        if (Config.getInstance().getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog")) {
            out.println("art.dialog.close();");
        } else {
            out.println("parent.closePopupWin();");
        }
        out.println("</script>");
    }
}

From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                                configuring to send a multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 *                            the mutlipart POST data to be sent via the {@link PostMethod}
 *///from ww w .  j a va 2 s. c om
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException {

    _log.debug("handleMultipartPost()");

    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(HttpConstants.STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new IOException(fileUploadException);
    }
}

From source file:dk.clarin.tools.rest.upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/xml");
    response.setStatus(200);//w  w  w.jav  a2  s .c  o m
    if (!BracMat.loaded()) {
        response.setStatus(500);
        throw new ServletException("Bracmat is not loaded. Reason:" + BracMat.reason());
    }

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

    String arg = "(method.POST)"; // bj 20120801 "(action.POST)";

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
        * Parse the request
        */
        @SuppressWarnings("unchecked")
        List<FileItem> items = (List<FileItem>) uploadHandler.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        FileItem theFile = null;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
            * Handle Form Fields.
            */
            if (item.isFormField()) {
                // We need the job parameter that indirectly tells us what local file name to give to the uploaded file.
                arg = arg + " (\"" + workflow.escape(item.getFieldName()) + "\".\""
                        + workflow.escape(item.getString()) + "\")";
            } else if (item.getName() != "") {
                //Handle Uploaded file.
                if (theFile != null) {
                    response.setStatus(400);
                    /**
                     * getStatusCode$
                     *
                     * Given a HTTP status code and an informatory text, return an HTML-file
                     * with a heading containing the status code and the official short description
                     * of the status code, a paragraph containing the informatory text and a 
                     * paragraph displaying a longer text explaining the code (From wikipedia).
                     * 
                     * This function could just as well have been written in Java.
                     */
                    String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"Too many files uploaded\")");
                    out.println(messagetext);
                    return;
                }
                theFile = item;
            }
        }
        if (theFile != null) {
            /*
            * Write file to the ultimate location.
            */
            /**
             * upload$
             *
             * Make a waiting job non-waiting upon receipt of a result from an 
             * asynchronous tool.
             *
             * Analyze the job parameter. It tells to which job the sent file belongs.
             * The jobs table knows the file name and location for the uploaded file.
             *              (Last field)
             * Input:
             *      List of HTTP request parameters.
             *      One of the parameters must be (job.<jobNr>-<jobID>)
             *
             * Output:
             *      The file name that must be given to the received file when saved in
             *      the staging area.
             *
             * Status codes:
             *      200     ok
             *      400     'job' parameter does not contain hyphen '-' or
             *              'job' parameter missing altogether.
             *      404     Job is not expecting a result (job is not waiting)
             *              Job is unknown
             *      500     Job list could not be read
             *
             * Affected tables:
             *      jobs.table
             */
            String LocalFileName = BracMat.Eval("upload$(" + arg + ")");
            if (LocalFileName == null) {
                response.setStatus(404);
                String messagetext = BracMat
                        .Eval("getStatusCode$(\"404\".\"doPost:" + workflow.escape(LocalFileName) + "\")");
                out.println(messagetext);
            } else if (LocalFileName.startsWith("HTTP-status-code")) {
                /**
                 * parseStatusCode$
                 *
                 * Find the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String statusCode = BracMat
                        .Eval("parseStatusCode$(\"" + workflow.escape(LocalFileName) + "\")");
                response.setStatus(Integer.parseInt(statusCode));
                /**
                 * parsemessage$
                 *
                 * Find the text following the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String messagetext = BracMat.Eval("parsemessage$(\"" + workflow.escape(LocalFileName) + "\")");
                messagetext = BracMat.Eval("getStatusCode$(\"" + workflow.escape(statusCode) + "\".\""
                        + workflow.escape(messagetext) + "\")");
                out.println(messagetext);
            } else {
                File file = new File(destinationDir, LocalFileName);
                try {
                    theFile.write(file);
                } catch (Exception ex) {
                    response.setStatus(500);
                    String messagetext = BracMat
                            .Eval("getStatusCode$(\"500\".\"Tools cannot save uploaded file to "
                                    + workflow.escape(destinationDir + LocalFileName) + "\")");
                    out.println(messagetext);
                    return;
                }
                /**
                 * uploadJobNr$
                 *
                 * Return the string preceding the hyphen in the input.
                 *
                 * Input: <jobNr>-<jobID>
                 */
                String JobNr = BracMat.Eval("uploadJobNr$(" + arg + ")");
                Runnable runnable = new workflow(JobNr, destinationDir);
                Thread thread = new Thread(runnable);
                thread.start();
                response.setStatus(201);
                String messagetext = BracMat.Eval("getStatusCode$(\"201\".\"\")");
                out.println(messagetext);
            }
        } else {
            response.setStatus(400);
            String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"No file uploaded\")");
            out.println(messagetext);
        }
    } catch (FileUploadException ex) {
        response.setStatus(500);
        String messagetext = BracMat.Eval("getStatusCode$(\"500\".\"doPost: FileUploadException "
                + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    } catch (Exception ex) {
        response.setStatus(500);
        String messagetext = BracMat
                .Eval("getStatusCode$(\"500\".\"doPost: Exception " + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    }
}

From source file:com.pureinfo.tgirls.servlet.TestServlet.java

private File uploadFile(HttpServletRequest request) throws Exception {
    // ,??ServletFileUpload
    DiskFileItemFactory dfif = new DiskFileItemFactory();
    dfif.setSizeThreshold(4096);// ?,4K.
    String tempfilepath = FileFactory.getInstance().lookupPathConfigByFlag("UP", true).getLocalPath();
    dfif.setRepository(new File(tempfilepath));// 

    // /*w  w w .j  a  va2  s .c o  m*/
    ServletFileUpload sfu = new ServletFileUpload(dfif);
    sfu.setHeaderEncoding("utf-8");
    // 
    //sfu.setSizeMax(MAX_SIZE_5M);

    // PrintWriter out = response.getWriter();
    // request  
    List fileList = null;
    try {
        fileList = sfu.parseRequest(request);
    } catch (FileUploadException e) {// ?
        logger.error("FileUploadException", e);
        if (e instanceof SizeLimitExceededException) {
            throw new Exception("?:" + MAX_SIZE_5M / 1024 + "K");
        }
    }
    // 
    if (fileList == null || fileList.size() == 0) {
        throw new Exception("");
    }
    // 
    Iterator fileItr = fileList.iterator();
    // ?
    while (fileItr.hasNext()) {
        FileItem fileItem = null;
        String path = null;
        long size = 0;
        // ?
        fileItem = (FileItem) fileItr.next();
        // ?form?(<input type="text" />)

        if (fileItem == null || fileItem.isFormField()) {
            continue;
        }
        // 
        path = fileItem.getName();

        logger.debug("path:" + path);

        // ?
        size = fileItem.getSize();
        if ("".equals(path) || size == 0) {
            throw new Exception("");
        }

        // ??
        String t_name = path.substring(path.lastIndexOf("\\") + 1);
        // ??(????)
        String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);

        logger.debug("the file ext name:" + t_ext);

        // ???
        int allowFlag = 0;
        int allowedExtCount = allowedExt.length;
        for (; allowFlag < allowedExtCount; allowFlag++) {
            if (allowedExt[allowFlag].equals(t_ext.toLowerCase()))
                break;
        }
        if (allowFlag == allowedExtCount) {
            String error = ":";
            for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
                error += "*." + allowedExt[allowFlag] + "  ";
            throw new Exception(error);
        }

        // ?
        String u_name = FileFactory.getInstance().getNextFileName("UP", t_ext, true);
        File temp = new File(u_name);

        int[] imgSize = getimgSize(fileItem);
        if ((imgSize[0] > 0 && imgSize[0] < 300) || (imgSize[1] > 0 && imgSize[1] < 300)) {
            throw new Exception("300x300");
        }

        logger.debug("to write file:" + temp);

        // ?
        fileItem.write(temp);

        temp = resizePic(temp);
        return temp;

    }

    throw new Exception("");

}

From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java

public String execute() throws Exception {

    //ActionContext ac = invocation.getInvocationContext();

    HttpServletResponse response = ServletActionContext.getResponse();

    // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest());
    HttpServletRequest multipartRequest = ServletActionContext.getRequest();

    List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest);
    System.out.println("TAMAO ITEMS " + items2.size());
    System.out.println("Check that we have a file upload request");
    boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest);
    System.out.println("isMultipart: " + isMultipart);

    String ourTempDirectory = "/opt/erp/import/obras/";

    byte[] cr = { 13 };
    byte[] lf = { 10 };
    String CR = new String(cr);
    String LF = new String(lf);
    String CRLF = CR + LF;//from  w ww.ja v  a  2  s . c o  m
    System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF);

    //Initialization for chunk management.
    boolean bLastChunk = false;
    int numChunk = 0;

    //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL
    boolean generateError = false;
    boolean generateWarning = false;
    boolean sendRequest = false;

    response.setContentType("text/plain");

    java.util.Enumeration<String> headers = multipartRequest.getHeaderNames();
    System.out.println("[parseRequest.jsp]  ------------------------------ ");
    System.out.println("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        System.out.println("[parseRequest.jsp]  " + header + ": " + multipartRequest.getHeader(header));
    }
    System.out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        System.out.println(" Get URL Parameters.");
        Enumeration paraNames = multipartRequest.getParameterNames();
        System.out.println("[parseRequest.jsp]  ------------------------------ ");
        System.out.println("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = multipartRequest.getParameter(pname);
            System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                System.out.println("pname.equals(\"jufinal\")");
                bLastChunk = pvalue.equals("1");
            } else if (pname.equals("jupart")) {
                System.out.println("pname.equals(\"jupart\")");
                numChunk = Integer.parseInt(pvalue);
            }

            //For debug convenience, putting error=true as a URL parameter, will generate an error
            //in this response.
            if (pname.equals("error") && pvalue.equals("true")) {
                generateError = true;
            }

            //For debug convenience, putting warning=true as a URL parameter, will generate a warning
            //in this response.
            if (pname.equals("warning") && pvalue.equals("true")) {
                generateWarning = true;
            }

            //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content
            //into the response of this page.
            if (pname.equals("sendRequest") && pvalue.equals("true")) {
                sendRequest = true;
            }

        }
        System.out.println("[parseRequest.jsp]  ------------------------------ ");

        int ourMaxMemorySize = 10000000;
        int ourMaxRequestSize = 2000000000;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //The code below is directly taken from the jakarta fileupload common classes
        //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(ourMaxMemorySize);
        factory.setRepository(new File(ourTempDirectory));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(ourMaxRequestSize);

        // Parse the request
        if (sendRequest) {
            //For debug only. Should be removed for production systems. 
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
            System.out.println("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = multipartRequest.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                System.out.write(c);
            } //while
            is.close();
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) {
            System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + multipartRequest.getContentType());
        } else {
            List /* FileItem */ items = upload.parseRequest(multipartRequest);
            // Process the uploaded items
            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            System.out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

                if (fileItem.isFormField()) {
                    System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = "
                            + fileItem.getString());

                    //If we receive the md5sum parameter, we've read finished to read the current file. It's not
                    //a very good (end of file) signal. Will be better in the future ... probably !
                    //Let's put a separator, to make output easier to read.
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        System.out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    //Ok, we've got a file. Let's process it.
                    //Again, for all informations of what is exactly a FileItem, please
                    //have a look to http://jakarta.apache.org/commons/fileupload/
                    //
                    System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number.
                    String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : "");
                    fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName());
                    System.out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    System.out.println(" write the file");
                    fileItem.write(fout);

                    //////////////////////////////////////////////////////////////////////////////////////
                    System.out.println(
                            " Chunk management: if it was the last chunk, let's recover the complete file");
                    System.out.println(" by concatenating all chunk parts.");
                    //
                    if (bLastChunk) {
                        System.out.println(
                                "[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                        + fileItem.getName() + ")");
                        //First: construct the final filename.
                        FileInputStream fis;
                        FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName());
                        int nbBytes;
                        byte[] byteBuff = new byte[1024];
                        String filename;
                        for (int i = 1; i <= numChunk; i += 1) {
                            filename = fileItem.getName() + ".part" + i;
                            System.out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    // End of chunk management
                    //////////////////////////////////////////////////////////////////////////////////////

                    fileItem.delete();
                }
            } //while
        }

        if (generateWarning) {
            System.out.println("WARNING: just a warning message.\\nOn two lines!");
        }

        System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :");

        //Let's wait a little, to simulate the server time to manage the file.
        Thread.sleep(500);

        //Do you want to test a successful upload, or the way the applet reacts to an error ?
        if (generateError) {
            System.out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            System.out.println("SUCCESS");
            //out.println("                        <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>");
        }

        System.out.println("[parseRequest.jsp] " + "End of server treatment ");

    } catch (Exception e) {
        System.out.println("");
        System.out.println("ERROR: Exception e = " + e.toString());
        System.out.println("");
    }
    return SUCCESS;
}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Sets up the given {@link EntityEnclosingMethod} to send the same multipart
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a multipart request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart data to be sent via the {@link EntityEnclosingMethod}
 *//*  w  w  w .  j  av a  2 s .  c  om*/
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod,
        HttpServletRequest httpServletRequest) throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
        entityEnclosingMethod.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:com.intbit.ServletModel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww w  .j av  a  2 s  . 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
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        look = new Looks();
        //            uploadXmlPath = getServletContext().getRealPath("") + "/model";
        uploadPath = AppConstants.BASE_MODEL_PATH;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("organization")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("users")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("categories")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mapper")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("layout")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mail")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("socialmedia")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("textstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("containerstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("element")) {
                        lookName = fi.getString();
                    }

                    String textstyleinfo = request.getParameter("textstyle");
                    String containerstyle = request.getParameter("containerstyle");
                    String mapfiledata = request.getParameter("element");
                    String textstylearray[] = textstyleinfo.split(",");
                    String containerstylearray[] = containerstyle.split(" ");
                    String mapfiledataarray[] = mapfiledata.split(",");
                    //        String image = request.getParameter("image");
                    logger.log(Level.INFO, containerstyle);

                    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

                    // root elements
                    Document doc = docBuilder.newDocument();
                    Element rootElement = doc.createElement("layout");
                    doc.appendChild(rootElement);

                    Document doc1 = docBuilder.newDocument();
                    Element rootElement1 = doc1.createElement("models");
                    doc1.appendChild(rootElement1);

                    Element container = doc.createElement("container");
                    rootElement.appendChild(container);

                    //                        for (int i = 0; i <= containerstylearray.length - 1; i++) {
                    //                            String v[] = containerstylearray[i].split(":");
                    //                            Attr attr = doc.createAttribute(v[0]);
                    //                            attr.setValue("" + v[1]);
                    //                            container.setAttributeNode(attr);
                    //                        }
                    //
                    //                        // staff elements
                    //                        for (int i = 0; i <= textstylearray.length - 1; i++) {
                    //                            Element element = doc.createElement("element");
                    //                            rootElement.appendChild(element);
                    //                            String field1[] = textstylearray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc.createAttribute(field2[0]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }
                    //
                    //            //            for mapper xml file
                    //                        for (int i = 0; i <= mapfiledataarray.length - 1; i++) {
                    //                            Element element1 = doc1.createElement("model");
                    //                            rootElement1.appendChild(element1);
                    //                            String field1[] = mapfiledataarray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc1.createAttribute(field2[k]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element1.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }

                    // write the content into xml file
                    //                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    //                        Transformer transformer = transformerFactory.newTransformer();
                    //                        DOMSource source = new DOMSource(doc);
                    //                        StreamResult result = new StreamResult(new File(uploadPath +File.separator + layoutfilename + ".xml"));
                    //
                    //                        TransformerFactory transformerFactory1 = TransformerFactory.newInstance();
                    //                        Transformer transformer1 = transformerFactory1.newTransformer();
                    //                        DOMSource source1 = new DOMSource(doc1);
                    //                        StreamResult result1 = new StreamResult(new File(uploadPath +File.separator + mapperfilename + ".xml"));

                    // Output to console for testing
                    // StreamResult result = new StreamResult(System.out);
                    //                        transformer.transform(source, result);
                    //                        transformer1.transform(source1, result1);
                    //                        layout.addLayouts(organization_id , user_id, category_id, layoutfilename, mapperfilename, type_email, type_social);

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    int inStr = fileName.indexOf(".");
                    String Str = fileName.substring(0, inStr);

                    fileName = lookName + "_" + Str + ".png";
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    fi.write(storeFile);

                    out.println("Uploaded Filename: " + filePath + "<br>");
                }
            }
            //                look.addLooks(lookName, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
            //                        request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp");
            //                        request_dispatcher.forward(request, response);
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));
        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
    }

}

From source file:fr.inrialpes.exmo.align.service.HTTPTransport.java

/**
 * Starts a HTTP server to given port./*from w  w  w  .  jav  a  2 s.co  m*/
 *
 * @param params: the parameters of the connection, including HTTP port and host
 * @param manager: the manager which will deal with connections
 * @param serv: the set of services to be listening on this connection
 * @throws AServException when something goes wrong (e.g., socket already in use)
 */
public void init(Properties params, AServProtocolManager manager, Vector<AlignmentServiceProfile> serv)
        throws AServException {
    this.manager = manager;
    services = serv;
    tcpPort = Integer.parseInt(params.getProperty("http"));
    tcpHost = params.getProperty("host");

    // ********************************************************************
    // JE: Jetty implementation
    server = new Server(tcpPort);

    // The handler deals with the request
    // most of its work is to deal with large content sent in specific ways 
    Handler handler = new AbstractHandler() {
        public void handle(String String, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String method = request.getMethod();
            String uri = request.getPathInfo();
            Properties params = new Properties();
            try {
                decodeParams(request.getQueryString(), params);
            } catch (Exception ex) {
                logger.debug("IGNORED EXCEPTION: {}", ex);
            }
            ;
            // I do not decode them here because it is useless
            // See below how it is done.
            Properties header = new Properties();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                header.setProperty(headerName, request.getHeader(headerName));
            }

            // Get the content if any
            // This is supposed to be only an uploaded file
            // Note that this could be made more uniform 
            // with the text/xml part stored in a file as well.
            String mimetype = request.getContentType();
            // Multi part: the content provided by an upload HTML form
            if (mimetype != null && mimetype.startsWith("multipart/form-data")) {
                try {
                    //if ( !ServletFileUpload.isMultipartContent( request ) ) {
                    //   logger.debug( "Does not detect multipart" );
                    //}
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    File tempDir = new File(System.getProperty("java.io.tmpdir"));
                    factory.setRepository(tempDir);
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    List<FileItem> items = upload.parseRequest(request);
                    for (FileItem fi : items) {
                        if (fi.isFormField()) {
                            logger.trace("  >> {} = {}", fi.getFieldName(), fi.getString());
                            params.setProperty(fi.getFieldName(), fi.getString());
                        } else {
                            logger.trace("  >> {} : {}", fi.getName(), fi.getSize());
                            logger.trace("  Stored at {}", fi.getName(), fi.getSize());
                            try {
                                // FilenameUtils.getName() needed for Internet Explorer problem
                                File uploadedFile = new File(tempDir, FilenameUtils.getName(fi.getName()));
                                fi.write(uploadedFile);
                                params.setProperty("filename", uploadedFile.toString());
                                params.setProperty("todiscard", "true");
                            } catch (Exception ex) {
                                logger.warn("Cannot load file", ex);
                            }
                            // Another solution is to run this in 
                            /*
                              InputStream uploadedStream = item.getInputStream();
                              ...
                              uploadedStream.close();
                            */
                        }
                    }
                    ;
                } catch (FileUploadException fuex) {
                    logger.trace("Upload Error", fuex);
                }
            } else if (mimetype != null && mimetype.startsWith("text/xml")) {
                // Most likely Web service request (REST through POST)
                int length = request.getContentLength();
                if (length > 0) {
                    char[] mess = new char[length + 1];
                    try {
                        new BufferedReader(new InputStreamReader(request.getInputStream())).read(mess, 0,
                                length);
                    } catch (Exception e) {
                        logger.debug("IGNORED Exception", e);
                    }
                    params.setProperty("content", new String(mess));
                }
                // File attached to SOAP messages
            } else if (mimetype != null && mimetype.startsWith("application/octet-stream")) {
                File alignFile = new File(File.separator + "tmp" + File.separator + newId() + "XXX.rdf");
                // check if file already exists - and overwrite if necessary.
                if (alignFile.exists())
                    alignFile.delete();
                FileOutputStream fos = new FileOutputStream(alignFile);
                InputStream is = request.getInputStream();

                try {
                    byte[] buffer = new byte[4096];
                    int bytes = 0;
                    while (true) {
                        bytes = is.read(buffer);
                        if (bytes < 0)
                            break;
                        fos.write(buffer, 0, bytes);
                    }
                } catch (Exception e) {
                } finally {
                    fos.flush();
                    fos.close();
                }
                is.close();
                params.setProperty("content", "");
                params.setProperty("filename", alignFile.getAbsolutePath());
            }

            // Get the answer (HTTP)
            HTTPResponse r = serve(uri, method, header, params);

            // Return it
            response.setContentType(r.getContentType());
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println(r.getData());
            ((Request) request).setHandled(true);
        }
    };
    server.setHandler(handler);

    // Common part
    try {
        server.start();
    } catch (Exception e) {
        throw new AServException("Cannot launch HTTP Server", e);
    }
    //server.join();

    // ********************************************************************
    //if ( params.getProperty( "wsdl" ) != null ){
    //    wsmanager = new WSAServProfile();
    //    if ( wsmanager != null ) wsmanager.init( params, manager );
    //}
    //if ( params.getProperty( "http" ) != null ){
    //    htmanager = new HTMLAServProfile();
    //    if ( htmanager != null ) htmanager.init( params, manager );
    //}
    myId = "LocalHTMLInterface";
    serverId = manager.serverURL();
    logger.info("Launched on {}/html/", serverId);
    localId = 0;
}