Search in sources :

Example 1 with AsyncFunction

use of org.forgerock.util.AsyncFunction 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 2 with AsyncFunction

use of org.forgerock.util.AsyncFunction 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 3 with AsyncFunction

use of org.forgerock.util.AsyncFunction in project OpenAM by OpenRock.

the class UmaPolicyApplicationListener method deletePolicies.

private void deletePolicies(String realm, String resourceServerId) {
    RealmContext realmContext = new RealmContext(new RootContext());
    realmContext.setDnsAlias("/", realm);
    final Context context = new AdminSubjectContext(logger, sessionCache, realmContext);
    QueryRequest request = Requests.newQueryRequest("").setQueryFilter(QueryFilter.equalTo(new JsonPointer("applicationName"), resourceServerId));
    final List<ResourceResponse> resources = new ArrayList<>();
    policyResource.handleQuery(context, request, new QueryResourceHandler() {

        @Override
        public boolean handleResource(ResourceResponse resource) {
            resources.add(resource);
            return true;
        }
    }).thenAsync(new AsyncFunction<QueryResponse, List<ResourceResponse>, ResourceException>() {

        @Override
        public Promise<List<ResourceResponse>, ResourceException> apply(QueryResponse response) {
            List<Promise<ResourceResponse, ResourceException>> promises = new ArrayList<>();
            for (ResourceResponse policy : resources) {
                DeleteRequest deleteRequest = Requests.newDeleteRequest("", policy.getId());
                promises.add(policyResource.handleDelete(context, deleteRequest));
            }
            Promise<List<ResourceResponse>, ResourceException> when = Promises.when(promises);
            return when;
        }
    }).thenOnException(new ExceptionHandler<ResourceException>() {

        @Override
        public void handleException(ResourceException error) {
            logger.error(error.getReason());
        }
    });
}
Also used : RootContext(org.forgerock.services.context.RootContext) RealmContext(org.forgerock.openam.rest.RealmContext) AdminSubjectContext(org.forgerock.openam.rest.resource.AdminSubjectContext) Context(org.forgerock.services.context.Context) RealmContext(org.forgerock.openam.rest.RealmContext) QueryRequest(org.forgerock.json.resource.QueryRequest) AdminSubjectContext(org.forgerock.openam.rest.resource.AdminSubjectContext) ArrayList(java.util.ArrayList) JsonPointer(org.forgerock.json.JsonPointer) AsyncFunction(org.forgerock.util.AsyncFunction) RootContext(org.forgerock.services.context.RootContext) Promise(org.forgerock.util.promise.Promise) ResourceResponse(org.forgerock.json.resource.ResourceResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) List(java.util.List) ArrayList(java.util.ArrayList) ResourceException(org.forgerock.json.resource.ResourceException) QueryResourceHandler(org.forgerock.json.resource.QueryResourceHandler) DenyOverride(com.sun.identity.entitlement.DenyOverride) DeleteRequest(org.forgerock.json.resource.DeleteRequest)

Example 4 with AsyncFunction

use of org.forgerock.util.AsyncFunction in project OpenAM by OpenRock.

the class UmaPolicyServiceImpl method createPolicy.

/**
     * {@inheritDoc}
     */
@Override
public Promise<UmaPolicy, ResourceException> createPolicy(final Context context, JsonValue policy) {
    final UmaPolicy umaPolicy;
    final ResourceSetDescription resourceSet;
    final String userId = contextHelper.getUserId(context);
    String realm = getRealm(context);
    try {
        String policyId = UmaPolicy.idOf(policy);
        resourceSet = getResourceSet(realm, policyId);
        umaPolicy = UmaPolicy.valueOf(resourceSet, resolveUsernameToUID(context, policy));
        boolean canShare = canUserShareResourceSet(resourceSet.getResourceOwnerId(), userId, resourceSet.getClientId(), realm, resourceSet.getId(), umaPolicy.getScopes());
        if (!canShare) {
            return new ForbiddenException().asPromise();
        }
        validateScopes(resourceSet, umaPolicy.getScopes());
        verifyPolicyDoesNotAlreadyExist(context, resourceSet);
    } catch (ResourceException e) {
        return e.asPromise();
    }
    return beforeResourceShared(umaPolicy).thenAsync(new AsyncFunction<UmaPolicy, List<ResourceResponse>, ResourceException>() {

        @Override
        public Promise<List<ResourceResponse>, ResourceException> apply(UmaPolicy umaPolicy) {
            return policyResourceDelegate.createPolicies(context, umaPolicy.asUnderlyingPolicies(userId));
        }
    }).thenAlways(afterResourceShared(umaPolicy)).thenAsync(new UpdatePolicyGraphStatesFunction<List<ResourceResponse>>(resourceSet, context)).thenAsync(new AuditAndProduceUmaPolicyFunction(resourceSet, context));
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) ResourceResponse(org.forgerock.json.resource.ResourceResponse) ResourceException(org.forgerock.json.resource.ResourceException) List(java.util.List) ArrayList(java.util.ArrayList) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) AsyncFunction(org.forgerock.util.AsyncFunction)

