Example usage for org.springframework.web.multipart MultipartFile getInputStream

List of usage examples for org.springframework.web.multipart MultipartFile getInputStream

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getInputStream.

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

From source file:org.openmrs.module.patientnarratives.web.controller.WebRtcMediaStreamController.java

@RequestMapping(FORM_PATH)
public ModelAndView handleRequest(HttpServletRequest request) throws Exception {

    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile videofile = (MultipartFile) multipartRequest.getFile("video");
        MultipartFile audiofile = (MultipartFile) multipartRequest.getFile("audio");

        /**//from  w ww .  j a  v a 2 s  .c  om
         * Xuggler merge process of the two binary streams
         */
        try {
            tempMergedVideoFile = File.createTempFile("mergedVideoFile", ".flv");
            String mergedUrl = tempMergedVideoFile.getCanonicalPath();

            IMediaWriter mWriter = ToolFactory.makeWriter(mergedUrl); //output file

            IContainer containerVideo = IContainer.make();
            IContainer containerAudio = IContainer.make();

            InputStream videoInputStream = videofile.getInputStream();
            InputStream audioInputStream = audiofile.getInputStream();

            if (containerVideo.open(videoInputStream, null) < 0)
                throw new IllegalArgumentException("Cant find " + videoInputStream);

            if (containerAudio.open(audioInputStream, null) < 0)
                throw new IllegalArgumentException("Cant find " + audioInputStream);

            int numStreamVideo = containerVideo.getNumStreams();
            int numStreamAudio = containerAudio.getNumStreams();

            System.out.println("Number of video streams: " + numStreamVideo + "\n" + "Number of audio streams: "
                    + numStreamAudio);

            int videostreamt = -1; //this is the video stream id
            int audiostreamt = -1;

            IStreamCoder videocoder = null;

            for (int i = 0; i < numStreamVideo; i++) {
                IStream stream = containerVideo.getStream(i);
                IStreamCoder code = stream.getStreamCoder();

                if (code.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
                    videostreamt = i;
                    videocoder = code;
                    break;
                }
            }

            for (int i = 0; i < numStreamAudio; i++) {
                IStream stream = containerAudio.getStream(i);
                IStreamCoder code = stream.getStreamCoder();

                if (code.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
                    audiostreamt = i;
                    break;
                }
            }

            if (videostreamt == -1)
                throw new RuntimeException("No video steam found");
            if (audiostreamt == -1)
                throw new RuntimeException("No audio steam found");

            if (videocoder.open() < 0)
                throw new RuntimeException("Cant open video coder");
            IPacket packetvideo = IPacket.make();

            IStreamCoder audioCoder = containerAudio.getStream(audiostreamt).getStreamCoder();

            if (audioCoder.open() < 0)
                throw new RuntimeException("Cant open audio coder");
            mWriter.addAudioStream(1, 1, audioCoder.getChannels(), audioCoder.getSampleRate());

            mWriter.addVideoStream(0, 0, videocoder.getWidth(), videocoder.getHeight());

            IPacket packetaudio = IPacket.make();

            while (containerVideo.readNextPacket(packetvideo) >= 0
                    || containerAudio.readNextPacket(packetaudio) >= 0) {

                if (packetvideo.getStreamIndex() == videostreamt) {

                    //video packet
                    IVideoPicture picture = IVideoPicture.make(videocoder.getPixelType(), videocoder.getWidth(),
                            videocoder.getHeight());
                    int offset = 0;
                    while (offset < packetvideo.getSize()) {
                        int bytesDecoded = videocoder.decodeVideo(picture, packetvideo, offset);
                        if (bytesDecoded < 0)
                            throw new RuntimeException("bytesDecoded not working");
                        offset += bytesDecoded;

                        if (picture.isComplete()) {
                            System.out.println(picture.getPixelType());
                            mWriter.encodeVideo(0, picture);

                        }
                    }
                }

                if (packetaudio.getStreamIndex() == audiostreamt) {
                    //audio packet

                    IAudioSamples samples = IAudioSamples.make(512, audioCoder.getChannels(),
                            IAudioSamples.Format.FMT_S32);
                    int offset = 0;
                    while (offset < packetaudio.getSize()) {
                        int bytesDecodedaudio = audioCoder.decodeAudio(samples, packetaudio, offset);
                        if (bytesDecodedaudio < 0)
                            throw new RuntimeException("could not detect audio");
                        offset += bytesDecodedaudio;

                        if (samples.isComplete()) {
                            mWriter.encodeAudio(1, samples);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e);
            e.getStackTrace();
        }
    }

    saveAndTransferVideoComplexObs();

    returnUrl = request.getContextPath() + "/module/patientnarratives/patientNarrativesForm.form";
    return new ModelAndView(new RedirectView(returnUrl));
}

From source file:org.openmrs.module.clinicalsummary.web.controller.upload.UploadSummariesController.java

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(final @RequestParam(required = true, value = "password") String password,
        final @RequestParam(required = true, value = "summaries") MultipartFile summaries,
        final HttpServletRequest request) {
    if (Context.isAuthenticated()) {
        if (!ServerUtil.isCentral()) {
            try {
                String filename = WebUtils.prepareFilename(null, null);
                log.info("Creating zipped file: " + filename);
                File encryptedPath = OpenmrsUtil
                        .getDirectoryInApplicationDataDirectory(Constants.ENCRYPTION_LOCATION);
                String encryptedFilename = StringUtils
                        .join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED), ".");
                OutputStream encryptedOutputStream = new FileOutputStream(
                        new File(encryptedPath, encryptedFilename));
                FileCopyUtils.copy(summaries.getInputStream(), encryptedOutputStream);
                validate(filename, password);
                upload(filename, password);
            } catch (Exception e) {
                log.error("Unable to process uploaded documents.", e);
                HttpSession session = request.getSession();
                session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "Unable to validate upload parameters. Please try again.");
                return "redirect:" + request.getHeader("Referer");
            }//ww  w . j  a  va 2 s. c  om
        }
    }
    return null;
}

