Search in sources :

Example 11 with InputTransformer

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

the class TestOpenSearchSource method testQueryBySearchPhraseContentTypeSetRss.

@Test
public void testQueryBySearchPhraseContentTypeSetRss() throws UnsupportedQueryException, URISyntaxException, IOException {
    WebClient client = mock(WebClient.class);
    Response clientResponse = mock(Response.class);
    when(client.get()).thenReturn(clientResponse);
    when(clientResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(clientResponse.getEntity()).thenReturn(getSampleRssStream());
    SecureCxfClientFactory factory = getMockFactory(client);
    OverriddenOpenSearchSource source = new OverriddenOpenSearchSource(FILTER_ADAPTER, encryptionService);
    InputTransformer inputTransformer = mock(InputTransformer.class);
    MetacardImpl generatedMetacard = new MetacardImpl();
    generatedMetacard.setMetadata(getSample());
    generatedMetacard.setId(SAMPLE_ID);
    generatedMetacard.setContentTypeName("myType");
    try {
        when(inputTransformer.transform(isA(InputStream.class))).thenReturn(generatedMetacard);
        when(inputTransformer.transform(isA(InputStream.class), isA(String.class))).thenReturn(generatedMetacard);
    } catch (IOException e) {
        fail();
    } catch (CatalogTransformerException e) {
        fail();
    }
    source.setInputTransformer(inputTransformer);
    source.setEndpointUrl("http://localhost:8181/services/catalog/query");
    source.init();
    source.setParameters(DEFAULT_PARAMETERS);
    source.factory = factory;
    Filter filter = filterBuilder.attribute(Metacard.METADATA).like().text(SAMPLE_SEARCH_PHRASE);
    SourceResponse response = source.query(new QueryRequestImpl(new QueryImpl(filter)));
    Assert.assertEquals(1, response.getHits());
    List<Result> results = response.getResults();
    Assert.assertTrue(results.size() == 1);
    Result result = results.get(0);
    Metacard metacard = result.getMetacard();
    Assert.assertNotNull(metacard);
    Assert.assertEquals("myType", metacard.getContentTypeName());
}
Also used : SourceResponse(ddf.catalog.operation.SourceResponse) SecureCxfClientFactory(org.codice.ddf.cxf.SecureCxfClientFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) InputTransformer(ddf.catalog.transform.InputTransformer) WebClient(org.apache.cxf.jaxrs.client.WebClient) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) Result(ddf.catalog.data.Result) Response(javax.ws.rs.core.Response) ResourceResponse(ddf.catalog.operation.ResourceResponse) SourceResponse(ddf.catalog.operation.SourceResponse) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Metacard(ddf.catalog.data.Metacard) Filter(org.opengis.filter.Filter) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) Test(org.junit.Test)

Example 12 with InputTransformer

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

the class TestOpenSearchSource method testQueryBySearchPhraseContentTypeSet.

@Test
public void testQueryBySearchPhraseContentTypeSet() throws UnsupportedQueryException, URISyntaxException, IOException {
    WebClient client = mock(WebClient.class);
    Response clientResponse = mock(Response.class);
    when(client.get()).thenReturn(clientResponse);
    when(clientResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(clientResponse.getEntity()).thenReturn(getSampleAtomStream());
    SecureCxfClientFactory factory = getMockFactory(client);
    OverriddenOpenSearchSource source = new OverriddenOpenSearchSource(FILTER_ADAPTER, encryptionService);
    InputTransformer inputTransformer = mock(InputTransformer.class);
    MetacardImpl generatedMetacard = new MetacardImpl();
    generatedMetacard.setMetadata(getSample());
    generatedMetacard.setId(SAMPLE_ID);
    generatedMetacard.setContentTypeName("myType");
    try {
        when(inputTransformer.transform(isA(InputStream.class))).thenReturn(generatedMetacard);
        when(inputTransformer.transform(isA(InputStream.class), isA(String.class))).thenReturn(generatedMetacard);
    } catch (IOException e) {
        fail();
    } catch (CatalogTransformerException e) {
        fail();
    }
    source.setInputTransformer(inputTransformer);
    source.setEndpointUrl("http://localhost:8181/services/catalog/query");
    source.init();
    source.setParameters(DEFAULT_PARAMETERS);
    source.factory = factory;
    Filter filter = filterBuilder.attribute(Metacard.METADATA).like().text(SAMPLE_SEARCH_PHRASE);
    SourceResponse response = source.query(new QueryRequestImpl(new QueryImpl(filter)));
    Assert.assertEquals(1, response.getHits());
    List<Result> results = response.getResults();
    Assert.assertTrue(results.size() == 1);
    Result result = results.get(0);
    Metacard metacard = result.getMetacard();
    Assert.assertNotNull(metacard);
    Assert.assertEquals("myType", metacard.getContentTypeName());
}
Also used : SourceResponse(ddf.catalog.operation.SourceResponse) SecureCxfClientFactory(org.codice.ddf.cxf.SecureCxfClientFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) InputTransformer(ddf.catalog.transform.InputTransformer) WebClient(org.apache.cxf.jaxrs.client.WebClient) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) Result(ddf.catalog.data.Result) Response(javax.ws.rs.core.Response) ResourceResponse(ddf.catalog.operation.ResourceResponse) SourceResponse(ddf.catalog.operation.SourceResponse) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Metacard(ddf.catalog.data.Metacard) Filter(org.opengis.filter.Filter) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) Test(org.junit.Test)

