Example usage for org.apache.commons.fileupload.disk DiskFileItem getString

List of usage examples for org.apache.commons.fileupload.disk DiskFileItem getString

Introduction

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

Prototype

public String getString() 

Source Link

Document

Returns the contents of the file as a String, using the default character encoding.

Usage

From source file:cServ.AltaDoc.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w .  j  a v a 2  s.  c  om*/
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        System.out.println("hit altadoc");

        //begin database operation
        String nomArch = "";
        String nombre = "";
        String contra = "";
        int id = 0;
        System.out.println(request.getParameter("idprofe"));
        String displayString = "Contrasea incorrecta";
        String divColor = "danger";
        String rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >";

        //start file up
        FileItemFactory factory = new DiskFileItemFactory();

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

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (Iterator it = items.iterator(); it.hasNext();) {
            DiskFileItem diskFileItem = (DiskFileItem) it.next();
            if (diskFileItem.isFormField()) {
                String fieldname = diskFileItem.getFieldName();
                String fieldvalue = diskFileItem.getString();
                System.out.println("fn: " + fieldname + " fv " + fieldvalue);
                if (fieldname.equals("nombre")) {
                    nombre = fieldvalue;
                } else if (fieldname.equals("contra")) {
                    contra = fieldvalue;
                } else if (fieldname.equals("idprofe")) {
                    id = Integer.parseInt(fieldvalue);
                }

            } else {

                //start getpath
                String relativeWebPath = "/../../web/pages/profesor/adminDocsPanels/docDump/";
                System.out.println("relative thing " + getServletContext().getRealPath(relativeWebPath));
                System.out.println(relativeWebPath);
                String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
                System.out.println("complete path " + absoluteDiskPath + "\\" + nomArch);
                absoluteDiskPath += "\\" + nomArch;
                //end getpath

                byte[] fileBytes = diskFileItem.get();
                nomArch = diskFileItem.getName();
                File file = new File(absoluteDiskPath + diskFileItem.getName());
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(fileBytes);
                fileOutputStream.flush();
            }
        }

        //end file up
        //start db insertion
        Validator valid = new Validator();
        valid.ValidatePDF(nomArch);
        if (valid.isValid() == true) {
            String adString = altaDoc(id, nomArch);
            if (adString.equals("operacion realizada")) {
                displayString = "Documento dado de alta";
                divColor = "success";
                rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >";
            }
        } else {
            displayString = "Archivo no vlido";
            divColor = "danger";
            rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >";
        }
        //end db insertion

        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<link rel=\"stylesheet\" href=\"css/style.css\">");
        out.println("<title>Servlet AltaGrupo</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<div class=\"container\">\n" + "            <div class=\"row\">\n"
                + "                <br><br>\n" + "                <div class=\"panel panel-" + divColor
                + "\">\n" + "                    <div class=\"panel-heading\">\n"
                + "                        <h3 class=\"panel-title\">Espera</h3>\n"
                + "                    </div>\n" + "                    <div class=\"panel-body\">\n"
                + "                        " + displayString + " \n" + "                    </div>\n"
                + "                </div>\n" + "            </div>\n" + "        </div>");
        out.println(rdrUrl);
        out.println("</body>");
        out.println("</html>");
        //end database operation
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.liferay.faces.bridge.context.map.internal.MultiPartFormDataProcessorImpl.java

