Search in sources :

Example 51 with NotFoundException

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

the class ResourceSetResourceTest method revokeAllUserPoliciesActionShouldHandleResourceException.

@Test
public void revokeAllUserPoliciesActionShouldHandleResourceException() {
    //Given
    Context context = mock(Context.class);
    ActionRequest request = mock(ActionRequest.class);
    given(contextHelper.getRealm(context)).willReturn("REALM");
    given(contextHelper.getUserId(context)).willReturn("RESOURCE_OWNER_ID");
    given(request.getAction()).willReturn("revokeAll");
    given(resourceSetService.revokeAllPolicies(context, "REALM", "RESOURCE_OWNER_ID")).willReturn(new NotFoundException().<Void>asPromise());
    //When
    Promise<ActionResponse, ResourceException> promise = resource.actionCollection(context, request);
    //Then
    assertThat(promise).failedWithException().isInstanceOf(ResourceException.class);
}
Also used : Context(org.forgerock.services.context.Context) ActionRequest(org.forgerock.json.resource.ActionRequest) NotFoundException(org.forgerock.json.resource.NotFoundException) ResourceException(org.forgerock.json.resource.ResourceException) ActionResponse(org.forgerock.json.resource.ActionResponse) Test(org.testng.annotations.Test)

Example 52 with NotFoundException

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

the class PolicyV1Filter method retrieveResourceType.

/**
     * Retrieves the resource type Id from the containing application
     * and sets it within the policies' JSON representation.
     *
     * @param jsonValue
     *         the policies' JSON representation
     * @param callingSubject
     *         the calling subject
     * @param realm
     *         the realm
     *
     * @throws EntitlementException
     *         should some policy error occur
     * @throws ResourceException
     *         should some violation occur that doesn't satisfy policy v1.0
     */
private void retrieveResourceType(JsonValue jsonValue, Subject callingSubject, String realm) throws EntitlementException, ResourceException {
    final String applicationName = jsonValue.get("applicationName").asString();
    if (applicationName == null) {
        throw new BadRequestException("Invalid application name defined in request");
    }
    final ApplicationService applicationService = applicationServiceFactory.create(callingSubject, realm);
    final Application application = applicationService.getApplication(applicationName);
    if (application == null) {
        throw new NotFoundException("Unable to find application " + applicationName);
    }
    if (application.getResourceTypeUuids().size() != 1) {
        throw new BadRequestException("Cannot create policy under an application with more than " + "one resource type using version 1.0 of this endpoint");
    }
    // Retrieve the resource type from the applications single resource type.
    final String resourceTypeUuid = application.getResourceTypeUuids().iterator().next();
    jsonValue.put(RESOURCE_TYPE_UUID, resourceTypeUuid);
}
Also used : BadRequestException(org.forgerock.json.resource.BadRequestException) NotFoundException(org.forgerock.json.resource.NotFoundException) Application(com.sun.identity.entitlement.Application) ApplicationService(org.forgerock.openam.entitlement.service.ApplicationService)

Example 53 with NotFoundException

use of org.forgerock.json.resource.NotFoundException 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 54 with NotFoundException

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

the class TokenResource method readInstance.

@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request) {
    try {
        AMIdentity uid = getUid(context);
        JsonValue response;
        ResourceResponse resource;
        try {
            response = tokenStore.read(resourceId);
        } catch (CoreTokenException e) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
            }
            throw new NotFoundException("Could not find valid token with given ID", e);
        }
        if (response == null) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
            }
            throw new NotFoundException("Could not find valid token with given ID");
        }
        JsonValue expireTimeValue = response.get(OAuth2Constants.CoreTokenParams.EXPIRE_TIME);
        long expireTime;
        if (expireTimeValue.isNumber()) {
            expireTime = expireTimeValue.asLong();
        } else {
            Set<String> expireTimeSet = (Set<String>) expireTimeValue.getObject();
            expireTime = Long.parseLong(expireTimeSet.iterator().next());
        }
        if (System.currentTimeMillis() > expireTime) {
            throw new NotFoundException("Could not find valid token with given ID");
        }
        String grantType = getAttributeValue(response, GRANT_TYPE);
        if (grantType != null && grantType.equalsIgnoreCase(OAuth2Constants.TokenEndpoint.CLIENT_CREDENTIALS)) {
            resource = newResourceResponse(OAuth2Constants.Params.ID, String.valueOf(System.currentTimeMillis()), response);
            return newResultPromise(resource);
        } else {
            String realm = getAttributeValue(response, REALM);
            String username = getAttributeValue(response, USERNAME);
            if (username == null || username.isEmpty()) {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
                }
                throw new NotFoundException("Could not find valid token with given ID");
            }
            AMIdentity uid2 = identityManager.getResourceOwnerIdentity(username, realm);
            if (uid.equals(adminUserId) || uid.equals(uid2)) {
                resource = newResourceResponse(OAuth2Constants.Params.ID, String.valueOf(System.currentTimeMillis()), response);
                return newResultPromise(resource);
            } else {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: READ : Only the resource owner or an administrator may perform " + "a read on the token with ID, " + resourceId + ".");
                }
                throw new PermanentException(401, "Unauthorized", null);
            }
        }
    } catch (ResourceException e) {
        return e.asPromise();
    } catch (SSOException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the IdRepo " + "failed to return a valid user.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (IdRepoException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the IdRepo " + "failed to return a valid user.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the client is not authorized.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    }
}
Also used : Set(java.util.Set) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) ResourceResponse(org.forgerock.json.resource.ResourceResponse) AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 55 with NotFoundException

use of org.forgerock.json.resource.NotFoundException 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

NotFoundException (org.forgerock.json.resource.NotFoundException)69 ResourceException (org.forgerock.json.resource.ResourceException)43 SSOException (com.iplanet.sso.SSOException)42 JsonValue (org.forgerock.json.JsonValue)39 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)39 BadRequestException (org.forgerock.json.resource.BadRequestException)38 SMSException (com.sun.identity.sm.SMSException)34 ResourceResponse (org.forgerock.json.resource.ResourceResponse)27 ForbiddenException (org.forgerock.json.resource.ForbiddenException)26 IdRepoException (com.sun.identity.idm.IdRepoException)24 PermanentException (org.forgerock.json.resource.PermanentException)24 ConflictException (org.forgerock.json.resource.ConflictException)22 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)21 NotSupportedException (org.forgerock.json.resource.NotSupportedException)18 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)17 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)16 RealmContext (org.forgerock.openam.rest.RealmContext)16 SSOToken (com.iplanet.sso.SSOToken)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)14 MessagingException (javax.mail.MessagingException)14