Example 5 with AsyncFunction

use of org.forgerock.util.AsyncFunction in project OpenAM by OpenRock.

the class PendingRequestsService method approvePendingRequest.

private AsyncFunction<UmaPolicy, Void, ResourceException> approvePendingRequest(final UmaPendingRequest request, final Collection<String> scopes, final String id, final String realm) {
    return new AsyncFunction<UmaPolicy, Void, ResourceException>() {

        @Override
        public Promise<Void, ResourceException> apply(UmaPolicy value) {
            try {
                if (isEmailRequestingPartyOnPendingRequestApprovalEnabled(realm)) {
                    Pair<String, String> template = pendingRequestEmailTemplate.getApprovalTemplate(request.getRequestingPartyId(), realm);
                    try {
                        emailService.email(realm, request.getRequestingPartyId(), template.getFirst(), MessageFormat.format(template.getSecond(), request.getResourceOwnerId(), request.getResourceSetName(), pendingRequestEmailTemplate.buildScopeString(scopes, request.getRequestingPartyId(), realm)));
                    } catch (MessagingException e) {
                        debug.warning("Pending Request Approval email could not be sent", e);
                    }
                }
                store.delete(id);
                AMIdentity resourceOwner = coreWrapper.getIdentity(request.getResourceOwnerId(), realm);
                auditLogger.log(request.getResourceSetId(), request.getResourceSetName(), resourceOwner, UmaAuditType.REQUEST_APPROVED, request.getRequestingPartyId());
                return newResultPromise(null);
            } catch (NotFoundException e) {
                return new org.forgerock.json.resource.NotFoundException("Pending request, " + id + ", not found", e).asPromise();
            } catch (ServerException e) {
                return new InternalServerErrorException("Failed to mark pending request, " + id + ", as approved", e).asPromise();
            }
        }
    };
}
Also used : ServerException(org.forgerock.openam.sm.datalayer.store.ServerException) MessagingException(javax.mail.MessagingException) NotFoundException(org.forgerock.openam.sm.datalayer.store.NotFoundException) AsyncFunction(org.forgerock.util.AsyncFunction) AMIdentity(com.sun.identity.idm.AMIdentity) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException) UmaPolicy(org.forgerock.openam.uma.UmaConstants.UmaPolicy)

Aggregations

ResourceException (org.forgerock.json.resource.ResourceException)5 AsyncFunction (org.forgerock.util.AsyncFunction)5 ResourceResponse (org.forgerock.json.resource.ResourceResponse)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 QueryRequest (org.forgerock.json.resource.QueryRequest)3 QueryResponse (org.forgerock.json.resource.QueryResponse)3 JsonPointer (org.forgerock.json.JsonPointer)2 ResourceSetDescription (org.forgerock.oauth2.resources.ResourceSetDescription)2 UmaPolicy (org.forgerock.openam.uma.UmaPolicy)2 Promise (org.forgerock.util.promise.Promise)2 DenyOverride (com.sun.identity.entitlement.DenyOverride)1 AMIdentity (com.sun.identity.idm.AMIdentity)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 Set (java.util.Set)1 MessagingException (javax.mail.MessagingException)1 JsonValue (org.forgerock.json.JsonValue)1