Search in sources :

Example 86 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class AtomTransformer method transform.

@Override
public BinaryContent transform(SourceResponse sourceResponse, Map<String, Serializable> arguments) throws CatalogTransformerException {
    if (sourceResponse == null) {
        throw new CatalogTransformerException("Cannot transform null " + SourceResponse.class.getName());
    }
    final Date currentDate = new Date();
    final Feed feed = createFeed();
    /*
     * Atom spec text (rfc4287) Sect 4.2.14: "The "atom:title" element is a Text construct that
     * conveys a human- readable title for an entry or feed."
     */
    feed.setTitle(DEFAULT_FEED_TITLE);
    feed.setUpdated(currentDate);
    // TODO Use the same id for the same query
    // one challenge is a query in one site should not have the same feed id
    // as a query in another site probably could factor in ddf.host and port
    // into the algorithm
    feed.setId(URN_UUID + UUID.randomUUID().toString());
    // TODO SELF LINK For the Feed, possible design --> serialize Query into
    // a URL
    /*
     * Atom spec text (rfc4287): "atom:feed elements SHOULD contain one atom:link element with a
     * rel attribute value of self. This is the preferred URI for retrieving Atom Feed Documents
     * representing this Atom feed. "
     */
    feed.addLink("#", Link.REL_SELF);
    if (!StringUtils.isEmpty(SystemInfo.getOrganization())) {
        feed.addAuthor(SystemInfo.getOrganization());
    } else {
        feed.addAuthor(DEFAULT_AUTHOR);
    }
    /*
     * Atom spec text (rfc4287 sect. 4.2.4): "The "atom:generator" element's content identifies
     * the agent used to generate a feed, for debugging and other purposes." Generator is not
     * required in the atom:feed element.
     */
    if (!StringUtils.isEmpty(SystemInfo.getSiteName())) {
        // text is required.
        feed.setGenerator(null, SystemInfo.getVersion(), SystemInfo.getSiteName());
    }
    /*
     * According to http://www.opensearch.org/Specifications/OpenSearch/1.1 specification,
     * totalResults must be a non-negative integer. Requirements: This attribute is optional.
     */
    if (sourceResponse.getHits() > -1) {
        Element hits = feed.addExtension(OpenSearchConstants.TOTAL_RESULTS);
        hits.setText(Long.toString(sourceResponse.getHits()));
    }
    if (sourceResponse.getRequest() != null && sourceResponse.getRequest().getQuery() != null) {
        Element itemsPerPage = feed.addExtension(OpenSearchConstants.ITEMS_PER_PAGE);
        Element startIndex = feed.addExtension(OpenSearchConstants.START_INDEX);
        /*
       * According to http://www.opensearch.org/Specifications/OpenSearch/1.1 specification,
       * itemsPerPage must be a non-negative integer. It is possible that Catalog pageSize is
       * set to a non-negative integer though. When non-negative we will instead we will
       * change it to the number of search results on current page.
       */
        if (sourceResponse.getRequest().getQuery().getPageSize() > -1) {
            itemsPerPage.setText(Integer.toString(sourceResponse.getRequest().getQuery().getPageSize()));
        } else {
            if (sourceResponse.getResults() != null) {
                itemsPerPage.setText(Integer.toString(sourceResponse.getResults().size()));
            }
        }
        startIndex.setText(Integer.toString(sourceResponse.getRequest().getQuery().getStartIndex()));
    }
    if (getCount(sourceResponse) != 0) {
        sourceResponse.getResults().stream().forEach(r -> addSingleResult(currentDate, feed, r));
    }
    byte[] bytes = createOutputStream(feed);
    return new BinaryContentImpl(new ByteArrayInputStream(bytes), MIME_TYPE);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) Element(org.apache.abdera.model.Element) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) Date(java.util.Date) Feed(org.apache.abdera.model.Feed)

Example 87 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException 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 = XML_UTILS.getSecureXmlParser();
        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)

Example 88 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class GeometryTransformer method transform.

public BinaryContent transform(Attribute attribute) throws CatalogTransformerException {
    ParserConfigurator parserConfigurator = getParserConfigurator().setHandler(new XmlValidationEventHandler());
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream(BUFFER_SIZE);
        getParser().marshal(parserConfigurator, GeometryAdapter.marshalFrom(attribute), os);
        ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());
        return new BinaryContentImpl(bais, MIME_TYPE);
    } catch (ParserException e) {
        throw new CatalogTransformerException("Failed to marshall geometry data", e);
    }
}
Also used : ParserConfigurator(org.codice.ddf.parser.ParserConfigurator) ParserException(org.codice.ddf.parser.ParserException) ByteArrayInputStream(java.io.ByteArrayInputStream) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl)

Example 89 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class CatalogFrameworkImplTest method testMetacardTransformWithTransformException.

