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));
}
});
}
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();
}
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());
}
});
}
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));
}
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();
}
}
};
}
Aggregations