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.hoteia.qalingo.web.mvc.controller.catalog.AssetController.java

@RequestMapping(value = BoUrls.ASSET_EDIT_URL, method = RequestMethod.POST)
public ModelAndView assetEdit(final HttpServletRequest request, final HttpServletResponse response,
        @Valid AssetForm assetForm, BindingResult result, Model model) throws Exception {

    if (result.hasErrors()) {
        return display(request, response, model);
    }/*from  ww w.j a va  2s .  c  om*/

    final String currentAssetId = assetForm.getId();
    final Asset asset = productMarketingService.getProductMarketingAssetById(currentAssetId);

    MultipartFile multipartFile = assetForm.getFile();
    if (multipartFile != null) {
        long size = multipartFile.getSize();
        asset.setFileSize(size);
    }

    try {
        if (multipartFile.getSize() > 0) {
            String pathProductMarketingImage = multipartFile.getOriginalFilename();
            String assetFileRootPath = engineSettingService.getSettingAssetFileRootPath().getDefaultValue();
            assetFileRootPath.replaceAll("\\\\", "/");
            if (assetFileRootPath.endsWith("/")) {
                assetFileRootPath = assetFileRootPath.substring(0, assetFileRootPath.length() - 1);
            }
            String assetProductMarketingFilePath = engineSettingService
                    .getSettingAssetProductMarketingFilePath().getDefaultValue();
            assetProductMarketingFilePath.replaceAll("\\\\", "/");
            if (assetProductMarketingFilePath.endsWith("/")) {
                assetProductMarketingFilePath = assetProductMarketingFilePath.substring(0,
                        assetProductMarketingFilePath.length() - 1);
            }
            if (!assetProductMarketingFilePath.startsWith("/")) {
                assetProductMarketingFilePath = "/" + assetProductMarketingFilePath;
            }

            String absoluteFilePath = assetFileRootPath + assetProductMarketingFilePath + "/"
                    + asset.getType().toLowerCase() + "/" + pathProductMarketingImage;

            InputStream inputStream = multipartFile.getInputStream();
            URI url = new URI(absoluteFilePath);
            File fileAsset;
            try {
                fileAsset = new File(url);
            } catch (IllegalArgumentException e) {
                fileAsset = new File(url.getPath());
            }
            OutputStream outputStream = new FileOutputStream(fileAsset);
            int readBytes = 0;
            byte[] buffer = new byte[8192];
            while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, readBytes);
            }
            outputStream.close();
            inputStream.close();
            asset.setPath(pathProductMarketingImage);
        }

        // UPDATE ASSET
        webBackofficeService.createOrUpdateProductMarketingAsset(asset, assetForm);

    } catch (Exception e) {
        logger.error("Can't save/update asset file!", e);
    }

    final String urlRedirect = backofficeUrlService.generateUrl(BoUrls.ASSET_DETAILS,
            requestUtil.getRequestData(request), asset);
    return new ModelAndView(new RedirectView(urlRedirect));
}

From source file:org.joget.apps.app.controller.ConsoleWebController.java

@RequestMapping(value = "/console/setting/plugin/upload/submit", method = RequestMethod.POST)
public String consoleSettingPluginUploadSubmit(ModelMap map, HttpServletRequest request) throws IOException {
    MultipartFile pluginFile;

    try {//from  w  ww. j  a  va  2s. c om
        pluginFile = FileStore.getFile("pluginFile");
    } catch (FileLimitException e) {
        map.addAttribute("errorMessage", ResourceBundleUtil.getMessage("general.error.fileSizeTooLarge",
                new Object[] { FileStore.getFileSizeLimit() }));
        return "console/setting/pluginUpload";
    }

    try {
        pluginManager.upload(pluginFile.getOriginalFilename(), pluginFile.getInputStream());
    } catch (Exception e) {
        if (e.getCause().getMessage() != null && e.getCause().getMessage().contains("Invalid jar file")) {
            map.addAttribute("errorMessage", "Invalid jar file");
        } else {
            map.addAttribute("errorMessage", "Error uploading plugin");
        }
        return "console/setting/pluginUpload";
    }
    String url = request.getContextPath() + "/web/console/setting/plugin";
    map.addAttribute("url", url);
    return "console/dialogClose";
}

From source file:org.joget.apps.app.service.AppServiceImpl.java

/**
 * Import Messages from a PO file/*from  w w  w.  j av  a 2 s  . co m*/
 * @param appId
 * @param version
 * @param locale
 * @param multipartFile
 * @throws IOException 
 */
