Example usage for javax.servlet.http Part getInputStream

List of usage examples for javax.servlet.http Part getInputStream

Introduction

In this page you can find the example usage for javax.servlet.http Part getInputStream.

Prototype

public InputStream getInputStream() throws IOException;

Source Link

Document

Gets the content of this part as an InputStream

Usage

From source file:codes.thischwa.c5c.DispatcherPUT.java

@Override
GenericResponse doRequest() {//from  w w w.  ja v a 2 s .  com
    logger.debug("Entering DispatcherPUT#doRequest");

    InputStream in = null;
    try {
        Context ctx = RequestData.getContext();
        FilemanagerAction mode = ctx.getMode();
        HttpServletRequest req = ctx.getServletRequest();
        FilemanagerConfig conf = UserObjectProxy.getFilemanagerUserConfig(req);
        switch (mode) {
        case UPLOAD: {
            boolean overwrite = conf.getUpload().isOverwrite();
            String currentPath = IOUtils.toString(req.getPart("currentpath").getInputStream());
            String backendPath = buildBackendPath(currentPath);
            Part uploadPart = req.getPart("newfile");
            String newName = getFileName(uploadPart);

            // Some browsers transfer the entire source path not just the filename
            String fileName = FilenameUtils.getName(newName); // TODO check forceSingleExtension
            String sanitizedName = FileUtils.sanitizeName(fileName);
            if (!overwrite)
                sanitizedName = getUniqueName(backendPath, sanitizedName);
            logger.debug("* upload -> currentpath: {}, filename: {}, sanitized filename: {}", currentPath,
                    fileName, sanitizedName);

            // check 'overwrite' and unambiguity
            String uniqueName = getUniqueName(backendPath, sanitizedName);
            if (!overwrite && !uniqueName.equals(sanitizedName)) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD,
                        FilemanagerException.Key.FileAlreadyExists, sanitizedName);
            }
            sanitizedName = uniqueName;

            in = uploadPart.getInputStream();

            // save the file temporary
            Path tempPath = saveTemp(in, sanitizedName);

            // pre-process the upload
            imageProcessingAndSizeCheck(tempPath, sanitizedName, uploadPart.getSize(), conf);

            connector.upload(backendPath, sanitizedName,
                    new BufferedInputStream(Files.newInputStream(tempPath)));

            logger.debug("successful uploaded {} bytes", uploadPart.getSize());
            Files.delete(tempPath);
            UploadFile ufResp = new UploadFile(currentPath, sanitizedName);
            ufResp.setName(newName);
            ufResp.setPath(currentPath);
            return ufResp;
        }
        case REPLACE: {
            String newFilePath = IOUtils.toString(req.getPart("newfilepath").getInputStream());
            String backendPath = buildBackendPath(newFilePath);
            Part uploadPart = req.getPart("fileR");
            logger.debug("* replacefile -> urlPath: {}, backendPath: {}", newFilePath, backendPath);

            // check if backendPath is protected
            boolean protect = connector.isProtected(backendPath);
            if (protect) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD,
                        FilemanagerException.Key.NotAllowedSystem, backendPath);
            }

            // check if file already exits
            VirtualFile vf = new VirtualFile(backendPath, false);
            String fileName = vf.getName();
            String uniqueName = getUniqueName(vf.getFolder(), fileName);
            if (uniqueName.equals(fileName)) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.FileNotExists,
                        backendPath);
            }

            in = uploadPart.getInputStream();

            // save the file temporary
            Path tempPath = saveTemp(in, fileName);

            // pre-process the upload
            imageProcessingAndSizeCheck(tempPath, fileName, uploadPart.getSize(), conf);

            connector.replace(backendPath, new BufferedInputStream(Files.newInputStream(tempPath)));
            logger.debug("successful replaced {} bytes", uploadPart.getSize());
            VirtualFile vfUrlPath = new VirtualFile(newFilePath, false);
            return new Replace(vfUrlPath.getFolder(), vfUrlPath.getName());
        }
        case SAVEFILE: {
            String urlPath = req.getParameter("path");
            String backendPath = buildBackendPath(urlPath);
            logger.debug("* savefile -> urlPath: {}, backendPath: {}", urlPath, backendPath);
            String content = req.getParameter("content");
            connector.saveFile(backendPath, content);
            return new SaveFile(urlPath);
        }
        default: {
            logger.error("Unknown 'mode' for POST: {}", req.getParameter("mode"));
            throw new C5CException(UserObjectProxy.getFilemanagerErrorMessage(Key.ModeError));
        }
        }
    } catch (C5CException e) {
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage());
    } catch (ServletException e) {
        logger.error("A ServletException was thrown while uploading: " + e.getMessage(), e);
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200);
    } catch (IOException e) {
        logger.error("A IOException was thrown while uploading: " + e.getMessage(), e);
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

@RequestMapping(value = "/channel/{channelId}/drop", method = RequestMethod.POST)
public void drop(@PathVariable("channelId") final String channelId,
        @RequestParameter(required = false, value = "name") String name,
        final @RequestParameter("file") Part file, final HttpServletResponse response) throws IOException {
    response.setContentType("text/plain");

    try {//from   w  w  w  .  j  a va  2  s.  co m
        if (name == null || name.isEmpty()) {
            name = file.getSubmittedFileName();
        }

        final String finalName = name;

        this.channelService.access(By.id(channelId), ModifiableChannel.class, channel -> {
            channel.getContext().createArtifact(file.getInputStream(), finalName, null);
        });

        // FIXME: this.service.createArtifact ( channelId, name, file.getInputStream (), null );
    } catch (final Throwable e) {
        logger.debug("Failed to drop file", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write("Internal error: " + ExceptionHelper.getMessage(e));
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write("OK");
}

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

@RequestMapping(value = "/channel/importAll", method = RequestMethod.POST)
public ModelAndView importAllPost(
        @RequestParameter(value = "useNames", required = false) final boolean useNames,
        @RequestParameter(value = "wipe", required = false) final boolean wipe,
        @RequestParameter("file") final Part part,
        @RequestParameter(value = "location", required = false) final String location) {
    try {/*from  ww  w  . j a  v  a 2 s. co m*/
        if (location != null && !location.isEmpty()) {
            try (BufferedInputStream stream = new BufferedInputStream(
                    new FileInputStream(new File(location)))) {
                this.service.importAll(stream, useNames, wipe);
            }
        } else {
            this.service.importAll(part.getInputStream(), useNames, wipe);
        }
        return new ModelAndView("redirect:/channel");
    } catch (final Exception e) {
        logger.warn("Failed to import", e);
        return CommonController.createError("Import", "Channel", "Failed to import channel", e, null);
    }
}

From source file:org.clothocad.phagebook.controllers.PersonController.java

public File partConverter(Part part, String fileName) throws IOException {
    String pathAndName = getFilepath() + fileName;

    OutputStream out = null;//w w w.  j  a v a 2s.c  o  m
    InputStream filecontent = null;

    try {
        out = new FileOutputStream(new File(pathAndName));
        filecontent = part.getInputStream();

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

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
    } catch (FileNotFoundException fne) {
        //            Logger.getLogger(uploadProfilePicture.class.getName()).log(Level.SEVERE, null, fne);
    }

    return new File(pathAndName);
}

From source file:org.eclipse.packagedrone.repo.channel.web.channel.ChannelController.java

@RequestMapping(value = "/channel/{channelId}/add", method = RequestMethod.POST)
public ModelAndView addPost(@PathVariable("channelId") final String channelId,
        @RequestParameter(required = false, value = "name") String name,
        final @RequestParameter("file") Part file) {
    try {/*from w  ww.j a  v  a 2s .  c  o  m*/
        if (name == null || name.isEmpty()) {
            name = file.getSubmittedFileName();
        }

        final String finalName = name;

        this.channelService.accessRun(By.id(channelId), ModifiableChannel.class, channel -> {
            channel.getContext().createArtifact(file.getInputStream(), finalName, null);
        });

        return redirectDefaultView(channelId, true);
    } catch (final Exception e) {
        return CommonController.createError("Upload", "Upload failed", e);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.backBeans.teacher.evaluation.EvaluationManagementBackingBean.java

public String loadMarks() throws FenixServiceException, ServletException, IOException {
    final HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance()
            .getExternalContext().getRequest();

    final Part fileItem = httpServletRequest.getPart("theFile");
    InputStream inputStream = null;
    try {// ww  w  . j  a v  a2  s.co m
        inputStream = fileItem.getInputStream();
        final Map<String, String> marks = loadMarks(inputStream);

        WriteMarks.writeByStudent(getExecutionCourseID(), getEvaluationID(), buildStudentMarks(marks));

        return "success";

    } catch (FenixServiceMultipleException e) {
        for (DomainException domainException : e.getExceptionList()) {
            addErrorMessage(BundleUtil.getString(Bundle.APPLICATION, domainException.getKey(),
                    domainException.getArgs()));
        }
        return "";
    } catch (IOException e) {
        addErrorMessage(BundleUtil.getString(Bundle.APPLICATION, e.getMessage()));
        return "";
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Nothing to do ...
            }
        }
    }
}

From source file:AddPost.java

/**
 * metodo usato per gestire il caso di upload di file multipli da 
 * parte del'utente su un singolo post, siccome la libreria 
 * utilizzata non gestiva questo particolare caso.
 * @throws IOException//from   w ww .j a v a  2  s . c om
 * @throws ServletException
 * @throws SQLException 
 */
private void getFiles() throws IOException, ServletException, SQLException {
    Collection<Part> p = mReq.getParts();
    for (Part part : p) {
        if (part.getName().equals("post")) {
            //
        } else {
            if (part.getSize() > 1024 * 1024 * 10) {
                error++;
            } else {
                String path = mReq.getServletContext().getRealPath("/");
                String name = part.getSubmittedFileName();
                int i;
                if (isInGroupFiles(name)) {
                    for (i = 1; isInGroupFiles("(" + i + ")" + name); i++)
                        ;
                    name = "(" + i + ")" + name;
                }

                //Hotfixies for absoluth paths

                //IE
                if (name.contains("\\")) {
                    name = name.substring(name.lastIndexOf("\\"));
                }

                //somthing else, never encountered
                if (name.contains("/")) {
                    name = name.substring(name.lastIndexOf("/"));
                }

                dbm.newFile(dbm.getIdFromUser(user), groupid, name);

                File outputFile = new File(path + "/files/" + groupid + "/" + name);
                if (!outputFile.exists()) {
                    outputFile.createNewFile();
                }
                if (!outputFile.isDirectory()) {
                    InputStream finput = new BufferedInputStream(part.getInputStream());
                    OutputStream foutput = new BufferedOutputStream(new FileOutputStream(outputFile));

                    byte[] buffer = new byte[1024 * 500];
                    int bytes_letti = 0;
                    while ((bytes_letti = finput.read(buffer)) > 0) {
                        foutput.write(buffer, 0, bytes_letti);
                    }
                    finput.close();
                    foutput.close();
                }
            }
        }

    }

}

From source file:org.eclipse.packagedrone.repo.channel.web.channel.ChannelController.java

@RequestMapping(value = "/channel/{channelId}/drop", method = RequestMethod.POST)
public void drop(@PathVariable("channelId") final String channelId,
        @RequestParameter(required = false, value = "name") String name,
        final @RequestParameter("file") Part file, final HttpServletResponse response) throws IOException {
    response.setContentType("text/plain");

    try {//from w w w.j  av a 2 s  .c om
        if (name == null || name.isEmpty()) {
            name = file.getSubmittedFileName();
        }

        final String finalName = name;

        this.channelService.accessRun(By.id(channelId), ModifiableChannel.class, channel -> {
            channel.getContext().createArtifact(file.getInputStream(), finalName, null);
        });
    } catch (final Throwable e) {
        logger.warn("Failed to drop file", e);

        final Throwable cause = ExceptionHelper.getRootCause(e);

        if (cause instanceof VetoArtifactException) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
            response.getWriter().format("Artifact rejected! %s",
                    ((VetoArtifactException) cause).getVetoMessage().orElse("No details given"));
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().format("Internal error! %s", ExceptionHelper.getMessage(cause));
        }
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write("OK");
}

From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java

@Override
public BinaryContent createMetacard(HttpServletRequest httpServletRequest, String transformerParam)
        throws CatalogServiceException {
    LOGGER.trace("ENTERING: createMetacard");

    InputStream stream = null;//from   w ww .j  a va2  s.c  om
    String contentType = null;

    try {
        Part contentPart = httpServletRequest.getPart(FILE_ATTACHMENT_CONTENT_ID);
        if (contentPart != null) {
            // Example Content-Type header:
            // Content-Type: application/json;id=geojson
            if (contentPart.getContentType() != null) {
                contentType = contentPart.getContentType();
            }

            // Get the file contents as an InputStream and ensure the stream is positioned
            // at the beginning
            try {
                stream = contentPart.getInputStream();
                if (stream != null && stream.available() == 0) {
                    stream.reset();
                }
            } catch (IOException e) {
                LOGGER.info("IOException reading stream from file attachment in multipart body", e);
            }
        } else {
            LOGGER.debug(NO_FILE_CONTENTS_ATT_FOUND);
        }
    } catch (ServletException | IOException e) {
        LOGGER.info("No file contents part found: ", e);
    }

    return createMetacard(stream, contentType, transformerParam);
}

From source file:com.ahm.fileupload.FileController.java

public String processUpload(Part fileUpload) throws Exception {
    String fileSaveData = null;/*  w  ww.  ja  va2  s . c o m*/
    try {
        if (fileUpload.getSize() > 0) {

            String submittedFileName = this.getFileName(fileUpload);
            if (checkFileType(submittedFileName)) {

                if (fileUpload.getSize() > this.limit_max_size) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(""));
                } else {
                    String currentFileName = submittedFileName;
                    String extension = currentFileName.substring(currentFileName.lastIndexOf("."),
                            currentFileName.length());
                    Long nameRandom = Calendar.getInstance().getTimeInMillis();

                    String newFileName = nameRandom + extension;

                    fileSaveData = newFileName;

                    String fileSavePath = FacesContext.getCurrentInstance().getExternalContext()
                            .getRealPath(this.path_to);
                    System.out.println("Save path " + fileSavePath);
                    //System.out.println("Save path " + currentFileName+" ext: "+extension);

                    try {
                        byte[] fileContent = new byte[(int) fileUpload.getSize()];
                        InputStream in = fileUpload.getInputStream();
                        in.read(fileContent);
                        File fileToCreate = new File(fileSavePath, newFileName);
                        File folder = new File(fileSavePath);
                        if (!folder.exists()) {
                            folder.mkdir();
                        }

                        FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
                        fileOutStream.write(fileContent);
                        fileOutStream.flush();
                        fileOutStream.close();
                        fileSaveData = newFileName;
                    } catch (Exception e) {
                        fileSaveData = null;
                        throw e;
                    }
                }
            } else {
                fileSaveData = null;
                System.out.println("No tiene formato valido");
            }
        } else {
            System.out.println("No tiene nada");
        }

    } catch (Exception e) {
        fileSaveData = null;
        throw e;
    }

    return fileSaveData;
}