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:no.kantega.publishing.admin.content.behaviours.attributes.PersistMediaAttributeBehaviour.java

@Override
public void persistAttribute(Connection c, Content content, Attribute attribute)
        throws SQLException, SystemException {
    if (multimediaAO == null) {
        multimediaAO = RootContext.getInstance().getBean(MultimediaDao.class);
        multimediaUploadHandler = RootContext.getInstance().getBean("aksessMultimediaUploadHandler",
                MultimediaUploadHandler.class);

    }//  w ww  .  j a v a2  s  .  c o  m

    if (attribute instanceof MediaAttribute) {
        MediaAttribute mediaAttr = (MediaAttribute) attribute;
        MultipartFile importFile = mediaAttr.getImportFile();
        try {
            if (importFile != null) {
                Multimedia multimedia = null;

                try {
                    if (content.getStatus() == ContentStatus.PUBLISHED) {
                        // When a file is uploaded and published directly, the old image if overwritten
                        // This cannot be done for drafts or pages awaiting to be published
                        int oldId = Integer.parseInt(mediaAttr.getValue());
                        multimedia = multimediaAO.getMultimedia(oldId);
                    }
                } catch (NumberFormatException e) {

                }

                String filename = importFile.getOriginalFilename();

                if (multimedia == null) {
                    multimedia = new Multimedia();

                    int mediaFolderId = -1;
                    String mediaFolder = mediaAttr.getDefaultMediaFolder();
                    if (mediaFolder != null) {
                        try {
                            mediaFolderId = Integer.parseInt(mediaFolder);
                            if (multimediaAO.getMultimedia(mediaFolderId) == null) {
                                mediaFolderId = -1;
                            }
                        } catch (Exception e) {
                            // Name of folder was specified
                        }
                    }

                    if (mediaFolderId == -1) {
                        mediaFolderId = createMediaFolder(mediaFolderId, mediaFolder);
                    }

                    multimedia.setParentId(mediaFolderId);
                }

                multimediaUploadHandler.updateMultimediaWithData(multimedia, importFile.getBytes(), filename,
                        true);
                multimedia.setOwnerPerson(content.getOwnerPerson());
                int id = multimediaAO.setMultimedia(multimedia);
                updateContentProperty(c, content, attribute, id);
                mediaAttr.setValue(String.valueOf(id));
                mediaAttr.setImportFile(null);
            }
        } catch (IllegalStateException e) {
            log.info("Uploaded file was discarded, has been deleted");
        } catch (IOException | InvalidImageFormatException e) {
            throw new SystemException("Feil ved filvedlegg", e);
        }
    }

    super.persistAttribute(c, content, attribute);
}

From source file:org.activiti.app.rest.idm.IdmProfileResource.java

