Search in sources :

Example 1 with UploadedFileFactory

use of com.liferay.faces.util.model.UploadedFileFactory in project liferay-faces-bridge-impl by liferay.

the class MultiPartFormDataProcessorCompatImpl method iterateOver.

/* package-private */
Map<String, List<UploadedFile>> iterateOver(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap, File uploadedFilesPath) {
    // Parse the request parameters and save all uploaded files in a map.
    Map<String, List<UploadedFile>> uploadedFileMap = new HashMap<>();
    // Determine the max file upload size threshold (in bytes).
    long defaultMaxFileSize = PortletConfigParam.UploadedFileMaxSize.getDefaultLongValue();
    long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig);
    if (defaultMaxFileSize != uploadedFileMaxSize) {
        logger.warn("Ignoring init param {0}=[{1}] since it has been replaced by <multipart-config> in web.xml", PortletConfigParam.UploadedFileMaxSize.getName(), uploadedFileMaxSize);
    }
    // FACES-271: Include name+value pairs found in the ActionRequest/ResourceRequest.
    PortletParameters portletParameters;
    boolean actionPhase;
    if (clientDataRequest instanceof ActionRequest) {
        actionPhase = true;
        ActionRequest actionRequest = (ActionRequest) clientDataRequest;
        portletParameters = actionRequest.getActionParameters();
    } else {
        actionPhase = false;
        ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
        portletParameters = resourceRequest.getResourceParameters();
    }
    Set<String> fullyQualifiedParameterNames = new HashSet<>(Collections.list(clientDataRequest.getParameterNames()));
    Set<String> portletParameterNames = portletParameters.getNames();
    for (String parameterName : portletParameterNames) {
        // the portlet namespace.
        if (!fullyQualifiedParameterNames.contains(parameterName)) {
            String fullyQualifiedParameterName = facesRequestParameterMap.getNamespace() + parameterName;
            if (fullyQualifiedParameterNames.contains(fullyQualifiedParameterName)) {
                parameterName = fullyQualifiedParameterName;
            }
        }
        String[] parameterValues = portletParameters.getValues(parameterName);
        if (parameterValues.length > 0) {
            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
                if (actionPhase) {
                    logger.debug("Added action parameter name={0} value={1}", parameterName, parameterValue);
                } else {
                    logger.debug("Added resource parameter name={0} value={1}", parameterName, parameterValue);
                }
            }
        }
    }
    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder.getFactory(portletConfig.getPortletContext(), UploadedFileFactory.class);
    // Begin parsing the request for file parts:
    try {
        Collection<Part> parts = clientDataRequest.getParts();
        List<String> fileUploadFieldNames = new ArrayList<String>();
        int totalFiles = 0;
        // For each field found in the request:
        for (Part part : parts) {
            String fieldName = part.getName();
            fileUploadFieldNames.add(fieldName);
            try {
                totalFiles++;
                String characterEncoding = clientDataRequest.getCharacterEncoding();
                String contentDispositionHeader = part.getHeader("content-disposition");
                String fileName = getValidFileName(contentDispositionHeader);
                // If the current field is a simple form-field, then save the form field value in the map.
                if ((fileName != null) && (fileName.length() > 0)) {
                    File uploadedFilePath = new File(uploadedFilesPath, fileName);
                    String uploadedFilePathAbsolutePath = uploadedFilePath.getAbsolutePath();
                    part.write(uploadedFilePathAbsolutePath);
                    // If the copy was successful, then
                    if (uploadedFilePath.exists()) {
                        // If present, build up a map of headers. According to Hypertext Transfer Protocol --
                        // HTTP/1.1 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2), header names
                        // are case-insensitive. In order to support this, use a TreeMap with case insensitive
                        // keys.
                        Map<String, List<String>> headersMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
                        Collection<String> headerNames = part.getHeaderNames();
                        for (String headerName : headerNames) {
                            Collection<String> headerValues = part.getHeaders(headerName);
                            List<String> headerValueList = new ArrayList<>();
                            for (String headerValue : headerValues) {
                                headerValueList.add(headerValue);
                            }
                            headersMap.put(headerName, headerValueList);
                        }
                        // 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 id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                        com.liferay.faces.util.model.UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(uploadedFilePathAbsolutePath, attributeMap, characterEncoding, part.getContentType(), headersMap, id, null, fileName, part.getSize(), com.liferay.faces.util.model.UploadedFile.Status.FILE_SAVED);
                        facesRequestParameterMap.addValue(fieldName, uploadedFilePathAbsolutePath);
                        addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                        logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName);
                    } else {
                        if (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)");
                            com.liferay.faces.util.model.UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e);
                com.liferay.faces.util.model.UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                String totalFilesfieldName = Integer.toString(totalFiles);
                addUploadedFile(uploadedFileMap, totalFilesfieldName, uploadedFile);
            }
        }
        for (String fileUploadFieldName : fileUploadFieldNames) {
            // value.
            if (!uploadedFileMap.containsKey(fileUploadFieldName)) {
                uploadedFileMap.put(fileUploadFieldName, Collections.<UploadedFile>emptyList());
            }
        }
    }// the map so that the developer can have some idea that something went wrong.
     catch (Exception e) {
        logger.error(e);
        com.liferay.faces.util.model.UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }
    return uploadedFileMap;
}
Also used : HashMap(java.util.HashMap) UploadedFile(com.liferay.faces.util.model.UploadedFile) ArrayList(java.util.ArrayList) PortletParameters(javax.portlet.PortletParameters) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) UploadedFileFactory(com.liferay.faces.util.model.UploadedFileFactory) IOException(java.io.IOException) TreeMap(java.util.TreeMap) IOException(java.io.IOException) UploadedFile(com.liferay.faces.util.model.UploadedFile) ActionRequest(javax.portlet.ActionRequest) Part(javax.servlet.http.Part) ResourceRequest(javax.portlet.ResourceRequest) UploadedFile(com.liferay.faces.util.model.UploadedFile) File(java.io.File)

