Example usage for org.apache.commons.fileupload.util Streams asString

List of usage examples for org.apache.commons.fileupload.util Streams asString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.util Streams asString.

Prototype

public static String asString(InputStream pStream) throws IOException 

Source Link

Document

This convenience method allows to read a org.apache.commons.fileupload.FileItemStream 's content into a string.

Usage

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  w ww . j  av  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.polymap.rap.updownload.upload.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from  www  . j av  a  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 {/* ww w .j  a v a 2  s. com*/
        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.sigmah.server.endpoint.export.sigmah.ExportModelServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (ServletFileUpload.isMultipartContent(req)) {

        final Authentication authentication = retrieveAuthentication(req);
        boolean hasPermission = false;

        if (authentication != null) {
            final User user = authentication.getUser();
            ProfileDTO profile = SigmahAuthDictionaryServlet.aggregateProfiles(user, null, injector);
            hasPermission = ProfileUtils.isGranted(profile, GlobalPermissionEnum.VIEW_ADMIN);
        }// ww  w .  j  av a 2 s. c om

        if (hasPermission) {

            final ServletFileUpload fileUpload = new ServletFileUpload();

            final HashMap<String, String> properties = new HashMap<String, String>();
            byte[] data = null;

            try {
                final FileItemIterator iterator = fileUpload.getItemIterator(req);

                // Iterating on the fields sent into the request
                while (iterator.hasNext()) {

                    final FileItemStream item = iterator.next();
                    final String name = item.getFieldName();

                    final InputStream stream = item.openStream();

                    if (item.isFormField()) {
                        final String value = Streams.asString(stream);
                        LOG.debug("field '" + name + "' = '" + value + '\'');

                        // The current field is a property
                        properties.put(name, value);

                    } else {
                        // The current field is a file
                        LOG.debug("field '" + name + "' (FILE)");

                        final ByteArrayOutputStream serializedData = new ByteArrayOutputStream();
                        long dataSize = 0L;

                        int b = stream.read();

                        while (b != -1 && dataSize < MAXIMUM_FILE_SIZE) {
                            serializedData.write(b);

                            dataSize++;
                            b = stream.read();
                        }

                        stream.close();

                        data = serializedData.toByteArray();
                    }
                }

            } catch (FileUploadException ex) {
                LOG.warn("Error while receiving a serialized model.", ex);
            }

            if (data != null) {
                // A file has been received

                final String type = properties.get("type");
                final ModelHandler handler = handlers.get(type);

                if (handler != null) {

                    if (handler instanceof ProjectModelHandler) {
                        final String projectModelTypeAsString = properties.get("project-model-type");
                        try {
                            final ProjectModelType projectModelType = ProjectModelType
                                    .valueOf(projectModelTypeAsString);
                            ((ProjectModelHandler) handler).setProjectModelType(projectModelType);
                        } catch (IllegalArgumentException e) {
                            LOG.debug("Bad value for project model type: " + projectModelTypeAsString, e);
                        }
                    }

                    final ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

                    try {
                        handler.importModel(inputStream, injector.getInstance(EntityManager.class),
                                authentication);

                    } catch (ExportException ex) {
                        LOG.error("Model import error, type: " + type, ex);
                        resp.sendError(500);
                    }

                } else {
                    LOG.warn("The asked model type (" + type + ") doesn't have any handler registered.");
                    resp.sendError(501);
                }
            } else {
                LOG.warn("No file has been received.");
                resp.sendError(400);
            }
        } else {
            LOG.warn("Unauthorized access to the import service from user " + authentication);
            resp.sendError(401);
        }

    } else {
        LOG.warn("The request doesn't have the correct enctype.");
        resp.sendError(400);
    }
}

From source file:org.sigmah.server.servlet.ImportServlet.java

private byte[] readFileAndProperties(final HttpServletRequest request, final Map<String, String> properties)
        throws FileUploadException, IOException {
    byte[] data = null;
    final ServletFileUpload fileUpload = new ServletFileUpload();

    final FileItemIterator iterator = fileUpload.getItemIterator(request);

    // Iterating on the fields sent into the request
    while (iterator.hasNext()) {

        final FileItemStream item = iterator.next();
        final String name = item.getFieldName();

        final InputStream stream = item.openStream();

        if (item.isFormField()) {

            final String value = Streams.asString(stream);

            LOG.debug("field '" + name + "' = '" + value + '\'');

            // The current field is a property
            properties.put(name, value);

        } else {// w  w w.jav  a2  s  . c o  m
            // The current field is a file
            LOG.debug("field '" + name + "' (FILE)");

            final ByteArrayOutputStream serializedData = new ByteArrayOutputStream();
            long dataSize = 0L;

            int b = stream.read();

            while (b != -1 && dataSize < MAXIMUM_FILE_SIZE) {
                serializedData.write(b);

                dataSize++;
                b = stream.read();
            }

            stream.close();

            data = serializedData.toByteArray();
        }
    }

    return data;
}