Example 13 with InputTransformer

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

the class CswSubscriptionEndpoint method getMetacards.

private List<Metacard> getMetacards(GetRecordsResponseType recordsResponse) throws CswException {
    try {
        InputTransformer transformer = inputTransformerManager.getTransformerBySchema(recordsResponse.getSearchResults().getRecordSchema());
        List<Metacard> metacards = new ArrayList<>();
        for (Object result : recordsResponse.getSearchResults().getAny()) {
            if (result instanceof Node) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                XMLUtils.transform((Node) result, new TransformerProperties(), new StreamResult(outputStream));
                InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
                metacards.add(transformer.transform(is));
            }
        }
        return metacards;
    } catch (IOException | CatalogTransformerException e) {
        String msg = "Could not parse SearchResults in getRecordsResponse";
        LOGGER.debug(msg, e);
        throw new CswException(msg, e);
    }
}
Also used : StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Node(org.w3c.dom.Node) TransformerProperties(org.codice.ddf.platform.util.TransformerProperties) ArrayList(java.util.ArrayList) CswException(org.codice.ddf.spatial.ogc.csw.catalog.common.CswException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InputTransformer(ddf.catalog.transform.InputTransformer) Metacard(ddf.catalog.data.Metacard) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 14 with InputTransformer

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

the class IntegrationTest method testInputAndOutput.

@Test
public void testInputAndOutput() throws CatalogTransformerException, IOException {
    Parser parser = new XmlParser();
    InputTransformer inputTransformer = new XmlInputTransformer(parser);
    MetacardMarshaller metacardMarshaller = new MetacardMarshallerImpl(parser, new PrintWriterProviderImpl());
    MetacardTransformer outputTransformer = new XmlMetacardTransformer(metacardMarshaller);
    InputStream input = getClass().getResourceAsStream("/extensibleMetacard.xml");
    Metacard metacard = inputTransformer.transform(input);
    LOGGER.info("Attributes: ");
    for (AttributeDescriptor descriptor : metacard.getMetacardType().getAttributeDescriptors()) {
        Attribute attribute = metacard.getAttribute(descriptor.getName());
        LOGGER.info("\t" + descriptor.getName() + ": " + ((attribute == null) ? attribute : attribute.getValue()));
    }
    BinaryContent output = outputTransformer.transform(metacard, mockArguments);
    String outputString = new String(output.getByteArray());
    // TODO test equivalence with XMLUnit.
    LOGGER.info(outputString);
}
Also used : XmlParser(org.codice.ddf.parser.xml.XmlParser) MetacardTransformer(ddf.catalog.transform.MetacardTransformer) XmlMetacardTransformer(ddf.catalog.transformer.xml.XmlMetacardTransformer) Attribute(ddf.catalog.data.Attribute) MetacardMarshaller(ddf.catalog.transformer.api.MetacardMarshaller) InputStream(java.io.InputStream) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) XmlMetacardTransformer(ddf.catalog.transformer.xml.XmlMetacardTransformer) XmlInputTransformer(ddf.catalog.transformer.xml.XmlInputTransformer) InputTransformer(ddf.catalog.transform.InputTransformer) BinaryContent(ddf.catalog.data.BinaryContent) Parser(org.codice.ddf.parser.Parser) XmlParser(org.codice.ddf.parser.xml.XmlParser) MetacardMarshallerImpl(ddf.catalog.transformer.xml.MetacardMarshallerImpl) Metacard(ddf.catalog.data.Metacard) PrintWriterProviderImpl(ddf.catalog.transformer.xml.PrintWriterProviderImpl) XmlInputTransformer(ddf.catalog.transformer.xml.XmlInputTransformer) Test(org.junit.Test)

Example 15 with InputTransformer

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

the class RESTEndpoint 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));
        } else {
            LOGGER.debug("Metacard had a null id");
        }
    } 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) ByteArrayInputStream(java.io.ByteArrayInputStream) 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

InputTransformer (ddf.catalog.transform.InputTransformer)29 InputStream (java.io.InputStream)23 Metacard (ddf.catalog.data.Metacard)17 CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)15 IOException (java.io.IOException)13 Test (org.junit.Test)12 ByteArrayInputStream (java.io.ByteArrayInputStream)11 ArrayList (java.util.ArrayList)8 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)7 MimeType (javax.activation.MimeType)7 MimeTypeToTransformerMapper (ddf.mime.MimeTypeToTransformerMapper)6 ServiceReference (org.osgi.framework.ServiceReference)5 Result (ddf.catalog.data.Result)4 Matchers.anyString (org.mockito.Matchers.anyString)4 BundleContext (org.osgi.framework.BundleContext)4 UnmarshallingContext (com.thoughtworks.xstream.converters.UnmarshallingContext)3 TreeUnmarshaller (com.thoughtworks.xstream.core.TreeUnmarshaller)3 HierarchicalStreamReader (com.thoughtworks.xstream.io.HierarchicalStreamReader)3 XppReader (com.thoughtworks.xstream.io.xml.XppReader)3 MockMemoryStorageProvider (ddf.catalog.content.impl.MockMemoryStorageProvider)3