Example usage for org.apache.commons.fileupload FileItemStream isFormField

List of usage examples for org.apache.commons.fileupload FileItemStream isFormField

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream isFormField.

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

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 {/*from w w w  .j av  a 2  s.  com*/
        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.synchronoss.cloud.nio.multipart.FunctionalTest.java

NioMultipartParserListener nioMultipartParserListenerVerifier(final FileItemIterator fileItemIterator,
        final AtomicBoolean finished) {

    return new NioMultipartParserListener() {

        AtomicInteger partIndex = new AtomicInteger(0);

        @Override/*  w  w  w  . jav  a 2  s . com*/
        public void onPartFinished(StreamStorage partBodyStreamStorage,
                Map<String, List<String>> headersFromPart) {
            log.info("<<<<< On part complete [" + (partIndex.addAndGet(1)) + "] >>>>>>");
            assertFileItemIteratorHasNext(true);
            final FileItemStream fileItemStream = fileItemIteratorNext();
            assertHeadersAreEqual(fileItemStream.getHeaders(), headersFromPart);
            assertInputStreamsAreEqual(fileItemStreamInputStream(fileItemStream),
                    partBodyStreamStorage.getInputStream());
        }

        @Override
        public void onFormFieldPartFinished(String fieldName, String fieldValue,
                Map<String, List<String>> headersFromPart) {
            log.info("<<<<< On form field complete [" + (partIndex.addAndGet(1)) + "] >>>>>>");
            assertFileItemIteratorHasNext(true);
            final FileItemStream fileItemStream = fileItemIteratorNext();
            assertTrue(fileItemStream.isFormField());
            Assert.assertEquals(fieldName, fileItemStream.getFieldName());
            try {
                Assert.assertEquals(fieldValue, IOUtils.toString(fileItemStream.openStream()));
            } catch (Exception e) {
                throw new IllegalStateException("Unable to assert field value", e);
            }
        }

        @Override
        public void onNestedPartStarted(Map<String, List<String>> headersFromParentPart) {
            log.info("<<<<< On form field complete [" + (partIndex) + "] >>>>>>");
        }

        @Override
        public void onAllPartsFinished() {
            log.info("<<<<< On all parts read: Number of parts [" + partIndex.get() + "] >>>>>>");
            assertFileItemIteratorHasNext(false);
            finished.set(true);
        }

        @Override
        public void onNestedPartFinished() {
            log.info("<<<<< On form field complete [" + (partIndex) + "] >>>>>>");
        }

        @Override
        public void onError(String message, Throwable cause) {
            log.info("<<<<< On error. Part " + partIndex.get() + "] >>>>>>");
            finished.set(true);
            log.error(message, cause);
            fail("Got an error from the parser");
        }

        InputStream fileItemStreamInputStream(final FileItemStream fileItemStream) {
            try {
                return fileItemStream.openStream();
            } catch (Exception e) {
                throw new IllegalStateException("Unable to open the file item inputstream", e);
            }
        }

        void assertFileItemIteratorHasNext(boolean hasNext) {
            try {
                assertTrue("File iterator has next is not " + hasNext, hasNext == fileItemIterator.hasNext());
            } catch (Exception e) {
                throw new IllegalStateException("Unable to verify if the FileItemIterator has a next", e);
            }
        }

        FileItemStream fileItemIteratorNext() {
            try {
                return fileItemIterator.next();
            } catch (Exception e) {
                throw new IllegalStateException("Unable to retrieve the next FileItemStream", e);
            }
        }

    };
}

From source file:org.tangram.components.servlet.ServletRequestParameterAccess.java

/**
 * Weak visibility to avoid direct instanciation.
 *//*www.  j  a va 2  s .  co m*/
@SuppressWarnings("unchecked")
ServletRequestParameterAccess(HttpServletRequest request, long uploadFileMaxSize) {
    final String reqContentType = request.getContentType();
    LOG.debug("() uploadFileMaxSize={} request.contentType={}", uploadFileMaxSize, reqContentType);
    if (StringUtils.isNotBlank(reqContentType) && reqContentType.startsWith("multipart/form-data")) {
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(uploadFileMaxSize);
        try {
            for (FileItemIterator itemIterator = upload.getItemIterator(request); itemIterator.hasNext();) {
                FileItemStream item = itemIterator.next();
                String fieldName = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    String[] value = parameterMap.get(item.getFieldName());
                    int i = 0;
                    if (value == null) {
                        value = new String[1];
                    } else {
                        String[] newValue = new String[value.length + 1];
                        System.arraycopy(value, 0, newValue, 0, value.length);
                        i = value.length;
                        value = newValue;
                    } // if
                    value[i] = Streams.asString(stream, "UTF-8");
                    LOG.debug("() request parameter {}='{}'", fieldName, value[0]);
                    parameterMap.put(item.getFieldName(), value);
                } else {
                    try {
                        LOG.debug("() item {} :{}", item.getName(), item.getContentType());
                        final byte[] bytes = IOUtils.toByteArray(stream);
                        if (bytes.length > 0) {
                            originalNames.put(fieldName, item.getName());
                            blobs.put(fieldName, bytes);
                        } // if
                    } catch (IOException ex) {
                        LOG.error("()", ex);
                        if (ex.getCause() instanceof FileUploadBase.FileSizeLimitExceededException) {
                            throw new RuntimeException(ex.getCause().getMessage()); // NOPMD we want to lose parts of our stack trace!
                        } // if
                    } // try/catch
                } // if
            } // for
        } catch (FileUploadException | IOException ex) {
            LOG.error("()", ex);
        } // try/catch
    } else {
        parameterMap = request.getParameterMap();
    } // if
}

