Search in sources :

Example 36 with CswRecordCollection

use of org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection in project ddf by codice.

the class TestCswEndpoint method testPostRetrieveProductGetRecordByIdWithRange.

@Test
public void testPostRetrieveProductGetRecordByIdWithRange() throws IOException, ResourceNotFoundException, ResourceNotSupportedException, CswException {
    final GetRecordByIdType getRecordByIdType = new GetRecordByIdType();
    getRecordByIdType.setOutputFormat(MediaType.APPLICATION_OCTET_STREAM);
    getRecordByIdType.setOutputSchema(OCTET_STREAM_OUTPUT_SCHEMA);
    getRecordByIdType.setId(Collections.singletonList("123"));
    setUpMocksForProductRetrieval(true);
    CswRecordCollection cswRecordCollection = csw.getRecordById(getRecordByIdType, RANGE_VALUE);
    assertThat(cswRecordCollection.getResource(), is(notNullValue()));
}
Also used : CswRecordCollection(org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection) GetRecordByIdType(net.opengis.cat.csw.v_2_0_2.GetRecordByIdType) Test(org.junit.Test)

Example 37 with CswRecordCollection

use of org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection in project ddf by codice.

the class CswQueryResponseTransformer method transform.

@Override
public BinaryContent transform(SourceResponse sourceResponse, Map<String, Serializable> arguments) throws CatalogTransformerException {
    validateInput(sourceResponse, arguments);
    CswRecordCollection recordCollection = buildCollection(sourceResponse, arguments);
    ByteArrayInputStream bais;
    if (ResultType.VALIDATE.equals(recordCollection.getResultType())) {
        ByteArrayOutputStream baos = writeAcknowledgement(recordCollection.getRequest());
        bais = new ByteArrayInputStream(baos.toByteArray());
    } else {
        // "catches" recordCollection.getResultType() == null
        List<Result> results = sourceResponse.getResults();
        String xmlString = convert(recordCollection, results, arguments);
        bais = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8));
    }
    BinaryContent transformedContent = new BinaryContentImpl(bais, CswRecordConverter.XML_MIME_TYPE);
    return transformedContent;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CswRecordCollection(org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) BinaryContent(ddf.catalog.data.BinaryContent) Result(ddf.catalog.data.Result)

Example 38 with CswRecordCollection

use of org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection in project ddf by codice.

the class CswEndpoint method getRecordById.

