Java Code Examples for org.glassfish.jersey.media.multipart.FormDataContentDisposition#getFileName()

The following examples show how to use org.glassfish.jersey.media.multipart.FormDataContentDisposition#getFileName() . 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: VideosResource.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadVideo(@FormDataParam("file") InputStream uploadedInputStream,
                            @FormDataParam("file") FormDataContentDisposition fileDetail) throws Exception {
    File videoDir = new File(this.videoDirectory);
    if (!videoDir.exists()) {
        videoDir.mkdirs();
    }

    File uploadFile = new File(videoDir.getAbsolutePath(), fileDetail.getFileName());
    writeToFile(uploadedInputStream, uploadFile.getAbsolutePath());
    Video video = new Video();
    video.setPath(String.format("%s/rest/public/videos/%s", this.baseUrl, URLEncoder.encode(fileDetail.getFileName(), "UTF8")));
    return Response.OK(video);
}
 
Example 2
Source File: FileUploadResource.java    From blog-tutorials with MIT License 6 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
		@FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException {

	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	byte[] buffer = new byte[1024];
	int len;

	while ((len = uploadedInputStream.read(buffer)) != -1) {
		byteArrayOutputStream.write(buffer, 0, len);
	}

	FileUpload upload = new FileUpload(fileDetail.getFileName(), fileDetail.getType(),
			byteArrayOutputStream.toByteArray());

	em.persist(upload);
}
 
Example 3
Source File: AssertionResource.java    From irontest with Apache License 2.0 6 votes vote down vote up
/**
 * Save the uploaded XSD file (or zip file) into the (XMLValidAgainstXSD) assertion.
 * Use @POST instead of @PUT because ng-file-upload seems not working with PUT.
 * @param assertionId
 * @param inputStream
 * @param contentDispositionHeader
 * @return
 */
@POST @Path("assertions/{assertionId}/xsdFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@PermitAll
public void saveXSDFile(@PathParam("assertionId") long assertionId,
                                @FormDataParam("file") InputStream inputStream,
                                @FormDataParam("file") FormDataContentDisposition contentDispositionHeader) throws IOException {
    //  check the file
    String fileName = contentDispositionHeader.getFileName();
    if (!(fileName.toLowerCase().endsWith(".xsd") || fileName.toLowerCase().endsWith(".zip"))) {
        throw new IllegalArgumentException("Only XSD file and Zip file are supported.");
    }

    XMLValidAgainstXSDAssertionProperties properties = new XMLValidAgainstXSDAssertionProperties();
    properties.setFileName(fileName);
    byte[] fileBytes;
    try {
        fileBytes = IOUtils.toByteArray(inputStream);
    } finally {
        inputStream.close();
    }
    properties.setFileBytes(fileBytes);
    assertionDAO.updateOtherProperties(assertionId, properties);
}
 
Example 4
Source File: RuleBatchServiceImpl.java    From Qualitis with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = {RuntimeException.class, UnExpectedRequestException.class})
public GeneralResponse<?> uploadRules(InputStream fileInputStream, FormDataContentDisposition fileDisposition, Long projectId) throws UnExpectedRequestException, IOException, MetaDataAcquireFailedException, SemanticException, ParseException {
    // Check Arguments
    if (fileInputStream == null || fileDisposition == null) {
        throw new UnExpectedRequestException("{&FILE_CAN_NOT_BE_NULL_OR_EMPTY}");
    }

    // Check suffix name of file
    String fileName = fileDisposition.getFileName();
    String suffixName = fileName.substring(fileName.lastIndexOf('.'));
    if (!suffixName.equals(SUPPORT_EXCEL_SUFFIX_NAME)) {
        throw new UnExpectedRequestException("{&DO_NOT_SUPPORT_SUFFIX_NAME}: [" + suffixName + "]. {&ONLY_SUPPORT} [" + SUPPORT_EXCEL_SUFFIX_NAME + "]");
    }
    Project projectInDb = projectDao.findById(projectId);
    if (projectInDb == null) {
        throw new UnExpectedRequestException("{&PROJECT_ID} {&DOES_NOT_EXIST}");
    }

    String username = HttpUtils.getUserName(httpServletRequest);
    if (username == null) {
        return new GeneralResponse<>("401", "{&PLEASE_LOGIN}", null);
    }

    ExcelRuleListener excelRuleListener = readExcel(fileInputStream);
    if (excelRuleListener.getCustomExcelContent().isEmpty() && excelRuleListener.getTemplateExcelContent().isEmpty()
            && excelRuleListener.getMultiTemplateExcelContent().isEmpty()) {
        throw new UnExpectedRequestException("{&FILE_CAN_NOT_BE_EMPTY_OR_FILE_CAN_NOT_BE_RECOGNIZED}");
    }
    getAndSaveRule(excelRuleListener.getTemplateExcelContent(), excelRuleListener.getCustomExcelContent(),
            excelRuleListener.getMultiTemplateExcelContent(), projectInDb, username);
    fileInputStream.close();
    return new GeneralResponse<>("200", "{&SUCCEED_TO_UPLOAD_FILE}", null);
}
 
