Search in sources :

Example 51 with BadRequestException

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

the class SubjectAttributesResourceV1 method queryCollection.

@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
    final Subject mySubject = getContextSubject(context);
    if (mySubject == null) {
        debug.error("SubjectAttributesResource :: QUERY : Unknown Subject");
        return new BadRequestException().asPromise();
    }
    final String principalName = PrincipalRestUtils.getPrincipalNameFromSubject(mySubject);
    final SubjectAttributesManager manager = getSubjectAttributesManager(mySubject, getRealm(context));
    final Set<String> attributes;
    try {
        attributes = manager.getAvailableSubjectAttributeNames();
    } catch (EntitlementException e) {
        debug.error("SubjectAttributesResource :: QUERY by " + principalName + " : Unable to query available " + "subject attribute names.");
        return new InternalServerErrorException().asPromise();
    }
    for (String attr : attributes) {
        handler.handleResource(newResourceResponse(attr, Long.toString(System.currentTimeMillis()), JsonValue.json(attr)));
    }
    return newResultPromise(newQueryResponse(null, CountPolicy.EXACT, 0));
}
Also used : EntitlementException(com.sun.identity.entitlement.EntitlementException) SubjectAttributesManager(com.sun.identity.entitlement.SubjectAttributesManager) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) Subject(javax.security.auth.Subject)

Example 52 with BadRequestException

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

the class PolicyResourceWithCopyMoveSupport method copyOrMovePoliciesByApplication.

private ActionResponse copyOrMovePoliciesByApplication(Context context, ActionRequest request, PolicyAction copyOrMoveAction) throws ResourceException {
    JsonValue payload = request.getContent();
    JsonValue from = payload.get("from");
    JsonValue to = payload.get("to");
    if (from.isNull()) {
        throw new BadRequestException("from definition is missing");
    }
    if (!from.isDefined("application")) {
        throw new BadRequestException("from application definition is missing");
    }
    String sourceApplication = from.get("application").asString();
    if (to.isNull()) {
        throw new BadRequestException("to definition is missing");
    }
    String sourceRealm = RealmContext.getRealm(context);
    String destinationRealm = to.get("realm").defaultTo(sourceRealm).asString();
    String destinationApplication = to.get("application").defaultTo(sourceApplication).asString();
    JsonValue resourceTypeMapping = payload.get("resourceTypeMapping").defaultTo(Collections.emptyMap());
    String namePostfix = to.get("namePostfix").defaultTo("").asString();
    QueryRequest queryRequest = Requests.newQueryRequest("policies");
    queryRequest.setQueryFilter(QueryFilter.equalTo(new JsonPointer("applicationName"), sourceApplication));
    final List<JsonValue> policies = new ArrayList<>();
    router.handleQuery(context, queryRequest, new QueryResourceHandler() {

        @Override
        public boolean handleResource(ResourceResponse resourceResponse) {
            policies.add(resourceResponse.getContent());
            return true;
        }
    }).getOrThrowUninterruptibly();
    JsonValue actionResponseContent = json(array());
    for (JsonValue policy : policies) {
        ActionResponse response = copyOrMoveGivenPolicy(context, policy, destinationRealm, destinationApplication, namePostfix, resourceTypeMapping, copyOrMoveAction);
        actionResponseContent.add(response.getJsonContent().asMap());
    }
    return Responses.newActionResponse(actionResponseContent);
}
Also used : QueryRequest(org.forgerock.json.resource.QueryRequest) ResourceResponse(org.forgerock.json.resource.ResourceResponse) JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) BadRequestException(org.forgerock.json.resource.BadRequestException) JsonPointer(org.forgerock.json.JsonPointer) QueryResourceHandler(org.forgerock.json.resource.QueryResourceHandler) ActionResponse(org.forgerock.json.resource.ActionResponse)

Example 53 with BadRequestException

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

the class PolicyResourceWithCopyMoveSupport method copyPolicy.

private ActionResponse copyPolicy(Context context, String resourceId, ActionRequest request) throws ResourceException {
    String sourceRealm = RealmContext.getRealm(context);
    JsonValue payload = request.getContent().get("to");
    if (payload.isNull()) {
        throw new BadRequestException("to definition is missing");
    }
    String destinationRealm = payload.get("realm").defaultTo(sourceRealm).asString();
    ReadRequest readRequest = Requests.newReadRequest("policies", resourceId);
    JsonValue policy = router.handleRead(context, readRequest).getOrThrowUninterruptibly().getContent();
    String sourceApplication = policy.get("applicationName").asString();
    String sourceResourceType = policy.get("resourceTypeUuid").asString();
    String destinationApplication = payload.get("application").defaultTo(sourceApplication).asString();
    String destinationResourceTypeId = payload.get("resourceType").defaultTo(sourceResourceType).asString();
    String copiedName = payload.get("name").defaultTo(resourceId).asString();
    if (sourceRealm.equals(destinationRealm) && resourceId.equals(copiedName)) {
        throw new BadRequestException("policy name already exists within the realm");
    }
    policy.put("name", copiedName);
    policy.put("applicationName", destinationApplication);
    policy.put("resourceTypeUuid", destinationResourceTypeId);
    RealmContext updatedContext = new RealmContext(context);
    updatedContext.setOverrideRealm(destinationRealm);
    CreateRequest createRequest = Requests.newCreateRequest("policies", policy);
    JsonValue copiedPolicy = router.handleCreate(updatedContext, createRequest).getOrThrowUninterruptibly().getContent();
    return Responses.newActionResponse(copiedPolicy);
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) CreateRequest(org.forgerock.json.resource.CreateRequest) JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) ReadRequest(org.forgerock.json.resource.ReadRequest)

