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

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

Introduction

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

Prototype

byte[] getBytes() throws IOException;

Source Link

Document

Return the contents of the file as an array of bytes.

Usage

From source file:org.kuali.coeus.propdev.impl.attachment.Narrative.java

@Override
public void init(MultipartFile multipartFile) throws Exception {
    this.name = multipartFile.getOriginalFilename();
    this.size = multipartFile.getSize();

    NarrativeAttachment attachment = new NarrativeAttachment();
    attachment.setType(multipartFile.getContentType());
    attachment.setData(multipartFile.getBytes());
    attachment.setName(multipartFile.getOriginalFilename());
    setNarrativeAttachment(attachment);/*from  w  ww.j  a  v a  2s .  com*/
}

From source file:org.kuali.coeus.propdev.impl.hierarchy.ProposalHierarchyServiceImpl.java

@Override
public void rejectProposalDevelopmentDocument(String proposalNumber, String reason, String principalName,
        MultipartFile rejectFile) throws WorkflowException, ProposalHierarchyException, IOException {
    DevelopmentProposal pbo = getDevelopmentProposal(proposalNumber);
    ProposalDevelopmentDocument pDoc = (ProposalDevelopmentDocument) documentService
            .getByDocumentHeaderId(pbo.getProposalDocument().getDocumentNumber());
    if (!pbo.isInHierarchy()) {
        rejectProposal(pDoc, renderMessage(PROPOSAL_ROUTING_REJECTED_ANNOTATION, reason), principalName,
                renderMessage(HIERARCHY_REJECTED_APPSTATUS));
    } else if (pbo.isParent()) {
        rejectProposalHierarchy(pDoc, reason, principalName);
    } else {/*  w ww.  ja va2 s.  co m*/
        //it is a child or in some unknown state, either way we do not support rejecting it.
        throw new UnsupportedOperationException(
                String.format("Cannot reject proposal %s it is a hierarchy child or ", proposalNumber));
    }

    if (rejectFile != null && rejectFile.getBytes().length > 0) {
        Narrative narrative = new Narrative();
        narrative.setName(rejectFile.getOriginalFilename());
        narrative.setComments(reason);
        try {
            narrative.init(rejectFile);
        } catch (Exception e) {
            throw new RuntimeException("Error Initializing narrative attachment file", e);
        }
        narrative.setNarrativeTypeCode(getParameterService().getParameterValueAsString(
                ProposalDevelopmentDocument.class, Constants.REJECT_NARRATIVE_TYPE_CODE_PARAM));
        NarrativeStatus status = (NarrativeStatus) dataObjectService.findUnique(NarrativeStatus.class,
                QueryByCriteria.Builder.forAttribute("code", "C").build());
        narrative.setNarrativeStatus(status);
        narrative.setModuleStatusCode(status.getCode());
        narrative.setModuleTitle("Proposal rejection attachment.");
        narrative.setContactName(globalVariableService.getUserSession().getPrincipalName());
        narrative.setPhoneNumber(globalVariableService.getUserSession().getPerson().getPhoneNumber());
        narrative.setEmailAddress(globalVariableService.getUserSession().getPerson().getEmailAddress());
        getLegacyNarrativeService().prepareNarrative(pDoc, narrative);
        pDoc.getDevelopmentProposal().getInstituteAttachments().add(narrative);
        dataObjectService.save(pDoc);
    }

}

From source file:org.kuali.coeus.propdev.impl.person.attachment.ProposalPersonBiography.java

@Override
public void init(MultipartFile multipartFile) throws Exception {
    this.name = multipartFile.getOriginalFilename();
    this.size = multipartFile.getSize();

    ProposalPersonBiographyAttachment attachment = new ProposalPersonBiographyAttachment();
    attachment.setType(multipartFile.getContentType());
    attachment.setData(multipartFile.getBytes());
    attachment.setName(multipartFile.getOriginalFilename());
    setPersonnelAttachment(attachment);/*  www .  j a  v  a  2s .  c  o  m*/
}

From source file:org.kuali.coeus.propdev.impl.s2s.ProposalDevelopmentS2SController.java

