Search in sources :

Example 26 with BadRequestException

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

the class RestSTSPublishServiceRequestHandler method handleCreate.

/*
     This method will be invoked by either a programmatic client, in which case a RestSTSInstanceConfig has emitted
     properly-formatted json, or from the RestSecurityTokenServiceViewBean, in which case the configuration state is
     in the sms-centric Map<String, Set<String>> format. This method needs to be able to handle both invocation types,
     and marshal the invocation state in to a RestSTSInstanceConfig instance either way. It also needs to return an accurate
     error message, so that in the case of RestSecurityTokenServiceViewBean invocation, the user can make appropriate
      corrections to the configuration state.
      */
public Promise<ResourceResponse, ResourceException> handleCreate(Context context, CreateRequest request) {
    final RestSTSInstanceConfig instanceConfig;
    try {
        instanceConfig = marshalInstanceConfigFromInvocation(request.getContent());
    } catch (BadRequestException e) {
        return e.asPromise();
    }
    if (!realmValidator.isRealm(instanceConfig.getDeploymentConfig().getRealm())) {
        logger.warn("Publish of Rest STS instance " + instanceConfig.getDeploymentSubPath() + " to realm " + instanceConfig.getDeploymentConfig().getRealm() + " rejected because realm does not exist.");
        return new NotFoundException("The specified realm does not exist.").asPromise();
    }
    Injector instanceInjector;
    try {
        instanceInjector = createInjector(instanceConfig);
    } catch (ResourceException e) {
        return e.asPromise();
    }
    return publishInstance(instanceConfig, instanceInjector);
}
Also used : RestSTSInstanceConfig(org.forgerock.openam.sts.rest.config.user.RestSTSInstanceConfig) Injector(com.google.inject.Injector) BadRequestException(org.forgerock.json.resource.BadRequestException) NotFoundException(org.forgerock.json.resource.NotFoundException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 27 with BadRequestException

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

the class IdentityServicesImpl method search.

/**
     * Searches the identity repository to find all identities that match the search criteria.
     *
     * @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 identifiers.
     * @throws ResourceException
     */
public List<String> search(CrestQuery crestQuery, Map<String, Set<String>> searchModifiers, SSOToken admin) throws ResourceException {
    List<String> rv = new ArrayList<>();
    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> objList = fetchAMIdentities(idType, crestQuery, false, repo, searchModifiers);
            if (objList != null && !objList.isEmpty()) {
                List<String> names = getNames(realm, idType, objList);
                if (!names.isEmpty()) {
                    for (String name : names) {
                        rv.add(name);
                    }
                }
            }
        } else {
            debug.error("IdentityServicesImpl:search unsupported IdType" + objectType);
            throw new BadRequestException("search unsupported IdType: " + objectType);
        }
    } catch (IdRepoException e) {
        debug.error("IdentityServicesImpl:search", e);
        throw new InternalServerErrorException(e.getMessage());
    } catch (SSOException e) {
        debug.error("IdentityServicesImpl:search", e);
        throw new InternalServerErrorException(e.getMessage());
    } catch (ObjectNotFound e) {
        debug.error("IdentityServicesImpl:search", e);
        throw new NotFoundException(e.getMessage());
    }
    return rv;
}
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) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Example 28 with BadRequestException

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

the class IdentityServicesImpl method delete.

/**
     * Deletes an {@code AMIdentity} from the identity repository that match
     * the details specified in {@code identity}.
     *
     * @param identity The identity to delete.
     * @param admin The admin token.
     * @throws ResourceException If a problem occurs.
     */
