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.flowable.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) {/*from w w  w . ja  v  a  2 s .  c  o m*/

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

    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 {
        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 FlowableIllegalArgumentException("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 FlowableException) {
            throw (FlowableException) e;
        }
        throw new FlowableException(e.getMessage(), e);
    }

}

From source file:org.flowable.rest.service.api.identity.UserPictureResource.java

@ApiOperation(value = "Updating a users picture", tags = {
        "Users" }, consumes = "multipart/form-data", notes = "The request should be of type multipart/form-data. There should be a single file-part included with the binary value of the picture. On top of that, the following additional form-fields can be present:\n"
                + "\n"
                + "mimeType: Optional mime-type for the uploaded picture. If omitted, the default of image/jpeg is used as a mime-type for the picture.")
@ApiResponses(value = {/*  w  w  w.  j a  v a 2s  .  co  m*/
        @ApiResponse(code = 200, message = "Indicates the user was found and the picture has been updated. The response-body is left empty intentionally."),
        @ApiResponse(code = 404, message = "Indicates the requested user was not found.") })
@RequestMapping(value = "/identity/users/{userId}/picture", method = RequestMethod.PUT)
public void updateUserPicture(@ApiParam(name = "userId") @PathVariable String userId,
        HttpServletRequest request, HttpServletResponse response) {
    User user = getUserFromRequest(userId);

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

    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 {
        String mimeType = file.getContentType();
        int size = ((Long) file.getSize()).intValue();

        // Copy file-body in a bytearray as the engine requires this
        ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(size);
        IOUtils.copy(file.getInputStream(), bytesOutput);

        Picture newPicture = new Picture(bytesOutput.toByteArray(), mimeType);
        identityService.setUserPicture(user.getId(), newPicture);

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

    } catch (Exception e) {
        throw new FlowableException("Error while reading uploaded file: " + e.getMessage(), e);
    }
}

From source file:org.flowable.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 = 200, 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.") })
@RequestMapping(value = "/repository/deployments", method = RequestMethod.POST, produces = "application/json")
public DeploymentResponse 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 == false) {
        throw new FlowableIllegalArgumentException("Multipart request is required");
    }//from w w  w.ja  v a  2  s  .  c o  m

    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 {
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !(fileName.endsWith(".bpmn20.xml") || fileName.endsWith(".bpmn")
                || fileName.toLowerCase().endsWith(".bar") || fileName.toLowerCase().endsWith(".zip"))) {

            fileName = file.getName();
        }

        if (fileName.endsWith(".bpmn20.xml") || fileName.endsWith(".bpmn")) {
            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 .bpmn20.xml, .bpmn, .bar or .zip");
        }

        if (StringUtils.isEmpty(deploymentName)) {
            String fileNameWithoutExtension = fileName.split("\\.")[0];

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

            deploymentBuilder.name(fileName);
        } else {
            deploymentBuilder.name(deploymentName);
        }

        if (deploymentKey != null) {
            deploymentBuilder.key(deploymentKey);
        }

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

        Deployment 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);
    }
}

From source file:org.flowable.rest.service.api.runtime.process.BaseExecutionVariableResource.java

