Java Code Examples for org.glassfish.jersey.media.multipart.FormDataBodyPart#getValueAs()

The following examples show how to use org.glassfish.jersey.media.multipart.FormDataBodyPart#getValueAs() . 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: NotifierInfoCatalogResource.java    From streamline with Apache License 2.0 6 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/notifiers/{id}")
@Timed
public Response addOrUpdateNotifierInfo(@PathParam("id") Long id,
                                        @FormDataParam("notifierJarFile") final InputStream inputStream,
                                        @FormDataParam("notifierJarFile") final FormDataContentDisposition contentDispositionHeader,
                                        @FormDataParam("notifierConfig") final FormDataBodyPart notifierConfig,
                                        @Context SecurityContext securityContext) throws IOException {
    SecurityUtil.checkPermissions(authorizer, securityContext, Notifier.NAMESPACE, id, WRITE);
    MediaType mediaType = notifierConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    Notifier notifier = notifierConfig.getValueAs(Notifier.class);
    String jarFileName = uploadJar(inputStream, notifier.getName());
    notifier.setJarFileName(jarFileName);
    Notifier newNotifier = catalogService.addOrUpdateNotifierInfo(id, notifier);
    return WSUtils.respondEntity(newNotifier, CREATED);
}
 
Example 2
Source File: UDFCatalogResource.java    From streamline with Apache License 2.0 6 votes vote down vote up
/**
 * Add a new UDF.
 * <p>
 * curl -X POST 'http://localhost:8080/api/v1/catalog/udfs' -F udfJarFile=/tmp/foo-function.jar
 * -F udfConfig='{"name":"Foo", "description": "testing", "type":"FUNCTION", "className":"com.test.Foo"};type=application/json'
 * </p>
 */
@Timed
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/udfs")
public Response addUDF(@FormDataParam("udfJarFile") final InputStream inputStream,
                       @FormDataParam("udfJarFile") final FormDataContentDisposition contentDispositionHeader,
                       @FormDataParam("udfConfig") final FormDataBodyPart udfConfig,
                       @FormDataParam("builtin") final boolean builtin,
                       @Context SecurityContext securityContext) throws Exception {
    SecurityUtil.checkRole(authorizer, securityContext, Roles.ROLE_UDF_ADMIN);
    MediaType mediaType = udfConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    UDF udf = udfConfig.getValueAs(UDF.class);
    processUdf(inputStream, udf, true, builtin);
    UDF createdUdf = catalogService.addUDF(udf);
    SecurityUtil.addAcl(authorizer, securityContext, UDF.NAMESPACE, createdUdf.getId(), EnumSet.allOf(Permission.class));
    return WSUtils.respondEntity(createdUdf, CREATED);
}
 
Example 3
Source File: PinotSchemaRestletResource.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private Schema getSchemaFromMultiPart(FormDataMultiPart multiPart) {
  try {
    Map<String, List<FormDataBodyPart>> map = multiPart.getFields();
    if (!PinotSegmentUploadDownloadRestletResource.validateMultiPart(map, null)) {
      throw new ControllerApplicationException(LOGGER, "Found not exactly one file from the multi-part fields",
          Response.Status.BAD_REQUEST);
    }
    FormDataBodyPart bodyPart = map.values().iterator().next().get(0);
    try (InputStream inputStream = bodyPart.getValueAs(InputStream.class)) {
      return Schema.fromInputSteam(inputStream);
    } catch (IOException e) {
      throw new ControllerApplicationException(LOGGER,
          "Caught exception while de-serializing the schema from request body: " + e.getMessage(),
          Response.Status.BAD_REQUEST);
    }
  } finally {
    multiPart.cleanup();
  }
}
 
Example 4
Source File: LLCSegmentCompletionHandlers.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts the segment file from the form into a local temporary file under file upload temporary directory.
 */
private static File extractSegmentFromFormToLocalTempFile(FormDataMultiPart form, String segmentName)
    throws IOException {
  try {
    Map<String, List<FormDataBodyPart>> map = form.getFields();
    Preconditions.checkState(PinotSegmentUploadDownloadRestletResource.validateMultiPart(map, segmentName),
        "Invalid multi-part for segment: %s", segmentName);
    FormDataBodyPart bodyPart = map.values().iterator().next().get(0);

    File localTempFile = new File(ControllerFilePathProvider.getInstance().getFileUploadTempDir(),
        getTempSegmentFileName(segmentName));
    try (InputStream inputStream = bodyPart.getValueAs(InputStream.class)) {
      Files.copy(inputStream, localTempFile.toPath());
    } catch (Exception e) {
      FileUtils.deleteQuietly(localTempFile);
      throw e;
    }
    return localTempFile;
  } finally {
    form.cleanup();
  }
}
 
