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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:org.gatein.wcm.portlet.editor.views.UploadsActions.java

public String actionEditUpload(ActionRequest request, ActionResponse response, UserWcm userWcm) {
    String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR);
    FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir));
    PortletFileUpload upload = new PortletFileUpload(factory);
    try {//from w  w  w. j a  v  a2  s . c o  m
        List<FileItem> items = upload.parseRequest(request);
        FileItem file = null;
        String description = null;
        String editUploadId = null;
        for (FileItem item : items) {
            if (!item.isFormField()) {
                file = item;
            } else {
                if (item.getFieldName().equals("uploadFileDescription")) {
                    description = item.getString();
                } else if (item.getFieldName().equals("editUploadId")) {
                    editUploadId = item.getString();
                }
            }
        }
        Upload updateUpload = wcm.findUpload(new Long(editUploadId), userWcm);
        if (updateUpload != null) {
            if (file != null && file.getSize() > 0 && file.getName().length() > 0) {
                updateUpload.setFileName(file.getName());
                updateUpload.setMimeType(file.getContentType());
                updateUpload.setDescription(description);
                wcm.unlock(new Long(editUploadId), Wcm.LOCK.UPLOAD, userWcm);
                wcm.update(updateUpload, file.getInputStream(), userWcm);
            } else {
                if (description != null) {
                    updateUpload.setDescription(description);
                    wcm.unlock(new Long(editUploadId), Wcm.LOCK.UPLOAD, userWcm);
                    wcm.update(updateUpload, userWcm);
                }
            }
        }
        return Wcm.VIEWS.UPLOADS;
    } catch (Exception e) {
        log.warning("Error uploading file");
        e.printStackTrace();
        response.setRenderParameter("errorWcm", "Error uploading file " + e.toString());
    }
    return Wcm.VIEWS.UPLOADS;
}

From source file:org.geoserver.ows.Dispatcher.java

BufferedReader fileItemReader(FileItem fileItem) throws IOException {
    return RequestUtils.getBufferedXMLReader(fileItem.getInputStream(), XML_LOOKAHEAD);
}

From source file:org.getobjects.appserver.elements.WOFileUpload.java

@Override
public void takeValuesFromRequest(final WORequest _rq, final WOContext _ctx) {
    final Object cursor = _ctx.cursor();

    String formName = this.elementNameInContext(_ctx);
    Object formValue = _rq.formValueForKey(formName);

    if (this.writeValue != null)
        this.writeValue.setValue(formValue, cursor);

    if (formValue == null) {
        if (this.filePath != null)
            this.filePath.setValue(null, cursor);
        if (this.data != null)
            this.data.setValue(null, cursor);
    } else if (formValue instanceof String) {
        /* this happens if the enctype is not multipart/formdata */
        if (this.filePath != null)
            this.filePath.setStringValue((String) formValue, cursor);
    } else if (formValue instanceof FileItem) {
        FileItem fileItem = (FileItem) formValue;

        if (this.size != null)
            this.size.setValue(fileItem.getSize(), cursor);

        if (this.contentType != null)
            this.contentType.setStringValue(fileItem.getContentType(), cursor);

        if (this.filePath != null)
            this.filePath.setStringValue(fileItem.getName(), cursor);

        /* process content */

        if (this.data != null)
            this.data.setValue(fileItem.get(), cursor);
        else if (this.string != null) {
            // TODO: we could support a encoding get-binding
            this.string.setStringValue(fileItem.getString(), cursor);
        } else if (this.inputStream != null) {
            try {
                this.inputStream.setValue(fileItem.getInputStream(), cursor);
            } catch (IOException e) {
                log.error("failed to get input stream for upload file", e);
                this.inputStream.setValue(null, cursor);
            }/*from  www  . ja  v  a2s . c om*/
        }

        /* delete temporary file */

        if (this.deleteAfterPush != null) {
            if (this.deleteAfterPush.booleanValueInComponent(cursor))
                fileItem.delete();
        }
    } else
        log.warn("cannot process WOFileUpload value: " + formValue);
}

From source file:org.gluewine.rest_server.RESTServlet.java

/**
 * Parses the parameters from the form stored in the given map.
 *
 * @param rm The method to process.//from w  w  w .ja va 2s. c  om
 * @param formFields The fields to parse.
 * @param serializer The serializer to use.
 * @param params the parameter value array to fill in.
 * @param paramTypes the parameter types array.
 * @throws IOException If an error occurs.
 */