Example 5
Source File: ActionUploadCallback.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public ActionResult<Wo<WoObject>> execute(EffectivePerson effectivePerson, String meetingId, Boolean summary,
		String callback, String fileName, byte[] bytes, FormDataContentDisposition disposition) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo<WoObject>> result = new ActionResult<>();
		Business business = new Business(emc);
		Meeting meeting = emc.find(meetingId, Meeting.class);
		if (null == meeting) {
			throw new ExceptionMeetingNotExistCallback(callback, meetingId);
		}
		business.meetingReadAvailable(effectivePerson, meeting, ExceptionWhen.not_allow);
		try (InputStream input = new ByteArrayInputStream(bytes)) {
			StorageMapping mapping = ThisApplication.context().storageMappings().random(Attachment.class);
			emc.beginTransaction(Attachment.class);
			fileName = StringUtils.isEmpty(fileName) ? disposition.getFileName() : fileName;
			fileName = FilenameUtils.getName(fileName);
			Attachment attachment = this.concreteAttachment(meeting, summary);
			attachment.saveContent(mapping, input, fileName);
			attachment.setLastUpdatePerson(effectivePerson.getDistinguishedName());
			attachment.setLastUpdateTime(new Date());
			emc.persist(attachment, CheckPersistType.all);
			emc.commit();
			WoObject woObject = new WoObject();
			woObject.setId(attachment.getId());
			Wo<WoObject> wo = new Wo<>(callback, woObject);
			result.setData(wo);
		}
		return result;
	}
}
 
Example 6
Source File: ActionUpload.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public ActionResult<Wo> execute(EffectivePerson effectivePerson, String meetingId, Boolean summary, String fileName,
		byte[] bytes, FormDataContentDisposition disposition) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Business business = new Business(emc);
		Meeting meeting = emc.find(meetingId, Meeting.class);
		if (null == meeting) {
			throw new ExceptionMeetingNotExist(meetingId);
		}
		business.meetingReadAvailable(effectivePerson, meeting, ExceptionWhen.not_allow);
		try (InputStream input = new ByteArrayInputStream(bytes)) {
			StorageMapping mapping = ThisApplication.context().storageMappings().random(Attachment.class);
			emc.beginTransaction(Attachment.class);
			fileName = StringUtils.isEmpty(fileName) ? disposition.getFileName() : fileName;
			fileName = FilenameUtils.getName(fileName);
			Attachment attachment = this.concreteAttachment(meeting, summary);
			attachment.saveContent(mapping, input, fileName);
			attachment.setLastUpdatePerson(effectivePerson.getDistinguishedName());
			attachment.setLastUpdateTime(new Date());
			emc.persist(attachment, CheckPersistType.all);
			emc.commit();
			Wo wo = new Wo();
			wo.setId(attachment.getId());
			result.setData(wo);
		}
		return result;
	}
}
 
Example 7
Source File: ActionUploadCallback.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public ActionResult<Wo<WoObject>> execute(EffectivePerson effectivePerson, String meetingId, Boolean summary,
		String callback, String fileName, byte[] bytes, FormDataContentDisposition disposition) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo<WoObject>> result = new ActionResult<>();
		Business business = new Business(emc);
		Meeting meeting = emc.find(meetingId, Meeting.class);
		if (null == meeting) {
			throw new ExceptionMeetingNotExistCallback(callback, meetingId);
		}
		business.meetingReadAvailable(effectivePerson, meeting, ExceptionWhen.not_allow);
		try (InputStream input = new ByteArrayInputStream(bytes)) {
			StorageMapping mapping = ThisApplication.context().storageMappings().random(Attachment.class);
			emc.beginTransaction(Attachment.class);
			fileName = StringUtils.isEmpty(fileName) ? disposition.getFileName() : fileName;
			fileName = FilenameUtils.getName(fileName);
			Attachment attachment = this.concreteAttachment(meeting, summary);
			attachment.saveContent(mapping, input, fileName);
			attachment.setLastUpdatePerson(effectivePerson.getDistinguishedName());
			attachment.setLastUpdateTime(new Date());
			emc.persist(attachment, CheckPersistType.all);
			emc.commit();
			WoObject woObject = new WoObject();
			woObject.setId(attachment.getId());
			Wo<WoObject> wo = new Wo<>(callback, woObject);
			result.setData(wo);
		}
		return result;
	}
}
 
