Search in sources :

Example 1 with LdapException

use of org.forgerock.opendj.ldap.LdapException in project OpenAM by OpenRock.

the class DSAMERole method getValidValues.

/**
     * Returns a list of possible values for the <code>Subject
     * </code> that matches the pattern. 
     *
     * @param token the <code>SSOToken</code> that will be used
     * to determine the possible values
     *
     * @return <code>ValidValues</code> object
     *
     * @exception SSOException if SSO token is not valid
     * @exception PolicyException if unable to get the list of valid
     * names.
     */
public ValidValues getValidValues(SSOToken token, String pattern) throws SSOException, PolicyException {
    if (!initialized) {
        throw (new PolicyException(ResBundleUtils.rbName, "role_subject_not_yet_initialized", null, null));
    }
    try {
        AMStoreConnection amConnection = new AMStoreConnection(token);
        AMOrganization orgObject = amConnection.getOrganization(organizationDN);
        AMSearchControl sc = new AMSearchControl();
        sc.setMaxResults(maxResults);
        sc.setTimeOut(timeLimit);
        sc.setSearchScope(roleSearchScope);
        AMSearchResults results = orgObject.searchAllRoles(pattern, sc);
        int status;
        switch(results.getErrorCode()) {
            case AMSearchResults.SUCCESS:
                status = ValidValues.SUCCESS;
                break;
            case AMSearchResults.SIZE_LIMIT_EXCEEDED:
                status = ValidValues.SIZE_LIMIT_EXCEEDED;
                break;
            case AMSearchResults.TIME_LIMIT_EXCEEDED:
                status = ValidValues.TIME_LIMIT_EXCEEDED;
                break;
            default:
                status = ValidValues.SUCCESS;
        }
        return new ValidValues(status, results.getSearchResults());
    } catch (AMException e) {
        LdapException lde = e.getLDAPException();
        if (lde != null) {
            ResultCode ldapErrorCode = lde.getResult().getResultCode();
            if (ResultCode.INVALID_CREDENTIALS.equals(ldapErrorCode)) {
                throw new PolicyException(ResBundleUtils.rbName, "ldap_invalid_password", null, null);
            } else if (ResultCode.NO_SUCH_OBJECT.equals(ldapErrorCode)) {
                String[] objs = { organizationDN };
                throw new PolicyException(ResBundleUtils.rbName, "no_such_am_roles_base_dn", objs, null);
            }
            String errorMsg = lde.getResult().getDiagnosticMessage();
            String additionalMsg = lde.getResult().getResultCode().getName().toString(Locale.ROOT);
            if (additionalMsg != null) {
                throw new PolicyException(errorMsg + ": " + additionalMsg);
            } else {
                throw new PolicyException(errorMsg);
            }
        }
        throw new PolicyException(e);
    }
}
Also used : AMStoreConnection(com.iplanet.am.sdk.AMStoreConnection) AMSearchControl(com.iplanet.am.sdk.AMSearchControl) PolicyException(com.sun.identity.policy.PolicyException) ValidValues(com.sun.identity.policy.ValidValues) AMOrganization(com.iplanet.am.sdk.AMOrganization) AMException(com.iplanet.am.sdk.AMException) AMSearchResults(com.iplanet.am.sdk.AMSearchResults) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode)

Example 2 with LdapException

use of org.forgerock.opendj.ldap.LdapException 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 3 with LdapException

use of org.forgerock.opendj.ldap.LdapException 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 4 with LdapException

use of org.forgerock.opendj.ldap.LdapException in project OpenAM by OpenRock.

the class Step3 method validateSMHost.

/**
     * Validate an Existing SM Host for Configuration Backend.
     * @return
     */
public boolean validateSMHost() {
    Context ctx = getContext();
    String strSSL = (String) ctx.getSessionAttribute(SessionAttributeNames.CONFIG_STORE_SSL);
    boolean ssl = (strSSL != null) && (strSSL.equals("SSL"));
    String host = (String) ctx.getSessionAttribute(SessionAttributeNames.CONFIG_STORE_HOST);
    if (host == null) {
        host = "localhost";
    }
    String strPort = (String) ctx.getSessionAttribute(SessionAttributeNames.CONFIG_STORE_PORT);
    if (strPort == null) {
        strPort = getAvailablePort(50389);
    }
    int port = Integer.parseInt(strPort);
    String bindDN = (String) ctx.getSessionAttribute(SessionAttributeNames.CONFIG_STORE_LOGIN_ID);
    String rootSuffix = (String) ctx.getSessionAttribute(SessionAttributeNames.CONFIG_STORE_ROOT_SUFFIX);
    String bindPwd = (String) ctx.getSessionAttribute(SessionAttributeNames.CONFIG_STORE_PWD);
    if (bindDN == null) {
        bindDN = "cn=Directory Manager";
    }
    if (rootSuffix == null) {
        rootSuffix = Constants.DEFAULT_ROOT_SUFFIX;
    }
    try (Connection conn = getConnection(host, port, bindDN, bindPwd.toCharArray(), 5, ssl)) {
        String filter = "cn=" + "\"" + rootSuffix + "\"";
        String[] attrs = { "" };
        conn.search(LDAPRequests.newSearchRequest(rootSuffix, SearchScope.BASE_OBJECT, filter, attrs));
        writeToResponse("ok");
    } catch (LdapException lex) {
        if (!writeErrorToResponse(lex.getResult().getResultCode())) {
            writeToResponse(getLocalizedString("cannot.connect.to.SM.datastore"));
        }
    } catch (Exception e) {
        writeToResponse(getLocalizedString("cannot.connect.to.SM.datastore"));
    }
    setPath(null);
    return false;
}
Also used : Context(org.apache.click.Context) Connection(org.forgerock.opendj.ldap.Connection) LdapException(org.forgerock.opendj.ldap.LdapException) LdapException(org.forgerock.opendj.ldap.LdapException) ConfiguratorException(com.sun.identity.setup.ConfiguratorException) UnknownHostException(java.net.UnknownHostException) ConfigurationException(com.sun.identity.common.configuration.ConfigurationException)