Example 54 with BadRequestException

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

the class TokenResource method queryCollection.

@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest queryRequest, QueryResourceHandler handler) {
    try {
        JsonValue response;
        Collection<QueryFilter<CoreTokenField>> query = new ArrayList<QueryFilter<CoreTokenField>>();
        //get uid of submitter
        AMIdentity uid;
        try {
            uid = getUid(context);
            if (!uid.equals(adminUserId)) {
                query.add(QueryFilter.equalTo(USERNAME_FIELD, uid.getName()));
                query.add(QueryFilter.equalTo(REALM_FIELD, DNMapper.orgNameToRealmName(uid.getRealm())));
            }
        } catch (Exception e) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: QUERY : Unable to query collection as no UID discovered " + "for requesting user.");
            }
            return new PermanentException(401, "Unauthorized", e).asPromise();
        }
        String id = queryRequest.getQueryId();
        String queryString;
        if (id.equals("access_token")) {
            queryString = "tokenName=access_token";
        } else {
            queryString = id;
        }
        String[] constraints = queryString.split(",");
        boolean userNamePresent = false;
        for (String constraint : constraints) {
            String[] params = constraint.split("=");
            if (params.length == 2) {
                if (OAuthTokenField.USER_NAME.getOAuthField().equals(params[0])) {
                    userNamePresent = true;
                }
                query.add(QueryFilter.equalTo(getOAuth2TokenField(params[0]), params[1]));
            }
        }
        if (adminUserId.equals(uid)) {
            if (!userNamePresent) {
                return new BadRequestException("userName field MUST be set in _queryId").asPromise();
            }
        } else if (userNamePresent) {
            return new BadRequestException("userName field MUST NOT be set in _queryId").asPromise();
        }
        response = tokenStore.query(QueryFilter.and(query));
        return handleResponse(handler, response, context);
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as the client is not authorized.", e);
        return new PermanentException(401, e.getMessage(), e).asPromise();
    } catch (CoreTokenException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as the token store is not available.", e);
        return new ServiceUnavailableException(e.getMessage(), e).asPromise();
    } catch (InternalServerErrorException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as writing the response failed.", e);
        return e.asPromise();
    } catch (NotFoundException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as realm does not have OAuth 2 provider.", e);
        return e.asPromise();
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.json.resource.NotFoundException) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) ResourceException(org.forgerock.json.resource.ResourceException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) QueryFilter(org.forgerock.util.query.QueryFilter) AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Example 55 with BadRequestException

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

the class IdentityServicesImpl method searchIdentityDetails.

/**
     * Searches the identity repository to find all identities that match the search criteria and returns them as a
     * list of identities.
     *
     * @param crestQuery A CREST Query object which will contain either a _queryId or a _queryFilter.
     * @param searchModifiers The search modifiers
     * @param admin Your SSO token.
     * @return a list of matching identities.
     * @throws ResourceException
     */
public List<IdentityDetails> searchIdentityDetails(CrestQuery crestQuery, Map<String, Set<String>> searchModifiers, SSOToken admin) throws ResourceException {
    try {
        String realm = "/";
        String objectType = "User";
        if (searchModifiers != null) {
            realm = attractValues("realm", searchModifiers, "/");
            objectType = attractValues("objecttype", searchModifiers, "User");
        }
        AMIdentityRepository repo = getRepo(admin, realm);
        IdType idType = getIdType(objectType);
        if (idType != null) {
            List<AMIdentity> identities = fetchAMIdentities(idType, crestQuery, true, repo, searchModifiers);
            List<IdentityDetails> result = new ArrayList<>();
            for (AMIdentity identity : identities) {
                result.add(convertToIdentityDetails(identity, null));
            }
            return result;
        }
        debug.error("IdentityServicesImpl.searchIdentities unsupported IdType " + objectType);
        throw new BadRequestException("searchIdentities: unsupported IdType " + objectType);
    } catch (IdRepoException e) {
        debug.error("IdentityServicesImpl.searchIdentities", e);
        throw new InternalServerErrorException(e.getMessage());
    } catch (SSOException e) {
        debug.error("IdentityServicesImpl.searchIdentities", e);
        throw new InternalServerErrorException(e.getMessage());
    } catch (ObjectNotFound e) {
        debug.error("IdentityServicesImpl.searchIdentities", e);
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ArrayList(java.util.ArrayList) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Aggregations

BadRequestException (org.forgerock.json.resource.BadRequestException)82 JsonValue (org.forgerock.json.JsonValue)44 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)40 ResourceException (org.forgerock.json.resource.ResourceException)39 SSOException (com.iplanet.sso.SSOException)37 NotFoundException (org.forgerock.json.resource.NotFoundException)37 SMSException (com.sun.identity.sm.SMSException)31 ForbiddenException (org.forgerock.json.resource.ForbiddenException)26 ResourceResponse (org.forgerock.json.resource.ResourceResponse)25 IdRepoException (com.sun.identity.idm.IdRepoException)23 PermanentException (org.forgerock.json.resource.PermanentException)22 ConflictException (org.forgerock.json.resource.ConflictException)21 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)20 SSOToken (com.iplanet.sso.SSOToken)19 NotSupportedException (org.forgerock.json.resource.NotSupportedException)17 RealmContext (org.forgerock.openam.rest.RealmContext)17 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)16 DeleteFailedException (org.forgerock.openam.cts.exceptions.DeleteFailedException)16 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)14 MessagingException (javax.mail.MessagingException)13