Search in sources :

Example 16 with ResourceException

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

the class RealmResource method readInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();
    ResourceResponse resource;
    JsonValue jval;
    String holdResourceId = checkForTopLevelRealm(resourceId);
    try {
        hasPermission(context);
        if (holdResourceId != null && !holdResourceId.startsWith("/")) {
            holdResourceId = "/" + holdResourceId;
        }
        if (!realmPath.equalsIgnoreCase("/")) {
            holdResourceId = realmPath + holdResourceId;
        }
        OrganizationConfigManager ocm = new OrganizationConfigManager(getSSOToken(), holdResourceId);
        // get associated services for this realm , include mandatory service names.
        Set serviceNames = ocm.getAssignedServices();
        jval = createJsonMessage(SERVICE_NAMES, serviceNames);
        String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
        resource = newResourceResponse(resourceId, String.valueOf(System.currentTimeMillis()), jval);
        if (debug.messageEnabled()) {
            debug.message("RealmResource.readInstance :: READ : Successfully read realm, " + resourceId + " performed by " + principalName);
        }
        return newResultPromise(resource);
    } catch (SSOException sso) {
        debug.error("RealmResource.updateInstance() : Cannot READ " + resourceId, sso);
        return new PermanentException(401, "Access Denied", null).asPromise();
    } catch (ForbiddenException fe) {
        debug.error("RealmResource.readInstance() : Cannot READ " + resourceId + ":" + fe);
        return fe.asPromise();
    } catch (SMSException smse) {
        debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, smse);
        try {
            configureErrorMessage(smse);
            return new BadRequestException(smse.getMessage(), smse).asPromise();
        } catch (NotFoundException nf) {
            debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, nf);
            return nf.asPromise();
        } catch (ForbiddenException fe) {
            // User does not have authorization
            debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, fe);
            return fe.asPromise();
        } catch (PermanentException pe) {
            debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, pe);
            // Cannot recover from this exception
            return pe.asPromise();
        } catch (ConflictException ce) {
            debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, ce);
            return ce.asPromise();
        } catch (BadRequestException be) {
            debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, be);
            return be.asPromise();
        } catch (Exception e) {
            debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, e);
            return new BadRequestException(e.getMessage(), e).asPromise();
        }
    } catch (Exception e) {
        return new BadRequestException(e.getMessage(), e).asPromise();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) HashSet(java.util.HashSet) Set(java.util.Set) RealmContext(org.forgerock.openam.rest.RealmContext) SMSException(com.sun.identity.sm.SMSException) ConflictException(org.forgerock.json.resource.ConflictException) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) SMSException(com.sun.identity.sm.SMSException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) JsonValueException(org.forgerock.json.JsonValueException) ResourceException(org.forgerock.json.resource.ResourceException) SSOException(com.iplanet.sso.SSOException) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) PermanentException(org.forgerock.json.resource.PermanentException) BadRequestException(org.forgerock.json.resource.BadRequestException)

Example 17 with ResourceException

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

the class IdentityResourceV1 method updateInstance.

/**
     * Updates an instance given a JSON object with User Attributes
     * @param admin Token that has administrative privileges
     * @param details Json Value containing details of user identity
     * @return A successful promise if the update was successful
     */
private Promise<ActionResponse, ResourceException> updateInstance(SSOToken admin, final JsonValue details, final String realm) {
    JsonValue jVal = details;
    IdentityDetails newDtls;
    String resourceId = jVal.get(USERNAME).asString();
    try {
        newDtls = jsonValueToIdentityDetails(objectType, jVal, realm);
        if (newDtls.getAttributes() == null || newDtls.getAttributes().length < 1) {
            throw new BadRequestException("Illegal arguments: One or more required arguments is null or empty");
        }
        newDtls.setName(resourceId);
        // update resource with new details
        identityServices.update(newDtls, admin);
        debug.message("IdentityResource.updateInstance :: Anonymous UPDATE in realm={} for resourceId={}", realm, resourceId);
        // read updated identity back to client
        IdentityDetails checkIdent = identityServices.read(resourceId, getIdentityServicesAttributes(realm), admin);
        // handle updated resource
        return newResultPromise(newActionResponse(identityDetailsToJsonValue(checkIdent)));
    } catch (ResourceException re) {
        debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE in realm={} for resourceId={}", realm, resourceId, re);
        return re.asPromise();
    } catch (final Exception e) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE in realm={} for resourceId={}", realm, resourceId, e);
        return new NotFoundException(e.getMessage(), e).asPromise();
    }
}
Also used : IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) IdentityRestUtils.jsonValueToIdentityDetails(org.forgerock.openam.core.rest.IdentityRestUtils.jsonValueToIdentityDetails) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) ResourceException(org.forgerock.json.resource.ResourceException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) BadRequestException(org.forgerock.json.resource.BadRequestException) MessagingException(javax.mail.MessagingException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) 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)

