Search in sources :

Example 36 with QueryConstraintType

use of net.opengis.cat.csw.v_2_0_2.QueryConstraintType in project ddf by codice.

the class TransactionMessageBodyReaderTest method testReadMultipleUpdatesFrom.

@Test
public void testReadMultipleUpdatesFrom() throws IOException, ParseException {
    TransactionMessageBodyReader reader = new TransactionMessageBodyReader(cswRecordConverter, CswQueryFactoryTest.getCswMetacardType(), registry);
    CswTransactionRequest request = reader.readFrom(CswTransactionRequest.class, null, null, null, null, IOUtils.toInputStream(MULTIPLE_UPDATES_REQUEST_XML, StandardCharsets.UTF_8));
    assertThat(request, notNullValue());
    assertThat(request.getInsertActions().size(), is(0));
    assertThat(request.getDeleteActions().size(), is(0));
    assertThat(request.getUpdateActions().size(), is(2));
    UpdateAction firstUpdateAction = request.getUpdateActions().get(0);
    assertThat(firstUpdateAction, notNullValue());
    assertThat(firstUpdateAction.getMetacard(), notNullValue());
    Metacard metacard = firstUpdateAction.getMetacard();
    assertThat(metacard.getId(), is("123"));
    assertThat(metacard.getTitle(), is("Aliquam fermentum purus quis arcu"));
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = simpleDateFormat.parse("2008-08-10");
    assertThat(metacard.getModifiedDate(), is(date));
    assertThat(metacard.getLocation(), is("POLYGON ((1.0 2.0, 3.0 2.0, 3.0 4.0, 1.0 4.0, 1.0 2.0))"));
    assertThat(firstUpdateAction.getHandle(), is("handle1"));
    assertThat(firstUpdateAction.getTypeName(), is(CswConstants.CSW_RECORD));
    UpdateAction secondUpdateAction = request.getUpdateActions().get(1);
    assertThat(secondUpdateAction, notNullValue());
    assertThat(secondUpdateAction.getMetacard(), nullValue());
    Map<String, Serializable> recordProperties = secondUpdateAction.getRecordProperties();
    assertThat(recordProperties, notNullValue());
    assertThat(recordProperties.size(), is(1));
    Serializable newSubject = recordProperties.get("topic.category");
    assertThat(newSubject, is("foo"));
    QueryConstraintType constraint = secondUpdateAction.getConstraint();
    assertThat(constraint, notNullValue());
    assertThat(constraint.getCqlText().trim(), is("title = 'bar'"));
    assertThat(secondUpdateAction.getHandle(), is("handle2"));
    assertThat(secondUpdateAction.getTypeName(), is(CswConstants.CSW_RECORD));
    assertThat(request.getService(), is(CswConstants.CSW));
    assertThat(request.getVersion(), is(CswConstants.VERSION_2_0_2));
    assertThat(request.isVerbose(), is(false));
}
Also used : Metacard(ddf.catalog.data.Metacard) Serializable(java.io.Serializable) UpdateAction(org.codice.ddf.spatial.ogc.csw.catalog.actions.UpdateAction) CswTransactionRequest(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.CswTransactionRequest) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) CswQueryFactoryTest(org.codice.ddf.spatial.ogc.csw.catalog.endpoint.CswQueryFactoryTest) Test(org.junit.Test)

Example 37 with QueryConstraintType

use of net.opengis.cat.csw.v_2_0_2.QueryConstraintType in project ddf by codice.

the class GetRecordsRequest method get202RecordsType.

/**
 * Convert the KVP values into a GetRecordsType, validates format of fields and enumeration
 * constraints required to meet the schema requirements of the GetRecordsType. No further
 * validation is done at this point
 *
 * @return GetRecordsType representation of this key-value representation
 * @throws CswException An exception when some field cannot be converted to the equivalent
 *     GetRecordsType value
 */
