Search in sources :

Example 61 with Attachment

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

the class CatalogServiceImplTest method testAddDocumentWithMetadataPositiveCase.

@Test
@SuppressWarnings({ "unchecked" })
public void testAddDocumentWithMetadataPositiveCase() throws Exception {
    CatalogFramework framework = givenCatalogFramework();
    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);
    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);
    when(attributeRegistry.lookup(Core.METADATA)).thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.METADATA)));
    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 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);
    String response = catalogService.addDocument(headers.getRequestHeader(HttpHeaders.CONTENT_TYPE), multipartBody, null, new ByteArrayInputStream("".getBytes()));
    LOGGER.debug(ToStringBuilder.reflectionToString(response));
    assertThat(response, equalTo(SAMPLE_ID));
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) 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) 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) Test(org.junit.Test)

Example 62 with Attachment

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

the class MessageContextImplTest method testAttachments.

@Test
public void testAttachments() throws IOException {
    final Message in = createMessage();
    final MessageContext mc = new MessageContextImpl(in);
    try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        final Message out = new MessageImpl();
        out.put(Message.CONTENT_TYPE, "image/png");
        out.setContent(OutputStream.class, output);
        out.setInterceptorChain(new PhaseInterceptorChain(Collections.emptySortedSet()));
        in.getExchange().setOutMessage(out);
        final Binding binding = in.getExchange().getEndpoint().getBinding();
        final Capture<Message> capture = Capture.newInstance();
        EasyMock.expect(binding.createMessage(EasyMock.capture(capture))).andAnswer(new IAnswer<Message>() {

            @Override
            public Message answer() throws Throwable {
                return capture.getValue();
            }
        }).anyTimes();
        final String id = UUID.randomUUID().toString();
        final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
        // Headers should be case-insensitive
        headers.add("Content-Id", id);
        mc.put(MultipartBody.OUTBOUND_MESSAGE_ATTACHMENTS, Collections.singletonList(new Attachment(headers, new byte[0])));
        output.flush();
        assertThat(new String(output.toByteArray()), containsString("Content-ID: <" + id + ">"));
    }
}
Also used : Binding(org.apache.cxf.binding.Binding) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) Message(org.apache.cxf.message.Message) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) IAnswer(org.easymock.IAnswer) MessageImpl(org.apache.cxf.message.MessageImpl) Test(org.junit.Test)

Example 63 with Attachment

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

the class JwsMultipartSignatureInFilter method filter.

@Override
public void filter(List<Attachment> atts) {
    if (atts.size() < 2) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    Attachment sigPart = atts.remove(atts.size() - 1);
    final String jwsSequence;
    try {
        jwsSequence = IOUtils.readStringFromStream(sigPart.getDataHandler().getInputStream());
    } catch (IOException ex) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    final String base64UrlEncodedHeaders;
    final String base64UrlEncodedSignature;
    if (!useJwsJsonSignatureFormat) {
        String[] parts = JoseUtils.getCompactParts(jwsSequence);
        if (parts.length != 3 || !parts[1].isEmpty()) {
            throw ExceptionUtils.toBadRequestException(null, null);
        }
        base64UrlEncodedHeaders = parts[0];
        base64UrlEncodedSignature = parts[2];
    } else {
        Map<String, Object> parts = reader.fromJson(jwsSequence);
        if (parts.size() != 2 || !parts.containsKey("protected") || !parts.containsKey("signature")) {
            throw ExceptionUtils.toBadRequestException(null, null);
        }
        base64UrlEncodedHeaders = (String) parts.get("protected");
        base64UrlEncodedSignature = (String) parts.get("signature");
    }
    JwsHeaders headers = new JwsHeaders(new JsonMapObjectReaderWriter().fromJson(JoseUtils.decodeToString(base64UrlEncodedHeaders)));
    JoseUtils.traceHeaders(headers);
    if (Boolean.FALSE != headers.getPayloadEncodingStatus()) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    final JwsSignatureVerifier theVerifier;
    if (verifier == null) {
        Properties props = KeyManagementUtils.loadStoreProperties(message, true, JoseConstants.RSSEC_SIGNATURE_IN_PROPS, JoseConstants.RSSEC_SIGNATURE_PROPS);
        theVerifier = JwsUtils.loadSignatureVerifier(message, props, headers);
    } else {
        theVerifier = verifier;
    }
    JwsVerificationSignature sig = theVerifier.createJwsVerificationSignature(headers);
    if (sig == null) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    byte[] signatureBytes = JoseUtils.decode(base64UrlEncodedSignature);
    byte[] headerBytesWithDot = StringUtils.toBytesASCII(base64UrlEncodedHeaders + '.');
    sig.update(headerBytesWithDot, 0, headerBytesWithDot.length);
    int attSize = atts.size();
    for (int i = 0; i < attSize; i++) {
        Attachment dataPart = atts.get(i);
        final InputStream dataPartStream;
        try {
            dataPartStream = dataPart.getDataHandler().getDataSource().getInputStream();
        } catch (IOException ex) {
            throw ExceptionUtils.toBadRequestException(ex, null);
        }
        boolean verifyOnLastRead = i == attSize - 1 ? true : false;
        JwsInputStream jwsStream = new JwsInputStream(dataPartStream, sig, signatureBytes, verifyOnLastRead);
        final InputStream newStream;
        if (bufferPayload) {
            CachedOutputStream cos = new CachedOutputStream();
            try {
                IOUtils.copy(jwsStream, cos);
                newStream = cos.getInputStream();
            } catch (Exception ex) {
                throw ExceptionUtils.toBadRequestException(ex, null);
            }
        } else {
            newStream = jwsStream;
        }
        Attachment newDataPart = new Attachment(newStream, dataPart.getHeaders());
        atts.set(i, newDataPart);
    }
}
Also used : JwsInputStream(org.apache.cxf.rs.security.jose.jws.JwsInputStream) InputStream(java.io.InputStream) JsonMapObjectReaderWriter(org.apache.cxf.jaxrs.json.basic.JsonMapObjectReaderWriter) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) IOException(java.io.IOException) Properties(java.util.Properties) IOException(java.io.IOException) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) JwsVerificationSignature(org.apache.cxf.rs.security.jose.jws.JwsVerificationSignature) JwsInputStream(org.apache.cxf.rs.security.jose.jws.JwsInputStream)