private void fillParamValuesFromForm(RESTMethod rm, Map<String, FileItem> formFields, RESTSerializer serializer,
        Object[] params, Class<?>[] paramTypes) throws IOException {
    for (int i = 0; i < params.length; i++) {
        if (params[i] != null)
            continue;

        RESTID id = AnnotationUtility.getAnnotations(RESTID.class, rm.getObject(), rm.getMethod(), i);
        if (id != null) {
            FileItem item = formFields.get(id.id());
            if (item != null) {
                String[] val = null;
                if (item.isFormField()) {
                    val = new String[] { item.getString("UTF-8") };
                    params[i] = serializer.deserialize(paramTypes[i], val);
                    if (logger.isTraceEnabled())
                        traceParameter(id.id(), val);
                } else {
                    if (id.mimetype()) {
                        params[i] = item.getContentType();
                    } else if (id.filename()) {
                        params[i] = item.getName();
                    } else {
                        try {
                            if (InputStream.class.isAssignableFrom(paramTypes[i])) {
                                params[i] = item.getInputStream();
                            } else {
                                File nf = new File(item.getName());
                                File f = File.createTempFile("___", "___" + nf.getName());
                                item.write(f);
                                if (File.class.isAssignableFrom(paramTypes[i])) {
                                    params[i] = f;
                                } else {
                                    logger.warn("File upload to string field for method " + rm.getMethod());
                                    params[i] = f.getAbsolutePath();
                                }
                            }
                        } catch (Exception e) {
                            throw new IOException(e.getMessage());
                        }
                    }
                }
            }
        }
    }
}

From source file:org.infoscoop.service.I18NService.java

/**
 * When we import a CSV file of globalization.
 * /* w ww  .ja  va 2s . c  om*/
 * @param type
 * @param country
 * @param lang
 */
public void replaceI18nByLocale(String type, String country, String lang, FileItem csvFile, String mode,
        Map countMap, List errorList, List defaultIdList) throws Exception {
    CSVReader csvReader = null;
    InputStreamReader is;

    boolean isSuccess = true;

    int insertCount = 0;
    int updateCount = 0;

    // In the case of all substitution, we delete all once.
    if (mode.equalsIgnoreCase("replace")) {
        this.i18NDAO.deleteI18NByLocale(type, country, lang);
    }

    try {
        is = new InputStreamReader(csvFile.getInputStream(), "Windows-31J");

        csvReader = new CSVReader(is);

        String[] nextLine = null;
        int lineNumber = 0;
        I18NImport ir;
        while ((nextLine = csvReader.readNext()) != null) {
            ir = new I18NImport(++lineNumber, nextLine, type, country, lang, defaultIdList);
            if (!ir.isError()) {
                // If it isn't error record, we register it.
                if (ir.execInsertUpdate(this.i18NDAO)) {
                    updateCount++;
                } else {
                    insertCount++;
                }
                defaultIdList.remove(ir.getId());
            } else {
                errorList.add(ir);
                isSuccess = false;
            }
        }
    } finally {
        if (csvReader != null)
            csvReader.close();
    }

    if (!isSuccess) {
        // rollback
        throw new I18NImportException("Because illegal data existed, the rollback is done.");
    }

    if (mode.equalsIgnoreCase("replace") && "ALL".equals(country) && "ALL".equals(lang)) {
        // fix #796 When there is the default ID that lost after substitution, we delete the other locale in the ID.
        String removeID;
        for (Iterator ite = defaultIdList.iterator(); ite.hasNext();) {
            removeID = (String) ite.next();
            i18NDAO.deleteI18NByIDWithoutDefault(type, removeID);
        }
    }

    this.i18NDAO.updateLastmodified(type);
    countMap.put("insertCount", new Integer(insertCount));
    countMap.put("updateCount", new Integer(updateCount));
}

From source file:org.jahia.ajax.gwt.content.server.GWTFileManagerUploadServlet.java

private void storeUploadedFile(String sessionID, final FileItem fileItem) {
    try {//from   w ww  . ja  v  a2s.co  m
        final InputStream contentStream = new BufferedInputStream(fileItem.getInputStream());
        try {
            getFileStorage().put(sessionID, fileItem.getName(), new UploadedPendingFile() {

                @Override
                public String getContentType() {
                    return fileItem.getContentType();
                }

                @Override
                public InputStream getContentStream() {
                    return contentStream;
                }

                @Override
                public void close() {
                }
            });
        } finally {
            contentStream.close();
        }
    } catch (IOException e) {
        throw new JahiaRuntimeException(e);
    }
}