public void delete(IdentityDetails identity, SSOToken admin) throws ResourceException {
    if (identity == null) {
        throw new BadRequestException("delete failed: identity object not specified.");
    }
    String name = identity.getName();
    String identityType = identity.getType();
    String realm = identity.getRealm();
    if (name == null) {
        throw new NotFoundException("delete failed: null object name.");
    }
    if (realm == null) {
        realm = "/";
    }
    try {
        AMIdentity amIdentity = getAMIdentity(admin, identityType, name, realm);
        if (amIdentity != null) {
            if (isSpecialUser(amIdentity)) {
                throw new ForbiddenException("Cannot delete user.");
            }
            AMIdentityRepository repo = getRepo(admin, realm);
            IdType idType = amIdentity.getType();
            if (IdType.GROUP.equals(idType) || IdType.ROLE.equals(idType)) {
                // First remove users from memberships
                Set<AMIdentity> members = getMembers(amIdentity, IdType.USER);
                for (AMIdentity member : members) {
                    try {
                        removeMember(repo, amIdentity, member);
                    } catch (IdRepoException ex) {
                    //ignore this, member maybe already removed.
                    }
                }
            }
            deleteAMIdentity(repo, amIdentity);
        } else {
            String msg = "Object \'" + name + "\' of type \'" + identityType + "\' was not found.";
            throw new NotFoundException(msg);
        }
    } catch (IdRepoException ex) {
        debug.error("IdentityServicesImpl:delete", ex);
        throw RESOURCE_MAPPING_HANDLER.handleError(ex);
    } catch (SSOException ex) {
        debug.error("IdentityServicesImpl:delete", ex);
        throw new BadRequestException(ex.getMessage());
    } catch (ObjectNotFound e) {
        debug.error("IdentityServicesImpl:delete", e);
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdRepoException(com.sun.identity.idm.IdRepoException) BadRequestException(org.forgerock.json.resource.BadRequestException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType)

Example 29 with BadRequestException

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

the class ResourceTypesResource method queryCollection.

/**
     * Reads the details of all {@link org.forgerock.openam.entitlement.ResourceType}s in the system.
     *
     * The user's {@link org.forgerock.json.resource.SecurityContext} must indicate they are a user with
     * administrator-level access.
     *
     * @param context {@inheritDoc}
     * @param request {@inheritDoc}
     * @param handler {@inheritDoc}
     */
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
    String principalName = "unknown";
    String realm = getRealm(context);
    QueryFilter<JsonPointer> queryFilter = request.getQueryFilter();
    try {
        Subject subject = getSubject(context);
        principalName = PrincipalRestUtils.getPrincipalNameFromSubject(subject);
        Map<String, Map<String, Set<String>>> configData = resourceTypeService.getResourceTypesData(subject, realm);
        Set<String> filterResults;
        if (queryFilter == null) {
            filterResults = configData.keySet();
        } else {
            filterResults = queryFilter.accept(new DataQueryFilterVisitor(), configData);
        }
        List<ResourceResponse> results = new ArrayList<>();
        for (String uuid : filterResults) {
            ResourceType resourceType = resourceTypeService.getResourceType(subject, realm, uuid);
            results.add(newResourceResponse(resourceType.getUUID(), null, new JsonResourceType(resourceType).toJsonValue()));
        }
        QueryResponsePresentation.enableDeprecatedRemainingQueryResponse(request);
        return QueryResponsePresentation.perform(handler, request, results);
    } catch (EntitlementException ee) {
        if (logger.errorEnabled()) {
            logger.error("ResourceTypesResource :: QUERY by " + principalName + ": Caused EntitlementException: ", ee);
        }
        return exceptionMappingHandler.handleError(context, request, ee).asPromise();
    } catch (QueryException e) {
        return new BadRequestException(e.getL10NMessage(ServerContextUtils.getLocaleFromContext(context))).asPromise();
    }
}
Also used : JsonResourceType(org.forgerock.openam.entitlement.rest.wrappers.JsonResourceType) JsonResourceType(org.forgerock.openam.entitlement.rest.wrappers.JsonResourceType) ResourceType(org.forgerock.openam.entitlement.ResourceType) JsonPointer(org.forgerock.json.JsonPointer) Subject(javax.security.auth.Subject) EntitlementException(com.sun.identity.entitlement.EntitlementException) QueryException(org.forgerock.openam.rest.query.QueryException) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) BadRequestException(org.forgerock.json.resource.BadRequestException) DataQueryFilterVisitor(org.forgerock.openam.rest.query.DataQueryFilterVisitor)

