Search in sources :

Example 21 with GetRecordsResponseType

use of org.geotoolkit.csw.xml.v202.GetRecordsResponseType in project ddf by codice.

the class TestGetRecordsResponseConverter method testMarshalRecordCollectionGetSummary.

@Ignore
public void testMarshalRecordCollectionGetSummary() throws UnsupportedEncodingException, JAXBException {
    final int totalResults = 5;
    XStream xstream = createXStream(CswConstants.GET_RECORDS_RESPONSE);
    GetRecordsType getRecords = new GetRecordsType();
    QueryType query = new QueryType();
    ElementSetNameType set = new ElementSetNameType();
    set.setValue(ElementSetType.SUMMARY);
    query.setElementSetName(set);
    ObjectFactory objectFactory = new ObjectFactory();
    getRecords.setAbstractQuery(objectFactory.createAbstractQuery(query));
    CswRecordCollection collection = createCswRecordCollection(getRecords, totalResults);
    collection.setElementSetType(ElementSetType.SUMMARY);
    ArgumentCaptor<MarshallingContext> captor = ArgumentCaptor.forClass(MarshallingContext.class);
    String xml = xstream.toXML(collection);
    // Verify the context arguments were set correctly
    verify(mockProvider, times(totalResults)).marshal(any(Object.class), any(HierarchicalStreamWriter.class), captor.capture());
    MarshallingContext context = captor.getValue();
    assertThat(context, not(nullValue()));
    assertThat(context.get(CswConstants.OUTPUT_SCHEMA_PARAMETER), is(CswConstants.CSW_OUTPUT_SCHEMA));
    assertThat(context.get(CswConstants.ELEMENT_SET_TYPE), is(ElementSetType.SUMMARY));
    JAXBElement<GetRecordsResponseType> jaxb = (JAXBElement<GetRecordsResponseType>) getJaxBContext().createUnmarshaller().unmarshal(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    GetRecordsResponseType response = jaxb.getValue();
    // Assert the GetRecordsResponse elements and attributes
    assertThat(response, not(nullValue()));
    SearchResultsType resultsType = response.getSearchResults();
    assertThat(resultsType, not(nullValue()));
    assertThat(resultsType.getElementSet(), is(ElementSetType.SUMMARY));
    assertThat(resultsType.getNumberOfRecordsMatched().intValue(), is(totalResults));
    assertThat(resultsType.getNumberOfRecordsReturned().intValue(), is(totalResults));
    assertThat(resultsType.getRecordSchema(), is(CswConstants.CSW_OUTPUT_SCHEMA));
}
Also used : HierarchicalStreamWriter(com.thoughtworks.xstream.io.HierarchicalStreamWriter) XStream(com.thoughtworks.xstream.XStream) SearchResultsType(net.opengis.cat.csw.v_2_0_2.SearchResultsType) GetRecordsType(net.opengis.cat.csw.v_2_0_2.GetRecordsType) Matchers.anyString(org.mockito.Matchers.anyString) JAXBElement(javax.xml.bind.JAXBElement) ObjectFactory(net.opengis.cat.csw.v_2_0_2.ObjectFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) CswRecordCollection(org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection) ElementSetNameType(net.opengis.cat.csw.v_2_0_2.ElementSetNameType) GetRecordsResponseType(net.opengis.cat.csw.v_2_0_2.GetRecordsResponseType) MarshallingContext(com.thoughtworks.xstream.converters.MarshallingContext) QueryType(net.opengis.cat.csw.v_2_0_2.QueryType) Ignore(jdk.nashorn.internal.ir.annotations.Ignore)

Example 22 with GetRecordsResponseType

use of org.geotoolkit.csw.xml.v202.GetRecordsResponseType in project ARLAS-server by gisaia.

the class CSWRESTService method doKVP.

@Timed
@Path("/csw")
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_XML, ATOM.APPLICATION_ATOM_XML, MIME_TYPE__OPENSEARCH_XML })
@ApiOperation(value = "CSW", produces = MediaType.APPLICATION_XML + "," + MediaType.TEXT_XML + "," + ATOM.APPLICATION_ATOM_XML + "," + MIME_TYPE__OPENSEARCH_XML, notes = "CSW")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful operation"), @ApiResponse(code = 500, message = "Arlas Server Error.", response = Error.class) })
public Response doKVP(@ApiParam(name = "version", value = "version", allowMultiple = false, required = true) @QueryParam(value = "version") String version, @ApiParam(name = "acceptversions", value = "acceptversions", allowMultiple = false, required = true) @QueryParam(value = "acceptversions") String acceptVersions, @ApiParam(name = "service", value = "service", allowMultiple = false, required = true) @QueryParam(value = "service") String service, @ApiParam(name = "request", value = "request", allowMultiple = false, required = true) @QueryParam(value = "request") String request, @ApiParam(name = "elementname", value = "elementname", allowMultiple = false, required = true) @QueryParam(value = "elementname") String elementName, @ApiParam(name = "elementsetname", value = "elementsetname", allowMultiple = false, required = true) @QueryParam(value = "elementsetname") String elementSetName, @ApiParam(name = "filter", value = "filter", allowMultiple = false, required = true) @QueryParam(value = "filter") String filter, @ApiParam(name = "constraint", value = "constraint", allowMultiple = false, required = true) @QueryParam(value = "constraint") String constraint, @ApiParam(name = "constraintLanguage", value = "constraintLanguage", allowMultiple = false, required = true) @QueryParam(value = "constraintLanguage") String constraintLanguage, @ApiParam(name = "startposition", value = "startposition", allowMultiple = false, required = false) @QueryParam(value = "startposition") Integer startPosition, @ApiParam(name = "maxrecords", value = "maxrecords", allowMultiple = false, required = false) @QueryParam(value = "maxrecords") Integer maxRecords, @ApiParam(name = "sections", value = "sections", allowMultiple = false, required = false) @QueryParam(value = "sections") String sections, @ApiParam(name = "acceptformats", value = "acceptformats", allowMultiple = false, required = false) @QueryParam(value = "acceptformats") String acceptFormats, @ApiParam(name = "q", value = "q", allowMultiple = false, required = false) @QueryParam(value = "q") String query, @ApiParam(name = "bbox", value = "bbox", allowMultiple = false, required = false) @QueryParam(value = "bbox") String bbox, @ApiParam(name = "outputformat", value = "outputformat", allowMultiple = false, required = false) @QueryParam(value = "outputformat") String outputFormat, @ApiParam(name = "outputschema", value = "outputschema", allowMultiple = false, required = false) @QueryParam(value = "outputschema") String outputSchema, @ApiParam(name = "typenames", value = "typenames", allowMultiple = false, required = false) @QueryParam(value = "typenames") String typeNames, @ApiParam(name = "recordids", value = "recordids", allowMultiple = false, required = false) @QueryParam(value = "recordids") String recordIds, @ApiParam(name = "id", value = "id", allowMultiple = false, required = false) @QueryParam(value = "id") String id, @ApiParam(name = "language", value = "language", allowMultiple = false, required = false) @QueryParam(value = "language") String language, @ApiParam(hidden = true) @HeaderParam(value = "Column-Filter") Optional<String> columnFilter, // --------------------------------------------------------
@ApiParam(name = "pretty", value = Documentation.FORM_PRETTY, allowMultiple = false, defaultValue = "false", required = false) @QueryParam(value = "pretty") Boolean pretty, @Context HttpHeaders headers) throws ArlasException, DatatypeConfigurationException, IOException {
    String acceptFormatMediaType = MediaType.APPLICATION_XML;
    String outputFormatMediaType = MediaType.APPLICATION_XML;
    for (MediaType mediaType : headers.getAcceptableMediaTypes()) {
        if (mediaType.getSubtype().contains("opensearchdescription")) {
            OpenSearchHandler openSearchHandler = cswHandler.openSearchHandler;
            OpenSearchDescription description = openSearchHandler.getOpenSearchDescription(serverBaseUri);
            return Response.ok(description).build();
        } else if (mediaType.getSubtype().contains("atom")) {
            outputFormatMediaType = MediaType.APPLICATION_ATOM_XML;
        }
    }
    if (request == null & version == null & service == null) {
        request = "GetCapabilities";
        version = CSWConstant.SUPPORTED_CSW_VERSION;
        service = CSWConstant.CSW;
    }
    String[] sectionList;
    if (sections == null) {
        sectionList = new String[] { "All" };
    } else {
        sectionList = sections.split(",");
        for (String section : sectionList) {
            if (!Arrays.asList(CSWConstant.SECTION_NAMES).contains(section)) {
                throw new OGCException(OGCExceptionCode.INVALID_PARAMETER_VALUE, "Invalid sections", "sections", Service.CSW);
            }
        }
    }
    if (acceptFormats != null) {
        if (acceptFormats.equals("text/xml")) {
            acceptFormatMediaType = MediaType.TEXT_XML;
        } else if (acceptFormats.equals("application/xml")) {
            acceptFormatMediaType = MediaType.APPLICATION_XML;
        } else {
            throw new OGCException(OGCExceptionCode.INVALID_PARAMETER_VALUE, "Invalid acceptFormats", "acceptFormats", Service.CSW);
        }
    }
    if (outputFormat != null) {
        if (outputFormat.equals("application/xml")) {
            outputFormatMediaType = MediaType.APPLICATION_XML;
        } else if (outputFormat.equals("application/atom+xml")) {
            outputFormatMediaType = MediaType.APPLICATION_ATOM_XML;
        } else {
            throw new OGCException(OGCExceptionCode.INVALID_PARAMETER_VALUE, "Invalid outputFormat", "outputFormat", Service.CSW);
        }
    }
    RequestUtils.checkRequestTypeByName(request, CSWConstant.SUPPORTED_CSW_REQUESTYPE, Service.CSW);
    CSWRequestType requestType = CSWRequestType.valueOf(request);
    CSWCheckParam.checkQuerySyntax(requestType, elementName, elementSetName, acceptVersions, version, service, outputSchema, typeNames, bbox, recordIds, query, id, constraintLanguage);
    String[] ids = null;
    if (recordIds != null && recordIds.length() > 0) {
        ids = recordIds.split(",");
    } else if (id != null) {
        ids = new String[] { id };
    }
    BoundingBox boundingBox = null;
    if (bbox != null && bbox.length() > 0) {
        // west, south, east, north CSW spec
        double[] bboxList = GeoFormat.toDoubles(bbox, Service.CSW);
        if (!(isBboxLatLonInCorrectRanges(bboxList) && bboxList[3] > bboxList[1]) && bboxList[0] != bboxList[2]) {
            throw new OGCException(OGCExceptionCode.INVALID_PARAMETER_VALUE, FluidSearchService.INVALID_BBOX, "bbox", Service.CSW);
        }
        boundingBox = new BoundingBox(bboxList[3], bboxList[1], bboxList[0], bboxList[2]);
    }
    startPosition = Optional.ofNullable(startPosition).orElse(1);
    maxRecords = Optional.ofNullable(maxRecords).orElse(cswHandler.ogcConfiguration.queryMaxFeature.intValue());
    elementSetName = Optional.ofNullable(elementSetName).orElse("summary");
    String[] elements = new String[] {};
    if (elementName != null) {
        elements = new String[elementName.split(",").length];
        int i = 0;
        for (String element : elementName.split(",")) {
            if (element.contains(":")) {
                elements[i] = elementName.split(":")[1];
                element = elements[i];
            } else {
                elements[i] = element;
            }
            if (!Arrays.asList(CSWConstant.DC_FIELDS).contains(element.toLowerCase()))
                throw new OGCException(OGCExceptionCode.INVALID_PARAMETER_VALUE, "Invalid elementName", "elementName", Service.CSW);
            i++;
        }
    }
    List<CollectionReference> collections;
    switch(requestType) {
        case GetCapabilities:
            GetCapabilitiesHandler getCapabilitiesHandler = cswHandler.getCapabilitiesHandler;
            List<String> responseSections = Arrays.asList(sectionList);
            String serviceUrl = serverBaseUri + "ogc/csw/?";
            getCapabilitiesHandler.setCapabilitiesType(responseSections, serviceUrl, serverBaseUri + "ogc/csw/opensearch");
            if (cswHandler.inspireConfiguration.enabled) {
                collections = collectionReferenceService.getAllCollectionReferences(columnFilter);
                collections.removeIf(collectionReference -> collectionReference.collectionName.equals(getMetacollectionName()));
                filterCollectionsByColumnFilter(columnFilter, collections);
                if (CollectionUtils.isNotEmpty(collections)) {
                    getCapabilitiesHandler.addINSPIRECompliantElements(collections, responseSections, serviceUrl, language);
                }
            }
            JAXBElement<CapabilitiesType> getCapabilitiesResponse = getCapabilitiesHandler.getCSWCapabilitiesResponse();
            return Response.ok(getCapabilitiesResponse).type(acceptFormatMediaType).build();
        case GetRecords:
            GetRecordsHandler getRecordsHandler = cswHandler.getRecordsHandler;
            CollectionReferences collectionReferences = getCollectionReferencesForGetRecords(elements, null, maxRecords, startPosition, ids, query, constraint, boundingBox);
            collections = new ArrayList<>(collectionReferences.collectionReferences);
            filterCollectionsByColumnFilter(columnFilter, collections);
            long recordsMatched = collectionReferences.totalCollectionReferences;
            if (recordIds != null && recordIds.length() > 0) {
                if (collections.size() == 0) {
                    throw new OGCException(OGCExceptionCode.NOT_FOUND, "Document not Found", "id", Service.CSW);
                }
            }
            GetRecordsResponseType getRecordsResponse = getRecordsHandler.getCSWGetRecordsResponse(collections, ElementSetName.valueOf(elementSetName), startPosition - 1, recordsMatched, elements, outputSchema);
            return Response.ok(getRecordsResponse).type(outputFormatMediaType).build();
        case GetRecordById:
            GetRecordsByIdHandler getRecordsByIdHandler = cswHandler.getRecordsByIdHandler;
            CollectionReferences recordCollectionReferences = ogcDao.getCollectionReferences(elements, null, maxRecords, startPosition - 1, ids, query, constraint, boundingBox);
            collections = new ArrayList<>(recordCollectionReferences.collectionReferences);
            ColumnFilterUtil.assertCollectionsAllowed(columnFilter, collections);
            if (outputSchema != null && outputSchema.equals(CSWConstant.SUPPORTED_CSW_OUTPUT_SCHEMA[2])) {
                GetRecordByIdResponse getRecordByIdResponse = getRecordsByIdHandler.getMDMetadaTypeResponse(collections, ElementSetName.valueOf(elementSetName));
                return Response.ok(getRecordByIdResponse).type(outputFormatMediaType).build();
            } else {
                AbstractRecordType abstractRecordType = getRecordsByIdHandler.getAbstractRecordTypeResponse(collections, ElementSetName.valueOf(elementSetName));
                return Response.ok(abstractRecordType).type(outputFormatMediaType).build();
            }
        default:
            throw new OGCException(OGCExceptionCode.INTERNAL_SERVER_ERROR, "Internal error: Unhandled request '" + request + "'.", Service.CSW);
    }
}
Also used : GetCapabilitiesHandler(io.arlas.server.ogc.csw.operation.getcapabilities.GetCapabilitiesHandler) GetRecordByIdResponse(io.arlas.server.ogc.csw.operation.getrecordbyid.GetRecordByIdResponse) GetRecordsByIdHandler(io.arlas.server.ogc.csw.operation.getrecordbyid.GetRecordsByIdHandler) OpenSearchHandler(io.arlas.server.ogc.csw.operation.opensearch.OpenSearchHandler) AbstractRecordType(net.opengis.cat.csw._3.AbstractRecordType) CollectionReference(io.arlas.server.core.model.CollectionReference) OpenSearchDescription(com.a9.opensearch.OpenSearchDescription) CapabilitiesType(net.opengis.cat.csw._3.CapabilitiesType) GetRecordsHandler(io.arlas.server.ogc.csw.operation.getrecords.GetRecordsHandler) BoundingBox(io.arlas.server.core.utils.BoundingBox) CollectionReferences(io.arlas.server.core.model.CollectionReferences) GetRecordsResponseType(net.opengis.cat.csw._3.GetRecordsResponseType) OGCException(io.arlas.server.ogc.common.exceptions.OGC.OGCException) CSWRequestType(io.arlas.server.ogc.csw.utils.CSWRequestType) Timed(com.codahale.metrics.annotation.Timed)