@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/profile-picture", method = RequestMethod.POST, produces = "application/json")
public void uploadProfilePicture(@RequestParam("file") MultipartFile file) {
    Picture picture = null;/*from   w w  w.j av  a 2s . c  o m*/
    try {
        picture = new Picture(file.getBytes(), file.getContentType());
    } catch (IOException e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
    identityService.setUserPicture(SecurityUtils.getCurrentUserId(), picture);
}

From source file:org.apache.servicecomb.demo.springmvc.tests.endpoints.CodeFirstSpringmvcBase.java

public String fileUpload(MultipartFile file1, MultipartFile file2, String name) {
    try {//from  w w w  .  ja v a 2  s.  c  o  m
        return IOUtils.toString(file1.getBytes(), StandardCharsets.UTF_8.name())
                + IOUtils.toString(file2.getBytes(), StandardCharsets.UTF_8.name()) + name;
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.benetech.secureapp.generator.SecureAppGeneratorApplication.java

static void saveMultiPartFileToLocation(MultipartFile file, File formFileUploaded)
        throws IOException, FileNotFoundException {
    byte[] bytes = file.getBytes();
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(formFileUploaded));
    stream.write(bytes);/*from ww w  .  ja  va 2  s .  c  o  m*/
    stream.close();
}

From source file:org.bonitasoft.web.designer.controller.asset.AssetService.java

/**
 * Upload a local asset/*from  www  .  j av  a  2  s .c  o m*/
 */
public Asset upload(MultipartFile file, T component, String type) {
    AssetType assetType = AssetType.getAsset(type);

    checkArgument(file != null && !file.isEmpty(),
            "Part named [file] is needed to successfully import a component");
    checkArgument(assetType != null, ASSET_TYPE_IS_REQUIRED);

    try {

        if (AssetType.JSON.getPrefix().equals(type)) {
            checkWellFormedJson(file.getBytes());
        }

        final Asset asset = new Asset().setName(getOriginalFilename(file.getOriginalFilename()))
                .setType(assetType).setOrder(getNextOrder(component));

        Optional<Asset> existingAsset = Iterables.<Asset>tryFind(component.getAssets(), new Predicate<Asset>() {

            @Override
            public boolean apply(Asset element) {
                return asset.equalsWithoutComponentId(element);
            }
        });
        if (existingAsset.isPresent()) {
            asset.setId(existingAsset.get().getId());
        }

        return save(component, asset, file.getBytes());

    } catch (IOException e) {
        logger.error("Asset creation" + e);
        throw new ServerImportException(format("Error while uploading asset in %s [%s]",
                file.getOriginalFilename(), repository.getComponentName()), e);
    }
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

/**
 *
 * @param applicationName/*from   w w  w .  ja v a  2s  . c o  m*/
 *            .
 * @param serviceName
 *            .
 * @param timeout
 *            .
 * @param templateName
 *            .
 * @param zone
 *            .
 * @param srcFile
 *            .
 * @param propsFile
 *            .
 * @param authGroups
 *            The authorization groups for which this deployment will be available.
 * @param serviceOverridesFile
 *            A file containing overrides for service's properties file.
 * @param cloudOverridesFile
 *            A file containing override parameters to be used by the cloud driver.
 * @param selfHealing
 *            .
 * @return status - success (error) and response - lifecycle events container id (error description)
 * @throws PackagingException
 * @throws DSLException .
 * @throws RestErrorException .
 * @throws TimeoutException .
 * @throws IOException .
 */
@JsonRequestExample(requestBody = "{\"zone\":5,\"template\":\"SMALL_LINUX\","
        + "\"file\":\"packaged service file\",\"props\":\"packaged properties file\"}")
@JsonResponseExample(status = "success", responseBody = "\"b41febb7-f48e-48d4-b14a-a6000d402d93\"")
@PossibleResponseStatuses(responseStatuses = { @PossibleResponseStatus(code = HTTP_OK, description = "success"),
        @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "TimeoutException"),
        @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "PackagingException"),
        @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "IOException"),
        @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "AdminException"),
        @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "DSLException") })
