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:com.fizzbuzz.vroom.extension.googlecloudstorage.api.resource.GcsFilesResource.java

/**
 *
 * @param rep/*from   ww  w.  j a  va2s  . c  om*/
 */
public void postResource(final Representation rep) {
    if (rep == null)
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    else {
        try {
            FileUpload fileUpload = new FileUpload();
            FileItemIterator fileItemIterator = fileUpload.getItemIterator(new RepresentationContext(rep));
            if (fileItemIterator.hasNext()) {
                FileItemStream fileItemStream = fileItemIterator.next();
                validateFileItemStream(fileItemStream);
                String fileName = fileItemStream.getName();
                byte[] bytes = ByteStreams.toByteArray(fileItemStream.openStream());

                F file = createFile(fileName);
                mBiz.create(file, bytes);

                // we're not going to send a representation of the file back to the client, since they probably
                // don't want that.  Instead, we'll send them a 201, with the URL to the created file in the
                // Location header of the response.
                getResponse().setStatus(Status.SUCCESS_CREATED);
                // set the Location response header
                String uri = getElementUri(file);
                getResponse().setLocationRef(uri);
                mLogger.info("created new file resource at: {}", uri);
            }
        } catch (FileUploadException e) {
            throw new IllegalArgumentException(
                    "caught FileUploadException while attempting to parse " + "multipart form", e);
        } catch (IOException e) {
            throw new IllegalArgumentException(
                    "caught IOException while attempting to parse multipart " + "form", e);
        }
    }
}

From source file:com.google.publicalerts.cap.validator.CapValidatorServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String input = null;//from www.ja  v a  2s .  co m
    String fileInput = null;
    String example = null;
    Set<CapProfile> profiles = Sets.newHashSet();

    try {
        FileItemIterator itemItr = upload.getItemIterator(req);
        while (itemItr.hasNext()) {
            FileItemStream item = itemItr.next();
            if ("input".equals(item.getFieldName())) {
                input = ValidatorUtil.readFully(item.openStream());
            } else if (item.getFieldName().startsWith("inputfile")) {
                fileInput = ValidatorUtil.readFully(item.openStream());
            } else if ("example".equals(item.getFieldName())) {
                example = ValidatorUtil.readFully(item.openStream());
            } else if ("profile".equals(item.getFieldName())) {
                String profileCode = ValidatorUtil.readFully(item.openStream());
                profiles.addAll(ValidatorUtil.parseProfiles(profileCode));
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    if (!CapUtil.isEmptyOrWhitespace(example)) {
        log.info("ExampleRequest: " + example);
        input = loadExample(example);
        profiles = ImmutableSet.of();
    } else if (!CapUtil.isEmptyOrWhitespace(fileInput)) {
        log.info("FileInput");
        input = fileInput;
    }

    input = (input == null) ? "" : input.trim();
    if ("".equals(input)) {
        log.info("EmptyRequest");
        doGet(req, resp);
        return;
    }

    ValidationResult result = capValidator.validate(input, profiles);

    req.setAttribute("input", input);
    req.setAttribute("profiles", ValidatorUtil.getProfilesJsp(profiles));
    req.setAttribute("validationResult", result);
    req.setAttribute("lines", Arrays.asList(result.getInput().split("\n")));
    req.setAttribute("timing", result.getTiming());
    JSONArray alertsJs = new MapVisualizer(result.getValidAlerts()).getAlertsJs();
    if (alertsJs != null) {
        req.setAttribute("alertsJs", alertsJs.toString());
    }
    render(req, resp);
}

From source file:edu.caltech.ipac.firefly.server.servlets.AnyFileUpload.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

    String dest = req.getParameter(DEST_PARAM);
    String preload = req.getParameter(PRELOAD_PARAM);
    String overrideCacheKey = req.getParameter(CACHE_KEY);
    String fileType = req.getParameter(FILE_TYPE);

    if (!ServletFileUpload.isMultipartContent(req)) {
        sendReturnMsg(res, 400, "Is not a Multipart request. Request rejected.", "");
    }/*  w  w w . j  ava2s. c om*/
    StopWatch.getInstance().start("Upload File");

    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();

        if (!item.isFormField()) {
            String fileName = item.getName();
            InputStream inStream = new BufferedInputStream(item.openStream(),
                    IpacTableUtil.FILE_IO_BUFFER_SIZE);
            String ext = resolveExt(fileName);
            FileType fType = resolveType(fileType, ext, item.getContentType());
            File destDir = resolveDestDir(dest, fType);
            boolean doPreload = resolvePreload(preload, fType);

            File uf = File.createTempFile("upload_", ext, destDir);
            String rPathInfo = ServerContext.replaceWithPrefix(uf);

            UploadFileInfo fi = new UploadFileInfo(rPathInfo, uf, fileName, item.getContentType());
            String fileCacheKey = overrideCacheKey != null ? overrideCacheKey : rPathInfo;
            UserCache.getInstance().put(new StringKey(fileCacheKey), fi);

            if (doPreload && fType == FileType.FITS) {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(uf),
                        IpacTableUtil.FILE_IO_BUFFER_SIZE);
                TeeInputStream tee = new TeeInputStream(inStream, bos);
                try {
                    final Fits fits = new Fits(tee);
                    FitsRead[] frAry = FitsRead.createFitsReadArray(fits);
                    FitsCacher.addFitsReadToCache(uf, frAry);
                } finally {
                    FileUtil.silentClose(bos);
                    FileUtil.silentClose(tee);
                }
            } else {
                FileUtil.writeToFile(inStream, uf);
            }
            sendReturnMsg(res, 200, null, fileCacheKey);
            Counters.getInstance().increment(Counters.Category.Upload, fi.getContentType());
            return;
        }
    }
    StopWatch.getInstance().printLog("Upload File");
}

