Search in sources :

Example 11 with QueryRequest

use of org.forgerock.json.resource.QueryRequest in project OpenAM by OpenRock.

the class ResourceSetService method getResourceSets.

/**
     * Queries resource sets across the resource set store and UMA policy store.
     *
     * @param context             The context.
     * @param realm               The realm.
     * @param query               The aggregated query.
     * @param resourceOwnerId     The resource owner id.
     * @param augmentWithPolicies {@code true} to pull in UMA policies into the resource set.
     * @return A Promise containing the Resource Sets or a ResourceException.
     */
Promise<Collection<ResourceSetDescription>, ResourceException> getResourceSets(final Context context, String realm, final ResourceSetWithPolicyQuery query, final String resourceOwnerId, final boolean augmentWithPolicies) {
    final Set<ResourceSetDescription> resourceSets;
    try {
        resourceSets = new ResourceSetSharedFilter(this, resourceOwnerId, realm).filter(resourceSetStoreFactory.create(realm).query(query.getResourceSetQuery()));
    } catch (ServerException e) {
        return new InternalServerErrorException(e).asPromise();
    }
    QueryRequest policyQuery = newQueryRequest("").setQueryId("searchAll");
    policyQuery.setQueryFilter(QueryFilter.<JsonPointer>alwaysTrue());
    return getSharedResourceSets(context, policyQuery, resourceOwnerId).thenAsync(new AsyncFunction<Set<ResourceSetDescription>, Collection<ResourceSetDescription>, ResourceException>() {

        @Override
        public Promise<Collection<ResourceSetDescription>, ResourceException> apply(final Set<ResourceSetDescription> sharedResourceSets) {
            //combine the owned ResourceSets with the shared ones, then filter based on the query
            sharedResourceSets.addAll(resourceSets);
            final Collection<ResourceSetDescription> filteredResourceSets = filterPolicies(resourceSets, query);
            Promise<Collection<ResourceSetDescription>, ResourceException> resourceSetsPromise;
            if (query.getPolicyQuery() != null) {
                QueryRequest policyQuery = newQueryRequest("").setQueryFilter(query.getPolicyQuery());
                resourceSetsPromise = policyService.queryPolicies(context, policyQuery).thenAsync(new AsyncFunction<Pair<QueryResponse, Collection<UmaPolicy>>, Collection<ResourceSetDescription>, ResourceException>() {

                    @Override
                    public Promise<Collection<ResourceSetDescription>, ResourceException> apply(Pair<QueryResponse, Collection<UmaPolicy>> result) throws ResourceException {
                        try {
                            return newResultPromise(combine(context, query, filteredResourceSets, result.getSecond(), augmentWithPolicies, resourceOwnerId));
                        } catch (org.forgerock.oauth2.core.exceptions.NotFoundException e) {
                            return new InternalServerErrorException(e).asPromise();
                        } catch (ServerException e) {
                            return new InternalServerErrorException(e).asPromise();
                        }
                    }
                });
            } else {
                if (augmentWithPolicies) {
                    List<Promise<ResourceSetDescription, ResourceException>> promises = new ArrayList<>();
                    PromiseImpl<ResourceSetDescription, ResourceException> kicker = PromiseImpl.create();
                    promises.add(kicker);
                    for (ResourceSetDescription resourceSet : filteredResourceSets) {
                        promises.add(augmentWithPolicy(context, resourceSet.getId(), resourceSet));
                    }
                    resourceSetsPromise = Promises.when(promises).thenAsync(new AsyncFunction<List<ResourceSetDescription>, Collection<ResourceSetDescription>, ResourceException>() {

                        @Override
                        public Promise<Collection<ResourceSetDescription>, ResourceException> apply(List<ResourceSetDescription> resourceSets) {
                            Collection<ResourceSetDescription> resourceSetDescriptions = new HashSet<>();
                            for (ResourceSetDescription rs : filteredResourceSets) {
                                if (rs != null) {
                                    resourceSetDescriptions.add(rs);
                                }
                            }
                            return newResultPromise(resourceSetDescriptions);
                        }
                    });
                    kicker.handleResult(null);
                } else {
                    resourceSetsPromise = newResultPromise(filteredResourceSets);
                }
            }
            return resourceSetsPromise;
        }
    });
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) ResourceException(org.forgerock.json.resource.ResourceException) List(java.util.List) ArrayList(java.util.ArrayList) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) Pair(org.forgerock.util.Pair) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) Requests.newQueryRequest(org.forgerock.json.resource.Requests.newQueryRequest) QueryRequest(org.forgerock.json.resource.QueryRequest) PromiseImpl(org.forgerock.util.promise.PromiseImpl) ResourceSetSharedFilter(org.forgerock.openam.uma.ResourceSetSharedFilter) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) QueryResponse(org.forgerock.json.resource.QueryResponse) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) Collection(java.util.Collection)

