use of org.apache.cxf.jaxrs.ext.multipart.MultipartBody in project jersey by jersey.
the class Jersey2776ITCase method testThatMultipartServerSupportsBoundaryQuotesEvenWithInterferingRuntimeDelegate.
@Test
public void testThatMultipartServerSupportsBoundaryQuotesEvenWithInterferingRuntimeDelegate() {
final JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
bean.setAddress(getBaseUri().toString());
bean.setServiceClass(ApacheCxfMultipartClient.class);
final ApacheCxfMultipartClient cxfClient = bean.create(ApacheCxfMultipartClient.class);
final String originalContent = "abc";
final byte[] content = originalContent.getBytes(StandardCharsets.US_ASCII);
final Attachment fileAttachment = new AttachmentBuilder().object(content).contentDisposition(new ContentDisposition("form-data; filename=\"abc-file\"; name=\"file_path\"")).build();
final String fileContentReturnedFromServer = cxfClient.uploadDocument(new MultipartBody(fileAttachment));
assertThat(fileContentReturnedFromServer, equalTo(originalContent));
}
use of org.apache.cxf.jaxrs.ext.multipart.MultipartBody in project ddf by codice.
the class TestRestEndpoint method testAddDocumentWithMetadataPositiveCase.
@Test
public void testAddDocumentWithMetadataPositiveCase() throws IOException, CatalogTransformerException, IngestException, SourceUnavailableException, URISyntaxException, InvalidSyntaxException, MimeTypeResolutionException {
CatalogFramework framework = givenCatalogFramework(SAMPLE_ID);
HttpHeaders headers = createHeaders(Arrays.asList(MediaType.APPLICATION_JSON));
BundleContext bundleContext = mock(BundleContext.class);
Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>();
ServiceReference serviceReference = mock(ServiceReference.class);
InputTransformer inputTransformer = mock(InputTransformer.class);
when(inputTransformer.transform(any())).thenReturn(new MetacardImpl());
when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer);
serviceReferences.add(serviceReference);
when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences);
RESTEndpoint rest = new RESTEndpoint(framework) {
@Override
BundleContext getBundleContext() {
return bundleContext;
}
};
UuidGenerator uuidGenerator = mock(UuidGenerator.class);
when(uuidGenerator.generateUuid()).thenReturn(UUID.randomUUID().toString());
rest.setUuidGenerator(uuidGenerator);
rest.setMetacardTypes(Collections.singletonList(BasicTypes.BASIC_METACARD));
MimeTypeMapper mimeTypeMapper = mock(MimeTypeMapper.class);
when(mimeTypeMapper.getMimeTypeForFileExtension("txt")).thenReturn("text/plain");
when(mimeTypeMapper.getMimeTypeForFileExtension("xml")).thenReturn("text/xml");
rest.setMimeTypeMapper(mimeTypeMapper);
addMatchingService(rest, Arrays.asList(getSimpleTransformer()));
UriInfo info = givenUriInfo(SAMPLE_ID);
List<Attachment> attachments = new ArrayList<>();
ContentDisposition contentDisposition = new ContentDisposition("form-data; name=parse.resource; filename=C:\\DDF\\metacard.txt");
Attachment attachment = new Attachment("parse.resource", new ByteArrayInputStream("Some Text".getBytes()), contentDisposition);
attachments.add(attachment);
ContentDisposition contentDisposition1 = new ContentDisposition("form-data; name=parse.metadata; filename=C:\\DDF\\metacard.xml");
Attachment attachment1 = new Attachment("parse.metadata", new ByteArrayInputStream("Some Text Again".getBytes()), contentDisposition1);
attachments.add(attachment1);
ContentDisposition contentDisposition2 = new ContentDisposition("form-data; name=metadata; filename=C:\\DDF\\metacard.xml");
Attachment attachment2 = new Attachment("metadata", new ByteArrayInputStream("<meta>beta</meta>".getBytes()), contentDisposition2);
attachments.add(attachment2);
MultipartBody multipartBody = new MultipartBody(attachments);
Response response = rest.addDocument(headers, info, mock(HttpServletRequest.class), multipartBody, null, new ByteArrayInputStream("".getBytes()));
LOGGER.debug(ToStringBuilder.reflectionToString(response));
assertThat(response.getStatus(), equalTo(201));
assertThat(response.getMetadata(), notNullValue());
assertThat(response.getMetadata().get(Metacard.ID).get(0).toString(), equalTo(SAMPLE_ID));
}
use of org.apache.cxf.jaxrs.ext.multipart.MultipartBody in project ddf by codice.
the class TestRestEndpoint method testGetMetacardAsXml.
/**
* Tests that a geojson input has its InputTransformer invoked by the REST endpoint to create
* a metacard that is then converted to XML and returned from the REST endpoint.
*
* @throws Exception
*/
@Test
public void testGetMetacardAsXml() throws Exception {
String filename = "src/test/resources/ValidGeojson.json";
CatalogFramework framework = givenCatalogFramework(SAMPLE_ID);
String metacardXml = "<metacard ns2:id=\"assigned-when-ingested\">\r\n" + "<type>type.metacard</type>\r\n" + "<string name=\"title\">\r\n" + "<value>Title goes here ...</value>\r\n" + "</string>\r\n" + "<string name=\"metadata\">\r\n" + "<value>metadata goes here ...</value>\r\n" + "</metacard>";
// Mock XmlMetacardTransformer that CatalogFramework will call to convert generated
// metacard into XML to be returned from REST endpoint.
final BinaryContent content = mock(BinaryContent.class);
InputStream inputStream = new ByteArrayInputStream(metacardXml.getBytes(GET_OUTPUT_TYPE));
when(content.getInputStream()).thenReturn(inputStream);
when(content.getMimeTypeValue()).thenReturn("application/json;id=geojson");
when(framework.transform(isA(Metacard.class), anyString(), isNull(Map.class))).thenAnswer(new Answer<BinaryContent>() {
@Override
public BinaryContent answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Metacard metacard = (Metacard) args[0];
return content;
}
});
RESTEndpoint restEndpoint = new RESTEndpoint(framework);
// Add a MimeTypeToINputTransformer that the REST endpoint will call to create the metacard
addMatchingService(restEndpoint, Arrays.asList(getSimpleTransformer()));
restEndpoint.setTikaMimeTypeResolver(new TikaMimeTypeResolver());
FilterBuilder filterBuilder = new GeotoolsFilterBuilder();
restEndpoint.setFilterBuilder(filterBuilder);
String json = "{\r\n" + " \"properties\": {\r\n" + " \"title\": \"myTitle\",\r\n" + " \"thumbnail\": \"CA==\",\r\n" + " \"resource-uri\": \"http://example.com\",\r\n" + " \"created\": \"2012-09-01T00:09:19.368+0000\",\r\n" + " \"metadata-content-type-version\": \"myVersion\",\r\n" + " \"metadata-content-type\": \"myType\",\r\n" + " \"metadata\": \"<xml>metadata goes here ...</xml>\",\r\n" + " \"modified\": \"2012-09-01T00:09:19.368+0000\"\r\n" + " },\r\n" + " \"type\": \"Feature\",\r\n" + " \"geometry\": {\r\n" + " \"type\": \"Point\",\r\n" + " \"coordinates\": [\r\n" + " 30.0,\r\n" + " 10.0\r\n" + " ]\r\n" + " }\r\n" + "} ";
// Sample headers for a multipart body specifying a geojson file to have a metacard created for:
// Content-Disposition: form-data; name="file"; filename="C:\DDF\geojson_valid.json"
// Content-Type: application/json;id=geojson
InputStream is = IOUtils.toInputStream(json);
List<Attachment> attachments = new ArrayList<>();
ContentDisposition contentDisposition = new ContentDisposition("form-data; name=file; filename=C:\\DDF\\geojson_valid.json");
Attachment attachment = new Attachment("file_part", is, contentDisposition);
attachments.add(attachment);
MediaType mediaType = new MediaType(MediaType.APPLICATION_JSON, "id=geojson");
MultipartBody multipartBody = new MultipartBody(attachments, mediaType, true);
UriInfo uriInfo = createSpecificUriInfo(LOCAL_RETRIEVE_ADDRESS);
Response response = restEndpoint.createMetacard(multipartBody, uriInfo, RESTEndpoint.DEFAULT_METACARD_TRANSFORMER);
assertEquals(OK, response.getStatus());
InputStream responseEntity = (InputStream) response.getEntity();
String responseXml = IOUtils.toString(responseEntity);
assertEquals(metacardXml, responseXml);
}
use of org.apache.cxf.jaxrs.ext.multipart.MultipartBody in project cxf by apache.
the class AbstractJwsMultipartSignatureFilter method getAttachmentParts.
protected List<Object> getAttachmentParts(Object rootEntity) {
List<Object> parts = null;
if (rootEntity instanceof MultipartBody) {
parts = CastUtils.cast(((MultipartBody) rootEntity).getAllAttachments());
} else {
parts = new ArrayList<Object>();
if (rootEntity instanceof List) {
List<Object> entityList = CastUtils.cast((List<?>) rootEntity);
parts.addAll(entityList);
} else {
parts.add(rootEntity);
}
}
JwsHeaders headers = new JwsHeaders();
headers.setPayloadEncodingStatus(false);
JwsSignatureProvider theSigProvider = sigProvider != null ? sigProvider : JwsUtils.loadSignatureProvider(headers, true);
JwsSignature jwsSignature = theSigProvider.createJwsSignature(headers);
String base64UrlEncodedHeaders = Base64UrlUtility.encode(writer.toJson(headers));
byte[] headerBytesWithDot = StringUtils.toBytesASCII(base64UrlEncodedHeaders + ".");
jwsSignature.update(headerBytesWithDot, 0, headerBytesWithDot.length);
AttachmentUtils.addMultipartOutFilter(new JwsMultipartSignatureOutFilter(jwsSignature));
JwsDetachedSignature jws = new JwsDetachedSignature(headers, base64UrlEncodedHeaders, jwsSignature, useJwsJsonSignatureFormat);
Attachment jwsPart = new Attachment("signature", JoseConstants.MEDIA_TYPE_JOSE, jws);
parts.add(jwsPart);
return parts;
}
use of org.apache.cxf.jaxrs.ext.multipart.MultipartBody in project cxf by apache.
the class FormEncodingProvider method populateMap.
/**
* Retrieve map of parameters from the passed in message
*
* @param message
* @return a Map of parameters.
*/
protected void populateMap(MultivaluedMap<String, String> params, Annotation[] anns, InputStream is, MediaType mt, boolean decode) {
if (mt.isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) {
MultipartBody body = AttachmentUtils.getMultipartBody(mc, attachmentDir, attachmentThreshold, attachmentMaxSize);
FormUtils.populateMapFromMultipart(params, body, PhaseInterceptorChain.getCurrentMessage(), decode);
} else {
String enc = HttpUtils.getEncoding(mt, StandardCharsets.UTF_8.name());
Object servletRequest = mc != null ? mc.getHttpServletRequest() : null;
if (servletRequest == null) {
FormUtils.populateMapFromString(params, PhaseInterceptorChain.getCurrentMessage(), FormUtils.readBody(is, enc), enc, decode);
} else {
FormUtils.populateMapFromString(params, PhaseInterceptorChain.getCurrentMessage(), FormUtils.readBody(is, enc), enc, decode, (javax.servlet.http.HttpServletRequest) servletRequest);
}
}
}
Aggregations