From source file:foo.domaintest.email.EmailApiModule.java

/**
 * Provides parsed email headers from the "headers" param in a multipart/form-data request.
 * <p>/*from   w  w  w  .  ja v  a  2  s .  c  o m*/
 * Although SendGrid parses some headers for us, it doesn't parse "reply-to", so we need to do
 * this. Once we are doing it, it's easier to be consistent and use this as the sole source of
 * truth for information that originates in the headers.
 */
@Provides
@Singleton
InternetHeaders provideHeaders(FileItemIterator iterator) {
    try {
        while (iterator != null && iterator.hasNext()) {
            FileItemStream item = iterator.next();
            // SendGrid sends us the headers in the "headers" param.
            if (item.getFieldName().equals("headers")) {
                try (InputStream stream = item.openStream()) {
                    // SendGrid always sends headers in UTF-8 encoding.
                    return new InternetHeaders(new ByteArrayInputStream(
                            CharStreams.toString(new InputStreamReader(stream, UTF_8.name())).getBytes(UTF_8)));
                }
            }
        }
    } catch (MessagingException | FileUploadException | IOException e) {
        // If we fail parsing the headers fall through returning the empty header object below.
    }
    return new InternetHeaders(); // Parsing failed or there was no "headers" param.
}

From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java

private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request))
        return request;

    final Map<String, String> requestParams = new HashMap<String, String>();
    List<FileItemStream> listFiles = new ArrayList<FileItemStream>();

    // Parse the request
    ServletFileUpload sfu = new ServletFileUpload();
    String characterEncoding = request.getCharacterEncoding();
    if (characterEncoding == null) {
        characterEncoding = "UTF-8";
    }/*from   w  w w .  j  a  v  a 2  s  . c  om*/
    sfu.setHeaderEncoding(characterEncoding);
    FileItemIterator iter = sfu.getItemIterator(request);

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream, characterEncoding));
        } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(stream, os);
                final byte[] bs = os.toByteArray();
                stream.close();

                listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                        new Class[] { FileItemStream.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if ("openStream".equals(method.getName())) {
                                    return new ByteArrayInputStream(bs);
                                }

                                return method.invoke(item, args);
                            }
                        }));
            }
        }
    }

    request.setAttribute(FileItemStream.class.getName(), listFiles);

    Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    // we replace getParameter() and getParameterValues()
                    // methods
                    if ("getParameter".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];
                        return requestParams.get(paramName);
                    }

                    if ("getParameterValues".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];

                        // normalize name 'key[]' to 'key'
                        if (paramName.endsWith("[]"))
                            paramName = paramName.substring(0, paramName.length() - 2);

                        if (requestParams.containsKey(paramName))
                            return new String[] { requestParams.get(paramName) };

                        // if contains key[1], key[2]...
                        int i = 0;
                        List<String> paramValues = new ArrayList<String>();
                        while (true) {
                            String name2 = String.format("%s[%d]", paramName, i++);
                            if (requestParams.containsKey(name2)) {
                                paramValues.add(requestParams.get(name2));
                            } else {
                                break;
                            }
                        }

                        return paramValues.isEmpty() ? new String[0]
                                : paramValues.toArray(new String[paramValues.size()]);
                    }

                    return arg1.invoke(request, arg2);
                }
            });
    return (HttpServletRequest) proxyInstance;
}

