Java Code Examples for org.glassfish.jersey.media.multipart.FormDataMultiPart#getField()

The following examples show how to use org.glassfish.jersey.media.multipart.FormDataMultiPart#getField() . 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: 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 2
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 3
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 4
Source File: XACMLRequestFilter.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean validateFormParam(String key, FormDataMultiPart params, boolean isRequired) {
    if (params.getField(key) == null && isRequired) {
        throw ErrorUtils.sendError("Form parameters do not contain " + key, INTERNAL_SERVER_ERROR);
    }
    return params.getField(key) == null;
}
 
Example 5
Source File: NotifierResource.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@CheckPermissionsForPath
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@JSONP
@Produces({MediaType.APPLICATION_JSON, "application/javascript"})
@Override
public ApiResponse executeMultiPartPut(@Context UriInfo ui,
    @QueryParam("callback") @DefaultValue("callback") String callback,
    FormDataMultiPart multiPart) throws Exception {

    if (logger.isTraceEnabled()) {
        logger.trace("NotifierResource.executeMultiPartPut");
    }

    String certInfoParam = getValueOrNull(multiPart, "certInfo");
    if (certInfoParam != null){
        throw new IllegalArgumentException("Cannot create or update with certInfo parameter.  It is derived.");
    }

    String name =         getValueOrNull(multiPart, "name");
    String provider =     getValueOrNull(multiPart, "provider");
    String certPassword = getValueOrNull(multiPart, "certificatePassword");

    InputStream is = null;
    Map<String, Object> certAttributes = null;
    String filename = null;
    byte[] certBytes = null;
    if (multiPart.getField("p12Certificate") != null) {
        filename = multiPart.getField("p12Certificate").getContentDisposition().getFileName();
        is = multiPart.getField("p12Certificate").getEntityAs(InputStream.class);
        if (is != null) {
            certBytes = IOUtils.toByteArray(is);
            certAttributes = CertificateUtils.getCertAtrributes(certBytes, certPassword);
        }
    }else{
        throw new IllegalArgumentException("Certificate is invalid .p12 file or incorrect certificatePassword");
    }

    // check to see if the certificate is valid
    if(!CertificateUtils.isValid(certAttributes)){
        throw new IllegalArgumentException("p12Certificate is expired");
    }

    HashMap<String, Object> certProps = new LinkedHashMap<String, Object>();
    certProps.put("name", name);
    certProps.put("provider", provider);
    certProps.put("environment", "production");
    certProps.put("certificatePassword", certPassword);

    if(certBytes != null && certBytes.length > 0 ){
        certProps.put("p12Certificate", certBytes);
    }
    HashMap<String, Object> certInfo = new LinkedHashMap<String, Object>();
    if (certAttributes != null){
        certInfo.put("filename", filename);
        certInfo.put("details", certAttributes);
    }
    certProps.put("certInfo", certInfo);


    ApiResponse response = createApiResponse();
    response.setAction("put");
    response.setApplication(services.getApplication());
    response.setParams(ui.getQueryParameters());
    ServicePayload payload = getPayload(certProps);
    executeServiceRequest(ui, response, ServiceAction.PUT, payload);

    return response;
}
 
Example 6
Source File: NotifierResource.java    From usergrid with Apache License 2.0 4 votes vote down vote up
private String getValueOrNull(FormDataMultiPart multiPart, String name) {
    if (multiPart.getField(name) != null) {
        return multiPart.getField(name).getValue();
    }
    return null;
}
 