From source file:architecture.ee.web.spring.controller.MyCloudDataController.java

@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping(value = "/files/upload.json", method = RequestMethod.POST)
@ResponseBody//  ww w  .  j a v a2 s .  co  m
public List<Attachment> uploadFiles(
        @RequestParam(value = "objectType", defaultValue = "2", required = false) Integer objectType,
        @RequestParam(value = "fileId", defaultValue = "0", required = false) Long fileId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();
    Iterator<String> names = request.getFileNames();
    List<Attachment> list = new ArrayList<Attachment>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("fileId: " + fileId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        Attachment attachment;
        if (fileId > 0) {
            attachment = attachmentManager.getAttachment(fileId);
            attachment.setName(mpf.getOriginalFilename());
            ((AttachmentImpl) attachment).setInputStream(is);
            ((AttachmentImpl) attachment).setSize((int) mpf.getSize());
        } else {
            attachment = attachmentManager.createAttachment(objectType, user.getUserId(),
                    mpf.getOriginalFilename(), mpf.getContentType(), is, (int) mpf.getSize());
        }

        attachmentManager.saveAttachment(attachment);
        list.add(attachment);
    }
    return list;
}

From source file:architecture.ee.web.spring.controller.MyCloudDataController.java

@Secured({ "ROLE_USER" })
@RequestMapping(value = "/me/photo/images/update_with_media.json", method = RequestMethod.POST)
@ResponseBody//from   www. j  a v  a 2  s. c  o m
public List<Image> uploadMyImageWithMedia(
        @RequestParam(value = "imageId", defaultValue = "0", required = false) Long imageId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();

    if (user.isAnonymous())
        throw new UnAuthorizedException();

    Iterator<String> names = request.getFileNames();
    List<Image> list = new ArrayList<Image>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("imageId: " + imageId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());
        Image image;
        if (imageId > 0) {
            image = imageManager.getImage(imageId);

            image.setName(mpf.getOriginalFilename());
            ((ImageImpl) image).setInputStream(is);
            ((ImageImpl) image).setSize((int) mpf.getSize());
        } else {
            image = imageManager.createImage(2, user.getUserId(), mpf.getOriginalFilename(),
                    mpf.getContentType(), is, (int) mpf.getSize());
            image.setUser(user);
        }
        log.debug(hasPermissions(image, user));
        imageManager.saveImage(image);
        list.add(image);
    }
    return list;
}

