Search in sources :

Example 6 with PermanentException

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

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

the class SmsRealmProvider method handleDelete.

@Override
public Promise<ResourceResponse, ResourceException> handleDelete(Context serverContext, DeleteRequest request) {
    RealmContext realmContext = serverContext.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();
    try {
        OrganizationConfigManager realmManager = new OrganizationConfigManager(getSSOToken(), realmPath);
        final ResourceResponse resource = getResource(getJsonValue(realmPath));
        realmManager.deleteSubOrganization(null, false);
        String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(serverContext);
        debug.message("RealmResource.deleteInstance :: DELETE of realm " + realmPath + " performed by " + principalName);
        return newResultPromise(resource);
    } catch (SMSException smse) {
        ResourceException exception = configureErrorMessage(smse);
        if (exception instanceof NotFoundException) {
            debug.warning("RealmResource.deleteInstance() : Cannot find {}", realmPath, smse);
            return exception.asPromise();
        } else if (exception instanceof ForbiddenException || exception instanceof PermanentException || exception instanceof ConflictException || exception instanceof BadRequestException) {
            debug.warning("RealmResource.deleteInstance() : Cannot DELETE {}", realmPath, smse);
            return exception.asPromise();
        } else {
            return new BadRequestException(exception.getMessage(), exception).asPromise();
        }
    } catch (Exception e) {
        return new BadRequestException(e.getMessage(), e).asPromise();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) RealmContext(org.forgerock.openam.rest.RealmContext) ResourceResponse(org.forgerock.json.resource.ResourceResponse) SMSException(com.sun.identity.sm.SMSException) ConflictException(org.forgerock.json.resource.ConflictException) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) PermanentException(org.forgerock.json.resource.PermanentException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) 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) SessionException(com.iplanet.dpro.session.SessionException)

Example 8 with PermanentException

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

the class SmsRealmProvider method handleRead.

@Override
public Promise<ResourceResponse, ResourceException> handleRead(Context context, ReadRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();
    if (!request.getResourcePath().isEmpty()) {
        //if the resource path is not empty, the realm has not resolved correctly
        return new NotFoundException("Realm \"" + RealmUtils.concatenateRealmPath(RealmUtils.cleanRealm(realmPath), RealmUtils.cleanRealm(request.getResourcePath())) + "\" is not a valid realm.").asPromise();
    }
    try {
        JsonValue jsonResponse = getJsonValue(realmPath);
        if (debug.messageEnabled()) {
            debug.message("RealmResource.readInstance :: READ : Successfully read realm, " + realmPath + " performed by " + PrincipalRestUtils.getPrincipalNameFromServerContext(context));
        }
        return newResultPromise(getResource(jsonResponse));
    } catch (SMSException smse) {
        ResourceException exception = configureErrorMessage(smse);
        if (exception instanceof NotFoundException) {
            debug.warning("RealmResource.readInstance() : Cannot find {}", realmPath, smse);
            return exception.asPromise();
        } else if (exception instanceof ForbiddenException || exception instanceof PermanentException || exception instanceof ConflictException || exception instanceof BadRequestException) {
            debug.warning("RealmResource.readInstance() : Cannot READ {}", realmPath, smse);
            return exception.asPromise();
        } else {
            return new BadRequestException(exception.getMessage(), exception).asPromise();
        }
    } catch (Exception e) {
        return new BadRequestException(e.getMessage(), e).asPromise();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) RealmContext(org.forgerock.openam.rest.RealmContext) SMSException(com.sun.identity.sm.SMSException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) 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) SessionException(com.iplanet.dpro.session.SessionException)

Example 9 with PermanentException

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

the class XMLResourceExceptionHandler method write.

