Example usage for org.apache.commons.fileupload FileItemStream openStream

List of usage examples for org.apache.commons.fileupload FileItemStream openStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream openStream.

Prototype

InputStream openStream() throws IOException;

Source Link

Document

Creates an InputStream , which allows to read the items contents.

Usage

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  a  v a  2 s .  com
    }

    // 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:hk.hku.cecid.corvus.http.PartnershipSenderUnitTest.java

/**
 * A Helper method which assert whether the HTTP content received in the HTTP monitor 
 * is a multi-part form data, with basic-auth and well-formed partnership operation request.
 *///w ww .  ja v a 2  s  . co m
private void assertHttpRequestReceived() throws Exception {
    // Debug print information.
    Map headers = monitor.getHeaders();

    // #0 Assertion
    assertFalse("No HTTP header found in the captured data.", headers.isEmpty());

    Map.Entry tmp = null;
    Iterator itr = null;
    itr = headers.entrySet().iterator();
    logger.info("Header information");
    while (itr.hasNext()) {
        tmp = (Map.Entry) itr.next();
        logger.info(tmp.getKey() + " : " + tmp.getValue());
    }

    // #1 Check BASIC authentication value.
    String basicAuth = (String) headers.get("Authorization");

    // #1 Assertion
    assertNotNull("No Basic Authentication found in the HTTP Header.", basicAuth);

    String[] authToken = basicAuth.split(" ");

    // There are 2 token, one is the "Basic" and another is the base64 auth value.
    assertTrue(authToken.length == 2);
    assertTrue("Missing basic auth prefix 'Basic'", authToken[0].equalsIgnoreCase("Basic"));
    // #1 Decode the base64 authentication value to see whether it is "corvus:corvus".
    String decodedCredential = new String(new BASE64Decoder().decodeBuffer(authToken[1]), "UTF-8");
    assertEquals("Invalid basic auth content", USER_NAME + ":" + PASSWORD, decodedCredential);

    // #2 Check content Type
    String contentType = monitor.getContentType();
    String mediaType = contentType.split(";")[0];
    assertEquals("Invalid content type", "multipart/form-data", mediaType);

    // #3 Check the multi-part content.
    // Make a request context that bridge the content from our monitor to FileUpload library.    
    RequestContext rc = new RequestContext() {
        public String getCharacterEncoding() {
            return "charset=ISO-8859-1";
        }

        public int getContentLength() {
            return monitor.getContentLength();
        }

        public String getContentType() {
            return monitor.getContentType();
        }

        public InputStream getInputStream() {
            return monitor.getInputStream();
        }
    };

    FileUpload multipartParser = new FileUpload();
    FileItemIterator item = multipartParser.getItemIterator(rc);
    FileItemStream fstream = null;

    /*
     * For each field in the partnership, we have to check the existence of the 
     * associated field in the HTTP request. Also we check whether the content
     * of that web form field has same data to the field in the partnership.    
     */
    itr = this.target.getPartnershipMapping().entrySet().iterator();
    Map data = ((KVPairData) this.target.properties).getProperties();
    Map.Entry e; // an entry representing the partnership data to web form name mapping.
    String formParamName; // a temporary pointer pointing to the value in the entry.
    Object dataValue; // a temporary pointer pointing to the value in the partnership data.

    while (itr.hasNext()) {
        e = (Map.Entry) itr.next();
        formParamName = (String) e.getValue();
        // Add new part if the mapped key is not null.
        if (formParamName != null) {
            assertTrue("Insufficient number of web form parameter hit.", item.hasNext());
            // Get the next multi-part element.
            fstream = item.next();
            // Assert field name
            assertEquals("Missed web form parameter ?", formParamName, fstream.getFieldName());
            // Assert field content
            dataValue = data.get(e.getKey());
            if (dataValue instanceof String) {
                // Assert content equal.
                assertEquals((String) dataValue, IOHandler.readString(fstream.openStream(), null));
            } else if (dataValue instanceof byte[]) {
                byte[] expectedBytes = (byte[]) dataValue;
                byte[] actualBytes = IOHandler.readBytes(fstream.openStream());
                // Assert byte length equal
                assertEquals(expectedBytes.length, actualBytes.length);
                for (int j = 0; j < expectedBytes.length; j++)
                    assertEquals(expectedBytes[j], actualBytes[j]);
            } else {
                throw new IllegalArgumentException("Invalid content found in multipart.");
            }
            // Log information.
            logger.info("Field name found and verifed: " + fstream.getFieldName() + " content type:"
                    + fstream.getContentType());
        }
    }
    /* Check whether the partnership operation in the HTTP request is expected as i thought */
    assertTrue("Missing request_action ?!", item.hasNext());
    fstream = item.next();
    assertEquals("request_action", fstream.getFieldName());
    // Assert the request_action has same content the operation name.
    Map partnershipOpMap = this.target.getPartnershipOperationMapping();
    assertEquals(partnershipOpMap.get(new Integer(this.target.getExecuteOperation())),
            IOHandler.readString(fstream.openStream(), null));
}

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();//w w w  .  j  a v a2s  .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 = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(portletConfig);

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

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

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

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

        if (parameterValues.length > 0) {

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

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

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

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

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

        if (fileItemIterator != null) {

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

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

                try {
                    totalFiles++;

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

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

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

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

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

                    String fileName = null;

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

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

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

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

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

                        File tempFile = diskFileItem.getStoreLocation();

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

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

                            String copiedFileName = stripIllegalCharacters(fileName);

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

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

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

                                if (headerNameItr != null) {

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

                                        if (headerValuesItr != null) {

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

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

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

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

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

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

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

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

    return uploadedFileMap;
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void createFile(HttpServletRequest req, HttpServletResponse resp, Document buildDoc)
        throws IndelibleWebAccessException, IOException, ServletException, FileUploadException {
    boolean completedOK = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    if (iter.hasNext()) {
        FileItemStream item = iter.next();
        String fieldName = item.getFieldName();
        FilePath dirPath = null;//from  ww  w .  j  a v  a  2  s  .  co  m
        if (fieldName.equals("upfile")) {
            try {
                connection.startTransaction();
                String path = req.getPathInfo();
                String fileName = item.getName();
                if (fileName.indexOf('/') >= 0)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
                dirPath = FilePath.getFilePath(path);
                FilePath reqPath = dirPath.getChild(fileName);
                if (reqPath == null || reqPath.getNumComponents() < 2)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

                // Should be an absolute path
                reqPath = reqPath.removeLeadingComponent();
                String fsIDStr = reqPath.getComponent(0);
                IndelibleFSVolumeIF volume = getVolume(fsIDStr);
                if (volume == null)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError,
                            null);
                FilePath createPath = reqPath.removeLeadingComponent();
                FilePath parentPath = createPath.getParent();
                FilePath childPath = createPath.getPathRelativeTo(parentPath);
                if (childPath.getNumComponents() != 1)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
                IndelibleFileNodeIF parentNode = volume.getObjectByPath(parentPath.makeAbsolute());
                if (!parentNode.isDirectory())
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null);
                IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode;
                IndelibleFileNodeIF childNode = null;
                childNode = parentDirectory.getChildNode(childPath.getName());
                if (childNode == null) {
                    try {
                        CreateFileInfo childInfo = parentDirectory.createChildFile(childPath.getName(), true);
                        childNode = childInfo.getCreatedNode();
                    } catch (FileExistsException e) {
                        // Probably someone else beat us to it...
                        childNode = parentDirectory.getChildNode(childPath.getName());
                    }
                } else {

                }
                if (childNode.isDirectory())
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null);

                IndelibleFSForkIF dataFork = childNode.getFork("data", true);
                dataFork.truncate(0);
                InputStream readStream = item.openStream();
                byte[] writeBuffer = new byte[1024 * 1024];
                int readLength;
                long bytesCopied = 0;
                int bufOffset = 0;
                while ((readLength = readStream.read(writeBuffer, bufOffset,
                        writeBuffer.length - bufOffset)) > 0) {
                    if (bufOffset + readLength == writeBuffer.length) {
                        dataFork.appendDataDescriptor(
                                new CASIDMemoryDataDescriptor(writeBuffer, 0, writeBuffer.length));
                        bufOffset = 0;
                    } else
                        bufOffset += readLength;
                    bytesCopied += readLength;
                }
                if (bufOffset != 0) {
                    // Flush out the final stuff
                    dataFork.appendDataDescriptor(new CASIDMemoryDataDescriptor(writeBuffer, 0, bufOffset));
                }
                connection.commit();
                completedOK = true;
            } catch (PermissionDeniedException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
            } catch (IOException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
            } catch (ObjectNotFoundException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
            } catch (ForkNotFoundException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kForkNotFound, e);
            } finally {
                if (!completedOK)
                    try {
                        connection.rollback();
                    } catch (IOException e) {
                        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
                    }
            }
            listPath(dirPath, buildDoc);
            return;
        }
    }
    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
}

From source file:net.ymate.platform.mvc.web.support.FileUploadHelper.java

/**
 * ???????//from   ww w  .j a v a2s . com
 * 
 * @param processer
 * @throws IOException 
 * @throws FileUploadException 
 */
private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer)
        throws FileUploadException, IOException {
    ServletFileUpload _upload = new ServletFileUpload();
    if (this.__listener != null) {
        _upload.setProgressListener(this.__listener);
    }
    _upload.setFileSizeMax(this.__fileSizeMax);
    _upload.setSizeMax(this.__sizeMax);
    UploadFormWrapper _form = new UploadFormWrapper();
    Map<String, List<String>> tmpParams = new HashMap<String, List<String>>();
    Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>();
    //
    FileItemIterator _iter = _upload.getItemIterator(this.__request);
    while (_iter.hasNext()) {
        FileItemStream _item = _iter.next();
        if (_item.isFormField()) {
            List<String> _valueList = tmpParams.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<String>();
                tmpParams.put(_item.getFieldName(), _valueList);
            }
            _valueList.add(Streams.asString(_item.openStream(), WebMVC.getConfig().getCharsetEncoding()));
        } else {
            List<UploadFileWrapper> _valueList2 = tmpFiles.get(_item.getFieldName());
            if (_valueList2 == null) {
                _valueList2 = new ArrayList<UploadFileWrapper>();
                tmpFiles.put(_item.getFieldName(), _valueList2);
            }
            // ??
            _valueList2.add(processer.process(_item));
        }
    }
    //
    for (Entry<String, List<String>> entry : tmpParams.entrySet()) {
        String key = entry.getKey();
        List<String> value = entry.getValue();
        _form.getFieldMap().put(key, value.toArray(new String[value.size()]));
    }
    for (Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) {
        String key = entry.getKey();
        _form.getFileMap().put(key, entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()]));
    }
    return _form;
}