@Transactional
public void importPO(String appId, String version, String locale, MultipartFile multipartFile)
        throws IOException {
    InputStream inputStream = multipartFile.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    AppDefinition appDef = getAppDefinition(appId, version);

    String line = null, key = null, translated = null;
    try {
        while ((line = bufferedReader.readLine()) != null) {
            if (line.startsWith("\"Language: ") && line.endsWith("\\n\"")) {
                locale = line.substring(11, line.length() - 3);
            } else if (line.startsWith("msgid \"") && !line.equals("msgid \"\"")) {
                key = line.substring(7, line.length() - 1);
                translated = null;
            } else if (line.startsWith("msgstr \"")) {
                translated = line.substring(8, line.length() - 1);
            }

            if (key != null && translated != null) {
                Message message = messageDao.loadByMessageKey(key, locale, appDef);
                if (message == null) {
                    message = new Message();
                    message.setLocale(locale);
                    message.setMessageKey(key);
                    message.setAppDefinition(appDef);
                    message.setMessage(translated);
                    messageDao.add(message);
                } else {
                    message.setMessage(translated);
                    messageDao.update(message);
                }
                key = null;
                translated = null;
            }
        }
    } catch (Exception e) {
    } finally {
        bufferedReader.close();
        inputStream.close();
    }
}

From source file:org.jumpmind.symmetric.web.rest.RestService.java

/**
 * Installs and starts a new node//from  w w w .ja  va  2  s.c  o m
 * 
 * @param file
 *            A file stream that contains the node's properties.
 */
