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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Return the name of the parameter in the multipart form.

Usage

From source file:org.activiti.app.rest.runtime.AbstractRelatedContentResource.java

protected ContentItemRepresentation uploadFile(User user, MultipartFile file, String taskId,
        String processInstanceId) {
    if (file != null && file.getName() != null) {
        try {// ww  w. j  av a2  s . c om
            String contentType = file.getContentType();

            // temp additional content type check for IE9 flash uploads
            if (StringUtils.equals(file.getContentType(), "application/octet-stream")) {
                contentType = getContentTypeForFileExtension(file);
            }

            ContentItem contentItem = contentService.newContentItem();
            contentItem.setName(getFileName(file));
            contentItem.setProcessInstanceId(processInstanceId);
            contentItem.setTaskId(taskId);
            contentItem.setMimeType(contentType);
            contentItem.setCreatedBy(user.getId());
            contentItem.setLastModifiedBy(user.getId());
            contentService.saveContentItem(contentItem, file.getInputStream());

            return createContentItemResponse(contentItem);

        } catch (IOException e) {
            throw new BadRequestException("Error while reading file data", e);
        }

    } else {
        throw new BadRequestException("File to upload is missing");
    }
}

From source file:org.activiti.rest.dmn.service.api.repository.DmnDeploymentCollectionResource.java

@RequestMapping(value = "/dmn-repository/deployments", method = RequestMethod.POST, produces = "application/json")
public DmnDeploymentResponse uploadDeployment(
        @RequestParam(value = "tenantId", required = false) String tenantId, HttpServletRequest request,
        HttpServletResponse response) {/*from w  ww. ja v  a2 s  .c o m*/

    if (request instanceof MultipartHttpServletRequest == false) {
        throw new ActivitiIllegalArgumentException("Multipart request is required");
    }

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    if (multipartRequest.getFileMap().size() == 0) {
        throw new ActivitiIllegalArgumentException("Multipart request with file content is required");
    }

    MultipartFile file = multipartRequest.getFileMap().values().iterator().next();

    try {
        DmnDeploymentBuilder deploymentBuilder = dmnRepositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !(fileName.endsWith(".dmn") || fileName.endsWith(".xml"))) {
            fileName = file.getName();
        }

        if (fileName.endsWith(".dmn") || fileName.endsWith(".xml")) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else {
            throw new ActivitiIllegalArgumentException("File must be of type .xml or .dmn");
        }
        deploymentBuilder.name(fileName);

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }

        DmnDeployment deployment = deploymentBuilder.deploy();

        response.setStatus(HttpStatus.CREATED.value());

        return dmnRestResponseFactory.createDmnDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof ActivitiException) {
            throw (ActivitiException) e;
        }
        throw new ActivitiException(e.getMessage(), e);
    }
}

From source file:org.activiti.rest.form.service.api.repository.FormDeploymentCollectionResource.java

@RequestMapping(value = "/form-repository/deployments", method = RequestMethod.POST, produces = "application/json")
public FormDeploymentResponse uploadDeployment(
        @RequestParam(value = "tenantId", required = false) String tenantId, HttpServletRequest request,
        HttpServletResponse response) {/*  w  w w. ja  va2s.com*/

    if (request instanceof MultipartHttpServletRequest == false) {
        throw new ActivitiIllegalArgumentException("Multipart request is required");
    }

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    if (multipartRequest.getFileMap().size() == 0) {
        throw new ActivitiIllegalArgumentException("Multipart request with file content is required");
    }

    MultipartFile file = multipartRequest.getFileMap().values().iterator().next();

    try {
        FormDeploymentBuilder deploymentBuilder = formRepositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !(fileName.endsWith(".form") || fileName.endsWith(".xml"))) {
            fileName = file.getName();
        }

        if (fileName.endsWith(".form") || fileName.endsWith(".xml")) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else {
            throw new ActivitiIllegalArgumentException("File must be of type .xml or .form");
        }
        deploymentBuilder.name(fileName);

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }

        FormDeployment deployment = deploymentBuilder.deploy();
        response.setStatus(HttpStatus.CREATED.value());

        return formRestResponseFactory.createFormDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof ActivitiException) {
            throw (ActivitiException) e;
        }
        throw new ActivitiException(e.getMessage(), e);
    }

}

From source file:org.aon.esolutions.appconfig.web.controller.EnvironmentController.java