@Override
public void write(MessageContext context, AuthenticationException exception) {
    Reject.ifNull(exception);
    try {
        ResourceException jre;
        if (exception instanceof AuthenticationFailedException) {
            jre = new PermanentException(Status.UNAUTHORIZED.getCode(), exception.getMessage(), null);
        } else if (exception.getCause() instanceof ResourceException) {
            jre = (ResourceException) exception.getCause();
        } else {
            LOGGER.error(exception.getMessage(), exception);
            jre = new InternalServerErrorException("Authentication Failed", exception);
        }
        AuditTrail auditTrail = context.getAuditTrail();
        List<Map<String, Object>> failureReasonList = auditTrail.getFailureReasons();
        if (failureReasonList != null && !failureReasonList.isEmpty()) {
            jre.setDetail(json(object(field("failureReasons", failureReasonList))));
        }
        Response response = context.getResponse();
        response.setStatus(Status.valueOf(jre.getCode()));
        context.<Response>getResponse().getHeaders().put(ContentTypeHeader.valueOf(MediaType.XML_UTF_8.toString()));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Transformer transformer = XMLUtils.getTransformerFactory().newTransformer();
        transformer.transform(new DOMSource(asXMLDOM(jre.includeCauseInJsonValue().toJsonValue().asMap())), new StreamResult(outputStream));
        response.getEntity().setBytes(outputStream.toByteArray());
    } catch (TransformerException e1) {
        throw new IllegalStateException("Could not write XML to response", e1);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) AuthenticationFailedException(org.forgerock.caf.authentication.framework.AuthenticationFailedException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Response(org.forgerock.http.protocol.Response) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException) AuditTrail(org.forgerock.caf.authentication.framework.AuditTrail) Map(java.util.Map) TransformerException(javax.xml.transform.TransformerException)

Example 10 with PermanentException

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

the class ClientResource method createInstance.

public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest createRequest) {
    String principal = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
    Map<String, String> responseVal = new HashMap<String, String>();
    try {
        if (serviceSchema == null || serviceSchemaManager == null) {
            if (debug.errorEnabled()) {
                debug.error("ClientResource :: CREATE by " + principal + ": No serviceSchema available.");
            }
            throw new PermanentException(ResourceException.INTERNAL_ERROR, "", null);
        }
        Map<String, ArrayList<String>> client = (Map<String, ArrayList<String>>) createRequest.getContent().getObject();
        String realm = null;
        if (client == null || client.isEmpty()) {
            if (debug.errorEnabled()) {
                debug.error("ClientResource :: CREATE by " + principal + ": No client definition.");
            }
            throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client definition", null);
        }
        //check for id
        String id = createRequest.getNewResourceId();
        if (client.containsKey(OAuth2Constants.OAuth2Client.CLIENT_ID)) {
            ArrayList<String> idList = client.remove(OAuth2Constants.OAuth2Client.CLIENT_ID);
            if (idList != null && !idList.isEmpty()) {
                id = idList.iterator().next();
            }
        }
        if (id == null || id.isEmpty()) {
            debug.error("ClientResource :: CREATE by " + principal + ": No client ID.");
            throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client id", null);
        }
        //get realm
        if (client.containsKey(OAuth2Constants.OAuth2Client.REALM)) {
            ArrayList<String> realmList = client.remove(OAuth2Constants.OAuth2Client.REALM);
            if (realmList != null && !realmList.isEmpty()) {
                realm = realmList.iterator().next();
            }
        }
        //check for required parameters
        if (!client.containsKey(OAuth2Constants.OAuth2Client.USERPASSWORD) || client.get(OAuth2Constants.OAuth2Client.USERPASSWORD).iterator().next().isEmpty()) {
            if (debug.errorEnabled()) {
                debug.error("ClientResource :: CREATE by " + principal + ": " + "Resource ID: " + id + ": No user password.");
            }
            throw new PermanentException(ResourceException.BAD_REQUEST, "Missing user password", null);
        }
        if (client.containsKey(OAuth2Constants.OAuth2Client.CLIENT_TYPE)) {
            String type = client.get(OAuth2Constants.OAuth2Client.CLIENT_TYPE).iterator().next();
            if (!(type.equals("Confidential") || type.equals("Public"))) {
                debug.error("ClientResource :: CREATE by " + principal + ": " + "Resource ID: " + id + ": No client type.");
                throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client type", null);
            }
        } else {
            debug.error("ClientResource :: CREATE by" + principal + ": " + "Resource ID: " + id + ": No client type.");
            throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client type", null);
        }
        Map<String, Set<String>> attrs = new HashMap<String, Set<String>>();
        for (Map.Entry mapEntry : client.entrySet()) {
            List<String> list = (ArrayList) mapEntry.getValue();
            Set<String> set = new HashSet<String>();
            if (isSingle((String) mapEntry.getKey())) {
                set.add((String) ((ArrayList) mapEntry.getValue()).get(0));
            } else {
                for (int i = 0; i < list.size(); i++) {
                    set.add("[" + i + "]=" + list.get(i));
                }
            }
            attrs.put((String) mapEntry.getKey(), set);
        }
        Set<String> temp = new HashSet<String>();
        temp.add("OAuth2Client");
        attrs.put("AgentType", temp);
        temp = new HashSet<String>();
        temp.add("Active");
        attrs.put("sunIdentityServerDeviceStatus", temp);
        manager.createIdentity(realm, id, attrs);
        responseVal.put("success", "true");
        JsonValue response = new JsonValue(responseVal);
        ResourceResponse resource = newResourceResponse("results", String.valueOf(System.currentTimeMillis()), response);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_CLIENT", responseVal.toString() };
            auditLogger.logAccessMessage("CREATED_CLIENT", obs, null);
        }
        return newResultPromise(resource);
    } catch (IdRepoException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to " + "IdRepo exception.", e);
        }
        return new InternalServerErrorException("Unable to create client", e).asPromise();
    } catch (SSOException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to " + "SSO exception.", e);
        }
        return new InternalServerErrorException("Unable to create client", e).asPromise();
    } catch (PermanentException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to exception.", e);
        }
        return e.asPromise();
    } catch (org.forgerock.json.resource.BadRequestException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
        }
        debug.error("ClientResource :: CREATE : Unable to create client due to Bad Request.", e);
        return e.asPromise();
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SSOException(com.iplanet.sso.SSOException) PermanentException(org.forgerock.json.resource.PermanentException) HashSet(java.util.HashSet) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

PermanentException (org.forgerock.json.resource.PermanentException)21 SSOException (com.iplanet.sso.SSOException)19 ResourceException (org.forgerock.json.resource.ResourceException)17 BadRequestException (org.forgerock.json.resource.BadRequestException)16 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)16 NotFoundException (org.forgerock.json.resource.NotFoundException)16 SMSException (com.sun.identity.sm.SMSException)15 IdRepoException (com.sun.identity.idm.IdRepoException)14 JsonValue (org.forgerock.json.JsonValue)14 ForbiddenException (org.forgerock.json.resource.ForbiddenException)14 RealmContext (org.forgerock.openam.rest.RealmContext)13 ConflictException (org.forgerock.json.resource.ConflictException)12 ResourceResponse (org.forgerock.json.resource.ResourceResponse)10 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)9 NotSupportedException (org.forgerock.json.resource.NotSupportedException)8 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)7 ObjectNotFound (com.sun.identity.idsvcs.ObjectNotFound)7 TokenExpired (com.sun.identity.idsvcs.TokenExpired)7 OrganizationConfigManager (com.sun.identity.sm.OrganizationConfigManager)7 SSOToken (com.iplanet.sso.SSOToken)6