Example usage for org.apache.commons.fileupload FileItemIterator next

List of usage examples for org.apache.commons.fileupload FileItemIterator next

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemIterator next.

Prototype

FileItemStream next() throws FileUploadException, IOException;

Source Link

Document

Returns the next available FileItemStream .

Usage

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

/**
 * Request parameters are documented in/*from   w  w  w.  j  a v a  2  s. c  om*/
 * 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>();

    /*/* w ww .  jav  a 2 s.  c o  m*/
     * 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;
    InputStream in = null;//from w w  w.ja va2  s .c  om

    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;
    InputStream in = null;//from   www  .  j a va 2s .com

    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;
    InputStream in = null;/*from   www . java  2s. c o m*/

    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 {/*w ww .j  av  a2s .  co 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 a  2 s . c om*/
        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.restlet.example.ext.fileupload.FileUploadServerResource.java

@Post
public Representation accept(Representation entity) throws Exception {
    Representation result = null;/* w  ww.ja  v  a  2  s .  c om*/
    if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
        // 1/ Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1000240);

        // 2/ Create a new file upload handler based on the Restlet
        // FileUpload extension that will parse Restlet requests and
        // generates FileItems.
        RestletFileUpload upload = new RestletFileUpload(factory);

        // 3/ Request is parsed by the handler which generates a
        // list of FileItems
        FileItemIterator fileIterator = upload.getItemIterator(entity);

        // Process only the uploaded item called "fileToUpload"
        // and return back
        boolean found = false;
        while (fileIterator.hasNext() && !found) {
            FileItemStream fi = fileIterator.next();

            if (fi.getFieldName().equals("fileToUpload")) {
                // For the matter of sample code, it filters the multo
                // part form according to the field name.
                found = true;
                // consume the stream immediately, otherwise the stream
                // will be closed.
                StringBuilder sb = new StringBuilder("media type: ");
                sb.append(fi.getContentType()).append("\n");
                sb.append("file name : ");
                sb.append(fi.getName()).append("\n");
                BufferedReader br = new BufferedReader(new InputStreamReader(fi.openStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                sb.append("\n");
                result = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN);
            }
        }
    } else {
        // POST request with no entity.
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }

    return result;
}

From source file:org.retrostore.request.RequestDataImpl.java

/**
 * Parses a multipart request and gets its files and parameters.
 *//*from  ww  w .j  a va  2s. co  m*/
private static void parseMultipartContent(HttpServletRequest request, Map<String, String> formParams,
        List<UploadFile> uploadFiles) {
    if (!ServletFileUpload.isMultipartContent(request)) {
        return;
    }

    ServletFileUpload upload = new ServletFileUpload();
    try {
        FileItemIterator itemIterator = upload.getItemIterator(request);
        while (itemIterator.hasNext()) {
            FileItemStream file = itemIterator.next();
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            ByteStreams.copy(file.openStream(), bytesOut);
            byte[] bytes = bytesOut.toByteArray();

            // If an item has a name, we think it's a file, otherwise we treat it as a regular string
            // parameter.
            if (!Strings.isNullOrEmpty(file.getName())) {
                uploadFiles.add(new UploadFile(file.getFieldName(), file.getName(), bytes));
            } else {
                String str = new String(bytes, StandardCharsets.UTF_8);
                formParams.put(file.getFieldName(), str);
            }
        }
    } catch (FileUploadException | IOException e) {
        LOG.log(Level.WARNING, "Cannot parse request for filename.", e);
    }
}

From source file:org.sharegov.cirm.utils.PhotoUploadResource.java

/**
 * Accepts and processes a representation posted to the resource. As
 * response, the content of the uploaded file is sent back the client.
 *///from   w  ww .  j a v a2s. co m
@Post
public Representation accept(Representation entity) {
    // NOTE: the return media type here is TEXT_HTML because IE opens up a file download box
    // if it's APPLICATION_JSON as we'd want it.

    Representation rep = new StringRepresentation(GenUtils.ko("Unable to upload, bad request.").toString(),
            MediaType.TEXT_HTML);
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

            // 1/ Create a factory for disk-based file items
            //                DiskFileItemFactory factory = new DiskFileItemFactory();
            //                factory.setSizeThreshold(1000240);

            // 2/ Create a new file upload handler based on the Restlet
            // FileUpload extension that will parse Restlet requests and
            // generates FileItems.
            RestletFileUpload upload = new RestletFileUpload();
            //                List<FileItem> items;
            //
            //                // 3/ Request is parsed by the handler which generates a
            //                // list of FileItems

            InputStream is = null;
            Graphics2D g = null;
            FileOutputStream fos = null;
            ByteArrayOutputStream baos = null;

            try {
                FileItemIterator fit = upload.getItemIterator(entity);
                while (fit.hasNext()) {
                    FileItemStream stream = fit.next();
                    if (stream.getFieldName().equals("uploadImage")) {
                        String contentType = stream.getContentType();
                        if (contentType.startsWith("image")) {
                            String extn = contentType.substring(contentType.indexOf("/") + 1);
                            byte[] data = GenUtils.getBytesFromStream(stream.openStream(), true);
                            String filename = "image_" + Refs.idFactory.resolve().newId(null) + "." + extn;
                            //String filename = "srphoto_123" + "."+extn; // + OWLRefs.idFactory.resolve().newId("Photo"); // may add Photo class to ontology
                            File f = new File(StartUp.config.at("workingDir").asString() + "/src/uploaded",
                                    filename);

                            StringBuilder sb = new StringBuilder("");

                            String hostname = java.net.InetAddress.getLocalHost().getHostName();
                            boolean ssl = StartUp.config.is("ssl", true);
                            int port = ssl ? StartUp.config.at("ssl-port").asInteger()
                                    : StartUp.config.at("port").asInteger();
                            if (ssl)
                                sb.append("https://");
                            else
                                sb.append("http://");
                            sb.append(hostname);
                            if ((ssl && port != 443) || (!ssl && port != 80))
                                sb.append(":").append(port);
                            sb.append("/uploaded/");
                            sb.append(filename);

                            //Start : resize Image
                            int rw = 400;
                            int rh = 300;
                            is = new ByteArrayInputStream(data);
                            BufferedImage image = ImageIO.read(is);
                            int w = image.getWidth();
                            int h = image.getHeight();

                            if (w > rw) {
                                BufferedImage bi = new BufferedImage(rw, rh, image.getType());
                                g = bi.createGraphics();
                                g.drawImage(image, 0, 0, rw, rh, null);
                                baos = new ByteArrayOutputStream();
                                ImageIO.write(bi, extn, baos);
                                data = baos.toByteArray();
                            }
                            //End: resize Image

                            fos = new FileOutputStream(f);
                            fos.write(data);

                            Json j = GenUtils.ok().set("image", sb.toString());
                            //Json j = GenUtils.ok().set("image", filename);
                            rep = new StringRepresentation(j.toString(), (MediaType) MediaType.TEXT_HTML);
                        } else {
                            rep = new StringRepresentation(GenUtils.ko("Please upload only Images.").toString(),
                                    MediaType.TEXT_HTML);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
                if (baos != null) {
                    try {
                        baos.flush();
                        baos.close();
                    } catch (IOException e) {
                    }
                }
                if (g != null) {
                    g.dispose();
                }
            }
        }
    } else {
        // POST request with no entity.
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
    return rep;
}