use of ddf.catalog.data.BinaryContent 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.data.BinaryContent 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);
}
use of ddf.catalog.data.BinaryContent in project ddf by codice.
the class CswTransformProvider method marshal.
/**
* Marshals Metacards to an xml. This method is not typically be called directly, instead it is
* called by another XStream Converter using MarshallingContext.convertAnother();
*
* @param o - metacard to transform.
* @param writer - writes the XML.
* @param context - the marshalling context. Should contain a map entry for {@link
* org.codice.ddf.spatial.ogc.csw.catalog.common.CswConstants#TRANSFORMER_LOOKUP_KEY}
* {@link org.codice.ddf.spatial.ogc.csw.catalog.common.CswConstants#TRANSFORMER_LOOKUP_VALUE}
* to identify which transformer to use. Also contains properties for any
* arguments to provide the transformer.
*/
@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext context) {
if (o == null) {
return;
}
Metacard metacard = (Metacard) o;
String keyArg = (String) context.get(CswConstants.TRANSFORMER_LOOKUP_KEY);
String valArg = (String) context.get(CswConstants.TRANSFORMER_LOOKUP_VALUE);
MetacardTransformer transformer;
if (StringUtils.isNotBlank(keyArg) && StringUtils.isNotBlank(valArg)) {
transformer = metacardTransformerManager.getTransformerByProperty(keyArg, valArg);
} else {
transformer = metacardTransformerManager.getTransformerBySchema(CswConstants.CSW_OUTPUT_SCHEMA);
}
if (transformer == null) {
throw new ConversionException(String.format("Unable to locate a transformer for %s = %s", keyArg, valArg));
}
BinaryContent content;
try {
content = transformer.transform(metacard, getArguments(context));
} catch (CatalogTransformerException e) {
throw new ConversionException("Unable to transform Metacard", e);
}
writeXml(content, writer);
}
use of ddf.catalog.data.BinaryContent in project ddf by codice.
the class TestKMLTransformerImpl method testTransformMetacardGetsDefaultStyle.
@Test
public void testTransformMetacardGetsDefaultStyle() throws CatalogTransformerException, IOException {
MetacardImpl metacard = createMockMetacard();
metacard.setLocation(POINT_WKT);
BinaryContent content = kmlTransformer.transform(metacard, null);
assertThat(content.getMimeTypeValue(), is(KMLTransformerImpl.KML_MIMETYPE.toString()));
IOUtils.toString(content.getInputStream());
}
use of ddf.catalog.data.BinaryContent in project ddf by codice.
the class TestGeoJsonMetacardTransformer method testWithMultiPolygonGeo.
@Test
public void testWithMultiPolygonGeo() throws CatalogTransformerException, IOException, ParseException {
Date now = new Date();
MetacardImpl metacard = new MetacardImpl();
metacard.setLocation("MULTIPOLYGON (((30 10, 10 20, 20 40, 40 40, 30 10)),((15 5, 40 10, 10 20, 5 10, 15 5)))");
setupBasicMetacard(now, metacard);
GeoJsonMetacardTransformer transformer = new GeoJsonMetacardTransformer();
BinaryContent content = transformer.transform(metacard, null);
assertEquals(content.getMimeTypeValue(), GeoJsonMetacardTransformer.DEFAULT_MIME_TYPE.getBaseType());
String jsonText = new String(content.getByteArray());
LOGGER.debug(jsonText);
Object object = PARSER.parse(jsonText);
JSONObject obj2 = (JSONObject) object;
Map geometryMap = (Map) obj2.get("geometry");
assertThat(geometryMap.get(CompositeGeometry.TYPE_KEY).toString(), is(MultiPolygon.TYPE));
List<List> listOfPolygons = (List<List>) geometryMap.get(CompositeGeometry.COORDINATES_KEY);
assertThat(listOfPolygons.size(), is(2));
List<List> polygon1 = listOfPolygons.get(0);
List<List> polygon2 = listOfPolygons.get(1);
List<List> polygon1FirstRing = polygon1.get(0);
List<List> polygon2FirstRing = polygon2.get(0);
testPopularPolygon(polygon1FirstRing);
testSecondPolygon(polygon2FirstRing);
verifyBasicMetacardJson(now, obj2);
}
Aggregations