protected RestVariable setBinaryVariable(MultipartHttpServletRequest request, Execution execution,
        int responseVariableType, boolean isNew) {

    // Validate input and set defaults
    if (request.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }//from  www .j a v  a  2  s .  c om

    // Get first file in the map, ignore possible other files
    MultipartFile file = request.getFile(request.getFileMap().keySet().iterator().next());

    if (file == null) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }

    String variableScope = null;
    String variableName = null;
    String variableType = null;

    Map<String, String[]> paramMap = request.getParameterMap();
    for (String parameterName : paramMap.keySet()) {

        if (paramMap.get(parameterName).length > 0) {

            if (parameterName.equalsIgnoreCase("scope")) {
                variableScope = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("name")) {
                variableName = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("type")) {
                variableType = paramMap.get(parameterName)[0];
            }
        }
    }

    try {

        // Validate input and set defaults
        if (variableName == null) {
            throw new FlowableIllegalArgumentException("No variable name was found in request body.");
        }

        if (variableType != null) {
            if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
                    && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new FlowableIllegalArgumentException(
                        "Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }

        RestVariableScope scope = RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }

        if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            byte[] variableBytes = IOUtils.toByteArray(file.getInputStream());
            setVariable(execution, variableName, variableBytes, scope, isNew);

        } else if (isSerializableVariableAllowed) {
            // Try deserializing the object
            ObjectInputStream stream = new ObjectInputStream(file.getInputStream());
            Object value = stream.readObject();
            setVariable(execution, variableName, value, scope, isNew);
            stream.close();
        } else {
            throw new FlowableContentNotSupportedException("Serialized objects are not allowed");
        }

        if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
            return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, null, null,
                    execution.getId());
        } else {
            return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, null,
                    execution.getId(), null);
        }

    } catch (IOException ioe) {
        throw new FlowableIllegalArgumentException("Could not process multipart content", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new FlowableContentNotSupportedException(
                "The provided body contains a serialized object for which the class is nog found: "
                        + ioe.getMessage());
    }

}

From source file:org.flowable.rest.service.api.runtime.task.TaskVariableBaseResource.java

protected RestVariable setBinaryVariable(MultipartHttpServletRequest request, Task task, boolean isNew) {

    // Validate input and set defaults
    if (request.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }//from   w ww .jav  a  2 s .  c o m

    // Get first file in the map, ignore possible other files
    MultipartFile file = request.getFile(request.getFileMap().keySet().iterator().next());

    if (file == null) {
        throw new FlowableIllegalArgumentException("No file content was found in request body.");
    }

    String variableScope = null;
    String variableName = null;
    String variableType = null;

    Map<String, String[]> paramMap = request.getParameterMap();
    for (String parameterName : paramMap.keySet()) {

        if (paramMap.get(parameterName).length > 0) {

            if (parameterName.equalsIgnoreCase("scope")) {
                variableScope = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("name")) {
                variableName = paramMap.get(parameterName)[0];

            } else if (parameterName.equalsIgnoreCase("type")) {
                variableType = paramMap.get(parameterName)[0];
            }
        }
    }

    try {

        if (variableName == null) {
            throw new FlowableIllegalArgumentException("No variable name was found in request body.");
        }

        if (variableType != null) {
            if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
                    && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new FlowableIllegalArgumentException(
                        "Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }

        RestVariableScope scope = RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }

        if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            byte[] variableBytes = IOUtils.toByteArray(file.getInputStream());
            setVariable(task, variableName, variableBytes, scope, isNew);

        } else if (isSerializableVariableAllowed) {
            // Try deserializing the object
            ObjectInputStream stream = new ObjectInputStream(file.getInputStream());
            Object value = stream.readObject();
            setVariable(task, variableName, value, scope, isNew);
            stream.close();

        } else {
            throw new FlowableContentNotSupportedException("Serialized objects are not allowed");
        }

        return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, task.getId(),
                null, null);

    } catch (IOException ioe) {
        throw new FlowableIllegalArgumentException("Error getting binary variable", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new FlowableContentNotSupportedException(
                "The provided body contains a serialized object for which the class is nog found: "
                        + ioe.getMessage());
    }

}

From source file:org.flowable.ui.modeler.service.AppDefinitionImportService.java

public AppDefinitionRepresentation importAppDefinition(HttpServletRequest request, MultipartFile file) {
    try {/* w w w  .j  a va  2s  .  c om*/
        InputStream is = file.getInputStream();
        String fileName = file.getOriginalFilename();
        return importAppDefinition(request, is, fileName, null, null, null, null, null);

    } catch (IOException e) {
        throw new InternalServerErrorException("Error loading file", e);
    }
}

From source file:org.flowable.ui.modeler.service.AppDefinitionImportService.java