Example 7
Source File: NotifiersResource.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@CheckPermissionsForPath
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Override
@JSONP
@Produces({MediaType.APPLICATION_JSON, "application/javascript"})
public ApiResponse executeMultiPartPost(
        @Context UriInfo ui,
        @QueryParam("callback") @DefaultValue("callback") String callback,
        FormDataMultiPart multiPart)
        throws Exception {

    if (logger.isTraceEnabled()) {
        logger.trace("Notifiers.executeMultiPartPost");
    }

    String certInfoParam = getValueOrNull(multiPart, "certInfo");
    if (certInfoParam != null){
        throw new IllegalArgumentException("Cannot create or update with certInfo parameter.  It is derived.");
    }

    String name =         getValueOrNull(multiPart, "name");
    String provider =     getValueOrNull(multiPart, "provider");
    String environment =  getValueOrNull(multiPart, "environment");
    String certPassword = getValueOrNull(multiPart, "certificatePassword");

    InputStream is = null;
    Map<String, Object> certAttributes = null;
    String filename = null;
    byte[] certBytes = null;
    if (multiPart.getField("p12Certificate") != null) {
        filename = multiPart.getField("p12Certificate").getContentDisposition().getFileName();
        is = multiPart.getField("p12Certificate").getEntityAs(InputStream.class);
        if (is != null) {
            certBytes = IOUtils.toByteArray(is);
            certAttributes = CertificateUtils.getCertAtrributes(certBytes, certPassword);
        }
    }else{
        throw new IllegalArgumentException("Certificate is invalid .p12 file or incorrect certificatePassword");
    }

    // check to see if the certificate is valid
    if(!CertificateUtils.isValid(certAttributes)){
        throw new IllegalArgumentException("p12Certificate is expired.");
    }


    HashMap<String, Object> certProps = new LinkedHashMap<String, Object>();

    certProps.put("name", name);
    certProps.put("provider", provider);
    certProps.put("environment", environment);
    certProps.put("certificatePassword", certPassword);

    if(certBytes != null && certBytes.length > 0 ){
        certProps.put("p12Certificate", certBytes);
    }
    HashMap<String, Object> certInfo = new LinkedHashMap<String, Object>();
    if (certAttributes != null){
        certInfo.put("filename", filename);
        certInfo.put("details", certAttributes);
    }
    certProps.put("certInfo", certInfo);

    ApiResponse response = createApiResponse();
    response.setAction("post");
    response.setApplication(services.getApplication());
    response.setParams(ui.getQueryParameters());
    ServicePayload payload = getPayload(certProps);
    executeServiceRequest(ui, response, ServiceAction.POST, payload);

    return response;
}
 
Example 8
Source File: NotifiersResource.java    From usergrid with Apache License 2.0 4 votes vote down vote up
private String getValueOrNull(FormDataMultiPart multiPart, String name) {
    if (multiPart.getField(name) != null) {
        return multiPart.getField(name).getValue();
    }
    return null;
}
 
Example 9
Source File: ServiceResource.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JSONP
@Produces({MediaType.APPLICATION_JSON, "application/javascript"})
private ApiResponse executeMultiPart( UriInfo ui, String callback, FormDataMultiPart multiPart,
                                          ServiceAction serviceAction ) throws Exception {
    // needed for testing
    this.binaryStore = binaryStoreFactory.getBinaryStore( properties.getProperty(PROPERTIES_USERGRID_BINARY_UPLOADER) );

    // collect form data values
    List<BodyPart> bodyParts = multiPart.getBodyParts();
    HashMap<String, Object> data = new HashMap<>();
    for ( BodyPart bp : bodyParts ) {
        FormDataBodyPart bodyPart = ( FormDataBodyPart ) bp;
        if ( bodyPart.getMediaType().equals( MediaType.TEXT_PLAIN_TYPE ) ) {
            data.put( bodyPart.getName(), bodyPart.getValue() );
        }
        else {
            if (logger.isTraceEnabled()) {
                logger.trace("skipping bodyPart {} of media type {}", bodyPart.getName(), bodyPart.getMediaType());
            }
        }
    }

    FormDataBodyPart fileBodyPart = multiPart.getField( FILE_FIELD_NAME );

    data.put( AssetUtils.FILE_METADATA, new HashMap() );

    // process entity
    ApiResponse response = createApiResponse();
    response.setAction( serviceAction.name().toLowerCase() );
    response.setApplication( services.getApplication() );
    response.setParams( ui.getQueryParameters() );

    //Updates entity with fields that are in text/plain as per loop above
    if(data.get( FILE_FIELD_NAME )==null){
        data.put( FILE_FIELD_NAME,null );
    }
    ServicePayload payload = getPayload( data );
    ServiceResults serviceResults = executeServiceRequest( ui, response, serviceAction, payload );

    // process file part
    if ( fileBodyPart != null ) {
        InputStream fileInput = ( (BodyPartEntity) fileBodyPart.getEntity() ).getInputStream();
        if ( fileInput != null ) {
            Entity entity = serviceResults.getEntity();
            EntityManager em = emf.getEntityManager( getApplicationId() );
            try {
                binaryStore.write( getApplicationId(), entity, fileInput );
            }
            catch ( AwsPropertiesNotFoundException apnfe){
                logger.error( "Amazon Property needed for this operation not found",apnfe );
                response.setError( "500","Amazon Property needed for this operation not found",apnfe );
            }
            catch ( RuntimeException re){
                logger.error(re.getMessage());
                response.setError( "500", re );
            }
            //em.update( entity );
            entity = serviceResults.getEntity();
            serviceResults.setEntity( entity );
        }
    }

    return response;
}