@RequestMapping(value = "applications/{applicationName}/services/{serviceName}/timeout/{timeout}", method = RequestMethod.POST)
@PreAuthorize("isFullyAuthenticated() and hasPermission(#authGroups, 'deploy')")
@ResponseBody
public Object deployElastic(@PathVariable final String applicationName, @PathVariable final String serviceName,
        @PathVariable final int timeout,
        @RequestParam(value = "template", required = false) final String templateName,
        @RequestParam(value = "zone", required = true) final String zone,
        @RequestParam(value = "file", required = true) final MultipartFile srcFile,
        @RequestParam(value = "props", required = true) final MultipartFile propsFile,
        @RequestParam(value = "authGroups", required = false) final String authGroups,
        @RequestParam(value = SERVICE_OVERRIDES_FILE_PARAM, required = false) final MultipartFile serviceOverridesFile,
        @RequestParam(value = CLOUD_OVERRIDES_FILE_PARAM, required = false) final MultipartFile cloudOverridesFile,
        @RequestParam(value = "selfHealing", required = false, defaultValue = "true") final Boolean selfHealing)
        throws TimeoutException, IOException, DSLException, RestErrorException, PackagingException {

    logger.info("Deploying service " + ServiceUtils.getAbsolutePUName(applicationName, serviceName)
            + " with template: " + templateName);
    String actualTemplateName = templateName;
    validateGsmState();
    if (cloud != null) {
        if (templateName == null || templateName.length() == 0) {
            if (cloud.getCloudCompute().getTemplates().isEmpty()) {
                throw new IllegalStateException("Cloud configuration has no compute template defined!");
            }
            actualTemplateName = cloud.getCloudCompute().getTemplates().keySet().iterator().next();
            logger.warning("Compute Template name missing from service deployment request."
                    + " Defaulting to first template: " + actualTemplateName);

        }
    }

    final String absolutePuName = ServiceUtils.getAbsolutePUName(applicationName, serviceName);
    final byte[] propsBytes = propsFile.getBytes();
    final Properties props = new Properties();
    final InputStream is = new ByteArrayInputStream(propsBytes);
    props.load(is);
    final File dest = copyMultipartFileToLocalFile(srcFile);
    final File cloudOverrides = copyMultipartFileToLocalFile(cloudOverridesFile);
    final File destFile = new File(dest.getParent(),
            absolutePuName + "." + FilenameUtils.getExtension(dest.getName()));
    if (destFile.exists()) {
        FileUtils.deleteQuietly(destFile);
    }

    String effectiveAuthGroups = authGroups;
    if (StringUtils.isBlank(effectiveAuthGroups)) {
        if (permissionEvaluator != null) {
            effectiveAuthGroups = permissionEvaluator.getUserAuthGroupsString();
        } else {
            effectiveAuthGroups = "";
        }
    }
    final File localServiceOverridesFile = copyMultipartFileToLocalFile(serviceOverridesFile);

    String lifecycleEventsContainerID = "";
    if (dest.renameTo(destFile)) {
        FileUtils.deleteQuietly(dest);

        final File cloudConfigurationFile = ZipUtils.unzipEntry(destFile,
                "ext/" + CloudifyConstants.SERVICE_CLOUD_CONFIGURATION_FILE_NAME,
                CloudifyConstants.SERVICE_CLOUD_CONFIGURATION_FILE_NAME);
        byte[] cloudConfigurationContents = null;
        if (cloudConfigurationFile != null) {
            cloudConfigurationContents = FileUtils.readFileToByteArray(cloudConfigurationFile);
        }

        lifecycleEventsContainerID = deployElasticProcessingUnit(absolutePuName, applicationName,
                effectiveAuthGroups, zone, destFile, props, actualTemplateName, false, timeout,
                TimeUnit.MINUTES, cloudConfigurationContents, selfHealing.booleanValue(),
                localServiceOverridesFile, cloudOverrides);
        destFile.deleteOnExit();
    } else {
        logger.warning("Deployment file could not be renamed to the absolute pu name."
                + " Deploaying using the name " + dest.getName());
        lifecycleEventsContainerID = deployElasticProcessingUnit(absolutePuName, applicationName,
                effectiveAuthGroups, zone, dest, props, actualTemplateName, false, timeout, TimeUnit.MINUTES,
                null, selfHealing.booleanValue(), localServiceOverridesFile, cloudOverrides);
        dest.deleteOnExit();
    }

    // TODO: move this Key String to the DSL project as a constant.
    // Map<String, String> serviceDetails = new HashMap<String, String>();
    // serviceDetails.put("lifecycleEventsContainerID",
    // lifecycleEventsContainerID.toString());
    return successStatus(lifecycleEventsContainerID);
}

