Java Code Examples for org.springframework.web.multipart.MultipartFile#getName()

The following examples show how to use org.springframework.web.multipart.MultipartFile#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtils.java    From file-service with Apache License 2.0 6 votes vote down vote up
public static MultipartFile cutImage(MultipartFile file, Double rotate, Integer axisX, Integer axisY, Integer width, Integer height) throws java.io.IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    if (rotate != null) {
        Thumbnails.of(file.getInputStream()).scale(1.0, 1.0).rotate(rotate).toOutputStream(outputStream);
    }
    if (axisX != null && axisY != null && width != null && height != null) {
        if (outputStream.size() > 0) {
            final InputStream rotateInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            outputStream.reset();
            Thumbnails.of(rotateInputStream).scale(1.0, 1.0).sourceRegion(axisX, axisY, width, height).toOutputStream(outputStream);
        } else {
            Thumbnails.of(file.getInputStream()).scale(1.0, 1.0).sourceRegion(axisX, axisY, width, height).toOutputStream(outputStream);
        }
    }
    if (outputStream.size() > 0) {
        file = new MockMultipartFile(file.getName(), file.getOriginalFilename(),
                file.getContentType(), outputStream.toByteArray());
    }
    return file;
}
 
Example 2
Source File: PluginPackageService.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
@Transactional
public PluginPackage uploadPackage(MultipartFile pluginPackageFile) throws Exception {
	String pluginPackageFileName = pluginPackageFile.getName();

	// 1. save package file to local
	String tmpFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
	File localFilePath = new File(SystemUtils.getTempFolderPath() + tmpFileName + "/");
	log.info("tmpFilePath= {}", localFilePath.getName());
	if (!localFilePath.exists()) {
		if (localFilePath.mkdirs()) {
			log.info("Create directory [{}] successful", localFilePath.getAbsolutePath());
		} else {
			throw new WecubeCoreException("Create directory [{}] failed");
		}
	}
	File dest = new File(localFilePath + "/" + pluginPackageFileName);
	log.info("new file location: {}, filename: {}, canonicalpath: {}, canonicalfilename: {}",
			dest.getAbsoluteFile(), dest.getName(), dest.getCanonicalPath(), dest.getCanonicalFile().getName());
	pluginPackageFile.transferTo(dest);

	PluginPackage savedPluginPackage = parsePackageFile(dest, localFilePath);

	return savedPluginPackage;
}
 
Example 3
Source File: AbstractRelatedContentResource.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected RelatedContentRepresentation uploadFile(User user, MultipartFile file, String taskId, String processInstanceId) {
    if (file != null && file.getName() != null) {
        try {
            String contentType = file.getContentType();
            
            // temp additional content type check for IE9 flash uploads
            if (StringUtils.equals(file.getContentType(), "application/octet-stream")) {
                contentType = getContentTypeForFileExtension(file);
            }
            
            RelatedContent relatedContent = contentService.createRelatedContent(user, getFileName(file), null, null, taskId, processInstanceId, 
                    contentType, file.getInputStream(), file.getSize(), true, false);
            return new RelatedContentRepresentation(relatedContent, simpleTypeMapper);
        } catch (IOException e) {
            throw new BadRequestException("Error while reading file data", e);
        }
    } else {
        throw new BadRequestException("File to upload is missing");
    }
}
 
