Example usage for javax.naming NamingException getLocalizedMessage

List of usage examples for javax.naming NamingException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 *
 * {@inheritDoc}// w w  w .  j  a  v a  2 s  .c o  m
 */
@Override
public String resolveDistinguishedName(final String userId, final AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    LOGGER.debug("resolveDistinguishedName userId: {}", userId);

    final SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    final String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName
            + "= userId))";

    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;

    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation

        searchResults = ctx.search(this.userSearchBase,
                "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId },
                userSearchCtls);

        if (searchResults.hasMore()) {
            result = searchResults.next();
            final Attributes attributes = result.getAttributes();
            final Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException(
                            "User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                } else {
                    LOGGER.warn("User returned by user search does not have mandatory user id attribute {}",
                            attributes);
                }
            }
            // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
            // only resolve this user if the user ID matches
            else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                final String name = result.getNameInNamespace();

                this.commonCloseSearchResult(result);
                result = null;
                return name;
            }

            this.commonCloseSearchResult(result);
            result = null;
        }

        final Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);

        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (final NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory
        final Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);

        // failed to search
        final Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        this.commonAfterQueryCleanup(searchResults, result, ctx);
    }
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }/* w w  w .ja  va 2 s .c  om*/
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName
            + "= userId))";

    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;

    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation            

        searchResults = ctx.search(this.userSearchBase,
                "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId },
                userSearchCtls);

        if (searchResults.hasMore()) {
            result = searchResults.next();
            Attributes attributes = result.getAttributes();
            Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException(
                            "User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                } else {
                    LDAPUserRegistry.logger
                            .warn("User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                }
            }
            // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
            // only resolve this user if the user ID matches
            else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                String name = result.getNameInNamespace();

                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
                return name;
            }

            // Close the contexts, see ALF-20682
            Context context = (Context) result.getObject();
            if (context != null) {
                context.close();
            }
            result = null;
        }

        Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);

        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory

        Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);

        // failed to search
        Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                logger.debug("error when closing ldap context", e);
            }
        }
    }
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 * /*w  w w.  j ava2  s. c  om*/
 * @param callback
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws AlfrescoRuntimeException           
 */
private void processQuery(SearchCallback callback, String searchBase, String query,
        String[] returningAttributes) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);
    if (LDAPUserRegistry.logger.isDebugEnabled()) {
        LDAPUserRegistry.logger.debug("Processing query");
        LDAPUserRegistry.logger.debug("Search base: " + searchBase);
        LDAPUserRegistry.logger.debug("    Return result limit: " + searchControls.getCountLimit());
        LDAPUserRegistry.logger.debug("    DerefLink: " + searchControls.getDerefLinkFlag());
        LDAPUserRegistry.logger.debug("    Return named object: " + searchControls.getReturningObjFlag());
        LDAPUserRegistry.logger.debug("    Time limit for search: " + searchControls.getTimeLimit());
        LDAPUserRegistry.logger.debug("    Attributes to return: " + returningAttributes.length + " items.");
        for (String ra : returningAttributes) {
            LDAPUserRegistry.logger.debug("        Attribute: " + ra);
        }
    }
    InitialDirContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize);
        do {
            searchResults = ctx.search(searchBase, query, searchControls);

            while (searchResults.hasMore()) {
                result = searchResults.next();
                callback.process(result);

                // Close the contexts, see ALF-20682
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (NamingException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (ParseException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        if (result != null) {
            try {
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
            searchResults = null;
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
        try {
            callback.close();
        } catch (NamingException e) {
        }
    }
}

From source file:org.apache.openaz.xacml.admin.view.components.LDAPPIPConfigurationComponent.java

protected void testLDAPConnection() {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, this.textFieldFactory.getValue());
    env.put(Context.PROVIDER_URL, this.textFieldProviderURL.getValue());
    env.put(Context.SECURITY_PRINCIPAL, this.textFieldPrincipal.getValue());
    env.put(Context.SECURITY_CREDENTIALS, this.textFieldCredentials.getValue());

    String auth = this.comboBoxAuthentication.getValue().toString();
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    ////from w  w w  .ja  v  a  2 s.  c o  m
    // Do we need to do anything?
    //
    /*
    if (auth.equals(LDAP_AUTH_ANONYMOUS)) {
               
    } else if (auth.equals(LDAP_AUTH_SIMPLE)) {
               
    } else if (auth.equals(LDAP_AUTH_SASL)) {
               
    }
    */

    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true)
                .show(Page.getCurrent());
    } catch (NamingException e) {
        logger.error(e);
        new Notification("Connection Failed", "<br/>" + e.getLocalizedMessage(), Type.ERROR_MESSAGE, true)
                .show(Page.getCurrent());
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException idontcare) { //NOPMD
        }
    }
}

