Search in sources :

Example 6 with NotSupportedException

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

the class Endpoints method from.

/**
     * Produce a {@code Handler} from the annotated methods on the provided object.
     * <p>
     * This method currently only distinguishes requests by their method type. In future this
     * should be extended to support selection by request and response media types, and request
     * path.
     * @param obj The object containing annotated methods.
     * @return A new {@code Handler}.
     */
public static Handler from(final Object obj) {
    final Map<String, AnnotatedMethod> methods = new HashMap<>();
    methods.put("DELETE", AnnotatedMethod.findMethod(obj, Delete.class));
    methods.put("GET", AnnotatedMethod.findMethod(obj, Get.class));
    methods.put("POST", AnnotatedMethod.findMethod(obj, Post.class));
    methods.put("PUT", AnnotatedMethod.findMethod(obj, Put.class));
    return new Handler() {

        @Override
        public Promise<Response, NeverThrowsException> handle(Context context, Request request) {
            AnnotatedMethod method = methods.get(getMethod(request));
            if (method == null) {
                Response response = new Response(Status.METHOD_NOT_ALLOWED);
                response.setEntity(new NotSupportedException().toJsonValue().getObject());
                return newResultPromise(response);
            }
            return method.invoke(context, request);
        }
    };
}
Also used : Context(org.forgerock.services.context.Context) HashMap(java.util.HashMap) Request(org.forgerock.http.protocol.Request) Handler(org.forgerock.http.Handler) Response(org.forgerock.http.protocol.Response) NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Example 7 with NotSupportedException

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

the class SmsCollectionProvider method queryCollection.

/**
     * Queries for child instances of config. The parent config referenced by the request path is found, and
     * all child config for the type is returned.
     * <p>
     * Note that only query filter is supported, and only a filter of value {@code true} (i.e. all values).
     * Sorting and paging are not supported.
     * {@inheritDoc}
     */
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
    if (!"true".equals(request.getQueryFilter().toString())) {
        return new NotSupportedException("Query not supported: " + request.getQueryFilter()).asPromise();
    }
    if (request.getPagedResultsCookie() != null || request.getPagedResultsOffset() > 0 || request.getPageSize() > 0) {
        return new NotSupportedException("Query paging not currently supported").asPromise();
    }
    try {
        ServiceConfigManager scm = getServiceConfigManager(context);
        String realm = realmFor(context);
        if (subSchemaPath.isEmpty()) {
            Set<String> instanceNames = new TreeSet<String>(scm.getInstanceNames());
            for (String instanceName : instanceNames) {
                ServiceConfig config = type == SchemaType.GLOBAL ? scm.getGlobalConfig(instanceName) : scm.getOrganizationConfig(realm, instanceName);
                if (config != null) {
                    JsonValue value = getJsonValue(realm, config);
                    handler.handleResource(newResourceResponse(instanceName, String.valueOf(value.hashCode()), value));
                }
            }
        } else {
            ServiceConfig config = parentSubConfigFor(context, scm);
            Set<String> names = config.getSubConfigNames("*", lastSchemaNodeName());
            for (String configName : names) {
                JsonValue value = getJsonValue(realm, config.getSubConfig(configName));
                handler.handleResource(newResourceResponse(configName, String.valueOf(value.hashCode()), value));
            }
        }
        return newResultPromise(newQueryResponse());
    } catch (SMSException e) {
        debug.warning("::SmsCollectionProvider:: SMSException on query", e);
        return new InternalServerErrorException("Unable to query SMS config: " + e.getMessage()).asPromise();
    } catch (SSOException e) {
        debug.warning("::SmsCollectionProvider:: SSOException on query", e);
        return new InternalServerErrorException("Unable to query SMS config: " + e.getMessage()).asPromise();
    }
}
Also used : ServiceConfig(com.sun.identity.sm.ServiceConfig) SMSException(com.sun.identity.sm.SMSException) TreeSet(java.util.TreeSet) JsonValue(org.forgerock.json.JsonValue) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) SSOException(com.iplanet.sso.SSOException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager)

Example 8 with NotSupportedException

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