@Override
public Map<String, List<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig,
        FacesRequestParameterMap facesRequestParameterMap) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;

    PortletSession portletSession = clientDataRequest.getPortletSession();

    String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig);

    // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = portletSession.getId();

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);

    File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//from w ww  . ja  v a  2s. c o m
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig);

    // Parse the request parameters and save all uploaded files in a map.
    PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
    portletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    // FACES-271: Include name+value pairs found in the ActionRequest.
    Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {

            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
            }
        }
    }

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        if (clientDataRequest instanceof ResourceRequest) {
            ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
            ActionRequest actionRequest = (ActionRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        if (fileItemIterator != null) {

            int totalFiles = 0;
            String namespace = facesRequestParameterMap.getNamespace();

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a simple form-field, then save the form field value in the map.
                    if (diskFileItem.isFormField()) {
                        String characterEncoding = clientDataRequest.getCharacterEncoding();
                        String requestParameterValue = null;

                        if (characterEncoding == null) {
                            requestParameterValue = diskFileItem.getString();
                        } else {
                            requestParameterValue = diskFileItem.getString(characterEncoding);
                        }

                        facesRequestParameterMap.addValue(fieldName, requestParameterValue);
                    } else {

                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:com.liferay.faces.bridge.context.map.MultiPartFormDataProcessorImpl.java

@Override
public Map<String, Collection<UploadedFile>> process(ClientDataRequest clientDataRequest,
        PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) {

    Map<String, Collection<UploadedFile>> uploadedFileMap = null;

    PortletSession portletSession = clientDataRequest.getPortletSession();

    String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig);

    // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = portletSession.getId();

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);

    File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();/* ww w  .j  a va  2s .  c  o  m*/
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(portletConfig);

    // Parse the request parameters and save all uploaded files in a map.
    PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
    portletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, Collection<UploadedFile>>();

    // FACES-271: Include name+value pairs found in the ActionRequest.
    Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {

            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
            }
        }
    }

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        if (clientDataRequest instanceof ResourceRequest) {
            ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
            ActionRequest actionRequest = (ActionRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        boolean optimizeNamespace = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig);

        if (fileItemIterator != null) {

            int totalFiles = 0;
            String namespace = facesRequestParameterMap.getNamespace();

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // If namespace optimization is enabled and the namespace is present in the field name,
                    // then remove the portlet namespace from the field name.
                    if (optimizeNamespace) {
                        int pos = fieldName.indexOf(namespace);

                        if (pos >= 0) {
                            fieldName = fieldName.substring(pos + namespace.length());
                        }
                    }

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a simple form-field, then save the form field value in the map.
                    if (diskFileItem.isFormField()) {
                        String characterEncoding = clientDataRequest.getCharacterEncoding();
                        String requestParameterValue = null;

                        if (characterEncoding == null) {
                            requestParameterValue = diskFileItem.getString();
                        } else {
                            requestParameterValue = diskFileItem.getString(characterEncoding);
                        }

                        facesRequestParameterMap.addValue(fieldName, requestParameterValue);
                    } else {

                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:com.novartis.opensource.yada.YADARequest.java

/**
 * Sets the upload items which will then be dervied from the
 * YADARequest by the preprocessor plugin
 * //from w w  w.  java2 s  .  com
 * @param uploadItems list of form field name/value pairs and upload content
 * @throws YADARequestException when a method invocation problem occurs while setting parameter values
 */
public void setUploadItems(List<FileItem> uploadItems) throws YADARequestException {
    this.uploadItems = uploadItems;
    Iterator<FileItem> iter = uploadItems.iterator();
    while (iter.hasNext()) {
        DiskFileItem fi = (DiskFileItem) iter.next();
        l.debug(fi);
        // set parameters from form fields
        if (fi.isFormField()) {
            String field = fi.getFieldName();
            String value = fi.getString();
            l.debug("field is [" + field + "], value is [" + value + "]");
            invokeSetter(field, new String[] { value });
            addToMap(field, new String[] { value });
        } else {
            File f;
            String fPath;
            String fName;
            try {
                // execute plugin, as we are not calling a WS
                f = fi.getStoreLocation(); // tmp dir
                fPath = f.getAbsolutePath(); // uploaded file
                fName = fi.getName(); // original file name
            } finally {
                f = null;
            }
            addArg(fPath);
            addArg(fName);
        }
    }
    l.debug(getFormattedDebugString("uploadItems", uploadItems.toString()));
}

From source file:org.eclipse.rap.addons.fileupload.test.CommonsFileUpload_Test.java

@Test
public void testUploadSmallerThanThreshold() throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory(100, tempDirectory);
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpServletRequest request = createFakeUploadRequest("Hello World!\n", "text/plain", "hello.txt");

    List items = upload.parseRequest(request);

    assertEquals(1, items.size());// w ww. j  a va 2s . c o  m
    DiskFileItem fileItem = (DiskFileItem) items.get(0);
    assertEquals("hello.txt", fileItem.getName());
    assertEquals("text/plain", fileItem.getContentType());
    assertEquals("Hello World!\n", fileItem.getString());
    // Content is smaller than threshold, therefore file is not written
    assertFalse(fileItem.getStoreLocation().exists());
}

From source file:org.eclipse.rap.fileupload.test.CommonsFileUpload_Test.java

@Test
public void testUploadSmallerThanThreshold() throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory(100, tempDirectory);
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpServletRequest request = createFakeUploadRequest("Hello World!\n", "text/plain", "hello.txt");

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

    assertEquals(1, items.size());/*  w  w  w. j a  v a 2 s  . co  m*/
    DiskFileItem fileItem = (DiskFileItem) items.get(0);
    assertEquals("hello.txt", fileItem.getName());
    assertEquals("text/plain", fileItem.getContentType());
    assertEquals("Hello World!\n", fileItem.getString());
    // Content is smaller than threshold, therefore file is not written
    assertFalse(fileItem.getStoreLocation().exists());
}

From source file:org.eclipse.rap.rwt.supplemental.fileupload.test.CommonsFileUpload_Test.java

public void testUploadSmallerThanThreshold() throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory(100, tempDirectory);
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpServletRequest request = FileUploadTestUtil.createFakeUploadRequest("Hello World!\n", "text/plain",
            "hello.txt");

    List items = upload.parseRequest(request);

    assertEquals(1, items.size());/*from  w  w  w .  j a  v a 2 s  .c  o  m*/
    DiskFileItem fileItem = (DiskFileItem) items.get(0);
    assertEquals("hello.txt", fileItem.getName());
    assertEquals("text/plain", fileItem.getContentType());
    assertEquals("Hello World!\n", fileItem.getString());
    // Content is smaller than threshold, therefore file is not written
    assertFalse(fileItem.getStoreLocation().exists());
}

From source file:org.infoglue.calendar.actions.CreateResourceAction.java

/**
 * This is the entry point for the main listing.
 *//*from  w w w .  j a v a  2s  .c om*/

public String execute() throws Exception {
    log.debug("-------------Uploading file.....");

    File uploadedFile = null;
    String maxUploadSize = "";
    String uploadSize = "";

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(2000000);
        //factory.setRepository(yourTempDirectory);

        PortletFileUpload upload = new PortletFileUpload(factory);

        String maxSize = getSetting("AssetUploadMaxFileSize");
        log.debug("maxSize:" + maxSize);
        if (maxSize != null && !maxSize.equals("") && !maxSize.equals("@AssetUploadMaxFileSize@")) {
            try {
                maxUploadSize = maxSize;
                upload.setSizeMax((new Long(maxSize) * 1000));
            } catch (Exception e) {
                log.warn("Faulty max size parameter sent from portlet component:" + maxSize);
            }
        } else {
            maxSize = "" + (10 * 1024);
            maxUploadSize = maxSize;
            upload.setSizeMax((new Long(maxSize) * 1000));
        }

        List fileItems = upload.parseRequest(ServletActionContext.getRequest());
        log.debug("fileItems:" + fileItems.size());
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            Object o = i.next();
            DiskFileItem dfi = (DiskFileItem) o;
            log.debug("dfi:" + dfi.getFieldName());
            log.debug("dfi:" + dfi);

            if (dfi.isFormField()) {
                String name = dfi.getFieldName();
                String value = dfi.getString();
                uploadSize = "" + (dfi.getSize() / 1000);

                log.debug("name:" + name);
                log.debug("value:" + value);
                if (name.equals("assetKey")) {
                    this.assetKey = value;
                } else if (name.equals("eventId")) {
                    this.eventId = new Long(value);
                    ServletActionContext.getRequest().setAttribute("eventId", this.eventId);
                } else if (name.equals("calendarId")) {
                    this.calendarId = new Long(value);
                    ServletActionContext.getRequest().setAttribute("calendarId", this.calendarId);
                } else if (name.equals("mode"))
                    this.mode = value;
            } else {
                String fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                uploadSize = "" + (dfi.getSize() / 1000);

                this.fileName = fileName;
                log.debug("FileName:" + this.fileName);
                uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
            }

        }
    } catch (Exception e) {
        ServletActionContext.getRequest().getSession().setAttribute("errorMessage",
                "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize
                        + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize);
        ActionContext.getContext().getValueStack().getContext().put("errorMessage",
                "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize
                        + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize);
        log.error("Exception uploading resource. " + e.getMessage());
        return Action.ERROR;
    }

    try {
        log.debug("Creating resources.....:" + this.eventId + ":"
                + ServletActionContext.getRequest().getParameter("eventId") + ":"
                + ServletActionContext.getRequest().getParameter("calendarId"));
        ResourceController.getController().createResource(this.eventId, this.getAssetKey(),
                this.getFileContentType(), this.getFileName(), uploadedFile, getSession());
    } catch (Exception e) {
        ServletActionContext.getRequest().getSession().setAttribute("errorMessage",
                "Exception saving resource to database: " + e.getMessage());
        ActionContext.getContext().getValueStack().getContext().put("errorMessage",
                "Exception saving resource to database: " + e.getMessage());
        log.error("Exception saving resource to database. " + e.getMessage());
        return Action.ERROR;
    }

    return Action.SUCCESS;
}