@Transactional
@RequestMapping(value = "/{environmentName}/import", method = RequestMethod.POST)
public void importProperties(@PathVariable String applicationName, @PathVariable String environmentName,
        @RequestParam(value = "file") MultipartFile multipartFile,
        @RequestParam(value = "importMode") String importMode) {

    if (multipartFile.getName().endsWith(".xml") || multipartFile.getOriginalFilename().endsWith(".xml")) {
        new XmlImporter(applicationRepository, environmentRepository, updateUtility)
                .importFromXml(multipartFile, importMode);
        return;/*www .  ja v a2  s  . c o m*/
    }

    Environment env = updateUtility.getEnvironmentForWrite(applicationName, environmentName);

    if (env != null) {
        Properties props = new Properties();

        try {
            props.load(multipartFile.getInputStream());
        } catch (IOException e) {
            logger.error("Error importing properties", e);
            throw new IllegalArgumentException("Uploaded file does not look like a properties file");
        }

        if ("full".equals(importMode)) {
            env.clearVariables();
        } else if ("newOnly".equals(importMode)) {
            for (Entry<String, String> entry : env.getVariableEntries()) {
                props.remove(entry.getKey());
            }
        }

        for (Object key : props.keySet()) {
            env.put((String) key, props.getProperty((String) key));
            env.getEncryptedVariables().remove((String) key);
        }

        updateUtility.saveEnvironment(env);
    }
}

From source file:org.encuestame.mvc.page.FileUploadController.java

/**
 * Upload Profile for User Account./* ww  w . ja  va  2s .  c  om*/
 * @param multipartFile
 * @return
 */
@PreAuthorize("hasRole('ENCUESTAME_USER')")
@RequestMapping(value = "/file/upload/profile", method = RequestMethod.POST)
public ModelAndView handleUserProfileFileUpload(@RequestParam("file") MultipartFile multipartFile) {
    ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
    if (!multipartFile.isEmpty()) {
        log.debug(multipartFile.getName());
        String orgName = multipartFile.getOriginalFilename();
        log.debug("org name " + orgName);
        //TODO: convert name to numbers, MD5 hash.
        String filePath = null;
        try {
            log.debug("getting file path for this user");
            filePath = getPictureService()
                    .getAccountUserPicturePath(getSecurityService().getUserAccount(getUserPrincipalUsername()));
            InputStream stream = multipartFile.getInputStream();
            try {
                //generate thumbnails
                thumbnailGeneratorEngine.generateThumbnails(PathUtil.DEFAUL_PICTURE_PREFIX, stream,
                        multipartFile.getContentType(), filePath);
            } catch (Exception e) {
                //e.printStackTrace();
                log.error(e);
            } finally {
                stream.close();
            }
            //TODO: after save image, we need relationship user with profile picture.
            //I suggest store ID on user account table, to retrieve easily future profile image.
            //BUG 102
        } catch (IllegalStateException e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (EnMeNoResultsFoundException e) {
            ///e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (EnmeFailOperation e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        }
        // Save the file here
        mav.addObject("status", "saved");
        mav.addObject("id", filePath);
    } else {
        mav.addObject("status", "failed");
    }
    return mav;
}

From source file:org.esupportail.publisher.service.FileService.java

private Pair<Boolean, MultipartException> isAuthorizedMimeType(final MultipartFile file,
        final FileUploadHelper fileUploadHelper) {
    if (file != null && !file.isEmpty()) {
        final String detectedType = file.getContentType();
        log.debug("Detected file Content informations {} ", detectedType);

        if (detectedType != null && fileUploadHelper.getAuthorizedMimeType() != null
                && fileUploadHelper.getAuthorizedMimeType().contains(detectedType)) {
            return new Pair<Boolean, MultipartException>(true, null);
        }/*from  w  ww  .j  a va 2  s .  co m*/
        log.warn("File {} with ContentType {} isn't authorized", file.getName(), detectedType);
        return new Pair<Boolean, MultipartException>(false, new UnsupportedMimeTypeException(detectedType));
    }
    return new Pair<Boolean, MultipartException>(false, new MultipartException(
            "Unable to read the content type of an empty file", new NullArgumentException("file")));
}

From source file:org.fao.geonet.api.site.LogosApi.java

@ApiOperation(value = "Add a logo", notes = "", authorizations = {
        @Authorization(value = "basicAuth") }, nickname = "addLogo")
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@PreAuthorize("hasRole('UserAdmin')")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Logo added."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_USER_ADMIN) })
@ResponseStatus(value = HttpStatus.CREATED)
@ResponseBody/*from  ww  w. j  av a 2  s  .c  om*/
public ResponseEntity addLogo(
        @ApiParam(value = "The logo image to upload") @RequestParam("file") MultipartFile[] file,
        @ApiParam(value = "Overwrite if exists", required = false) @RequestParam(defaultValue = "false", required = false) boolean overwrite)
        throws Exception {
    ApplicationContext appContext = ApplicationContextHolder.get();
    Path directoryPath;
    synchronized (this) {
        if (this.logoDirectory == null) {
            this.logoDirectory = Resources.locateHarvesterLogosDirSMVC(appContext);
        }
        directoryPath = this.logoDirectory;
    }

    for (MultipartFile f : file) {
        String fileName = f.getName();

        checkFileName(fileName);

        Path filePath = directoryPath.resolve(f.getOriginalFilename());
        if (Files.exists(filePath) && overwrite) {
            IO.deleteFile(filePath, true, "Deleting file");
            filePath = directoryPath.resolve(f.getOriginalFilename());
        } else if (Files.exists(filePath)) {
            throw new ResourceAlreadyExistException(f.getOriginalFilename());
        }

        filePath = Files.createFile(filePath);
        FileUtils.copyInputStreamToFile(f.getInputStream(), filePath.toFile());
    }
    return new ResponseEntity(HttpStatus.CREATED);
}

From source file:org.flowable.app.rest.service.api.repository.AppDeploymentCollectionResource.java

@ApiOperation(value = "Create a new app deployment", tags = {
        "App Deployments" }, consumes = "multipart/form-data", produces = "application/json", notes = "The request body should contain data of type multipart/form-data. There should be exactly one file in the request, any additional files will be ignored. The deployment name is the name of the file-field passed in. Make sure the file-name ends with .app, .zip or .bar.")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the app deployment was created."),
        @ApiResponse(code = 400, message = "Indicates there was no content present in the request body or the content mime-type is not supported for app deployment. The status-description contains additional information.") })