@Transactional
@RequestMapping(value = "/proposalDevelopment", params = { "methodToCall=addUserAttachedForm" })
public ModelAndView addUserAttachedForm(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form)
        throws Exception {
    S2sUserAttachedForm s2sUserAttachedForm = form.getS2sUserAttachedForm();
    ProposalDevelopmentDocument proposalDevelopmentDocument = form.getProposalDevelopmentDocument();

    MultipartFile userAttachedFormFile = s2sUserAttachedForm.getNewFormFile();

    s2sUserAttachedForm.setNewFormFileBytes(userAttachedFormFile.getBytes());
    s2sUserAttachedForm.setFormFileName(userAttachedFormFile.getOriginalFilename());
    s2sUserAttachedForm/*from  w  w w .  j  a v  a2s . c o m*/
            .setProposalNumber(proposalDevelopmentDocument.getDevelopmentProposal().getProposalNumber());
    try {
        List<S2sUserAttachedForm> userAttachedForms = getS2sUserAttachedFormService()
                .extractNSaveUserAttachedForms(proposalDevelopmentDocument, s2sUserAttachedForm);
        proposalDevelopmentDocument.getDevelopmentProposal().getS2sUserAttachedForms()
                .addAll(userAttachedForms);
        form.setS2sUserAttachedForm(new S2sUserAttachedForm());
    } catch (S2SException ex) {
        LOG.error(ex.getMessage(), ex);
        if (ex.getTabErrorKey() != null) {
            if (getGlobalVariableService().getMessageMap()
                    .getErrorMessagesForProperty(ex.getTabErrorKey()) == null) {
                getGlobalVariableService().getMessageMap().putError(ex.getTabErrorKey(), ex.getErrorKey(),
                        ex.getParams());
            }
        } else {
            getGlobalVariableService().getMessageMap().putError(Constants.NO_FIELD, ex.getErrorKey(),
                    ex.getMessageWithParams());
        }
    }

    return super.save(form);
}

From source file:org.kuali.rice.krad.labs.fileUploads.XmlIngesterController.java

/**
 * Copies the MultipartFiles into an XmlDocCollection list
 *
 * <p>/*from  ww w .j  a  va2s  .  c om*/
 * Reads each of the input files into temporary files to get File reference needed
 * to create FileXmlDocCollection objects.  Also verifies that only .xml or .zip files are
 * to be processed.
 * </p>
 *
 * @param fileList list of MultipartFiles selected for ingestion
 * @param tempFiles temporary files used to get File reference
 *
 * @return uploaded files in a List of XmlDocCollections
 */
protected List<XmlDocCollection> copyInputFiles(List<MultipartFile> fileList, List<File> tempFiles) {
    List<XmlDocCollection> collections = new ArrayList<XmlDocCollection>();
    for (MultipartFile file : fileList) {
        if (file == null || StringUtils.isBlank(file.getOriginalFilename())) {
            continue;
        }

        // Need to copy into temp file get File reference because XmlDocs based on ZipFile
        // can't be constructed without a file reference.
        FileOutputStream fos = null;
        File temp = null;
        try {
            temp = File.createTempFile("ingester", null);
            tempFiles.add(temp);
            fos = new FileOutputStream(temp);
            fos.write(file.getBytes());
        } catch (IOException ioe) {
            GlobalVariables.getMessageMap().putErrorForSectionId(XmlIngesterConstants.INGESTER_SECTION_ID,
                    XmlIngesterConstants.ERROR_INGESTER_COPY_FILE, file.getOriginalFilename(),
                    ExceptionUtils.getFullStackTrace(ioe));
            continue;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ioe) {
                    //                          LOG.error("Error closing temp file output stream: " + temp, ioe);
                }
            }
        }

        // only .zip and .xml files will be processed
        if (file.getOriginalFilename().toLowerCase().endsWith(".zip")) {
            try {
                collections.add(new ZipXmlDocCollection(temp));
            } catch (IOException ioe) {
                GlobalVariables.getMessageMap().putErrorForSectionId(XmlIngesterConstants.INGESTER_SECTION_ID,
                        XmlIngesterConstants.ERROR_INGESTER_LOAD_FILE, file.getOriginalFilename());
            }
        } else if (file.getOriginalFilename().endsWith(".xml")) {
            collections.add(new FileXmlDocCollection(temp, file.getOriginalFilename()));
        } else {
            GlobalVariables.getMessageMap().putErrorForSectionId(XmlIngesterConstants.INGESTER_SECTION_ID,
                    XmlIngesterConstants.ERROR_INGESTER_EXTRANEOUS_FILE, file.getOriginalFilename());
        }
    }

    return collections;
}