From source file:net.ymate.platform.webmvc.util.FileUploadHelper.java

/**
 * ???????//from  w w w .jav  a  2  s . c o  m
 *
 * @param processer ?
 * @throws FileUploadException ?
 * @throws IOException         ?
 */
private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer)
        throws FileUploadException, IOException {
    ServletFileUpload _upload = new ServletFileUpload();
    _upload.setFileSizeMax(__fileSizeMax);
    _upload.setSizeMax(__sizeMax);
    if (__listener != null) {
        _upload.setProgressListener(__listener);
    }
    Map<String, List<String>> tmpParams = new HashMap<String, List<String>>();
    Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>();
    //
    FileItemIterator _fileItemIT = _upload.getItemIterator(__request);
    while (_fileItemIT.hasNext()) {
        FileItemStream _item = _fileItemIT.next();
        if (_item.isFormField()) {
            List<String> _valueList = tmpParams.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<String>();
                tmpParams.put(_item.getFieldName(), _valueList);
            }
            _valueList.add(Streams.asString(_item.openStream(), __charsetEncoding));
        } else {
            List<UploadFileWrapper> _valueList = tmpFiles.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<UploadFileWrapper>();
                tmpFiles.put(_item.getFieldName(), _valueList);
            }
            // ??
            _valueList.add(processer.process(_item));
        }
    }
    //
    UploadFormWrapper _form = new UploadFormWrapper();
    for (Map.Entry<String, List<String>> entry : tmpParams.entrySet()) {
        _form.getFieldMap().put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]));
    }
    for (Map.Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) {
        _form.getFileMap().put(entry.getKey(),
                entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()]));
    }
    return _form;
}

