Search in sources :

Example 11 with BadRequestException

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

the class ApplicationsResource method queryCollection.

/**
     * Queries for a collection of resources.
     *
     * @param context {@inheritDoc}
     * @param request {@inheritDoc}
     * @param handler {@inheritDoc}
     */
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
    //auth
    final Subject mySubject = getContextSubject(context);
    if (mySubject == null) {
        debug.error("ApplicationsResource :: UPDATE : Unknown Subject");
        return new BadRequestException().asPromise();
    }
    //select
    final String realm = getRealm(context);
    final String principalName = PrincipalRestUtils.getPrincipalNameFromSubject(mySubject);
    try {
        List<ResourceResponse> results = new ArrayList<>();
        final Set<String> appNames = query(request, mySubject, realm);
        for (String appName : appNames) {
            final Application application = appManager.getApplication(mySubject, realm, appName);
            if (application == null) {
                debug.warning("Unable to find application " + appName);
                continue;
            }
            ApplicationWrapper wrapper = createApplicationWrapper(application, appTypeManagerWrapper);
            results.add(newResourceResponse(wrapper.getName(), null, wrapper.toJsonValue()));
        }
        QueryResponsePresentation.enableDeprecatedRemainingQueryResponse(request);
        return QueryResponsePresentation.perform(handler, request, results);
    } catch (EntitlementException e) {
        if (debug.errorEnabled()) {
            debug.error("ApplicationsResource :: QUERY by " + principalName + ": Failed to query resource.", e);
        }
        return exceptionMappingHandler.handleError(context, request, e).asPromise();
    }
}
Also used : EntitlementException(com.sun.identity.entitlement.EntitlementException) ApplicationWrapper(org.forgerock.openam.entitlement.rest.wrappers.ApplicationWrapper) ResourceResponse(org.forgerock.json.resource.ResourceResponse) BadRequestException(org.forgerock.json.resource.BadRequestException) Application(com.sun.identity.entitlement.Application) Subject(javax.security.auth.Subject)

Example 12 with BadRequestException

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

the class IdentityResourceExceptionMappingHandler method handleError.

@Override
public ResourceException handleError(IdRepoException idRepoException) {
    int code = Integer.valueOf(idRepoException.getErrorCode());
    ResultCode ldapResultCode = ResultCode.valueOf(idRepoException.getLdapErrorIntCode());
    if (idRepoException instanceof PasswordPolicyException) {
        //Convert the error code for the LDAP code
        if (ldapResultCode == ResultCode.INVALID_CREDENTIALS) {
            idRepoException = new PasswordPolicyException(ldapResultCode, IdRepoErrorCode.OLD_PASSWORD_INCORRECT, idRepoException.getMessageArgs());
        }
        if (ldapResultCode == ResultCode.INSUFFICIENT_ACCESS_RIGHTS) {
            return new ForbiddenException(idRepoException);
        }
        if (ldapResultCode == ResultCode.CONSTRAINT_VIOLATION) {
            idRepoException = new PasswordPolicyException(idRepoException.getConstraintViolationDetails());
        }
        return new BadRequestException(idRepoException.getMessage());
    }
    //compute LDAP error
    if (ldapResultCode == ResultCode.NO_SUCH_OBJECT) {
        return new NotFoundException(idRepoException);
    }
    if (ldapResultCode == ResultCode.NOT_ALLOWED_ON_RDN) {
        return new ForbiddenException(idRepoException);
    }
    // Compute error code
    switch(code) {
        case GENERAL_OBJECT_NOT_FOUND:
            return new NotFoundException(idRepoException);
        case GENERAL_ACCESS_DENIED:
            return new ForbiddenException(idRepoException);
        default:
            return new InternalServerErrorException(idRepoException);
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) PasswordPolicyException(com.sun.identity.idm.PasswordPolicyException) BadRequestException(org.forgerock.json.resource.BadRequestException) NotFoundException(org.forgerock.json.resource.NotFoundException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResultCode(org.forgerock.opendj.ldap.ResultCode)

Example 13 with BadRequestException

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

the class MailService method sendEmail.

// Mapping to known type
@SuppressWarnings("unchecked")
private JsonValue sendEmail(String realm, JsonValue jsonValue) throws ResourceException {
    String to = jsonValue.get("to").asString();
    if (isBlank(to)) {
        throw new BadRequestException("to field is missing");
    }
    String mimeType = jsonValue.get("type").asString();
    if (isBlank(mimeType)) {
        throw new BadRequestException("mime type needs to be specified");
    }
    String subject = jsonValue.get("subject").asString();
    String body = jsonValue.get("body").asString();
    Map<String, Set<String>> mailConfigAttributes;
    try {
        ServiceConfigManager configManager = new ServiceConfigManager(RestUtils.getToken(), MailServerImpl.SERVICE_NAME, MailServerImpl.SERVICE_VERSION);
        ServiceConfig mailConfig = configManager.getOrganizationConfig(realm, null);
        mailConfigAttributes = mailConfig.getAttributes();
    } catch (SMSException | SSOException e) {
        throw new InternalServerErrorException("Cannot create the service " + MailServerImpl.SERVICE_NAME, e);
    }
    if (isEmpty(mailConfigAttributes)) {
        throw new InternalServerErrorException("No service mail config found for realm " + realm);
    }
    MailServer mailServer;
    try {
        String attr = mailConfigAttributes.get(MAIL_SERVER_CLASS).iterator().next();
        mailServer = mailServerLoader.load(attr, realm);
    } catch (IllegalStateException e) {
        throw new InternalServerErrorException("Failed to create mail server", e);
    }
    if (isBlank(subject)) {
        subject = mailConfigAttributes.get(MAIL_SUBJECT).iterator().next();
    }
    if (isBlank(body)) {
        body = mailConfigAttributes.get(MAIL_BODY).iterator().next();
    }
    try {
        mailServer.sendEmail(to, subject, body, mimeType);
    } catch (MessagingException e) {
        throw new InternalServerErrorException("Failed to send email", e);
    }
    return json(object(field("success", "true")));
}
Also used : Set(java.util.Set) SMSException(com.sun.identity.sm.SMSException) MessagingException(javax.mail.MessagingException) SSOException(com.iplanet.sso.SSOException) MailServer(org.forgerock.openam.services.email.MailServer) ServiceConfig(com.sun.identity.sm.ServiceConfig) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager)

Example 14 with BadRequestException

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

the class CrestProtocolEnforcementFilter method defaultProtocolVersion.

private Version defaultProtocolVersion(Request request) throws BadRequestException {
    AcceptApiVersionHeader apiVersionHeader;
    try {
        apiVersionHeader = AcceptApiVersionHeader.valueOf(request);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e);
    }
    apiVersionHeader.withDefaultProtocolVersion(ENFORCE_PROTOCOL_VERSION);
    request.getHeaders().put(apiVersionHeader);
    return apiVersionHeader.getProtocolVersion();
}
Also used : BadRequestException(org.forgerock.json.resource.BadRequestException) AcceptApiVersionHeader(org.forgerock.http.header.AcceptApiVersionHeader)

