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

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

Introduction

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

Prototype

public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) 

Source Link

Document

Create a new org.apache.commons.fileupload.disk.DiskFileItem instance from the supplied parameters and the local factory configuration.

Usage

From source file:fr.paris.lutece.portal.web.style.PageTemplatesJspBeanTest.java

public void testDoCreatePageTemplateNoToken() throws AccessDeniedException, IOException {
    final String desc = getRandomName();
    Map<String, String[]> parameters = new HashMap<String, String[]>();
    parameters.put(Parameters.PAGE_TEMPLATE_DESCRIPTION, new String[] { desc });
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    Map<String, List<FileItem>> files = new HashMap<>();
    List<FileItem> pageTemplateFiles = new ArrayList<>();
    FileItem pageTemplateFile = fileItemFactory.createItem("page_template_file", "text/html", false,
            "junit.html");
    pageTemplateFile.getOutputStream().write(new byte[1]);
    pageTemplateFiles.add(pageTemplateFile);
    files.put("page_template_file", pageTemplateFiles);
    List<FileItem> pageTemplatePictures = new ArrayList<>();
    FileItem pageTemplatePicture = fileItemFactory.createItem("page_template_picture", "image/jpg", false,
            "junit.jpg");
    pageTemplatePicture.getOutputStream().write(new byte[1]);
    pageTemplatePictures.add(pageTemplatePicture);
    files.put("page_template_picture", pageTemplatePictures);
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, files, parameters);
    try {/*w  w w.ja  v  a  2 s . c  om*/
        instance.doCreatePageTemplate(multipartRequest);
        fail("Should have thrown");
    } catch (AccessDeniedException e) {
        assertFalse(PageTemplateHome.getPageTemplatesList().stream()
                .anyMatch(t -> t.getDescription().equals(desc)));
    } finally {
        PageTemplateHome.getPageTemplatesList().stream().filter(t -> t.getDescription().equals(desc))
                .forEach(t -> PageTemplateHome.remove(t.getId()));
    }
}

From source file:fr.paris.lutece.portal.web.style.PageTemplatesJspBeanTest.java

/**
 * Test of doCreatePageTemplate method, of fr.paris.lutece.portal.web.style.PageTemplatesJspBean.
 * /*w w w. ja  v  a 2  s.  c om*/
 * @throws AccessDeniedException
 * @throws IOException
 */
public void testDoCreatePageTemplate() throws AccessDeniedException, IOException {
    final String desc = getRandomName();
    Map<String, String[]> parameters = new HashMap<String, String[]>();
    parameters.put(Parameters.PAGE_TEMPLATE_DESCRIPTION, new String[] { desc });
    parameters.put(SecurityTokenService.PARAMETER_TOKEN, new String[] {
            SecurityTokenService.getInstance().getToken(request, "admin/style/create_page_template.html") });
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    Map<String, List<FileItem>> files = new HashMap<>();
    List<FileItem> pageTemplateFiles = new ArrayList<>();
    FileItem pageTemplateFile = fileItemFactory.createItem("page_template_file", "text/html", false,
            "junit.html");
    pageTemplateFile.getOutputStream().write(new byte[1]);
    pageTemplateFiles.add(pageTemplateFile);
    files.put("page_template_file", pageTemplateFiles);
    List<FileItem> pageTemplatePictures = new ArrayList<>();
    FileItem pageTemplatePicture = fileItemFactory.createItem("page_template_picture", "image/jpg", false,
            "junit.jpg");
    pageTemplatePicture.getOutputStream().write(new byte[1]);
    pageTemplatePictures.add(pageTemplatePicture);
    files.put("page_template_picture", pageTemplatePictures);
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, files, parameters);
    try {
        instance.doCreatePageTemplate(multipartRequest);
        assertTrue(PageTemplateHome.getPageTemplatesList().stream()
                .anyMatch(t -> t.getDescription().equals(desc)));
    } finally {
        PageTemplateHome.getPageTemplatesList().stream().filter(t -> t.getDescription().equals(desc))
                .forEach(t -> PageTemplateHome.remove(t.getId()));
    }
}

