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));
}
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 "";
}
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()));
}
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"));
});
}
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;
}
Aggregations