Example 8
Source File: ActionUpload.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public ActionResult<Wo> execute(EffectivePerson effectivePerson, String meetingId, Boolean summary, String fileName,
		byte[] bytes, FormDataContentDisposition disposition) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Business business = new Business(emc);
		Meeting meeting = emc.find(meetingId, Meeting.class);
		if (null == meeting) {
			throw new ExceptionMeetingNotExist(meetingId);
		}
		business.meetingReadAvailable(effectivePerson, meeting, ExceptionWhen.not_allow);
		try (InputStream input = new ByteArrayInputStream(bytes)) {
			StorageMapping mapping = ThisApplication.context().storageMappings().random(Attachment.class);
			emc.beginTransaction(Attachment.class);
			fileName = StringUtils.isEmpty(fileName) ? disposition.getFileName() : fileName;
			fileName = FilenameUtils.getName(fileName);
			Attachment attachment = this.concreteAttachment(meeting, summary);
			attachment.saveContent(mapping, input, fileName);
			attachment.setLastUpdatePerson(effectivePerson.getDistinguishedName());
			attachment.setLastUpdateTime(new Date());
			emc.persist(attachment, CheckPersistType.all);
			emc.commit();
			Wo wo = new Wo();
			wo.setId(attachment.getId());
			result.setData(wo);
		}
		return result;
	}
}
 
Example 9
Source File: PortalMediaResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@POST
@Permissions({
        @Permission(value = RolePermission.ENVIRONMENT_DOCUMENTATION, acls = RolePermissionAction.CREATE)
})
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
public Response upload(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("file") final FormDataBodyPart body
) throws IOException {
    String mediaId;

    if (fileDetail.getSize() > this.mediaService.getMediaMaxSize()) {
        throw new UploadUnauthorized("Max size achieved " + fileDetail.getSize());
    } else {
        MediaEntity mediaEntity = new MediaEntity(
                IOUtils.toByteArray(uploadedInputStream),
                body.getMediaType().getType(),
                body.getMediaType().getSubtype(),
                fileDetail.getFileName(),
                fileDetail.getSize());

        try {
            ImageUtils.verify(body.getMediaType().getType(), body.getMediaType().getSubtype(), mediaEntity.getData());
        } catch (InvalidImageException e) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Invalid image format").build();
        }

        mediaId = mediaService.savePortalMedia(mediaEntity);
    }

    return Response.status(200).entity(mediaId).build();
}
 
Example 10
Source File: StageLibraryResource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/stageLibraries/extras/{library}/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Install additional drivers", response = Object.class,
    authorizations = @Authorization(value = "basic"))
@RolesAllowed({AuthzRole.ADMIN, AuthzRole.ADMIN_REMOTE})
public Response installExtras(
    @PathParam("library") String library,
    @FormDataParam("file") InputStream uploadedInputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail
) throws IOException, RestException {
  String libsExtraDir = runtimeInfo.getLibsExtraDir();
  if (StringUtils.isEmpty(libsExtraDir)) {
    throw new RestException(RestErrors.REST_1004);
  }

  File additionalLibraryFile = new File(
      libsExtraDir + "/"	+ library + "/" + STAGE_LIB_JARS_DIR,
      fileDetail.getFileName()
  );
  File parent = additionalLibraryFile.getParentFile();
  if (!parent.exists()) {
    if (!parent.mkdirs()) {
      throw new RestException(RestErrors.REST_1003, parent.getName());
    }
  }
  saveFile(uploadedInputStream, additionalLibraryFile);
  return Response.ok().build();
}
 
