Example usage for org.apache.commons.fileupload FileItem isInMemory

List of usage examples for org.apache.commons.fileupload FileItem isInMemory

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem isInMemory.

Prototype

boolean isInMemory();

Source Link

Document

Provides a hint as to whether or not the file contents will be read from memory.

Usage

From source file:org.eclipse.kura.web.server.servlet.FileServlet.java

@SuppressWarnings("unchecked")
public void parse(HttpServletRequest req) throws FileUploadException {

    s_logger.debug("upload.getFileSizeMax(): {}", getFileSizeMax());
    s_logger.debug("upload.getSizeMax(): {}", getSizeMax());

    // Parse the request
    List<FileItem> items = null;
    items = parseRequest(req);//  w  w  w  . j  a  v  a 2s.c o  m

    // Process the uploaded items
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();

            s_logger.debug("Form field item name: {}, value: {}", name, value);

            this.formFields.put(name, value);
        } else {
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            String contentType = item.getContentType();
            boolean isInMemory = item.isInMemory();
            long sizeInBytes = item.getSize();

            s_logger.debug("File upload item name: {}, fileName: {}, contentType: {}, isInMemory: {}, size: {}",
                    new Object[] { fieldName, fileName, contentType, isInMemory, sizeInBytes });

            this.fileItems.add(item);
        }
    }
}

From source file:org.infoglue.deliver.taglib.common.ParseMultipartTag.java

/**
 * Process the end tag. Sets a cookie.  
 * /*from ww  w .j  a  v  a  2 s.c om*/
 * @return indication of whether to continue evaluating the JSP page.
 * @throws JspException if an error occurred while processing this tag.
 */
public int doEndTag() throws JspException {
    Map parameters = new HashMap();

    try {
        //Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Set factory constraints
        factory.setSizeThreshold(maxSize.intValue());
        //factory.setRepository(new File(CmsPropertyHandler.getDigitalAssetPath()));

        //Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        //Set overall request size constraint
        upload.setSizeMax(this.maxSize.intValue());

        if (upload.isMultipartContent(this.getController().getHttpServletRequest())) {
            //Parse the request
            List items = upload.parseRequest(this.getController().getHttpServletRequest());

            List files = new ArrayList();

            //Process the uploaded items
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (isValidContentType(contentType)) {
                        files.add(item);
                    } else {
                        if ((item.getName() == null || item.getName().equals("")) && this.ignoreEmpty) {
                            logger.warn("Empty file but that was ok..");
                        } else {
                            pageContext.setAttribute("status", "nok");
                            pageContext.setAttribute("upload_error",
                                    "A field did not have a valid content type");
                            pageContext.setAttribute(fieldName + "_error", "Not a valid content type");
                            //throw new JspException("Not a valid content type");
                        }
                    }
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    String oldValue = (String) parameters.get(name);
                    if (oldValue != null)
                        value = oldValue + "," + value;

                    if (value != null) {
                        try {
                            String fromEncoding = "iso-8859-1";
                            String toEncoding = "utf-8";

                            String testValue = new String(value.getBytes(fromEncoding), toEncoding);

                            if (testValue.indexOf((char) 65533) == -1)
                                value = testValue;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    parameters.put(name, value);
                }

            }

            parameters.put("files", files);

            setResultAttribute(parameters);
        } else {
            setResultAttribute(null);
        }
    } catch (Exception e) {
        logger.warn("Error doing an upload" + e.getMessage(), e);
        //pageContext.setAttribute("fieldName_exception", "contentType_MAX");
        //throw new JspException("File upload failed: " + e.getMessage());
        pageContext.setAttribute("status", "nok");
        pageContext.setAttribute("upload_error", "" + e.getMessage());
    }

    return EVAL_PAGE;
}

From source file:org.mitre.medj.WebUtils.java

