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

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

Introduction

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

Prototype

public String getContentType() 

Source Link

Document

Returns the content type passed by the agent or null if not defined.

Usage

From source file:httpUtils.HttpUtils.java

/**
 * Parse the httpServletRequest for the file item that was received within a 
 * multipart/form-data POST request/*from  ww  w.  j  a va2s  .c om*/
 * @param httpServletRequest
 * @return the file item
 */
public static DiskFileItem parseRequestForFileItem(HttpServletRequest httpServletRequest) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request for file
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(httpServletRequest);
    } catch (FileUploadException fue) {
        log.error("Error reading/parsing file", fue);
    }

    if (items.size() != 1) {
        log.debug("there should only be one file here.");
        for (FileItem x : items) {
            log.debug("item: " + x.toString());
        }
    }
    DiskFileItem dfi = (DiskFileItem) items.get(0);
    log.debug("parseRequestForFile - store location: `" + dfi.getStoreLocation() + "'");
    log.debug("dfi content type: " + dfi.getContentType());
    return dfi;
}

From source file:fr.ippon.wip.http.request.MultipartRequestBuilder.java

public HttpRequestBase buildHttpRequest() throws URISyntaxException {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {/*from w  ww  .ja v a2 s  . c  o  m*/
        for (DiskFileItem fileItem : files) {
            if (fileItem.isFormField())
                multipartEntity.addPart(fileItem.getFieldName(), new StringBody(new String(fileItem.get())));
            else {
                //               FileBody fileBody = new FileBody(fileItem.getStoreLocation(), fileItem.getName(), fileItem.getContentType(), fileItem.getCharSet());
                InputStreamBody fileBody = new InputStreamKnownSizeBody(fileItem.getInputStream(),
                        fileItem.get().length, fileItem.getContentType(), fileItem.getName());
                multipartEntity.addPart(fileItem.getFieldName(), fileBody);
            }
        }

        // some request may have additional parameters in a query string
        if (parameterMap != null)
            for (Entry<String, String> entry : parameterMap.entries())
                multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));

    } catch (Exception e) {
        e.printStackTrace();
    }

    HttpPost postRequest = new HttpPost(requestedURL);
    postRequest.setEntity(multipartEntity);
    return postRequest;
}

From source file:com.liferay.portal.editor.fckeditor.receiver.impl.BaseCommandReceiver.java

public void fileUpload(CommandArgument commandArgument, HttpServletRequest request,
        HttpServletResponse response) {/* w  ww .ja  v a  2s .co m*/

    InputStream inputStream = null;

    String returnValue = null;

    try {
        ServletFileUpload servletFileUpload = new LiferayFileUpload(
                new LiferayFileItemFactory(UploadServletRequestImpl.getTempDir()), request);

        servletFileUpload
                .setFileSizeMax(PrefsPropsUtil.getLong(PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE));

        LiferayServletRequest liferayServletRequest = new LiferayServletRequest(request);

        List<FileItem> fileItems = servletFileUpload.parseRequest(liferayServletRequest);

        Map<String, Object> fields = new HashMap<String, Object>();

        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {
                fields.put(fileItem.getFieldName(), fileItem.getString());
            } else {
                fields.put(fileItem.getFieldName(), fileItem);
            }
        }

        DiskFileItem diskFileItem = (DiskFileItem) fields.get("NewFile");

        String fileName = StringUtil.replace(diskFileItem.getName(), CharPool.BACK_SLASH, CharPool.SLASH);
        String[] fileNameArray = StringUtil.split(fileName, '/');
        fileName = fileNameArray[fileNameArray.length - 1];

        String contentType = diskFileItem.getContentType();

        if (Validator.isNull(contentType) || contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) {

            contentType = MimeTypesUtil.getContentType(diskFileItem.getStoreLocation());
        }

        if (diskFileItem.isInMemory()) {
            inputStream = diskFileItem.getInputStream();
        } else {
            inputStream = new ByteArrayFileInputStream(diskFileItem.getStoreLocation(),
                    LiferayFileItem.THRESHOLD_SIZE);
        }

        long size = diskFileItem.getSize();

        returnValue = fileUpload(commandArgument, fileName, inputStream, contentType, size);
    } catch (Exception e) {
        FCKException fcke = null;

        if (e instanceof FCKException) {
            fcke = (FCKException) e;
        } else {
            fcke = new FCKException(e);
        }

        Throwable cause = fcke.getCause();

        returnValue = "203";

        if (cause != null) {
            String causeString = GetterUtil.getString(cause.toString());

            if (causeString.contains("NoSuchFolderException") || causeString.contains("NoSuchGroupException")) {

                returnValue = "204";
            } else if (causeString.contains("ImageNameException")) {
                returnValue = "205";
            } else if (causeString.contains("FileExtensionException")
                    || causeString.contains("FileNameException")) {

                returnValue = "206";
            } else if (causeString.contains("PrincipalException")) {
                returnValue = "207";
            } else if (causeString.contains("ImageSizeException")
                    || causeString.contains("FileSizeException")) {

                returnValue = "208";
            } else if (causeString.contains("SystemException")) {
                returnValue = "209";
            } else {
                throw fcke;
            }
        }

        _writeUploadResponse(returnValue, response);
    } finally {
        StreamUtil.cleanUp(inputStream);
    }

    _writeUploadResponse(returnValue, response);
}