From source file:fr.paris.lutece.portal.web.style.PageTemplatesJspBeanTest.java

public void testDoCreatePageTemplateInvalidToken() throws AccessDeniedException, IOException {
    final String desc = getRandomName();
    Map<String, String[]> parameters = new HashMap<String, String[]>();
    parameters.put(Parameters.PAGE_TEMPLATE_DESCRIPTION, new String[] { desc });
    parameters.put(SecurityTokenService.PARAMETER_TOKEN, new String[] {
            SecurityTokenService.getInstance().getToken(request, "admin/style/create_page_template.html")
                    + "b" });
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    Map<String, List<FileItem>> files = new HashMap<>();
    List<FileItem> pageTemplateFiles = new ArrayList<>();
    FileItem pageTemplateFile = fileItemFactory.createItem("page_template_file", "text/html", false,
            "junit.html");
    pageTemplateFile.getOutputStream().write(new byte[1]);
    pageTemplateFiles.add(pageTemplateFile);
    files.put("page_template_file", pageTemplateFiles);
    List<FileItem> pageTemplatePictures = new ArrayList<>();
    FileItem pageTemplatePicture = fileItemFactory.createItem("page_template_picture", "image/jpg", false,
            "junit.jpg");
    pageTemplatePicture.getOutputStream().write(new byte[1]);
    pageTemplatePictures.add(pageTemplatePicture);
    files.put("page_template_picture", pageTemplatePictures);
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, files, parameters);
    try {//from   w w  w. j  a v  a 2 s.  c  o  m
        instance.doCreatePageTemplate(multipartRequest);
        fail("Should have thrown");
    } catch (AccessDeniedException e) {
        assertFalse(PageTemplateHome.getPageTemplatesList().stream()
                .anyMatch(t -> t.getDescription().equals(desc)));
    } finally {
        PageTemplateHome.getPageTemplatesList().stream().filter(t -> t.getDescription().equals(desc))
                .forEach(t -> PageTemplateHome.remove(t.getId()));
    }
}

From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java

/**
 * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection ,
 *      FileUploadSelector, String, UploadProgress)
 *//*from  w w w .  j  a  va  2s .c om*/
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex,
        final UploadProgress progress) throws Exception {
    final ApplicationInstance app = conn.getUserInstance().getApplicationInstance();

    final DiskFileItemFactory itemFactory = new DiskFileItemFactory();
    itemFactory.setRepository(getDiskCacheLocation());
    itemFactory.setSizeThreshold(getMemoryCacheThreshold());

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

    final ServletFileUpload upload = new ServletFileUpload(itemFactory);
    upload.setHeaderEncoding(encoding);
    upload.setProgressListener(new UploadProgressListener(progress));

    long sizeLimit = uploadSelect.getUploadSizeLimit();
    if (sizeLimit == 0)
        sizeLimit = getFileUploadSizeLimit();
    if (sizeLimit != NO_SIZE_LIMIT) {
        upload.setSizeMax(sizeLimit);
    }

    String fileName = null;
    String contentType = null;

    try {
        final FileItemIterator iter = upload.getItemIterator(conn.getRequest());
        if (iter.hasNext()) {
            final FileItemStream stream = iter.next();

            if (!stream.isFormField()) {
                fileName = FilenameUtils.getName(stream.getName());
                contentType = stream.getContentType();

                final Set<String> types = uploadSelect.getContentTypeFilter();
                if (!types.isEmpty()) {
                    if (!types.contains(contentType)) {
                        app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable(
                                uploadSelect, uploadIndex, fileName, contentType, progress));
                        return;
                    }
                }

                progress.setStatus(Status.inprogress);
                final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName());
                item.getOutputStream(); // initialise DiskFileItem internals

                uploadSelect.notifyCallback(
                        new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize()));

                IOUtils.copy(stream.openStream(), item.getOutputStream());

                app.enqueueTask(uploadSelect.getTaskQueue(),
                        new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress));

                return;
            }
        }

        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new RuntimeException("No multi-part content!"), progress));
    } catch (final FileUploadBase.SizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final FileUploadBase.FileSizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final MultipartStream.MalformedStreamException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(),
                new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress));
    }
}

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();/*from ww w. j  a 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).
    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  w w .  j  a v a 2 s  .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).
    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  . j  av  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();//from w  ww.j  a va  2  s .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.apache.wicket.markup.html.form.upload.FileUploadTest.java

/**
 * Test that when getting an input stream a new input stream is returned every time.
 * /*from www .ja  va 2 s  .c  o m*/
 * Also test that the inputstream is saved internally for later closing.
 * 
 * @throws Exception
 */