From source file:org.tangram.spring.StreamingMultipartResolver.java

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);
    String encoding = determineEncoding(request);
    Map<String, String[]> multipartParameters = new HashMap<>();
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>();
    Map<String, String> multipartFileContentTypes = new HashMap<>();

    try {/*from ww w.  j  a  va  2s  .co  m*/
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream, encoding);
                String[] curParam = multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }
            } else {
                try {
                    MultipartFile file = new StreamingMultipartFile(item);
                    multipartFiles.add(name, file);
                    multipartFileContentTypes.put(name, file.getContentType());
                } catch (final IOException e) {
                    LOG.warn("({})", e.getCause().getMessage(), e);
                    MultipartFile file = new MultipartFile() {

                        @Override
                        public String getName() {
                            return "";
                        }

                        @Override
                        public String getOriginalFilename() {
                            return e.getCause().getMessage();
                        }

                        @Override
                        public String getContentType() {
                            return ERROR;
                        }

                        @Override
                        public boolean isEmpty() {
                            return true;
                        }

                        @Override
                        public long getSize() {
                            return 0L;
                        }

                        @Override
                        public byte[] getBytes() throws IOException {
                            return new byte[0];
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return null;
                        }

                        @Override
                        public void transferTo(File file) throws IOException, IllegalStateException {
                            throw new UnsupportedOperationException("NYI", e);
                        }
                    };
                    multipartFiles.add(name, file);
                    multipartFileContentTypes.put(name, file.getContentType());
                } // try/catch
            } // if
        } // while
    } catch (IOException | FileUploadException e) {
        throw new MultipartException("Error uploading a file", e);
    } // try/catch

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters,
            multipartFileContentTypes);
}

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;/* ww  w.java 2  s  .  c  o  m*/
    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:org.vosao.servlet.FileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //logger.info("File upload...");
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(MAX_SIZE);//ww w. j  a  v a 2s  . c  om
    upload.setHeaderEncoding("UTF-8");
    String message = null;
    Map<String, String> parameters = new HashMap<String, String>();
    List<UploadItem> uploadItems = new ArrayList<UploadItem>();
    try {
        FileItemIterator iter;
        try {
            iter = upload.getItemIterator(request);
            FileItemStream imageFileItem = null;
            String folder = null;
            InputStream stream = null;
            InputStream filestream = null;
            byte[] fileData = null;
            parameters.put(IMAGE_UPLOAD_PAGE_ID,
                    VosaoContext.getInstance().getSession().getString(IMAGE_UPLOAD_PAGE_ID));

            if (request.getParameter("CKEditorFuncNum") != null) {
                ckeditorFuncNum = request.getParameter("CKEditorFuncNum");
            }
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                stream = item.openStream();
                if (item.isFormField()) {
                    parameters.put(item.getFieldName(), Streams.asString(stream, "UTF-8"));
                } else {
                    UploadItem uploadItem = new UploadItem();
                    uploadItem.item = item;
                    uploadItem.data = StreamUtil.readFileStream(stream);
                    uploadItems.add(uploadItem);
                }
            }
            //logger.info(parameters.toString());
            for (UploadItem item : uploadItems) {
                message = processFile(item.item, item.data, parameters);
            }
        } catch (FileUploadException e) {
            logger.error(Messages.get("request_parsing_error"));
            throw new UploadException(Messages.get("request_parsing_error"));
        }
    } catch (UploadException e) {
        message = createMessage("error", e.getMessage());
        logger.error(message);
    }
    if (isCKeditorUpload(parameters)) {
        response.setContentType("text/html");
    } else {
        response.setContentType("text/plain");
    }
    response.setStatus(200);
    response.getWriter().write(message);
}