From source file:org.sosy_lab.cpachecker.appengine.server.resource.TasksServerResource.java

@Override
public Representation createTaskFromHtml(Representation input) throws IOException {
    List<String> errors = new LinkedList<>();
    Map<String, Object> settings = new HashMap<>();
    Map<String, String> options = new HashMap<>();

    ServletFileUpload upload = new ServletFileUpload();
    try {/* ww  w.jav a 2 s. c  o  m*/
        FileItemIterator iter = upload.getItemIterator(ServletUtils.getRequest(getRequest()));
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream);
                switch (item.getFieldName()) {
                case "specification":
                    value = (value.equals("")) ? null : value;
                    settings.put("specification", value);
                    break;
                case "configuration":
                    value = (value.equals("")) ? null : value;
                    settings.put("configuration", value);
                    break;
                case "disableOutput":
                    options.put("output.disable", "true");
                    break;
                case "disableExportStatistics":
                    options.put("statistics.export", "false");
                    break;
                case "dumpConfig":
                    options.put("configuration.dumpFile", "UsedConfiguration.properties");
                    break;
                case "logLevel":
                    options.put("log.level", value);
                    break;
                case "machineModel":
                    options.put("analysis.machineModel", value);
                    break;
                case "wallTime":
                    options.put("limits.time.wall", value);
                    break;
                case "instanceType":
                    options.put("gae.instanceType", value);
                    break;
                case "programText":
                    if (!value.isEmpty()) {
                        settings.put("programName", "program.c");
                        settings.put("programText", value);
                    }
                    break;
                }
            } else {
                if (settings.get("programText") == null) {
                    settings.put("programName", item.getName());
                    settings.put("programText", IOUtils.toString(stream));
                }
            }
        }
    } catch (FileUploadException | IOException e) {
        getLogger().log(Level.WARNING, "Could not upload program file.", e);
        errors.add("task.program.CouldNotUpload");
    }

    settings.put("options", options);

    Task task = null;
    if (errors.isEmpty()) {
        TaskBuilder taskBuilder = new TaskBuilder();
        task = taskBuilder.fromMap(settings);
        errors = taskBuilder.getErrors();
    }

    if (errors.isEmpty()) {
        try {
            Configuration config = Configuration.builder().setOptions(task.getOptions()).build();
            new GAETaskQueueTaskExecutor(config).execute(task);
        } catch (InvalidConfigurationException e) {
            errors.add("error.invalidConfiguration");
        }
    }

    if (errors.isEmpty()) {
        getResponse().setStatus(Status.SUCCESS_CREATED);
        redirectSeeOther("/tasks/" + task.getKey());
        return getResponseEntity();
    }

    getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    return FreemarkerUtil.templateBuilder().context(getContext()).addData("task", task)
            .addData("errors", errors).addData("allowedOptions", DefaultOptions.getDefaultOptions())
            .addData("defaultOptions", DefaultOptions.getImmutableOptions())
            .addData("specifications", DefaultOptions.getSpecifications())
            .addData("configurations", DefaultOptions.getConfigurations())
            .addData("cpacheckerVersion", CPAchecker.getCPAcheckerVersion()).templateName("root.ftl").build();
}

From source file:org.ut.biolab.medsavant.MedSavantServlet.java

private Upload[] handleUploads(FileItemIterator iter)
        throws FileUploadException, IOException, InterruptedException {
    List<Upload> uploads = new ArrayList<Upload>();

    FileItemStream streamToUpload = null;
    long filesize = -1;

    String sn = null;/* www . ja va  2  s  . c  om*/
    String fn = null;

    while (iter.hasNext()) {

        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        // System.out.println("Got file " + name);
        if (item.isFormField()) {
            if (name.startsWith("size_")) {
                sn = name.split("_")[1];
                filesize = Long.parseLong(Streams.asString(stream));
            }
        } else if (name.startsWith("file_")) {
            streamToUpload = item;
        } else {
            throw new IllegalArgumentException("Unrecognized file detected with field name " + name);
        }
        if (streamToUpload != null) {
            // Do the upload               
            int streamId = copyStreamToServer(streamToUpload.openStream(), streamToUpload.getName(),
                    (sn != null && fn != null && sn.equals(fn)) ? filesize : -1);
            if (streamId >= 0) {
                uploads.add(new Upload(name, streamId));
            }
        }

    }

    return uploads.toArray(new Upload[uploads.size()]);
}

