Search in sources :

Example 1 with OpenSearchQuery

use of org.codice.ddf.opensearch.endpoint.query.OpenSearchQuery in project ddf by codice.

the class OpenSearchEndpointTest method testProcessQueryForProperHandlingOfSiteNameLOCAL.

/**
 * Test method for {@link OpenSearchEndpoint#processQuery(String, String, String, String, String,
 * String, String, String, String, String, String, String, String, String, String, String, String,
 * String, UriInfo, String, String, HttpServletRequest)} .
 *
 * <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.
 */
@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(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);
}
Also used : AttributeBuilder(ddf.catalog.filter.AttributeBuilder) QueryRequest(ddf.catalog.operation.QueryRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ContextualExpressionBuilder(ddf.catalog.filter.ContextualExpressionBuilder) ContextualExpressionBuilder(ddf.catalog.filter.ContextualExpressionBuilder) ExpressionBuilder(ddf.catalog.filter.ExpressionBuilder) BinaryContent(ddf.catalog.data.BinaryContent) URI(java.net.URI) QueryResponseImpl(ddf.catalog.operation.impl.QueryResponseImpl) OpenSearchQuery(org.codice.ddf.opensearch.endpoint.query.OpenSearchQuery) Filter(org.opengis.filter.Filter) ByteArrayInputStream(java.io.ByteArrayInputStream) FilterBuilder(ddf.catalog.filter.FilterBuilder) QueryResponse(ddf.catalog.operation.QueryResponse) CatalogFramework(ddf.catalog.CatalogFramework) UriInfo(javax.ws.rs.core.UriInfo) Test(org.junit.Test)

Example 2 with OpenSearchQuery

use of org.codice.ddf.opensearch.endpoint.query.OpenSearchQuery in project ddf by codice.

the class OpenSearchEndpoint method processQuery.

/**
 * @param searchTerms Space-delimited list of search terms.
 * @param maxResults Maximum # of results to return. If count is also specified, the count value
 *     will take precedence over the maxResults value
 * @param sources Comma-delimited list of data sources to query (default: default sources
 *     selected).
 * @param maxTimeout Maximum timeout (msec) for query to respond (default: mt=30000).
 * @param startIndex Index of first result to return. Integer >= 0 (default: start=1).
 * @param count Number of results to retrieve per page (default: count=10).
 * @param geometry WKT Geometries.
 * @param bbox Comma-delimited list of lat/lon (deg) bounding box coordinates (geo format:
 *     geo:bbox ~ West,South,East,North).
 * @param polygon Comma-delimited list of lat/lon (deg) pairs, in clockwise order around the
 *     polygon, with the last point being the same as the first in order to close the polygon.
 * @param lat Latitude in decimal degrees (typical GPS receiver WGS84 coordinates).
 * @param lon Longitude in decimal degrees (typical GPS receiver WGS84 coordinates).
 * @param radius The radius (m) parameter, used with the lat and lon parameters, specifies the
 *     search distance from this point (default: radius=5000).
 * @param dateStart Specifies the beginning of the time slice of the search on the modified time
 *     field (RFC-3339 - Date and Time format, i.e. YYYY-MM-DDTHH:mm:ssZ). Default value of
 *     "1970-01-01T00:00:00Z" is used when dtend is indicated but dtstart is not specified
 * @param dateEnd Specifies the ending of the time slice of the search on the modified time field
 *     (RFC-3339 - Date and Time format, i.e. YYYY-MM-DDTHH:mm:ssZ). Current GMT date/time is used
 *     when dtstart is specified but not dtend.
 * @param dateOffset Specifies an offset, backwards from the current time, to search on the
 *     modified time field for entries. Defined in milliseconds.
 * @param sort Specifies sort by field as sort=<sbfield>:<sborder>, where <sbfield> may be 'date'
 *     or 'relevance' (default is 'relevance'). The conditional param <sborder> is optional but
 *     has a value of 'asc' or 'desc' (default is 'desc'). When <sbfield> is 'relevance',
 *     <sborder> must be 'desc'.
 * @param format Defines the format that the return type should be in. (example:atom, html)
 * @param selectors Defines a comma-delimited list of XPath selectors to narrow the query.
 * @param type Specifies the type of data to search for. (example: nitf)
 * @param versions Specifies the versions in a comma-delimited list.
 */
@Override
@GET
public Response processQuery(@QueryParam(OpenSearchConstants.SEARCH_TERMS) String searchTerms, @QueryParam(OpenSearchConstants.MAX_RESULTS) String maxResults, @QueryParam(OpenSearchConstants.SOURCES) String sources, @QueryParam(OpenSearchConstants.MAX_TIMEOUT) String maxTimeout, @QueryParam(OpenSearchConstants.START_INDEX) String startIndex, @QueryParam(OpenSearchConstants.COUNT) String count, @QueryParam(OpenSearchConstants.GEOMETRY) String geometry, @QueryParam(OpenSearchConstants.BBOX) String bbox, @QueryParam(OpenSearchConstants.POLYGON) String polygon, @QueryParam(OpenSearchConstants.LAT) String lat, @QueryParam(OpenSearchConstants.LON) String lon, @QueryParam(OpenSearchConstants.RADIUS) String radius, @QueryParam(OpenSearchConstants.DATE_START) String dateStart, @QueryParam(OpenSearchConstants.DATE_END) String dateEnd, @QueryParam(OpenSearchConstants.DATE_OFFSET) String dateOffset, @QueryParam(OpenSearchConstants.SORT) String sort, @QueryParam(OpenSearchConstants.FORMAT) String format, @QueryParam(OpenSearchConstants.SELECTORS) String selectors, @Context UriInfo ui, @QueryParam(OpenSearchConstants.TYPE) String type, @QueryParam(OpenSearchConstants.VERSIONS) String versions, @Context HttpServletRequest request) {
    Response response;
    LOGGER.trace("request url: {}", ui.getRequestUri());
    try {
        OpenSearchQuery query = createNewQuery(startIndex, count, maxResults, sort, maxTimeout);
        if (StringUtils.isNotEmpty(sources)) {
            LOGGER.trace("Received site names from client.");
            final Set<String> siteSet = SOURCES_PATTERN.splitAsStream(sources).collect(Collectors.toSet());
            // eventually remove support for it.
            if (siteSet.remove(OpenSearchConstants.LOCAL_SOURCE)) {
                LOGGER.trace("Found 'local' alias, replacing with {}.", SystemInfo.getSiteName());
                siteSet.add(SystemInfo.getSiteName());
            }
            if (siteSet.contains(framework.getId()) && siteSet.size() == 1) {
                LOGGER.trace("Only local site specified, saving overhead and just performing a local query on Id : {} .", framework.getId());
            } else {
                LOGGER.trace("Querying site set: {}", siteSet);
                query.setSiteIds(siteSet);
            }
            query.setIsEnterprise(false);
        } else {
            LOGGER.trace("No sites found, defaulting to enterprise query.");
            query.setIsEnterprise(true);
        }
        // contextual
        if (StringUtils.isNotBlank(searchTerms)) {
            query.addContextualFilter(searchTerms.trim(), selectors);
        }
        if (StringUtils.isNotBlank(dateStart) || StringUtils.isNotBlank(dateEnd)) {
            // If either start date OR end date is specified and non-empty, then a temporal filter can
            // be created
            query.addStartEndTemporalFilter(dateStart, dateEnd);
        } else if (StringUtils.isNotBlank(dateOffset)) {
            query.addOffsetTemporalFilter(dateOffset);
        }
        // spatial
        // single spatial criterion per query
        addSpatialFilter(query, geometry, polygon, bbox, radius, lat, lon);
        if (StringUtils.isNotBlank(type)) {
            query.addTypeFilter(type.trim(), versions);
        }
        Map<String, Serializable> properties = new HashMap<>();
        for (Object key : request.getParameterMap().keySet()) {
            if (key instanceof String) {
                Object value = request.getParameterMap().get(key);
                if (value != null) {
                    properties.put((String) key, ((String[]) value)[0]);
                }
            }
        }
        response = executeQuery(format, query, ui, properties);
    } catch (ParsingException e) {
        LOGGER.debug("Bad input found while executing a query", e);
        response = Response.status(Response.Status.BAD_REQUEST).entity(wrapStringInPreformattedTags(e.getMessage())).build();
    } catch (RuntimeException re) {
        LOGGER.debug("Exception while executing a query", re);
        response = Response.serverError().entity(wrapStringInPreformattedTags("Exception while executing a query")).build();
    }
    return response;
}
Also used : QueryResponse(ddf.catalog.operation.QueryResponse) Response(javax.ws.rs.core.Response) Serializable(java.io.Serializable) OpenSearchQuery(org.codice.ddf.opensearch.endpoint.query.OpenSearchQuery) HashMap(java.util.HashMap) ParsingException(org.parboiled.errors.ParsingException) GET(javax.ws.rs.GET)

Aggregations

QueryResponse (ddf.catalog.operation.QueryResponse)2 OpenSearchQuery (org.codice.ddf.opensearch.endpoint.query.OpenSearchQuery)2 CatalogFramework (ddf.catalog.CatalogFramework)1 BinaryContent (ddf.catalog.data.BinaryContent)1 AttributeBuilder (ddf.catalog.filter.AttributeBuilder)1 ContextualExpressionBuilder (ddf.catalog.filter.ContextualExpressionBuilder)1 ExpressionBuilder (ddf.catalog.filter.ExpressionBuilder)1 FilterBuilder (ddf.catalog.filter.FilterBuilder)1 QueryRequest (ddf.catalog.operation.QueryRequest)1 QueryResponseImpl (ddf.catalog.operation.impl.QueryResponseImpl)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 Serializable (java.io.Serializable)1 URI (java.net.URI)1 HashMap (java.util.HashMap)1 GET (javax.ws.rs.GET)1 Response (javax.ws.rs.core.Response)1 UriInfo (javax.ws.rs.core.UriInfo)1 Test (org.junit.Test)1 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)1