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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:org.apache.ofbiz.pricat.PricatParseExcelHtmlThread.java

private boolean storePricatFile() throws IOException {
    FileItem fi = null;//from   w  w  w . ja v  a2s  .  c  o  m
    FileItem pricatFi = null;
    byte[] pricatBytes = {};
    // check excelTemplateType
    for (int i = 0; i < fileItems.size(); i++) {
        fi = fileItems.get(i);
        String fieldName = fi.getFieldName();
        if (fi.isFormField() && UtilValidate.isNotEmpty(fieldName)) {
            if (fieldName.equals(EXCEL_TEMPLATE_TYPE)) {
                selectedPricatType = fi.getString();
            }
        }
    }
    getReport().print(UtilProperties.getMessage(resource, "ExcelTemplateTypeSelected", getLocale()),
            InterfaceReport.FORMAT_DEFAULT);
    if (PricatTypeLabels.containsKey(selectedPricatType)) {
        getReport().print(
                UtilProperties.getMessage(resource, PricatTypeLabels.get(selectedPricatType), getLocale()),
                InterfaceReport.FORMAT_DEFAULT);
        getReport().println(" ... " + UtilProperties.getMessage(resource, "ok", getLocale()),
                InterfaceReport.FORMAT_OK);
    } else {
        getReport().println(
                UtilProperties.getMessage(resource, PricatTypeLabels.get(selectedPricatType), getLocale()),
                InterfaceReport.FORMAT_ERROR);
        return false;
    }

    // store the file
    for (int i = 0; i < fileItems.size(); i++) {
        fi = fileItems.get(i);
        String fieldName = fi.getFieldName();
        if (fieldName.equals("filename")) {
            pricatFi = fi;
            pricatBytes = pricatFi.get();
            Path path = Paths.get(fi.getName());
            pricatFile = new File(
                    InterfacePricatParser.tempFilesFolder + userLoginId + "/" + path.getFileName().toString());
            FileOutputStream fos = new FileOutputStream(pricatFile);
            fos.write(pricatBytes);
            fos.flush();
            fos.close();
            session.setAttribute(PRICAT_FILE, pricatFile.getAbsolutePath());
        }
    }
    return true;
}

From source file:org.apache.ofbiz.webapp.event.ServiceEventHandler.java

