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:com.flexive.core.Database.java

/**
 * Retrieves a DataSource.//  w w  w .  j a v a2s.  com
 *
 * @param divisionId the division id
 * @param useTX      request transaction support?
 * @return a DataSource
 * @throws SQLException If no DataSource could be retrieved
 */
private static DataSource getDataSource(int divisionId, boolean useTX) throws SQLException {
    // Check division
    if (!DivisionData.isValidDivisionId(divisionId)) {
        throw new SQLException("Unable to obtain connection: Division not defined (" + divisionId + ").");
    }
    DataSource[] dataSourceCache = useTX ? dataSources : dataSourcesNoTX;
    // use cached datasource, if available
    if (divisionId == DivisionData.DIVISION_TEST && useTX && testDataSource != null) {
        return testDataSource;
    } else if (divisionId == DivisionData.DIVISION_TEST && !useTX && testDataSourceNoTX != null) {
        return testDataSourceNoTX;
    } else if (divisionId != DivisionData.DIVISION_TEST && dataSourceCache[divisionId] != null) {
        return dataSourceCache[divisionId];
    }
    synchronized (Database.class) {
        // Try to obtain a connection
        String finalDsName = null;
        try {
            if (divisionId == DivisionData.DIVISION_GLOBAL) {
                // Special case: global config database
                finalDsName = DS_GLOBAL_CONFIG;
            } else {
                // else: get data source from global configuration
                GlobalConfigurationEngine globalConfiguration = EJBLookup.getGlobalConfigurationEngine();
                finalDsName = globalConfiguration.getDivisionData(divisionId).getDataSource();
                if (!useTX)
                    finalDsName += NO_TX_SUFFIX;
            }
            LOG.info("Looking up datasource for division " + divisionId + ": " + finalDsName);
            final DataSource dataSource = getDataSource(finalDsName, false);
            if (divisionId == DivisionData.DIVISION_TEST) {
                if (useTX) {
                    return (testDataSource = dataSource);
                } else {
                    return (testDataSourceNoTX = dataSource);
                }
            } else {
                return (dataSourceCache[divisionId] = dataSource);
            }
        } catch (NamingException exc) {
            if (divisionId == 1) {
                // try default JavaEE 6 data source
                try {
                    final DataSource ds = tryGetDefaultDataSource(EJBLookup.getInitialContext(),
                            GlobalConfigurationEngineBean.DEFAULT_DS + (useTX ? "" : NO_TX_SUFFIX),
                            new DefaultDivisionDataSourceInitializer());
                    if (ds != null) {
                        if (LOG.isInfoEnabled()) {
                            LOG.info("No datasource configured for division 1, using default datasource: "
                                    + GlobalConfigurationEngineBean.DEFAULT_DS);
                        }
                        // remember data source for #getDataSource(String)
                        dataSourcesByName.put(finalDsName, ds);
                        defaultDataSourceInitialized = true; // remember to unload driver in cleanup
                        // set division data source, return
                        return (dataSourceCache[divisionId] = ds);
                    } else {
                        if (LOG.isErrorEnabled()) {
                            LOG.error(
                                    "Default datasource for division 1 not found (not a JavaEE 6 container?)");
                        }
                        // fall through to error handling
                    }
                } catch (NamingException e) {
                    // not bound, throw error
                }
            }
            String sErr = "Naming Exception, unable to retrieve Connection to [" + finalDsName + "]: "
                    + exc.getMessage();
            LOG.error(sErr);
            throw new SQLException(sErr);
        } catch (FxNotFoundException exc) {
            String sErr = "Failed to retrieve datasource for division " + divisionId + " (not configured).";
            LOG.error(sErr);
            throw new SQLException(sErr);
        } catch (FxLoadException exc) {
            String sErr = "Failed to load datasource configuration: " + exc.getMessage();
            LOG.error(sErr);
            throw new SQLException(sErr);
        } catch (FxApplicationException exc) {
            String sErr = "Unknown error while loading datasource for division " + divisionId + ": "
                    + exc.getMessage();
            LOG.error(sErr);
            throw new SQLException(sErr);
        }
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

@Override
public boolean userExists(UserKey key) throws SSOIdentityException {
    if (getUseBindCredentials()) {
        String uid = null;//from  w  w w. j ava2  s  . co  m
        try {
            uid = selectUser(((SimpleUserKey) key).getId());
        } catch (NamingException e) {
            logger.error("NamingException while obtaining user", e);
            throw new SSOIdentityException("Error obtaining user : " + key);
        } catch (IOException e) {
            logger.error("StartTLS error", e);
            throw new SSOIdentityException("StartTLS error : " + e.getMessage());
        }
        if (uid != null) {
            return true;
        } else {
            return false;
        }
    }
    return super.userExists(key);
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

public void updateAccountPassword(UserKey key, Credential newPassword) throws SSOIdentityException {
    try {/*  ww  w.j  a  va2  s.  co  m*/
        if (!(key instanceof SimpleUserKey)) {
            throw new SSOIdentityException("Unsupported key type : " + key.getClass().getName());
        }

        Attributes atts = new BasicAttributes();
        atts.put(this.getUpdateableCredentialAttribute(), ((BaseCredential) newPassword).getValue());

        this.replaceAttributes(this.selectUserDN(((SimpleUserKey) key).getId()), atts);

    } catch (NamingException e) {
        logger.error("NamingException while updating password account", e);
        throw new SSOIdentityException("Error updating password account for user : " + key);
    } catch (IOException e) {
        logger.error("StartTLS error", e);
        throw new SSOIdentityException("StartTLS error : " + e.getMessage());
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Loads user information and its user attributes from the LDAP server.
 *
 * @param key the userid value to fetch the user in the LDAP server.
 * @return the user instance with the provided userid
 * @throws NoSuchUserException  if the user does not exist
 * @throws SSOIdentityException a fatal exception loading the requested user
 *///from   ww  w  .  j  a v  a  2s .  c om
public BaseUser loadUser(UserKey key) throws NoSuchUserException, SSOIdentityException {

    try {
        if (!(key instanceof SimpleUserKey)) {
            throw new SSOIdentityException("Unsupported key type : " + key.getClass().getName());
        }

        String uid = selectUser(((SimpleUserKey) key).getId());

        if (uid == null) {
            throw new NoSuchUserException(key);
        }

        BaseUser bu = new BaseUserImpl();
        bu.setName(uid);

        List userProperties = new ArrayList();

        // Optionally find user properties.
        if (getUserPropertiesQueryString() != null) {

            HashMap userPropertiesResultSet = selectUserProperties(((SimpleUserKey) key).getId());

            Iterator i = userPropertiesResultSet.keySet().iterator();
            while (i.hasNext()) {
                String pName = (String) i.next();
                String pValue = (String) userPropertiesResultSet.get(pName);

                SSONameValuePair vp = new SSONameValuePair(pName, pValue);
                userProperties.add(vp);
            }

        }

        // Store User DN as a SSOUser property.
        String dn = selectUserDN(((SimpleUserKey) key).getId());
        userProperties.add(new SSONameValuePair("josso.user.dn", dn));

        SSONameValuePair[] props = (SSONameValuePair[]) userProperties
                .toArray(new SSONameValuePair[userProperties.size()]);
        bu.setProperties(props);

        return bu;
    } catch (NamingException e) {
        logger.error("NamingException while obtaining user", e);
        throw new SSOIdentityException("Error obtaining user : " + key);
    } catch (IOException e) {
        logger.error("StartTLS error", e);
        throw new SSOIdentityException("StartTLS error : " + e.getMessage());
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Loads user credential information for the supplied user from the LDAP server.
 *
 * @param key the user id of the user for whom credential information is to be retrieved.
 * @return the credentials associated with the supplied user.
 * @throws SSOIdentityException fatal exception obtaining user credentials
 *//*from  www . j  a  v  a2  s  . c o m*/
public Credential[] loadCredentials(CredentialKey key, CredentialProvider cp) throws SSOIdentityException {

    try {

        if (!(key instanceof CredentialKey)) {
            throw new SSOIdentityException("Unsupported key type : " + key.getClass().getName());
        }

        List credentials = new ArrayList();
        HashMap credentialResultSet = selectCredentials(((SimpleUserKey) key).getId(), cp);

        Iterator i = credentialResultSet.keySet().iterator();
        while (i.hasNext()) {
            String cName = (String) i.next();
            List cValues = (List) credentialResultSet.get(cName);

            Iterator valIter = cValues.iterator();
            while (valIter.hasNext()) {
                Credential c = cp.newCredential(cName, valIter.next());
                credentials.add(c);
            }
        }

        return (Credential[]) credentials.toArray(new Credential[credentialResultSet.size()]);
    } catch (NamingException e) {
        logger.error("NamingException while obtaining Credentials", e);
        throw new SSOIdentityException("Error obtaining credentials for user : " + key);
    } catch (IOException e) {
        logger.error("StartTLS error", e);
        throw new SSOIdentityException("StartTLS error : " + e.getMessage());
    }

}

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

@XNodeList(value = "ldapUrl", componentType = LDAPUrlDescriptor.class, type = LDAPUrlDescriptor[].class)
public void setLdapUrls(LDAPUrlDescriptor[] ldapUrls) throws DirectoryException {
    if (ldapUrls == null) {
        throw new DirectoryException("At least one <ldapUrl/> server declaration is required");
    }/*from w  w w  . j a  v a 2  s .  co  m*/
    ldapEntries = new LinkedHashSet<LdapEntry>();

    Set<LDAPUrlDescriptor> processed = new HashSet<LDAPUrlDescriptor>();

    List<String> urls = new ArrayList<String>(ldapUrls.length);
    for (LDAPUrlDescriptor url : ldapUrls) {
        LdapURL ldapUrl;
        try {
            /*
             * Empty string translates to ldap://localhost:389 through JNDI
             */
            if (StringUtils.isEmpty(url.getValue())) {
                urls.add(url.getValue());
                ldapEntries.add(new LdapEntryDescriptor(url));
                continue;
            }

            /*
             * Parse the URI to make sure it is valid
             */
            ldapUrl = new LdapURL(url.getValue());
            if (!processed.add(url)) {
                continue;
            }
        } catch (NamingException e) {
            throw new DirectoryException(e);
        }

        useSsl = useSsl || ldapUrl.useSsl();

        /*
         * RFC-2255 - The "ldap" prefix indicates an entry or entries residing in the LDAP server running on the
         * given hostname at the given port number. The default LDAP port is TCP port 389. If no hostport is given,
         * the client must have some apriori knowledge of an appropriate LDAP server to contact.
         */
        if (ldapUrl.getHost() == null) {
            /*
             * RFC-2782 - Check to see if an LDAP SRV record is defined in the DNS server
             */
            String domain = convertDNtoFQDN(ldapUrl.getDN());
            if (domain != null) {
                /*
                 * Dynamic URL - retrieve from SRV record
                 */
                List<String> discoveredUrls;
                try {
                    discoveredUrls = discoverLdapServers(domain, ldapUrl.useSsl(), url.getSrvPrefix());
                } catch (NamingException e) {
                    throw new DirectoryException(String.format("SRV record DNS lookup failed for %s.%s: %s",
                            url.getSrvPrefix(), domain, e.getMessage()), e);
                }

                /*
                 * Discovered URLs could be empty, lets check at the end though
                 */
                urls.addAll(discoveredUrls);

                /*
                 * Store entries in an ordered set and remember that we were dynamic
                 */
                ldapEntries.add(new LdapEntryDomain(url, domain, ldapUrl.useSsl()));
                isDynamicServerList = true;
            } else {
                throw new DirectoryException("Invalid LDAP SRV reference, this should be of the form"
                        + " ldap:///dc=example,dc=org");
            }
        } else {
            /*
             * Static URL - store the value
             */
            urls.add(url.getValue());

            /*
             * Store entries in an ordered set
             */
            ldapEntries.add(new LdapEntryDescriptor(url));
        }
    }

    /*
     * Oops no valid URLs to connect to :(
     */
    if (urls.isEmpty()) {
        throw new DirectoryException("No valid server urls returned from DNS query");
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Loads user UID for the given credential key.
 *
 * @param key the key used to load UID from store.
 * @param cp credential provider// w  w w.j  a  v  a  2  s  . c  o  m
 * @throws SSOIdentityException
 */
public String loadUID(CredentialKey key, CredentialProvider cp) throws SSOIdentityException {
    try {
        if (key instanceof CertificateUserKey) {
            return loadUID(((CertificateUserKey) key).getId(), ((CertificateUserKey) key).getCertificate(), cp);
        } else if (key instanceof SimpleUserKey) {
            return ((SimpleUserKey) key).getId();
        } else {
            throw new SSOIdentityException("Unsupported key type : " + key.getClass().getName());
        }
    } catch (NamingException e) {
        logger.error("Failed to locate user", e);
        throw new SSOIdentityException("Failed to locate user for certificate : "
                + ((CertificateUserKey) key).getCertificate().getSubjectX500Principal().getName());
    } catch (IOException e) {
        logger.error("StartTLS error", e);
        throw new SSOIdentityException("StartTLS error : " + e.getMessage());
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

public String loadUsernameByRelayCredential(ChallengeResponseCredential cred) throws SSOIdentityException {
    try {/*from w  w w . jav  a2s  . co m*/
        return this.selectUser(cred.getId(), cred.getResponse());
    } catch (NamingException e) {
        logger.error("NamingException while obtaining user with relay credential", e);
        throw new SSOIdentityException("Error obtaining user with relay credential: ID[" + cred.getId()
                + "] = RESPONSE[" + cred.getResponse() + "]");
    } catch (IOException e) {
        logger.error("StartTLS error", e);
        throw new SSOIdentityException("StartTLS error : " + e.getMessage());
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationRead(String entryName, ParameterResolutionContext prc, Map paramValueMap)
        throws SenderException, ParameterException {
    DirContext dirContext = null;
    try {/*from   ww w.ja v a 2 s . c om*/
        dirContext = getDirContext(paramValueMap);
        return attributesToXml(dirContext.getAttributes(entryName, getAttributesReturnedParameter())).toXML();
    } catch (NamingException e) {
        // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
        //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
        // Sun:
        //   [LDAP: error code 32 - No Such Object...
        if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
            if (log.isDebugEnabled())
                log.debug("Operation [" + getOperation() + "] found nothing - no such entryName: " + entryName);
            return DEFAULT_RESULT_READ;
        } else {
            storeLdapException(e, prc);
            throw new SenderException(
                    "Exception in operation [" + getOperation() + "] entryName=[" + entryName + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationChallenge(String principal, ParameterResolutionContext prc, Map paramValueMap)
        throws SenderException, ParameterException {
    DirContext dirContext = null;
    try {//w  w w . j a  v a2 s . c o m
        // Use loopkupDirContext instead of getDirContext to prevent
        // NamingException (with error code 49) being converted to
        // SenderException.
        dirContext = loopkupDirContext(paramValueMap);
        attributesToXml(dirContext.getAttributes(principal, getAttributesReturnedParameter())).toXML();
        return DEFAULT_RESULT_CHALLENGE_OK;
    } catch (NamingException e) {
        // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
        //   49 LDAP_INVALID_CREDENTIALS Indicates that during a bind operation one of the following occurred: The client passed either an incorrect DN or password, or the password is incorrect because it has expired, intruder detection has locked the account, or another similar reason. This is equivalent to AD error code 52e.
        if (e.getMessage().startsWith("[LDAP: error code 49 - ")) {
            if (log.isDebugEnabled())
                log.debug("Operation [" + getOperation() + "] invalid credentials for: " + principal);
            return DEFAULT_RESULT_CHALLENGE_NOK;
        } else {
            storeLdapException(e, prc);
            throw new SenderException(
                    "Exception in operation [" + getOperation() + "] principal=[" + principal + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}