Search in sources :

Example 26 with Attachment

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

the class CatalogServiceImplTest method testAddDocumentWithAttributeOverrides.

@Test
@SuppressWarnings({ "unchecked" })
public void testAddDocumentWithAttributeOverrides() throws Exception {
    CatalogFramework framework = givenCatalogFramework();
    AttributeDescriptor descriptor = new AttributeDescriptorImpl("custom.attribute", true, true, false, false, BasicTypes.STRING_TYPE);
    HttpHeaders headers = createHeaders(Collections.singletonList(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);
    when(attributeRegistry.lookup("custom.attribute")).thenReturn(Optional.of(descriptor));
    CatalogServiceImpl catalogService = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry) {

        @Override
        protected BundleContext getBundleContext() {
            return bundleContext;
        }
    };
    UuidGenerator uuidGenerator = mock(UuidGenerator.class);
    when(uuidGenerator.generateUuid()).thenReturn(UUID.randomUUID().toString());
    catalogService.setUuidGenerator(uuidGenerator);
    addMatchingService(catalogService, Collections.singletonList(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 contentDisposition2 = new ContentDisposition("form-data; name=custom.attribute; ");
    Attachment attachment2 = new Attachment(descriptor.getName(), new ByteArrayInputStream("CustomValue".getBytes()), contentDisposition2);
    attachments.add(attachment2);
    MultipartBody multipartBody = new MultipartBody(attachments);
    String response = catalogService.addDocument(headers.getRequestHeader(HttpHeaders.CONTENT_TYPE), multipartBody, null, new ByteArrayInputStream("".getBytes()));
    LOGGER.debug(ToStringBuilder.reflectionToString(response));
    ArgumentCaptor<CreateStorageRequest> captor = ArgumentCaptor.forClass(CreateStorageRequest.class);
    verify(framework, times(1)).create(captor.capture());
    assertThat(captor.getValue().getContentItems().get(0).getMetacard().getMetacardType().getAttributeDescriptor(descriptor.getName()), equalTo(descriptor));
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) ArrayList(java.util.ArrayList) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) AttributeDescriptorImpl(ddf.catalog.data.impl.AttributeDescriptorImpl) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) 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) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) CatalogFramework(ddf.catalog.CatalogFramework) BundleContext(org.osgi.framework.BundleContext) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest) Test(org.junit.Test)

Example 27 with Attachment

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

the class CatalogServiceImplTest method testParseAttachmentsTooLarge.

@Test
@SuppressWarnings({ "unchecked" })
public void testParseAttachmentsTooLarge() throws IOException, CatalogTransformerException, SourceUnavailableException, IngestException, InvalidSyntaxException {
    CatalogFramework framework = givenCatalogFramework();
    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);
    CatalogServiceImpl catalogServiceImpl = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry) {

        @Override
        protected BundleContext getBundleContext() {
            return bundleContext;
        }
    };
    when(attributeRegistry.lookup(Core.METADATA)).thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.METADATA)));
    when(attributeRegistry.lookup("foo")).thenReturn(Optional.empty());
    addMatchingService(catalogServiceImpl, Collections.singletonList(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);
    Pair<AttachmentInfo, Metacard> attachmentInfoAndMetacard = catalogServiceImpl.parseAttachments(attachments, "xml");
    assertThat(attachmentInfoAndMetacard.getValue().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(Strings.repeat("hi", 100_000).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);
    attachmentInfoAndMetacard = catalogServiceImpl.parseAttachments(attachments, "xml");
    // Ensure that the metadata was not overriden because it was too large to be parsed
    assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("Some Text Again"));
    assertThat(attachmentInfoAndMetacard.getValue().getAttribute("foo"), equalTo(null));
}
Also used : CoreAttributes(ddf.catalog.data.impl.types.CoreAttributes) ArrayList(java.util.ArrayList) AttachmentInfo(org.codice.ddf.attachment.AttachmentInfo) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) InputTransformer(ddf.catalog.transform.InputTransformer) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) ServiceReference(org.osgi.framework.ServiceReference) Metacard(ddf.catalog.data.Metacard) 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 28 with Attachment

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

the class CatalogServiceImplTest method mcardIdTest.

private String mcardIdTest(Metacard metacard, UuidGenerator uuidGenerator) throws Exception {
    CatalogFramework framework = mock(CatalogFramework.class);
    when(framework.create(isA(CreateStorageRequest.class))).thenAnswer(args -> {
        ContentItem item = ((CreateStorageRequest) args.getArguments()[0]).getContentItems().get(0);
        item.getMetacard().setAttribute(new AttributeImpl(Core.ID, item.getId()));
        return new CreateResponseImpl(null, new HashMap<>(), Collections.singletonList(item.getMetacard()));
    });
    HttpHeaders headers = createHeaders(Collections.singletonList(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(metacard);
    when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer);
    serviceReferences.add(serviceReference);
    when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences);
    CatalogServiceImpl catalogService = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry) {

        @Override
        protected BundleContext getBundleContext() {
            return bundleContext;
        }
    };
    String generatedMcardId = UUID.randomUUID().toString();
    when(uuidGenerator.generateUuid()).thenReturn(generatedMcardId);
    catalogService.setUuidGenerator(uuidGenerator);
    when(attributeRegistry.lookup(Core.METADATA)).thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.METADATA)));
    addMatchingService(catalogService, Collections.singletonList(inputTransformer));
    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);
    MultipartBody multipartBody = new MultipartBody(attachments);
    return catalogService.addDocument(headers.getRequestHeader(HttpHeaders.CONTENT_TYPE), multipartBody, null, new ByteArrayInputStream("".getBytes()));
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) CoreAttributes(ddf.catalog.data.impl.types.CoreAttributes) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) InputTransformer(ddf.catalog.transform.InputTransformer) ServiceReference(org.osgi.framework.ServiceReference) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) CatalogFramework(ddf.catalog.CatalogFramework) ContentItem(ddf.catalog.content.data.ContentItem) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest) CreateResponseImpl(ddf.catalog.operation.impl.CreateResponseImpl) BundleContext(org.osgi.framework.BundleContext)

