Search in sources :

Example 11 with ContentDisposition

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

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

the class GetRecordsMessageBodyReader method handleContentDispositionHeader.

/**
 * Check Content-Disposition header for filename and return it
 *
 * @param httpHeaders The HTTP headers
 * @return the filename
 */
private String handleContentDispositionHeader(MultivaluedMap<String, String> httpHeaders) {
    String contentDispositionHeader = httpHeaders.getFirst(HttpHeaders.CONTENT_DISPOSITION);
    if (StringUtils.isNotBlank(contentDispositionHeader)) {
        ContentDisposition contentDisposition = new ContentDisposition(contentDispositionHeader);
        String filename = contentDisposition.getParameter("filename");
        if (StringUtils.isNotBlank(filename)) {
            LOGGER.debug("Found Content-Disposition header, changing resource name to {}", filename);
            return filename;
        }
    }
    return "";
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)

Example 13 with ContentDisposition

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

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

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method addAPIClientCertificate.

@Override
public Response addAPIClientCertificate(String apiId, InputStream certificateInputStream, Attachment certificateDetail, String alias, String tier, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        ContentDisposition contentDisposition = certificateDetail.getContentDisposition();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isEmpty(alias) || StringUtils.isEmpty(apiId)) {
            RestApiUtil.handleBadRequest("The alias and/ or apiId should not be empty", log);
        }
        if (StringUtils.isBlank(fileName)) {
            RestApiUtil.handleBadRequest("Certificate addition failed. Proper Certificate file should be provided", log);
        }
        // validate if api exists
        validateAPIExistence(apiId);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        api.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        String userName = RestApiCommonUtil.getLoggedInUsername();
        String base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
        int responseCode = apiProvider.addClientCertificate(userName, api.getId(), base64EncodedCert, alias, tier, organization);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Add certificate operation response code : %d", responseCode));
        }
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
            // Handle api product case.
            if (API_PRODUCT_TYPE.equals(api.getType())) {
                APIIdentifier apiIdentifier = api.getId();
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
                APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
                apiProduct.setOrganization(organization);
                apiProvider.updateAPIProduct(apiProduct);
            } else {
                apiProvider.updateAPI(api);
            }
            ClientCertMetadataDTO certificateDTO = new ClientCertMetadataDTO();
            certificateDTO.setAlias(alias);
            certificateDTO.setApiId(apiId);
            certificateDTO.setTier(tier);
            URI createdCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
            return Response.created(createdCertUri).entity(certificateDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Internal server error while adding the client certificate to " + "API " + apiId, log);
        } else if (ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceAlreadyExistsError("The alias '" + alias + "' already exists in the trust store.", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while adding the certificate to the API " + apiId + ". " + "Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("APIManagement exception while adding the certificate to the API " + apiId + " due to an internal " + "server error", e, log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("IOException while generating the encoded certificate for the API " + apiId, e, log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
    } catch (FaultGatewaysException e) {
        RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
    }
    return null;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Aggregations

ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)37 Attachment (org.apache.cxf.jaxrs.ext.multipart.Attachment)25 Test (org.junit.Test)18 MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)15 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ArrayList (java.util.ArrayList)11 CatalogFramework (ddf.catalog.CatalogFramework)10 IOException (java.io.IOException)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 Response (javax.ws.rs.core.Response)5 File (java.io.File)4 WebClient (org.apache.cxf.jaxrs.client.WebClient)4