Example 11
Source File: ProjectBatchServiceImpl.java    From Qualitis with Apache License 2.0 4 votes vote down vote up
@Override
@Transactional(rollbackFor = {Exception.class})
public GeneralResponse<?> uploadProjects(InputStream fileInputStream, FormDataContentDisposition fileDisposition) throws UnExpectedRequestException,
        MetaDataAcquireFailedException, IOException, SemanticException, ParseException {
    String fileName = fileDisposition.getFileName();
    String suffixName = fileName.substring(fileName.lastIndexOf('.'));
    if (!suffixName.equals(SUPPORT_EXCEL_SUFFIX_NAME)) {
        throw new UnExpectedRequestException("{&DO_NOT_SUPPORT_SUFFIX_NAME}: [" + suffixName + "]. {&ONLY_SUPPORT} [" + SUPPORT_EXCEL_SUFFIX_NAME + "]");
    }

    String username = HttpUtils.getUserName(httpServletRequest);
    if (username == null) {
        return new GeneralResponse<>("401", "{&PLEASE_LOGIN}", null);
    }
    Long userId = HttpUtils.getUserId(httpServletRequest);

    // Read file and create project
    ExcelProjectListener listener = readExcel(fileInputStream);

    // Check if excel file is empty
    if (listener.getExcelProjectContent().isEmpty() && listener.getExcelRuleContent().isEmpty()
            && listener.getExcelCustomRuleContent().isEmpty() && listener.getExcelMultiRuleContent().isEmpty()) {
        throw new UnExpectedRequestException("{&FILE_CAN_NOT_BE_EMPTY_OR_FILE_CAN_NOT_BE_RECOGNIZED}");
    }

    for (ExcelProject excelProject : listener.getExcelProjectContent()) {
        // Check excel project arguments is valid or not
        AddProjectRequest request = convertExcelProjectToAddProjectRequest(excelProject);
        projectService.addProject(request, userId);
    }

    // Create rules according to excel sheet
    Map<String, Map<String, List<ExcelTemplateRule>>> excelTemplateRulePartitionedByProject = listener.getExcelRuleContent();
    Map<String, Map<String, List<ExcelCustomRule>>> excelCustomRulePartitionedByProject = listener.getExcelCustomRuleContent();
    Map<String, Map<String, List<ExcelMultiTemplateRule>>> excelMultiTemplateRulePartitionedByProject = listener.getExcelMultiRuleContent();
    Set<String> allProjects = new HashSet<>();
    allProjects.addAll(excelTemplateRulePartitionedByProject.keySet());
    allProjects.addAll(excelCustomRulePartitionedByProject.keySet());
    allProjects.addAll(excelMultiTemplateRulePartitionedByProject.keySet());

    for (String projectName : allProjects) {
        Project projectInDb = projectDao.findByName(projectName);
        if (projectInDb == null) {
            throw new UnExpectedRequestException("{&PROJECT}: [" + projectName + "] {&DOES_NOT_EXIST}");
        }
        ruleBatchService.getAndSaveRule(excelTemplateRulePartitionedByProject.get(projectName), excelCustomRulePartitionedByProject.get(projectName),
                excelMultiTemplateRulePartitionedByProject.get(projectName), projectInDb, username);
    }

    fileInputStream.close();
    return new GeneralResponse<>("200", "{&SUCCEED_TO_UPLOAD_FILE}", null);
}
 
Example 12
Source File: ApiMediaResource.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@POST
@ApiOperation(value = "Create a picture for an API",
        notes = "User must have the API_DOCUMENTATION permission to use this service")
@ApiResponses({
        @ApiResponse(code = 201, message = "Page successfully created", response = PageEntity.class),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions({
        @Permission(value = RolePermission.API_DOCUMENTATION, acls = RolePermissionAction.CREATE)
})
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
public Response uploadImage(
        @PathParam("api") String api,
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("file") final FormDataBodyPart body
) throws IOException {
    final String mediaId;

    if (fileDetail.getSize() > this.mediaService.getMediaMaxSize()) {
        throw new UploadUnauthorized("Max size achieved " + fileDetail.getSize());
    } else {
        MediaEntity mediaEntity = new MediaEntity(
                IOUtils.toByteArray(uploadedInputStream),
                body.getMediaType().getType(),
                body.getMediaType().getSubtype(),
                fileDetail.getFileName(),
                fileDetail.getSize());

        try {
            ImageUtils.verify(body.getMediaType().getType(), body.getMediaType().getSubtype(), mediaEntity.getData());
        } catch (InvalidImageException e) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Invalid image format").build();
        }

        mediaId = mediaService.saveApiMedia(api, mediaEntity);
    }

    return Response.status(200).entity(mediaId).build();
}