@ApiImplicitParams({ @ApiImplicitParam(name = "file", paramType = "form", dataType = "java.io.File") })
@PostMapping(value = "/app-repository/deployments", produces = "application/json", consumes = "multipart/form-data")
public AppDeploymentResponse uploadDeployment(
        @ApiParam(name = "tenantId") @RequestParam(value = "tenantId", required = false) String tenantId,
        HttpServletRequest request, HttpServletResponse response) {

    if (restApiInterceptor != null) {
        restApiInterceptor.executeNewDeploymentForTenantId(tenantId);
    }//from   w w  w.  j av  a  2 s .  c  o  m

    if (!(request instanceof MultipartHttpServletRequest)) {
        throw new FlowableIllegalArgumentException("Multipart request is required");
    }

    String queryString = request.getQueryString();
    Map<String, String> decodedQueryStrings = splitQueryString(queryString);

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    if (multipartRequest.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("Multipart request with file content is required");
    }

    MultipartFile file = multipartRequest.getFileMap().values().iterator().next();

    try {
        AppDeploymentBuilder deploymentBuilder = appRepositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !(fileName.endsWith(".app")
                || fileName.toLowerCase().endsWith(".bar") || fileName.toLowerCase().endsWith(".zip"))) {
            fileName = file.getName();
        }

        if (fileName.endsWith(".app")) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else if (fileName.toLowerCase().endsWith(".bar") || fileName.toLowerCase().endsWith(".zip")) {
            deploymentBuilder.addZipInputStream(new ZipInputStream(file.getInputStream()));
        } else {
            throw new FlowableIllegalArgumentException("File must be of type .app");
        }

        if (!decodedQueryStrings.containsKey("deploymentName")
                || StringUtils.isEmpty(decodedQueryStrings.get("deploymentName"))) {
            String fileNameWithoutExtension = fileName.split("\\.")[0];

            if (StringUtils.isNotEmpty(fileNameWithoutExtension)) {
                fileName = fileNameWithoutExtension;
            }

            deploymentBuilder.name(fileName);

        } else {
            deploymentBuilder.name(decodedQueryStrings.get("deploymentName"));
        }

        if (decodedQueryStrings.containsKey("deploymentKey")
                && StringUtils.isNotEmpty(decodedQueryStrings.get("deploymentKey"))) {
            deploymentBuilder.key(decodedQueryStrings.get("deploymentKey"));
        }

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }
        deploymentBuilder.name(fileName);

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }

        if (restApiInterceptor != null) {
            restApiInterceptor.enhanceDeployment(deploymentBuilder);
        }

        AppDeployment deployment = deploymentBuilder.deploy();
        response.setStatus(HttpStatus.CREATED.value());

        return appRestResponseFactory.createAppDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof FlowableException) {
            throw (FlowableException) e;
        }
        throw new FlowableException(e.getMessage(), e);
    }
}

