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:com.jmstoolkit.logging.JTKHandler.java

/**
 *
 * @param inDestinationName the JMS Destination
 *///  w w  w  .java2  s.  co  m
@ManagedAttribute
public final void setDestinationName(final String inDestinationName) {
    this.destinationName = inDestinationName;
    try {
        this.setDestination((Destination) this.getJndiTemplate().lookup(this.destinationName));
    } catch (NamingException e) {
        System.err.println("Failed to set Destination: " + e.getLocalizedMessage());
    }
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Overloaded method used to search the ldap based on the search constraints, search filter & search base 
 * @param attrs//from ww  w  .  j  a  v  a2s.  com
 * @param searchFilter
 * @param searchBase
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults(String[] attrs, String searchFilter, String searchBase) {
    LdapContext ldapCtx = null;
    try {
        try {
            ldapCtx = getLDAPContext();
        } catch (NamingException e) {
            Logger.error("Error occured while creating the connection to LDAP[" + e.getLocalizedMessage() + "]",
                    LDAPUtils.class);
        }
        if (ldapCtx == null) {
            return null;
        }
        SearchControls searchCtls = getSimpleSearchControls(attrs);
        // Search for objects using the filter
        try {
            return ldapCtx.search(searchBase, searchFilter, searchCtls);
        } catch (NamingException e) {
            Logger.error(
                    "Error occured while searching results :288: getSearchResults(String[] attrs, String searchFilter, String searchBase): ["
                            + e.getLocalizedMessage() + "]",
                    LDAPUtils.class);
        }
    } finally {
        if (ldapCtx != null) {
            try {
                ldapCtx.close();
            } catch (NamingException e) {
                Logger.error("Error occured while closing connection to LDAP [" + e.getLocalizedMessage() + "]",
                        LDAPUtils.class);
            }
        }
    }
    return null;
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Search the LDAP based on default inputs. This method searches for <b>memberOf </b>
 * @return/* w  w  w.  j a v  a  2 s.  c  o  m*/
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults() {

    // Specify the attributes to return
    String returnedAtts[] = { PROPERTY_MEMBER_OF };
    // Specify the search scope
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setReturningAttributes(returnedAtts);
    // Search for objects using the filter
    try {
        return getSearchResults(getLDAPContext(), searchCtls, SEARCH_FILTER, LDAP_BASE);
    } catch (NamingException e) {
        Logger.error("Error occured while searching results : 181: getSearchResults():["
                + e.getLocalizedMessage() + "]", LDAPUtils.class);
    }
    return null;
}

From source file:com.wfp.utils.LDAPUtils.java

public static String getUserImageAsString(String uid) {
    String base64String = null;
    if (uid != null && uid != "") {
        // Specify the attributes to return
        String searchFilter = "(&" + FILTER_LDAP_USERS + "((uid=" + uid + ")))";
        String searchBase = LDAP_FILTER_URL + "uid=" + uid + "," + LDAP_BASE;

        String returnedAtts[] = { "" + PROPERTY_IMAGE };
        // Specify the search scope
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchCtls.setReturningAttributes(returnedAtts);
        // Search for objects using the filter
        try {/*from  w ww  .jav  a  2  s  . com*/
            NamingEnumeration results = getSearchResults(getLDAPContext(), searchCtls, searchFilter,
                    searchBase);
            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();
                Attribute attr = attributes.get(PROPERTY_IMAGE);
                if (attr != null)
                    base64String = new String(
                            org.apache.commons.codec.binary.Base64.encodeBase64((byte[]) attr.get()));

            }
        } catch (NamingException e) {
            Logger.error(" Error occured while fetching user image 1334: getUserImageBytes(String uid):["
                    + e.getLocalizedMessage() + "]", LDAPUtils.class);
        }
    }
    return base64String;
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Overloaded method for searching the LDAP based on the searchfilter & searchbase with contraint as "cn"
 * @param searchFilter/*  w  w  w . jav a 2 s  .co m*/
 * @param searchBase
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults(String searchFilter, String searchBase) {

    // Specify the attributes to return
    String returnedAtts[] = { PROPERTY_CN };
    // Specify the search scope
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setReturningAttributes(returnedAtts);
    // Search for objects using the filter
    try {
        return getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase);
    } catch (NamingException e) {
        Logger.error(
                " Error occured while searching results 206: getSearchResults(String searchFilter, String searchBase):["
                        + e.getLocalizedMessage() + "]",
                LDAPUtils.class);
    }
    return null;
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Overloaded method used to search the ldap based on the search controls, search gfilter & search base 
 * @param searchCtls/*  w ww.  ja va2 s .  c  o m*/
 * @param searchFilter
 * @param searchBase
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults(SearchControls searchCtls, String searchFilter,
        String searchBase) {
    //Logger.info("Peforming search on LDAP =============", LDAPUtils.class);
    // Search for objects using the filter
    try {
        //Logger.info("Search Filter ["+searchFilter+"]", LDAPUtils.class);
        //Logger.info("Search Base ["+searchBase+"]", LDAPUtils.class);
        return getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase);
    } catch (NamingException e) {
        Logger.error(
                "Error occured while searching results :228:getSearchResults(SearchControls searchCtls, String searchFilter, String searchBase): ["
                        + e.getLocalizedMessage() + "]",
                LDAPUtils.class);
    }
    return null;
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Used to search the LDAP based on the follwoing argumets
 * @param ldapCtx//from   ww w  .  ja v  a 2  s  .  co  m
 * @param searchCtls
 * @param searchFilter
 * @param searchBase
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults(LdapContext ldapCtx, SearchControls searchCtls,
        String searchFilter, String searchBase) {
    try {
        // Search for objects using the filter
        try {
            return ldapCtx.search(searchBase, searchFilter, searchCtls);
        } catch (NamingException e) {
            Logger.error(
                    "Error occured while searching results : 249: getSearchResults(LdapContext ldapCtx, SearchControls searchCtls, String searchFilter, String searchBase)["
                            + e.getLocalizedMessage() + "]",
                    LDAPUtils.class);
        }
    } finally {
        if (ldapCtx != null) {
            try {
                ldapCtx.close();
            } catch (NamingException e) {
                Logger.error(
                        "Error occured while closing the connection to LDAP [" + e.getLocalizedMessage() + "]",
                        LDAPUtils.class);
            }
        }
    }
    return null;
}

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

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback/*www . j av a2  s. c om*/
 *            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
 */
protected void processQuery(final SearchCallback callback, final String searchBase, final String query,
        final String[] returningAttributes) {
    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "Processing query {}\nSearch base: {}\n\rReturn result limit: {}\n\tDereflink: {}\n\rReturn named object: {}\n\tTime limit for search: {}\n\tAttributes to return: {} items\n\tAttributes: {}",
                query, searchBase, searchControls.getCountLimit(), searchControls.getDerefLinkFlag(),
                searchControls.getReturningObjFlag(), searchControls.getTimeLimit(),
                String.valueOf(returningAttributes.length), Arrays.toString(returningAttributes));
    }

    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);

                this.commonCloseSearchResult(result);
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (final NamingException e) {
        final Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (final ParseException e) {
        final Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        this.commonAfterQueryCleanup(searchResults, result, ctx);
    }
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback//from w  w w .ja v a2s. com
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws org.alfresco.error.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 (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
        LDAPMultiBaseUserRegistry.logger.debug("Processing query");
        LDAPMultiBaseUserRegistry.logger.debug("Search base: " + searchBase);
        LDAPMultiBaseUserRegistry.logger.debug("    Return result limit: " + searchControls.getCountLimit());
        LDAPMultiBaseUserRegistry.logger.debug("    DerefLink: " + searchControls.getDerefLinkFlag());
        LDAPMultiBaseUserRegistry.logger
                .debug("    Return named object: " + searchControls.getReturningObjFlag());
        LDAPMultiBaseUserRegistry.logger.debug("    Time limit for search: " + searchControls.getTimeLimit());
        LDAPMultiBaseUserRegistry.logger
                .debug("    Attributes to return: " + returningAttributes.length + " items.");
        for (String ra : returningAttributes) {
            LDAPMultiBaseUserRegistry.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);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
}

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

protected Collection<String> lookupGroupChildren(final SearchResult searchResult, final String gid,
        final boolean disjoint, final LdapName groupDistinguishedNamePrefix,
        final LdapName userDistinguishedNamePrefix) throws NamingException {
    final InitialDirContext ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext();
    try {// ww w . j  a  v  a  2 s  .c om
        LOGGER.debug("Processing group: {}, from source: {}", gid, searchResult.getNameInNamespace());

        final Collection<String> children = new HashSet<>();

        final Attributes attributes = searchResult.getAttributes();
        Attribute memAttribute = this.getRangeRestrictedAttribute(attributes, this.memberAttributeName);
        int nextStart = this.attributeBatchSize;

        while (memAttribute != null) {
            for (int i = 0; i < memAttribute.size(); i++) {
                final String attribute = (String) memAttribute.get(i);
                if (attribute != null && attribute.length() > 0) {
                    try {
                        // Attempt to parse the member attribute as a DN. If this fails we have a fallback
                        // in the catch block
                        final LdapName distinguishedNameForComparison = fixedLdapName(
                                attribute.toLowerCase(Locale.ENGLISH));
                        Attribute nameAttribute;

                        // If the user and group search bases are different we may be able to recognize user
                        // and group DNs without a secondary lookup
                        if (disjoint) {
                            final LdapName distinguishedName = fixedLdapName(attribute);
                            final Attributes nameAttributes = distinguishedName
                                    .getRdn(distinguishedName.size() - 1).toAttributes();

                            // Recognize user DNs
                            if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix)
                                    && (nameAttribute = nameAttributes.get(this.userIdAttributeName)) != null) {
                                final Collection<String> attributeValues = this.mapAttribute(nameAttribute,
                                        String.class);
                                final String personName = attributeValues.iterator().next();
                                LOGGER.debug("User DN recognized: {}", personName);
                                children.add(personName);
                                continue;
                            }

                            // Recognize group DNs
                            if (distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix)
                                    && (nameAttribute = nameAttributes
                                            .get(this.groupIdAttributeName)) != null) {
                                final Collection<String> attributeValues = this.mapAttribute(nameAttribute,
                                        String.class);
                                final String groupName = attributeValues.iterator().next();
                                LOGGER.debug("Group DN recognized: {}{}", AuthorityType.GROUP.getPrefixString(),
                                        groupName);
                                children.add(AuthorityType.GROUP.getPrefixString() + groupName);
                                continue;
                            }
                        }

                        // If we can't determine the name and type from the DN alone, try a directory lookup
                        if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix)
                                || distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix)) {
                            try {
                                final Attributes childAttributes = ctx.getAttributes(jndiName(attribute),
                                        new String[] { "objectclass", this.groupIdAttributeName,
                                                this.userIdAttributeName });
                                final Attribute objectClass = childAttributes.get("objectclass");
                                if (this.hasAttributeValue(objectClass, this.personType)) {
                                    nameAttribute = childAttributes.get(this.userIdAttributeName);
                                    if (nameAttribute == null) {
                                        if (this.errorOnMissingUID) {
                                            throw new AlfrescoRuntimeException(
                                                    "User missing user id attribute DN =" + attribute
                                                            + "  att = " + this.userIdAttributeName);
                                        } else {
                                            LOGGER.warn("User missing user id attribute DN =" + attribute
                                                    + "  att = " + this.userIdAttributeName);
                                            continue;
                                        }
                                    }

                                    final Collection<String> attributeValues = this.mapAttribute(nameAttribute,
                                            String.class);
                                    final String personName = attributeValues.iterator().next();

                                    LOGGER.debug("User DN recognized by directory lookup: {}", personName);
                                    children.add(personName);
                                    continue;
                                } else if (this.hasAttributeValue(objectClass, this.groupType)) {
                                    nameAttribute = childAttributes.get(this.groupIdAttributeName);
                                    if (nameAttribute == null) {
                                        if (this.errorOnMissingGID) {
                                            final Object[] params = { searchResult.getNameInNamespace(),
                                                    this.groupIdAttributeName };
                                            throw new AlfrescoRuntimeException(
                                                    "synchronization.err.ldap.get.group.id.missing", params);
                                        } else {
                                            LOGGER.warn("Missing GID on {}", childAttributes);
                                            continue;
                                        }
                                    }

                                    final Collection<String> attributeValues = this.mapAttribute(nameAttribute,
                                            String.class);
                                    final String groupName = attributeValues.iterator().next();
                                    LOGGER.debug("Group DN recognized by directory lookup: {}{}",
                                            AuthorityType.GROUP.getPrefixString(), groupName);
                                    children.add(AuthorityType.GROUP.getPrefixString() + groupName);
                                    continue;
                                }
                            } catch (final NamingException e) {
                                // Unresolvable name
                                if (this.errorOnMissingMembers) {
                                    final Object[] params = { gid, attribute, e.getLocalizedMessage() };
                                    throw new AlfrescoRuntimeException(
                                            "synchronization.err.ldap.group.member.missing.exception", params,
                                            e);
                                }
                                LOGGER.warn(
                                        "Failed to resolve member of group '{}, ' with distinguished name: {}",
                                        gid, attribute, e);
                                continue;
                            }
                        }
                        if (this.errorOnMissingMembers) {
                            final Object[] params = { gid, attribute };
                            throw new AlfrescoRuntimeException("synchronization.err.ldap.group.member.missing",
                                    params);
                        }
                        LOGGER.warn("Failed to resolve member of group '{}' with distinguished name: {}", gid,
                                attribute);
                    } catch (final InvalidNameException e) {
                        // The member attribute didn't parse as a DN. So assume we have a group class like
                        // posixGroup (FDS) that directly lists user names
                        LOGGER.debug("Member DN recognized as posixGroup: {}", attribute);
                        children.add(attribute);
                    }
                }
            }

            // If we are using attribute matching and we haven't got to the end (indicated by an asterisk),
            // fetch the next batch
            if (nextStart > 0
                    && !PATTERN_RANGE_END.matcher(memAttribute.getID().toLowerCase(Locale.ENGLISH)).find()) {
                final Attributes childAttributes = ctx.getAttributes(
                        jndiName(searchResult.getNameInNamespace()), new String[] { this.memberAttributeName
                                + ";range=" + nextStart + '-' + (nextStart + this.attributeBatchSize - 1) });
                memAttribute = this.getRangeRestrictedAttribute(childAttributes, this.memberAttributeName);
                nextStart += this.attributeBatchSize;
            } else {
                memAttribute = null;
            }
        }

        return children;
    } finally {
        this.commonAfterQueryCleanup(null, null, ctx);
    }
}