Example 4
Source File: SetFiles.java    From Tbed with GNU Affero General Public License v3.0 5 votes vote down vote up
public static File changeFile(MultipartFile multipartFile) {
    // 获取文件名
    String fileName = multipartFile.getName();//multipartFile.getOriginalFilename();
    // 获取文件后缀
    String prefix = fileName.substring(fileName.lastIndexOf("."));
    // todo 修改临时文件文件名
    File file = null;
    try {
        file = File.createTempFile(fileName, prefix);
        multipartFile.transferTo(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;
}
 
Example 5
Source File: SmUtil.java    From uccn with Apache License 2.0 5 votes vote down vote up
public static File getFile(MultipartFile multipartFile){
    File file = new File(multipartFile.getName());
    try {
        FileUtil.writeFromStream(multipartFile.getInputStream(), file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return file;
}
 
Example 6
Source File: PetApiDelegateImpl.java    From openapi-petstore with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<ModelApiResponse> uploadFile(Long petId, String additionalMetadata, MultipartFile file) {
    try {
        String uploadedFileLocation = "./" + file.getName();
        System.out.println("uploading to " + uploadedFileLocation);
        IOUtils.copy(file.getInputStream(), new FileOutputStream(uploadedFileLocation));
        String msg = String.format("additionalMetadata: %s\nFile uploaded to %s, %d bytes", additionalMetadata, uploadedFileLocation, (new File(uploadedFileLocation)).length());
        ModelApiResponse output = new ModelApiResponse().code(200).message(msg);
        return ResponseEntity.ok(output);
    }
    catch (Exception e) {
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Couldn't upload file", e);
    }
}
 
Example 7
Source File: BladeFile.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
public BladeFile(MultipartFile file, String dir) {
	this.dir = dir;
	this.file = file;
	this.fileName = file.getName();
	this.originalFileName = file.getOriginalFilename();
	this.uploadPath = BladeFileUtil.formatUrl(File.separator + SystemConstant.me().getUploadRealPath() + File.separator + dir + File.separator + DateUtil.format(new Date(), "yyyyMMdd") + File.separator + this.originalFileName);
	this.uploadVirtualPath = BladeFileUtil.formatUrl(SystemConstant.me().getUploadCtxPath().replace(SystemConstant.me().getContextPath(), "") + File.separator + dir + File.separator + DateUtil.format(new Date(), "yyyyMMdd") + File.separator + this.originalFileName);
}
 
Example 8
Source File: FileSystemStorageService.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
@Override
public String store(FileType fileType, MultipartFile file) {
    try {
        return storeAbstract(fileType, file.getOriginalFilename(), file.getInputStream(), file::isEmpty);
    } catch (IOException e) {
        log.error(String.format("Failed storing file %s", file.getName()), e);
        throw new StorageException("Failed to store file " + file.getName(), e);
    }
}
 
Example 9
Source File: WebuiMailAttachmentsRepository.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
public LookupValue createAttachment(@NonNull final String emailId, @NonNull final MultipartFile file)
{
	//
	// Extract the original filename
	String originalFilename = file.getOriginalFilename();
	if (Check.isEmpty(originalFilename, true))
	{
		originalFilename = file.getName();
	}
	if (Check.isEmpty(originalFilename, true))
	{
		throw new AdempiereException("Filename not provided");
	}

	byte[] fileContent;
	try
	{
		fileContent = file.getBytes();
	}
	catch (IOException e)
	{
		throw new AdempiereException("Failed fetching attachment content")
				.setParameter("filename", originalFilename);
	}

	return createAttachment(emailId, originalFilename, fileContent);
}
 
Example 10
Source File: EchoResource.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path = "/attachment", method=RequestMethod.POST)
public ResponseEntity<String> receiveFile(@RequestParam("testFile") MultipartFile file) throws IOException {
    String fileName = file.getName();
    byte[] fileContents = file.getBytes();

    return ResponseEntity.ok(fileName);
}
 
Example 11
Source File: AbstractRelatedContentResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected ContentItemRepresentation uploadFile(User user, MultipartFile file, String taskId, String processInstanceId, String caseId) {
    if (file != null && file.getName() != null) {
        try {
            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");
    }
}
 
Example 12
Source File: AppDeploymentCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@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);
    }
    
    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);
    }
}
 
Example 13
Source File: DeploymentCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@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 = "/event-registry-repository/deployments", produces = "application/json", consumes = "multipart/form-data")
public EventDeploymentResponse uploadDeployment(@ApiParam(name = "category") @RequestParam(value = "category", required = false) String category,
        @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");
    }
    
    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 {
        EventDeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !(fileName.endsWith(".event") || fileName.endsWith(".channel"))) {

            fileName = file.getName();
        }

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

        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("category") || StringUtils.isNotEmpty(decodedQueryStrings.get("category"))) {
            deploymentBuilder.category(decodedQueryStrings.get("category"));
        }

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

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

        EventDeployment 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);
    }
}
 
Example 14
Source File: DmnDeploymentCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@ApiOperation(value = "Create a new decision table deployment", nickname = "uploadDecisionTableDeployment", 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", paramType = "form", dataType = "java.io.File")
})
@PostMapping(value = "/dmn-repository/deployments", produces = "application/json", consumes = "multipart/form-data")
public DmnDeploymentResponse uploadDeployment(@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");
    }
    
    if (restApiInterceptor != null) {
        restApiInterceptor.executeNewDeploymentForTenantId(tenantId);
    }

    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 {
        DmnDeploymentBuilder deploymentBuilder = dmnRepositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !DmnResourceUtil.isDmnResource(fileName)) {
            fileName = file.getName();
        }

        if (DmnResourceUtil.isDmnResource(fileName)) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else {
            throw new FlowableIllegalArgumentException("File must be of type .dmn");
        }
        deploymentBuilder.name(fileName);

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

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

        DmnDeployment deployment = deploymentBuilder.deploy();

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

        return dmnRestResponseFactory.createDmnDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof FlowableException) {
            throw (FlowableException) e;
        }
        throw new FlowableException(e.getMessage(), e);
    }
}
 