Example 5
Source File: PinotSegmentUploadDownloadRestletResource.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private File getFileFromMultipart(FormDataMultiPart multiPart, File dstFile)
    throws IOException {
  // Read segment file or segment metadata file and directly use that information to update zk
  Map<String, List<FormDataBodyPart>> segmentMetadataMap = multiPart.getFields();
  if (!validateMultiPart(segmentMetadataMap, null)) {
    throw new ControllerApplicationException(LOGGER, "Invalid multi-part form for segment metadata",
        Response.Status.BAD_REQUEST);
  }
  FormDataBodyPart segmentMetadataBodyPart = segmentMetadataMap.values().iterator().next().get(0);
  try (InputStream inputStream = segmentMetadataBodyPart.getValueAs(InputStream.class);
      OutputStream outputStream = new FileOutputStream(dstFile)) {
    IOUtils.copyLarge(inputStream, outputStream);
  } finally {
    multiPart.cleanup();
  }
  return dstFile;
}
 
Example 6
Source File: AttachmentAction.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
@JaxrsMethodDescribe(value = "上传附件.", action = ActionUpload.class)
@POST
@Path("upload/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void upload(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
				   @JaxrsParameterDescribe("工作标识") @PathParam("workId") String workId,
				   @JaxrsParameterDescribe("位置") @FormDataParam("site") String site,
				   @JaxrsParameterDescribe("附件名称") @FormDataParam(FILENAME_FIELD) String fileName,
				   @JaxrsParameterDescribe("天印扩展字段") @FormDataParam("extraParam") String extraParam,
				   @FormDataParam(FILE_FIELD) byte[] bytes,
				   @FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
	ActionResult<ActionUpload.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		if(StringUtils.isEmpty(extraParam)){
			extraParam = this.request2Json(request);
		}
		if(bytes==null){
			Map<String, List<FormDataBodyPart>> map = form.getFields();
			for(String key: map.keySet()){
				FormDataBodyPart part = map.get(key).get(0);
				if("application".equals(part.getMediaType().getType())){
					bytes = part.getValueAs(byte[].class);
					break;
				}
			}
		}
		result = new ActionUpload().execute(effectivePerson, workId, site, fileName, bytes, disposition,
				extraParam);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 7
Source File: AttachmentAction.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
@JaxrsMethodDescribe(value = "上传附件.", action = ActionUploadWithWorkCompleted.class)
@POST
@Path("upload/workcompleted/{workCompletedId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadWithWorkCompleted(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse,
		@Context HttpServletRequest request,
		@JaxrsParameterDescribe("已完成工作标识") @PathParam("workCompletedId") String workCompletedId,
		@JaxrsParameterDescribe("位置") @FormDataParam("site") String site,
		@JaxrsParameterDescribe("附件名称") @FormDataParam(FILENAME_FIELD) String fileName,
		@JaxrsParameterDescribe("天印扩展字段") @FormDataParam("extraParam") String extraParam,
		@FormDataParam(FILE_FIELD) byte[] bytes,
		@FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
	ActionResult<ActionUploadWithWorkCompleted.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		if(StringUtils.isEmpty(extraParam)){
			extraParam = this.request2Json(request);
		}
		if(bytes==null){
			Map<String, List<FormDataBodyPart>> map = form.getFields();
			for(String key: map.keySet()){
				FormDataBodyPart part = map.get(key).get(0);
				if("application".equals(part.getMediaType().getType())){
					bytes = part.getValueAs(byte[].class);
					break;
				}
			}
		}
		result = new ActionUploadWithWorkCompleted().execute(effectivePerson, workCompletedId, site, fileName,
				bytes, disposition, extraParam);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));

}
 