From source file:org.easyrec.controller.PluginUploadController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    String tenantId = ServletUtils.getSafeParameter(request, "tenantId", "");
    String operatorId = ServletUtils.getSafeParameter(request, "operatorId", "");

    logger.info("PluginUploadController: submit called");

    // cast the fubean
    FileUploadBean fubean = (FileUploadBean) command;
    if (fubean == null || fubean.getFile() == null || fubean.getFile().isEmpty()) {
        logger.info("no file or empty file was uploaded, aborting");
        // well, let's do nothing with the fubean for now and return
        return super.onSubmit(request, response, command, errors);
    }/*from   ww  w.j a v a 2 s . c o m*/
    // check if there's content there
    MultipartFile file = fubean.getFile();
    PluginVO plugin = pluginRegistry.checkPlugin(file.getBytes());
    plugin.setOrigFilename(file.getOriginalFilename());
    pluginDAO.storePlugin(plugin);

    ModelAndView mav = new ModelAndView("dev/page");

    mav.addObject("title", "??::?");

    mav.addObject("operatorId", operatorId);
    mav.addObject("tenantId", tenantId);
    mav.addObject("signedinOperatorId", Security.signedInOperatorId(request));

    mav.addObject("page", "plugins");
    List<PluginVO> plugins = pluginDAO.loadPlugins();
    mav.addObject("pluginList", plugins);

    return mav;

    // well, let's do nothing with the fubean for now and return
    //return super.onSubmit(request, response, command, errors);
}

From source file:org.eclipse.vorto.repository.web.AdminController.java

@RequestMapping(value = "/content", method = RequestMethod.POST)
@Secured("ROLE_ADMIN")
public void restoreRepository(@RequestParam("file") MultipartFile file) throws Exception {
    this.repositoryManager.restore(file.getBytes());

}

From source file:org.eclipse.vorto.repository.web.ModelRepositoryController.java

@ApiOperation(value = "Model Image upload")
@RequestMapping(value = "/image", method = RequestMethod.POST)
public void uploadModelImage(
        @ApiParam(value = "Image", required = true) @RequestParam("file") MultipartFile file,
        @ApiParam(value = "Namespace", required = true) final @RequestParam String namespace,
        @ApiParam(value = "name", required = true) final @RequestParam String name,
        @ApiParam(value = "version", required = true) final @RequestParam String version) {
    logger.info("uploadImage: [" + file.getOriginalFilename() + "]");
    try {//from   w  ww  .  j ava 2 s  . c om
        modelRepository.addModelImage(new ModelId(name, namespace, version), file.getBytes());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.egov.eis.web.controller.masters.employee.ViewAndUpdateEmployeController.java

@RequestMapping(value = "/update/{code}", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute final Employee employee, final BindingResult errors,
        final RedirectAttributes redirectAttrs, final Model model, @RequestParam final MultipartFile file,
        @RequestParam final String removedJurisdictionIds, @RequestParam final String removedassignIds) {

    final Boolean codeExists = employeeService.validateEmployeeCode(employee);
    if (codeExists)
        errors.rejectValue("code", "Unique.employee.code");

    try {//from   w  w w.  ja  v a 2  s  .co m
        if (!file.isEmpty())
            employee.setSignature(file.getBytes());
    } catch (final IOException e) {
        LOGGER.error("Error in loading Employee Signature" + e.getMessage(), e);
    }
    jurisdictionService.removeDeletedJurisdictions(employee, removedJurisdictionIds);
    final String positionName = employeeService.validatePosition(employee, removedassignIds);
    if (StringUtils.isNotBlank(positionName)) {
        setDropDownValues(model);
        final String fieldError = messageSource.getMessage("position.exists.workflow",
                new String[] { positionName }, null);
        model.addAttribute("error", fieldError);
        return EMPLOYEEFORM;
    }
    if (!employeeService.primaryAssignmentExists(employee) && employee.isActive())
        errors.rejectValue("assignments", "primary.assignment");

    if (employeeService.primaryAssignExistsForSamePeriod(employee))
        errors.rejectValue("assignments", "primary.assignment.daterange");

    if (errors.hasErrors()) {
        setDropDownValues(model);
        model.addAttribute("mode", "update");
        return EMPLOYEEFORM;
    }

    String image = null;
    if (null != employee.getSignature())
        image = Base64.encodeBytes(employee.getSignature());
    model.addAttribute(IMAGE, image);

    employeeService.update(employee);
    redirectAttrs.addFlashAttribute("employee", employee);
    model.addAttribute("message", "Employee updated successfully");
    return EMPLOYEESUCCESS;
}