Search in sources :

Example 26 with UnsupportedQueryException

use of ddf.catalog.source.UnsupportedQueryException in project ddf by codice.

the class AbstractCswStore method create.

@Override
public CreateResponse create(CreateRequest createRequest) throws IngestException {
    Map<String, Serializable> properties = new HashMap<>();
    validateOperation();
    Subject subject = (Subject) createRequest.getPropertyValue(SecurityConstants.SECURITY_SUBJECT);
    Csw csw = factory.getClientForSubject(subject);
    CswTransactionRequest transactionRequest = getTransactionRequest();
    List<Metacard> metacards = createRequest.getMetacards();
    List<String> metacardIds = metacards.stream().map(Metacard::getId).collect(Collectors.toList());
    List<Metacard> createdMetacards = new ArrayList<>();
    List<Filter> createdMetacardFilters;
    HashSet<ProcessingDetails> errors = new HashSet<>();
    String insertTypeName = schemaTransformerManager.getTransformerIdForSchema(cswSourceConfiguration.getOutputSchema());
    if (insertTypeName == null) {
        throw new IngestException("Could not find transformer for output schema " + cswSourceConfiguration.getOutputSchema());
    }
    transactionRequest.getInsertActions().add(new InsertAction(insertTypeName, null, metacards));
    try {
        TransactionResponseType response = csw.transaction(transactionRequest);
        Set<String> processedIds = new HashSet<>();
        //dive down into the response to get the created ID's. We need these so we can query
        //the source again to get the created metacards and put them in the result
        createdMetacardFilters = response.getInsertResult().stream().map(InsertResultType::getBriefRecord).flatMap(Collection::stream).map(BriefRecordType::getIdentifier).flatMap(Collection::stream).map(JAXBElement::getValue).map(SimpleLiteral::getContent).flatMap(Collection::stream).map(id -> {
            processedIds.add(id);
            return filterBuilder.attribute(Core.ID).is().equalTo().text(id);
        }).collect(Collectors.toList());
        metacardIds.removeAll(processedIds);
        errors.addAll(metacardIds.stream().map(id -> new ProcessingDetailsImpl(id, null, "Failed to create metacard")).collect(Collectors.toList()));
    } catch (CswException e) {
        throw new IngestException("Csw Transaction Failed : ", e);
    }
    try {
        createdMetacards = transactionQuery(createdMetacardFilters, subject);
    } catch (UnsupportedQueryException e) {
        errors.add(new ProcessingDetailsImpl(this.getId(), e, "Failed to retrieve newly created metacards"));
    }
    return new CreateResponseImpl(createRequest, properties, createdMetacards, errors);
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) ArrayList(java.util.ArrayList) CswException(org.codice.ddf.spatial.ogc.csw.catalog.common.CswException) ProcessingDetailsImpl(ddf.catalog.operation.impl.ProcessingDetailsImpl) TransactionResponseType(net.opengis.cat.csw.v_2_0_2.TransactionResponseType) ProcessingDetails(ddf.catalog.operation.ProcessingDetails) IngestException(ddf.catalog.source.IngestException) SimpleLiteral(net.opengis.cat.csw.v_2_0_2.dc.elements.SimpleLiteral) HashSet(java.util.HashSet) Csw(org.codice.ddf.spatial.ogc.csw.catalog.common.Csw) Subject(ddf.security.Subject) Metacard(ddf.catalog.data.Metacard) Filter(org.opengis.filter.Filter) CswTransactionRequest(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.CswTransactionRequest) InsertAction(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.InsertAction) Collection(java.util.Collection) CreateResponseImpl(ddf.catalog.operation.impl.CreateResponseImpl)

Example 27 with UnsupportedQueryException

use of ddf.catalog.source.UnsupportedQueryException in project ddf by codice.

the class CswCqlTextFilter method getCqlText.