From source file:com.campodejazayeri.wedding.AdminController.java

@RequestMapping("/bulk-invite")
public String bulkInvite(@RequestParam("invitees") MultipartFile invitees) throws Exception {
    if (!invitees.isEmpty()) {
        Map<String, InvitationGroup> groupsByName = new HashMap<String, InvitationGroup>();
        ViewQuery query = new ViewQuery().designDocId("_design/groups").viewName("groups").includeDocs(true);
        for (InvitationGroup existing : db.queryView(query, InvitationGroup.class)) {
            groupsByName.put(standardizeName(existing.getGroupName()), existing);
        }//ww  w. j  a  v  a 2 s.  c  o m

        BufferedReader r = new BufferedReader(new InputStreamReader(invitees.getInputStream()));
        for (String row = r.readLine(); row != null; row = r.readLine()) {
            String[] cells = row.split(",");
            if (cells[0].equals("Group Name"))
                continue;
            if (!(StringUtils.hasText(cells[0]) && StringUtils.hasText(cells[1])
                    && StringUtils.hasText(cells[2])))
                throw new RuntimeException("Malformed row: " + row);
            if (cells[0].startsWith("\"") && cells[0].endsWith("\""))
                cells[0] = cells[0].substring(1, cells[0].length() - 1);
            InvitationGroup group = groupsByName.get(cells[0].trim());
            if (group == null) {
                group = new InvitationGroup();
                group.setGroupName(cells[0].trim());
                throw new RuntimeException("Only updates now! Couldn't find " + cells[0]);
            }
            group.setEmail(cells[1].trim());
            group.setLanguage(cells[2].trim());
            group.setInvitedTours(StringUtils.hasText(cells[3]));
            group.setInvitedRehearsal(StringUtils.hasText(cells[4]));
            if (group.getInvitees() != null)
                group.getInvitees().clear();
            for (int i = 5; i < cells.length; ++i) {
                if (StringUtils.hasText(cells[i].trim())) {
                    Invitee invitee = new Invitee();
                    invitee.setName(cells[i].trim());
                    group.addInvitee(invitee);
                }
            }
            if (group.getInvitees().size() == 0)
                throw new RuntimeException("Group with no invitees: " + row);
            if (group.getId() == null) {
                group.setId(randomId());
                db.create(group);
                System.out.println("Created " + group.getGroupName());
            } else {
                db.update(group);
                System.out.println("Updated " + group.getId() + " " + group.getGroupName());
            }
        }
    }
    return "redirect:admin";
}

From source file:com.dlshouwen.wzgl.picture.controller.PictureController.java

/**
 * /* w  w w.  j  a  v a  2s  .  c  o m*/
 *
 * @param picture 
 * @param bindingResult ?
 * @param request 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/ajaxEdit", method = RequestMethod.POST)
