Search in sources :

Example 26 with ContentDisposition

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

the class CatalogServiceImplTest method testParseAttachments.

@Test
@SuppressWarnings({ "unchecked" })
public void testParseAttachments() 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("<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);
    attachmentInfoAndMetacard = catalogServiceImpl.parseAttachments(attachments, "xml");
    assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("<meta>beta</meta>"));
    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 27 with ContentDisposition

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

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

the class ApisApiServiceImpl method updateAPIClientCertificateByAlias.

@Override
public Response updateAPIClientCertificateByAlias(String alias, String apiId, InputStream certificateInputStream, Attachment certificateDetail, String tier, MessageContext messageContext) {
    try {
        // validate if api exists
        validateAPIExistence(apiId);
        ContentDisposition contentDisposition;
        String fileName;
        String base64EncodedCert = null;
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        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();
        int tenantId = APIUtil.getInternalOrganizationId(organization);
        ClientCertificateDTO clientCertificateDTO = CertificateRestApiUtils.preValidateClientCertificate(alias, api.getId(), organization);
        if (certificateDetail != null) {
            contentDisposition = certificateDetail.getContentDisposition();
            fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
            if (StringUtils.isNotBlank(fileName)) {
                base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
            }
        }
        if (StringUtils.isEmpty(base64EncodedCert) && StringUtils.isEmpty(tier)) {
            return Response.ok().entity("Client Certificate is not updated for alias " + alias).build();
        }
        int responseCode = apiProvider.updateClientCertificate(base64EncodedCert, alias, clientCertificateDTO.getApiIdentifier(), tier, tenantId, organization);
        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 clientCertMetadataDTO = new ClientCertMetadataDTO();
            clientCertMetadataDTO.setAlias(alias);
            clientCertMetadataDTO.setApiId(api.getUUID());
            clientCertMetadataDTO.setTier(clientCertificateDTO.getTierName());
            URI updatedCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
            return Response.ok(updatedCertUri).entity(clientCertMetadataDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Error while updating the client certificate for the alias " + alias + " due to an internal " + "server error", log);
        } else if (ResponseCode.CERTIFICATE_NOT_FOUND.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceNotFoundError("", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while updating the client certificate for the alias " + alias + " Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while updating the client certificate for the alias " + alias + " due to an internal " + "server error", e, log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error while encoding client certificate for the alias " + alias, 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) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 29 with ContentDisposition

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

the class RestApiPublisherUtils method attachFileToDocument.

/**
 * Attaches a file to the specified document
 *
 * @param apiId         identifier of the API, the document belongs to
 * @param documentation Documentation object
 * @param inputStream   input Stream containing the file
 * @param fileDetails   file details object as cxf Attachment
 * @param organization  identifier of an organization
 * @throws APIManagementException if unable to add the file
 */
public static void attachFileToDocument(String apiId, Documentation documentation, InputStream inputStream, Attachment fileDetails, String organization) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String documentId = documentation.getId();
    String randomFolderName = RandomStringUtils.randomAlphanumeric(10);
    String tmpFolder = System.getProperty(RestApiConstants.JAVA_IO_TMPDIR) + File.separator + RestApiConstants.DOC_UPLOAD_TMPDIR + File.separator + randomFolderName;
    File docFile = new File(tmpFolder);
    boolean folderCreated = docFile.mkdirs();
    if (!folderCreated) {
        RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, log);
    }
    InputStream docInputStream = null;
    try {
        ContentDisposition contentDisposition = fileDetails.getContentDisposition();
        String filename = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isBlank(filename)) {
            filename = RestApiConstants.DOC_NAME_DEFAULT + randomFolderName;
            log.warn("Couldn't find the name of the uploaded file for the document " + documentId + ". Using name '" + filename + "'");
        }
        // APIIdentifier apiIdentifier = APIMappingUtil
        // .getAPIIdentifierFromUUID(apiId, tenantDomain);
        RestApiUtil.transferFile(inputStream, filename, docFile.getAbsolutePath());
        docInputStream = new FileInputStream(docFile.getAbsolutePath() + File.separator + filename);
        String mediaType = fileDetails.getHeader(RestApiConstants.HEADER_CONTENT_TYPE);
        mediaType = mediaType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : mediaType;
        PublisherCommonUtils.addDocumentationContentForFile(docInputStream, mediaType, filename, apiProvider, apiId, documentId, organization);
        docFile.deleteOnExit();
    } catch (FileNotFoundException e) {
        RestApiUtil.handleInternalServerError("Unable to read the file from path ", e, log);
    } finally {
        IOUtils.closeQuietly(docInputStream);
    }
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 30 with ContentDisposition

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

the class EndpointCertificatesApiServiceImpl method addEndpointCertificate.

public Response addEndpointCertificate(InputStream certificateInputStream, Attachment certificateDetail, String alias, String endpoint, MessageContext messageContext) {
    try {
        if (StringUtils.isEmpty(alias) || StringUtils.isEmpty(endpoint)) {
            RestApiUtil.handleBadRequest("The alias and/ or endpoint should not be empty", log);
        }
        ContentDisposition contentDisposition = certificateDetail.getContentDisposition();
        String fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isBlank(fileName)) {
            RestApiUtil.handleBadRequest("Certificate update failed. Proper Certificate file should be provided", log);
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String userName = RestApiCommonUtil.getLoggedInUsername();
        String base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
        int responseCode = apiProvider.addCertificate(userName, base64EncodedCert, alias, endpoint);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Add certificate operation response code : %d", responseCode));
        }
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
            CertMetadataDTO certificateDTO = new CertMetadataDTO();
            certificateDTO.setEndpoint(endpoint);
            certificateDTO.setAlias(alias);
            URI createdCertUri = new URI(RestApiConstants.CERTS_BASE_PATH + "?alias=" + alias);
            return Response.created(createdCertUri).entity(certificateDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Error while adding the certificate due to an" + " internal server error", 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. Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while adding the certificate due to an internal server " + "error", log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error while generating the encoded certificate", log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", log);
    }
    return null;
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) CertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.CertMetadataDTO) URI(java.net.URI)

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