/**
 * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w  w w  . j av  a  2  s.  co  m
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request,
        HttpServletResponse response) throws EventHandlerException {
    // make sure we have a valid reference to the Service Engine
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    if (dispatcher == null) {
        throw new EventHandlerException("The local service dispatcher is null");
    }
    DispatchContext dctx = dispatcher.getDispatchContext();
    if (dctx == null) {
        throw new EventHandlerException("Dispatch context cannot be found");
    }

    // get the details for the service(s) to call
    String mode = SYNC;
    String serviceName = null;

    if (UtilValidate.isEmpty(event.path)) {
        mode = SYNC;
    } else {
        mode = event.path;
    }

    // make sure we have a defined service to call
    serviceName = event.invoke;
    if (serviceName == null) {
        throw new EventHandlerException("Service name (eventMethod) cannot be null");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module);

    // some needed info for when running the service
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");

    // get the service model to generate context
    ModelService model = null;

    try {
        model = dctx.getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new EventHandlerException("Problems getting the service model", e);
    }

    if (model == null) {
        throw new EventHandlerException("Problems getting the service model");
    }

    if (Debug.verboseOn()) {
        Debug.logVerbose("[Processing]: SERVICE Event", module);
        Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> multiPartMap = new HashMap<String, Object>();
    if (isMultiPart) {
        // get the http upload configuration
        String maxSizeStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.size", "-1",
                dctx.getDelegator());
        long maxUploadSize = -1;
        try {
            maxUploadSize = Long.parseLong(maxSizeStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1",
                    module);
            maxUploadSize = -1;
        }
        // get the http size threshold configuration - files bigger than this will be
        // temporarly stored on disk during upload
        String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general",
                "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
        int sizeThreshold = 10240; // 10K
        try {
            sizeThreshold = Integer.parseInt(sizeThresholdStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K",
                    module);
            sizeThreshold = -1;
        }
        // directory used to temporarily store files that are larger than the configured size threshold
        String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general",
                "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
        String encoding = request.getCharacterEncoding();
        // check for multipart content types which may have uploaded items

        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        session.setAttribute("uploadProgressListener", listener);

        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);

        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                //byte[] itemBytes = item.get();
                /*
                Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                    item.getContentType() + " FF: " + item.isFormField(), module);
                */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = new LinkedList<String>();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!",
                                    module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }

    // store the multi-part map as an attribute so we can access the parameters
    request.setAttribute("multiPartMap", multiPartMap);

    Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();

    // we have a service and the model; build the context
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;

        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;

        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap,
                    modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap,
                    modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);

            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request
                        .getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name
                                : modelParam.requestAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session,
                        serviceName, dctx.getDelegator());

                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }

                // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                if (value == null) {
                    value = UtilHttp.makeParamValueFromComposite(request, name, locale);
                }
            }

            // then session
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getSession()
                        .getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name
                                : modelParam.sessionAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // no field found
            if (value == null) {
                //still null, give up for this one
                continue;
            }

            if (value instanceof String && ((String) value).length() == 0) {
                // interpreting empty fields as null values for each in back end handling...
                value = null;
            }
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }

    // get only the parameters for this service - converted to proper type
    // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
    List<Object> errorMessages = new LinkedList<Object>();
    serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone,
            locale);
    if (errorMessages.size() > 0) {
        // uh-oh, had some problems...
        request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages);
        return "error";
    }

    // include the UserLogin value object
    if (userLogin != null) {
        serviceContext.put("userLogin", userLogin);
    }

    // include the Locale object
    if (locale != null) {
        serviceContext.put("locale", locale);
    }

    // include the TimeZone object
    if (timeZone != null) {
        serviceContext.put("timeZone", timeZone);
    }

    // invoke the service
    Map<String, Object> result = null;
    try {
        if (ASYNC.equalsIgnoreCase(mode)) {
            dispatcher.runAsync(serviceName, serviceContext);
        } else {
            result = dispatcher.runSync(serviceName, serviceContext);
        }
    } catch (ServiceAuthException e) {
        // not logging since the service engine already did
        request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        return "error";
    } catch (ServiceValidationException e) {
        // not logging since the service engine already did
        request.setAttribute("serviceValidationException", e);
        if (e.getMessageList() != null) {
            request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
        } else {
            request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        }
        return "error";
    } catch (GenericServiceException e) {
        Debug.logError(e, "Service invocation error", module);
        throw new EventHandlerException("Service invocation error", e.getNested());
    }

    String responseString = null;

    if (result == null) {
        responseString = ModelService.RESPOND_SUCCESS;
    } else {

        if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
            responseString = ModelService.RESPOND_SUCCESS;
        } else {
            responseString = (String) result.get(ModelService.RESPONSE_MESSAGE);
        }

        // set the messages in the request; this will be picked up by messages.ftl and displayed
        request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
        request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
        request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));

        request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
        request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));

        // set the results in the request
        for (Map.Entry<String, Object> rme : result.entrySet()) {
            String resultKey = rme.getKey();
            Object resultValue = rme.getValue();

            if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
                request.setAttribute(resultKey, resultValue);
            }
        }
    }

    if (Debug.verboseOn())
        Debug.logVerbose("[Event Return]: " + responseString, module);
    return responseString;
}

From source file:org.bibsonomy.webapp.controller.ajax.DocumentsController.java

/**
 * This method handles file upload to a temporary directory 
 * @param command//from   ww  w  .  ja v a 2s .  c  o  m
 * @return
 */