public GetRecordsType get202RecordsType() throws CswException {
    GetRecordsType getRecords = new GetRecordsType();
    getRecords.setOutputSchema(getOutputSchema());
    getRecords.setRequestId(getRequestId());
    if (getMaxRecords() != null) {
        getRecords.setMaxRecords(getMaxRecords());
    }
    if (getStartPosition() != null) {
        getRecords.setStartPosition(getStartPosition());
    }
    if (getOutputFormat() != null) {
        getRecords.setOutputFormat(getOutputFormat());
    }
    if (getResponseHandler() != null) {
        getRecords.setResponseHandler(Arrays.asList(getResponseHandler()));
    }
    if (getResultType() != null) {
        try {
            getRecords.setResultType(ResultType.fromValue(getResultType()));
        } catch (IllegalArgumentException iae) {
            LOGGER.debug("Failed to find \"{}\" as a valid ResultType", LogSanitizer.sanitize(getResultType()), iae);
            throw new CswException("A CSW getRecords request ResultType must be \"hits\", \"results\", or \"validate\"");
        }
    }
    if (getDistributedSearch() != null && getDistributedSearch()) {
        DistributedSearchType disSearch = new DistributedSearchType();
        disSearch.setHopCount(getHopCount());
        getRecords.setDistributedSearch(disSearch);
    }
    QueryType query = new QueryType();
    Map<String, String> namespaces = parseNamespaces(getNamespace());
    List<QName> typeNames = typeStringToQNames(getTypeNames(), namespaces);
    query.setTypeNames(typeNames);
    if (getElementName() != null && getElementSetName() != null) {
        LOGGER.debug("CSW getRecords request received with mutually exclusive ElementName and SetElementName set");
        throw new CswException("A CSW getRecords request can only have an \"ElementName\" or an \"ElementSetName\"");
    }
    if (getElementName() != null) {
        query.setElementName(typeStringToQNames(getElementName(), namespaces));
    }
    if (getElementSetName() != null) {
        try {
            ElementSetNameType eleSetName = new ElementSetNameType();
            eleSetName.setTypeNames(typeNames);
            eleSetName.setValue(ElementSetType.fromValue(getElementSetName()));
            query.setElementSetName(eleSetName);
        } catch (IllegalArgumentException iae) {
            LOGGER.debug("Failed to find \"{}\" as a valid elementSetType", LogSanitizer.sanitize(getElementSetName()), iae);
            throw new CswException("A CSW getRecords request ElementSetType must be \"brief\", \"summary\", or \"full\"");
        }
    }
    if (getSortBy() != null) {
        SortByType sort = new SortByType();
        List<SortPropertyType> sortProps = new LinkedList<SortPropertyType>();
        String[] sortOptions = getSortBy().split(",");
        for (String sortOption : sortOptions) {
            if (sortOption.lastIndexOf(':') < 1) {
                throw new CswException("Invalid Sort Order format: " + getSortBy());
            }
            SortPropertyType sortProperty = new SortPropertyType();
            PropertyNameType propertyName = new PropertyNameType();
            String propName = StringUtils.substringBeforeLast(sortOption, ":");
            String direction = StringUtils.substringAfterLast(sortOption, ":");
            propertyName.setContent(Arrays.asList((Object) propName));
            SortOrderType sortOrder;
            if (direction.equals("A")) {
                sortOrder = SortOrderType.ASC;
            } else if (direction.equals("D")) {
                sortOrder = SortOrderType.DESC;
            } else {
                throw new CswException("Invalid Sort Order format: " + getSortBy());
            }
            sortProperty.setPropertyName(propertyName);
            sortProperty.setSortOrder(sortOrder);
            sortProps.add(sortProperty);
        }
        sort.setSortProperty(sortProps);
        query.setElementName(typeStringToQNames(getElementName(), namespaces));
        query.setSortBy(sort);
    }
    if (getConstraint() != null) {
        QueryConstraintType queryConstraint = new QueryConstraintType();
        if (getConstraintLanguage().equalsIgnoreCase(CswConstants.CONSTRAINT_LANGUAGE_CQL)) {
            queryConstraint.setCqlText(getConstraint());
        } else if (getConstraintLanguage().equalsIgnoreCase(CswConstants.CONSTRAINT_LANGUAGE_FILTER)) {
            try {
                XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
                xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
                xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
                XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(constraint));
                Unmarshaller unmarshaller = JAX_BCONTEXT.createUnmarshaller();
                @SuppressWarnings("unchecked") JAXBElement<FilterType> jaxbFilter = (JAXBElement<FilterType>) unmarshaller.unmarshal(xmlStreamReader);
                queryConstraint.setFilter(jaxbFilter.getValue());
            } catch (JAXBException e) {
                LOGGER.debug("JAXBException parsing OGC Filter:", e);
                throw new CswException("JAXBException parsing OGC Filter:" + getConstraint());
            } catch (Exception e) {
                LOGGER.debug("Unable to parse OGC Filter:", e);
                throw new CswException("Unable to parse OGC Filter:" + getConstraint());
            }
        } else {
            throw new CswException("Invalid Constraint Language defined: " + getConstraintLanguage());
        }
        query.setConstraint(queryConstraint);
    }
    JAXBElement<QueryType> jaxbQuery = new JAXBElement<QueryType>(new QName(CswConstants.CSW_OUTPUT_SCHEMA), QueryType.class, query);
    getRecords.setAbstractQuery(jaxbQuery);
    return getRecords;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) SortByType(net.opengis.filter.v_1_1_0.SortByType) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) StringReader(java.io.StringReader) ElementSetNameType(net.opengis.cat.csw.v_2_0_2.ElementSetNameType) SortPropertyType(net.opengis.filter.v_1_1_0.SortPropertyType) DistributedSearchType(net.opengis.cat.csw.v_2_0_2.DistributedSearchType) Unmarshaller(javax.xml.bind.Unmarshaller) PropertyNameType(net.opengis.filter.v_1_1_0.PropertyNameType) QName(javax.xml.namespace.QName) JAXBException(javax.xml.bind.JAXBException) GetRecordsType(net.opengis.cat.csw.v_2_0_2.GetRecordsType) JAXBElement(javax.xml.bind.JAXBElement) LinkedList(java.util.LinkedList) JAXBException(javax.xml.bind.JAXBException) SortOrderType(net.opengis.filter.v_1_1_0.SortOrderType) FilterType(net.opengis.filter.v_1_1_0.FilterType) QueryType(net.opengis.cat.csw.v_2_0_2.QueryType) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 38 with QueryConstraintType

