Search in sources :

Example 1 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition 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 ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition in project ddf by codice.

the class TestRestEndpoint method testParseAttachments.

@Test
public void testParseAttachments() throws IOException, CatalogTransformerException, SourceUnavailableException, IngestException, InvalidSyntaxException, MimeTypeResolutionException, URISyntaxException {
    CatalogFramework framework = givenCatalogFramework(SAMPLE_ID);
    BundleContext bundleContext = mock(BundleContext.class);
    Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>();
    ServiceReference serviceReference = mock(ServiceReference.class);
    InputTransformer inputTransformer = mock(InputTransformer.class);
    MetacardImpl metacard = new MetacardImpl();
    metacard.setMetadata("Some Text Again");
    when(inputTransformer.transform(any())).thenReturn(metacard);
    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;
        }
    };
    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()));
    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);
    RESTEndpoint.CreateInfo createInfo = rest.parseAttachments(attachments, "xml");
    assertThat(createInfo.getMetacard().getMetadata(), equalTo("Some Text Again"));
    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);
    ContentDisposition contentDisposition3 = new ContentDisposition("form-data; name=foo; filename=C:\\DDF\\metacard.xml");
    Attachment attachment3 = new Attachment("foo", new ByteArrayInputStream("bar".getBytes()), contentDisposition3);
    attachments.add(attachment3);
    createInfo = rest.parseAttachments(attachments, "xml");
    assertThat(createInfo.getMetacard().getMetadata(), equalTo("<meta>beta</meta>"));
    assertThat(createInfo.getMetacard().getAttribute("foo"), equalTo(null));
}
Also used : 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) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) CatalogFramework(ddf.catalog.CatalogFramework) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 3 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition 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 4 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition 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 5 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition in project tesb-rt-se by Talend.

the class ThirdPartyRegistrationService method register.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/")
public ConsumerRegistration register(MultipartBody body) {
    String appName = body.getAttachmentObject("appName", String.class);
    String appURI = body.getAttachmentObject("appURI", String.class);
    String appRedirectURI = body.getAttachmentObject("appRedirectURI", String.class);
    String appDesc = body.getAttachmentObject("appDescription", String.class);
    URI logoURI = null;
    Attachment att = body.getAttachment("appLogo");
    if (att != null) {
        InputStream logoStream = att.getObject(InputStream.class);
        CachedOutputStream cos = new CachedOutputStream();
        try {
            IOUtils.copy(logoStream, cos);
            appLogos.put(appName.toLowerCase(), cos);
            UriBuilder ub = uriInfo.getAbsolutePathBuilder();
            ub.path("logo").path(appName.toLowerCase());
            ContentDisposition cd = att.getContentDisposition();
            if (cd != null && cd.getParameter("filename") != null) {
                ub.path(cd.getParameter("filename"));
            }
            logoURI = ub.build();
        } catch (IOException ex) {
        // ignore
        }
    }
    String clientId = generateClientId(appName, appURI);
    String clientSecret = generateClientSecret();
    Client newClient = new Client(clientId, clientSecret, true, appName, appURI);
    newClient.setApplicationDescription(appDesc);
    newClient.setApplicationLogoUri(logoURI.toString());
    newClient.setRedirectUris(Collections.singletonList(appRedirectURI));
    manager.registerClient(newClient);
    return new ConsumerRegistration(clientId, clientSecret);
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) InputStream(java.io.InputStream) ConsumerRegistration(oauth2.common.ConsumerRegistration) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) IOException(java.io.IOException) UriBuilder(javax.ws.rs.core.UriBuilder) Client(org.apache.cxf.rs.security.oauth2.common.Client) URI(java.net.URI) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Aggregations

ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)36 Attachment (org.apache.cxf.jaxrs.ext.multipart.Attachment)24 Test (org.junit.Test)17 MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)15 ByteArrayInputStream (java.io.ByteArrayInputStream)13 CatalogFramework (ddf.catalog.CatalogFramework)10 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 InputStream (java.io.InputStream)9 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)7 InputTransformer (ddf.catalog.transform.InputTransformer)7 BundleContext (org.osgi.framework.BundleContext)7 ServiceReference (org.osgi.framework.ServiceReference)7 Metacard (ddf.catalog.data.Metacard)6 URI (java.net.URI)6 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)6 CoreAttributes (ddf.catalog.data.impl.types.CoreAttributes)5 File (java.io.File)4 Response (javax.ws.rs.core.Response)4 WebClient (org.apache.cxf.jaxrs.client.WebClient)4