Example 30 with BadRequestException

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

the class ApplicationV1Filter method filterUpdate.

/**
     * Update expects the application json to contain both actions and resources; these attributes are part of the old
     * json definition for an application. It also expects that the mentioned application exists with exactly one
     * resource type - no resource types or many resource types is not acceptable, else it is impossible to determine
     * which resource type applies to the set of actions and resources being passed as part of the application json.
     * <p/>
     * Changes to the actions and/or resources will be reflected in the applications associated resource type.
     *
     * @param context
     *         the filter chain context
     * @param request
     *         the update request
     * @param next
     *         a request handler representing the remainder of the filter chain
     */
@Override
public Promise<ResourceResponse, ResourceException> filterUpdate(final Context context, final UpdateRequest request, final RequestHandler next) {
    final JsonValue jsonValue = request.getContent();
    final Map<String, Boolean> actions = jsonValue.get(ACTIONS).asMap(Boolean.class);
    final Set<String> resources = jsonValue.get(RESOURCES).asSet(String.class);
    final String bodyRealm = jsonValue.get(REALM).asString();
    final String pathRealm = contextHelper.getRealm(context);
    if (actions == null) {
        return new BadRequestException("Invalid actions defined in request").asPromise();
    }
    if (resources == null) {
        return new BadRequestException("Invalid resources defined in request").asPromise();
    }
    if (!pathRealm.equals(bodyRealm)) {
        return resourceErrorHandler.handleError(context, request, new EntitlementException(EntitlementException.INVALID_APP_REALM, new String[] { bodyRealm, pathRealm })).asPromise();
    }
    final Subject callingSubject = contextHelper.getSubject(context);
    final String applicationName = request.getResourcePath();
    try {
        final ApplicationService applicationService = applicationServiceFactory.create(callingSubject, pathRealm);
        final Application application = applicationService.getApplication(applicationName);
        if (application == null) {
            return new NotFoundException("Unable to find application " + applicationName).asPromise();
        }
        if (application.getResourceTypeUuids().size() != 1) {
            return new BadRequestException("Cannot modify application with more than one " + "resource type using version 1.0 of this endpoint").asPromise();
        }
        // Retrieve the resource type from the applications single resource type.
        final String resourceTypeUuid = application.getResourceTypeUuids().iterator().next();
        ResourceType resourceType = resourceTypeService.getResourceType(callingSubject, pathRealm, resourceTypeUuid);
        boolean resourceTypeModified = false;
        if (!actions.equals(resourceType.getActions())) {
            resourceTypeModified = true;
            resourceType = resourceType.populatedBuilder().setActions(actions).build();
        }
        if (!resources.equals(resourceType.getPatterns())) {
            resourceTypeModified = true;
            resourceType = resourceType.populatedBuilder().setPatterns(resources).build();
        }
        if (resourceTypeModified) {
            resourceTypeService.updateResourceType(callingSubject, pathRealm, resourceType);
        }
        // Ensure the resource type UUID isn't lost.
        jsonValue.put(RESOURCE_TYPE_UUIDS, new HashSet<String>(Arrays.asList(resourceTypeUuid)));
    } catch (EntitlementException eE) {
        debug.error("Error filtering application update CREST request", eE);
        return resourceErrorHandler.handleError(context, request, eE).asPromise();
    }
    // Forward onto next handler.
    return applicationTransformer.transform(next.handleUpdate(context, request), context);
}
Also used : JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) ResourceType(org.forgerock.openam.entitlement.ResourceType) Subject(javax.security.auth.Subject) EntitlementException(com.sun.identity.entitlement.EntitlementException) BadRequestException(org.forgerock.json.resource.BadRequestException) Application(com.sun.identity.entitlement.Application) ApplicationService(org.forgerock.openam.entitlement.service.ApplicationService)

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