@ResponseBody
public void ajaxEditPicture(@Valid Picture picture, HttpServletRequest request, BindingResult bindingResult,
        HttpServletResponse response) throws Exception {
    //          AJAX?
    AjaxResponse ajaxResponse = new AjaxResponse();
    //      ??
    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        //         ?
        LogUtils.updateOperationLog(request, OperationType.INSERT,
                "???"
                        + AjaxResponse.getBindingResultMessage(bindingResult) + "");

        response.setContentType("text/html;charset=utf-8");
        JSONObject obj = JSONObject.fromObject(ajaxResponse);
        response.getWriter().write(obj.toString());
        return;

    }

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String fileName = multipartFile.getOriginalFilename();
    //?
    String path = null;
    if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
        JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream());
        if (jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }

    Picture oldPicture = dao.getPictureById(picture.getPicture_id());
    oldPicture.setDescription(picture.getDescription());
    oldPicture.setFlag(picture.getFlag());
    oldPicture.setOrder(picture.getOrder());
    oldPicture.setPicture_name(picture.getPicture_name());
    oldPicture.setShow(picture.getShow());
    //      ??
    Date nowDate = new Date();
    //       
    picture.setUpdate_time(nowDate);

    if (null != path) {
        oldPicture.setPath(path);
    }

    try {
        //      
        dao.updatePicture(picture);
        //      ????
        ajaxResponse.setSuccess(true);
        ajaxResponse.setSuccessMessage("??");
    } catch (Exception e) {
        //      ????
        ajaxResponse.setError(true);
        ajaxResponse.setErrorMessage("?");
    }

    //?
    Map map = new HashMap();
    map.put("URL", basePath + "picture");
    ajaxResponse.setExtParam(map);

    //      ?
    LogUtils.updateOperationLog(request, OperationType.INSERT,
            "?" + picture.getPicture_id());

    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
}

From source file:org.openmrs.module.logmanager.web.controller.ConfigController.java

/**
 * Handles an import configuration request
 * @param request the http request/*from   www.  ja  va2 s  .c o  m*/
 */
private void importConfiguration(HttpServletRequest request) {
    if (request instanceof MultipartHttpServletRequest) {
        // Spring will have detected a multipart request and wrapped it
        MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
        MultipartFile importFile = mpRequest.getFile("importFile");

        // Check file exists and isn't empty
        if (importFile == null || importFile.isEmpty()) {
            log.error("Uploaded file is empty or invalid");
            return;
        }

        String filename = importFile.getOriginalFilename();

        // Check for xml extension
        if (!filename.toLowerCase().endsWith(".xml")) {
            WebUtils.setErrorMessage(request, Constants.MODULE_ID + ".error.invalidConfigurationFile",
                    new Object[] { filename });
            return;
        }

        // Parse as an XML configuration
        try {
            LogManagerService svc = Context.getService(LogManagerService.class);
            Reader reader = new InputStreamReader(importFile.getInputStream());
            Document document = LogManagerUtils.readDocument(reader, new Log4jEntityResolver());
            reader.close();

            StringWriter str = new StringWriter();
            LogManagerUtils.writeDocument(document, str);

            log.warn(str.toString());

            if (document != null) {
                svc.loadConfiguration(document);

                WebUtils.setInfoMessage(request, Constants.MODULE_ID + ".config.importSuccess",
                        new Object[] { filename });
            } else
                WebUtils.setErrorMessage(request, Constants.MODULE_ID + ".error.invalidConfigurationFile",
                        new Object[] { filename });
        } catch (IOException e) {
            log.error(e);
        }
    }
}

From source file:architecture.ee.web.spring.controller.MyCloudDataController.java

@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping(value = "/images/update_with_media.json", method = RequestMethod.POST)
@ResponseBody//from www  . ja  v a2  s. c om
public List<Image> uploadImageWithMedia(
        @RequestParam(value = "objectType", defaultValue = "2", required = false) Integer objectType,
        @RequestParam(value = "objectId", defaultValue = "0", required = false) Long objectId,
        @RequestParam(value = "imageId", defaultValue = "0", required = false) Long imageId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();
    if (objectType == 1) {
        objectId = user.getCompanyId();
    } else if (objectType == 2) {
        objectId = user.getUserId();
    } else if (objectType == 30) {
        objectId = WebSiteUtils.getWebSite(request).getWebSiteId();
    }

    Iterator<String> names = request.getFileNames();
    List<Image> list = new ArrayList<Image>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("imageId: " + imageId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        Image image;
        if (imageId > 0) {
            image = imageManager.getImage(imageId);
            image.setName(mpf.getOriginalFilename());
            ((ImageImpl) image).setInputStream(is);
            ((ImageImpl) image).setSize((int) mpf.getSize());
        } else {
            image = imageManager.createImage(objectType, objectId, mpf.getOriginalFilename(),
                    mpf.getContentType(), is, (int) mpf.getSize());
            image.setUser(user);
        }
        log.debug(hasPermissions(image, user));
        imageManager.saveImage(image);
        list.add(image);
    }
    return list;
}