public String getCqlText(FilterType filterType) throws UnsupportedQueryException {
    Parser parser = new Parser(new OGCConfiguration());
    try {
        StringReader reader = new StringReader(marshalFilterType(filterType));
        Object parsedFilter = parser.parse(reader);
        if (parsedFilter instanceof Filter) {
            Filter filterToCql = (Filter) parsedFilter;
            LOGGER.debug("Filter to Convert to CQL => {}", filterToCql);
            String cql = ECQL.toCQL(filterToCql);
            LOGGER.debug("Generated CQL from Filter => {}", cql);
            return cql;
        } else {
            throw new UnsupportedQueryException("Query did not produce a valid filter.");
        }
    } catch (IOException | SAXException | ParserConfigurationException | JAXBException e) {
        throw new UnsupportedQueryException("Unable to create CQL Filter.", e);
    }
}
Also used : Filter(org.opengis.filter.Filter) OGCConfiguration(org.geotools.filter.v1_1.OGCConfiguration) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) JAXBException(javax.xml.bind.JAXBException) StringReader(java.io.StringReader) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Parser(org.geotools.xml.Parser) SAXException(org.xml.sax.SAXException)

Example 28 with UnsupportedQueryException

use of ddf.catalog.source.UnsupportedQueryException in project ddf by codice.

the class AbstractCswSource method query.

protected SourceResponse query(QueryRequest queryRequest, ElementSetType elementSetName, List<QName> elementNames, Csw csw) throws UnsupportedQueryException {
    Query query = queryRequest.getQuery();
    LOGGER.debug("{}: Received query:\n{}", cswSourceConfiguration.getId(), query);
    GetRecordsType getRecordsType = createGetRecordsRequest(query, elementSetName, elementNames);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("{}: GetRecords request:\n {}", cswSourceConfiguration.getId(), getGetRecordsTypeAsXml(getRecordsType));
    }
    LOGGER.debug("{}: Sending query to: {}", cswSourceConfiguration.getId(), cswSourceConfiguration.getCswUrl());
    List<Result> results;
    Long totalHits;
    try {
        CswRecordCollection cswRecordCollection = csw.getRecords(getRecordsType);
        if (cswRecordCollection == null) {
            throw new UnsupportedQueryException("Invalid results returned from server");
        }
        this.availabilityTask.updateLastAvailableTimestamp(System.currentTimeMillis());
        LOGGER.debug("{}: Received [{}] record(s) of the [{}] record(s) matched from {}.", cswSourceConfiguration.getId(), cswRecordCollection.getNumberOfRecordsReturned(), cswRecordCollection.getNumberOfRecordsMatched(), cswSourceConfiguration.getCswUrl());
        results = createResults(cswRecordCollection);
        totalHits = cswRecordCollection.getNumberOfRecordsMatched();
    } catch (CswException cswe) {
        LOGGER.info(CSW_SERVER_ERROR, cswe);
        throw new UnsupportedQueryException(CSW_SERVER_ERROR, cswe);
    } catch (WebApplicationException wae) {
        String msg = handleWebApplicationException(wae);
        throw new UnsupportedQueryException(msg, wae);
    } catch (Exception ce) {
        String msg = handleClientException(ce);
        throw new UnsupportedQueryException(msg, ce);
    }
    LOGGER.debug("{}: Adding {} result(s) to the source response.", cswSourceConfiguration.getId(), results.size());
    SourceResponseImpl sourceResponse = new SourceResponseImpl(queryRequest, results, totalHits);
    addContentTypes(sourceResponse);
    return sourceResponse;
}
Also used : Query(ddf.catalog.operation.Query) WebApplicationException(javax.ws.rs.WebApplicationException) SourceResponseImpl(ddf.catalog.operation.impl.SourceResponseImpl) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) CswRecordCollection(org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection) CswException(org.codice.ddf.spatial.ogc.csw.catalog.common.CswException) GetRecordsType(net.opengis.cat.csw.v_2_0_2.GetRecordsType) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) WebApplicationException(javax.ws.rs.WebApplicationException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) CswException(org.codice.ddf.spatial.ogc.csw.catalog.common.CswException) JAXBException(javax.xml.bind.JAXBException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) Result(ddf.catalog.data.Result)