From source file:org.apache.openaz.xacml.admin.view.components.SQLPIPConfigurationComponent.java

protected void testJNDIConnection() {
    try {//  w w w  .j a  v  a2  s .c o m
        Context initialContext = new InitialContext();
        DataSource dataSource = (DataSource) initialContext.lookup(this.textFieldDataSource.getValue());
        try (Connection connection = dataSource.getConnection()) {
            new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true)
                    .show(Page.getCurrent());
        }
    } catch (NamingException e) {
        logger.error(e);
        new Notification("JNDI Naming Exception",
                "<br/>" + e.getLocalizedMessage()
                        + "<br/>Is the context defined in this J2EE Container instance?",
                Type.ERROR_MESSAGE, true).show(Page.getCurrent());
    } catch (SQLException e) {
        logger.error(e);
        new Notification("SQL Exception",
                "<br/>" + e.getLocalizedMessage() + "<br/>Are the configuration parameters correct?",
                Type.ERROR_MESSAGE, true).show(Page.getCurrent());
    }
}

From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java

private Destination getDestination(Session session) {
    Destination dest = queue;//from   w  w w .java2 s  .  c o m
    if (dest != null) {
        return dest;
    }
    InitialContext newContext = null;
    try {
        dest = lookup(context, javax.jms.Destination.class, destination);
    } catch (NamingException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(nameString() + ". Could not lookup destination [" + destination + "]. Message: "
                    + e.getLocalizedMessage());
        }
        newContext = newContext();
    }
    try {
        if (newContext != null) {
            dest = lookup(newContext, javax.jms.Destination.class, destination);
        }
    } catch (Throwable t) {
        logger.info(nameString() + ". Destination [" + destination + "] not defined in JNDI context. Message:"
                + t.getLocalizedMessage());
    }
    if (dest == null && session != null) {
        try {
            dest = session.createQueue(destination);
            if (logger.isDebugEnabled()) {
                logger.debug(nameString() + " created destination [" + destination + "] from session object.");
            }
        } catch (JMSException e) {
            logger.error(nameString() + " could not create destination [" + destination + "]. Error:"
                    + e.getLocalizedMessage(), e);
            dest = null;
        }
    }
    if (dest == null && session == null) {
        if (logger.isDebugEnabled()) {
            logger.debug(nameString() + ". Both destination and session is null."
                    + " Could not create destination.");
        }
    }
    synchronized (queueLock) {
        queue = dest;
    }
    return dest;
}

From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java

private InitialContext newContext() {
    Properties properties = new Properties();
    InitialContext newContext;//from  ww w.j a va 2  s .  c  o m
    Map env;
    try {
        env = context.getEnvironment();
        Object o = env.get(NAMING_FACTORY_INITIAL);
        if (o != null) {
            properties.put(NAMING_FACTORY_INITIAL, o);
        }
        o = env.get(CONNECTION_STRING);
        if (o != null) {
            properties.put(CONNECTION_STRING, o);
        }
        o = env.get(PROVIDER_URL);
        if (o != null) {
            properties.put(PROVIDER_URL, o);
        }
        properties.put(QUEUE_PREFIX + destination, destination);
        newContext = new InitialContext(properties);
    } catch (NamingException e) {
        logger.info(nameString() + " could not create a new Context. Message:" + e.getLocalizedMessage());
        return null;
    }
    if (logger.isDebugEnabled()) {
        logger.debug(nameString() + " Created a new Context.");
    }
    return newContext;
}