Search in sources :

Example 16 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", 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, Exception {}", 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 17 with QueryConstraintType

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

the class TestTransactionRequestConverter 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 DeleteAction(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.common.transaction.DeleteAction) DeleteType(net.opengis.cat.csw.v_2_0_2.DeleteType) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) Test(org.junit.Test)

Example 18 with QueryConstraintType

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

the class AbstractCswStore method delete.

@Override
public DeleteResponse delete(DeleteRequest deleteRequest) throws IngestException {
    Map<String, Serializable> properties = new HashMap<>();
    validateOperation();
    Subject subject = (Subject) deleteRequest.getPropertyValue(SecurityConstants.SECURITY_SUBJECT);
    Csw csw = factory.getClientForSubject(subject);
    CswTransactionRequest transactionRequest = getTransactionRequest();
    OperationTransaction opTrans = (OperationTransaction) deleteRequest.getPropertyValue(Constants.OPERATION_TRANSACTION_KEY);
    String typeName = schemaTransformerManager.getTransformerIdForSchema(cswSourceConfiguration.getOutputSchema());
    if (typeName == null) {
        typeName = CswConstants.CSW_RECORD;
    }
    for (Serializable itemToDelete : deleteRequest.getAttributeValues()) {
        try {
            DeleteType deleteType = new DeleteType();
            deleteType.setTypeName(typeName);
            QueryConstraintType queryConstraintType = new QueryConstraintType();
            Filter filter;
            FilterType filterType;
            filter = filterBuilder.attribute(deleteRequest.getAttributeName()).is().equalTo().text(itemToDelete.toString());
            filterType = filterAdapter.adapt(filter, cswFilterDelegate);
            queryConstraintType.setCqlText(CswCqlTextFilter.getInstance().getCqlText(filterType));
            deleteType.setConstraint(queryConstraintType);
            DeleteAction deleteAction = new DeleteAction(deleteType, DefaultCswRecordMap.getPrefixToUriMapping());
            transactionRequest.getDeleteActions().add(deleteAction);
        } catch (UnsupportedQueryException e) {
            throw new IngestException("Unsupported Query.", e);
        }
    }
    try {
        TransactionResponseType response = csw.transaction(transactionRequest);
        if (response.getTransactionSummary().getTotalDeleted().intValue() != deleteRequest.getAttributeValues().size()) {
            throw new IngestException("Csw Transaction Failed. Number of metacards deleted did not match number requested.");
        }
    } catch (CswException e) {
        throw new IngestException("Csw Transaction Failed", e);
    }
    return new DeleteResponseImpl(deleteRequest, properties, new ArrayList(opTrans.getPreviousStateMetacards()));
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) Csw(org.codice.ddf.spatial.ogc.csw.catalog.common.Csw) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) CswException(org.codice.ddf.spatial.ogc.csw.catalog.common.CswException) ArrayList(java.util.ArrayList) Subject(ddf.security.Subject) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) TransactionResponseType(net.opengis.cat.csw.v_2_0_2.TransactionResponseType) OperationTransaction(ddf.catalog.operation.OperationTransaction) FilterType(net.opengis.filter.v_1_1_0.FilterType) DeleteResponseImpl(ddf.catalog.operation.impl.DeleteResponseImpl) Filter(org.opengis.filter.Filter) CswTransactionRequest(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.CswTransactionRequest) DeleteAction(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.DeleteAction) DeleteType(net.opengis.cat.csw.v_2_0_2.DeleteType) IngestException(ddf.catalog.source.IngestException)

Example 19 with QueryConstraintType

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

the class AbstractCswSource method createQuery.