Example 15
Source File: DeploymentCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@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 = "/repository/deployments", produces = "application/json", consumes = "multipart/form-data")
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)) {
        throw new FlowableIllegalArgumentException("Multipart request is required");
    }
    
    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 {
        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 (!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);
        }

        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);
    }
}
 
Example 16
Source File: DeploymentCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@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");
    }
    
    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);
    }
}
 
Example 17
Source File: VSCrawlerManager.java    From vscrawler with Apache License 2.0 4 votes vote down vote up
public void reloadJar(MultipartFile multipartFile) throws Exception {
    String fileName = multipartFile.getName();
    if (StringUtils.isBlank(fileName)) {
        fileName = multipartFile.getOriginalFilename();
    }
    if (StringUtils.isBlank(fileName)) {
        fileName = String.valueOf(System.currentTimeMillis()) + ".jar";
    }

    File hotJarDir = new File(calcHotJarDir());
    Set<String> existFileSign = Sets.newHashSet();
    Set<String> existFileNames = Sets.newHashSet();
    //load all exits crawler, to avoid duplicate move
    for (File jarFile : hotJarDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return StringUtils.endsWith(name, ".jar");
        }
    })) {
        existFileSign.add(getFileSign(jarFile));
        existFileNames.add(jarFile.getName());
    }
    fileName = PathResolver.getFileName(fileName);
    File targetFile = judgeCopyTargetFile(fileName, existFileNames, hotJarDir);
    multipartFile.transferTo(targetFile);
    if (existFileSign.contains(getFileSign(targetFile))) {
        deleteJarIfJarIllegal(targetFile);
        return;
    }

    try {
        //scan and load crawler
        CrawlerBean crawlerBean = loadJarFile(targetFile);
        if (crawlerBean == null) {
            throw new IllegalStateException("not crawler defined in this jar file");
        }

        //stop old crawler if necessary
        String crawlerName = crawlerBean.getCrawler().getVsCrawlerContext().getCrawlerName();
        CrawlerBean oldVSCrawler = allCrawler.get(crawlerName);
        if (oldVSCrawler != null) {
            if (!oldVSCrawler.isReloadable()) {
                throw new IllegalStateException("can not reload crawler " + crawlerName + " ,this crawler defined in servlet context,not defined in vscrawler context ");
            }
            // 这里可能比较耗时
            oldVSCrawler.getCrawler().stopCrawler();
            deleteJarIfJarIllegal(oldVSCrawler.relatedJarFile());
        }
        //register new crawler
        allCrawler.put(crawlerName, crawlerBean);
    } catch (Exception e) {
        deleteJarIfJarIllegal(targetFile);
        throw e;
    }
}
 
Example 18
Source File: DeploymentCollectionResource.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@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. 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 = "tenantId") @RequestParam(value = "tenantId", required = false) String tenantId, HttpServletRequest request, HttpServletResponse response) {

  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 {
    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 ActivitiIllegalArgumentException("File must be of type .bpmn20.xml, .bpmn, .bar or .zip");
    }
    deploymentBuilder.name(fileName);

    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 ActivitiException) {
      throw (ActivitiException) e;
    }
    throw new ActivitiException(e.getMessage(), e);
  }
}
 
Example 19
Source File: DmnDeploymentCollectionResource.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@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) {

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

  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

  if (multipartRequest.getFileMap().size() == 0) {
    throw new ActivitiDmnIllegalArgumentException("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 ActivitiDmnIllegalArgumentException("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 ActivitiDmnException) {
      throw (ActivitiDmnException) e;
    }
    throw new ActivitiDmnException(e.getMessage(), e);
  }
}
 
Example 20
Source File: FileResourceUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 *
 * Builds a {@link FileResource} from a {@link MultipartFile}.
 *
 * @param key the key to associate to the {@link FileResource}
 * @param file a {@link MultipartFile}
 * @param domain a {@link FileResourceDomain}
 * @return a valid {@link FileResource} populated with data from the provided
 *         file
 * @throws IOException if hashing fails
 *
 */
public static FileResource build( String key, MultipartFile file, FileResourceDomain domain )
    throws IOException
{
    return new FileResource( key, file.getName(), file.getContentType(), file.getSize(),
        ByteSource.wrap( file.getBytes() ).hash( Hashing.md5() ).toString(), domain );
}