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:org.openehealth.ipf.platform.camel.lbs.http.process.HttpResourceHandler.java

private void extractFromSinglePart(String subUnit, ResourceList resources, FileItemIterator iter)
        throws Exception {
    FileItemStream next = iter.next();
    InputStream inputStream = next.openStream();
    try {//from  w  ww. j  av  a 2 s  .co  m
        handleResource(subUnit, resources, next.getContentType(), next.getName(), next.getFieldName(),
                inputStream);
    } finally {
        inputStream.close();
    }
}

From source file:org.operamasks.faces.render.widget.AjaxFileUploadRenderer.java

private InputStream openStream(FileItemStream item, UIFileUpload fileUpload) throws IOException {
    if (fileUpload != null && fileUpload.getMaxSize() != null)
        return new LimitedSizeInputStream(item, fileUpload.getMaxSize());

    return item.openStream();
}

From source file:org.oryxeditor.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in//ww  w. java 2 s  . co  m
 * editor/test/examples/stencilset-extension-generator.xhtml
 * The parameter 'csvFile' is always required.
 * An example CSV file can be found in
 * editor/test/examples/design-thinking-example-data.csv
 * which has been exported using OpenOffice.org from
 * editor/test/examples/design-thinking-example-data.ods
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.baseUrl = Repository.getBaseUrl(request);
    this.repository = new Repository(baseUrl);

    // parameters and their default values
    String modelNamePrefix = "Generated Model using ";
    String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX;
    String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH;
    String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET;
    String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL;
    List<String> stencilSetExtensionUrls = new ArrayList<String>();
    String[] columnPropertyMapping = null;
    String[] csvHeader = null;
    List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>();
    String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator.";
    String additionalERDFContentForGeneratedModel = "";
    String[] modelTags = null;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

        // Parse the request
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // ordinary form field
                    String value = Streams.asString(stream);
                    //System.out.println("Form field " + name + " with value "
                    //    + value + " detected.");
                    if (name.equals("modelNamePrefix")) {
                        modelNamePrefix = value;
                    } else if (name.equals("stencilSetExtensionNamePrefix")) {
                        stencilSetExtensionNamePrefix = value;
                    } else if (name.equals("baseStencilSetPath")) {
                        baseStencilSetPath = value;
                    } else if (name.equals("baseStencilSet")) {
                        baseStencilSet = value;
                    } else if (name.equals("stencilSetExtension")) {
                        stencilSetExtensionUrls.add(value);
                    } else if (name.equals("baseStencil")) {
                        baseStencil = value;
                    } else if (name.equals("columnPropertyMapping")) {
                        columnPropertyMapping = value.split(",");
                    } else if (name.equals("modelDescription")) {
                        modelDescription = value;
                    } else if (name.equals("modelTags")) {
                        modelTags = value.split(",");
                    } else if (name.equals("additionalERDFContentForGeneratedModel")) {
                        additionalERDFContentForGeneratedModel = value;
                    }
                } else {
                    // file field
                    //System.out.println("File field " + name + " with file name "
                    //    + item.getName() + " detected.");
                    // Process the input stream
                    if (name.equals("csvFile")) {
                        CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream),
                                CsvPreference.EXCEL_PREFERENCE);
                        csvHeader = csvFileReader.getCSVHeader(true);
                        if (columnPropertyMapping != null && columnPropertyMapping.length > 0) {
                            csvHeader = columnPropertyMapping;
                        }
                        Map<String, String> row;
                        while ((row = csvFileReader.read(csvHeader)) != null) {
                            stencilPropertyMatrix.add(row);
                        }
                    }
                }
            }

            // generate stencil set
            Date creationDate = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS");
            String stencilSetExtensionName = stencilSetExtensionNamePrefix + " "
                    + dateFormat.format(creationDate);

            stencilSetExtensionUrls
                    .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName,
                            stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil));

            // generate new model
            String modelName = modelNamePrefix + stencilSetExtensionName;
            String model = repository.generateERDF(UUID.randomUUID().toString(),
                    additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet,
                    stencilSetExtensionUrls, modelName, modelDescription);
            String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription,
                    baseStencilSet, baseStencilSetPath);

            // hack for reverse proxies:
            modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://"));

            // tag model
            if (modelTags != null) {
                for (String tagName : modelTags) {
                    repository.addTag(modelUrl, tagName.trim());
                }
            }

            // redirect client to editor with that newly generated model
            response.setHeader("Location", modelUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // TODO Add some error message
    }
}