From source file:org.vosao.servlet.FormSendServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String message = null;//www . j a va2 s .com
    Map<String, String> parameters = new HashMap<String, String>();
    List<FileItem> files = new ArrayList<FileItem>();
    try {
        if (request.getContentType().startsWith("multipart/form-data")) {
            ServletFileUpload upload = new ServletFileUpload();
            upload.setFileSizeMax(MAX_SIZE);
            upload.setHeaderEncoding("UTF-8");
            FileItemIterator iter;
            try {
                iter = upload.getItemIterator(request);
                InputStream stream = null;
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    stream = item.openStream();
                    if (item.isFormField()) {
                        parameters.put(item.getFieldName(), Streams.asString(stream, "UTF-8"));
                    } else {
                        files.add(new FileItem(item, StreamUtil.readFileStream(stream)));
                    }
                }
            } catch (FileUploadException e) {
                logger.error(e.getMessage());
                throw new UploadException(Messages.get("request_parsing_error"));
            }
        } else {
            for (Object key : request.getParameterMap().keySet()) {
                String paramName = (String) key;
                parameters.put(paramName, request.getParameter(paramName));
            }
        }
        message = processForm(parameters, files, request);
    } catch (UploadException e) {
        message = createMessage("error", e.getMessage());
        logger.error(message);
    } catch (Exception e) {
        message = createMessage("error", e.getMessage());
        logger.error(message);
        e.printStackTrace();
    }
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(200);
    response.getWriter().write(message);
}

From source file:org.wahlzeit.servlets.MainServlet.java

/**
 * Searches for files in the request and puts them in the resulting map with the key "fileName". When a file is
 * found, you can access its path by searching for elements with the key "fileName".
 *///w  w w  .  j a v  a2s. c  o m
protected Map getMultiPartRequestArgs(HttpServletRequest request, UserSession us)
        throws IOException, ServletException {
    Map<String, String> result = new HashMap<String, String>();
    result.putAll(request.getParameterMap());
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);

        while (iterator.hasNext()) {
            FileItemStream fileItemStream = iterator.next();
            String filename = fileItemStream.getName();

            if (!fileItemStream.isFormField()) {
                InputStream inputStream = fileItemStream.openStream();
                Image image = getImage(inputStream);
                User user = (User) us.getClient();
                user.setUploadedImage(image);
                result.put("fileName", filename);
                log.config(
                        LogBuilder.createSystemMessage().addParameter("Uploaded image", filename).toString());
            } else {
                String key = fileItemStream.getFieldName();
                InputStream is = fileItemStream.openStream();
                String value = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
                result.put(key, value);
                log.config(LogBuilder.createSystemMessage().addParameter("Key of uploaded parameter", key)
                        .addParameter("value", value).toString());
            }
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

    return result;
}

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

public static PluploadChunk create(FileItemIterator items) throws IOException, FileUploadException {
    PluploadChunk chunk = new PluploadChunk();
    while (items.hasNext()) {
        FileItemStream item = (FileItemStream) items.next();

        if (item.isFormField()) {
            setChunkField(chunk, item);/* w  w  w. j a  v a2s . c  o m*/
        } else {
            saveChunkData(chunk, item);
            break;
        }
    }
    return chunk;
}

From source file:Project.FileUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w w w . j a  va  2  s. c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    response.setContentType("text/html");
    String path = "";
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            String category = "";
            String keywords = "";
            double cost = 0.0;
            String imagess = "";
            String user = "";
            FileItemIterator itr = upload.getItemIterator(request);
            Map<String, String> map = new HashMap<String, String>();
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    //do variable declaration of the specific field
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    response.getWriter().println(fieldName + ":" + value + "<br/>");
                    map.put(fieldName, value);
                } else {
                    //do file upload and store the path as variable
                    path = getServletContext().getRealPath("/");
                    //will write a method and we will call here
                    if (processFile(path, item)) {
                        response.getWriter().println("File uploaded successfully");
                        response.getWriter().println(path);
                    } else {
                        response.getWriter().println("File uploading failed");
                    }
                }

                for (Map.Entry<String, String> entry : map.entrySet()) {
                    if (entry.getKey().equals("category")) {
                        category = entry.getValue();
                    } else if (entry.getKey().equals("keywords")) {
                        keywords = entry.getValue();
                    } else if (entry.getKey().equals("cost")) {
                        cost = Double.parseDouble(entry.getValue());
                    } else if (entry.getKey().equals("fileName")) {
                        imagess = entry.getValue();
                    } else if (entry.getKey().equals("user")) {
                        user = entry.getValue();
                    }
                }

            }
            response.getWriter().println("images\\" + imagess);
            imagess = "images\\" + imagess;
            response.getWriter().println(category + "---" + keywords + "----" + cost + "---" + imagess);
            DB_Users d = new DB_Users();
            d.insertProduct(category, keywords, imagess, cost, user);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else {
        //do nothing
    }
}