Example 29 with UnsupportedQueryException

use of ddf.catalog.source.UnsupportedQueryException in project ddf by codice.

the class Historian method version.

/**
     * Versions updated {@link Metacard}s and {@link ContentItem}s.
     *
     * @param streamUpdateRequest   Needed to pass {@link ddf.catalog.core.versioning.MetacardVersion#SKIP_VERSIONING}
     *                              flag into downstream update
     * @param updateStorageResponse Versions this response's updated items
     * @return the update response originally passed in
     * @throws UnsupportedQueryException
     * @throws SourceUnavailableException
     * @throws IngestException
     */
public UpdateStorageResponse version(UpdateStorageRequest streamUpdateRequest, UpdateStorageResponse updateStorageResponse, UpdateResponse updateResponse) throws UnsupportedQueryException, SourceUnavailableException, IngestException {
    if (doSkip(updateStorageResponse)) {
        return updateStorageResponse;
    }
    setSkipFlag(streamUpdateRequest);
    setSkipFlag(updateStorageResponse);
    List<Metacard> updatedMetacards = updateStorageResponse.getUpdatedContentItems().stream().filter(ci -> StringUtils.isBlank(ci.getQualifier())).map(ContentItem::getMetacard).filter(Objects::nonNull).filter(isNotVersionNorDeleted).collect(Collectors.toList());
    Map<String, Metacard> originalMetacards = query(forIds(updatedMetacards.stream().map(Metacard::getId).collect(Collectors.toList())));
    Collection<ReadStorageRequest> ids = getReadStorageRequests(updatedMetacards);
    Map<String, List<ContentItem>> content = getContent(ids);
    Function<String, Action> getAction = (id) -> content.containsKey(id) ? Action.VERSIONED_CONTENT : Action.VERSIONED;
    Map<String, Metacard> versionMetacards = getVersionMetacards(originalMetacards.values(), getAction, (Subject) updateResponse.getProperties().get(SecurityConstants.SECURITY_SUBJECT));
    CreateStorageResponse createStorageResponse = versionContentItems(content, versionMetacards);
    if (createStorageResponse == null) {
        LOGGER.debug("Could not version content items.");
        return updateStorageResponse;
    }
    setResourceUriForContent(/*mutable*/
    versionMetacards, createStorageResponse);
    storeVersionMetacards(versionMetacards);
    return updateStorageResponse;
}
Also used : UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) LoggerFactory(org.slf4j.LoggerFactory) StringUtils(org.apache.commons.lang3.StringUtils) ReadStorageRequest(ddf.catalog.content.operation.ReadStorageRequest) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) DeletedMetacardImpl(ddf.catalog.core.versioning.impl.DeletedMetacardImpl) Map(java.util.Map) Action(ddf.catalog.core.versioning.MetacardVersion.Action) SubjectUtils(ddf.security.SubjectUtils) Bundle(org.osgi.framework.Bundle) UpdateStorageResponse(ddf.catalog.content.operation.UpdateStorageResponse) MetacardVersionImpl(ddf.catalog.core.versioning.impl.MetacardVersionImpl) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) BundleContext(org.osgi.framework.BundleContext) MetacardType(ddf.catalog.data.MetacardType) Objects(java.util.Objects) StorageException(ddf.catalog.content.StorageException) List(java.util.List) Operation(ddf.catalog.operation.Operation) CreateStorageResponse(ddf.catalog.content.operation.CreateStorageResponse) Optional(java.util.Optional) UpdateResponse(ddf.catalog.operation.UpdateResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) FilterBuilder(ddf.catalog.filter.FilterBuilder) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) DeleteResponse(ddf.catalog.operation.DeleteResponse) Function(java.util.function.Function) Update(ddf.catalog.operation.Update) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) SKIP_VERSIONING(ddf.catalog.core.versioning.MetacardVersion.SKIP_VERSIONING) ContentItem(ddf.catalog.content.data.ContentItem) CreateResponse(ddf.catalog.operation.CreateResponse) Metacard(ddf.catalog.data.Metacard) SecurityConstants(ddf.security.SecurityConstants) StorageProvider(ddf.catalog.content.StorageProvider) ByteSource(com.google.common.io.ByteSource) Result(ddf.catalog.data.Result) Hashtable(java.util.Hashtable) Nullable(javax.annotation.Nullable) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Logger(org.slf4j.Logger) Security(org.codice.ddf.security.common.Security) IngestException(ddf.catalog.source.IngestException) IOException(java.io.IOException) Subject(ddf.security.Subject) TimeUnit(java.util.concurrent.TimeUnit) StorageRequest(ddf.catalog.content.operation.StorageRequest) ReadStorageRequestImpl(ddf.catalog.content.operation.impl.ReadStorageRequestImpl) SourceResponse(ddf.catalog.operation.SourceResponse) CatalogProvider(ddf.catalog.source.CatalogProvider) Filter(org.opengis.filter.Filter) Collections(java.util.Collections) FrameworkUtil(org.osgi.framework.FrameworkUtil) InputStream(java.io.InputStream) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) ReadStorageResponse(ddf.catalog.content.operation.ReadStorageResponse) Action(ddf.catalog.core.versioning.MetacardVersion.Action) CreateStorageResponse(ddf.catalog.content.operation.CreateStorageResponse) Metacard(ddf.catalog.data.Metacard) ReadStorageRequest(ddf.catalog.content.operation.ReadStorageRequest) Objects(java.util.Objects) List(java.util.List) ArrayList(java.util.ArrayList)

