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