use of ddf.catalog.operation.impl.QueryResponseImpl in project ddf by codice.
the class SortedQueryMonitorTest method setUp.
@Before
public void setUp() throws Exception {
cachingFederationStrategy = mock(CachingFederationStrategy.class);
completionService = mock(CompletionService.class);
queryRequest = mock(QueryRequest.class);
queryResponse = new QueryResponseImpl(queryRequest);
query = mock(Query.class);
// Enforce insertion order for testing purposes
futures = new LinkedHashMap<>();
for (int i = 0; i < 4; i++) {
SourceResponse sourceResponseMock = null;
Future futureMock = mock(Future.class);
QueryRequest queryRequest = mock(QueryRequest.class);
when(queryRequest.getSourceIds()).thenReturn(Collections.singleton("Source-" + i));
switch(i) {
case 1:
sourceResponseMock = mock(SourceResponse.class);
when(sourceResponseMock.getResults()).thenReturn(Lists.newArrayList(mock(Result.class), mock(Result.class), mock(Result.class)));
when(sourceResponseMock.getHits()).thenReturn(3L);
break;
case 2:
sourceResponseMock = mock(SourceResponse.class);
when(sourceResponseMock.getResults()).thenReturn(Lists.newArrayList(mock(Result.class)));
when(sourceResponseMock.getHits()).thenReturn(1L);
break;
case 3:
sourceResponseMock = mock(SourceResponse.class);
when(sourceResponseMock.getResults()).thenReturn(Lists.<Result>emptyList());
when(sourceResponseMock.getHits()).thenReturn(0L);
break;
}
when(futureMock.get()).thenReturn(sourceResponseMock);
futures.put(futureMock, queryRequest);
}
}
use of ddf.catalog.operation.impl.QueryResponseImpl in project ddf by codice.
the class Jpeg2000ThumbnailConverterTest method testConversion.
@Test
public void testConversion() throws IOException, StopProcessingException, PluginExecutionException {
IIORegistry.getDefaultInstance().registerServiceProvider(jpeg2000ThumbnailConverter);
List<Result> resultList = new ArrayList<>();
Metacard metacard = new MetacardImpl();
byte[] j2kbytes = new byte[0];
resultList.add(new ResultImpl(metacard));
QueryResponseImpl queryResponse = new QueryResponseImpl(null, resultList, 1);
// there are two possible byte signatures, so test an example of each one
for (String image : new String[] { "/Bretagne2.j2k", "/Cevennes2.jp2" }) {
URL imageResource = Jpeg2000ThumbnailConverterTest.class.getResource(image);
if (imageResource == null) {
fail("The Image Resource came back null. Was the resources folder removed?");
}
String imageResourcePath = new File(imageResource.getFile()).getAbsolutePath();
j2kbytes = Files.readAllBytes(Paths.get(imageResourcePath));
metacard.setAttribute(new AttributeImpl(Metacard.THUMBNAIL, j2kbytes));
jpeg2000ThumbnailConverter.process(queryResponse);
// verify the plugin converted the j2k/jp2 image
assertTrue(!Arrays.equals(j2kbytes, metacard.getThumbnail()));
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(ImageIO.read(new ByteArrayInputStream(j2kbytes)), "gif", output);
metacard.setAttribute(new AttributeImpl(Metacard.THUMBNAIL, output.toByteArray()));
jpeg2000ThumbnailConverter.process(queryResponse);
// verify the plugin ignored the non-j2k
assertTrue(Arrays.equals(output.toByteArray(), metacard.getThumbnail()));
}
use of ddf.catalog.operation.impl.QueryResponseImpl in project ddf by codice.
the class QueryOperations method injectAttributes.
private QueryResponse injectAttributes(QueryResponse response) {
List<Result> results = response.getResults().stream().map(result -> {
Metacard original = result.getMetacard();
Metacard metacard = opsMetacardSupport.applyInjectors(original, frameworkProperties.getAttributeInjectors());
ResultImpl newResult = new ResultImpl(metacard);
newResult.setDistanceInMeters(result.getDistanceInMeters());
newResult.setRelevanceScore(result.getRelevanceScore());
return newResult;
}).collect(Collectors.toList());
QueryResponseImpl queryResponse = new QueryResponseImpl(response.getRequest(), results, true, response.getHits(), response.getProperties());
queryResponse.setProcessingDetails(response.getProcessingDetails());
return queryResponse;
}
use of ddf.catalog.operation.impl.QueryResponseImpl in project ddf by codice.
the class OpenSearchEndpoint method executeQuery.
/**
* Executes the OpenSearchQuery and formulates the response
*
* @param format - of the results in the response
* @param query - the query to execute
* @param ui -the ui information to use to format the results
* @param properties
* @return the response on the query
*/
private Response executeQuery(String format, OpenSearchQuery query, UriInfo ui, Map<String, Serializable> properties) {
Response response = null;
String queryFormat = format;
MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
List<String> subscriptionList = queryParams.get(Constants.SUBSCRIPTION_KEY);
LOGGER.debug("Attempting to execute query: {}", query.toString());
try {
Map<String, Serializable> arguments = new HashMap<String, Serializable>();
String organization = framework.getOrganization();
String url = ui.getRequestUri().toString();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("organization: {}", organization);
LOGGER.debug("url: {}", url);
}
arguments.put("organization", organization);
arguments.put("url", url);
// interval
if (subscriptionList != null && !subscriptionList.isEmpty()) {
String subscription = subscriptionList.get(0);
LOGGER.debug("Subscription: {}", subscription);
arguments.put(Constants.SUBSCRIPTION_KEY, subscription);
List<String> intervalList = queryParams.get(UPDATE_QUERY_INTERVAL);
if (intervalList != null && !intervalList.isEmpty()) {
arguments.put(UPDATE_QUERY_INTERVAL, intervalList.get(0));
}
}
if (StringUtils.isEmpty(queryFormat)) {
queryFormat = DEFAULT_FORMAT;
}
if (query.getFilter() != null) {
QueryRequest queryRequest = new QueryRequestImpl(query, query.isEnterprise(), query.getSiteIds(), properties);
QueryResponse queryResponse;
LOGGER.debug("Sending query");
queryResponse = framework.query(queryRequest);
// pass in the format for the transform
BinaryContent content = framework.transform(queryResponse, queryFormat, arguments);
response = Response.ok(content.getInputStream(), content.getMimeTypeValue()).build();
} else {
// No query was specified
QueryRequest queryRequest = new QueryRequestImpl(query, query.isEnterprise(), query.getSiteIds(), null);
// Create a dummy QueryResponse with zero results
QueryResponseImpl queryResponseQueue = new QueryResponseImpl(queryRequest, new ArrayList<Result>(), 0);
// pass in the format for the transform
BinaryContent content = framework.transform(queryResponseQueue, queryFormat, arguments);
if (null != content) {
response = Response.ok(content.getInputStream(), content.getMimeTypeValue()).build();
}
}
} catch (UnsupportedQueryException ce) {
LOGGER.info("Unsupported query", ce);
response = Response.status(Response.Status.BAD_REQUEST).entity(wrapStringInPreformattedTags("Unsupported query")).build();
} catch (CatalogTransformerException e) {
LOGGER.info("Error transforming response", e);
response = Response.serverError().entity(wrapStringInPreformattedTags("Error transforming response")).build();
} catch (FederationException e) {
LOGGER.info("Error executing query", e);
response = Response.serverError().entity(wrapStringInPreformattedTags("Error executing query")).build();
} catch (SourceUnavailableException e) {
LOGGER.info("Error executing query because the underlying source was unavailable.", e);
response = Response.serverError().entity(wrapStringInPreformattedTags("Error executing query because the underlying source was unavailable.")).build();
} catch (RuntimeException e) {
// Account for any runtime exceptions and send back a server error
// this prevents full stacktraces returning to the client
// this allows for a graceful server error to be returned
LOGGER.info("RuntimeException on executing query", e);
response = Response.serverError().entity(wrapStringInPreformattedTags("RuntimeException on executing query")).build();
}
return response;
}
use of ddf.catalog.operation.impl.QueryResponseImpl in project ddf by codice.
the class OpenSearchEndpointTest method testProcessQueryForProperHandlingOfSiteNameLOCAL.
/**
* Test method for
* {@link org.codice.ddf.endpoints.OpenSearchEndpoint#processQuery(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, javax.ws.rs.core.UriInfo, java.lang.String, java.lang.String)}
* .
* <p>
* This test will verify that the string "local" in the sources passed to
* OpenSearchEndpoint.processQuery is replaced with the local site name (in this case the mocked
* name "TestSiteName"). The QueryRequest object is checked when the framework.query is called
* to retrieve the OpenSearchQuery, which contains the Set of sites. An assertion within the
* Answer object for the call framework.query checks that the sites Set is contains the
* TEST_SITE_NAME.
*
* @throws URISyntaxException
* @throws FederationException
* @throws SourceUnavailableException
* @throws UnsupportedQueryException
* @throws UnsupportedEncodingException
* @throws CatalogTransformerException
*/
@SuppressWarnings("unchecked")
@Test
public void testProcessQueryForProperHandlingOfSiteNameLOCAL() throws URISyntaxException, UnsupportedQueryException, SourceUnavailableException, FederationException, UnsupportedEncodingException, CatalogTransformerException {
// ***Test setup***
final String testSiteName = "TestSiteName";
CatalogFramework mockFramework = mock(CatalogFramework.class);
FilterBuilder mockFilterBuilder = mock(FilterBuilder.class);
AttributeBuilder mockAB = mock(AttributeBuilder.class);
ExpressionBuilder mockEB = mock(ExpressionBuilder.class);
ContextualExpressionBuilder mockCEB = mock(ContextualExpressionBuilder.class);
Filter mockFilter = mock(Filter.class);
when(mockFilterBuilder.attribute(anyString())).thenReturn(mockAB);
when(mockAB.is()).thenReturn(mockEB);
when(mockEB.like()).thenReturn(mockCEB);
when(mockCEB.text(anyString())).thenReturn(mockFilter);
String searchTerms = "searchForThis";
// "local" MUST be included
String sources = "test, local";
String count = "200";
// dummy UriInfo, not really used functionally
UriInfo mockUriInfo = mock(UriInfo.class);
URI uri = new URI("test");
when(mockUriInfo.getRequestUri()).thenReturn(uri);
MultivaluedMap<String, String> mockMVMap = mock(MultivaluedMap.class);
when(mockMVMap.get("subscription")).thenReturn(null);
when(mockMVMap.get("interval")).thenReturn(null);
when(mockUriInfo.getQueryParameters()).thenReturn(mockMVMap);
@SuppressWarnings("unused") BinaryContent mockByteContent = mock(BinaryContent.class);
// Check on the sites passed in to framework.query
when(mockFramework.query(any(QueryRequest.class))).thenAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) {
QueryRequest queryRequest = (QueryRequest) invocation.getArguments()[0];
// ***Test verification***
// This assert is the whole point of this unit test
Assert.assertTrue(((OpenSearchQuery) queryRequest.getQuery()).getSiteIds().contains(testSiteName));
return new QueryResponseImpl(queryRequest);
}
});
// setup the BinaryContent for the call to Response.ok(...)
// This is just needed to get the method to complete, the
BinaryContent mockBinaryContent = mock(BinaryContent.class);
InputStream is = new ByteArrayInputStream("Test String From InputStream".getBytes("UTF-8"));
when(mockBinaryContent.getInputStream()).thenReturn(is);
when(mockBinaryContent.getMimeTypeValue()).thenReturn("text/plain");
when(mockFramework.transform(any(QueryResponse.class), anyString(), anyMap())).thenReturn(mockBinaryContent);
OpenSearchEndpoint osEndPoint = new OpenSearchEndpoint(mockFramework, mockFilterBuilder);
System.setProperty(SystemInfo.SITE_NAME, testSiteName);
// ***Test Execution***
osEndPoint.processQuery(searchTerms, null, sources, null, null, count, null, null, null, null, null, null, null, null, null, null, null, null, mockUriInfo, null, null, null);
}
Aggregations