From source file:org.jahia.ajax.gwt.content.server.GWTFileManagerUploadServlet.java

private int saveToJcr(JahiaUser user, FileItem item, String location, StringBuilder name) throws IOException {

    String filename = name.toString();
    if (logger.isDebugEnabled()) {
        logger.debug("item : " + item);
        logger.debug("destination : " + location);
        logger.debug("filename : " + filename);
        logger.debug("size : " + item.getSize());
    }/*from ww w  . j a  v  a  2  s  .c  o  m*/
    if (item == null || location == null || filename == null) {
        return UNKNOWN_ERROR;
    }

    JCRNodeWrapper locationFolder;
    try {
        locationFolder = JCRSessionFactory.getInstance().getCurrentUserSession().getNode(location);
    } catch (RepositoryException e) {
        logger.error(e.toString(), e);
        return BAD_LOCATION;
    }

    if (!locationFolder.hasPermission("jcr:addChildNodes") || locationFolder.isLocked()) {
        logger.debug("destination is not writable for user " + user.getName());
        return READONLY;
    }
    try {
        if (locationFolder.hasNode(JCRContentUtils.escapeLocalNodeName(filename))) {
            return EXISTS;
        }
        InputStream is = item.getInputStream();
        try {
            boolean versioningAvailable = false;
            if (locationFolder.getProvider().isVersioningAvailable()) {
                versioningAvailable = true;
            }
            if (versioningAvailable) {
                locationFolder.getSession().checkout(locationFolder);
            }
            JCRNodeWrapper node = locationFolder.uploadFile(filename, is,
                    JCRContentUtils.getMimeType(filename, item.getContentType()));
            node.getSession().save();
            if (!node.getName().equals(filename)) {
                name.delete(0, name.length());
                name.append(node.getName());
            }
            // Handle potential move of the node after save
            node = node.getSession().getNodeByIdentifier(node.getIdentifier());
            if (node.getProvider().isVersioningAvailable()) {
                node.checkpoint();
                JCRVersionService.getInstance().addVersionLabel(node, VersioningHelper
                        .getVersionLabel(node.getProperty("jcr:created").getDate().getTime().getTime()));
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
        locationFolder.saveSession();
    } catch (RepositoryException e) {
        logger.error("exception ", e);
        return UNKNOWN_ERROR;
    }
    return OK;
}

From source file:org.jbpm.bpel.web.DeploymentServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // parse request
    parseRequest(request);/*from ww w. ja v  a2  s  . c  o  m*/
    // read and deploy process definition
    FileItem fileItem = (FileItem) request.getAttribute(PARAM_PROCESS_ARCHIVE);
    String fileName = extractFileName(fileItem.getName());
    ProcessDefinition processDefinition = readProcessDefinition(fileItem.getInputStream(), fileName);
    deployProcessDefinition(processDefinition, fileName);
    // transfer web flow
    response.sendRedirect("processes.jsp");
}

From source file:org.jbpm.bpel.web.RegistrationServlet.java

private InputStream parseDescriptionFile(FileItem descriptionItem) throws ServletException, IOException {
    if (!PARAM_DESCRIPTION_FILE.equals(descriptionItem.getFieldName())) {
        throw new ServletException("expected parameter '" + PARAM_DESCRIPTION_FILE + "', found: "
                + descriptionItem.getFieldName());
    }//from w  ww.  ja v a  2s. c o  m

    if (descriptionItem.isFormField()) {
        throw new ServletException("parameter '" + PARAM_DESCRIPTION_FILE + "' is not an uploaded file");
    }

    if (descriptionItem.getSize() == 0)
        return null;

    String contentType = descriptionItem.getContentType();
    if (!contentType.startsWith(WebConstants.CONTENT_TYPE_XML)) {
        throw new ServletException(
                "parameter '" + PARAM_DESCRIPTION_FILE + "' is expected to have content type '"
                        + WebConstants.CONTENT_TYPE_XML + "', found: " + contentType);
    }

    return descriptionItem.getInputStream();
}

From source file:org.jbpm.console.ng.documents.backend.server.DocumentViewServlet.java

private String processUpload(final FileItem uploadItem, String folder) throws IOException {

    // If the file it doesn't exist.
    if ("".equals(uploadItem.getName())) {
        throw new IOException("No file selected.");
    }/*from   ww  w  . j  ava2s.  co  m*/

    uploadFile(uploadItem, folder);
    uploadItem.getInputStream().close();

    return "OK";
}