Example 23 with GetRecordsResponseType

use of org.geotoolkit.csw.xml.v202.GetRecordsResponseType in project geotoolkit by Geomatys.

the class CSWClientDemo method main.

public static void main(String[] args) throws MalformedURLException, URISyntaxException, IOException, JAXBException {
    Demos.init();
    final MarshallerPool pool = CSWMarshallerPool.getInstance();
    final Unmarshaller um = pool.acquireUnmarshaller();
    final MarshallWarnings warnings = new MarshallWarnings();
    um.setProperty(XML.CONVERTER, warnings);
    // build a new CSW client
    final CatalogServicesClient cswServer = new CatalogServicesClient(new URL("http://catalog.data.gov/csw?"), "2.0.2");
    /**
     * make a getCapabilities request
     */
    final GetCapabilitiesRequest getCapa = cswServer.createGetCapabilities();
    InputStream is = getCapa.getResponseStream();
    // unmarshall the response
    Capabilities capabilities = (Capabilities) um.unmarshal(is);
    // print the title of the server
    System.out.println(capabilities.getServiceIdentification().getTitle());
    /**
     * make a getRecords request
     */
    final GetRecordsRequest getRecords = cswServer.createGetRecords();
    getRecords.setTypeNames("gmd:MD_Metadata");
    getRecords.setConstraintLanguage("CQL");
    getRecords.setConstraintLanguageVersion("1.1.0");
    getRecords.setConstraint("apiso:Title like '%'");
    getRecords.setElementSetName(ElementSetType.FULL);
    is = getRecords.getResponseStream();
    // unmarshall the response
    Object obj = um.unmarshal(is);
    GetRecordsResponseType response;
    if (obj instanceof ExceptionReport) {
        System.out.println("Error received:" + obj);
        return;
    } else {
        response = ((JAXBElement<GetRecordsResponseType>) obj).getValue();
    }
    // print the number of result matching the request
    System.out.println(response.getSearchResults().getNumberOfRecordsMatched());
    /**
     * retrieve results in dublin core
     */
    getRecords.setResultType(ResultType.RESULTS);
    is = getRecords.getResponseStream();
    obj = um.unmarshal(is);
    // unmarshall the response
    if (obj instanceof ExceptionReport) {
        System.out.println("Error received:" + obj);
        return;
    } else {
        response = ((JAXBElement<GetRecordsResponseType>) obj).getValue();
    }
    // print the first result (Dublin core)
    AbstractRecord record = (AbstractRecord) response.getSearchResults().getAny().get(0);
    System.out.println(record);
    /**
     * retrieve results in ISO 19139
     */
    getRecords.setOutputSchema("http://www.isotc211.org/2005/gmd");
    is = getRecords.getResponseStream();
    // unmarshall the response
    obj = um.unmarshal(is);
    // unmarshall the response
    if (obj instanceof ExceptionReport) {
        System.out.println("Error received:" + obj);
        return;
    } else {
        response = ((JAXBElement<GetRecordsResponseType>) obj).getValue();
    }
    // print the first result (ISO 19139)
    Metadata meta = (Metadata) response.getSearchResults().getAny().get(0);
    System.out.println(meta);
    final String identifier = meta.getFileIdentifier();
    /**
     * make a getRecordById request
     */
    final GetRecordByIdRequest getRecordById = cswServer.createGetRecordById();
    getRecordById.setOutputSchema("http://www.isotc211.org/2005/gmd");
    getRecordById.setIds(identifier);
    is = getRecordById.getResponseStream();
    // unmarshall the response
    obj = um.unmarshal(is);
    // unmarshall the response
    GetRecordByIdResponse responseBi;
    if (obj instanceof ExceptionReport) {
        System.out.println("Error received:" + obj);
        return;
    } else {
        responseBi = ((JAXBElement<GetRecordByIdResponse>) obj).getValue();
    }
    // print the result (same as getRecords first result)
    meta = (Metadata) responseBi.getAny().get(0);
    System.out.println(meta);
    pool.recycle(um);
}
Also used : GetRecordByIdResponse(org.geotoolkit.csw.xml.GetRecordByIdResponse) GetCapabilitiesRequest(org.geotoolkit.csw.GetCapabilitiesRequest) InputStream(java.io.InputStream) ExceptionReport(org.geotoolkit.ows.xml.v100.ExceptionReport) AbstractRecord(org.geotoolkit.csw.xml.AbstractRecord) Metadata(org.opengis.metadata.Metadata) CSWMarshallerPool(org.geotoolkit.csw.xml.CSWMarshallerPool) MarshallerPool(org.apache.sis.xml.MarshallerPool) GetRecordByIdRequest(org.geotoolkit.csw.GetRecordByIdRequest) URL(java.net.URL) GetRecordsRequest(org.geotoolkit.csw.GetRecordsRequest) CatalogServicesClient(org.geotoolkit.csw.CatalogServicesClient) Capabilities(org.geotoolkit.csw.xml.v202.Capabilities) GetRecordsResponseType(org.geotoolkit.csw.xml.v202.GetRecordsResponseType) Unmarshaller(javax.xml.bind.Unmarshaller)