From source file:com.chinarewards.gwt.license.util.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // text/html IE??
    response.setContentType("text/plain;charset=utf-8");

    StringBuffer responseMessage = new StringBuffer("<?xml version=\"1.0\" encoding=\"GB2312\"?>");
    responseMessage.append("<root>");

    StringBuffer errorMsg = new StringBuffer(responseMessage).append("<result>").append("FAILED")
            .append("</result>");

    String info = "";
    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator iter = null;/*  www.ja v  a  2s.c  om*/
    try {
        iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                info = "Form field " + name + " with value " + Streams.asString(stream) + " detected.";
                responseMessage = new StringBuffer(responseMessage).append(errorMsg).append("<info>")
                        .append(info).append("</info>");
                finishPrintResponseMsg(response, responseMessage);
                return;
            } else {
                BufferedInputStream inputStream = new BufferedInputStream(stream);// ?

                String uploadPath = getUploadPath(request, "upload");
                if (uploadPath != null) {
                    String fileName = getOutputFileName(item);
                    String outputFilePath = getOutputFilePath(uploadPath, fileName);

                    int widthdist = 72;
                    int heightdist = 72;

                    widthdist = 200;
                    heightdist = 200;

                    BufferedOutputStream outputStream = new BufferedOutputStream(
                            new FileOutputStream(new File(outputFilePath)));// ?
                    Streams.copy(inputStream, outputStream, true); //
                    //                   stream.close();

                    reduceImg(inputStream, outputFilePath, outputFilePath, widthdist, heightdist, 0);

                    stream.close();

                    responseMessage.append("<result>").append("SUCCESS").append("</result>");
                    responseMessage.append("<info>");
                    responseMessage.append(fileName);
                    responseMessage.append(info).append("</info>");
                } else {
                    responseMessage = errorMsg.append("<info>").append("")
                            .append("</info>");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseMessage = errorMsg.append("<info>").append(":" + e.getMessage())
                .append("</info>");
    }
    finishPrintResponseMsg(response, responseMessage);
}

From source file:com.google.phonenumbers.PhoneNumberParserServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String phoneNumber = null;//from   w ww  . j a  v  a  2  s.  c  o m
    String defaultCountry = null;
    String languageCode = "en"; // Default languageCode to English if nothing is entered.
    String regionCode = "";
    String fileContents = null;
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(50000);
    try {
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("phoneNumber")) {
                    phoneNumber = Streams.asString(in, "UTF-8");
                } else if (fieldName.equals("defaultCountry")) {
                    defaultCountry = Streams.asString(in).toUpperCase();
                } else if (fieldName.equals("languageCode")) {
                    String languageEntered = Streams.asString(in).toLowerCase();
                    if (languageEntered.length() > 0) {
                        languageCode = languageEntered;
                    }
                } else if (fieldName.equals("regionCode")) {
                    regionCode = Streams.asString(in).toUpperCase();
                }
            } else {
                try {
                    fileContents = IOUtils.toString(in);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

    StringBuilder output;
    if (fileContents.length() == 0) {
        output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().println("<html><head>");
        resp.getWriter()
                .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />");
        resp.getWriter().println("</head>");
        resp.getWriter().println("<body>");
        resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>");
        resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>");
        resp.getWriter().println("Language entered: " + languageCode
                + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>"));
    } else {
        output = getOutputForFile(defaultCountry, fileContents);
        resp.setContentType("text/html");
    }
    resp.getWriter().println(output);
    resp.getWriter().println("</body></html>");
}

From source file:com.sifiso.dvs.util.PhotoUtil.java

public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil)
        throws FileUploadException {
    logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n");
    ResponseDTO resp = new ResponseDTO();
    InputStream stream = null;/*from   w w  w.  jav  a  2  s. c  o  m*/
    File rootDir;
    try {
        rootDir = dvsProperties.getImageDir();
        logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath());
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Properties file problem", ex);
        resp.setMessage("Server file unavailable. Please try later");
        resp.setStatusCode(114);

        return resp;
    }

    PhotoUploadDTO dto = null;
    Gson gson = new Gson();
    File doctorFileDir = null, surgeryDir = null;
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            stream = item.openStream();
            if (item.isFormField()) {
                if (name.equalsIgnoreCase("JSON")) {
                    String json = Streams.asString(stream);
                    if (json != null) {
                        logger.log(Level.INFO, "picture with associated json: {0}", json);
                        dto = gson.fromJson(json, PhotoUploadDTO.class);
                        if (dto != null) {
                            surgeryDir = createSurgeryFileDirectory(rootDir, surgeryDir, dto.getSurgeryID());
                            if (dto.getDoctorID() > 0) {
                                doctorFileDir = createDoctorDirectory(surgeryDir, doctorFileDir,
                                        dto.getDoctorID());
                            }

                        }
                    } else {
                        logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL..");
                    }
                }
            } else {
                File imageFile = null;
                if (dto == null) {
                    continue;
                }
                DateTime dt = new DateTime();
                String fileName = "";
                if (dto.isIsFullPicture()) {
                    fileName = "f" + dt.getMillis() + ".jpg";
                } else {
                    fileName = "t" + dt.getMillis() + ".jpg";
                }
                if (dto.getPatientfileID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getPatientfileID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getPatientfileID() + ".jpg";
                    }
                }

                //
                switch (dto.getPictureType()) {
                case PhotoUploadDTO.FILES_DOCTOR:
                    imageFile = new File(doctorFileDir, fileName);
                    break;
                case PhotoUploadDTO.FILES_SURGERY:
                    imageFile = new File(surgeryDir, fileName);
                }

                writeFile(stream, imageFile);
                resp.setStatusCode(0);
                resp.setMessage("Photo downloaded from mobile app ");
                //add database
                System.out.println("filepath: " + imageFile.getAbsolutePath());
                //create uri
                /*int index = imageFile.getAbsolutePath().indexOf("monitor_images");
                 if (index > -1) {
                 String uri = imageFile.getAbsolutePath().substring(index);
                 System.out.println("uri: " + uri);
                 dto.setUri(uri);
                 }
                 dto.setDateUploaded(new Date());
                 if (dto.isIsFullPicture()) {
                 dto.setThumbFlag(null);
                 } else {
                 dto.setThumbFlag(1);
                 }
                 dataUtil.addPhotoUpload(dto);*/

            }
        }

    } catch (FileUploadException | IOException | JsonSyntaxException ex) {
        logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex);
        throw new FileUploadException();
    }

    return resp;
}