Example 30 with UnsupportedQueryException

use of ddf.catalog.source.UnsupportedQueryException in project ddf by codice.

the class CswEndpoint method getRecordById.

@Override
@GET
@Consumes({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
public CswRecordCollection getRecordById(@QueryParam("") GetRecordByIdRequest 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);
    if (StringUtils.isNotBlank(request.getId())) {
        List<String> ids = Arrays.asList(request.getId().split(CswConstants.COMMA));
        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 ID: {}", 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 (StringUtils.isNotBlank(request.getElementSetName())) {
            response.setElementSetType(ElementSetType.fromValue(request.getElementSetName()));
        } else {
            response.setElementSetType(ElementSetType.SUMMARY);
        }
        LOGGER.debug("{} successfully retrieved record(s): {}", request.getRequest(), 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) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

UnsupportedQueryException (ddf.catalog.source.UnsupportedQueryException)85 QueryRequestImpl (ddf.catalog.operation.impl.QueryRequestImpl)34 FederationException (ddf.catalog.federation.FederationException)31 QueryRequest (ddf.catalog.operation.QueryRequest)31 Metacard (ddf.catalog.data.Metacard)28 QueryImpl (ddf.catalog.operation.impl.QueryImpl)27 Filter (org.opengis.filter.Filter)27 ArrayList (java.util.ArrayList)26 Result (ddf.catalog.data.Result)25 QueryResponse (ddf.catalog.operation.QueryResponse)25 SourceUnavailableException (ddf.catalog.source.SourceUnavailableException)25 Test (org.junit.Test)21 SourceResponse (ddf.catalog.operation.SourceResponse)16 IngestException (ddf.catalog.source.IngestException)15 IOException (java.io.IOException)15 Query (ddf.catalog.operation.Query)12 CreateResponse (ddf.catalog.operation.CreateResponse)10 GeotoolsFilterAdapterImpl (ddf.catalog.filter.proxy.adapter.GeotoolsFilterAdapterImpl)9 ResourceNotFoundException (ddf.catalog.resource.ResourceNotFoundException)9 Subject (ddf.security.Subject)9