From source file:pl.exsio.plupload.PluploadChunkFactory.java

private static void setChunkField(PluploadChunk chunk, FileItemStream item)
        throws NumberFormatException, IOException {
    String value = Streams.asString(item.openStream());
    switch (item.getFieldName()) {
    case "fileId":
        chunk.setFileId(value);/*from   w w w  .j av a 2s .  c o m*/
        break;
    case "name":
        chunk.setName(value);
        break;
    case "chunk":
        chunk.setChunk(Integer.parseInt(value));
        break;
    case "chunks":
        chunk.setChunks(Integer.parseInt(value));
    }
}

From source file:tech.oleks.pmtalk.PmTalkServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Order o = new Order();
    ServletFileUpload upload = new ServletFileUpload();
    try {//from  w w  w  .j ava  2 s  .c  o  m
        FileItemIterator it = upload.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            InputStream fieldValue = item.openStream();
            String fieldName = item.getFieldName();
            if ("candidate".equals(fieldName)) {
                String candidate = Streams.asString(fieldValue);
                o.setCandidate(candidate);
            } else if ("staffing".equals(fieldName)) {
                String staffingLink = Streams.asString(fieldValue);
                o.setStaffingLink(staffingLink);
            } else if ("resume".equals(fieldName)) {
                FileUpload resume = new FileUpload();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(fieldValue, os);
                resume.setStream(new ByteArrayInputStream(os.toByteArray()));
                resume.setContentType(item.getContentType());
                resume.setFileName(item.getName());
                o.setResume(resume);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    pmTalkService.minimal(o);
    req.setAttribute("order", o);
    if (o.getErrors() != null) {
        forward("/form.jsp", req, resp);
    } else {
        forward("/created.jsp", req, resp);
    }
}

From source file:uk.ac.ebi.sail.server.service.UploadSvc.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

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

    String res = null;// w w  w. j  a va 2s .  co  m
    int studyID = -1;
    int collectionID = -1;

    String fileContent = null;

    String upType = null;

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                if ("CollectionID".equals(name)) {
                    try {
                        collectionID = Integer.parseInt(Streams.asString(stream));
                    } catch (Exception e) {
                    }
                }
                if ("StudyID".equals(name)) {
                    try {
                        studyID = Integer.parseInt(Streams.asString(stream));
                    } catch (Exception e) {
                    }
                } else if ("UploadType".equals(name)) {
                    upType = Streams.asString(stream);
                }

                //     System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
            } else {
                //     System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
                InputStream uploadedStream = item.openStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                StreamPump.doPump(uploadedStream, baos);

                byte[] barr = baos.toByteArray();

                if ((barr[0] == -1 && barr[1] == -2) || (barr[0] == -2 && barr[1] == -1))
                    fileContent = new String(barr, "UTF-16");
                else
                    fileContent = new String(barr);
            }
        }
    } catch (Exception ex) {
        res = ex.getMessage();
        ex.printStackTrace();
    }

    if (fileContent != null) {
        if ("AvailabilityData".equals(upType)) {
            if (collectionID != -1) {
                try {
                    DataManager.getInstance().importData(fileContent, collectionID);
                } catch (Exception ex) {
                    res = ex.getMessage();
                    ex.printStackTrace();
                }
            } else
                res = "Invalid or absent collection ID";
        } else if ("RelationMap".equals(upType)) {
            try {
                DataManager.getInstance().importRelations(new String(fileContent));
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }
        } else if ("Study2SampleRelation".equals(upType)) {
            try {
                DataManager.getInstance().importSample2StudyRelations(new String(fileContent), studyID,
                        collectionID);
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }
        } else {
            try {
                DataManager.getInstance().importParameters(fileContent);
            } catch (ParseException pex) {
                res = "Line " + pex.getLineNumber() + ": " + pex.getMessage();
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }

        }

    } else {
        res = "File content not found";
    }

    JSONObject response = null;
    try {
        response = new JSONObject();
        response.put("success", res == null);
        response.put("error", res == null ? "uploaded successfully" : res);
        response.put("code", "232");
    } catch (Exception e) {

    }

    Writer w = new OutputStreamWriter(resp.getOutputStream());
    w.write(response.toString());
    System.out.println(response.toString());
    w.close();
    resp.setStatus(HttpServletResponse.SC_OK);
}