Aggregations

GetRecordsResponseType (net.opengis.cat.csw.v_2_0_2.GetRecordsResponseType)19 SearchResultsType (net.opengis.cat.csw.v_2_0_2.SearchResultsType)16 JAXBElement (javax.xml.bind.JAXBElement)15 CswRecordCollection (org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection)15 XStream (com.thoughtworks.xstream.XStream)14 ByteArrayInputStream (java.io.ByteArrayInputStream)14 GetRecordsType (net.opengis.cat.csw.v_2_0_2.GetRecordsType)14 ObjectFactory (net.opengis.cat.csw.v_2_0_2.ObjectFactory)12 QueryType (net.opengis.cat.csw.v_2_0_2.QueryType)12 Test (org.junit.Test)11 MarshallingContext (com.thoughtworks.xstream.converters.MarshallingContext)10 HierarchicalStreamWriter (com.thoughtworks.xstream.io.HierarchicalStreamWriter)10 ElementSetNameType (net.opengis.cat.csw.v_2_0_2.ElementSetNameType)10 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)7 Ignore (jdk.nashorn.internal.ir.annotations.Ignore)6 Ignore (org.junit.Ignore)6 Matchers.anyString (org.mockito.Matchers.anyString)6 ArrayList (java.util.ArrayList)5 InputStream (java.io.InputStream)3 LinkedList (java.util.LinkedList)3