From source file:org.mortbay.servlet.LLabsMultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///from w  w  w . j  ava  2 s.  co  m
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Received uploadRequest:" + request);
    if (Log.isDebugEnabled())
        Log.debug(getClass().getName() + ">>> Received Request");

    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    if (ServletFileUpload.isMultipartContent(srequest)) {
        // Parse the request

        List<File> tempFiles = new ArrayList<File>();
        try {

            MultiMap params = new MultiMap();

            logger.info("Parsing Request");

            List<DiskFileItem> fileItems = uploadHandler.parseRequest(srequest);

            logger.info("Done Parsing Request, got FileItems:" + fileItems);

            StringBuilder filenames = new StringBuilder();

            for (final DiskFileItem diskFileItem : fileItems) {
                if (diskFileItem.getName() == null && diskFileItem.getFieldName() != null
                        && diskFileItem.getFieldName().length() > 0) {
                    params.put(diskFileItem.getFieldName(), diskFileItem.getString());
                    continue;
                }
                if (diskFileItem.getName() == null)
                    continue;
                final File tempFile = File.createTempFile("upload" + diskFileItem.getName(), ".tmp");
                tempFiles.add(tempFile);

                diskFileItem.write(tempFile);
                request.setAttribute(diskFileItem.getName(), tempFile);
                filenames.append(diskFileItem.getName()).append(",");
            }
            params.put("Filenames", filenames.toString());
            logger.info("passing on filter");
            chain.doFilter(new Wrapper(srequest, params), response);

            for (final DiskFileItem diskFileItem : fileItems) {
                diskFileItem.delete();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            logger.error("FileUpload Failed", e);
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            e.printStackTrace();
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } finally {
            for (File tempFile : tempFiles) {
                try {
                    tempFile.delete();
                } catch (Throwable t) {
                }
            }
        }
    }

}