From source file:org.flowable.cmmn.rest.service.api.repository.DeploymentCollectionResource.java

@ApiOperation(value = "Create a new deployment", tags = {
        "Deployment" }, consumes = "multipart/form-data", produces = "application/json", notes = "The request body should contain data of type multipart/form-data. There should be exactly one file in the request, any additional files will be ignored. The deployment name is the name of the file-field passed in. If multiple resources need to be deployed in a single deployment, compress the resources in a zip and make sure the file-name ends with .bar or .zip.\n"
                + "\n"
                + "An additional parameter (form-field) can be passed in the request body with name tenantId. The value of this field will be used as the id of the tenant this deployment is done in.")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the deployment was created."),
        @ApiResponse(code = 400, message = "Indicates there was no content present in the request body or the content mime-type is not supported for deployment. The status-description contains additional information.") })

@ApiImplicitParams({ @ApiImplicitParam(name = "file", dataType = "file", paramType = "form", required = true) })
@PostMapping(value = "/cmmn-repository/deployments", produces = "application/json", consumes = "multipart/form-data")
public CmmnDeploymentResponse uploadDeployment(
        @ApiParam(name = "deploymentKey") @RequestParam(value = "deploymentKey", required = false) String deploymentKey,
        @ApiParam(name = "deploymentName") @RequestParam(value = "deploymentName", required = false) String deploymentName,
        @ApiParam(name = "tenantId") @RequestParam(value = "tenantId", required = false) String tenantId,
        HttpServletRequest request, HttpServletResponse response) {

    if (!(request instanceof MultipartHttpServletRequest)) {
        throw new FlowableIllegalArgumentException("Multipart request is required");
    }//from  ww  w.  j a  v  a2 s . c o m

    if (restApiInterceptor != null) {
        restApiInterceptor.executeNewDeploymentForTenantId(tenantId);
    }

    String queryString = request.getQueryString();
    Map<String, String> decodedQueryStrings = splitQueryString(queryString);

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    if (multipartRequest.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("Multipart request with file content is required");
    }

    MultipartFile file = multipartRequest.getFileMap().values().iterator().next();

    try {
        CmmnDeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !(fileName.endsWith(".cmmn.xml") || fileName.endsWith(".cmmn"))) {

            fileName = file.getName();
        }

        if (fileName.endsWith(".cmmn.xml") || fileName.endsWith(".cmmn")) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else {
            throw new FlowableIllegalArgumentException("File must be of type .cmmn.xml, .cmmn");
        }

        if (!decodedQueryStrings.containsKey("deploymentName")
                || StringUtils.isEmpty(decodedQueryStrings.get("deploymentName"))) {
            String fileNameWithoutExtension = fileName.split("\\.")[0];

            if (StringUtils.isNotEmpty(fileNameWithoutExtension)) {
                fileName = fileNameWithoutExtension;
            }

            deploymentBuilder.name(fileName);
        } else {
            deploymentBuilder.name(decodedQueryStrings.get("deploymentName"));
        }

        if (decodedQueryStrings.containsKey("deploymentKey")
                || StringUtils.isNotEmpty(decodedQueryStrings.get("deploymentKey"))) {
            deploymentBuilder.key(decodedQueryStrings.get("deploymentKey"));
        }

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }

        if (restApiInterceptor != null) {
            restApiInterceptor.enhanceDeployment(deploymentBuilder);
        }

        CmmnDeployment deployment = deploymentBuilder.deploy();

        response.setStatus(HttpStatus.CREATED.value());

        return restResponseFactory.createDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof FlowableException) {
            throw (FlowableException) e;
        }
        throw new FlowableException(e.getMessage(), e);
    }
}