From source file:org.mitre.mpf.mvc.controller.MediaController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public ResponseEntity saveMediaFileUpload(MultipartHttpServletRequest request, HttpServletResponse response)
        throws WfmProcessingException, MpfServiceException {
    log.debug("[saveMediaFileUpload]");
    File newFile = null;//from  w  ww.j  a v  a  2s .  c o  m
    String desiredPathParam = request.getParameter("desiredpath");
    log.debug("Upload to Directory:" + desiredPathParam);
    if (desiredPathParam == null)
        return new ResponseEntity<>("{\"error\":\"desiredPathParam Empty\"}", HttpStatus.INTERNAL_SERVER_ERROR);
    String webTmpDirectory = propertiesUtil.getRemoteMediaCacheDirectory().getAbsolutePath();

    try {
        //verify the desired path
        File desiredPath = new File(desiredPathParam);
        if (!desiredPath.exists() || !desiredPath.getAbsolutePath().startsWith(webTmpDirectory)) {//make sure it is valid and within the remote-media directory
            String err = "Error with desired path: " + desiredPathParam;
            log.error(err);
            return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        Iterator<String> itr = request.getFileNames();
        while (itr.hasNext()) {
            String uploadedFile = itr.next();
            MultipartFile file = request.getFile(uploadedFile);
            String filename = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            String contentType = ioUtils.getMimeType(bytes);

            log.debug("[saveMediaFileUpload] File:" + filename + "  ContentType:" + contentType + " Size:"
                    + bytes.length);

            if (filename.isEmpty()) {
                String err = "The filename is empty during upload of the MultipartFile.";
                log.error(err);
                return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR);
            }

            //return error if the file has an invalid content type and the filename does not have a valid extension
            if (!ioUtils.isApprovedFile(contentType, filename)) {
                String msg = "The media is not a supported type. Please add a whitelist." + contentType
                        + " entry to the mediaType.properties file.";
                log.error(msg + " File:" + filename);
                return new ResponseEntity<>("{\"error\":\"" + msg + "\"}", HttpStatus.INTERNAL_SERVER_ERROR);
            }

            //get a new filename
            newFile = ioUtils.getNewFileName(desiredPath.getAbsolutePath(), filename);

            //save the file
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile));
            stream.write(bytes);
            stream.close();
            log.info("Completed upload and write of {} to {} ContentType:{}", newFile.getPath(),
                    newFile.getAbsolutePath(), contentType);
            return new ResponseEntity<>(filename, HttpStatus.OK);
        }
    } catch (IOException badWrite) {
        String err = "Error writing media to temp file";
        log.error(err);
        return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR);

    } catch (Exception e) {
        String err = "Unknown file upload error";
        log.error(err, e);
        return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    String err = "Unknown file upload error";
    log.error(err);
    return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR);
}

From source file:org.nextframework.bean.editors.FileEditor.java

public void setValue(Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipartFile = (MultipartFile) value;
        long size = multipartFile.getSize();
        try {//from www .  java2 s  . co m
            File file = createFile(value);
            String name = multipartFile.getOriginalFilename();
            name = name.replace('\\', '/');
            if (name.contains("/")) {
                name = name.substring(name.indexOf('/'));
            }

            file.setName(name);
            file.setContenttype(multipartFile.getContentType());
            file.setContent(multipartFile.getBytes());
            file.setSize(size);
            super.setValue(file);
        } catch (IOException ex) {
            logger.error("Cannot read contents of multipart file", ex);
            throw new IllegalArgumentException("Cannot read contents of multipart file: " + ex.getMessage());
        }
    } else if (value instanceof File) {
        super.setValue(value);
    }
}

From source file:org.nishkarma.petclinic.controller.MailController.java

@RequestMapping(value = "/mail/sendMailWithAttachment", method = RequestMethod.POST)
public String sendMailWithAttachment(@RequestParam("recipientName") final String recipientName,
        @RequestParam("recipientEmail") final String recipientEmail,
        @RequestParam("attachment") final MultipartFile attachment, final Locale locale)
        throws MessagingException, IOException {

    logger.debug("recipientName=" + recipientName);
    logger.debug("recipientEmail=" + recipientEmail);

    try {//from ww w.j  av  a 2  s . c om

        this.emailService.sendMailWithAttachment(recipientName, recipientEmail,
                attachment.getOriginalFilename(), attachment.getBytes(), attachment.getContentType(), locale);
    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        throw new NishkarmaException(
                NishkarmaMessageSource.getMessage("exception_message", NishkarmaLocaleUtil.resolveLocale()));

    }

    return "redirect:sent";

}

From source file:org.nishkarma.petclinic.controller.MailController.java

@RequestMapping(value = "/mail/sendMailWithInlineImage", method = RequestMethod.POST)
public String sendMailWithInline(@RequestParam("recipientName") final String recipientName,
        @RequestParam("recipientEmail") final String recipientEmail,
        @RequestParam("image") final MultipartFile image, final Locale locale)
        throws MessagingException, IOException {

    logger.debug("recipientName=" + recipientName);
    logger.debug("recipientEmail=" + recipientEmail);

    try {//from  www.j a  v  a 2s.  c o  m

        this.emailService.sendMailWithInline(recipientName, recipientEmail, image.getName(), image.getBytes(),
                image.getContentType(), locale);
    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        throw new NishkarmaException(
                NishkarmaMessageSource.getMessage("exception_message", NishkarmaLocaleUtil.resolveLocale()));

    }

    return "redirect:sent";

}