@Test(expected = CatalogTransformerException.class)
public void testMetacardTransformWithTransformException() throws Exception {
    BundleContext context = mock(BundleContext.class);
    MetacardTransformer transformer = mock(MetacardTransformer.class);
    ServiceReference reference = mock(ServiceReference.class);
    ServiceReference[] serviceReferences = new ServiceReference[] { reference };
    when(context.getServiceReferences(anyString(), anyString())).thenReturn(serviceReferences);
    when(context.getService(isA(ServiceReference.class))).thenReturn(transformer);
    when(transformer.transform(isA(Metacard.class), isA(Map.class))).thenThrow(new CatalogTransformerException("Could not transform"));
    CatalogFramework framework = this.createDummyCatalogFramework(provider, storageProvider, context, eventAdmin, true);
    MetacardImpl newCard = new MetacardImpl();
    newCard.setId(null);
    framework.transform(newCard, "NONE", new HashMap<String, Serializable>());
}
Also used : Metacard(ddf.catalog.data.Metacard) Serializable(java.io.Serializable) MetacardTransformer(ddf.catalog.transform.MetacardTransformer) CatalogFramework(ddf.catalog.CatalogFramework) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Map(java.util.Map) ArgumentMatchers.anyMap(org.mockito.ArgumentMatchers.anyMap) HashMap(java.util.HashMap) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 90 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class AbstractCatalogService method generateMetacard.

private Metacard generateMetacard(MimeType mimeType, String id, InputStream message, String transformerId) throws MetacardCreationException {
    Metacard generatedMetacard = null;
    List<InputTransformer> listOfCandidates = mimeTypeToTransformerMapper.findMatches(InputTransformer.class, mimeType);
    List<String> stackTraceList = new ArrayList<>();
    LOGGER.trace("Entering generateMetacard.");
    LOGGER.debug("List of matches for mimeType [{}]: {}", mimeType, listOfCandidates);
    try (TemporaryFileBackedOutputStream fileBackedOutputStream = new TemporaryFileBackedOutputStream()) {
        try {
            if (null != message) {
                IOUtils.copy(message, fileBackedOutputStream);
            } else {
                throw new MetacardCreationException("Could not copy bytes of content message.  Message was NULL.");
            }
        } catch (IOException e) {
            throw new MetacardCreationException("Could not copy bytes of content message.", e);
        }
        Iterator<InputTransformer> it = listOfCandidates.iterator();
        if (StringUtils.isNotEmpty(transformerId)) {
            BundleContext bundleContext = getBundleContext();
            Collection<ServiceReference<InputTransformer>> serviceReferences = bundleContext.getServiceReferences(InputTransformer.class, "(id=" + transformerId + ")");
            it = serviceReferences.stream().map(bundleContext::getService).iterator();
        }
        while (it.hasNext()) {
            InputTransformer transformer = it.next();
            try (InputStream inputStreamMessageCopy = fileBackedOutputStream.asByteSource().openStream()) {
                generatedMetacard = transformer.transform(inputStreamMessageCopy);
            } catch (CatalogTransformerException | IOException e) {
                List<String> stackTraces = Arrays.asList(ExceptionUtils.getRootCauseStackTrace(e));
                stackTraceList.add(String.format("Transformer [%s] could not create metacard.", transformer));
                stackTraceList.addAll(stackTraces);
                LOGGER.debug("Transformer [{}] could not create metacard.", transformer, e);
            }
            if (generatedMetacard != null) {
                break;
            }
        }
        if (generatedMetacard == null) {
            throw new MetacardCreationException(String.format("Could not create metacard with mimeType %s : %s", mimeType, StringUtils.join(stackTraceList, "\n")));
        }
        if (id != null) {
            generatedMetacard.setAttribute(new AttributeImpl(Metacard.ID, id));
        }
        LOGGER.debug("Metacard id is {}", generatedMetacard.getId());
    } catch (IOException e) {
        throw new MetacardCreationException("Could not create metacard.", e);
    } catch (InvalidSyntaxException e) {
        throw new MetacardCreationException("Could not determine transformer", e);
    }
    return generatedMetacard;
}
Also used : MetacardCreationException(ddf.catalog.data.MetacardCreationException) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) BoundedInputStream(org.apache.commons.io.input.BoundedInputStream) InputStream(java.io.InputStream) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) ArrayList(java.util.ArrayList) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) InputTransformer(ddf.catalog.transform.InputTransformer) ServiceReference(org.osgi.framework.ServiceReference) Metacard(ddf.catalog.data.Metacard) ArrayList(java.util.ArrayList) List(java.util.List) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) BundleContext(org.osgi.framework.BundleContext)

Aggregations

CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)112 IOException (java.io.IOException)53 Metacard (ddf.catalog.data.Metacard)44 InputStream (java.io.InputStream)40 ByteArrayInputStream (java.io.ByteArrayInputStream)29 BinaryContent (ddf.catalog.data.BinaryContent)25 InputTransformer (ddf.catalog.transform.InputTransformer)21 Serializable (java.io.Serializable)21 HashMap (java.util.HashMap)21 Result (ddf.catalog.data.Result)16 BinaryContentImpl (ddf.catalog.data.impl.BinaryContentImpl)15 TemporaryFileBackedOutputStream (org.codice.ddf.platform.util.TemporaryFileBackedOutputStream)14 ArrayList (java.util.ArrayList)13 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)12 Test (org.junit.Test)12 AttributeImpl (ddf.catalog.data.impl.AttributeImpl)10 MimeType (javax.activation.MimeType)10 SourceResponse (ddf.catalog.operation.SourceResponse)9 MetacardTransformer (ddf.catalog.transform.MetacardTransformer)8 List (java.util.List)8