001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019 package org.apache.shiro.realm.ldap;
020
021 import java.util.Collection;
022 import java.util.HashSet;
023 import java.util.Set;
024 import javax.naming.NamingEnumeration;
025 import javax.naming.NamingException;
026 import javax.naming.directory.Attribute;
027 import javax.naming.ldap.LdapContext;
028
029 import org.slf4j.Logger;
030 import org.slf4j.LoggerFactory;
031
032 /**
033 * Utility class providing static methods to make working with LDAP
034 * easier.
035 *
036 * @author Jeremy Haile
037 * @since 0.2
038 */
039 public class LdapUtils {
040
041 /** Private internal log instance. */
042 private static final Logger log = LoggerFactory.getLogger(LdapUtils.class);
043
044 /**
045 * Private constructor to prevent instantiation
046 */
047 private LdapUtils() {
048 }
049
050 /**
051 * Closes an LDAP context, logging any errors, but not throwing
052 * an exception if there is a failure.
053 *
054 * @param ctx the LDAP context to close.
055 */
056 public static void closeContext(LdapContext ctx) {
057 try {
058 if (ctx != null) {
059 ctx.close();
060 }
061 } catch (NamingException e) {
062 if (log.isErrorEnabled()) {
063 log.error("Exception while closing LDAP context. ", e);
064 }
065 }
066 }
067
068
069 /**
070 * Helper method used to retrieve all attribute values from a particular context attribute.
071 *
072 * @param attr the LDAP attribute.
073 * @return the values of the attribute.
074 * @throws javax.naming.NamingException if there is an LDAP error while reading the values.
075 */
076 public static Collection<String> getAllAttributeValues(Attribute attr) throws NamingException {
077 Set<String> values = new HashSet<String>();
078 for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
079 String value = (String) e.next();
080 values.add(value);
081 }
082 return values;
083 }
084
085
086 }