From source file:org.owasp.esapi.waf.internal.InterceptingHTTPServletRequest.java

public InterceptingHTTPServletRequest(HttpServletRequest request) throws FileUploadException, IOException {

    super(request);

    allParameters = new Vector<Parameter>();
    allParameterNames = new Vector<String>();

    /*/*from   ww w .j a v a 2 s .  com*/
     * Get all the regular parameters.
     */

    Enumeration e = request.getParameterNames();

    while (e.hasMoreElements()) {
        String param = (String) e.nextElement();
        allParameters.add(new Parameter(param, request.getParameter(param), false));
        allParameterNames.add(param);
    }

    /*
     * Get all the multipart fields.
     */

    isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        requestBody = new RandomAccessFile(File.createTempFile("oew", "mpc"), "rw");

        byte buffer[] = new byte[CHUNKED_BUFFER_SIZE];

        long size = 0;
        int len = 0;

        while (len != -1 && size <= Integer.MAX_VALUE) {
            len = request.getInputStream().read(buffer, 0, CHUNKED_BUFFER_SIZE);
            if (len != -1) {
                size += len;
                requestBody.write(buffer, 0, len);
            }
        }

        is = new RAFInputStream(requestBody);

        ServletFileUpload sfu = new ServletFileUpload();
        FileItemIterator iter = sfu.getItemIterator(this);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();

            /*
             * If this is a regular form field, add it to our
             * parameter collection.
             */

            if (item.isFormField()) {

                String value = Streams.asString(stream);

                allParameters.add(new Parameter(name, value, true));
                allParameterNames.add(name);

            } else {
                /*
                 * This is a multipart content that is not a
                 * regular form field. Nothing to do here.
                 */

            }

        }

        requestBody.seek(0);

    }

}