public AppDefinitionRepresentation importAppDefinitionNewVersion(HttpServletRequest request, MultipartFile file,
        String appDefId) {//from  ww w  .j a v  a2  s  . c om
    try {
        InputStream is = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Model appModel = modelService.getModel(appDefId);
        if (!appModel.getModelType().equals(Model.MODEL_TYPE_APP)) {
            throw new BadRequestException("No app definition found for id " + appDefId);
        }

        AppDefinitionRepresentation appDefinition = createAppDefinitionRepresentation(appModel);

        Map<String, Model> existingProcessModelMap = new HashMap<>();
        Map<String, Model> existingCaseModelMap = new HashMap<>();
        Map<String, Model> existingFormModelMap = new HashMap<>();
        Map<String, Model> existingDecisionTableMap = new HashMap<>();
        if (appDefinition.getDefinition() != null
                && CollectionUtils.isNotEmpty(appDefinition.getDefinition().getModels())) {
            for (AppModelDefinition modelDef : appDefinition.getDefinition().getModels()) {
                Model processModel = modelService.getModel(modelDef.getId());

                List<Model> referencedModels = modelRepository.findByParentModelId(processModel.getId());
                for (Model childModel : referencedModels) {
                    if (Model.MODEL_TYPE_FORM == childModel.getModelType()) {
                        existingFormModelMap.put(childModel.getKey(), childModel);

                    } else if (Model.MODEL_TYPE_DECISION_TABLE == childModel.getModelType()) {
                        existingDecisionTableMap.put(childModel.getKey(), childModel);
                    }
                }

                existingProcessModelMap.put(processModel.getKey(), processModel);
            }
        }

        if (appDefinition.getDefinition() != null
                && CollectionUtils.isNotEmpty(appDefinition.getDefinition().getCmmnModels())) {
            for (AppModelDefinition modelDef : appDefinition.getDefinition().getCmmnModels()) {
                Model caseModel = modelService.getModel(modelDef.getId());

                List<Model> referencedModels = modelRepository.findByParentModelId(caseModel.getId());
                for (Model childModel : referencedModels) {
                    if (Model.MODEL_TYPE_FORM == childModel.getModelType()) {
                        existingFormModelMap.put(childModel.getKey(), childModel);

                    } else if (Model.MODEL_TYPE_DECISION_TABLE == childModel.getModelType()) {
                        existingDecisionTableMap.put(childModel.getKey(), childModel);
                    }
                }

                existingCaseModelMap.put(caseModel.getKey(), caseModel);
            }
        }

        return importAppDefinition(request, is, fileName, appModel, existingProcessModelMap,
                existingCaseModelMap, existingFormModelMap, existingDecisionTableMap);

    } catch (IOException e) {
        throw new InternalServerErrorException("Error loading file", e);
    }
}

From source file:org.flowable.ui.modeler.service.FlowableDecisionTableService.java

public ModelRepresentation importDecisionTable(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".dmn") || fileName.endsWith(".xml"))) {
        try {/*ww  w. j a va  2s .c  o  m*/

            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);

            DmnDefinition dmnDefinition = dmnXmlConverter.convertToDmnModel(xtr);

            if (dmnDefinition.getDecisions().size() == 0) {
                throw new FlowableException("No decisions found in " + fileName);
            }

            ObjectNode editorJsonNode = dmnJsonConverter.convertToJson(dmnDefinition);

            // remove id to avoid InvalidFormatException when deserializing
            editorJsonNode.remove("id");

            // set to latest model version
            editorJsonNode.put("modelVersion", 2);

            ModelRepresentation modelRepresentation = new ModelRepresentation();
            modelRepresentation.setKey(dmnDefinition.getDecisions().get(0).getId());
            modelRepresentation.setName(dmnDefinition.getName());
            modelRepresentation.setDescription(dmnDefinition.getDescription());
            modelRepresentation.setModelType(AbstractModel.MODEL_TYPE_DECISION_TABLE);
            Model model = modelService.createModel(modelRepresentation, editorJsonNode.toString(),
                    SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(model);

        } catch (Exception e) {
            LOGGER.error("Could not import decision table model", e);
            throw new InternalServerErrorException("Could not import decision table model");
        }
    } else {
        throw new BadRequestException(
                "Invalid file name, only .dmn or .xml files are supported not " + fileName);
    }

}

