Search in sources :

Example 31 with InternalServerErrorException

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

the class UmaLabelsStore method read.

/**
     * Reads a label from the underlying database.
     * @param realm The current realm.
     * @param username The user that owns the label.
     * @param id The id of the label.
     * @return The retrieved label details.
     * @throws ResourceException Thrown if the label cannot be read.
     */
public ResourceSetLabel read(String realm, String username, String id) throws ResourceException {
    try (Connection connection = getConnection()) {
        SearchResultEntry entry = connection.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(getLabelDn(realm, username, id)));
        Set<String> resourceSets = new HashSet<>();
        final Attribute resourceSetAttribute = entry.getAttribute(RESOURCE_SET_ATTR);
        if (resourceSetAttribute != null) {
            for (ByteString resourceSetId : resourceSetAttribute) {
                resourceSets.add(resourceSetId.toString());
            }
        }
        return getResourceSetLabel(entry, resourceSets);
    } catch (LdapException e) {
        final ResultCode resultCode = e.getResult().getResultCode();
        if (resultCode.equals(ResultCode.NO_SUCH_OBJECT)) {
            throw new NotFoundException();
        }
        throw new InternalServerErrorException("Could not read", e);
    }
}
Also used : Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) NotFoundException(org.forgerock.json.resource.NotFoundException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) HashSet(java.util.HashSet)

Example 32 with InternalServerErrorException

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

the class UmaLabelsStore method query.

private Set<ResourceSetLabel> query(String realm, String username, Filter filter, boolean includeResourceSets) throws ResourceException {
    try (Connection connection = getConnection()) {
        Set<ResourceSetLabel> result = new HashSet<>();
        String[] attrs;
        if (includeResourceSets) {
            attrs = new String[] { ID_ATTR, NAME_ATTR, TYPE_ATTR, RESOURCE_SET_ATTR };
        } else {
            attrs = new String[] { ID_ATTR, NAME_ATTR, TYPE_ATTR };
        }
        ConnectionEntryReader searchResult = connection.search(LDAPRequests.newSearchRequest(getUserDn(realm, username), SearchScope.SUBORDINATES, filter, attrs));
        while (searchResult.hasNext()) {
            if (searchResult.isReference()) {
                debug.warning("Encountered reference {} searching for resource set labels for user {} in realm {}", searchResult.readReference(), username, realm);
            } else {
                final SearchResultEntry entry = searchResult.readEntry();
                result.add(getResourceSetLabel(entry, getResourceSetIds(entry)));
            }
        }
        return result;
    } catch (LdapException e) {
        if (e.getResult().getResultCode().equals(ResultCode.NO_SUCH_OBJECT)) {
            return Collections.emptySet();
        }
        throw new InternalServerErrorException("Could not complete search", e);
    } catch (SearchResultReferenceIOException e) {
        throw new InternalServerErrorException("Shouldn't get a reference as these have been handled", e);
    }
}
Also used : ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Connection(org.forgerock.opendj.ldap.Connection) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) HashSet(java.util.HashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 33 with InternalServerErrorException

use of org.forgerock.json.resource.InternalServerErrorException 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)

Example 34 with InternalServerErrorException

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

the class TokenResource method getExpiryDate.

private String getExpiryDate(JsonValue token, Context context) throws CoreTokenException, InternalServerErrorException, NotFoundException {
    OAuth2ProviderSettings oAuth2ProviderSettings;
    final String realm = getAttributeValue(token, "realm");
    try {
        oAuth2ProviderSettings = oAuth2ProviderSettingsFactory.get(realm);
    } catch (org.forgerock.oauth2.core.exceptions.NotFoundException e) {
        throw new NotFoundException(e.getMessage());
    }
    try {
        if (token.isDefined("refreshToken")) {
            if (oAuth2ProviderSettings.issueRefreshTokensOnRefreshingToken()) {
                return getIndefinitelyString(context);
            } else {
                //Use refresh token expiry
                JsonValue refreshToken = tokenStore.read(getAttributeValue(token, "refreshToken"));
                long expiryTimeInMilliseconds = Long.parseLong(getAttributeValue(refreshToken, EXPIRE_TIME_KEY));
                if (expiryTimeInMilliseconds == -1) {
                    return getIndefinitelyString(context);
                }
                return getDateFormat(context).format(new Date(expiryTimeInMilliseconds));
            }
        } else {
            //Use access token expiry
            long expiryTimeInMilliseconds = Long.parseLong(getAttributeValue(token, EXPIRE_TIME_KEY));
            return getDateFormat(context).format(new Date(expiryTimeInMilliseconds));
        }
    } catch (ServerException | SMSException | SSOException e) {
        throw new InternalServerErrorException(e);
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) SMSException(com.sun.identity.sm.SMSException) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) Date(java.util.Date) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 35 with InternalServerErrorException

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

