Search in sources :

Example 21 with MultipartBody

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

the class JAXRSUtils method processFormParam.

private static Object processFormParam(Message m, String key, Class<?> pClass, Type genericType, Annotation[] paramAnns, String defaultValue, boolean decode) {
    MessageContext mc = new MessageContextImpl(m);
    MediaType mt = mc.getHttpHeaders().getMediaType();
    @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = (MultivaluedMap<String, String>) m.get(FormUtils.FORM_PARAM_MAP);
    String enc = HttpUtils.getEncoding(mt, StandardCharsets.UTF_8.name());
    if (params == null) {
        params = new MetadataMap<>();
        m.put(FormUtils.FORM_PARAM_MAP, params);
        if (mt == null || mt.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
            InputStream entityStream = copyAndGetEntityStream(m);
            String body = FormUtils.readBody(entityStream, enc);
            // Do not decode unless the key is empty value, fe @FormParam("")
            FormUtils.populateMapFromStringOrHttpRequest(params, m, body, enc, StringUtils.isEmpty(key) && decode);
        } else {
            if ("multipart".equalsIgnoreCase(mt.getType()) && MediaType.MULTIPART_FORM_DATA_TYPE.isCompatible(mt)) {
                MultipartBody body = AttachmentUtils.getMultipartBody(mc);
                FormUtils.populateMapFromMultipart(params, body, m, decode);
            } else {
                org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message("WRONG_FORM_MEDIA_TYPE", BUNDLE, mt.toString());
                LOG.warning(errorMsg.toString());
                throw ExceptionUtils.toNotSupportedException(null, null);
            }
        }
    }
    if (decode && !MessageUtils.getContextualBoolean(m, FormUtils.FORM_PARAM_MAP_DECODED, false)) {
        List<String> values = params.get(key);
        if (values != null) {
            values = values.stream().map(value -> HttpUtils.urlDecode(value, enc)).collect(Collectors.toList());
            params.replace(key, values);
        }
    }
    if ("".equals(key)) {
        return InjectionUtils.handleBean(pClass, paramAnns, params, ParameterType.FORM, m, false);
    }
    List<String> results = params.get(key);
    return InjectionUtils.createParameterObject(results, pClass, genericType, paramAnns, defaultValue, false, ParameterType.FORM, m);
}
Also used : Message(org.apache.cxf.message.Message) ReaderInputStream(org.apache.cxf.io.ReaderInputStream) InputStream(java.io.InputStream) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) MediaType(javax.ws.rs.core.MediaType) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 22 with MultipartBody

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

the class CatalogServiceImplTest 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.
 */
@Test
@SuppressWarnings({ "unchecked" })
public void testGetMetacardAsXml() throws Exception {
    CatalogFramework framework = givenCatalogFramework();
    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())).thenReturn(content);
    CatalogServiceImpl catalogService = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry);
    // Add a MimeTypeToINputTransformer that the REST endpoint will call to create the metacard
    addMatchingService(catalogService, Collections.singletonList(getSimpleTransformer()));
    catalogService.setTikaMimeTypeResolver(new TikaMimeTypeResolver());
    FilterBuilder filterBuilder = new GeotoolsFilterBuilder();
    catalogService.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);
    BinaryContent binaryContent = catalogService.createMetacard(multipartBody, AbstractCatalogService.DEFAULT_METACARD_TRANSFORMER);
    InputStream responseEntity = binaryContent.getInputStream();
    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) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) BinaryContent(ddf.catalog.data.BinaryContent) Metacard(ddf.catalog.data.Metacard) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) 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) Test(org.junit.Test)

Example 23 with MultipartBody

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

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

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

the class MultipartProvider method convertToDataHandlers.

private List<Attachment> convertToDataHandlers(Object obj, Class<?> type, Type genericType, Annotation[] anns, MediaType mt) throws IOException {
    if (Map.class.isAssignableFrom(obj.getClass())) {
        Map<Object, Object> objects = CastUtils.cast((Map<?, ?>) obj);
        List<Attachment> handlers = new ArrayList<>(objects.size());
        int i = 0;
        for (Iterator<Map.Entry<Object, Object>> iter = objects.entrySet().iterator(); iter.hasNext(); ) {
            Map.Entry<Object, Object> entry = iter.next();
            Object value = entry.getValue();
            Attachment handler = createDataHandler(value, value.getClass(), new Annotation[] {}, entry.getKey().toString(), mt.toString(), i++);
            handlers.add(handler);
        }
        return handlers;
    }
    String rootMediaType = getRootMediaType(anns, mt);
    if (List.class.isAssignableFrom(obj.getClass())) {
        return getAttachments((List<?>) obj, rootMediaType);
    }
    if (MultipartBody.class.isAssignableFrom(type)) {
        List<Attachment> atts = ((MultipartBody) obj).getAllAttachments();
        // these attachments may have no DataHandlers, but objects only
        return getAttachments(atts, rootMediaType);
    }
    Attachment handler = createDataHandler(obj, genericType, anns, rootMediaType, mt.toString(), 1);
    return Collections.singletonList(handler);
}
Also used : MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Aggregations

MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)35 Attachment (org.apache.cxf.jaxrs.ext.multipart.Attachment)25 ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)15 Test (org.junit.Test)13 ArrayList (java.util.ArrayList)12 ByteArrayInputStream (java.io.ByteArrayInputStream)10 WebClient (org.apache.cxf.jaxrs.client.WebClient)7 CatalogFramework (ddf.catalog.CatalogFramework)6 InputStream (java.io.InputStream)6 IOException (java.io.IOException)5 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)5 Response (javax.ws.rs.core.Response)5 InputTransformer (ddf.catalog.transform.InputTransformer)4 LinkedHashMap (java.util.LinkedHashMap)4 HttpHeaders (javax.ws.rs.core.HttpHeaders)4 MediaType (javax.ws.rs.core.MediaType)4 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)4 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)3 Map (java.util.Map)3 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)3