private String uploadFile(AjaxDocumentCommand command, Locale locale) {
    log.debug("Start uploading file");

    /*
     * the uploaded file
     */
    final FileItem fileItem = command.getFile().getFileItem();
    final int fileID = command.getFileID();
    /*
     * unsupported file extensions
     */
    if (!StringUtils.matchExtension(fileItem.getName(), FileUploadInterface.fileUploadExt)) {
        return getXmlError("error.upload.failed.filetype", new Object[] { ALLOWED_EXTENSIONS }, fileID,
                fileItem.getName(), locale);
    }

    /*
     * wrong file size
     */
    final long size = fileItem.getSize();
    if (size >= maxFileSize) {
        return getXmlError("error.upload.failed.size", new Object[] { maxFileSizeMB }, fileID,
                fileItem.getName(), locale);
    } else if (size == 0) {
        return getXmlError("error.upload.failed.size0", null, fileID, fileItem.getName(), locale);
    }

    final File uploadFile;
    String fileHash = FileUtil.getRandomFileHash(fileItem.getName());
    if (command.isTemp()) { // /editPublication
        uploadFile = new File(tempPath + fileHash);
    } else { // /bibtex/....
        uploadFile = new File(FileUtil.getFilePath(docPath, fileHash));
    }
    final String md5Hash = HashUtils.getMD5Hash(fileItem.get());
    try {
        fileItem.write(uploadFile);
    } catch (final Exception ex) {
        log.error("Could not write uploaded file.", ex);
        return getXmlError("error.500", null, fileID, fileItem.getName(), locale);
    }

    if (!command.isTemp()) {
        final Document document = new Document();
        document.setFileName(fileItem.getName());
        document.setFileHash(fileHash);
        document.setMd5hash(md5Hash);
        document.setUserName(command.getContext().getLoginUser().getName());

        /*
         * add document to the data base
         */
        logic.createDocument(document, command.getIntraHash());

        /*
         * clear fileHash (randomFileName), so only md5Hash over the file content will be sent back
         */
        fileHash = "";
    }

    return "<root><status>ok</status><fileid>" + fileID + "</fileid><filehash>" + md5Hash + fileHash
            + "</filehash><filename>" + fileItem.getName() + "</filename></root>";
}

From source file:org.carrot2.dcs.RestProcessorServlet.java

/**
 * Handle multipart request, possibly including dcs.c2stream. 
 *//*w  w  w. j ava 2  s . c o m*/
@SuppressWarnings("unchecked")
private void handleMultiPart(HttpServletRequest request, HttpServletResponse response) throws IOException {
    final Map<String, Object> parameters = Maps.newHashMap();
    ProcessingResult input = null;

    final ServletFileUpload upload = new ServletFileUpload(new MemoryFileItemFactory());
    final List<FileItem> items;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e1) {
        sendBadRequest("Could not parse multipart/form-data", response, e1);
        return;
    }

    // Extract uploaded data and other parameters
    for (FileItem fileItem : items) {
        final String fieldName = fileItem.getFieldName();
        if (DCS_C2STREAM.equals(fieldName)) {
            final InputStream uploadInputStream;
            if (fileItem.isFormField()) {
                uploadInputStream = new ByteArrayInputStream(fileItem.get());
            } else {
                uploadInputStream = fileItem.getInputStream();
            }

            // Deserialize documents from the stream
            try {
                input = ProcessingResult.deserialize(uploadInputStream);
            } catch (Exception e) {
                sendBadRequest("Could not parse Carrot2 XML stream", response, e);
                return;
            } finally {
                CloseableUtils.close(uploadInputStream);
            }
        } else if (fileItem.isFormField()) {
            parameters.put(fieldName, fileItem.getString());
        }
    }

    processRequest(response, input, parameters);
}

From source file:org.chiba.adapter.web.HttpRequestHandler.java

private byte[] processMultiPartFile(FileItem item, String id, File savedFile, String encoding, byte[] data)
        throws XFormsException {
    // some data uploaded ...
    if (item.getSize() > 0) {

        if (chibaBean.storesExternalData(id)) {

            // store data to file and create URI
            try {
                savedFile.getParentFile().mkdir();
                item.write(savedFile);/*w ww. ja v  a 2 s.c o  m*/
            } catch (Exception e) {
                throw new XFormsException(e);
            }
            // content is URI in this case
            try {
                data = savedFile.toURI().toString().getBytes(encoding);
            } catch (UnsupportedEncodingException e) {
                throw new XFormsException(e);
            }

        } else {
            // content is the data
            data = item.get();
        }
    }
    return data;
}

From source file:org.chiba.agent.web.servlet.HttpRequestHandler.java

protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)");
    }/*from   w w w  .  j  av a2s  .c o  m*/

    try {
        // update repeat indices
        Iterator iterator = uploads.keySet().iterator();
        String id;
        FileItem item;
        byte[] data;

        while (iterator.hasNext()) {
            id = (String) iterator.next();
            item = (FileItem) uploads.get(id);

            if (item.getSize() > 0) {
                LOGGER.debug("i'm here");
                String name = item.getName();
                if (name.contains("/")) {
                    name = name.substring(name.lastIndexOf('/') + 1);
                }
                if (name.contains("\\")) {
                    name = name.substring(name.lastIndexOf('\\') + 1);
                }
                if (this.xformsProcessor.isFileUpload(id, "anyURI")) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("found upload type 'anyURI'");
                    }

                    String localPath = new StringBuffer().append(System.currentTimeMillis()).append('/')
                            .append(name).toString();

                    File localFile = new File(this.uploadRoot, localPath);
                    localFile.getParentFile().mkdirs();
                    item.write(localFile);

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("saving data to path: " + localFile);
                    }

                    // todo: externalize file handling and uri generation
                    data = localFile.toURI().toString().getBytes("UTF-8");
                } else {
                    data = item.get();
                }

                this.xformsProcessor.setUploadValue(id, item.getContentType(), name, data);

                // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done'
                request.getSession().setAttribute(XFormsSession.ADAPTER_PREFIX + sessionKey + "-uploadInfo",
                        new UploadInfo(1, 0, 0, 0, "done"));
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("ignoring empty upload " + id);
                }
                // todo: removal ?
            }

            item.delete();
        }
    } catch (Exception e) {
        LOGGER.error(e);
        throw new XFormsException(e);
    }
}

From source file:org.chiba.web.servlet._HttpRequestHandler.java

protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException {
    LOGGER.info("updating " + uploads.keySet().size() + " uploads(s)");

    try {//from  www .j av  a  2  s. c  o  m
        // update repeat indices

        Iterator iterator = uploads.keySet().iterator();
        String id;
        FileItem item;
        byte[] data;
        while (iterator.hasNext()) {
            id = (String) iterator.next();
            item = (FileItem) uploads.get(id);

            if (item.getSize() > 0) {
                if (this.chibaBean.hasControlType(id, "anyURI")) {

                    String localPath = new StringBuffer().append('/').append(id).toString();
                    File localFile = new File(uploadRoot + this.sessionKey, localPath);

                    localFile.getParentFile().mkdirs();
                    item.write(localFile);
                    // todo: externalize file handling and uri generation
                    data = localFile.toURI().toString().getBytes("UTF-8");
                } else {
                    data = item.get();
                }

                this.chibaBean.updateControlValue(id, item.getContentType(), item.getName(), data);

                // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done'
                request.getSession().setAttribute(XFormsSession.ADAPTER_PREFIX + sessionKey + "-uploadInfo",
                        new UploadInfo(1, 0, 0, 0, "done"));
            } else {
                LOGGER.info("ignoring empty upload " + id);
                // todo: removal ?
            }

            item.delete();
        }

    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given
 * {@link HttpServletRequest}.//w  w w  .j  a  v a2 s  . c o  m
 *
 * @param postMethodProxyRequest    The {@link PostMethod} that we are configuring to send a multipart POST request
 * @param httpServletRequest    The {@link HttpServletRequest} that contains the mutlipart POST data to be sent via the {@link PostMethod}
 */
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(maxFileUploadSize);
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(HEADER_CONTENT_TYPE, multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:org.codemucker.testserver.capturing.CapturedFileItem.java

public CapturedFileItem(final FileItem item) {
    fieldName = item.getFieldName();//from  ww w.j  av a  2s  .co  m
    fileName = item.getName();
    size = item.getSize();
    contentType = item.getContentType();
    payloadBytes = item.get();
}

From source file:org.eclipse.che.api.workspace.server.stack.StackService.java

@POST
@Path("/{id}/icon")
@Consumes(MULTIPART_FORM_DATA)/*from   w w  w  .  j a  va  2s . com*/
@Produces(TEXT_PLAIN)
@GenerateLink(rel = LINK_REL_UPLOAD_ICON)
@ApiOperation(value = "Upload icon for required stack", notes = "This operation can be performed only by authorized stack owner")
@ApiResponses({ @ApiResponse(code = 200, message = "Image was successfully uploaded"),
        @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
        @ApiResponse(code = 403, message = "The user does not have access upload image for stack with required id"),
        @ApiResponse(code = 404, message = "The stack doesn't exist"),
        @ApiResponse(code = 500, message = "Internal server error occurred") })
public Response uploadIcon(@ApiParam("The image for stack") final Iterator<FileItem> formData,
        @ApiParam("The stack id") @PathParam("id") final String id)
        throws NotFoundException, ServerException, BadRequestException, ForbiddenException, ConflictException {
    if (formData.hasNext()) {
        FileItem fileItem = formData.next();
        StackIcon stackIcon = new StackIcon(fileItem.getName(), fileItem.getContentType(), fileItem.get());

        StackImpl stack = stackDao.getById(id);

        stack.setStackIcon(stackIcon);
        stackDao.update(stack);
    }
    return Response.ok().build();
}