Example 12 with QueryRequest

use of org.forgerock.json.resource.QueryRequest in project OpenAM by OpenRock.

the class UmaPolicyServiceImpl method queryPolicies.

/**
     * {@inheritDoc}
     */
@Override
public Promise<Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException> queryPolicies(final Context context, final QueryRequest umaQueryRequest) {
    if (umaQueryRequest.getQueryExpression() != null) {
        return new BadRequestException("Query expressions not supported").asPromise();
    }
    QueryRequest request = Requests.newQueryRequest("");
    final AggregateQuery<QueryFilter<JsonPointer>, QueryFilter<JsonPointer>> filter = umaQueryRequest.getQueryFilter().accept(new AggregateUmaPolicyQueryFilter(), new AggregateQuery<QueryFilter<JsonPointer>, QueryFilter<JsonPointer>>());
    String queryId = umaQueryRequest.getQueryId();
    if (queryId != null && queryId.equals("searchAll")) {
        request.setQueryFilter(QueryFilter.<JsonPointer>alwaysTrue());
    } else {
        String resourceOwnerUid = getResourceOwnerUid(context);
        if (filter.getFirstQuery() == null) {
            request.setQueryFilter(QueryFilter.equalTo(new JsonPointer("createdBy"), resourceOwnerUid));
        } else {
            request.setQueryFilter(QueryFilter.and(QueryFilter.equalTo(new JsonPointer("createdBy"), resourceOwnerUid), filter.getFirstQuery()));
        }
    }
    return policyResourceDelegate.queryPolicies(context, request).thenAsync(new AsyncFunction<Pair<QueryResponse, List<ResourceResponse>>, Collection<UmaPolicy>, ResourceException>() {

        @Override
        public Promise<Collection<UmaPolicy>, ResourceException> apply(Pair<QueryResponse, List<ResourceResponse>> value) {
            Map<String, Set<ResourceResponse>> policyMapping = new HashMap<>();
            for (ResourceResponse policy : value.getSecond()) {
                String resource = policy.getContent().get("resources").asList(String.class).get(0);
                if (!resource.startsWith(UMA_POLICY_SCHEME)) {
                    continue;
                }
                resource = resource.replaceFirst(UMA_POLICY_SCHEME, "");
                if (resource.indexOf(":") > 0) {
                    resource = resource.substring(0, resource.indexOf(":"));
                }
                Set<ResourceResponse> mapping = policyMapping.get(resource);
                if (mapping == null) {
                    mapping = new HashSet<>();
                    policyMapping.put(resource, mapping);
                }
                mapping.add(policy);
            }
            try {
                Collection<UmaPolicy> umaPolicies = new HashSet<>();
                for (Map.Entry<String, Set<ResourceResponse>> entry : policyMapping.entrySet()) {
                    ResourceSetDescription resourceSet = getResourceSetDescription(entry.getKey(), context);
                    UmaPolicy umaPolicy = UmaPolicy.fromUnderlyingPolicies(resourceSet, entry.getValue());
                    resolveUIDToUsername(umaPolicy.asJson());
                    umaPolicies.add(umaPolicy);
                }
                return newResultPromise(umaPolicies);
            } catch (ResourceException e) {
                return e.asPromise();
            }
        }
    }).thenAsync(new AsyncFunction<Collection<UmaPolicy>, Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException>() {

        @Override
        public Promise<Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException> apply(Collection<UmaPolicy> policies) {
            Collection<UmaPolicy> results = policies;
            if (filter.getSecondQuery() != null) {
                PolicySearch search = filter.getSecondQuery().accept(new UmaPolicyQueryFilterVisitor(), new PolicySearch(policies));
                if (AggregateQuery.Operator.AND.equals(filter.getOperator())) {
                    results.retainAll(search.getPolicies());
                }
            }
            int pageSize = umaQueryRequest.getPageSize();
            String pagedResultsCookie = umaQueryRequest.getPagedResultsCookie();
            int pagedResultsOffset = umaQueryRequest.getPagedResultsOffset();
            Collection<UmaPolicy> pagedPolicies = new HashSet<UmaPolicy>();
            int count = 0;
            for (UmaPolicy policy : results) {
                if (count >= pagedResultsOffset * pageSize) {
                    pagedPolicies.add(policy);
                }
                count++;
            }
            int remainingPagedResults = results.size() - pagedPolicies.size();
            if (pageSize > 0) {
                remainingPagedResults /= pageSize;
            }
            return newResultPromise(Pair.of(newQueryResponse(pagedResultsCookie, CountPolicy.EXACT, remainingPagedResults), pagedPolicies));
        }
    });
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) JsonPointer(org.forgerock.json.JsonPointer) AsyncFunction(org.forgerock.util.AsyncFunction) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) List(java.util.List) ArrayList(java.util.ArrayList) ResourceException(org.forgerock.json.resource.ResourceException) PolicySearch(org.forgerock.openam.uma.PolicySearch) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) Pair(org.forgerock.util.Pair) HashSet(java.util.HashSet) UmaPolicyQueryFilterVisitor(org.forgerock.openam.uma.UmaPolicyQueryFilterVisitor) QueryRequest(org.forgerock.json.resource.QueryRequest) Promise(org.forgerock.util.promise.Promise) QueryFilter(org.forgerock.util.query.QueryFilter) ResourceResponse(org.forgerock.json.resource.ResourceResponse) Responses.newQueryResponse(org.forgerock.json.resource.Responses.newQueryResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) BadRequestException(org.forgerock.json.resource.BadRequestException) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap)