private JAXBElement<QueryType> createQuery(Query query, ElementSetType elementSetType, List<QName> elementNames) throws UnsupportedQueryException {
    QueryType queryType = new QueryType();
    QName queryTypeQName = null;
    try {
        if (StringUtils.isNotBlank(cswSourceConfiguration.getQueryTypeName())) {
            String[] parts = cswSourceConfiguration.getQueryTypeName().split(":");
            if (parts.length > 1) {
                queryTypeQName = new QName(cswSourceConfiguration.getQueryTypeNamespace(), parts[1], parts[0]);
            } else {
                queryTypeQName = new QName(cswSourceConfiguration.getQueryTypeNamespace(), cswSourceConfiguration.getQueryTypeName());
            }
        }
    } catch (IllegalArgumentException e) {
        LOGGER.debug("Unable to parse query type QName of {}.  Defaulting to CSW Record", cswSourceConfiguration.getQueryTypeName());
    }
    if (queryTypeQName == null) {
        queryTypeQName = new QName(CswConstants.CSW_OUTPUT_SCHEMA, CswConstants.CSW_RECORD_LOCAL_NAME, CswConstants.CSW_NAMESPACE_PREFIX);
    }
    queryType.setTypeNames(Arrays.asList(queryTypeQName));
    if (null != elementSetType) {
        queryType.setElementSetName(createElementSetName(elementSetType));
    } else if (!CollectionUtils.isEmpty(elementNames)) {
        queryType.setElementName(elementNames);
    } else {
        queryType.setElementSetName(createElementSetName(ElementSetType.FULL));
    }
    SortByType sortBy = createSortBy(query);
    if (sortBy != null) {
        queryType.setSortBy(sortBy);
    }
    QueryConstraintType constraint = createQueryConstraint(query);
    if (null != constraint) {
        queryType.setConstraint(constraint);
    }
    ObjectFactory objectFactory = new ObjectFactory();
    return objectFactory.createQuery(queryType);
}
Also used : ObjectFactory(net.opengis.cat.csw.v_2_0_2.ObjectFactory) QName(javax.xml.namespace.QName) SortByType(net.opengis.filter.v_1_1_0.SortByType) QueryType(net.opengis.cat.csw.v_2_0_2.QueryType) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType)

Example 20 with QueryConstraintType

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

the class TestCswEndpoint method testUpdateTransactionWithConstraint.

