Search in sources :

Example 1 with FileItemHeaders

use of org.apache.commons.fileupload.FileItemHeaders in project ninja by ninjaframework.

the class MemoryFileItemProvider method create.

@Override
public FileItem create(FileItemStream item) {
    // build output stream to get bytes
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    // do copy
    try {
        ByteStreams.copy(item.openStream(), outputStream);
    } catch (IOException e) {
        throw new RuntimeException("Failed to create temporary uploaded file in memory", e);
    }
    // return
    final String name = item.getName();
    final byte[] bytes = outputStream.toByteArray();
    final String contentType = item.getContentType();
    final FileItemHeaders headers = item.getHeaders();
    return new FileItem() {

        @Override
        public String getFileName() {
            return name;
        }

        @Override
        public InputStream getInputStream() {
            return new ByteArrayInputStream(bytes);
        }

        @Override
        public File getFile() {
            throw new UnsupportedOperationException("Not supported in MemoryFileProvider");
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public FileItemHeaders getHeaders() {
            return headers;
        }

        @Override
        public void cleanup() {
        }
    };
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileItemHeaders(org.apache.commons.fileupload.FileItemHeaders) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 2 with FileItemHeaders

use of org.apache.commons.fileupload.FileItemHeaders in project wiremock by wiremock.

the class FileItemPartAdapter method getHeaders.

@Override
public HttpHeaders getHeaders() {
    FileItemHeaders headers = fileItem.getHeaders();
    Iterator<String> i = headers.getHeaderNames();
    ImmutableList.Builder<HttpHeader> builder = ImmutableList.builder();
    while (i.hasNext()) {
        String name = i.next();
        builder.add(getHeader(name));
    }
    return new HttpHeaders(builder.build());
}
Also used : HttpHeaders(com.github.tomakehurst.wiremock.http.HttpHeaders) HttpHeader(com.github.tomakehurst.wiremock.http.HttpHeader) FileItemHeaders(org.apache.commons.fileupload.FileItemHeaders) ImmutableList(com.google.common.collect.ImmutableList)

Example 3 with FileItemHeaders

use of org.apache.commons.fileupload.FileItemHeaders in project jahia by Jahia.

the class FileUpload method prepareUploadFileItem.

private DiskFileItemFactory prepareUploadFileItem(FileItemStream item, DiskFileItemFactory factory) throws FileUploadException, IOException {
    try (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<>();
                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(stream, 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);
            }
        }
    }
    return factory;
}
Also used : InputStream(java.io.InputStream) FileItemHeaders(org.apache.commons.fileupload.FileItemHeaders) IOFileUploadException(org.apache.commons.fileupload.FileUploadBase.IOFileUploadException) IOException(java.io.IOException) FileUploadIOException(org.apache.commons.fileupload.FileUploadBase.FileUploadIOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) FileUploadIOException(org.apache.commons.fileupload.FileUploadBase.FileUploadIOException)

Example 4 with FileItemHeaders

use of org.apache.commons.fileupload.FileItemHeaders in project ninja by ninjaframework.

the class DiskFileItemProvider method create.

@Override
public FileItem create(FileItemStream item) {
    File tmpFile = null;
    // do copy
    try (InputStream is = item.openStream()) {
        tmpFile = File.createTempFile("nju", null, tmpFolder);
        Files.copy(is, tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new RuntimeException("Failed to create temporary uploaded file on disk", e);
    }
    // return
    final String name = item.getName();
    final File file = tmpFile;
    final String contentType = item.getContentType();
    final FileItemHeaders headers = item.getHeaders();
    return new FileItem() {

        @Override
        public String getFileName() {
            return name;
        }

        @Override
        public InputStream getInputStream() {
            try {
                return new FileInputStream(file);
            } catch (FileNotFoundException e) {
                throw new RuntimeException("Failed to read temporary uploaded file from disk", e);
            }
        }

        @Override
        public File getFile() {
            return file;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public FileItemHeaders getHeaders() {
            return headers;
        }

        @Override
        public void cleanup() {
            // try to delete temporary file, silently fail on error
            try {
                file.delete();
            } catch (Exception e) {
            }
        }
    };
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileItemHeaders(org.apache.commons.fileupload.FileItemHeaders) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 5 with FileItemHeaders

use of org.apache.commons.fileupload.FileItemHeaders 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)

Aggregations

FileItemHeaders (org.apache.commons.fileupload.FileItemHeaders)5 IOException (java.io.IOException)4 File (java.io.File)3 InputStream (java.io.InputStream)2 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)2 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)2 HttpHeader (com.github.tomakehurst.wiremock.http.HttpHeader)1 HttpHeaders (com.github.tomakehurst.wiremock.http.HttpHeaders)1 ImmutableList (com.google.common.collect.ImmutableList)1 UploadedFile (com.liferay.faces.util.model.UploadedFile)1 UploadedFileFactory (com.liferay.faces.util.model.UploadedFileFactory)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 ExternalContext (javax.faces.context.ExternalContext)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1