the class OathDevicesResource method actionCollection.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request) {
    try {
        //could be admin
        final AMIdentity identity = getUserIdFromUri(context);
        final AuthenticatorOathService realmOathService = oathServiceFactory.create(getRealm(context));
        switch(request.getAction()) {
            case SKIP:
                try {
                    final boolean setValue = request.getContent().get(VALUE).asBoolean();
                    realmOathService.setUserSkipOath(identity, setValue ? AuthenticatorOathService.SKIPPABLE : AuthenticatorOathService.NOT_SKIPPABLE);
                    return newResultPromise(newActionResponse(JsonValueBuilder.jsonValue().build()));
                } catch (SSOException | IdRepoException e) {
                    debug.error("OathDevicesResource :: SKIP action - Unable to set value in user store.", e);
                    return new InternalServerErrorException().asPromise();
                }
            case CHECK:
                try {
                    final Set resultSet = identity.getAttribute(realmOathService.getSkippableAttributeName());
                    boolean result = false;
                    if (CollectionUtils.isNotEmpty(resultSet)) {
                        String tmp = (String) resultSet.iterator().next();
                        int resultInt = Integer.valueOf(tmp);
                        if (resultInt == AuthenticatorOathService.SKIPPABLE) {
                            result = true;
                        }
                    }
                    return newResultPromise(newActionResponse(JsonValueBuilder.jsonValue().put(RESULT, result).build()));
                } catch (SSOException | IdRepoException e) {
                    debug.error("OathDevicesResource :: CHECK action - Unable to read value from user store.", e);
                    return new InternalServerErrorException().asPromise();
                }
            case //sets their 'skippable' selection to default (NOT_SET) and deletes their profiles attribute
            RESET:
                try {
                    realmOathService.setUserSkipOath(identity, AuthenticatorOathService.NOT_SET);
                    realmOathService.removeAllUserDevices(identity);
                    return newResultPromise(newActionResponse(JsonValueBuilder.jsonValue().put(RESULT, true).build()));
                } catch (SSOException | IdRepoException e) {
                    debug.error("OathDevicesResource :: Action - Unable to reset identity attributes", e);
                    return new InternalServerErrorException().asPromise();
                }
            default:
                return new NotSupportedException().asPromise();
        }
    } catch (SMSException e) {
        debug.error("OathDevicesResource :: Action - Unable to communicate with the SMS.", e);
        return new InternalServerErrorException().asPromise();
    } catch (SSOException | InternalServerErrorException e) {
        debug.error("OathDevicesResource :: Action - Unable to retrieve identity data from request context", e);
        return new InternalServerErrorException().asPromise();
    }
}
Also used : Set(java.util.Set) AuthenticatorOathService(org.forgerock.openam.core.rest.devices.services.AuthenticatorOathService) SMSException(com.sun.identity.sm.SMSException) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) AMIdentity(com.sun.identity.idm.AMIdentity) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Example 9 with NotSupportedException

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

the class IdentityResourceV2 method createRegistrationEmail.

/**
     * This method will create a confirmation email that contains a {@link org.forgerock.openam.cts.api.tokens.Token},
     * confirmationId and email that was provided in the request.
     * @param context Current Server Context
     * @param request Request from client to retrieve id
     */
