use of ddf.catalog.data.BinaryContent in project ddf by codice.
the class CswRecordCollectionMessageBodyWriter method writeTo.
@Override
public void writeTo(CswRecordCollection recordCollection, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outStream) throws IOException, WebApplicationException {
final String mimeType = recordCollection.getMimeType();
LOGGER.debug("Attempting to transform RecordCollection with mime-type: {} & outputSchema: {}", mimeType, recordCollection.getOutputSchema());
QueryResponseTransformer transformer;
Map<String, Serializable> arguments = new HashMap<String, Serializable>();
if (StringUtils.isBlank(recordCollection.getOutputSchema()) && StringUtils.isNotBlank(mimeType) && !XML_MIME_TYPES.contains(mimeType)) {
transformer = transformerManager.getTransformerByMimeType(mimeType);
} else if (OCTET_STREAM_OUTPUT_SCHEMA.equals(recordCollection.getOutputSchema())) {
Resource resource = recordCollection.getResource();
httpHeaders.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(resource.getMimeType()));
httpHeaders.put(HttpHeaders.CONTENT_DISPOSITION, Arrays.asList(String.format("inline; filename=\"%s\"", resource.getName())));
// Custom HTTP header to represent that the product data will be returned in the response.
httpHeaders.put(CswConstants.PRODUCT_RETRIEVAL_HTTP_HEADER, Arrays.asList("true"));
// Accept-ranges header to represent that ranges in bytes are accepted.
httpHeaders.put(CswConstants.ACCEPT_RANGES_HEADER, Arrays.asList(CswConstants.BYTES));
ByteArrayInputStream in = new ByteArrayInputStream(resource.getByteArray());
IOUtils.copy(in, outStream);
return;
} else {
transformer = transformerManager.getTransformerBySchema(CswConstants.CSW_OUTPUT_SCHEMA);
if (recordCollection.getElementName() != null) {
arguments.put(CswConstants.ELEMENT_NAMES, recordCollection.getElementName().toArray());
}
arguments.put(CswConstants.OUTPUT_SCHEMA_PARAMETER, recordCollection.getOutputSchema());
arguments.put(CswConstants.ELEMENT_SET_TYPE, recordCollection.getElementSetType());
arguments.put(CswConstants.IS_BY_ID_QUERY, recordCollection.isById());
arguments.put(CswConstants.GET_RECORDS, recordCollection.getRequest());
arguments.put(CswConstants.RESULT_TYPE_PARAMETER, recordCollection.getResultType());
arguments.put(CswConstants.WRITE_NAMESPACES, false);
}
if (transformer == null) {
throw new WebApplicationException(new CatalogTransformerException("Unable to locate Transformer."));
}
BinaryContent content = null;
try {
content = transformer.transform(recordCollection.getSourceResponse(), arguments);
} catch (CatalogTransformerException e) {
throw new WebApplicationException(e);
}
if (content != null) {
try (InputStream inputStream = content.getInputStream()) {
IOUtils.copy(inputStream, outStream);
}
} else {
throw new WebApplicationException(new CatalogTransformerException("Transformer returned null."));
}
}
use of ddf.catalog.data.BinaryContent in project ddf by codice.
the class TestCswQueryResponseTransformer method testMarshalAcknowledgementWithFailedTransforms.
@Test
public void testMarshalAcknowledgementWithFailedTransforms() throws WebApplicationException, IOException, JAXBException, CatalogTransformerException {
GetRecordsType query = new GetRecordsType();
query.setResultType(ResultType.RESULTS);
query.setMaxRecords(BigInteger.valueOf(6));
query.setStartPosition(BigInteger.valueOf(0));
SourceResponse sourceResponse = createSourceResponse(query, 6);
Map<String, Serializable> args = new HashMap<>();
args.put(CswConstants.RESULT_TYPE_PARAMETER, ResultType.RESULTS);
args.put(CswConstants.GET_RECORDS, query);
PrintWriter printWriter = getSimplePrintWriter();
MetacardTransformer mockMetacardTransformer = mock(MetacardTransformer.class);
final AtomicLong atomicLong = new AtomicLong(0);
when(mockMetacardTransformer.transform(any(Metacard.class), anyMap())).then(invocationOnMock -> {
if (atomicLong.incrementAndGet() == 2) {
throw new CatalogTransformerException("");
}
Metacard metacard = (Metacard) invocationOnMock.getArguments()[0];
BinaryContentImpl bci = new BinaryContentImpl(IOUtils.toInputStream(metacard.getId() + ","), new MimeType("application/xml"));
return bci;
});
when(mockPrintWriterProvider.build((Class<Metacard>) notNull())).thenReturn(printWriter);
when(mockTransformerManager.getTransformerBySchema(anyString())).thenReturn(mockMetacardTransformer);
CswQueryResponseTransformer cswQueryResponseTransformer = new CswQueryResponseTransformer(mockTransformerManager, mockPrintWriterProvider);
cswQueryResponseTransformer.init();
BinaryContent content = cswQueryResponseTransformer.transform(sourceResponse, args);
cswQueryResponseTransformer.destroy();
String xml = new String(content.getByteArray());
assertThat(xml, containsString(CswQueryResponseTransformer.NUMBER_OF_RECORDS_MATCHED_ATTRIBUTE + " 6"));
assertThat(xml, containsString(CswQueryResponseTransformer.NUMBER_OF_RECORDS_RETURNED_ATTRIBUTE + " 5"));
assertThat(xml, containsString(CswQueryResponseTransformer.NEXT_RECORD_ATTRIBUTE + " 0"));
}
use of ddf.catalog.data.BinaryContent in project ddf by codice.
the class TestGmdTransformer method testMetacardTransform.
@Test
public void testMetacardTransform() throws IOException, CatalogTransformerException {
Metacard metacard = getTestMetacard();
Map<String, Serializable> args = new HashMap<>();
args.put(CswConstants.OMIT_XML_DECLARATION, false);
BinaryContent content = new GmdTransformer(gmdMetacardType).transform(metacard, args);
String xml = IOUtils.toString(content.getInputStream());
assertThat(xml, startsWith(XML_DECLARATION));
}
use of ddf.catalog.data.BinaryContent in project ddf by codice.
the class TestGmdTransformer method testMetacardTransformNullArgs.
@Test
public void testMetacardTransformNullArgs() throws IOException, CatalogTransformerException {
Metacard metacard = getTestMetacard();
BinaryContent content = new GmdTransformer(gmdMetacardType).transform(metacard, null);
String xml = IOUtils.toString(content.getInputStream());
assertThat(xml, startsWith(XML_DECLARATION));
}
use of ddf.catalog.data.BinaryContent in project ddf by codice.
the class XsltMetacardTransformer method transform.
@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException {
LOGGER.debug("Entering metacard xslt transform.");
Transformer transformer;
Map<String, Object> mergedMap = new HashMap<String, Object>(localMap);
if (arguments != null) {
mergedMap.putAll(arguments);
}
// adding metacard data not in document
mergedMap.put("id", getValueOrEmptyString(metacard.getId()));
mergedMap.put("siteName", getValueOrEmptyString(metacard.getSourceId()));
mergedMap.put("title", getValueOrEmptyString(metacard.getTitle()));
mergedMap.put("type", getValueOrEmptyString(metacard.getMetacardType()));
mergedMap.put("date", getValueOrEmptyString(metacard.getCreatedDate()));
mergedMap.put("product", getValueOrEmptyString(metacard.getResourceURI()));
mergedMap.put("thumbnail", getValueOrEmptyString(metacard.getThumbnail()));
mergedMap.put("geometry", getValueOrEmptyString(metacard.getLocation()));
ServiceReference[] refs = null;
try {
LOGGER.debug("Searching for other Metacard Transformers.");
// TODO INJECT THESE!!!
refs = context.getServiceReferences(MetacardTransformer.class.getName(), null);
} catch (InvalidSyntaxException e) {
// can't happen because filter is null
}
if (refs != null) {
List<String> serviceList = new ArrayList<String>();
LOGGER.debug("Found other Metacard transformers, adding them to a service reference list.");
for (ServiceReference ref : refs) {
if (ref != null) {
String title = null;
String shortName = (String) ref.getProperty(Constants.SERVICE_SHORTNAME);
if ((title = (String) ref.getProperty(Constants.SERVICE_TITLE)) == null) {
title = "View as " + shortName.toUpperCase();
}
String url = "/services/catalog/" + metacard.getId() + "?transform=" + shortName;
// define the services
serviceList.add(title);
serviceList.add(url);
}
}
mergedMap.put("services", serviceList);
} else {
LOGGER.debug("No other Metacard transformers were found.");
}
// TODO: maybe add updated, type, and uuid here?
// map.put("updated", fmt.print(result.getPostedDate().getTime()));
// map.put("type", card.getSingleType().getValue());
BinaryContent resultContent;
StreamResult resultOutput = null;
XMLReader xmlReader = null;
try {
XMLReader xmlParser = XMLReaderFactory.createXMLReader();
xmlParser.setFeature("http://xml.org/sax/features/external-general-entities", false);
xmlParser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
xmlParser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
xmlReader = new XMLFilterImpl(xmlParser);
} catch (SAXException e) {
LOGGER.debug(e.getMessage(), e);
}
Source source = new SAXSource(xmlReader, new InputSource(new StringReader(metacard.getMetadata())));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
resultOutput = new StreamResult(baos);
try {
transformer = templates.newTransformer();
} catch (TransformerConfigurationException tce) {
throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(), tce.getCause());
}
if (!mergedMap.isEmpty()) {
for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
LOGGER.debug("Adding parameter to transform {}:{}", entry.getKey(), entry.getValue());
transformer.setParameter(entry.getKey(), entry.getValue());
}
}
try {
transformer.transform(source, resultOutput);
byte[] bytes = baos.toByteArray();
IOUtils.closeQuietly(baos);
LOGGER.debug("Transform complete.");
resultContent = new XsltTransformedContent(bytes, mimeType);
} catch (TransformerException te) {
throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getMessage(), te.getCause());
} finally {
// TODO: if we ever start to reuse transformers, we should add this
// code back in
// transformer.reset();
}
return resultContent;
}
Aggregations