use of net.opengis.cat.csw.v_2_0_2.QueryConstraintType in project ddf by codice.

the class TransactionRequestConverterTest method testValidDeleteMarshal.

@Test
public void testValidDeleteMarshal() throws SAXException, IOException, XpathException {
    CswTransactionRequest transactionRequest = new CswTransactionRequest();
    MetacardImpl metacard = new MetacardImpl();
    metacard.setId(METACARD_ID);
    DeleteType deleteType = new DeleteType();
    QueryConstraintType queryConstraintType = new QueryConstraintType();
    queryConstraintType.setCqlText("identifier = " + METACARD_ID);
    deleteType.setConstraint(queryConstraintType);
    DeleteAction deleteAction = new DeleteActionImpl(deleteType, null);
    transactionRequest.getDeleteActions().add(deleteAction);
    transactionRequest.setService(CswConstants.CSW);
    transactionRequest.setVerbose(true);
    transactionRequest.setVersion(CswConstants.VERSION_2_0_2);
    String xml = xStream.toXML(transactionRequest);
    Diff diff = XMLUnit.compareXML(xml, EXPECTED_DELETE_XML);
    assertThat(diff.similar(), is(true));
}
Also used : Diff(org.custommonkey.xmlunit.Diff) CswTransactionRequest(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.CswTransactionRequest) DeleteAction(org.codice.ddf.spatial.ogc.csw.catalog.actions.DeleteAction) DeleteType(net.opengis.cat.csw.v_2_0_2.DeleteType) DeleteActionImpl(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.DeleteActionImpl) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) Test(org.junit.Test)

Example 39 with QueryConstraintType

use of net.opengis.cat.csw.v_2_0_2.QueryConstraintType in project ddf by codice.

the class TransactionRequestConverterTest method testMultipleOperations.