Example 64 with Attachment

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

the class MessageContextImpl method createAttachments.

private MultipartBody createAttachments(String propertyName) {
    Message inMessage = m.getExchange().getInMessage();
    boolean embeddedAttachment = inMessage.get("org.apache.cxf.multipart.embedded") != null;
    Object o = inMessage.get(propertyName);
    if (o != null) {
        return (MultipartBody) o;
    }
    if (embeddedAttachment) {
        inMessage = new MessageImpl();
        inMessage.setExchange(new ExchangeImpl());
        inMessage.put(AttachmentDeserializer.ATTACHMENT_DIRECTORY, m.getExchange().getInMessage().get(AttachmentDeserializer.ATTACHMENT_DIRECTORY));
        inMessage.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD, m.getExchange().getInMessage().get(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD));
        inMessage.put(AttachmentDeserializer.ATTACHMENT_MAX_SIZE, m.getExchange().getInMessage().get(AttachmentDeserializer.ATTACHMENT_MAX_SIZE));
        inMessage.put(AttachmentDeserializer.ATTACHMENT_MAX_HEADER_SIZE, m.getExchange().getInMessage().get(AttachmentDeserializer.ATTACHMENT_MAX_HEADER_SIZE));
        inMessage.setContent(InputStream.class, m.getExchange().getInMessage().get("org.apache.cxf.multipart.embedded.input"));
        inMessage.put(Message.CONTENT_TYPE, m.getExchange().getInMessage().get("org.apache.cxf.multipart.embedded.ctype").toString());
    }
    new AttachmentInputInterceptor().handleMessage(inMessage);
    List<Attachment> newAttachments = new LinkedList<>();
    try {
        Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) inMessage.get(AttachmentDeserializer.ATTACHMENT_PART_HEADERS));
        Attachment first = new Attachment(AttachmentUtil.createAttachment(inMessage.getContent(InputStream.class), headers), new ProvidersImpl(inMessage));
        newAttachments.add(first);
    } catch (IOException ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
    Collection<org.apache.cxf.message.Attachment> childAttachments = inMessage.getAttachments();
    if (childAttachments == null) {
        childAttachments = Collections.emptyList();
    }
    for (org.apache.cxf.message.Attachment a : childAttachments) {
        newAttachments.add(new Attachment(a, new ProvidersImpl(inMessage)));
    }
    MediaType mt = embeddedAttachment ? (MediaType) inMessage.get("org.apache.cxf.multipart.embedded.ctype") : getHttpHeaders().getMediaType();
    MultipartBody body = new MultipartBody(newAttachments, mt, false);
    inMessage.put(propertyName, body);
    return body;
}
Also used : Message(org.apache.cxf.message.Message) AttachmentInputInterceptor(org.apache.cxf.jaxrs.interceptor.AttachmentInputInterceptor) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) IOException(java.io.IOException) LinkedList(java.util.LinkedList) ProvidersImpl(org.apache.cxf.jaxrs.impl.ProvidersImpl) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) MediaType(javax.ws.rs.core.MediaType) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) MessageImpl(org.apache.cxf.message.MessageImpl) ExchangeImpl(org.apache.cxf.message.ExchangeImpl)

Example 65 with Attachment

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

the class ClientProxyImpl method handleMultipart.

protected List<Attachment> handleMultipart(MultivaluedMap<ParameterType, Parameter> map, OperationResourceInfo ori, Object[] params) {
    List<Parameter> fm = getParameters(map, ParameterType.REQUEST_BODY);
    List<Attachment> atts = new ArrayList<>(fm.size());
    fm.forEach(p -> {
        Multipart part = getMultipart(ori, p.getIndex());
        if (part != null) {
            Object partObject = params[p.getIndex()];
            if (partObject != null) {
                atts.add(new Attachment(part.value(), part.type(), partObject));
            }
        }
    });
    return atts;
}
Also used : Multipart(org.apache.cxf.jaxrs.ext.multipart.Multipart) ArrayList(java.util.ArrayList) Parameter(org.apache.cxf.jaxrs.model.Parameter) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment)

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