Example 13 with QueryRequest

use of org.forgerock.json.resource.QueryRequest in project OpenAM by OpenRock.

the class Requester method query.

/**
     * Request to perform a query at a specified endpoint.
     *
     * @param location Endpoint destination of this request. May not be null.
     * @param queryId Specific query ID to perform. May be null.
     * @param context Context of this request.
     * @return The {@link org.forgerock.json.JsonValue} returned from the endpoint.
     * @throws ResourceException If any exception occurred during processing.
     */
public JsonValue query(String location, String queryId, Context context) throws ResourceException {
    Reject.ifTrue(StringUtils.isEmpty(location), "The endpoint destination may not be null or empty.");
    final Router rootRouter = router.get();
    final QueryRequest queryRequest = Requests.newQueryRequest(location);
    if (queryId != null) {
        queryRequest.setQueryId(queryId);
    }
    final InMemoryQueryResourceHandler resourceHandler = new InMemoryQueryResourceHandler();
    return rootRouter.handleQuery(context, queryRequest, resourceHandler).thenAsync(new AsyncFunction<QueryResponse, JsonValue, ResourceException>() {

        @Override
        public Promise<JsonValue, ResourceException> apply(QueryResponse value) {
            final JsonArray responses = JsonValueBuilder.jsonValue().array("results");
            for (ResourceResponse resource : resourceHandler.getResources()) {
                responses.add(resource.getContent());
            }
            return newResultPromise(responses.build().build());
        }
    }).getOrThrowUninterruptibly();
}
Also used : JsonArray(org.forgerock.openam.utils.JsonArray) QueryRequest(org.forgerock.json.resource.QueryRequest) ResourceResponse(org.forgerock.json.resource.ResourceResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) JsonValue(org.forgerock.json.JsonValue) Router(org.forgerock.json.resource.Router) ResourceException(org.forgerock.json.resource.ResourceException) AsyncFunction(org.forgerock.util.AsyncFunction)