public static List<ContinuityOfCareRecord> translateFiles(List<FileItem> items, String pathName) {

    try {/*ww  w.  j a  va2 s  . c o  m*/
        ArrayList<ContinuityOfCareRecord> ccrs = new ArrayList<ContinuityOfCareRecord>();
        System.out.println("WebUtils uploadFile : got items " + items);
        boolean writeToFile = true;
        System.out.println("WebUtils uploadFile : got items " + items.size());

        for (FileItem fileSetItem : items) {
            String itemName = fileSetItem.getFieldName();
            System.out.println("WebUtils: first file item  " + itemName);

            String fileName = "";
            if (!fileSetItem.isFormField()) {
                String fieldName = fileSetItem.getFieldName();
                fileName = fileSetItem.getName();

                String contentType = fileSetItem.getContentType();
                boolean isInMemory = fileSetItem.isInMemory();
                long sizeInBytes = fileSetItem.getSize();

                ContinuityOfCareRecord ccr = translate(fileSetItem.getString());
                String patientId = getPatientId(ccr);

                uploadFile(fileSetItem, pathName, fileName, patientId);
                if (ccr != null)
                    ccrs.add(ccr);

            }

        }
        return ccrs;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

From source file:org.mojavemvc.core.HttpParameterMapSource.java

private void processUploadedFile(FileItem item, Map<String, Object> paramMap) throws IOException {

    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    InputStream uploadedStream = item.getInputStream();

    paramMap.put(fieldName, new UploadedFile(fileName, uploadedStream, contentType, isInMemory, sizeInBytes));
}

From source file:org.nuxeo.ecm.webengine.forms.FormData.java

protected Blob getBlob(FileItem item) {
    StreamSource src;//from w w  w .j  a v a 2  s  .c o  m
    if (item.isInMemory()) {
        src = new ByteArraySource(item.get());
    } else {
        try {
            src = new InputStreamSource(item.getInputStream());
        } catch (IOException e) {
            throw WebException.wrap("Failed to get blob data", e);
        }
    }
    String ctype = item.getContentType();

    StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype);
    try {
        blob.persist();
    } catch (IOException e) {
        log.error(e, e);
    }
    blob.setFilename(item.getName());
    return blob;
}

From source file:org.nuxeo.ecm.webengine.util.FormData.java

protected Blob getBlob(FileItem item) throws WebException {
    StreamSource src;//from  ww  w. j a v  a2s. c o  m
    if (item.isInMemory()) {
        src = new ByteArraySource(item.get());
    } else {
        try {
            src = new InputStreamSource(item.getInputStream());
        } catch (IOException e) {
            throw new WebException("Failed to get blob data", e);
        }
    }
    String ctype = item.getContentType();
    StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype);
    blob.setFilename(item.getName());
    return blob;
}

From source file:org.nuxeo.opensocial.container.server.handler.AbstractActionHandler.java

protected static Blob getBlob(FileItem item) {
    StreamSource src;/* ww  w  . j  a va  2s  .c  o m*/
    if (item.isInMemory()) {
        src = new ByteArraySource(item.get());
    } else {
        try {
            src = new InputStreamSource(item.getInputStream());
        } catch (IOException e) {
            throw WebException.wrap("Failed to get blob data", e);
        }
    }
    String ctype = item.getContentType();
    StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype);
    blob.setFilename(item.getName());
    return blob;
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Create debug string containing all parameter names and their values from
 * the request, all attributes, all cookies and other data characterizing the
 * request./*www  . j a v a  2 s  . c o  m*/
 *
 * @param  hsrqRequest - the servlet request.
 * @return String - debug string containing all parameter names and their
 *                  values from the request
 */