@Test
public void getInputStream() throws Exception {
    final IFileCleaner fileUploadCleaner = new FileCleaner();

    DiskFileItemFactory itemFactory = new DiskFileItemFactory() {
        @Override
        public FileCleaningTracker getFileCleaningTracker() {
            return new FileCleanerTrackerAdapter(fileUploadCleaner);
        }
    };
    FileItem fileItem = itemFactory.createItem("dummyFieldName", "text/java", false, "FileUploadTest.java");
    // Initialize the upload
    fileItem.getOutputStream();

    // Get the internal list out
    Field inputStreamsField = FileUpload.class.getDeclaredField("inputStreamsToClose");
    inputStreamsField.setAccessible(true);

    FileUpload fileUpload = new FileUpload(fileItem);

    List<?> inputStreams = (List<?>) inputStreamsField.get(fileUpload);

    assertNull(inputStreams);

    InputStream is1 = fileUpload.getInputStream();
    inputStreams = (List<?>) inputStreamsField.get(fileUpload);

    assertEquals(1, inputStreams.size());

    InputStream is2 = fileUpload.getInputStream();
    inputStreams = (List<?>) inputStreamsField.get(fileUpload);

    assertEquals(2, inputStreams.size());

    assertNotSame(is1, is2);

    // Ok lets close all the streams
    try {
        fileUpload.closeStreams();
    } catch (Exception e) {
        fail();
    }

    inputStreams = (List<?>) inputStreamsField.get(fileUpload);

    assertNull(inputStreams);

    fileUploadCleaner.destroy();
}

From source file:org.jahia.tools.files.FileUpload.java

/**
 * Init the MultiPartReq object if it's actually null
 *
 * @exception IOException//from w w w .j a  v a 2s.c o m
 */
protected void init() throws IOException {

    params = new HashMap<String, List<String>>();
    paramsContentType = new HashMap<String, String>();
    files = new HashMap<String, DiskFileItem>();
    filesByFieldName = new HashMap<String, DiskFileItem>();

    parseQueryString();

    if (checkSavePath(savePath)) {
        try {
            final ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(req);
            DiskFileItemFactory factory = null;
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    final String name = item.getFieldName();
                    final List<String> v;
                    if (params.containsKey(name)) {
                        v = params.get(name);
                    } else {
                        v = new ArrayList<String>();
                        params.put(name, v);
                    }
                    v.add(Streams.asString(stream, encoding));
                    paramsContentType.put(name, item.getContentType());
                } else {
                    if (factory == null) {
                        factory = new DiskFileItemFactory();
                        factory.setSizeThreshold(1);
                        factory.setRepository(new File(savePath));
                    }
                    DiskFileItem fileItem = (DiskFileItem) factory.createItem(item.getFieldName(),
                            item.getContentType(), item.isFormField(), item.getName());
                    try {
                        Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                    } catch (FileUploadIOException e) {
                        throw (FileUploadException) e.getCause();
                    } catch (IOException e) {
                        throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                                + " request failed. " + e.getMessage(), e);
                    }
                    final FileItemHeaders fih = item.getHeaders();
                    fileItem.setHeaders(fih);
                    if (fileItem.getSize() > 0) {
                        files.put(fileItem.getStoreLocation().getName(), fileItem);
                        filesByFieldName.put(fileItem.getFieldName(), fileItem);
                    }
                }
            }
        } catch (FileUploadException ioe) {
            logger.error("Error while initializing FileUpload class:", ioe);
            throw new IOException(ioe.getMessage());
        }
    } else {
        logger.error("FileUpload::init storage path does not exists or can write");
        throw new IOException("FileUpload::init storage path does not exists or cannot write");
    }
}