private Promise<ActionResponse, ResourceException> createRegistrationEmail(final Context context, final ActionRequest request, final String realm, final RestSecurity restSecurity) {
    JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1));
    final JsonValue jVal = request.getContent();
    String emailAddress = null;
    String confirmationLink;
    String tokenID;
    try {
        if (restSecurity == null) {
            if (debug.warningEnabled()) {
                debug.warning("IdentityResource.createRegistrationEmail(): Rest Security not created. " + "restSecurity={}", restSecurity);
            }
            throw new NotFoundException("Rest Security Service not created");
        }
        if (!restSecurity.isSelfServiceRestEndpointEnabled()) {
            if (debug.warningEnabled()) {
                debug.warning("IdentityResource.createRegistrationEmail(): Self-Registration set to : {}", restSecurity.isSelfServiceRestEndpointEnabled());
            }
            throw new NotSupportedException("Legacy Self Service REST Endpoint is not enabled.");
        }
        if (!restSecurity.isSelfRegistration()) {
            if (debug.warningEnabled()) {
                debug.warning("IdentityResource.createRegistrationEmail(): Self-Registration set to : {}", restSecurity.isSelfRegistration());
            }
            throw new NotSupportedException("Self Registration is not enabled.");
        }
        // Get full deployment URL
        HttpContext header = context.asContext(HttpContext.class);
        String baseURL = baseURLProviderFactory.get(realm).getRootURL(header);
        // Get the email address provided from registration page
        emailAddress = jVal.get(EMAIL).asString();
        if (StringUtils.isBlank(emailAddress)) {
            throw new BadRequestException("Email not provided");
        }
        String subject = jVal.get("subject").asString();
        String message = jVal.get("message").asString();
        // Retrieve email registration token life time
        Long tokenLifeTime = restSecurity.getSelfRegTLT();
        // Create CTS Token
        org.forgerock.openam.cts.api.tokens.Token ctsToken = generateToken(emailAddress, "anonymous", tokenLifeTime, realm);
        // Store token in datastore
        CTSHolder.getCTS().createAsync(ctsToken);
        tokenID = ctsToken.getTokenId();
        // Create confirmationId
        String confirmationId = Hash.hash(tokenID + emailAddress + SystemProperties.get(AM_ENCRYPTION_PWD));
        // Build Confirmation URL
        String confURL = restSecurity.getSelfRegistrationConfirmationUrl();
        StringBuilder confURLBuilder = new StringBuilder(100);
        if (StringUtils.isEmpty(confURL)) {
            confURLBuilder.append(baseURL).append("/json/confirmation/register");
        } else if (confURL.startsWith("/")) {
            confURLBuilder.append(baseURL).append(confURL);
        } else {
            confURLBuilder.append(confURL);
        }
        confirmationLink = confURLBuilder.append("?confirmationId=").append(requestParamEncode(confirmationId)).append("&email=").append(requestParamEncode(emailAddress)).append("&tokenId=").append(requestParamEncode(tokenID)).append("&realm=").append(realm).toString();
        // Send Registration
        sendNotification(emailAddress, subject, message, realm, confirmationLink);
        if (debug.messageEnabled()) {
            debug.message("IdentityResource.createRegistrationEmail() :: Sent notification to={} with subject={}. " + "In realm={} for token ID={}", emailAddress, subject, realm, tokenID);
        }
        return newResultPromise(newActionResponse(result));
    } catch (BadRequestException be) {
        debug.warning("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, be);
        return be.asPromise();
    } catch (NotFoundException nfe) {
        debug.warning("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, nfe);
        return nfe.asPromise();
    } catch (NotSupportedException nse) {
        if (debug.warningEnabled()) {
            debug.warning("IdentityResource.createRegistrationEmail(): Operation not enabled. email={}", emailAddress, nse);
        }
        return nse.asPromise();
    } catch (Exception e) {
        debug.error("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, e);
        return new NotFoundException("Email not sent").asPromise();
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue) HttpContext(org.forgerock.json.resource.http.HttpContext) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) MessagingException(javax.mail.MessagingException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) SSOException(com.iplanet.sso.SSOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) 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) BadRequestException(org.forgerock.json.resource.BadRequestException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Example 10 with NotSupportedException

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

the class IdentityResourceV2 method actionInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ActionResponse, ResourceException> actionInstance(final Context context, final String resourceId, final ActionRequest request) {
    String action = request.getAction();
    if ("changePassword".equalsIgnoreCase(action)) {
        RealmContext realmContext = context.asContext(RealmContext.class);
        final String realm = realmContext.getResolvedRealm();
        JsonValue value = request.getContent();
        try {
            String userPassword = value.get(USER_PASSWORD).asString();
            if (StringUtils.isBlank(userPassword)) {
                throw new BadRequestException("'" + USER_PASSWORD + "' attribute not set in JSON content.");
            }
            String currentPassword = value.get(CURRENT_PASSWORD).asString();
            if (StringUtils.isBlank(currentPassword)) {
                throw new BadRequestException("'" + CURRENT_PASSWORD + "' attribute not set in JSON content.");
            }
            IdentityRestUtils.changePassword(context, realm, resourceId, currentPassword, userPassword);
            if (debug.messageEnabled()) {
                String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
                debug.message("IdentityResource.actionInstance :: ACTION of change password for " + resourceId + " in realm " + realm + " performed by " + principalName);
            }
            return newResultPromise(newActionResponse(json(object())));
        } catch (ResourceException re) {
            debug.warning("Cannot change password! " + resourceId + ":" + re);
            return re.asPromise();
        }
    } else {
        return new NotSupportedException(action + " not supported for resource instances").asPromise();
    }
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Aggregations

NotSupportedException (org.forgerock.json.resource.NotSupportedException)21 JsonValue (org.forgerock.json.JsonValue)11 SSOException (com.iplanet.sso.SSOException)8 SMSException (com.sun.identity.sm.SMSException)8 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)8 ResourceException (org.forgerock.json.resource.ResourceException)7 BadRequestException (org.forgerock.json.resource.BadRequestException)5 RealmContext (org.forgerock.openam.rest.RealmContext)4 IdRepoException (com.sun.identity.idm.IdRepoException)3 ArrayList (java.util.ArrayList)3 ForbiddenException (org.forgerock.json.resource.ForbiddenException)3 SSOToken (com.iplanet.sso.SSOToken)2 AMAuthenticationManager (com.sun.identity.authentication.config.AMAuthenticationManager)2 AMConfigurationException (com.sun.identity.authentication.config.AMConfigurationException)2 ServiceConfig (com.sun.identity.sm.ServiceConfig)2 ServiceConfigManager (com.sun.identity.sm.ServiceConfigManager)2 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)2 ServiceSchemaManager (com.sun.identity.sm.ServiceSchemaManager)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MessagingException (javax.mail.MessagingException)2