public static String debug(HttpServletRequest hsrqRequest) {
    Enumeration enumNames;
    Enumeration enumValues;
    Iterator iterValues;
    String strName;
    String[] arValues;
    Cookie[] arCookies;
    int iIndex;
    Map<String, String[]> mpParamMap;
    StringBuilder sbfReturn = new StringBuilder();

    sbfReturn.append("HttpServletRequest=[");
    sbfReturn.append("\nRemoteAddress=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemotePort=");
    sbfReturn.append(hsrqRequest.getRemotePort());
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteHost=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteUser=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser()));
    sbfReturn.append(";");
    sbfReturn.append("\nFullURL=");
    sbfReturn.append(getFullRequestURL(hsrqRequest));
    sbfReturn.append(";");
    sbfReturn.append("\nContextPath=");
    sbfReturn.append(hsrqRequest.getContextPath());
    sbfReturn.append(";");
    sbfReturn.append("\nServletPath=");
    sbfReturn.append(hsrqRequest.getServletPath());
    sbfReturn.append(";");
    sbfReturn.append("\nPathInfo =");
    sbfReturn.append(hsrqRequest.getPathInfo());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURI=");
    sbfReturn.append(hsrqRequest.getRequestURI());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURL=");
    sbfReturn.append(hsrqRequest.getRequestURL());
    sbfReturn.append(";");
    sbfReturn.append("\nMethod=");
    sbfReturn.append(hsrqRequest.getMethod());
    sbfReturn.append(";");
    sbfReturn.append("\nAuthenticationType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType()));
    sbfReturn.append(";");
    sbfReturn.append("\nCharacterEncoding=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding()));
    sbfReturn.append(";");
    sbfReturn.append("\nContentType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType()));
    sbfReturn.append(";");
    sbfReturn.append("\nMultiPart=");
    sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest));
    sbfReturn.append(";");

    // Parameters ////////////////////////////////////////////////////////////

    try {
        Map.Entry<String, String[]> entry;

        // Use getParameterMap rather than request.getParameterNames since it 
        // correctly handles multipart requests
        mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest);
        for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) {
            entry = (Map.Entry<String, String[]>) iterValues.next();
            strName = entry.getKey();
            arValues = entry.getValue();
            sbfReturn.append("\nParam=");
            sbfReturn.append(strName);
            sbfReturn.append(" values=");
            for (iIndex = 0; iIndex < arValues.length; iIndex++) {
                sbfReturn.append(arValues[iIndex]);
                if (iIndex < (arValues.length - 1)) {
                    sbfReturn.append(";");
                }
            }
            if (iterValues.hasNext()) {
                sbfReturn.append(";");
            }
        }
    } catch (OSSInvalidDataException ex) {
        sbfReturn.append("<Cannot access parameter map of the request>");
        s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex);
    }

    // Uploaded files ////////////////////////////////////////////////////////

    if (ServletFileUpload.isMultipartContent(hsrqRequest)) {
        try {
            FileItem item;
            Map<String, FileItem> mpFiles;
            TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params;

            params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest);
            mpFiles = params.getSecond();

            for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) {
                item = (FileItem) iterValues.next();
                sbfReturn.append("\nUpload=");
                sbfReturn.append(item.getName());
                sbfReturn.append(" field=");
                sbfReturn.append(item.getFieldName());
                sbfReturn.append(" contentType=");
                sbfReturn.append(item.getContentType());
                sbfReturn.append(" isInMemory=");
                sbfReturn.append(item.isInMemory());
                sbfReturn.append(" sizeInBytes=");
                sbfReturn.append(item.getSize());
                if (iterValues.hasNext()) {
                    sbfReturn.append(";");
                }
            }
        } catch (OSSInvalidDataException ex) {
            sbfReturn.append("<Cannot access list of multipart parameters>");
            s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex);
        }
    }

    // Headers ///////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nHeader=");
        sbfReturn.append(strName);
        sbfReturn.append(" values=");
        for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) {
            sbfReturn.append(enumValues.nextElement());
            if (enumValues.hasMoreElements()) {
                sbfReturn.append(";");
            }
        }
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Cookies ///////////////////////////////////////////////////////////////

    arCookies = hsrqRequest.getCookies();
    if (arCookies != null) {
        Cookie cookie;

        for (iIndex = 0; iIndex < arCookies.length; iIndex++) {
            cookie = arCookies[iIndex];
            sbfReturn.append("\nCookie=");
            sbfReturn.append(cookie.getName());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getPath());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getDomain());
            sbfReturn.append(" maxage=");
            sbfReturn.append(cookie.getMaxAge());
            sbfReturn.append(" version=");
            sbfReturn.append(cookie.getVersion());
            sbfReturn.append(" secure=");
            sbfReturn.append(cookie.getSecure());
            sbfReturn.append(" value=");
            sbfReturn.append(cookie.getValue());
            sbfReturn.append(" comment=");
            sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment()));
            if (iIndex < (arCookies.length - 1)) {
                sbfReturn.append(";");
            }
        }
    }
    if (enumNames.hasMoreElements()) {
        sbfReturn.append(";");
    }

    // Attributes ////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nAttribute=");
        sbfReturn.append(strName);
        sbfReturn.append(" value=");
        sbfReturn.append(hsrqRequest.getAttribute(strName));
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Content ///////////////////////////////////////////////////////////////

    sbfReturn.append("\nContent=");
    try {
        sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true));
    } catch (IOException ex) {
        sbfReturn.append("<Cannot access input stream of the request>");
        s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex);
    }
    sbfReturn.append(";");

    return sbfReturn.toString();
}

From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java

/**
 * Check whether a specific FileItem must be generated as Base64.
 *///from w ww .jav  a2s. c om
private boolean useBase64(PipelineContext pipelineContext, FileItem fileItem) {
    State state = (State) getState(pipelineContext);

    return (state.requestedStreamType == null && fileItem.isInMemory()) || (state.requestedStreamType != null
            && state.requestedStreamType.equals(XMLConstants.XS_BASE64BINARY_QNAME));
}

From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java

public static String urlForFileItem(FileItem fileItem) throws SAXException {
    // Only a reference to the file is output (xs:anyURI)
    final DiskFileItem diskFileItem = (DiskFileItem) fileItem;
    final String uriExpiringWithRequest;
    if (!fileItem.isInMemory()) {
        // File must exist on disk since isInMemory() returns false
        final File file = diskFileItem.getStoreLocation();
        uriExpiringWithRequest = file.toURI().toString();
    } else {//from   w ww  . j av a2s.  c  o m
        // File does not exist on disk, must convert
        // NOTE: Conversion occurs every time this method is called. Not optimal.
        try {
            uriExpiringWithRequest = NetUtils.inputStreamToAnyURI(fileItem.getInputStream(),
                    NetUtils.REQUEST_SCOPE, logger);
        } catch (IOException e) {
            throw new OXFException(e);
        }
    }

    return uriExpiringWithRequest;
}