Example 18 with ResourceException

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

the class IdentityResourceV1 method createInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> createInstance(final Context context, final CreateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        // anyone can create an account add
        SSOToken admin = getSSOToken(getCookieFromServerContext(context));
        final JsonValue jVal = request.getContent();
        String resourceId = request.getNewResourceId();
        UserAttributeInfo userAttributeInfo = configHandler.getConfig(realm, UserAttributeInfoBuilder.class);
        enforceWhiteList(context, request.getContent(), objectType, userAttributeInfo.getValidCreationAttributes());
        IdentityDetails identity = jsonValueToIdentityDetails(objectType, jVal, realm);
        // check to see if request has included resource ID
        if (resourceId != null) {
            if (identity.getName() != null) {
                if (!resourceId.equalsIgnoreCase(identity.getName())) {
                    ResourceException be = new BadRequestException("id in path does not match id in request body");
                    debug.error("IdentityResource.createInstance() :: Cannot CREATE ", be);
                    return be.asPromise();
                }
            }
            identity.setName(resourceId);
        } else {
            resourceId = identity.getName();
        }
        final String id = resourceId;
        return attemptResourceCreation(realm, admin, identity, resourceId).thenAsync(new AsyncFunction<IdentityDetails, ResourceResponse, ResourceException>() {

            @Override
            public Promise<ResourceResponse, ResourceException> apply(IdentityDetails dtls) {
                if (dtls != null) {
                    String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
                    debug.message("IdentityResource.createInstance :: CREATE of resourceId={} in realm={} performed by " + "principalName={}", id, realm, principalName);
                    return newResultPromise(newResourceResponse(id, "0", identityDetailsToJsonValue(dtls)));
                } else {
                    debug.error("IdentityResource.createInstance :: Identity not found ");
                    return new NotFoundException("Identity not found").asPromise();
                }
            }
        });
    } catch (SSOException e) {
        debug.error("IdentityResource.createInstance() :: failed.", e);
        return new NotFoundException(e.getMessage(), e).asPromise();
    } catch (BadRequestException bre) {
        return bre.asPromise();
    }
}
Also used : UserAttributeInfo(org.forgerock.openam.core.rest.UserAttributeInfo) IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) RealmContext(org.forgerock.openam.rest.RealmContext) IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOException(com.iplanet.sso.SSOException) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) ResourceResponse(org.forgerock.json.resource.ResourceResponse) IdentityRestUtils.jsonValueToIdentityDetails(org.forgerock.openam.core.rest.IdentityRestUtils.jsonValueToIdentityDetails) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 19 with ResourceException

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

the class IdentityResourceV1 method queryCollection.

/**
     * {@inheritDoc}
     */
@Override
public Promise<QueryResponse, ResourceException> queryCollection(final Context context, final QueryRequest request, final QueryResourceHandler handler) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        SSOToken admin = getSSOToken(getCookieFromServerContext(context));
        // This will only return 1 user..
        // getQueryFilter() is not implemented yet..returns dummy false value
        String queryId = request.getQueryId();
        if (queryId == null || queryId.isEmpty()) {
            queryId = "*";
        }
        List<String> users = identityServices.search(new CrestQuery(queryId), getIdentityServicesAttributes(realm), admin);
        String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
        debug.message("IdentityResource.queryCollection :: QUERY performed on realm={}  by principalName={}", realm, principalName);
        for (final String user : users) {
            JsonValue val = new JsonValue(user);
            ResourceResponse resource = newResourceResponse(user, "0", val);
            handler.handleResource(resource);
        }
    } catch (Exception ex) {
    }
    return newResultPromise(newQueryResponse());
}
Also used : CrestQuery(org.forgerock.openam.utils.CrestQuery) IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) RealmContext(org.forgerock.openam.rest.RealmContext) ResourceResponse(org.forgerock.json.resource.ResourceResponse) IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) BadRequestException(org.forgerock.json.resource.BadRequestException) MessagingException(javax.mail.MessagingException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) 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)