Example 29 with Attachment

use of org.apache.cxf.jaxrs.ext.multipart.Attachment in project meecrowave by apache.

the class ProxyServletTest method upload.

@Test
public void upload() {
    withClient(target -> {
        final Response response = target.path("/upload1").request().post(entity(new MultipartBody(asList(new Attachment("metadata", APPLICATION_JSON, "{\"content\":\"text\"}"), new Attachment("file", Thread.currentThread().getContextClassLoader().getResourceAsStream("ProxyServletTest/upload/file.txt"), new ContentDisposition("uploadded.txt")))), MULTIPART_FORM_DATA));
        assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
        final String actual = response.readEntity(String.class);
        assertTrue(actual, actual.contains("uuid:"));
        assertTrue(actual, actual.contains("Content-Type: application/json"));
        assertTrue(actual, actual.contains("{\"content\":\"text\"}"));
        assertTrue(actual, actual.contains("Content-Type: application/octet-stream"));
        assertTrue(actual, actual.contains("test\nfile\nwith\nmultiple\nlines"));
    });
}
Also used : Response(javax.ws.rs.core.Response) 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)

Example 30 with Attachment

use of org.apache.cxf.jaxrs.ext.multipart.Attachment in project cxf by apache.

the class MessageContextImpl method convertToAttachments.

private void convertToAttachments(Object value) {
    List<?> handlers = (List<?>) value;
    List<org.apache.cxf.message.Attachment> atts = new ArrayList<>();
    for (int i = 1; i < handlers.size(); i++) {
        Attachment handler = (Attachment) handlers.get(i);
        AttachmentImpl att = new AttachmentImpl(handler.getContentId(), handler.getDataHandler());
        for (String key : handler.getHeaders().keySet()) {
            att.setHeader(key, handler.getHeader(key));
        }
        att.setXOP(false);
        atts.add(att);
    }
    Message outMessage = getOutMessage();
    outMessage.setAttachments(atts);
    outMessage.put(AttachmentOutInterceptor.WRITE_ATTACHMENTS, "true");
    Attachment root = (Attachment) handlers.get(0);
    String rootContentType = root.getContentType().toString();
    MultivaluedMap<String, String> rootHeaders = new MetadataMap<>(root.getHeaders(), true, false, true);
    if (!AttachmentUtil.isMtomEnabled(outMessage)) {
        rootHeaders.putSingle(Message.CONTENT_TYPE, rootContentType);
    }
    String messageContentType = outMessage.get(Message.CONTENT_TYPE).toString();
    int index = messageContentType.indexOf(";type");
    if (index > 0) {
        messageContentType = messageContentType.substring(0, index).trim();
    }
    AttachmentOutputInterceptor attInterceptor = new AttachmentOutputInterceptor(messageContentType, rootHeaders);
    outMessage.put(Message.CONTENT_TYPE, rootContentType);
    Map<String, List<String>> allHeaders = CastUtils.cast((Map<?, ?>) outMessage.get(Message.PROTOCOL_HEADERS));
    if (allHeaders != null) {
        allHeaders.remove(Message.CONTENT_TYPE);
    }
    attInterceptor.handleMessage(outMessage);
}
Also used : Message(org.apache.cxf.message.Message) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) Endpoint(org.apache.cxf.endpoint.Endpoint) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) AttachmentOutputInterceptor(org.apache.cxf.jaxrs.interceptor.AttachmentOutputInterceptor) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) AttachmentImpl(org.apache.cxf.attachment.AttachmentImpl)

Aggregations

Attachment (org.apache.cxf.jaxrs.ext.multipart.Attachment)79 ArrayList (java.util.ArrayList)31 Test (org.junit.Test)29 InputStream (java.io.InputStream)25 ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)25 ByteArrayInputStream (java.io.ByteArrayInputStream)23 MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)23 Response (javax.ws.rs.core.Response)17 IOException (java.io.IOException)15 WebClient (org.apache.cxf.jaxrs.client.WebClient)15 CatalogFramework (ddf.catalog.CatalogFramework)10 LinkedHashMap (java.util.LinkedHashMap)9 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)9 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)8 PushbackInputStream (java.io.PushbackInputStream)8 POST (javax.ws.rs.POST)8 Path (javax.ws.rs.Path)8 Metacard (ddf.catalog.data.Metacard)7 InputTransformer (ddf.catalog.transform.InputTransformer)7 LinkedList (java.util.LinkedList)7