Example 15 with BadRequestException

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

the class RestSTSPublishServiceRequestHandler method handleUpdate.

/*
      * A PUT to the url composed of the publish endpont + the sts instance id with a payload corresponding to a
      * RestSTSInstanceId (wrapped in invocation context information) will result in republishing the existing instance
      * (which is a delete followed by a create).
      */
public Promise<ResourceResponse, ResourceException> handleUpdate(Context context, UpdateRequest request) {
    String stsId = request.getResourcePath();
    String realm = getRealmFromResourceName(request.getResourcePath());
    if (!realmValidator.isRealm(realm)) {
        logger.warn("Update of rest STS instance state for instance " + stsId + " in realm " + realm + " rejected because realm does not exist");
        return new NotFoundException("The specified realm does not exist.").asPromise();
    }
    /*
        Insure that the instance is published before performing an update.
         */
    final boolean publishedToSMS;
    try {
        publishedToSMS = publisher.isInstancePersistedInSMS(stsId, realm);
    } catch (STSPublishException e) {
        logger.error("In RestSTSPublishServiceRequestHandler#handleUpdate, exception caught determining whether " + "instance persisted in SMS. Instance not updated. Exception: " + e, e);
        return e.asPromise();
    }
    final boolean publishedToCrest = publisher.isInstanceExposedInCrest(stsId);
    if (publishedToSMS) {
        if (!publishedToCrest) {
            /*
                Entering this branch would seem to be an error condition. It could possibly happen in a site deployment,
                where a rest sts instance is published to a different server than the current server, and the registered
                ServiceListener was not called when the ldap replication created the service entry on the current server.
                I will log a warning, and still publish the instance, just for robustness.
                 */
            logger.warn("The rest sts instance " + stsId + " in realm " + realm + " is present in the SMS, but " + "has not been hung off of the CREST router. This is an illegal state. The instance will be" + " republished.");
        }
        RestSTSInstanceConfig instanceConfig;
        try {
            instanceConfig = marshalInstanceConfigFromInvocation(request.getContent());
        } catch (BadRequestException e) {
            logger.error("In RestSTSPublishServiceRequestHandler#handleUpdate, exception caught marshalling " + "invocation state to RestSTSInstanceConfig. Instance not updated. The state: " + request.getContent() + "Exception: " + e, e);
            return e.asPromise();
        }
        Injector instanceInjector;
        try {
            instanceInjector = createInjector(instanceConfig);
        } catch (ResourceException e) {
            logger.error("In RestSTSPublishServiceRequestHandler#handleUpdate, exception caught creating an " + "Injector using the RestSTSInstanceConfig. The instance: " + instanceConfig.toJson() + "; Exception: " + e, e);
            return e.asPromise();
        }
        try {
            publisher.updateInstanceInSMS(stsId, realm, instanceConfig, instanceInjector.getInstance(RestSTS.class));
            return newResultPromise(newResourceResponse(instanceConfig.getDeploymentSubPath(), Integer.toString(instanceConfig.hashCode()), json(object(field(RESULT, SUCCESS)))));
        } catch (STSPublishException e) {
            logger.error("In RestSTSPublishServiceRequestHandler#handleUpdate, exception caught removing " + "rest sts instance " + instanceConfig.getDeploymentSubPath() + ". This means instance is" + "in indeterminate state, and has not been updated. The instance config: " + instanceConfig + "; Exception: " + e, e);
            return e.asPromise();
        }
    } else {
        //404 - realm and id not found in SMS
        return new NotFoundException("No rest sts instance with id " + stsId + " in realm " + realm).asPromise();
    }
}
Also used : RestSTSInstanceConfig(org.forgerock.openam.sts.rest.config.user.RestSTSInstanceConfig) Injector(com.google.inject.Injector) STSPublishException(org.forgerock.openam.sts.STSPublishException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) RestSTS(org.forgerock.openam.sts.rest.RestSTS)

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