Example 20 with ResourceException

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

the class IdentityResourceV1 method anonymousCreate.

private Promise<ActionResponse, ResourceException> anonymousCreate(final Context context, final ActionRequest request, final String realm, RestSecurity restSecurity) {
    final JsonValue jVal = request.getContent();
    String confirmationId;
    String email;
    try {
        if (!restSecurity.isSelfRegistration()) {
            throw new BadRequestException("Self-registration disabled");
        }
        final String tokenID = jVal.get(TOKEN_ID).asString();
        jVal.remove(TOKEN_ID);
        confirmationId = jVal.get(CONFIRMATION_ID).asString();
        jVal.remove(CONFIRMATION_ID);
        email = jVal.get(EMAIL).asString();
        if (email == null || email.isEmpty()) {
            throw new BadRequestException("Email not provided");
        }
        // Convert to IDRepo Attribute schema
        jVal.put("mail", email);
        if (confirmationId == null || confirmationId.isEmpty()) {
            throw new BadRequestException("confirmationId not provided");
        }
        if (tokenID == null || tokenID.isEmpty()) {
            throw new BadRequestException("tokenId not provided");
        }
        validateToken(tokenID, realm, email, confirmationId);
        // create an Identity
        SSOToken admin = RestUtils.getToken();
        return createInstance(admin, jVal, realm).thenAsync(new AsyncFunction<ActionResponse, ActionResponse, ResourceException>() {

            @Override
            public Promise<ActionResponse, ResourceException> apply(ActionResponse response) {
                // Only remove the token if the create was successful, errors will be set in the handler.
                try {
                    // Even though the generated token will eventually timeout, delete it after a successful read
                    // so that the completed registration request cannot be made again using the same token.
                    CTSHolder.getCTS().deleteAsync(tokenID);
                } catch (DeleteFailedException e) {
                    // reading and deleting, the token has expired.
                    if (debug.messageEnabled()) {
                        debug.message("IdentityResource.anonymousCreate: Deleting token {} after a" + " successful read failed.", tokenID, e);
                    }
                } catch (CoreTokenException cte) {
                    // For any unexpected CTS error
                    debug.error("IdentityResource.anonymousCreate(): CTS Error", cte);
                    return new InternalServerErrorException(cte.getMessage(), cte).asPromise();
                }
                return newResultPromise(response);
            }
        });
    } catch (BadRequestException bre) {
        debug.warning("IdentityResource.anonymousCreate() :: Invalid Parameter", bre);
        return bre.asPromise();
    } catch (ResourceException re) {
        debug.warning("IdentityResource.anonymousCreate() :: Resource error", re);
        return re.asPromise();
    } catch (CoreTokenException cte) {
        // For any unexpected CTS error
        debug.error("IdentityResource.anonymousCreate() :: CTS error", cte);
        return new InternalServerErrorException(cte).asPromise();
    } catch (ServiceNotFoundException snfe) {
        // Failure from RestSecurity
        debug.error("IdentityResource.anonymousCreate() :: Internal error", snfe);
        return new InternalServerErrorException(snfe).asPromise();
    }
}
Also used : IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) ActionResponse(org.forgerock.json.resource.ActionResponse) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException)

Aggregations

ResourceException (org.forgerock.json.resource.ResourceException)323 Test (org.testng.annotations.Test)233 ResourceResponse (org.forgerock.json.resource.ResourceResponse)179 JsonValue (org.forgerock.json.JsonValue)145 Context (org.forgerock.services.context.Context)145 RealmContext (org.forgerock.openam.rest.RealmContext)110 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)71 Subject (javax.security.auth.Subject)58 ClientContext (org.forgerock.services.context.ClientContext)56 NotFoundException (org.forgerock.json.resource.NotFoundException)47 BadRequestException (org.forgerock.json.resource.BadRequestException)44 QueryResponse (org.forgerock.json.resource.QueryResponse)43 HashSet (java.util.HashSet)42 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)42 CreateRequest (org.forgerock.json.resource.CreateRequest)40 SSOException (com.iplanet.sso.SSOException)38 ActionResponse (org.forgerock.json.resource.ActionResponse)37 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)37 Matchers.anyString (org.mockito.Matchers.anyString)37 ArrayList (java.util.ArrayList)35