Example 2 with UploadedFileFactory

use of com.liferay.faces.util.model.UploadedFileFactory in project liferay-faces-alloy by liferay.

the class InputFileDecoderCommonsImpl method decode.

@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();
    }
    // 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);
                }
            }
        }
    }// 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;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ExternalContext(javax.faces.context.ExternalContext) ArrayList(java.util.ArrayList) List(java.util.List) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) UploadedFileFactory(com.liferay.faces.util.model.UploadedFileFactory) FileItemHeaders(org.apache.commons.fileupload.FileItemHeaders) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) InvalidFileNameException(org.apache.commons.fileupload.InvalidFileNameException) IOException(java.io.IOException) UploadedFile(com.liferay.faces.util.model.UploadedFile) FileItemStream(org.apache.commons.fileupload.FileItemStream) UploadedFile(com.liferay.faces.util.model.UploadedFile) File(java.io.File) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) InvalidFileNameException(org.apache.commons.fileupload.InvalidFileNameException)

Example 3 with UploadedFileFactory

use of com.liferay.faces.util.model.UploadedFileFactory in project liferay-faces-alloy by liferay.

the class InputFileDecoderPartImpl method decode.

@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);
    if (sessionId != null) {
        // 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();
        }
        uploadedFileMap = new HashMap<String, List<UploadedFile>>();
        UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder.getFactory(externalContext, UploadedFileFactory.class);
        // Begin parsing the request for file parts:
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
            Collection<Part> parts = httpServletRequest.getParts();
            int totalFiles = 0;
            // For each part found in the multipart/form-data request:
            for (Part part : parts) {
                try {
                    totalFiles++;
                    // Get field name and file name of the current part.
                    String fieldName = null;
                    String fileName = null;
                    String safeFileName = null;
                    String contentDispositionHeader = part.getHeader("Content-Disposition");
                    String[] keyValuePairs = contentDispositionHeader.split(";");
                    for (String keyValuePair : keyValuePairs) {
                        String trimmedKeyValuePair = keyValuePair.trim();
                        if (trimmedKeyValuePair.startsWith("filename")) {
                            int equalsPos = trimmedKeyValuePair.indexOf("=");
                            fileName = trimmedKeyValuePair.substring(equalsPos + 2, trimmedKeyValuePair.length() - 1);
                            safeFileName = stripIllegalCharacters(fileName);
                        } else if (trimmedKeyValuePair.startsWith("name")) {
                            int equalsPos = trimmedKeyValuePair.indexOf("=");
                            fieldName = trimmedKeyValuePair.substring(equalsPos + 2, trimmedKeyValuePair.length() - 1);
                        }
                    }
                    if ((fileName != null) && (fileName.length() > 0)) {
                        try {
                            long partSize = part.getSize();
                            int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);
                            if (partSize > uploadedFileMaxSize) {
                                throw new UploadedFileMaxSizeExceededException(fileName, partSize, uploadedFileMaxSize, WebConfigParam.UploadedFileMaxSize.getName());
                            }
                            // Copy the stream of file data to a file.
                            File copiedFile = new File(uploadedFilesPath, safeFileName);
                            String copiedFileAbsolutePath = copiedFile.getAbsolutePath();
                            part.write(copiedFileAbsolutePath);
                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            Collection<String> headerNames = part.getHeaderNames();
                            for (String headerName : headerNames) {
                                List<String> headerValues = new ArrayList<String>(part.getHeaders(headerName));
                                headersMap.put(headerName, headerValues);
                            }
                            // Get the Content-Type header
                            String contentType = part.getContentType();
                            // Get the charset from the Content-Type header
                            String charSet = null;
                            if (contentType != null) {
                                keyValuePairs = contentType.split(";");
                                for (String keyValuePair : keyValuePairs) {
                                    String trimmedKeyValuePair = keyValuePair.trim();
                                    if (trimmedKeyValuePair.startsWith("charset")) {
                                        int equalsPos = trimmedKeyValuePair.indexOf("=");
                                        charSet = trimmedKeyValuePair.substring(equalsPos + 2, trimmedKeyValuePair.length() - 1);
                                    }
                                }
                            }
                            // 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, charSet, contentType, headersMap, id, message, fileName, partSize, UploadedFile.Status.FILE_SAVED);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName);
                            // Delete temporary file created by the Servlet API.
                            part.delete();
                        } catch (UploadedFileMaxSizeExceededException e) {
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e, UploadedFile.Status.FILE_SIZE_LIMIT_EXCEEDED);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                        } catch (IOException e) {
                            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);
                }
            }
        }// 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;
}
Also used : UploadedFileFactory(com.liferay.faces.util.model.UploadedFileFactory) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) UploadedFile(com.liferay.faces.util.model.UploadedFile) ExternalContext(javax.faces.context.ExternalContext) Part(javax.servlet.http.Part) ArrayList(java.util.ArrayList) List(java.util.List) UploadedFile(com.liferay.faces.util.model.UploadedFile) File(java.io.File)

Aggregations

UploadedFile (com.liferay.faces.util.model.UploadedFile)3 UploadedFileFactory (com.liferay.faces.util.model.UploadedFileFactory)3 File (java.io.File)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 List (java.util.List)3 ExternalContext (javax.faces.context.ExternalContext)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 Part (javax.servlet.http.Part)2 HashSet (java.util.HashSet)1 TreeMap (java.util.TreeMap)1 ActionRequest (javax.portlet.ActionRequest)1 PortletParameters (javax.portlet.PortletParameters)1 ResourceRequest (javax.portlet.ResourceRequest)1 ServletException (javax.servlet.ServletException)1 FileItemHeaders (org.apache.commons.fileupload.FileItemHeaders)1 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)1 FileItemStream (org.apache.commons.fileupload.FileItemStream)1 InvalidFileNameException (org.apache.commons.fileupload.InvalidFileNameException)1