Search in sources :

Example 1 with MultipartBody

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));
}
Also used : JAXRSClientFactoryBean(org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean) AttachmentBuilder(org.apache.cxf.jaxrs.ext.multipart.AttachmentBuilder) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 2 with MultipartBody

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));
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) MimeTypeMapper(ddf.mime.MimeTypeMapper) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) InputTransformer(ddf.catalog.transform.InputTransformer) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) ServiceReference(org.osgi.framework.ServiceReference) QueryResponse(ddf.catalog.operation.QueryResponse) Response(javax.ws.rs.core.Response) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) CatalogFramework(ddf.catalog.CatalogFramework) UriInfo(javax.ws.rs.core.UriInfo) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 3 with MultipartBody

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);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) TikaMimeTypeResolver(ddf.mime.tika.TikaMimeTypeResolver) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) Matchers.anyString(org.mockito.Matchers.anyString) BinaryContent(ddf.catalog.data.BinaryContent) QueryResponse(ddf.catalog.operation.QueryResponse) Response(javax.ws.rs.core.Response) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) Metacard(ddf.catalog.data.Metacard) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) InvocationOnMock(org.mockito.invocation.InvocationOnMock) GeotoolsFilterBuilder(ddf.catalog.filter.proxy.builder.GeotoolsFilterBuilder) FilterBuilder(ddf.catalog.filter.FilterBuilder) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) GeotoolsFilterBuilder(ddf.catalog.filter.proxy.builder.GeotoolsFilterBuilder) CatalogFramework(ddf.catalog.CatalogFramework) MediaType(javax.ws.rs.core.MediaType) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) UriInfo(javax.ws.rs.core.UriInfo) Test(org.junit.Test)

Example 4 with MultipartBody

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;
}
Also used : JwsSignature(org.apache.cxf.rs.security.jose.jws.JwsSignature) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) JwsDetachedSignature(org.apache.cxf.rs.security.jose.jws.JwsDetachedSignature) ArrayList(java.util.ArrayList) List(java.util.List) JwsSignatureProvider(org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider)

Example 5 with MultipartBody

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);
        }
    }
}
Also used : MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody)

Aggregations

MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)28 Attachment (org.apache.cxf.jaxrs.ext.multipart.Attachment)19 ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)9 Test (org.junit.Test)8 ArrayList (java.util.ArrayList)7 WebClient (org.apache.cxf.jaxrs.client.WebClient)7 ByteArrayInputStream (java.io.ByteArrayInputStream)5 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)5 LinkedHashMap (java.util.LinkedHashMap)4 MediaType (javax.ws.rs.core.MediaType)4 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)4 LinkedList (java.util.LinkedList)3 Map (java.util.Map)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 Response (javax.ws.rs.core.Response)3 Message (org.apache.cxf.message.Message)3 CatalogFramework (ddf.catalog.CatalogFramework)2 QueryResponse (ddf.catalog.operation.QueryResponse)2