From source file:org.flowable.ui.task.rest.runtime.AbstractRelatedContentResource.java

protected ContentItemRepresentation uploadFile(User user, MultipartFile file, String taskId,
        String processInstanceId, String caseId) {
    if (file != null && file.getName() != null) {
        try {//from w  ww  . j a v 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);
            if (StringUtils.isNotEmpty(caseId)) {
                contentItem.setScopeType("cmmn");
                contentItem.setScopeId(caseId);
            }
            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.hoteia.qalingo.core.service.WebBackofficeService.java

public Retailer createOrUpdateRetailer(Retailer retailer, final RetailerForm retailerForm) throws Exception {
    if (retailer == null) {
        retailer = new Retailer();
    }//from  w  ww .  jav a  2s  .  com
    if (StringUtils.isNotEmpty(retailerForm.getCode())) {
        retailer.setCode(CoreUtil.cleanEntityCode(retailerForm.getCode()));
    }
    if (StringUtils.isNotEmpty(retailerForm.getName())) {
        retailer.setName(retailerForm.getName());
    }
    retailer.setDescription(retailerForm.getDescription());

    RetailerAddress retailerAddress = retailer.getDefaultAddress();
    if (retailerAddress == null) {
        retailerAddress = new RetailerAddress();
        retailer.getAddresses().add(retailerAddress);
    }

    retailerAddress.setAddress1(retailerForm.getAddress1());
    retailerAddress.setAddress2(retailerForm.getAddress2());
    retailerAddress.setAddressAdditionalInformation(retailerForm.getAddressAdditionalInformation());
    retailerAddress.setPostalCode(retailerForm.getPostalCode());
    retailerAddress.setCity(retailerForm.getCity());
    retailerAddress.setStateCode(retailerForm.getStateCode());
    retailerAddress.setCountryCode(retailerForm.getCountryCode());

    retailerAddress.setPhone(retailerForm.getPhone());
    retailerAddress.setFax(retailerForm.getFax());
    retailerAddress.setMobile(retailerForm.getMobile());
    retailerAddress.setEmail(retailerForm.getEmail());
    retailerAddress.setWebsite(retailerForm.getWebsite());

    retailer.setBrand(retailerForm.isBrand());
    retailer.setCorner(retailerForm.isCorner());
    retailer.setEcommerce(retailerForm.isEcommerce());
    retailer.setOfficialRetailer(retailerForm.isOfficialRetailer());

    //      if(StringUtils.isNotBlank(retailerForm.getWarehouseId())){
    //         final Warehouse warehouse = warehouseService.getWarehouseById(retailerForm.getWarehouseId());
    //         if(warehouse != null){
    //            retailer.setWarehouse(warehouse);
    //         }
    //      } else {
    //         retailer.setWarehouse(null);
    //      }

    MultipartFile multipartFile = retailerForm.getFile();
    if (multipartFile != null && multipartFile.getSize() > 0) {
        UUID uuid = UUID.randomUUID();
        String pathRetailerLogoImage = new StringBuilder(uuid.toString())
                .append(System.getProperty("file.separator"))
                .append(FilenameUtils.getExtension(multipartFile.getOriginalFilename())).toString();

        String absoluteFilePath = retailerService.buildRetailerLogoFilePath(retailer, pathRetailerLogoImage);
        String absoluteFolderPath = absoluteFilePath.replace(pathRetailerLogoImage, "");

        InputStream inputStream = multipartFile.getInputStream();
        File fileLogo = null;
        File folderLogo = null;
        try {
            folderLogo = new File(absoluteFolderPath);
            folderLogo.mkdirs();
            fileLogo = new File(absoluteFilePath);

        } catch (Exception e) {
            //
        }
        if (fileLogo != null) {
            OutputStream outputStream = new FileOutputStream(fileLogo);
            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();
            retailer.setLogo(pathRetailerLogoImage);
        }
    }

    return retailerService.saveOrUpdateRetailer(retailer);
}