@ApiOperation(value = "Load a configuration file to the single engine")
@RequestMapping(value = "engine/install", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ResponseBody
public final void postInstall(@RequestParam MultipartFile file) {
    try {
        Properties properties = new Properties();
        properties.load(file.getInputStream());
        getSymmetricEngineHolder().install(properties);
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.kuali.mobility.writer.service.WriterServiceImpl.java

public Media uploadMediaData(MultipartFile mediaFile, int mediaType) {
    // TODO this whole media saving code should be moved to a media store project!
    Media returnMedia = null;//from   w w  w.j a  v a2s.c  o m
    if (mediaFile != null && !mediaFile.isEmpty()) {
        try {
            String mediaExt = null;
            // Get the file extension from the original filename
            if (mediaFile.getOriginalFilename() != null) {
                String oName = mediaFile.getOriginalFilename();
                int index = oName.lastIndexOf('.');
                if (index > 0) {
                    mediaExt = oName.substring(index + 1);
                }
            }
            // If the extension is still empty, we fallback to .dat
            if (mediaExt == null || mediaExt.length() == 0) {
                mediaExt = ".dat";
            }

            InputStream originalMediaStream = mediaFile.getInputStream();
            Media uploadedMedia = new Media();
            uploadedMedia.setType(mediaType);
            IOUtils.closeQuietly(originalMediaStream);

            /*/
             * Attempt to get the mime type of the media
             */
            if (mediaFile.getContentType() == null || mediaFile.getContentType().length() == 0) {
                if (mediaType == Media.MEDIA_TYPE_VIDEO) {
                    uploadedMedia.setMimeType("video/3gp"); // Fallback format TODO get proper mapping
                }
            } else {
                uploadedMedia.setMimeType(mediaFile.getContentType());
            }
            if (mediaType == Media.MEDIA_TYPE_VIDEO) {
                String originalPath = this.storeMedia(mediaType, mediaExt, false, originalMediaStream);
                uploadedMedia.setPath(originalPath);
                uploadedMedia.setThumbNailPath(""); // No thumbnail for video for now
            } else if (mediaType == Media.MEDIA_TYPE_IMAGE) {
                uploadedMedia.setMimeType("image/jpeg"); // We allways save images a jpeg

                InputStream scaledImageStream = null;
                String newFilePath = null;
                BufferedImage originalImage = ImageIO.read(mediaFile.getInputStream());
                if (originalImage == null) {
                    LOG.error("Failed to read uploaded image - posibly incorrect file type");
                    return null;
                }

                // If we are saving an image, we need to resize the original to the max configured size, and also convert to jpeg
                if (originalImage.getWidth() > MAX_IMAGE_WIDTH
                        || originalImage.getHeight() > MAX_IMAGE_HEIGHT) {
                    scaledImageStream = this.resizeImage(mediaFile.getInputStream(), MAX_IMAGE_WIDTH,
                            MAX_IMAGE_HEIGHT);
                }
                // Image is small enough, just convert to jpeg
                else {
                    scaledImageStream = this.convertToJPEG(mediaFile.getInputStream());
                }
                if (scaledImageStream == null) {
                    LOG.error("Failed to scale uploaded image - posibly incorrect file type");
                    return null;
                }
                newFilePath = this.storeMedia(Media.MEDIA_TYPE_IMAGE, ".jpeg", false, scaledImageStream);
                uploadedMedia.setPath(newFilePath);
                IOUtils.closeQuietly(scaledImageStream);

                // Create a thumbnail of the image
                scaledImageStream = this.resizeImage(mediaFile.getInputStream(), MAX_IMAGE_THUMB_WIDTH,
                        MAX_IMAGE_THUMB_HEIGHT);
                if (scaledImageStream == null) {
                    LOG.error("Failed to scale thumbnail of uploaded image - posibly incorrect file type");
                    return null;
                }
                newFilePath = this.storeMedia(Media.MEDIA_TYPE_IMAGE, ".jpeg", true, scaledImageStream);
                uploadedMedia.setThumbNailPath(newFilePath);
                IOUtils.closeQuietly(scaledImageStream);
            }
            returnMedia = this.maintainMedia(uploadedMedia);
        } catch (IOException e) {
            LOG.error("Exception trying to upload media data", e);
        }
    }
    return returnMedia;
}

From source file:org.kuali.ole.select.controller.OleLicenseRequestController.java

/**
 * This method store the uploaded agreement document to the specified location
 *
 * @return ModelAndView//from  w  ww.j av a  2s  . c o m
 */
private void storeAgreementAttachment(MultipartFile agreementFile) throws IOException {
    String location = "";
    location = getKualiConfigurationService()
            .getPropertyValueAsString(KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)
            + OLEConstants.OleLicenseRequest.AGREEMENT_TMP_LOCATION;
    LOG.info("Agreement Attachment LOG :" + location);
    File dirLocation = new File(location);
    if (!dirLocation.exists()) {
        boolean success = dirLocation.mkdirs();
        if (!success) {
            LOG.error("Could not generate directory for File at: " + dirLocation.getAbsolutePath());
        }
    }
    location = location + File.separator + agreementFile.getOriginalFilename();
    InputStream fileContents = agreementFile.getInputStream();
    File fileOut = new File(location);
    FileOutputStream streamOut = null;
    BufferedOutputStream bufferedStreamOut = null;
    try {
        streamOut = new FileOutputStream(fileOut);
        bufferedStreamOut = new BufferedOutputStream(streamOut);
        int c;
        while ((c = fileContents.read()) != -1) {
            bufferedStreamOut.write(c);
        }
    } finally {
        bufferedStreamOut.close();
        streamOut.close();
    }

}

From source file:org.kuali.rice.krad.document.DocumentControllerServiceImpl.java

/**
 * Builds an attachment for the file (if any) associated with the add note instance.
 *
 * @param form form instance containing the attachment file
 * @param document document instance the attachment should be associated with
 * @param newNote note instance the attachment should be associated with
 * @return Attachment instance for the note, or null if no attachment file was present
 *//*from   w  w  w .  j  a v  a 2  s .c o  m*/
protected Attachment getNewNoteAttachment(DocumentFormBase form, Document document, Note newNote) {
    MultipartFile attachmentFile = form.getAttachmentFile();

    if ((attachmentFile == null) || StringUtils.isBlank(attachmentFile.getOriginalFilename())) {
        return null;
    }

    if (attachmentFile.getSize() == 0) {
        GlobalVariables.getMessageMap().putError(
                String.format("%s.%s", KRADConstants.NEW_DOCUMENT_NOTE_PROPERTY_NAME,
                        KRADConstants.NOTE_ATTACHMENT_FILE_PROPERTY_NAME),
                RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile.getOriginalFilename());

        return null;
    }

    String attachmentTypeCode = null;
    if (newNote.getAttachment() != null) {
        attachmentTypeCode = newNote.getAttachment().getAttachmentTypeCode();
    }

    DocumentAuthorizer documentAuthorizer = getDocumentDictionaryService().getDocumentAuthorizer(document);
    if (!documentAuthorizer.canAddNoteAttachment(document, attachmentTypeCode,
            GlobalVariables.getUserSession().getPerson())) {
        throw buildAuthorizationException("annotate", document);
    }

    Attachment attachment;
    try {
        attachment = getAttachmentService().createAttachment(document.getNoteTarget(),
                attachmentFile.getOriginalFilename(), attachmentFile.getContentType(),
                (int) attachmentFile.getSize(), attachmentFile.getInputStream(), attachmentTypeCode);
    } catch (IOException e) {
        throw new RiceRuntimeException("Unable to store attachment", e);
    }

    return attachment;
}

From source file:org.kuali.rice.krad.web.controller.DocumentControllerBase.java

/**
 * Called by the add note action for adding a note. Method validates, saves attachment and adds the
 * time stamp and author. Calls the UifControllerBase.addLine method to handle generic actions.
 *
 * @param uifForm - document form base containing the note instance that will be inserted into the document
 * @return ModelAndView/*from w  w  w  .  j  a  v a  2s .c o  m*/
 */
@RequestMapping(method = RequestMethod.POST, params = "methodToCall=insertNote")
public ModelAndView insertNote(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
        HttpServletRequest request, HttpServletResponse response) {

    // Get the note add line
    String selectedCollectionPath = uifForm.getActionParamaterValue(UifParameters.SELECTED_COLLECTION_PATH);
    String selectedCollectionId = uifForm.getActionParamaterValue(UifParameters.SELECTED_COLLECTION_ID);

    BindingInfo addLineBindingInfo = (BindingInfo) uifForm.getViewPostMetadata()
            .getComponentPostData(selectedCollectionId, UifConstants.PostMetadata.ADD_LINE_BINDING_INFO);

    String addLinePath = addLineBindingInfo.getBindingPath();
    Object addLine = ObjectPropertyUtils.getPropertyValue(uifForm, addLinePath);
    Note newNote = (Note) addLine;
    newNote.setNotePostedTimestampToCurrent();

    Document document = ((DocumentFormBase) uifForm).getDocument();

    newNote.setRemoteObjectIdentifier(document.getNoteTarget().getObjectId());

    // Get the attachment file
    String attachmentTypeCode = null;
    MultipartFile attachmentFile = uifForm.getAttachmentFile();
    Attachment attachment = null;
    if (attachmentFile != null && !StringUtils.isBlank(attachmentFile.getOriginalFilename())) {
        if (attachmentFile.getSize() == 0) {
            GlobalVariables.getMessageMap().putError(
                    String.format("%s.%s", KRADConstants.NEW_DOCUMENT_NOTE_PROPERTY_NAME,
                            KRADConstants.NOTE_ATTACHMENT_FILE_PROPERTY_NAME),
                    RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile.getOriginalFilename());
        } else {
            if (newNote.getAttachment() != null) {
                attachmentTypeCode = newNote.getAttachment().getAttachmentTypeCode();
            }

            DocumentAuthorizer documentAuthorizer = getDocumentDictionaryService()
                    .getDocumentAuthorizer(document);
            if (!documentAuthorizer.canAddNoteAttachment(document, attachmentTypeCode,
                    GlobalVariables.getUserSession().getPerson())) {
                throw buildAuthorizationException("annotate", document);
            }

            try {
                String attachmentType = null;
                Attachment newAttachment = newNote.getAttachment();
                if (newAttachment != null) {
                    attachmentType = newAttachment.getAttachmentTypeCode();
                }

                attachment = getAttachmentService().createAttachment(document.getNoteTarget(),
                        attachmentFile.getOriginalFilename(), attachmentFile.getContentType(),
                        (int) attachmentFile.getSize(), attachmentFile.getInputStream(), attachmentType);
            } catch (IOException e) {
                throw new RiceRuntimeException("Unable to store attachment", e);
            }
        }
    }

    Person kualiUser = GlobalVariables.getUserSession().getPerson();
    if (kualiUser == null) {
        throw new IllegalStateException("Current UserSession has a null Person.");
    }

    newNote.setAuthorUniversalIdentifier(kualiUser.getPrincipalId());

    // validate the note
    boolean rulePassed = KRADServiceLocatorWeb.getKualiRuleService()
            .applyRules(new AddNoteEvent(document, newNote));

    // if the rule evaluation passed, let's add the note; otherwise, return with an error
    if (rulePassed) {
        DocumentHeader documentHeader = document.getDocumentHeader();

        // adding the attachment after refresh gets called, since the attachment record doesn't get persisted
        // until the note does (and therefore refresh doesn't have any attachment to autoload based on the id, nor does it
        // autopopulate the id since the note hasn't been persisted yet)
        if (attachment != null) {
            newNote.addAttachment(attachment);
        }
        // Save the note if the document is already saved
        if (!documentHeader.getWorkflowDocument().isInitiated()
                && StringUtils.isNotEmpty(document.getNoteTarget().getObjectId())
                && !(document instanceof MaintenanceDocument
                        && NoteType.BUSINESS_OBJECT.getCode().equals(newNote.getNoteTypeCode()))) {

            getNoteService().save(newNote);
        }

        return addLine(uifForm, result, request, response);
    } else {
        return getUIFModelAndView(uifForm);
    }
}

From source file:org.openflamingo.web.fs.HdfsBrowserController.java

/**
 * ?? ./*from  w  w w .  j a  v  a2s. com*/
 *
 * @return REST Response JAXB Object
 */
@RequestMapping(value = "upload", method = RequestMethod.POST, consumes = { "multipart/form-data" })
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseEntity<String> upload(HttpServletRequest req) throws IOException {
    Response response = new Response();
    if (!(req instanceof DefaultMultipartHttpServletRequest)) {
        response.setSuccess(false);
        response.getError().setCause(message("S_FS_SERVICE", "CANNOT_UPLOAD_INVALID", null));
        response.getError().setMessage(message("S_FS_SERVICE", "CANNOT_UPLOAD", null));
        String json = new ObjectMapper().writeValueAsString(response);
        return new ResponseEntity(json, HttpStatus.BAD_REQUEST);
    }

    InputStream inputStream = null;
    try {
        DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) req;
        String pathToUpload = request.getParameter("path");
        String engineId = req.getParameter("engineId");
        MultipartFile uploadedFile = request.getFile("file");
        String originalFilename = uploadedFile.getOriginalFilename();
        String fullyQualifiedPath = pathToUpload.equals("/") ? pathToUpload + originalFilename
                : pathToUpload + FILE_SEPARATOR + originalFilename;
        inputStream = uploadedFile.getInputStream();
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);

        Engine engine = engineService.getEngine(Long.parseLong(engineId));
        FileSystemService fileSystemService = (FileSystemService) lookupService.getService(RemoteService.HDFS,
                engine);

        Context context = getContext(engine);
        String forbiddenPaths = ConfigurationManager.getConfigurationManager()
                .get("hdfs.delete.forbidden.paths", DEFAULT_FORBIDDEN_PATH);
        context.putString("hdfs.delete.forbidden.paths", forbiddenPaths);

        FileSystemCommand command = new FileSystemCommand();
        command.putString("path", fullyQualifiedPath);
        command.putObject("content", bytes);

        boolean file = fileSystemService.save(context, command);
        response.setSuccess(file);
        response.getMap().put("directory", pathToUpload);

        String json = new ObjectMapper().writeValueAsString(response);
        return new ResponseEntity(json, HttpStatus.OK);
    } catch (Exception ex) {
        response.setSuccess(false);
        response.getError().setMessage(ex.getMessage());
        if (ex.getCause() != null)
            response.getError().setCause(ex.getCause().getMessage());
        response.getError().setException(ExceptionUtils.getFullStackTrace(ex));

        String json = new ObjectMapper().writeValueAsString(response);
        return new ResponseEntity(json, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.openlmis.fulfillment.service.TemplateService.java

/**
 * Validate ".jrxml" report file with JasperCompileManager.
 * If report is valid create additional report parameters.
 * Save additional report parameters as TemplateParameter list.
 * Save report file as ".jasper" in byte array in Template class.
 * If report is not valid throw exception.
 *///from w w w.  j  av a  2  s.c o  m
private void validateFile(Template template, MultipartFile file) {
    throwIfFileIsNull(file);
    throwIfIncorrectFileType(file);
    throwIfFileIsEmpty(file);

    try {
        JasperReport report = JasperCompileManager.compileReport(file.getInputStream());
        JRParameter[] jrParameters = report.getParameters();

        if (jrParameters != null && jrParameters.length > 0) {
            setTemplateParameters(template, jrParameters);
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(report);
        template.setData(bos.toByteArray());
    } catch (JRException ex) {
        throw new ReportingException(ex, ERROR_REPORTING_FILE_INVALID);
    } catch (IOException ex) {
        throw new ReportingException(ex, ERROR_IO, ex.getMessage());
    }
}