the class OAuth2UserApplications method query.

/**
     * Allows users to query OAuth2 applications that they have given their consent access to and that have active
     * access and/or refresh tokens.
     *
     * <p>Applications consist of an id, a name (the client id), a set of scopes and an expiry time. The scopes field
     * is the union of the scopes of the individual access/refresh tokens. The expiry time is the time when the last
     * access/refresh token will expire, or null if the server is configured to allow tokens to be refreshed
     * indefinitely.</p>
     *
     * @param context The request context.
     * @param queryHandler The query handler.
     * @param request Unused but necessary for used of the {@link @Query} annotation.
     * @return A promise of a query response.
     */
@Query
public Promise<QueryResponse, ResourceException> query(Context context, QueryResourceHandler queryHandler, QueryRequest request) {
    String userId = contextHelper.getUserId(context);
    String realm = contextHelper.getRealm(context);
    try {
        QueryFilter<CoreTokenField> queryFilter = getQueryFilter(userId, realm);
        JsonValue tokens = tokenStore.query(queryFilter);
        Map<String, Set<JsonValue>> applicationTokensMap = new HashMap<>();
        for (JsonValue token : tokens) {
            String clientId = getAttributeValue(token, CLIENT_ID.getOAuthField());
            Set<JsonValue> applicationTokens = applicationTokensMap.get(clientId);
            if (applicationTokens == null) {
                applicationTokens = new HashSet<>();
                applicationTokensMap.put(clientId, applicationTokens);
            }
            applicationTokens.add(token);
        }
        for (Map.Entry<String, Set<JsonValue>> applicationTokens : applicationTokensMap.entrySet()) {
            ResourceResponse resource = getResourceResponse(context, applicationTokens.getKey(), applicationTokens.getValue());
            queryHandler.handleResource(resource);
        }
        return Promises.newResultPromise(Responses.newQueryResponse());
    } catch (CoreTokenException | ServerException | InvalidClientException | NotFoundException e) {
        debug.message("Failed to query OAuth2 clients for user {}", userId, e);
        return new InternalServerErrorException(e).asPromise();
    } catch (InternalServerErrorException e) {
        debug.message("Failed to query OAuth2 clients for user {}", userId, e);
        return e.asPromise();
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) ResourceResponse(org.forgerock.json.resource.ResourceResponse) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) HashMap(java.util.HashMap) Map(java.util.Map) Query(org.forgerock.json.resource.annotations.Query)

Aggregations

InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)70 SSOException (com.iplanet.sso.SSOException)39 JsonValue (org.forgerock.json.JsonValue)33 SMSException (com.sun.identity.sm.SMSException)29 BadRequestException (org.forgerock.json.resource.BadRequestException)27 NotFoundException (org.forgerock.json.resource.NotFoundException)25 ResourceException (org.forgerock.json.resource.ResourceException)24 SSOToken (com.iplanet.sso.SSOToken)19 IdRepoException (com.sun.identity.idm.IdRepoException)18 Set (java.util.Set)15 ResourceResponse (org.forgerock.json.resource.ResourceResponse)15 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)14 AMIdentity (com.sun.identity.idm.AMIdentity)13 ArrayList (java.util.ArrayList)11 HashSet (java.util.HashSet)11 ForbiddenException (org.forgerock.json.resource.ForbiddenException)11 ServiceConfig (com.sun.identity.sm.ServiceConfig)10 NotSupportedException (org.forgerock.json.resource.NotSupportedException)10 Responses.newResourceResponse (org.forgerock.json.resource.Responses.newResourceResponse)10 ServiceConfigManager (com.sun.identity.sm.ServiceConfigManager)9