From source file:ninja.servlet.NinjaServletContext.java

private void processFormFields() {
    if (formFieldsProcessed)
        return;/*from w ww. j  a  v a2s . c  o m*/
    formFieldsProcessed = true;

    // return if not multipart
    if (!ServletFileUpload.isMultipartContent(httpServletRequest))
        return;

    // get fileProvider from route method/class, or defaults to an injected one
    // if none injected, then we do not process form fields this way and let the user
    // call classic getFileItemIterator() by himself
    FileProvider fileProvider = null;
    if (route != null) {
        if (fileProvider == null) {
            fileProvider = route.getControllerMethod().getAnnotation(FileProvider.class);
        }
        if (fileProvider == null) {
            fileProvider = route.getControllerClass().getAnnotation(FileProvider.class);
        }
    }

    // get file item provider from file provider or default one
    FileItemProvider fileItemProvider = null;
    if (fileProvider == null) {
        fileItemProvider = injector.getInstance(FileItemProvider.class);
    } else {
        fileItemProvider = injector.getInstance(fileProvider.value());
    }

    if (fileItemProvider instanceof NoFileItemProvider)
        return;

    // Initialize maps and other constants
    ArrayListMultimap<String, String> formMap = ArrayListMultimap.create();
    ArrayListMultimap<String, FileItem> fileMap = ArrayListMultimap.create();

    // This is the iterator we can use to iterate over the contents of the request.
    try {

        FileItemIterator fileItemIterator = getFileItemIterator();

        while (fileItemIterator.hasNext()) {

            FileItemStream item = fileItemIterator.next();

            if (item.isFormField()) {

                String charset = NinjaConstant.UTF_8;

                String contentType = item.getContentType();

                if (contentType != null) {
                    charset = HttpHeaderUtils.getCharsetOfContentTypeOrUtf8(contentType);
                }

                // save the form field for later use from getParameter
                String value = Streams.asString(item.openStream(), charset);
                formMap.put(item.getFieldName(), value);

            } else {

                // process file as input stream and save for later use in getParameterAsFile or getParameterAsInputStream
                FileItem fileItem = fileItemProvider.create(item);
                fileMap.put(item.getFieldName(), fileItem);
            }
        }
    } catch (FileUploadException | IOException e) {
        throw new RuntimeException("Failed to parse multipart request data", e);
    }

    // convert both multimap<K,V> to map<K,List<V>>
    formFieldsMap = toUnmodifiableMap(formMap);
    fileFieldsMap = toUnmodifiableMap(fileMap);
}

