org.glassfish.jersey.media.multipart.BodyPart Java Examples

The following examples show how to use org.glassfish.jersey.media.multipart.BodyPart. 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: SchemaRegistryClient.java    From registry with Apache License 2.0 8 votes vote down vote up
@Override
public String uploadFile(InputStream inputStream) {
    MultiPart multiPart = new MultiPart();
    BodyPart filePart = new StreamDataBodyPart("file", inputStream, "file");
    multiPart.bodyPart(filePart);
    return runRetryableBlock((SchemaRegistryTargets targets) -> {
        try {
            return login.doAction(new PrivilegedAction<String>() {
                @Override
                public String run() {
                    return targets.filesTarget.request()
                            .post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA), String.class);
                }
            });
        } catch (LoginException | ProcessingException e) {
            throw new RegistryRetryableException(e);
        }
    });
}
 
Example #2
Source File: SchemaRegistryClient.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public String uploadFile(InputStream inputStream) {
    MultiPart multiPart = new MultiPart();
    BodyPart filePart = new StreamDataBodyPart("file", inputStream, "file");
    multiPart.bodyPart(filePart);
    try {
        return login.doAction(new PrivilegedAction<String>() {
            @Override
            public String run() {
                return currentSchemaRegistryTargets().filesTarget.request()
                        .post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA), String.class);
            }
        });
    } catch (LoginException e) {
        throw new RegistryRetryableException(e);
    }
}
 
Example #3
Source File: ObjectsResourceTest.java    From imagej-server with Apache License 2.0 6 votes vote down vote up
/**
 * Upload file to IOResource
 * 
 * @param filename name of file
 * @param stream stream of file content
 * @return the object ID of that file
 * @throws IOException
 */
private String uploadFile(final String filename, final InputStream stream)
	throws IOException
{
	try (final FormDataMultiPart multiPart = new FormDataMultiPart()) {
		multiPart.bodyPart(new BodyPart(stream,
			MediaType.MULTIPART_FORM_DATA_TYPE).contentDisposition(
				FormDataContentDisposition.name("file").fileName(filename).build()));
		final String response = resources.client().register(
			MultiPartFeature.class).target("/objects/upload").request().post(Entity
				.entity(multiPart, multiPart.getMediaType()), String.class);
		final Matcher matcher = Pattern.compile("\\{\"id\":\"([^\"]+)\"\\}")
			.matcher(response);
		assertTrue(matcher.find());
		return matcher.group(1);
	}
}
 
Example #4
Source File: JerseyHttpClient.java    From karate with MIT License 5 votes vote down vote up
@Override
public Entity getEntity(List<MultiPartItem> items, String mediaType) {
    MultiPart multiPart = new MultiPart();
    for (MultiPartItem item : items) {
        if (item.getValue() == null || item.getValue().isNull()) {
            continue;
        }
        String name = item.getName();
        String filename = item.getFilename();
        ScriptValue sv = item.getValue();
        String ct = item.getContentType();
        if (ct == null) {
            ct = HttpUtils.getContentType(sv);
        }
        MediaType itemType = MediaType.valueOf(ct);
        if (name == null) { // most likely multipart/mixed
            BodyPart bp = new BodyPart().entity(sv.getAsString()).type(itemType);
            multiPart.bodyPart(bp);
        } else if (filename != null) {
            StreamDataBodyPart part = new StreamDataBodyPart(name, sv.getAsStream(), filename, itemType);
            multiPart.bodyPart(part);
        } else {
            multiPart.bodyPart(new FormDataBodyPart(name, sv.getAsString(), itemType));
        }
    }
    return Entity.entity(multiPart, mediaType);
}
 
Example #5
Source File: AbstractRestIntegrationTest.java    From registry with Apache License 2.0 5 votes vote down vote up
protected MultiPart getMultiPart(ResourceTestElement resourceToTest, Object entity) {
    MultiPart multiPart = new MultiPart();
    BodyPart filePart = new FileDataBodyPart(resourceToTest.getFileNameHeader(), resourceToTest.getFileToUpload());
    BodyPart entityPart = new FormDataBodyPart(resourceToTest.getEntityNameHeader(), entity, MediaType.APPLICATION_JSON_TYPE);
    multiPart.bodyPart(filePart).bodyPart(entityPart);
    return multiPart;
}
 
Example #6
Source File: RestIntegrationTest.java    From streamline with Apache License 2.0 5 votes vote down vote up
private MultiPart getMultiPart(ResourceTestElement resourceToTest, Object entity) {
    MultiPart multiPart = new MultiPart();
    BodyPart filePart = new FileDataBodyPart(resourceToTest.fileNameHeader, resourceToTest.fileToUpload);
    BodyPart entityPart = new FormDataBodyPart(resourceToTest.entityNameHeader, entity, MediaType.APPLICATION_JSON_TYPE);
    multiPart.bodyPart(filePart).bodyPart(entityPart);
    return multiPart;
}
 
Example #7
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;
}