@Test
public void testMultipleOperations() throws Exception {
    CswTransactionRequest transactionRequest = new CswTransactionRequest();
    MetacardImpl metacard = new MetacardImpl();
    metacard.setId(METACARD_ID);
    transactionRequest.setService(CswConstants.CSW);
    transactionRequest.setVerbose(true);
    transactionRequest.setVersion(CswConstants.VERSION_2_0_2);
    InsertAction insertAction = new InsertActionImpl(CswConstants.CSW_METACARD_TYPE_NAME, null, Arrays.asList(metacard));
    transactionRequest.getInsertActions().add(insertAction);
    UpdateAction updateAction = new UpdateActionImpl(metacard, CswConstants.CSW_METACARD_TYPE_NAME, null);
    transactionRequest.getUpdateActions().add(updateAction);
    DeleteType deleteType = new DeleteType();
    QueryConstraintType queryConstraintType = new QueryConstraintType();
    queryConstraintType.setCqlText("identifier = " + METACARD_ID);
    deleteType.setConstraint(queryConstraintType);
    DeleteAction deleteAction = new DeleteActionImpl(deleteType, null);
    transactionRequest.getDeleteActions().add(deleteAction);
    String xml = xStream.toXML(transactionRequest);
    Diff diff = XMLUnit.compareXML(xml, EXPECTED_MULTI_OP_XML);
    assertThat(diff.similar(), is(true));
}
Also used : InsertActionImpl(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.InsertActionImpl) UpdateActionImpl(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.UpdateActionImpl) UpdateAction(org.codice.ddf.spatial.ogc.csw.catalog.actions.UpdateAction) Diff(org.custommonkey.xmlunit.Diff) CswTransactionRequest(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.CswTransactionRequest) InsertAction(org.codice.ddf.spatial.ogc.csw.catalog.actions.InsertAction) DeleteAction(org.codice.ddf.spatial.ogc.csw.catalog.actions.DeleteAction) DeleteType(net.opengis.cat.csw.v_2_0_2.DeleteType) DeleteActionImpl(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.DeleteActionImpl) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) Test(org.junit.Test)

Example 40 with QueryConstraintType

use of net.opengis.cat.csw.v_2_0_2.QueryConstraintType in project ddf by codice.

the class TransactionRequestConverter method parseUpdateAction.