From source file:ninja.uploads.DiskFileItemProvider.java

@Override
public FileItem create(FileItemStream item) {

    File tmpFile = null;/*from w w w  .jav a  2 s .c o m*/

    // 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) {
            }
        }
    };

}

From source file:ninja.uploads.MemoryFileItemProvider.java

@Override
public FileItem create(FileItemStream item) {

    // build output stream to get bytes
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    // do copy//from  w ww  . j a va 2 s .c  o m
    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() {
        }
    };

}

From source file:nu.kelvin.jfileshare.ajax.FileReceiverServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();
    UserItem currentUser = (UserItem) session.getAttribute("user");
    if (currentUser != null && ServletFileUpload.isMultipartContent(req)) {
        Conf conf = (Conf) getServletContext().getAttribute("conf");
        // keep files of up to 10 MiB in memory 10485760
        FileItemFactory factory = new DiskFileItemFactory(10485760, new File(conf.getPathTemp()));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(conf.getFileSizeMax());

        // set file upload progress listener
        FileUploadListener listener = new FileUploadListener();
        session.setAttribute("uploadListener", listener);
        upload.setProgressListener(listener);

        File tempFile = File.createTempFile(String.format("%05d-", currentUser.getUid()), null,
                new File(conf.getPathTemp()));
        tempFile.deleteOnExit();//from  w w  w  .j av a2  s. c om
        try {
            FileItem file = new FileItem();

            /* iterate over all uploaded items */
            FileItemIterator it = upload.getItemIterator(req);
            FileOutputStream filestream = null;

            while (it.hasNext()) {
                FileItemStream item = it.next();
                String name = item.getFieldName();
                InputStream instream = item.openStream();
                DigestOutputStream outstream = null;

                if (item.isFormField()) {
                    String value = Streams.asString(instream);
                    // logger.info(name + " : " + value);
                    /* not the file upload. Maybe the password field? */
                    if (name.equals("password") && !value.equals("")) {
                        logger.info("Uploaded file has password set");
                        file.setPwPlainText(value);
                    }
                    instream.close();
                } else {
                    // This is the file you're looking for
                    file.setName(item.getName());
                    file.setType(
                            item.getContentType() == null ? "application/octet-stream" : item.getContentType());
                    file.setUid(currentUser.getUid());

                    try {
                        filestream = new FileOutputStream(tempFile);
                        MessageDigest md = MessageDigest.getInstance("MD5");
                        outstream = new DigestOutputStream(filestream, md);
                        long filesize = IOUtils.copyLarge(instream, outstream);

                        if (filesize == 0) {
                            throw new Exception("File is empty.");
                        }
                        md = outstream.getMessageDigest();
                        file.setMd5sum(toHex(md.digest()));
                        file.setSize(filesize);

                    } finally {
                        if (outstream != null) {
                            try {
                                outstream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (filestream != null) {
                            try {
                                filestream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (instream != null) {
                            try {
                                instream.close();
                            } catch (IOException ignored) {
                            }
                        }
                    }
                }
            }
            /* All done. Save the new file */
            if (conf.getDaysFileExpiration() != 0) {
                file.setDaysToKeep(conf.getDaysFileExpiration());
            }
            if (file.create(ds, req.getRemoteAddr())) {
                File finalFile = new File(conf.getPathStore(), Integer.toString(file.getFid()));
                tempFile.renameTo(finalFile);
                logger.log(Level.INFO, "User {0} storing file \"{1}\" in the filestore",
                        new Object[] { currentUser.getUid(), file.getName() });
                req.setAttribute("msg",
                        "File <strong>\"" + Helpers.htmlSafe(file.getName())
                                + "\"</strong> uploaded successfully. <a href='" + req.getContextPath()
                                + "/file/edit/" + file.getFid() + "'>Click here to edit file</a>");
                req.setAttribute("javascript", "parent.uploadComplete('info');");
            } else {
                req.setAttribute("msg", "Unable to contact the database");
                req.setAttribute("javascript", "parent.uploadComplete('critical');");
            }
        } catch (SizeLimitExceededException e) {
            tempFile.delete();
            req.setAttribute("msg", "File is too large. The maximum size of file uploads is "
                    + FileItem.humanReadable(conf.getFileSizeMax()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (FileUploadException e) {
            tempFile.delete();
            req.setAttribute("msg", "Unable to upload file");
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (Exception e) {
            tempFile.delete();
            req.setAttribute("msg",
                    "Unable to upload file. ".concat(e.getMessage() == null ? "" : e.getMessage()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } finally {
            session.setAttribute("uploadListener", null);
        }
        ServletContext app = getServletContext();
        RequestDispatcher disp = app.getRequestDispatcher("/templates/AjaxDummy.jsp");
        disp.forward(req, resp);
    }
}