Example usage for javax.naming NamingException getMessage

List of usage examples for javax.naming NamingException getMessage

Introduction

In this page you can find the example usage for javax.naming NamingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.swordess.ldap.odm.core.SessionImpl.java

private void disconnectIndirections(IndirectionsMetaData metaData, String oneDN, List<String> theOtherDNs) {
    if (StringUtils.isEmpty(oneDN) || CollectionUtils.isEmpty(theOtherDNs)) {
        LogUtils.debug(LOG, "disconnectIndirections: either one or theOther is empty, do nothing.");
        return;/* w w w .  j av a 2 s  . com*/
    }

    LogUtils.debug(LOG, "disconnect " + oneDN + " and " + theOtherDNs);

    try {
        ctx.modifyAttributes(oneDN, new ModificationItem[] {
                ModUtils.remove(metaData.getOne().getIndirectionAttr(), theOtherDNs) });
        LogUtils.debug(LOG, String.format("disconnected: %s -> %s", oneDN, theOtherDNs));

        for (String theOtherDN : theOtherDNs) {
            String indirectionAttr = metaData.getTheOther().dnToIndirectionAttr(theOtherDN);
            if (null == indirectionAttr) {
                LogUtils.debug(LOG, "no corresponding indirection configured for " + theOtherDN);
                continue;
            }

            ctx.modifyAttributes(theOtherDN,
                    new ModificationItem[] { ModUtils.remove(indirectionAttr, oneDN) });
            LogUtils.debug(LOG, String.format("disconnected: %s -> %s", theOtherDN, oneDN));
        }
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

/**
 * @throws NamingException/*from w ww.  j a  va2  s. c o m*/
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 */
protected Set<Map<String, String>> buildGroup(Properties systemConfig, String filter) {
    Set<Map<String, String>> ret = new HashSet<Map<String, String>>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }
    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();
        /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName
        + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);

        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
            boolean ldapApiEnumerationBugEncountered = false;
            while ((!ldapApiEnumerationBugEncountered) && answer.hasMoreElements()) {//BZ:582471- ldap api bug change
                // We use the first match
                SearchResult si = null;
                try {
                    si = answer.next();
                } catch (NullPointerException npe) {
                    ldapApiEnumerationBugEncountered = true;
                    break;
                }
                Map<String, String> entry = new HashMap<String, String>();
                String name = (String) si.getAttributes().get("cn").get();
                name = name.trim();
                Attribute desc = si.getAttributes().get("description");
                String description = desc != null ? (String) desc.get() : "";
                description = description.trim();
                entry.put("id", name);
                entry.put("name", name);
                entry.put("description", description);
                ret.add(entry);
            }
        }
    } catch (NamingException e) {
        if (e instanceof InvalidSearchFilterException) {
            InvalidSearchFilterException fException = (InvalidSearchFilterException) e;
            String message = "The ldap group filter defined is invalid ";
            log.error(message, fException);
            throw new LdapFilterException(message + " " + fException.getMessage());
        }
        //TODO: check for ldap connection/unavailable/etc. exceptions.
        else {
            log.error("LDAP communication error: " + e.getMessage(), e);
            throw new LdapCommunicationException(e);
        }
    }

    return ret;
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public void create(Object obj) {
    if (null == obj) {
        return;//ww w  . java 2 s .c  om
    }
    if (obj instanceof Persistent) {
        update(obj);
        return;
    }

    Object idValue = EntityMetaData.get(obj.getClass()).getIdProperty().getter().get(obj);
    if (null == idValue) {
        throw new SessionException("Unable to persist an object which has no id: " + obj);
    }

    String dn = DnHelper.build(idValue.toString(), obj.getClass());
    LogUtils.debug(LOG, "create dn=" + dn);

    try {
        ctx.bind(dn, null, fromTransientToAttributes(obj));

        /*
         * We didn't do an extra lookup invocation to put it into the cache,
         * as we have no idea whether the client code need the persisted
         * entity or not. Besides, if the answer is no, we slow down the
         * speed. If yes, the client code still hold the original reference
         * of the transient object and we would rather the client code to do
         * the extra lookup by itself.
         */

    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected boolean organizationExists(String orgId) throws ExecutionException {
    NamingEnumeration<SearchResult> searchResults = null;
    try {/*  www.java2s . c o m*/
        searchResults = this.query(LDAPConnector.getSingletonInstance().getInstitutionBaseDN(),
                new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (")
                        .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(),
                new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE);
        if (searchResults.hasMore()) {
            return true;
        } else {
            return false;
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (NamingException e) {
            }
        }
    }
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected boolean licensedOganizationExists(String orgId) throws ExecutionException {
    NamingEnumeration<SearchResult> searchResults = null;
    try {/*from   w  w  w . j  a v  a 2 s  .  c o  m*/
        searchResults = this.query(LDAPConnector.getSingletonInstance().getLicensedInstitutionsBaseDN(),
                new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (")
                        .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(),
                new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE);
        if (searchResults.hasMore()) {
            return true;
        } else {
            return false;
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (NamingException e) {
            }
        }
    }
}

From source file:org.apache.archiva.redback.rbac.ldap.LdapRbacManager.java

protected void closeContext(DirContext context) {
    if (context != null) {
        try {//from www.j  av  a 2s  .  co m
            context.close();
        } catch (NamingException e) {
            log.warn("skip issue closing context: {}", e.getMessage());
        }
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public Map<String, Object> read(Class<?> clazz, String dn, String[] returningAttrs) {
    if (null == dn) {
        return null;
    }//from ww w  . j  a  v a2  s .  com

    LogUtils.debug(LOG, String.format("read %s with dn=%s, returningAttrs=%s", clazz.getName(), dn,
            Arrays.toString(returningAttrs)));

    // fetch the information from session cache first to decrease one possible lookup operation
    if (sessionCache.containsKey(dn)) {
        Object entity = sessionCache.get(dn);
        Map<String, Object> retVal = new HashMap<String, Object>();

        EntityMetaData metaData = EntityMetaData.get(clazz);
        for (String returningAttr : returningAttrs) {
            EntityPropertyMetaData propMetaData = metaData.getProperty(returningAttr);
            if (null == propMetaData) {
                continue;
            }

            Object propValue = propMetaData.getter().get(entity);
            if (null == propValue) {
                continue;
            }

            if (!propMetaData.isMultiple()) {
                retVal.put(returningAttr, propValue);
            } else {
                List propValues = (List) propValue;
                if (!propValues.isEmpty()) {
                    if (!propMetaData.isReference()) {
                        retVal.put(returningAttr, propValues);
                    } else {
                        List simpleValues = new ArrayList();
                        for (Object referenceEntity : propValues) {
                            simpleValues.add(DnHelper.build(referenceEntity));
                        }
                        retVal.put(returningAttr, simpleValues);
                    }
                }
            }
        }
        return retVal;

    } else {
        try {
            return fromAttributesToMap(clazz, ctx.getAttributes(dn, returningAttrs));
        } catch (NamingException e) {
            throw new SessionException(e.getMessage(), e);
        }
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public void update(Object entity) {
    if (null == entity) {
        return;//from   w w  w .j ava 2  s.  c o m
    }

    if (!(entity instanceof Persistent)) {
        create(entity);
        return;
    }

    String dn = DnHelper.build(entity);
    List<ModificationItem> mods = fromEntityToModificationItems(entity);
    if (mods.isEmpty()) {
        LogUtils.debug(LOG, "no changes found when updating dn=" + dn + ", do nothing");
        return;
    }

    LogUtils.debug(LOG, "update dn=" + dn);

    try {
        ctx.modifyAttributes(dn, mods.toArray(new ModificationItem[0]));

        /*
         * All current modifications are cleared, so could we continue
         * to use this entity? The answer is no!
         * 
         * For simple string properties, this works fine. But for
         * multiple values we need to do following things before reusing
         * this entity:
         * 1. clear changes of all the modified MonitoredList
         * 2. turn normal List into MonitoredList
         */
        EntityProxyFactory.getModifiedPropNames(entity).clear();
        for (EntityPropertyMetaData propMetaData : EntityMetaData.get(ClassHelper.actualClass(entity))) {
            if (propMetaData.isReadonly() || !propMetaData.isMultiple()) {
                continue;
            }

            Object propValue = propMetaData.getter().get(entity);
            if (null == propValue) {
                continue;
            }

            List propValues = (List) propValue;
            if (propValues instanceof MoniteredList) {
                // clear changes of all the modifed MoniteredList
                ((MoniteredList) propValues).clearChanges();
            } else {
                // turn normal List into MoniteredList
                propMetaData.setter().set(entity, new MoniteredList(propValues));
            }
        }

        /*
         * Now we have no need to remove the entity from the cache. And its
         * possible to continuous use of the entity.
         */

    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java

/** Get the AD-derived access tokens for a user and domain */
protected List<String> getADTokens(String userPart, String domainPart, String userName)
        throws NameNotFoundException, NamingException, ManifoldCFException {
    // Now, look through the rules for the matching domain controller
    String domainController = null;
    for (DCRule rule : dCRules) {
        String suffix = rule.getSuffix();
        if (suffix.length() == 0
                || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT))
                        && (suffix.length() == domainPart.length()
                                || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) {
            domainController = rule.getDomainControllerName();
            break;
        }/* w  ww . ja v  a  2 s .co m*/
    }

    if (domainController == null)
        // No AD user
        return null;

    // Look up connection parameters
    DCConnectionParameters dcParams = dCConnectionParameters.get(domainController);
    if (dcParams == null)
        // No AD user
        return null;

    // Use the complete fqn if the field is the "userPrincipalName"
    String userBase;
    String userACLsUsername = dcParams.getUserACLsUsername();
    if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) {
        userBase = userName;
    } else {
        userBase = userPart;
    }

    //Build the DN searchBase from domain part
    StringBuilder domainsb = new StringBuilder();
    int j = 0;
    while (true) {
        if (j > 0)
            domainsb.append(",");

        int k = domainPart.indexOf(".", j);
        if (k == -1) {
            domainsb.append("DC=").append(ldapEscape(domainPart.substring(j)));
            break;
        }
        domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k)));
        j = k + 1;
    }

    // Establish a session with the selected domain controller
    LdapContext ctx = createDCSession(domainController);

    //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com")
    String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername);
    if (searchBase == null)
        return null;

    //specify the LDAP search filter
    String searchFilter = "(objectClass=user)";

    //Create the search controls for finding the access tokens   
    SearchControls searchCtls = new SearchControls();

    //Specify the search scope, must be base level search for tokenGroups
    searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

    //Specify the attributes to return
    String returnedAtts[] = { "tokenGroups", "objectSid" };
    searchCtls.setReturningAttributes(returnedAtts);

    //Search for tokens.  Since every user *must* have a SID, the "no user" detection should be safe.
    NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

    List<String> theGroups = new ArrayList<String>();
    String userToken = userTokenFromLoginName(domainPart + "\\" + userPart);
    if (userToken != null)
        theGroups.add(userToken);

    //Loop through the search results
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        //the sr.GetName should be null, as it is relative to the base object

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                        String sid = sid2String((byte[]) e.next());
                        String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid)
                                : groupTokenFromSID(sid);
                        theGroups.add(token);
                    }
                }
            } catch (NamingException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
    }

    if (theGroups.size() == 0)
        return null;

    // User is in AD, so add the 'everyone' group
    theGroups.add(everyoneGroup());
    return theGroups;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@Override
public boolean hasEntry(String id) throws DirectoryException {
    try {/*from w w w. j  av  a  2s  . c  o m*/
        // TODO: check directory cache first
        return getLdapEntry(id) != null;
    } catch (NamingException e) {
        throw new DirectoryException("hasEntry failed: " + e.getMessage(), e);
    }
}