From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

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

    // 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]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//w ww .  ja va 2 s  .co 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 = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

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

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

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

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // 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 file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        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);

                            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.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

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

    // 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]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();/*from w  ww.ja v  a  2 s .co  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 = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

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

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

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

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // 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 file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        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);

                            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.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();//ww w  . java 2s  . c  om
    }

    // 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();//from  ww w. j a  v a2s .  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:org.datacleaner.monitor.server.media.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    clearSession(req);//from w  w  w.  j  a  v a  2 s  .  co m

    File tempFolder = FileHelper.getTempDir();
    try {
        File subDirectory = new File(tempFolder, ".datacleaner_upload");
        if (subDirectory.mkdirs()) {
            tempFolder = subDirectory;
        }
    } catch (Exception e) {
        logger.warn("Could not create subdirectory in temp folder", e);
    }

    final FileItemFactory fileItemFactory = new DiskFileItemFactory(0, tempFolder);
    final ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    servletFileUpload.setFileSizeMax(FILE_SIZE_MAX);
    servletFileUpload.setSizeMax(REQUEST_SIZE_MAX);

    final List<Object> resultFileElements = new ArrayList<Object>();
    final HttpSession session = req.getSession();

    try {
        int index = 0;
        @SuppressWarnings("unchecked")
        final List<DiskFileItem> items = servletFileUpload.parseRequest(req);
        for (DiskFileItem item : items) {
            if (item.isFormField()) {
                logger.warn("Ignoring form field in request: {}", item);
            } else {
                final String sessionKey = "file_upload_" + index;
                final File file = item.getStoreLocation();

                String filename = toFilename(item.getName());
                logger.info("File '{}' uploaded to temporary location: {}", filename, file);

                session.setAttribute(sessionKey, file);

                final Map<String, String> resultItem = new LinkedHashMap<String, String>();
                resultItem.put("field_name", item.getFieldName());
                resultItem.put("file_name", filename);
                resultItem.put("content_type", item.getContentType());
                resultItem.put("size", Long.toString(item.getSize()));
                resultItem.put("session_key", sessionKey);

                resultFileElements.add(resultItem);

                index++;
            }
        }
    } catch (FileUploadException e) {
        logger.error("Unexpected file upload exception: " + e.getMessage(), e);
        throw new IOException(e);
    }

    final String contentType = req.getParameter("contentType");
    if (contentType == null) {
        resp.setContentType("application/json");
    } else {
        resp.setContentType(contentType);
    }

    final Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    resultMap.put("status", "success");
    resultMap.put("files", resultFileElements);

    // write result as JSON
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writeValue(resp.getOutputStream(), resultMap);
}

From source file:org.debux.webmotion.server.handler.ParametersMultipartHandler.java

@Override
public void handle(Mapping mapping, Call call) {
    HttpContext context = call.getContext();
    HttpServletRequest request = context.getRequest();

    Map<String, Object> extractParameters = call.getExtractParameters();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory fileItemFactory = new DiskFileItemFactory(0, null);
        ServletFileUpload upload = new ServletFileUpload(fileItemFactory);

        HttpSession session = request.getSession();
        if (session != null) {
            log.debug("Set file upload listener");
            FileProgressListener listener = new FileProgressListener();
            upload.setProgressListener(listener);
            session.setAttribute(FileProgressListener.SESSION_ATTRIBUTE_NAME, listener);
            call.setFileUploadRequest(true);
        } else {/*  ww w.  j  av a 2  s .  com*/
            log.warn("No session for file upload listener");
        }

        try {
            List<DiskFileItem> items = upload.parseRequest(request);
            for (DiskFileItem item : items) {
                String fieldName = item.getFieldName();

                if (item.isFormField()) {
                    String fieldValue;
                    try {
                        fieldValue = item.getString("UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        fieldValue = item.getString();
                    }

                    String[] values = (String[]) extractParameters.get(fieldName);
                    if (values == null) {
                        values = new String[] { fieldValue };
                        extractParameters.put(fieldName, values);

                    } else {
                        values = (String[]) ArrayUtils.add(values, fieldValue);
                        extractParameters.put(fieldName, values);
                    }

                } else {
                    UploadFile uploadFile = new UploadFile();

                    File file = item.getStoreLocation();
                    uploadFile.setFile(file);

                    String fileName = item.getName();
                    uploadFile.setName(fileName);

                    long fileSize = item.getSize();
                    uploadFile.setSize(fileSize);

                    String fileType = item.getContentType();
                    uploadFile.setContentType(fileType);

                    extractParameters.put(fieldName, uploadFile);
                }
            }
        } catch (FileUploadException fue) {
            throw new WebMotionException("Error during upload file on server", fue);
        }

    } else {
        Map<String, String[]> parameters = context.getParameters();
        extractParameters.putAll(parameters);
    }
}

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

@Test
public void testUploadEmptyFileWithZeroThreshold() throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory(0, tempDirectory);
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpServletRequest request = createFakeUploadRequest("", "text/empty", "empty.txt");

    List items = upload.parseRequest(request);

    assertEquals(1, items.size());// w  w w .ja  v a 2 s. c  om
    DiskFileItem fileItem = (DiskFileItem) items.get(0);
    assertEquals("empty.txt", fileItem.getName());
    assertEquals("text/empty", fileItem.getContentType());
    assertEquals(0L, fileItem.getSize());
    // Content and threshold is zero, empty file is not written
    assertFalse(fileItem.getStoreLocation().exists());
}