@Override
@POST
@Consumes({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
public CswRecordCollection getRecordById(GetRecordByIdType request, @HeaderParam(CswConstants.RANGE_HEADER) String rangeValue) throws CswException {
    if (request == null) {
        throw new CswException("GetRecordByIdRequest request is null");
    }
    String outputFormat = request.getOutputFormat();
    String outputSchema = request.getOutputSchema();
    validator.validateOutputFormat(outputFormat, mimeTypeTransformerManager);
    validator.validateOutputSchema(outputSchema, schemaTransformerManager);
    List<String> ids = request.getId();
    if (!ids.isEmpty()) {
        String id = ids.get(0);
        // Check if the request wants to retrieve a product.
        if (isProductRetrieval(ids, outputFormat, outputSchema)) {
            LOGGER.debug("{} is attempting to retrieve product for: {}", request.getService(), id);
            try {
                return queryProductById(id, rangeValue);
            } catch (UnsupportedQueryException e) {
                throw new CswException(String.format(ERROR_ID_PRODUCT_RETRIEVAL, id), e);
            }
        }
        LOGGER.debug("{} is attempting to retrieve records: {}", request.getService(), ids);
        CswRecordCollection response = queryById(ids, outputSchema);
        response.setOutputSchema(outputSchema);
        if (request.isSetElementSetName() && request.getElementSetName().getValue() != null) {
            response.setElementSetType(request.getElementSetName().getValue());
        } else {
            response.setElementSetType(ElementSetType.SUMMARY);
        }
        LOGGER.debug("{} successfully retrieved record(s): {}", request.getService(), request.getId());
        return response;
    } else {
        throw new CswException("A GetRecordById Query must contain an ID.", CswConstants.MISSING_PARAMETER_VALUE, "id");
    }
}
Also used : UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) CswException(org.codice.ddf.spatial.ogc.csw.catalog.common.CswException) CswRecordCollection(org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 39 with CswRecordCollection

use of org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection in project ddf by codice.

the class GetRecordsMessageBodyReader method readFrom.

@Override
public CswRecordCollection readFrom(Class<CswRecordCollection> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream inStream) throws IOException, WebApplicationException {
    CswRecordCollection cswRecords = null;
    Map<String, Serializable> resourceProperties = new HashMap<>();
    // Check if the server returned a Partial Content response (hopefully in response to a range header)
    String contentRangeHeader = httpHeaders.getFirst(HttpHeaders.CONTENT_RANGE);
    if (StringUtils.isNotBlank(contentRangeHeader)) {
        contentRangeHeader = StringUtils.substringBetween(contentRangeHeader.toLowerCase(), "bytes ", "-");
        long bytesSkipped = Long.parseLong(contentRangeHeader);
        resourceProperties.put(BYTES_SKIPPED, Long.valueOf(bytesSkipped));
    }
    // If the following HTTP header exists and its value is true, the input stream will contain
    // raw product data
    String productRetrievalHeader = httpHeaders.getFirst(CswConstants.PRODUCT_RETRIEVAL_HTTP_HEADER);
    if (productRetrievalHeader != null && productRetrievalHeader.equalsIgnoreCase("TRUE")) {
        String fileName = handleContentDispositionHeader(httpHeaders);
        cswRecords = new CswRecordCollection();
        cswRecords.setResource(new ResourceImpl(inStream, mediaType.toString(), fileName));
        cswRecords.setResourceProperties(resourceProperties);
        return cswRecords;
    }
    // Save original input stream for any exception message that might need to be
    // created
    String originalInputStream = IOUtils.toString(inStream, "UTF-8");
    LOGGER.debug("Converting to CswRecordCollection: \n {}", originalInputStream);
    // Re-create the input stream (since it has already been read for potential
    // exception message creation)
    inStream = new ByteArrayInputStream(originalInputStream.getBytes("UTF-8"));
    try {
        HierarchicalStreamReader reader = new XppReader(new InputStreamReader(inStream, StandardCharsets.UTF_8), XmlPullParserFactory.newInstance().newPullParser());
        cswRecords = (CswRecordCollection) xstream.unmarshal(reader, null, argumentHolder);
    } catch (XmlPullParserException e) {
        LOGGER.debug("Unable to create XmlPullParser, and cannot parse CSW Response.", e);
    } catch (XStreamException e) {
        // If an ExceptionReport is sent from the remote CSW site it will be sent with an
        // JAX-RS "OK" status, hence the ErrorResponse exception mapper will not fire.
        // Instead the ExceptionReport will come here and be treated like a GetRecords
        // response, resulting in an XStreamException since ExceptionReport cannot be
        // unmarshalled. So this catch clause is responsible for catching that XStream
        // exception and creating a JAX-RS response containing the original stream
        // (with the ExceptionReport) and rethrowing it as a WebApplicatioNException,
        // which CXF will wrap as a ClientException that the CswSource catches, converts
        // to a CswException, and logs.
        ByteArrayInputStream bis = new ByteArrayInputStream(originalInputStream.getBytes(StandardCharsets.UTF_8));
        ResponseBuilder responseBuilder = Response.ok(bis);
        responseBuilder.type("text/xml");
        Response response = responseBuilder.build();
        throw new WebApplicationException(e, response);
    } finally {
        IOUtils.closeQuietly(inStream);
    }
    return cswRecords;
}
Also used : Serializable(java.io.Serializable) InputStreamReader(java.io.InputStreamReader) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) Response(javax.ws.rs.core.Response) XStreamException(com.thoughtworks.xstream.XStreamException) ResourceImpl(ddf.catalog.resource.impl.ResourceImpl) ByteArrayInputStream(java.io.ByteArrayInputStream) XppReader(com.thoughtworks.xstream.io.xml.XppReader) CswRecordCollection(org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 40 with CswRecordCollection

use of org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection in project ddf by codice.

the class TestGetRecordsResponseConverter method testUnmarshalGetRecordsResponseFull.

/**
     * This test actually runs the full thread of calling the GetRecordsResponseConverter then calls the CswInputTransformer.
     */
@Test
public void testUnmarshalGetRecordsResponseFull() {
    XStream xstream = new XStream(new WstxDriver());
    xstream.setClassLoader(this.getClass().getClassLoader());
    CswTransformProvider provider = new CswTransformProvider(null, mockInputManager);
    when(mockInputManager.getTransformerBySchema(anyString())).thenReturn(new CswRecordConverter(TestCswRecordConverter.getCswMetacardType()));
    xstream.registerConverter(new GetRecordsResponseConverter(provider));
    xstream.alias("GetRecordsResponse", CswRecordCollection.class);
    String xml = "<csw:GetRecordsResponse xmlns:csw=\"http://www.opengis.net/cat/csw\">\r\n" + "  <csw:SearchStatus status=\"subset\" timestamp=\"2013-05-01T02:13:36+0200\"/>\r\n" + "  <csw:SearchResults elementSet=\"full\" nextRecord=\"11\" numberOfRecordsMatched=\"479\" numberOfRecordsReturned=\"10\" recordSchema=\"csw:Record\">\r\n" + "    <csw:Record xmlns:csw=\"http://www.opengis.net/cat/csw\">\r\n" + "      <dc:identifier xmlns:dc=\"http://purl.org/dc/elements/1.1/\">{8C1F6297-EC96-4302-A01E-14988C9149FD}</dc:identifier>\r\n" + "      <dc:title xmlns:dc=\"http://purl.org/dc/elements/1.1/\">title 1</dc:title>\r\n" + "      <dct:modified xmlns:dct=\"http://purl.org/dc/terms/\">2008-12-15</dct:modified>\r\n" + "      <dc:subject xmlns:dc=\"http://purl.org/dc/elements/1.1/\">subject 1</dc:subject>\r\n" + "      <dc:subject xmlns:dc=\"http://purl.org/dc/elements/1.1/\">second subject</dc:subject>\r\n" + "      <dct:abstract xmlns:dct=\"http://purl.org/dc/terms/\">abstract 1</dct:abstract>\r\n" + "      <dc:rights xmlns:dc=\"http://purl.org/dc/elements/1.1/\">copyright 1</dc:rights>\r\n" + "      <dc:rights xmlns:dc=\"http://purl.org/dc/elements/1.1/\">copyright 2</dc:rights>\r\n" + "      <dc:language xmlns:dc=\"http://purl.org/dc/elements/1.1/\">english</dc:language>      \r\n" + "      <ows:BoundingBox xmlns:ows=\"http://www.opengis.net/ows\" crs=\"EPSG:RD_New (28992)\">\r\n" + "        <ows:LowerCorner>5.121 52.139</ows:LowerCorner>\r\n" + "        <ows:UpperCorner>4.468 52.517</ows:UpperCorner>\r\n" + "      </ows:BoundingBox>   \r\n" + "      <dc:type xmlns:dc=\"http://purl.org/dc/elements/1.1/\">dataset</dc:type>\r\n" + "      <dc:format xmlns:dc=\"http://purl.org/dc/elements/1.1/\">Shapefile</dc:format> \r\n" + "    </csw:Record>\r\n" + "    <csw:Record xmlns:csw=\"http://www.opengis.net/cat/csw\">\r\n" + "      <dc:identifier xmlns:dc=\"http://purl.org/dc/elements/1.1/\">{23362852-F370-4369-B0B2-BE74B2859614}</dc:identifier>\r\n" + "      <dc:title xmlns:dc=\"http://purl.org/dc/elements/1.1/\">mc2 title</dc:title>\r\n" + "      <dct:modified xmlns:dct=\"http://purl.org/dc/terms/\">2010-12-15</dct:modified>\r\n" + "      <dc:subject xmlns:dc=\"http://purl.org/dc/elements/1.1/\">first subject</dc:subject>\r\n" + "      <dc:subject xmlns:dc=\"http://purl.org/dc/elements/1.1/\">subject 2</dc:subject>\r\n" + "      <dct:abstract xmlns:dct=\"http://purl.org/dc/terms/\">mc2 abstract</dct:abstract>\r\n" + "      <dc:rights xmlns:dc=\"http://purl.org/dc/elements/1.1/\">first copyright</dc:rights>\r\n" + "      <dc:rights xmlns:dc=\"http://purl.org/dc/elements/1.1/\">second copyright</dc:rights>\r\n" + "      <dc:language xmlns:dc=\"http://purl.org/dc/elements/1.1/\">english</dc:language>\r\n" + "      <ows:BoundingBox xmlns:ows=\"http://www.opengis.net/ows\" crs=\"EPSG:RD_New (28992)\">\r\n" + "        <ows:LowerCorner>6.121 53.139</ows:LowerCorner>\r\n" + "        <ows:UpperCorner>5.468 53.517</ows:UpperCorner>\r\n" + "      </ows:BoundingBox>\r\n" + "      <dc:type xmlns:dc=\"http://purl.org/dc/elements/1.1/\">dataset 2</dc:type>\r\n" + "      <dc:format xmlns:dc=\"http://purl.org/dc/elements/1.1/\">Shapefile 2</dc:format>\r\n" + "    </csw:Record>\r\n" + "  </csw:SearchResults>\r\n" + "</csw:GetRecordsResponse>";
    InputStream inStream = IOUtils.toInputStream(xml);
    CswRecordCollection cswRecords = (CswRecordCollection) xstream.fromXML(inStream);
    IOUtils.closeQuietly(inStream);
    List<Metacard> metacards = cswRecords.getCswRecords();
    assertThat(metacards, not(nullValue()));
    assertThat(metacards.size(), is(2));
    // verify first metacard's values
    Metacard mc = metacards.get(0);
    assertThat(mc, not(nullValue()));
    Map<String, Object> expectedValues = new HashMap<>();
    expectedValues.put(Core.ID, "{8C1F6297-EC96-4302-A01E-14988C9149FD}");
    expectedValues.put(Core.TITLE, "title 1");
    String expectedModifiedDateStr = "2008-12-15";
    DateTimeFormatter dateFormatter = ISODateTimeFormat.dateOptionalTimeParser();
    Date expectedModifiedDate = dateFormatter.parseDateTime(expectedModifiedDateStr).toDate();
    expectedValues.put(Core.MODIFIED, expectedModifiedDate);
    expectedValues.put(Topic.CATEGORY, new String[] { "subject 1", "second subject" });
    expectedValues.put(Core.DESCRIPTION, new String[] { "abstract 1" });
    expectedValues.put(Core.LANGUAGE, new String[] { "english" });
    expectedValues.put(Media.FORMAT, "Shapefile");
    expectedValues.put(Metacard.CONTENT_TYPE, "dataset");
    expectedValues.put(Core.LOCATION, "POLYGON ((5.121 52.139, 4.468 52.139, 4.468 52.517, 5.121 52.517, 5.121 52.139))");
    assertMetacard(mc, expectedValues);
    expectedValues.clear();
    // verify second metacard's values
    mc = metacards.get(1);
    assertThat(mc, not(nullValue()));
    expectedValues = new HashMap<>();
    expectedValues.put(Core.ID, "{23362852-F370-4369-B0B2-BE74B2859614}");
    expectedValues.put(Core.TITLE, "mc2 title");
    expectedModifiedDateStr = "2010-12-15";
    dateFormatter = ISODateTimeFormat.dateOptionalTimeParser();
    expectedModifiedDate = dateFormatter.parseDateTime(expectedModifiedDateStr).toDate();
    expectedValues.put(Core.MODIFIED, expectedModifiedDate);
    expectedValues.put(Topic.CATEGORY, new String[] { "first subject", "subject 2" });
    expectedValues.put(Core.DESCRIPTION, new String[] { "mc2 abstract" });
    expectedValues.put(Core.LANGUAGE, new String[] { "english" });
    expectedValues.put(Media.FORMAT, "Shapefile 2");
    expectedValues.put(Metacard.CONTENT_TYPE, "dataset 2");
    expectedValues.put(Core.LOCATION, "POLYGON ((6.121 53.139, 5.468 53.139, 5.468 53.517, 6.121 53.517, 6.121 53.139))");
    assertMetacard(mc, expectedValues);
    expectedValues.clear();
}
Also used : WstxDriver(com.thoughtworks.xstream.io.xml.WstxDriver) HashMap(java.util.HashMap) XStream(com.thoughtworks.xstream.XStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Matchers.anyString(org.mockito.Matchers.anyString) Date(java.util.Date) Metacard(ddf.catalog.data.Metacard) CswRecordCollection(org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) Test(org.junit.Test)

Aggregations

CswRecordCollection (org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection)51 Test (org.junit.Test)26 ByteArrayInputStream (java.io.ByteArrayInputStream)21 Matchers.anyString (org.mockito.Matchers.anyString)18 GetRecordsType (net.opengis.cat.csw.v_2_0_2.GetRecordsType)17 JAXBElement (javax.xml.bind.JAXBElement)12 Metacard (ddf.catalog.data.Metacard)11 QueryType (net.opengis.cat.csw.v_2_0_2.QueryType)11 XStream (com.thoughtworks.xstream.XStream)10 ArrayList (java.util.ArrayList)10 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)9 QName (javax.xml.namespace.QName)9 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)8 Resource (ddf.catalog.resource.Resource)8 Result (ddf.catalog.data.Result)7 Ignore (jdk.nashorn.internal.ir.annotations.Ignore)7 ElementSetNameType (net.opengis.cat.csw.v_2_0_2.ElementSetNameType)7 GetRecordsResponseType (net.opengis.cat.csw.v_2_0_2.GetRecordsResponseType)7 SearchResultsType (net.opengis.cat.csw.v_2_0_2.SearchResultsType)7 CswException (org.codice.ddf.spatial.ogc.csw.catalog.common.CswException)7