Example 14 with QueryRequest

use of org.forgerock.json.resource.QueryRequest in project OpenAM by OpenRock.

the class ResourceSetResourceTest method queryShouldNotBeSupported.

@Test
public void queryShouldNotBeSupported() {
    //Given
    Context context = mock(Context.class);
    QueryRequest request = mock(QueryRequest.class);
    QueryResourceHandler handler = mock(QueryResourceHandler.class);
    given(request.getQueryFilter()).willReturn(QueryFilter.equalTo(new JsonPointer("/fred"), 5));
    //When
    Promise<QueryResponse, ResourceException> promise = resource.queryCollection(context, request, handler);
    //Then
    assertThat(promise).failedWithException().isInstanceOf(NotSupportedException.class);
}
Also used : Context(org.forgerock.services.context.Context) QueryRequest(org.forgerock.json.resource.QueryRequest) QueryResponse(org.forgerock.json.resource.QueryResponse) ResourceException(org.forgerock.json.resource.ResourceException) QueryResourceHandler(org.forgerock.json.resource.QueryResourceHandler) JsonPointer(org.forgerock.json.JsonPointer) Test(org.testng.annotations.Test)

Example 15 with QueryRequest

use of org.forgerock.json.resource.QueryRequest in project OpenAM by OpenRock.

the class PolicyResourceDelegateTest method shouldQueryPoliciesWithHandler.

@Test
public void shouldQueryPoliciesWithHandler() throws ResourceException {
    //Given
    Context context = mock(Context.class);
    QueryRequest request = mock(QueryRequest.class);
    QueryResourceHandler handler = mock(QueryResourceHandler.class);
    //When
    delegate.queryPolicies(context, request, handler);
    //Then
    verify(policyResource).handleQuery(context, request, handler);
}
Also used : Context(org.forgerock.services.context.Context) QueryRequest(org.forgerock.json.resource.QueryRequest) QueryResourceHandler(org.forgerock.json.resource.QueryResourceHandler) Test(org.testng.annotations.Test)

Aggregations

QueryRequest (org.forgerock.json.resource.QueryRequest)79 Test (org.testng.annotations.Test)68 QueryResponse (org.forgerock.json.resource.QueryResponse)40 JsonPointer (org.forgerock.json.JsonPointer)34 Context (org.forgerock.services.context.Context)34 QueryResourceHandler (org.forgerock.json.resource.QueryResourceHandler)29 ResourceException (org.forgerock.json.resource.ResourceException)28 Subject (javax.security.auth.Subject)26 RealmContext (org.forgerock.openam.rest.RealmContext)26 ResourceResponse (org.forgerock.json.resource.ResourceResponse)24 ClientContext (org.forgerock.services.context.ClientContext)22 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)20 Collection (java.util.Collection)15 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)15 SearchFilter (com.sun.identity.entitlement.util.SearchFilter)10 Matchers.anyString (org.mockito.Matchers.anyString)9 JsonValue (org.forgerock.json.JsonValue)8 ArrayList (java.util.ArrayList)7 Set (java.util.Set)7 EntitlementException (com.sun.identity.entitlement.EntitlementException)6