From source file:com.netflix.genie.web.controllers.JobRestController.java

private ResponseEntity<Void> handleSubmitJob(final JobRequest jobRequest, final MultipartFile[] attachments,
        final String clientHost, final String userAgent, final HttpServletRequest httpServletRequest)
        throws GenieException {
    if (jobRequest == null) {
        throw new GeniePreconditionException("No job request entered. Unable to submit.");
    }//from   w w  w.  j  av  a  2s  .  c  om

    // get client's host from the context
    final String localClientHost;
    if (StringUtils.isNotBlank(clientHost)) {
        localClientHost = clientHost.split(",")[0];
    } else {
        localClientHost = httpServletRequest.getRemoteAddr();
    }

    final JobRequest jobRequestWithId;
    // If the job request does not contain an id create one else use the one provided.
    final String jobId;
    final Optional<String> jobIdOptional = jobRequest.getId();
    if (jobIdOptional.isPresent() && StringUtils.isNotBlank(jobIdOptional.get())) {
        jobId = jobIdOptional.get();
        jobRequestWithId = jobRequest;
    } else {
        jobId = UUID.randomUUID().toString();
        final JobRequest.Builder builder = new JobRequest.Builder(jobRequest.getName(), jobRequest.getUser(),
                jobRequest.getVersion(), jobRequest.getCommandArgs(), jobRequest.getClusterCriterias(),
                jobRequest.getCommandCriteria()).withId(jobId)
                        .withDisableLogArchival(jobRequest.isDisableLogArchival())
                        .withTags(jobRequest.getTags()).withDependencies(jobRequest.getDependencies())
                        .withApplications(jobRequest.getApplications());

        jobRequest.getCpu().ifPresent(builder::withCpu);
        jobRequest.getMemory().ifPresent(builder::withMemory);
        jobRequest.getGroup().ifPresent(builder::withGroup);
        jobRequest.getSetupFile().ifPresent(builder::withSetupFile);
        jobRequest.getDescription().ifPresent(builder::withDescription);
        jobRequest.getEmail().ifPresent(builder::withEmail);
        jobRequest.getTimeout().ifPresent(builder::withTimeout);

        jobRequestWithId = builder.build();
    }

    // Download attachments
    int numAttachments = 0;
    long totalSizeOfAttachments = 0L;
    if (attachments != null) {
        log.info("Saving attachments for job {}", jobId);
        numAttachments = attachments.length;
        for (final MultipartFile attachment : attachments) {
            totalSizeOfAttachments += attachment.getSize();
            log.debug("Attachment name: {} Size: {}", attachment.getOriginalFilename(), attachment.getSize());
            try {
                this.attachmentService.save(jobId, attachment.getOriginalFilename(),
                        attachment.getInputStream());
            } catch (final IOException ioe) {
                throw new GenieServerException(ioe);
            }
        }
    }

    final JobMetadata metadata = new JobMetadata.Builder().withClientHost(localClientHost)
            .withUserAgent(userAgent).withNumAttachments(numAttachments)
            .withTotalSizeOfAttachments(totalSizeOfAttachments).build();

    this.jobCoordinatorService.coordinateJob(jobRequestWithId, metadata);

    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(
            ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(jobId).toUri());

    return new ResponseEntity<>(httpHeaders, HttpStatus.ACCEPTED);
}