From source file:controllers.PictureController.java

@FilterWith(SecureFilter.class)
public Result uploadFinish(@LoggedInUser String username, Context context) throws Exception {
    String fileLocation = "";
    // Make sure the context really is a multipart context...
    if (context.isMultipart()) {
        Picture pic = new Picture();
        // This is the iterator we can use to iterate over the
        // contents of the request.
        FileItemIterator fileItemIterator = context.getFileItemIterator();

        while (fileItemIterator.hasNext()) {

            FileItemStream item = fileItemIterator.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();

            String contentType = item.getContentType();

            if (item.isFormField()) {
                String value = Streams.asString(stream);
                switch (name) {
                case "name":
                    pic.setName(value);// w  w  w .j  a  v a2s. co  m
                    break;
                case "about":
                    pic.setAbout(value);
                    break;
                }

            } else {
                OutputStream outputStream = null;

                try {
                    fileLocation = "public/pictures/" + item.getName();
                    outputStream = new FileOutputStream(new File(fileLocation));

                    int read = 0;
                    byte[] bytes = new byte[1024];

                    while ((read = stream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, read);
                    }
                    pic.setFile(item.getName());

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (outputStream != null) {
                        try {
                            // outputStream.flush();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
        pictureDao.postArticlePicture(username, pic);
    }

    reziseImage(fileLocation);
    // We always return ok. You don't want to do that in production ;)
    return Results.redirect("/picture/all");

}

From source file:n3phele.backend.RepoProxy.java

@POST
@Path("{id}/upload/{bucket}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket,
        @QueryParam("name") String destination, @QueryParam("expires") long expires,
        @QueryParam("signature") String signature, @Context HttpServletRequest request)
        throws NotFoundException {
    Repository repo = Dao.repository().load(id);
    if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(),
            bucket + ":" + destination)) {
        log.severe("Expired temporary authorization");
        throw new NotFoundException();
    }/*from  w ww.j  a  v a2s.  c  o  m*/

    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding "
                + upload.getHeaderEncoding());
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();

            if (item.isFormField()) {
                log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream()));
            } else {
                InputStream stream = item.openStream();
                log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()
                        + " content " + item.getContentType());
                URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination);
                Response.created(target).build();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Processing error", e);
    }

    return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build();
}