Search in sources :

Example 71 with BinaryContent

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."));
    }
}
Also used : Serializable(java.io.Serializable) WebApplicationException(javax.ws.rs.WebApplicationException) QueryResponseTransformer(ddf.catalog.transform.QueryResponseTransformer) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Resource(ddf.catalog.resource.Resource) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) BinaryContent(ddf.catalog.data.BinaryContent)

Example 72 with BinaryContent

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"));
}
Also used : Serializable(java.io.Serializable) MetacardTransformer(ddf.catalog.transform.MetacardTransformer) SourceResponse(ddf.catalog.operation.SourceResponse) HashMap(java.util.HashMap) GetRecordsType(net.opengis.cat.csw.v_2_0_2.GetRecordsType) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Matchers.containsString(org.hamcrest.Matchers.containsString) Matchers.anyString(org.mockito.Matchers.anyString) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) BinaryContent(ddf.catalog.data.BinaryContent) MimeType(javax.activation.MimeType) AtomicLong(java.util.concurrent.atomic.AtomicLong) Metacard(ddf.catalog.data.Metacard) PrintWriter(ddf.catalog.transformer.api.PrintWriter) Test(org.junit.Test)

Example 73 with BinaryContent

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));
}
Also used : Metacard(ddf.catalog.data.Metacard) Serializable(java.io.Serializable) HashMap(java.util.HashMap) BinaryContent(ddf.catalog.data.BinaryContent) Test(org.junit.Test)

Example 74 with BinaryContent

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));
}
Also used : Metacard(ddf.catalog.data.Metacard) BinaryContent(ddf.catalog.data.BinaryContent) Test(org.junit.Test)

Example 75 with BinaryContent

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;
}
Also used : InputSource(org.xml.sax.InputSource) Transformer(javax.xml.transform.Transformer) MetacardTransformer(ddf.catalog.transform.MetacardTransformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) BinaryContent(ddf.catalog.data.BinaryContent) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) SAXException(org.xml.sax.SAXException) XMLFilterImpl(org.xml.sax.helpers.XMLFilterImpl) StringReader(java.io.StringReader) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) XMLReader(org.xml.sax.XMLReader) TransformerException(javax.xml.transform.TransformerException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServiceReference(org.osgi.framework.ServiceReference) SAXSource(javax.xml.transform.sax.SAXSource) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Aggregations

BinaryContent (ddf.catalog.data.BinaryContent)112 Test (org.junit.Test)79 Metacard (ddf.catalog.data.Metacard)42 SourceResponse (ddf.catalog.operation.SourceResponse)41 HashMap (java.util.HashMap)30 MetacardTransformer (ddf.catalog.transform.MetacardTransformer)28 Map (java.util.Map)24 Result (ddf.catalog.data.Result)22 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)19 CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)19 Matchers.anyString (org.mockito.Matchers.anyString)18 Serializable (java.io.Serializable)17 ByteArrayInputStream (java.io.ByteArrayInputStream)15 Date (java.util.Date)12 LineString (ddf.geo.formatter.LineString)11 MultiLineString (ddf.geo.formatter.MultiLineString)11 File (java.io.File)11 BinaryContentImpl (ddf.catalog.data.impl.BinaryContentImpl)10 ResultImpl (ddf.catalog.data.impl.ResultImpl)10 IOException (java.io.IOException)10