List of usage examples for javax.naming.directory DirContext close
public void close() throws NamingException;
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getUser(String cn) { LDAPUser user = null;/* w w w . j a v a2s . c o m*/ NamingEnumeration results = null; DirContext ctx = null; try { ctx = getContext(); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return user; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getIfValidUser(String cn, String password) { LDAPUser user = null;//w w w . j ava 2s.c o m NamingEnumeration results = null; DirContext ctx = null; try { ctx = getAuthContext(cn, password); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return user; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * change password of given user, needs old password for authentication. * * @param inUser/* w w w .j av a 2s.co m*/ * User object * @param inOldPassword * String * @param inNewPassword * String * @return boolean about result of change */ public boolean changeUserPassword(User inUser, String inOldPassword, String inNewPassword) throws NoSuchAlgorithmException { MD4 digester = new MD4(); Hashtable<String, String> env = getLdapConnectionSettings(); if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) { env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); try { DirContext ctx = new InitialDirContext(env); /* * Encryption of password and Base64-Encoding */ MessageDigest md = MessageDigest.getInstance(ConfigCore.getParameter("ldap_encryption", "SHA")); md.update(inNewPassword.getBytes(StandardCharsets.UTF_8)); String digestBase64 = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8); ModificationItem[] mods = new ModificationItem[4]; /* * UserPasswort-Attribut ndern */ BasicAttribute userpassword = new BasicAttribute("userPassword", "{" + ConfigCore.getParameter("ldap_encryption", "SHA") + "}" + digestBase64); /* * LanMgr-Passwort-Attribut ndern */ BasicAttribute lanmgrpassword = null; try { lanmgrpassword = new BasicAttribute("sambaLMPassword", LdapUser.toHexString(LdapUser.lmHash(inNewPassword))); // TODO: Don't catch super class exception, make sure that // the password isn't logged here } catch (Exception e) { logger.error(e); } /* * NTLM-Passwort-Attribut ndern */ BasicAttribute ntlmpassword = null; try { byte hmm[] = digester.digest(inNewPassword.getBytes("UnicodeLittleUnmarked")); ntlmpassword = new BasicAttribute("sambaNTPassword", LdapUser.toHexString(hmm)); } catch (UnsupportedEncodingException e) { // TODO: Make sure that the password isn't logged here logger.error(e); } BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet", String.valueOf(System.currentTimeMillis() / 1000l)); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userpassword); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrpassword); mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmpassword); mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet); ctx.modifyAttributes(getUserDN(inUser), mods); // Close the context when we're done ctx.close(); return true; } catch (NamingException e) { logger.debug("Benutzeranmeldung nicht korrekt oder Passwortnderung nicht mglich", e); return false; } } return false; }
From source file:com.konakart.bl.LDAPMgrCore.java
/** * Called if the LDAP module is installed and active. This method should return: * <ul>/*from ww w . j ava 2 s. c om*/ * <li>A negative number in order for the login attempt to fail. The KonaKart login() method * will return a null sessionId</li> * <li>Zero to signal that this method is not implemented. The KonaKart login() method will * perform the credential check.</li> * <li>A positive number for the login attempt to pass. The KonaKart login() will not check * credentials, and will log in the customer, returning a valid session id.</li> * </ul> * This method may need to be modified slightly depending on the structure of your LDAP. The * example works when importing the exampleData.ldif file in the LDAP module jar: * * dn: cn=Robert Smith,ou=people,dc=example,dc=com<br/> * objectclass: inetOrgPerson<br/> * cn: Robert Smith<br/> * cn: Robert J Smith<br/> * cn: bob smith<br/> * sn: smith<br/> * uid: rjsmith<br/> * userpassword: rJsmitH<br/> * carlicense: HISCAR 123<br/> * homephone: 555-111-2222<br/> * mail: r.smith@example.com<br/> * mail: rsmith@example.com<br/> * mail: bob.smith@example.com<br/> * description: swell guy<br/> * * The code attempts to connect to LDAP using the username, password and URL in the * configuration variables set when the module was installed through the admin app.<br/> * * After having connected, the person object is searched for using the email address of the * user. If found we use the "cn" attribute and the password of the user to attempt to bind to * LDAP. If the bind is successful, we return a positive number which means that authentication * was successful. * * @param emailAddr * The user name required to log in * @param password * The log in password * @return Returns an integer * @throws Exception */ public int checkCredentials(String emailAddr, String password) throws Exception { DirContext ctx = null; try { Hashtable<String, String> environment = new Hashtable<String, String>(); if (log.isDebugEnabled()) { log.debug("LDAP connection URL = " + url); log.debug("LDAP user name = " + ldapUserName); log.debug("LDAP person object distinguished name (DN) = " + personDN); } if (ldapUserName == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_USER_NAME configuration variable hasn't been set."); } if (ldapPassword == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_PASSWORD configuration variable hasn't been set."); } if (url == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_URL configuration variable hasn't been set."); } if (personDN == null) { throw new KKException( "Cannot validate through LDAP because the MODULE_OTHER_LDAP_PERSON_DN (Distinguished Name of Person Object) configuration variable hasn't been set."); } environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environment.put(Context.SECURITY_AUTHENTICATION, "simple"); environment.put(Context.PROVIDER_URL, url); environment.put(Context.SECURITY_PRINCIPAL, ldapUserName); environment.put(Context.SECURITY_CREDENTIALS, ldapPassword); /* * connect to LDAP using the credentials and connection string from the configuration * variables */ try { ctx = new InitialDirContext(environment); } catch (Exception e) { log.error("Cannot connect to LDAP", e); return -1; } /* Specify the search filter on the eMail address */ String filter = "(mail=" + emailAddr + ")"; /* * limit returned attributes to those we care about. In this case we only require the * "cn" attribute which we will use to attempt to bind the user in order to validate his * password */ String[] attrIDs = { "cn" }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); /* Search for objects using filter and controls */ NamingEnumeration<SearchResult> answer = ctx.search(personDN, filter, ctls); /* close the connection */ ctx.close(); if (answer == null || !answer.hasMore()) { return -1; } SearchResult sr = answer.next(); Attributes attrs = sr.getAttributes(); String cn = attrs.get("cn").toString(); if (log.isDebugEnabled()) { log.debug("cn of user with eMail (" + emailAddr + ") is " + cn); } /* * cn could be in the format "cn: Peter Smith, Pete Smith, Smithy" so we need to capture * just the first entry */ if (cn != null) { if (cn.contains(",")) { cn = cn.split(",")[0]; if (cn.contains(":")) { cn = cn.split(":")[1]; } } else if (cn.contains(":")) { cn = cn.split(":")[1]; } } if (log.isDebugEnabled()) { log.debug("Cleaned cn of user with eMail (" + emailAddr + ") is " + cn); } /* Now we try to bind as the user */ String userName = "cn=" + cn + "," + personDN; if (log.isDebugEnabled()) { log.debug("LDAP user name of user with eMail (" + emailAddr + ") is " + userName); } /* Bind as the user */ environment.put(Context.SECURITY_PRINCIPAL, userName); environment.put(Context.SECURITY_CREDENTIALS, password); try { ctx = new InitialDirContext(environment); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Could not bind user " + userName); } return -1; } ctx.close(); if (log.isDebugEnabled()) { log.debug("user with eMail (" + emailAddr + ") was successfully authenticated using LDAP"); } return 1; } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { log.error("Received an exception while closing the LDAP DirContext", e); } } } }
From source file:com.openkm.principal.LdapPrincipalAdapter.java
@SuppressWarnings("unchecked") private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) { log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute }); List<String> al = new ArrayList<String>(); DirContext ctx = null; Hashtable<String, String> env = getEnvironment(); try {/* ww w. j a v a 2 s. com*/ ctx = new InitialDirContext(env); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); for (String searchBase : searchBases) { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); if (attribute.equals("")) { StringBuilder sb = new StringBuilder(); for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) { Attribute attr = (Attribute) ne.nextElement(); sb.append(attr.toString()); sb.append("\n"); } al.add(sb.toString()); } else { Attribute attrib = attributes.get(attribute); if (attrib != null) { // Handle multi-value attributes for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) { String value = (String) ne.nextElement(); // If FQDN get only main part if (value.startsWith("CN=") || value.startsWith("cn=")) { String cn = value.substring(3, value.indexOf(',')); log.debug("FQDN: {}, CN: {}", value, cn); al.add(cn); } else { al.add(value); } } } } } } } catch (ReferralException e) { log.error("ReferralException: {}", e.getMessage()); log.error("ReferralInfo: {}", e.getReferralInfo()); log.error("ResolvedObj: {}", e.getResolvedObj()); try { log.error("ReferralContext: {}", e.getReferralContext()); } catch (NamingException e1) { log.error("NamingException logging context: {}", e1.getMessage()); } } catch (NamingException e) { log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})", new Object[] { e.getMessage(), searchBases, searchFilter, attribute }); } finally { try { if (ctx != null) { ctx.close(); } } catch (NamingException e) { log.error("NamingException closing context: {}", e.getMessage()); } } log.debug("ldapSearch: {}", al); return al; }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the field value of the specified field for the specified id. * @see IExternalStorage#getField(java.lang.String, java.lang.String) *///from w w w . j av a2 s. c o m public Object getField(String id, String field) throws UserException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; Object oValue = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attribute '"); sbFailed.append(field); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration oAttrEnum = oAttributes.getAll(); if (oAttrEnum.hasMore()) { Attribute oAttribute = (Attribute) oAttrEnum.next(); oValue = oAttribute.get(); } } catch (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not retrieve field: " + field, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return oValue; }
From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java
private boolean ldapAuthorizationVerification(String user) { M_log.debug("ldapAuthorizationVerification(): called"); boolean isAuthorized = false; DirContext dirContext = null; NamingEnumeration listOfPeopleInAuthGroup = null; NamingEnumeration allSearchResultAttributes = null; NamingEnumeration simpleListOfPeople = null; Hashtable<String, String> env = new Hashtable<String, String>(); if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) { env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY); env.put(Context.PROVIDER_URL, providerURL); } else {//from w w w. j a va 2s. c o m M_log.error( " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file"); return isAuthorized; } try { dirContext = new InitialDirContext(env); String[] attrIDs = { "member" }; SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(attrIDs); searchControls.setReturningObjFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBase = OU_GROUPS; String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))"; listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls); String positiveMatch = "uid=" + user + ","; outerloop: while (listOfPeopleInAuthGroup.hasMore()) { SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next(); allSearchResultAttributes = (searchResults.getAttributes()).getAll(); while (allSearchResultAttributes.hasMoreElements()) { Attribute attr = (Attribute) allSearchResultAttributes.nextElement(); simpleListOfPeople = attr.getAll(); while (simpleListOfPeople.hasMoreElements()) { String val = (String) simpleListOfPeople.nextElement(); if (val.indexOf(positiveMatch) != -1) { isAuthorized = true; break outerloop; } } } } return isAuthorized; } catch (NamingException e) { M_log.error("Problem getting attribute:" + e); return isAuthorized; } finally { try { if (simpleListOfPeople != null) { simpleListOfPeople.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ", e); } try { if (allSearchResultAttributes != null) { allSearchResultAttributes.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ", e); } try { if (listOfPeopleInAuthGroup != null) { listOfPeopleInAuthGroup.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ", e); } try { if (dirContext != null) { dirContext.close(); } } catch (NamingException e) { M_log.error("Problem occurred while closing the \"dirContext\" object", e); } } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the values of the specified fields for the supplied id. * @see IExternalStorage#getFields(java.lang.String, java.util.List) */// w w w . j a v a2 s . c om public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException { Hashtable<String, Object> htReturn = new Hashtable<String, Object>(); DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] saFields = fields.toArray(new String[0]); oScope.setReturningAttributes(saFields); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes '"); sbFailed.append(fields); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); htReturn.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; htReturn.put(sAttributeName, oValue); } } } catch (UserException e) { throw e; } catch (Exception e) { _logger.fatal("Could not retrieve fields: " + fields, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return htReturn; }
From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java
/** * Gathers attributes from JNDI storage to the supplied attributes object. * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes) *//*from www. j a v a2 s .c om*/ public void process(String sUserId, IAttributes oAttributes) throws AttributeException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); if (_listGather.size() > 0) { String[] saAttributes = _listGather.toArray(new String[0]); oScope.setReturningAttributes(saAttributes); } String searchFilter = resolveSearchQuery(sUserId); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes for id: "); sbFailed.append(sUserId); _logger.error(sbFailed.toString(), e); throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.debug("User unknown: " + sUserId); return; } if (oNamingEnumeration.hasMore()) { SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oSearchedAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oSearchedAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); String sMappedName = _htMapper.get(sAttributeName); if (sMappedName != null) sAttributeName = sMappedName; if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); oAttributes.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; oAttributes.put(sAttributeName, oValue); } } } } catch (AttributeException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch attributes for user: " + sUserId, e); } catch (Exception e) { _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e); throw new AttributeException(SystemErrors.ERROR_INTERNAL); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e); } } } }
From source file:it.webappcommon.lib.LDAPHelper.java
/** * @param args//from ww w.j a v a2 s . co m * the command line arguments */ // public static void main(String[] args) { private List<UserInfo> search(String filter) throws NamingException { DirContext ctx = null; SearchControls ctls = null; Properties env = new Properties(); List<UserInfo> res = new ArrayList<UserInfo>(); boolean trovatiRisultati = false; env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT); env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port); env.put(Context.SECURITY_AUTHENTICATION, "simple"); if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) { env.put(Context.SECURITY_PRINCIPAL, loginUserName); } else { env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName); } env.put(Context.SECURITY_CREDENTIALS, loginPassword); try { ctx = new InitialDirContext(env); ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // String filter = ""; // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))"; // filter = FILTER_USERS_ACTIVE; // Tutti i membri di un gruppo // (objectCategory=user)(memberOf=CN=QA Users,OU=Help // Desk,DC=dpetri,DC=net) // ESEMPI // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm // Account disabled // (UserAccountControl:1.2.840.113556.1.4.803:=2) NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls); UserInfo userInfo = null; while (answer.hasMoreElements()) { trovatiRisultati = true; SearchResult a = answer.nextElement(); // logger.debug(a.getNameInNamespace()); Attributes result = a.getAttributes(); if (result == null) { // System.out.print("Attributi non presenti"); } else { NamingEnumeration<? extends Attribute> attributi = result.getAll(); userInfo = new UserInfo(); while (attributi.hasMoreElements()) { Attribute att = attributi.nextElement(); // logger.debug(att.getID()); String value = ""; // for (NamingEnumeration vals = att.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())) // ; NamingEnumeration<?> vals = att.getAll(); while (vals.hasMoreElements()) { Object val = vals.nextElement(); // logger.debug("\t" + val); value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString(); } if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) { // userInfo.setFIELD_ACCOUNT_NAME(value); userInfo.setAccount(value); } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) { // userInfo.setFIELD_COGNOME(value); userInfo.setCognome(value); } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) { // userInfo.setFIELD_EMAIL(value); userInfo.setEmail(value); } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) { // userInfo.setFIELD_GROUPS(value); userInfo.setGruppi(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) { // userInfo.setFIELD_NOME(value); userInfo.setNome(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) { // userInfo.setFIELD_NOME_COMPLETO(value); userInfo.setNomeCompleto(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) { // userInfo.setFIELD_NOME_VISUALIZZATO(value); // userInfo.setNome(value); } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) { // userInfo.setFIELD_TEL(value); userInfo.setTel(value); } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) { // userInfo.setFIELD_UFFICIO(value); userInfo.setUfficio(value); } // res.put(att.getID(), value); } // Attribute attr = result.get("cn"); // if (attr != null) { // logger.debug("cn:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // attr = result.get("sn"); // if (attr != null) { // logger.debug("sn:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // attr = result.get("mail"); // if (attr != null) { // logger.debug("mail:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // // attr = result.get("uid"); // // if (attr != null) { // // logger.debug("uid:"); // // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // // } // // // // attr = result.get("userPassword"); // // if (attr != null) { // // logger.debug("userPassword:"); // // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // // } if (userInfo != null) { res.add(userInfo); } } } } catch (NamingException ne) { // ne.printStackTrace(); logger.error(ne); throw ne; } finally { try { if (ctx != null) { ctx.close(); } } catch (Exception e) { } } // Azzero l'hash map if (!trovatiRisultati) { res = null; } return res; }