@Test
public void testUpdateTransactionWithConstraint() throws CswException, FederationException, IngestException, SourceUnavailableException, UnsupportedQueryException {
    List<Result> results = new ArrayList<>();
    MetacardImpl firstResult = new MetacardImpl();
    firstResult.setId("123");
    firstResult.setTitle("Title one");
    firstResult.setAttribute("subject", "Subject one");
    results.add(new ResultImpl(firstResult));
    MetacardImpl secondResult = new MetacardImpl();
    secondResult.setId("789");
    secondResult.setTitle("Title two");
    secondResult.setAttribute("subject", "Subject two");
    results.add(new ResultImpl(secondResult));
    QueryResponse queryResponse = new QueryResponseImpl(null, results, results.size());
    doReturn(queryResponse).when(catalogFramework).query(any(QueryRequest.class));
    List<Update> updatedMetacards = new ArrayList<>();
    updatedMetacards.add(new UpdateImpl(new MetacardImpl(), new MetacardImpl()));
    updatedMetacards.add(new UpdateImpl(new MetacardImpl(), new MetacardImpl()));
    UpdateResponse updateResponse = new UpdateResponseImpl(null, null, updatedMetacards);
    doReturn(updateResponse).when(catalogFramework).update(any(UpdateRequest.class));
    Map<String, Serializable> recordProperties = new HashMap<>();
    recordProperties.put("title", "foo");
    recordProperties.put("subject", "bar");
    QueryConstraintType constraint = new QueryConstraintType();
    constraint.setCqlText("title = 'fake'");
    UpdateAction updateAction = new UpdateAction(recordProperties, CswConstants.CSW_RECORD, "", constraint, DefaultCswRecordMap.getDefaultCswRecordMap().getPrefixToUriMapping());
    CswTransactionRequest updateRequest = new CswTransactionRequest();
    updateRequest.getUpdateActions().add(updateAction);
    updateRequest.setVersion(CswConstants.VERSION_2_0_2);
    updateRequest.setService(CswConstants.CSW);
    updateRequest.setVerbose(false);
    TransactionResponseType response = csw.transaction(updateRequest);
    assertThat(response, notNullValue());
    TransactionSummaryType summary = response.getTransactionSummary();
    assertThat(summary, notNullValue());
    assertThat(summary.getTotalDeleted().intValue(), is(0));
    assertThat(summary.getTotalInserted().intValue(), is(0));
    assertThat(summary.getTotalUpdated().intValue(), is(2));
    verifyMarshalResponse(response, "net.opengis.cat.csw.v_2_0_2:net.opengis.filter.v_1_1_0:net.opengis.gml.v_3_1_1", cswQnameOutPutSchema);
    ArgumentCaptor<UpdateRequest> updateRequestArgumentCaptor = ArgumentCaptor.forClass(UpdateRequest.class);
    verify(catalogFramework, times(1)).update(updateRequestArgumentCaptor.capture());
    UpdateRequest actualUpdateRequest = updateRequestArgumentCaptor.getValue();
    List<Map.Entry<Serializable, Metacard>> updates = actualUpdateRequest.getUpdates();
    assertThat(updates.size(), is(2));
    Metacard firstUpdate = updates.get(0).getValue();
    assertThat(firstUpdate.getId(), is("123"));
    assertThat(firstUpdate.getTitle(), is("foo"));
    assertThat(firstUpdate.getAttribute("subject").getValue(), is("bar"));
    Metacard secondUpdate = updates.get(1).getValue();
    assertThat(secondUpdate.getId(), is("789"));
    assertThat(secondUpdate.getTitle(), is("foo"));
    assertThat(secondUpdate.getAttribute("subject").getValue(), is("bar"));
}
Also used : UpdateImpl(ddf.catalog.operation.impl.UpdateImpl) Serializable(java.io.Serializable) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ResultImpl(ddf.catalog.data.impl.ResultImpl) Update(ddf.catalog.operation.Update) TransactionSummaryType(net.opengis.cat.csw.v_2_0_2.TransactionSummaryType) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) Result(ddf.catalog.data.Result) TransactionResponseType(net.opengis.cat.csw.v_2_0_2.TransactionResponseType) UpdateResponse(ddf.catalog.operation.UpdateResponse) UpdateResponseImpl(ddf.catalog.operation.impl.UpdateResponseImpl) QueryRequest(ddf.catalog.operation.QueryRequest) UpdateRequest(ddf.catalog.operation.UpdateRequest) UpdateAction(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.UpdateAction) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) QueryResponseImpl(ddf.catalog.operation.impl.QueryResponseImpl) Metacard(ddf.catalog.data.Metacard) CswTransactionRequest(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.CswTransactionRequest) QueryResponse(ddf.catalog.operation.QueryResponse) Test(org.junit.Test)

Aggregations

QueryConstraintType (net.opengis.cat.csw.v_2_0_2.QueryConstraintType)24 ArrayList (java.util.ArrayList)17 QName (javax.xml.namespace.QName)14 QueryType (net.opengis.cat.csw.v_2_0_2.QueryType)14 JAXBElement (javax.xml.bind.JAXBElement)13 GetRecordsType (net.opengis.cat.csw.v_2_0_2.GetRecordsType)13 Test (org.junit.Test)12 QueryImpl (ddf.catalog.operation.impl.QueryImpl)7 FilterType (net.opengis.filter.v_1_1_0.FilterType)7 CswTransactionRequest (org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.CswTransactionRequest)7 Metacard (ddf.catalog.data.Metacard)5 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)5 QueryRequest (ddf.catalog.operation.QueryRequest)5 Serializable (java.io.Serializable)5 UpdateAction (org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.UpdateAction)5 HashMap (java.util.HashMap)4 DeleteType (net.opengis.cat.csw.v_2_0_2.DeleteType)4 DeleteAction (org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.DeleteAction)4 Result (ddf.catalog.data.Result)3 QueryResponse (ddf.catalog.operation.QueryResponse)3