private UpdateAction parseUpdateAction(HierarchicalStreamReader reader, UnmarshallingContext context) {
    Map<String, String> xmlnsAttributeToUriMappings = getXmlnsAttributeToUriMappingsFromContext(context);
    Map<String, String> prefixToUriMappings = getPrefixToUriMappingsFromXmlnsAttributes(xmlnsAttributeToUriMappings);
    String typeName = StringUtils.defaultIfEmpty(reader.getAttribute(CswConstants.TYPE_NAME_PARAMETER), CswConstants.CSW_RECORD);
    String handle = StringUtils.defaultIfEmpty(reader.getAttribute(CswConstants.HANDLE_PARAMETER), "");
    // Move down to the content of the <Update>.
    reader.moveDown();
    UpdateAction updateAction;
    // Do we have a list of <RecordProperty> elements or a new <csw:Record>?
    if (reader.getNodeName().contains("RecordProperty")) {
        Map<String, Serializable> cswRecordProperties = new HashMap<>();
        while (reader.getNodeName().contains("RecordProperty")) {
            String cswField;
            Serializable newValue = null;
            // Move down to the <Name>.
            reader.moveDown();
            if (reader.getNodeName().contains("Name")) {
                String attribute = reader.getValue();
                cswField = CswRecordConverter.getCswAttributeFromAttributeName(attribute);
            } else {
                throw new ConversionException("Missing Parameter Value: missing a Name in a RecordProperty.");
            }
            // Move back up to the <RecordProperty>.
            reader.moveUp();
            String attrName = DefaultCswRecordMap.getDefaultMetacardFieldForPrefixedString(cswField);
            cswRecordProperties.put(attrName, null);
            // Is there a <Value>?
            while (reader.hasMoreChildren()) {
                // Move down to the <Value>.
                reader.moveDown();
                if (reader.getNodeName().contains("Value")) {
                    newValue = getRecordPropertyValue(reader, attrName);
                } else {
                    throw new ConversionException("Invalid Parameter Value: invalid element in a RecordProperty.");
                }
                Serializable currentValue = cswRecordProperties.get(attrName);
                if (currentValue != null) {
                    if (currentValue instanceof List) {
                        ((List) currentValue).add(newValue);
                    } else {
                        LinkedList<Serializable> list = new LinkedList<>();
                        list.add(currentValue);
                        list.add(newValue);
                        cswRecordProperties.put(attrName, list);
                    }
                } else {
                    cswRecordProperties.put(attrName, newValue);
                }
                // Back to the <RecordProperty>.
                reader.moveUp();
            }
            // Back to the <Update>, look for the next <RecordProperty>.
            reader.moveUp();
            if (!reader.hasMoreChildren()) {
                // Constraint, which is required.
                throw new ConversionException("Missing Parameter Value: missing a Constraint.");
            }
            // What's the next element in the <Update>?
            reader.moveDown();
        }
        // Now there should be a <Constraint> element.
        if (reader.getNodeName().contains("Constraint")) {
            StringWriter writer = new StringWriter();
            XStreamAttributeCopier.copyXml(reader, writer, xmlnsAttributeToUriMappings);
            QueryConstraintType constraint = getElementFromXml(writer.toString(), QueryConstraintType.class);
            // For any CSW attributes that map to basic metacard attributes (e.g. title,
            // modified date, etc.), update the basic metacard attributes as well.
            Map<String, String> cswToMetacardAttributeNames = DefaultCswRecordMap.getDefaultCswRecordMap().getCswToMetacardAttributeNames();
            Map<String, Serializable> cswRecordPropertiesWithMetacardAttributes = new HashMap<>(cswRecordProperties);
            for (Entry<String, Serializable> recordProperty : cswRecordProperties.entrySet()) {
                String cswAttributeName = recordProperty.getKey();
                // basic metacard attribute.
                if (cswToMetacardAttributeNames.containsKey(cswAttributeName)) {
                    String metacardAttrName = cswToMetacardAttributeNames.get(cswAttributeName);
                    // If this basic metacard attribute hasn't already been set, set it.
                    if (!cswRecordPropertiesWithMetacardAttributes.containsKey(metacardAttrName)) {
                        Attribute metacardAttr = cswRecordConverter.getMetacardAttributeFromCswAttribute(cswAttributeName, recordProperty.getValue(), metacardAttrName);
                        cswRecordPropertiesWithMetacardAttributes.put(metacardAttrName, metacardAttr.getValue());
                    }
                }
            }
            updateAction = new UpdateActionImpl(cswRecordPropertiesWithMetacardAttributes, typeName, handle, constraint, prefixToUriMappings);
        } else {
            throw new ConversionException("Missing Parameter Value: missing a Constraint.");
        }
    } else {
        context.put(CswConstants.TRANSFORMER_LOOKUP_KEY, TransformerManager.ID);
        context.put(CswConstants.TRANSFORMER_LOOKUP_VALUE, typeName);
        Metacard metacard = (Metacard) context.convertAnother(null, MetacardImpl.class, delegatingTransformer);
        updateAction = new UpdateActionImpl(metacard, typeName, handle);
        // Move back to the <Update>.
        reader.moveUp();
    }
    return updateAction;
}
Also used : ConversionException(com.thoughtworks.xstream.converters.ConversionException) Serializable(java.io.Serializable) UpdateActionImpl(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.UpdateActionImpl) UpdateAction(org.codice.ddf.spatial.ogc.csw.catalog.actions.UpdateAction) HashMap(java.util.HashMap) Attribute(ddf.catalog.data.Attribute) LinkedList(java.util.LinkedList) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) Metacard(ddf.catalog.data.Metacard) StringWriter(java.io.StringWriter) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List)

Aggregations

QueryConstraintType (net.opengis.cat.csw.v_2_0_2.QueryConstraintType)40 ArrayList (java.util.ArrayList)26 Test (org.junit.Test)25 QName (javax.xml.namespace.QName)22 QueryType (net.opengis.cat.csw.v_2_0_2.QueryType)22 JAXBElement (javax.xml.bind.JAXBElement)20 GetRecordsType (net.opengis.cat.csw.v_2_0_2.GetRecordsType)20 CswTransactionRequest (org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.CswTransactionRequest)14 QueryRequest (ddf.catalog.operation.QueryRequest)11 Metacard (ddf.catalog.data.Metacard)10 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)10 Serializable (java.io.Serializable)10 CswRecordCollection (org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection)10 FilterType (net.opengis.filter.v_1_1_0.FilterType)9 QueryImpl (ddf.catalog.operation.impl.QueryImpl)8 HashMap (java.util.HashMap)8 DeleteType (net.opengis.cat.csw.v_2_0_2.DeleteType)8 UpdateAction (org.codice.ddf.spatial.ogc.csw.catalog.actions.UpdateAction)8 Result (ddf.catalog.data.Result)7 ElementSetNameType (net.opengis.cat.csw.v_2_0_2.ElementSetNameType)7