From source file:org.plista.kornakapi.web.servlets.BatchAddCandidatesServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int batchSize = getParameterAsInt(request, Parameters.BATCH_SIZE, Parameters.DEFAULT_BATCH_SIZE);

    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator fileItems;// ww  w  .j av  a2 s. co m
    InputStream in = null;

    boolean fileProcessed = false;

    Storage storage = this.getDomainIndependetStorage();

    try {
        fileItems = upload.getItemIterator(request);
        while (fileItems.hasNext()) {

            FileItemStream item = fileItems.next();

            if (Parameters.FILE.equals(item.getFieldName()) && !item.isFormField()) {

                in = item.openStream();
                Iterator<Candidate> candidates = new CSVCandidateFileIterator(in);

                storage.batchAddCandidates(candidates, batchSize);

                fileProcessed = true;

                break;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(in);
    }

    if (!fileProcessed) {
        throw new IllegalStateException("Unable to find supplied data file!");
    }
}

From source file:org.plista.kornakapi.web.servlets.BatchDeleteCandidatesServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int batchSize = getParameterAsInt(request, Parameters.BATCH_SIZE, Parameters.DEFAULT_BATCH_SIZE);

    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator fileItems;//from  w  w w .  j a v  a2s  . c o  m
    InputStream in = null;

    boolean fileProcessed = false;

    Storage storage = this.getDomainIndependetStorage();
    try {
        fileItems = upload.getItemIterator(request);
        while (fileItems.hasNext()) {

            FileItemStream item = fileItems.next();

            if (Parameters.FILE.equals(item.getFieldName()) && !item.isFormField()) {

                in = item.openStream();
                Iterator<Candidate> candidates = new CSVCandidateFileIterator(in);

                storage.batchDeleteCandidates(candidates, batchSize);

                fileProcessed = true;

                break;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(in);
    }

    if (!fileProcessed) {
        throw new IllegalStateException("Unable to find supplied data file!");
    }
}

From source file:org.plista.kornakapi.web.servlets.BatchSetPreferencesServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int batchSize = getParameterAsInt(request, Parameters.BATCH_SIZE, Parameters.DEFAULT_BATCH_SIZE);

    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator fileItems;//from  ww  w  .ja va 2 s .co m
    InputStream in = null;

    boolean fileProcessed = false;

    Storage storage = this.getDomainIndependetStorage();

    try {
        fileItems = upload.getItemIterator(request);
        while (fileItems.hasNext()) {

            FileItemStream item = fileItems.next();

            if (Parameters.FILE.equals(item.getFieldName()) && !item.isFormField()) {

                in = item.openStream();
                Iterator<Preference> preferences = new CSVPreferenceFileIterator(in);

                storage.batchSetPreferences(preferences, batchSize);

                fileProcessed = true;

                break;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(in);
    }

    if (!fileProcessed) {
        throw new IllegalStateException("Unable to find supplied data file!");
    }
}

From source file:org.polymap.rap.updownload.upload.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from  w ww  .  j  a  va  2 s.  c  o  m*/
        FileItemIterator it = fileUpload.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            String name = item.getFieldName();
            InputStream in = item.openStream();
            try {
                if (item.isFormField()) {
                    log.info("Form field " + name + " with value " + Streams.asString(in) + " detected.");
                } else {
                    log.info("File field " + name + " with file name " + item.getName() + " detected.");

                    String key = req.getParameter("handler");
                    assert key != null;
                    IUploadHandler handler = handlers.get(key);
                    // for the upload field we always get just one item (which has the length of the request!?)
                    int length = req.getContentLength();
                    handler.uploadStarted(item.getName(), item.getContentType(), length, in);
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } catch (Exception e) {
        log.warn("", e);
        throw new RuntimeException(e);
    }
}

From source file:org.polymap.rap.updownload.upload.UploadService.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {/*from   w  w  w  .j  a  v  a2  s  . co m*/
        FileItemIterator it = fileUpload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();

            try (InputStream in = item.openStream()) {
                if (item.isFormField()) {
                    log.info("Form field " + item.getFieldName() + " with value " + Streams.asString(in)
                            + " detected.");
                } else {
                    log.info("File field " + item.getFieldName() + " with file name " + item.getName()
                            + " detected.");

                    String handlerId = request.getParameter(ID_REQUEST_PARAM);
                    assert handlerId != null;
                    IUploadHandler handler = handlers.get(handlerId);
                    ClientFile clientFile = new ClientFile() {
                        @Override
                        public String getName() {
                            return item.getName();
                        }

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

                        @Override
                        public long getSize() {
                            // for the upload field we always get just one item (which has the length of the request!?)
                            return request.getContentLength();
                        }
                    };
                    handler.uploadStarted(clientFile, in);
                }
            }
        }
    } catch (Exception e) {
        log.warn("", e);
        throw new RuntimeException(e);
    }
}

From source file:org.rapidcontext.app.web.AppWebService.java

/**
 * Processes a file upload request. This is used when files are
 * POST:ed to the special upload URL.//from   w  w w.j  av  a2  s.  c om
 *
 * @param request        the request to process
 */
protected void processUpload(Request request) {
    Session session = (Session) Session.activeSession.get();
    if (session == null) {
        errorUnauthorized(request);
        return;
    }
    try {
        FileItemStream stream = request.getNextFile();
        if (stream == null) {
            errorBadRequest(request, "Missing file data");
            return;
        }
        String fileName = stream.getName();
        if (fileName.lastIndexOf("/") >= 0) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        if (fileName.lastIndexOf("\\") >= 0) {
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
        }
        String fileId = request.getPath();
        while (fileId != null && fileId.startsWith("/")) {
            fileId = fileId.substring(1);
        }
        if (fileId == null || fileId.trim().length() == 0) {
            fileId = fileName;
        }
        session.removeFile(fileId);
        File file = FileUtil.tempFile(fileName);
        FileUtil.copy(stream.openStream(), file);
        session.addFile(fileId, file);
        request.sendText(Mime.TEXT[0], "Session file " + fileId + " uploaded");
    } catch (IOException e) {
        LOG.log(Level.WARNING, "failed to process file upload", e);
        errorBadRequest(request, e.getMessage());
    }
}