From source file:org.openmrs.module.reporting.web.reports.renderers.ExcelReportRendererFormController.java

/**
 * Saves report design/*w  ww  .  ja v a 2 s.co  m*/
 * @throws ClassNotFoundException 
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 */
@SuppressWarnings("unchecked")
@RequestMapping("/module/reporting/reports/renderers/saveExcelReportRenderer")
public String saveExcelReportRenderer(ModelMap model, HttpServletRequest request,
        @RequestParam(required = false, value = "uuid") String uuid,
        @RequestParam(required = true, value = "name") String name,
        @RequestParam(required = false, value = "description") String description,
        @RequestParam(required = true, value = "reportDefinition") String reportDefinitionUuid,
        @RequestParam(required = true, value = "rendererType") Class<? extends ReportTemplateRenderer> rendererType,
        @RequestParam(required = false, value = "properties") String properties,
        @RequestParam(required = false, value = "resourceId") String resourceId,
        @RequestParam(required = false, value = "expressionPrefix") String expressionPrefix,
        @RequestParam(required = false, value = "expressionSuffix") String expressionSuffix,
        @RequestParam(required = false, value = "includeDataSetNameAndParameters") String includeDataSetNameAndParameters,
        @RequestParam(required = true, value = "successUrl") String successUrl)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    ReportService rs = Context.getService(ReportService.class);
    ReportDesign design = null;

    if (StringUtils.isNotEmpty(uuid)) {
        design = rs.getReportDesignByUuid(uuid);
    }

    if (design == null) {
        design = new ReportDesign();
    }

    design.setName(name);
    design.setDescription(description);
    design.setReportDefinition(
            Context.getService(ReportDefinitionService.class).getDefinitionByUuid(reportDefinitionUuid));
    design.setRendererType(rendererType);

    if (ExcelTemplateRenderer.class.isAssignableFrom(design.getRendererType())) {
        WidgetHandler propHandler = HandlerUtil.getPreferredHandler(WidgetHandler.class, Properties.class);
        Properties props = (Properties) propHandler.parse(properties, Properties.class);

        Class<?> rt = Context.loadClass(design.getRendererType().getName());
        ReportTemplateRenderer type = (ReportTemplateRenderer) rt.newInstance();

        MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request;
        MultipartFile file = mpr.getFile("resource");
        Set<String> foundResources = new HashSet<String>();

        if (file != null) {
            try {
                ReportDesignResource resource = null;
                if (!StringUtils.isEmpty(resourceId)) {
                    foundResources.add(resourceId);
                    resource = design.getResourceByUuid(resourceId);
                } else {
                    resource = new ReportDesignResource();
                }
                String fileName = file.getOriginalFilename();
                if (StringUtils.isNotEmpty(fileName)) {
                    int index = fileName.lastIndexOf(".");
                    resource.setReportDesign(design);
                    resource.setContentType(file.getContentType());
                    resource.setName(fileName.substring(0, index));
                    resource.setExtension(fileName.substring(index + 1));
                    resource.setContents(file.getBytes());
                    design.getResources().add(resource);
                }
            } catch (Exception e) {
                throw new RuntimeException("Unable to add resource to design.", e);
            }

        }

        for (Iterator<ReportDesignResource> i = design.getResources().iterator(); i.hasNext();) {
            ReportDesignResource r = i.next();
            if (r.getId() != null && !foundResources.contains(r.getUuid())) {
                i.remove();
            }
        }

        if (!StringUtils.isEmpty(expressionPrefix)
                && !expressionPrefix.equals(type.getExpressionPrefix(design))) {
            props.setProperty("expressionPrefix", expressionPrefix);
        }

        if (!StringUtils.isEmpty(expressionSuffix)
                && !expressionSuffix.equals(type.getExpressionSuffix(design))) {
            props.setProperty("expressionSuffix", expressionSuffix);
        }

        design.setProperties(props);
    } else {
        Properties p = new Properties();
        if ("true".equals(includeDataSetNameAndParameters)) {
            p.setProperty(XlsReportRenderer.INCLUDE_DATASET_NAME_AND_PARAMETERS_PROPERTY, "true");
        }
        design.setProperties(p);
    }

    String pathToRemove = "/" + WebConstants.WEBAPP_NAME;
    if (StringUtils.isEmpty(successUrl)) {
        successUrl = "/module/reporting/reports/manageReportDesigns.form";
    } else if (successUrl.startsWith(pathToRemove)) {
        successUrl = successUrl.substring(pathToRemove.length());
    }
    design = rs.saveReportDesign(design);
    return "redirect:" + successUrl;
}