use of ddf.catalog.transform.InputTransformer in project ddf by codice.
the class OpenSearchSource method query.
@Override
public SourceResponse query(QueryRequest queryRequest) throws UnsupportedQueryException {
String methodName = "query";
LOGGER.trace(methodName);
Serializable metacardId = queryRequest.getPropertyValue(Metacard.ID);
SourceResponseImpl response = null;
Subject subject = null;
WebClient restWebClient = null;
if (queryRequest.hasProperties()) {
Object subjectObj = queryRequest.getProperties().get(SecurityConstants.SECURITY_SUBJECT);
subject = (Subject) subjectObj;
}
restWebClient = factory.getWebClientForSubject(subject);
Query query = queryRequest.getQuery();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Received query: " + query);
}
boolean canDoOpenSearch = setOpenSearchParameters(query, subject, restWebClient);
if (canDoOpenSearch) {
InputStream responseStream = performRequest(restWebClient);
response = new SourceResponseImpl(queryRequest, new ArrayList<Result>());
if (responseStream != null) {
response = processResponse(responseStream, queryRequest);
}
} else {
if (StringUtils.isEmpty((String) metacardId)) {
OpenSearchFilterVisitor visitor = new OpenSearchFilterVisitor();
query.accept(visitor, null);
metacardId = visitor.getMetacardId();
}
restWebClient = newRestClient(query, (String) metacardId, false, subject);
if (restWebClient != null) {
InputStream responseStream = performRequest(restWebClient);
Metacard metacard = null;
List<Result> resultQueue = new ArrayList<Result>();
try (TemporaryFileBackedOutputStream fileBackedOutputStream = new TemporaryFileBackedOutputStream()) {
if (responseStream != null) {
IOUtils.copyLarge(responseStream, fileBackedOutputStream);
InputTransformer inputTransformer = null;
try (InputStream inputStream = fileBackedOutputStream.asByteSource().openStream()) {
inputTransformer = getInputTransformer(inputStream);
} catch (IOException e) {
LOGGER.debug("Problem with transformation.", e);
}
if (inputTransformer != null) {
try (InputStream inputStream = fileBackedOutputStream.asByteSource().openStream()) {
metacard = inputTransformer.transform(inputStream);
} catch (IOException e) {
LOGGER.debug("Problem with transformation.", e);
}
}
}
} catch (IOException | CatalogTransformerException e) {
LOGGER.debug("Problem with transformation.", e);
}
if (metacard != null) {
metacard.setSourceId(getId());
ResultImpl result = new ResultImpl(metacard);
resultQueue.add(result);
response = new SourceResponseImpl(queryRequest, resultQueue);
response.setHits(resultQueue.size());
}
}
}
LOGGER.trace(methodName);
return response;
}
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());
}
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());
}
use of ddf.catalog.transform.InputTransformer in project ddf by codice.
the class TestCswTransformProvider method testUnmarshalOtherSchema.
@Test
public void testUnmarshalOtherSchema() throws Exception {
InputTransformer mockInputTransformer = mock(InputTransformer.class);
when(mockInputManager.getTransformerByProperty(TransformerManager.SCHEMA, OTHER_SCHEMA)).thenReturn(mockInputTransformer);
when(mockInputTransformer.transform(any(InputStream.class))).thenReturn(getMetacard());
// XppReader is not namespace aware so it will read the XML and ignore the namespaces
// WstxReader is namespace aware. It may fail for XML fragments.
HierarchicalStreamReader reader = new XppReader(new StringReader(getRecord()), XmlPullParserFactory.newInstance().newPullParser());
CswTransformProvider provider = new CswTransformProvider(null, mockInputManager);
UnmarshallingContext context = new TreeUnmarshaller(null, null, null, null);
context.put(CswConstants.TRANSFORMER_LOOKUP_KEY, TransformerManager.SCHEMA);
context.put(CswConstants.TRANSFORMER_LOOKUP_VALUE, OTHER_SCHEMA);
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
provider.unmarshal(reader, context);
// Verify the context arguments were set correctly
verify(mockInputManager, times(1)).getTransformerByProperty(captor.capture(), captor.capture());
String outputSchema = captor.getValue();
assertThat(outputSchema, is(OTHER_SCHEMA));
}
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;
}
Aggregations