Example 8
Source File: AttachmentAction.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
@JaxrsMethodDescribe(value = "更新附件.", action = ActionUpdate.class)
@PUT
@Path("update/{id}/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void update(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("附件标识") @PathParam("id") String id,
		@JaxrsParameterDescribe("工作标识") @PathParam("workId") String workId,
		@JaxrsParameterDescribe("附件名称") @FormDataParam(FILENAME_FIELD) String fileName,
		@JaxrsParameterDescribe("天印扩展字段") @FormDataParam("extraParam") String extraParam,
		@FormDataParam(FILE_FIELD) byte[] bytes,
		@JaxrsParameterDescribe("附件") @FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
	ActionResult<ActionUpdate.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		if(StringUtils.isEmpty(extraParam)){
			extraParam = this.request2Json(request);
		}
		if(bytes==null){
			Map<String, List<FormDataBodyPart>> map = form.getFields();
			for(String key: map.keySet()){
				FormDataBodyPart part = map.get(key).get(0);
				if("application".equals(part.getMediaType().getType())){
					bytes = part.getValueAs(byte[].class);
					break;
				}
			}
		}
		result = new ActionUpdate().execute(effectivePerson, id, workId, fileName, bytes, disposition, extraParam);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 9
Source File: AttachmentAction.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
/** 与update方法同,为了兼容ntko对于附件上传只能设置post方法 */
@JaxrsMethodDescribe(value = "更新附件.", action = ActionUpdate.class)
@POST
@Path("update/{id}/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void updatePost(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("附件标识") @PathParam("id") String id,
		@JaxrsParameterDescribe("工作标识") @PathParam("workId") String workId,
		@JaxrsParameterDescribe("附件名称") @FormDataParam(FILENAME_FIELD) String fileName,
		@JaxrsParameterDescribe("天印扩展字段") @FormDataParam("extraParam") String extraParam,
		@FormDataParam(FILE_FIELD) byte[] bytes,
		@JaxrsParameterDescribe("附件") @FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
	ActionResult<ActionUpdate.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		if(StringUtils.isEmpty(extraParam)){
			extraParam = this.request2Json(request);
		}
		if(bytes==null){
			Map<String, List<FormDataBodyPart>> map = form.getFields();
			for(String key: map.keySet()){
				FormDataBodyPart part = map.get(key).get(0);
				if("application".equals(part.getMediaType().getType())){
					bytes = part.getValueAs(byte[].class);
					break;
				}
			}
		}
		result = new ActionUpdate().execute(effectivePerson, id, workId, fileName, bytes, disposition, extraParam);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 10
Source File: Forms.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
static File uploadFile(FormDataBodyPart part, String directory) throws IOException {
  try (InputStream in = part.getValueAs(InputStream.class)) {
    Path path = Paths.get(directory, part.getFormDataContentDisposition().getFileName());
    FileHelper.copy(in, path);
    return path.toFile();
  }
}
 
Example 11
Source File: TopologyComponentBundleResource.java    From streamline with Apache License 2.0 5 votes vote down vote up
private <T> T getFormDataFromMultiPartRequestAs (Class<T> clazz, FormDataMultiPart form, String paramName) {
    T result = null;
    try {
        FormDataBodyPart part = form.getField(paramName);
        if (part != null) {
            result = part.getValueAs(clazz);
        }
    } catch (Exception e) {
        LOG.debug("Cannot get param " + paramName + " as" + clazz + " from multipart form" );
    }
    return result;
}
 
Example 12
Source File: NotifierInfoCatalogResource.java    From streamline with Apache License 2.0 5 votes vote down vote up
/**
 * Sample request :
 * <pre>
 * curl -X POST 'http://localhost:8080/api/v1/catalog/notifiers' -F notifierJarFile=/tmp/email-notifier.jar
 * -F notifierConfig='{
 *  "name":"email_notifier",
 *  "description": "testing",
 * "className":"com.hortonworks.streamline.streams.notifiers.EmailNotifier",
 *   "properties": {
 *     "username": "[email protected]",
 *     "password": "testing12",
 *     "host": "smtp.gmail.com",
 *     "port": "587",
 *     "starttls": "true",
 *     "debug": "true"
 *     },
 *   "fieldValues": {
 *     "from": "[email protected]",
 *     "to": "[email protected]",
 *     "subject": "Testing email notifications",
 *     "contentType": "text/plain",
 *     "body": "default body"
 *     }
 * };type=application/json'
 * </pre>
 */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/notifiers")
@Timed
public Response addNotifier(@FormDataParam("notifierJarFile") final InputStream inputStream,
                            @FormDataParam("notifierJarFile") final FormDataContentDisposition contentDispositionHeader,
                            @FormDataParam("notifierConfig") final FormDataBodyPart notifierConfig,
                            @Context SecurityContext securityContext) throws IOException {
    SecurityUtil.checkRole(authorizer, securityContext, Roles.ROLE_NOTIFIER_ADMIN);
    MediaType mediaType = notifierConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    Notifier notifier = notifierConfig.getValueAs(Notifier.class);
    Collection<Notifier> existing = null;
    existing = catalogService.listNotifierInfos(Collections.singletonList(new QueryParam(Notifier.NOTIFIER_NAME, notifier.getName())));
    if (existing != null && !existing.isEmpty()) {
        LOG.warn("Received a post request for an already registered notifier. Not creating entity for " + notifier);
        return WSUtils.respondEntity(notifier, CONFLICT);
    }
    String jarFileName = uploadJar(inputStream, notifier.getName());
    notifier.setJarFileName(jarFileName);
    Notifier createdNotifier = catalogService.addNotifierInfo(notifier);
    SecurityUtil.addAcl(authorizer, securityContext, Notifier.NAMESPACE, createdNotifier.getId(),
            EnumSet.allOf(Permission.class));
    return WSUtils.respondEntity(createdNotifier, CREATED);
}
 
Example 13
Source File: XmlDVReportService.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
@POST
@Path("/inferSchema")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response inferSchema(FormDataMultiPart form) throws IOException{
	LOGGER.debug("Start to infer Schema");
	boolean response = false;
	String schemaDef;
	try {
		FormDataBodyPart jarFile = form.getField("inputFile");
		String fileName = jarFile.getContentDisposition().getFileName();
		JobConfig jobConfig = getJobConfig(form);
		if (fileName == null) {
			return null;
		}
		File fileObject = jarFile.getValueAs(File.class);
		schemaDef = generateSchema(fileObject, fileName);
		response = saveDataAndCreateDirectories(jobConfig.getJumbuneJobName(), schemaDef);
		if (response) {
			return Response.ok(response).build();
		} else {
			return Response.status(Status.INTERNAL_SERVER_ERROR).build();
		}
	} catch (Exception e) {
		LOGGER.error(JumbuneRuntimeException.throwException(e.getStackTrace()));
		return Response.status(Status.INTERNAL_SERVER_ERROR).build();
	}

}
 
Example 14
Source File: LLCSegmentCompletionHandlers.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts a file from the form into the given directory.
 */
private static void extractFileFromForm(FormDataMultiPart form, String fileName, File outputDir)
    throws IOException {
  FormDataBodyPart bodyPart = form.getField(fileName);
  Preconditions.checkState(bodyPart != null, "Failed to find: %s", fileName);

  try (InputStream inputStream = bodyPart.getValueAs(InputStream.class)) {
    Files.copy(inputStream, new File(outputDir, fileName).toPath());
  }
}
 
Example 15
Source File: UDFCatalogResource.java    From streamline with Apache License 2.0 4 votes vote down vote up
/**
 * Update a udf.
 * <p>
 *     curl -X PUT 'http://localhost:8080/api/v1/catalog/udfs/34'
 *     -F udfJarFile=@/tmp/streams-functions-0.6.0-SNAPSHOT.jar
 *     -F udfConfig='{"name":"stddev", "description": "stddev",
 *                   "type":"AGGREGATE", "className":"com.hortonworks.streamline.streams.rule.udaf.Stddev"};type=application/json'
 * </p>
 * <pre>
 * {
 *   "responseCode": 1000,
 *   "responseMessage": "Success",
 *   "entity": {
 *     "id": 48,
 *     "name": "SUBSTRING",
 *     "description": "Substring",
 *     "type": "FUNCTION",
 *     "className": "builtin"
 *   }
 * }
 * </pre>
 */
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/udfs/{id}")
@Timed
public Response addOrUpdateUDF(@PathParam("id") Long udfId,
                               @FormDataParam("udfJarFile") final InputStream inputStream,
                               @FormDataParam("udfJarFile") final FormDataContentDisposition contentDispositionHeader,
                               @FormDataParam("udfConfig") final FormDataBodyPart udfConfig,
                               @FormDataParam("builtin") final boolean builtin,
                               @Context SecurityContext securityContext) throws Exception {
    SecurityUtil.checkPermissions(authorizer, securityContext, UDF.NAMESPACE, udfId, WRITE);
    MediaType mediaType = udfConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    UDF udf = udfConfig.getValueAs(UDF.class);
    processUdf(inputStream, udf, false, builtin);
    UDF newUdf = catalogService.addOrUpdateUDF(udfId, udf);
    return WSUtils.respondEntity(newUdf, CREATED);
}