Example 5 with LdapException

use of org.forgerock.opendj.ldap.LdapException in project OpenAM by OpenRock.

the class LDAPUsers method getUserDN.

/**
     * Gets the DN for a user identified 
     * by the token. If the Directory server is locally installed to speed
     * up the search, no directoty search is performed and the DN obtained
     * from the token is returned. If the directory is remote
     * a LDAP search is performed to get the user DN.
     */
private DN getUserDN(SSOToken token) throws SSOException, PolicyException {
    Set<String> qualifiedUserDNs = new HashSet<>();
    String userLocalDN = token.getPrincipal().getName();
    DN userDN = null;
    if (localDS && !PolicyUtils.principalNameEqualsUuid(token)) {
        userDN = DN.valueOf(userLocalDN);
    } else {
        // try to figure out the user name from the local user DN
        int beginIndex = userLocalDN.indexOf("=");
        int endIndex = userLocalDN.indexOf(",");
        if ((beginIndex <= 0) || (endIndex <= 0) || (beginIndex >= endIndex)) {
            throw (new PolicyException(ResBundleUtils.rbName, "ldapusers_subject_invalid_local_user_dn", null, null));
        }
        String userName = userLocalDN.substring(beginIndex + 1, endIndex);
        String searchFilter = null;
        if ((userSearchFilter != null) && !(userSearchFilter.length() == 0)) {
            searchFilter = "(&" + userSearchFilter + PolicyUtils.constructUserFilter(token, userRDNAttrName, userName, aliasEnabled) + ")";
        } else {
            searchFilter = PolicyUtils.constructUserFilter(token, userRDNAttrName, userName, aliasEnabled);
        }
        if (debug.messageEnabled()) {
            debug.message("LDAPUsers.getUserDN(): search filter is: " + searchFilter);
        }
        String[] attrs = { userRDNAttrName };
        // search the remote ldap and find out the user DN
        try (Connection ld = connPool.getConnection()) {
            ConnectionEntryReader res = search(searchFilter, ld, attrs);
            while (res.hasNext()) {
                try {
                    SearchResultEntry entry = res.readEntry();
                    qualifiedUserDNs.add(entry.getName().toString());
                } catch (SearchResultReferenceIOException e) {
                    // ignore referrals
                    continue;
                } catch (LdapException e) {
                    String[] objs = { orgName };
                    ResultCode resultCode = e.getResult().getResultCode();
                    if (resultCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
                        debug.warning("LDAPUsers.getUserDN(): exceeded the size limit");
                        throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_size_limit", objs, null);
                    } else if (resultCode.equals(ResultCode.TIME_LIMIT_EXCEEDED)) {
                        debug.warning("LDAPUsers.getUserDN(): exceeded the time limit");
                        throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_time_limit", objs, null);
                    } else {
                        throw new PolicyException(e);
                    }
                }
            }
        } catch (LdapException e) {
            throw handleResultException(e);
        } catch (Exception e) {
            throw new PolicyException(e);
        }
        // check if the user belongs to any of the selected users
        if (qualifiedUserDNs.size() > 0) {
            debug.message("LDAPUsers.getUserDN(): qualified users={}", qualifiedUserDNs);
            Iterator<String> iter = qualifiedUserDNs.iterator();
            // we only take the first qualified DN
            userDN = DN.valueOf(iter.next());
        }
    }
    return userDN;
}
Also used : Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) NameNotFoundException(com.sun.identity.policy.NameNotFoundException) PolicyException(com.sun.identity.policy.PolicyException) InvalidNameException(com.sun.identity.policy.InvalidNameException) SSOException(com.iplanet.sso.SSOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PolicyException(com.sun.identity.policy.PolicyException) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) HashSet(java.util.HashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Aggregations

LdapException (org.forgerock.opendj.ldap.LdapException)90 Connection (org.forgerock.opendj.ldap.Connection)64 ByteString (org.forgerock.opendj.ldap.ByteString)45 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)38 ResultCode (org.forgerock.opendj.ldap.ResultCode)37 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)37 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)24 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)24 HashSet (java.util.HashSet)22 Attribute (org.forgerock.opendj.ldap.Attribute)19 PolicyException (com.sun.identity.policy.PolicyException)13 SMSException (com.sun.identity.sm.SMSException)12 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)12 SSOException (com.iplanet.sso.SSOException)11 LinkedHashSet (java.util.LinkedHashSet)11 DN (org.forgerock.opendj.ldap.DN)11 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)10 IOException (java.io.IOException)10 InvalidNameException (com.sun.identity.policy.InvalidNameException)9 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)9