List of usage examples for javax.naming.directory Attribute getAll
NamingEnumeration<?> getAll() throws NamingException;
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
private List searchGroupMember(DirContext context, Map filters) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); Set userList = new HashSet(); String filter = buildFilter(filters); if (log.isInfoEnabled()) log.info("Search User from " + userBase + " by " + filter); NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls); while (searchResultEnum.hasMore()) { SearchResult searchResult = (SearchResult) searchResultEnum.next(); Attributes attrs = searchResult.getAttributes(); String dn = searchResult.getName() + "," + groupBase; String uniquememberAttrName = "uniqueMember"; if (this.propAttrMap.containsKey("org_member")) { try { uniquememberAttrName = (String) this.propAttrMap.get("org_member"); } catch (Exception ex) { //ignore }//from w w w . j av a 2 s .c om } Attribute uniquememberAttr = attrs.get(uniquememberAttrName); if (uniquememberAttr == null) continue; NamingEnumeration memberDNs = uniquememberAttr.getAll(); while (memberDNs.hasMoreElements()) { //System.out.println(memberDNs[j]); userList.add(memberDNs.next());//DN of user } } List members = new ArrayList(); for (Iterator userDns = userList.iterator(); userDns.hasNext();) { /* Next directory entry */ String userDn = (String) userDns.next(); Attributes userEntry = null; try { userEntry = context.getAttributes(userDn);//DN of user } catch (Exception e) { log.error(userDn + ": " + e.getMessage()); } if (userEntry == null) continue; LDAPAccount user = createLDAPUser(userDn, userEntry); if (user.getUid() == null) continue; members.add(user); } return members; }
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) *///from w ww. j a v a 2 s.c o m 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:org.pentaho.platform.plugin.services.security.userrole.ldap.transform.SearchResultToAttrValueList.java
public Object transform(final Object obj) { Object transformed = obj;/* w w w. j a v a 2 s .co m*/ if (obj instanceof SearchResult) { transformed = new HashSet(); Set valueSet = (Set) transformed; SearchResult res = (SearchResult) obj; if (SearchResultToAttrValueList.logger.isDebugEnabled()) { SearchResultToAttrValueList.logger.debug(Messages.getInstance().getString( "SearchResultToAttrValueList.DEBUG_ATTRIBUTES_FROM_SEARCHRESULT", (null != res.getAttributes()) ? res.getAttributes().toString() : "null")); //$NON-NLS-1$ //$NON-NLS-2$ } Attribute attr = res.getAttributes().get(attributeName); if (SearchResultToAttrValueList.logger.isDebugEnabled()) { SearchResultToAttrValueList.logger .debug(Messages.getInstance().getString("SearchResultToAttrValueList.DEBUG_ATTRIBUTE_VALUE", attributeName, (null != attr) ? attr.toString() : "null")); //$NON-NLS-1$ //$NON-NLS-2$ } if (attr != null) { // check for null as node might not have attribute we're looking for try { NamingEnumeration values = attr.getAll(); while (values.hasMore()) { // if tokenName was specified, extract from value; otherwise // store value unchanged Object value = values.next(); if (StringUtils.hasLength(tokenName)) { if ((null != value) && (value instanceof String)) { String tokenValue = extract((String) value, tokenName); if (null != tokenValue) { valueSet.add(tokenValue); } } else { if (SearchResultToAttrValueList.logger.isWarnEnabled()) { SearchResultToAttrValueList.logger.warn(Messages.getInstance() .getString("SearchResultToAttrValueList.WARN_ATTRIBUTE_NOT_A_STRING")); //$NON-NLS-1$ } } } else { if (null != value) { valueSet.add(value.toString()); } } } } catch (NamingException e) { if (SearchResultToAttrValueList.logger.isErrorEnabled()) { SearchResultToAttrValueList.logger.error(Messages.getInstance() .getErrorString("SearchResultToAttrValueList.ERROR_0001_NAMING_EXCEPTION"), e); //$NON-NLS-1$ } } } return transformed; } return transformed; }
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private void serialize(List results, Config config, ContentHandler ch) { try {/*w ww.ja v a2s . c om*/ ch.startDocument(); ch.startElement("", "results", "results", SAXUtils.EMPTY_ATTRIBUTES); for (Iterator i = results.iterator(); i.hasNext();) { SearchResult sr = (SearchResult) i.next(); ch.startElement("", "result", "result", SAXUtils.EMPTY_ATTRIBUTES); addElement(ch, "name", sr.getName()); try { addElement(ch, "fullname", sr.getNameInNamespace()); } catch (UnsupportedOperationException e) { // This seems to be the only way to know if sr contains a name! } Attributes attr = sr.getAttributes(); NamingEnumeration attrEn = attr.getAll(); while (attrEn.hasMoreElements()) { Attribute a = (Attribute) attrEn.next(); if (config.getAttributes().isEmpty() || config.getAttributes().contains(a.getID())) { ch.startElement("", "attribute", "attribute", SAXUtils.EMPTY_ATTRIBUTES); addElement(ch, "name", a.getID()); NamingEnumeration aEn = a.getAll(); while (aEn.hasMoreElements()) { Object o = aEn.next(); addElement(ch, "value", o.toString()); } ch.endElement("", "attribute", "attribute"); } } ch.endElement("", "result", "result"); } ch.endElement("", "results", "results"); ch.endDocument(); } catch (Exception e) { throw new OXFException(e); } }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public boolean isValidPassword(String serverName, Object existingCredentials) throws DirectoryServerManagerException { DirContext dirContext;//from w w w. j ava2s .c om try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } //first search the existing user entry. String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD); NamingEnumeration passwords = userPassword.getAll(); String passwordHashMethod = null; if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray, StandardCharsets.UTF_8); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}")); } return password.equals(getPasswordToStore((String) existingCredentials, passwordHashMethod)); } } } catch (NamingException e) { log.error("Failed, validating password. Can not access the directory service", e); throw new DirectoryServerManagerException( "Failed, validating password. " + "Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } return false; }
From source file:org.wso2.carbon.appfactory.s4.integration.DomainMappingManagementService.java
/** * Resolve CNAME and A records for the given {@code hostname}. * * @param domain hostname to be resolved. * @param environmentConfigs environment configuration * @return {@link com.google.common.collect.Multimap} of resolved dns entries. This {@link com.google.common.collect.Multimap} will contain the resolved * "CNAME" and "A" records from the given {@code hostname} * @throws AppFactoryException if error occurred while the operation *///from w w w . j a v a 2 s . com public Multimap<String, String> resolveDNS(String domain, Hashtable<String, String> environmentConfigs) throws AppFactoryException, DomainMappingVerificationException { // result mutimap of dns records. Contains the cname and records resolved by the given hostname // ex: CNAME => foo.com,bar.com // A => 192.1.2.3 , 192.3.4.5 Multimap<String, String> dnsRecordsResult = ArrayListMultimap.create(); Attributes dnsRecords; boolean isARecordFound = false; boolean isCNAMEFound = false; try { if (log.isDebugEnabled()) { log.debug("DNS validation: resolving DNS for " + domain + " " + "(A/CNAME)"); } DirContext context = new InitialDirContext(environmentConfigs); String[] dnsRecordsToCheck = new String[] { DNS_A_RECORD, DNS_CNAME_RECORD }; dnsRecords = context.getAttributes(domain, dnsRecordsToCheck); } catch (NamingException e) { String msg = "DNS validation: DNS query failed for: " + domain + ". Error occurred while configuring " + "directory context."; log.error(msg, e); throw new AppFactoryException(msg, e); } try { // looking for for A records Attribute aRecords = dnsRecords.get(DNS_A_RECORD); if (aRecords != null && aRecords.size() > 0) { // if an A record exists NamingEnumeration aRecordHosts = aRecords.getAll(); // get all resolved A entries String aHost; while (aRecordHosts.hasMore()) { isARecordFound = true; aHost = (String) aRecordHosts.next(); dnsRecordsResult.put(DNS_A_RECORD, aHost); if (log.isDebugEnabled()) { log.debug("DNS validation: A record found: " + aHost); } } } // looking for CNAME records Attribute cnameRecords = dnsRecords.get(DNS_CNAME_RECORD); if (cnameRecords != null && cnameRecords.size() > 0) { // if CNAME record exists NamingEnumeration cnameRecordHosts = cnameRecords.getAll(); // get all resolved CNAME entries for hostname String cnameHost; while (cnameRecordHosts.hasMore()) { isCNAMEFound = true; cnameHost = (String) cnameRecordHosts.next(); if (cnameHost.endsWith(".")) { // Since DNS records are end with "." we are removing it. // For example real dns entry for www.google.com is www.google.com. cnameHost = cnameHost.substring(0, cnameHost.lastIndexOf('.')); } dnsRecordsResult.put(DNS_CNAME_RECORD, cnameHost); if (log.isDebugEnabled()) { log.debug("DNS validation: recurring on CNAME record towards host " + cnameHost); } dnsRecordsResult.putAll(resolveDNS(cnameHost, environmentConfigs)); // recursively resolve cnameHost } } if (!isARecordFound && !isCNAMEFound && log.isDebugEnabled()) { log.debug("DNS validation: No CNAME or A record found for domain: '" + domain); } return dnsRecordsResult; } catch (NamingException ne) { String msg = "DNS validation: DNS query failed for: " + domain + ". Provided domain: " + domain + " might be a " + "non existing domain."; // we are logging this as warn messages since this is caused, due to an user error. For example if the // user entered a rubbish custom url(Or a url which is, CNAME record is not propagated at the // time of adding the url), then url validation will fail but it is not an system error log.warn(msg, ne); throw new DomainMappingVerificationException(msg, ne); } }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static void parseData(NamingEnumeration searchResults) { int totalResultLogger = 0; if (searchResults == null) { return;// w w w.j a v a 2 s . c om } // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return; } Attributes attrs = sr.getAttributes(); if (attrs != null) { try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static Map<String, String> parseDataAsMap(NamingEnumeration searchResults) { Map<String, String> resultAttrMap = null; int totalResultLogger = 0; if (searchResults == null) { return null; }/*from w w w. j a v a 2 s.c o m*/ // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { if (resultAttrMap == null) { resultAttrMap = new HashMap<String, String>(); } try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { String attrValue = (String) e.next(); resultAttrMap.put(attr.getID(), attrValue); } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } return resultAttrMap; }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static List parseDataAsList(NamingEnumeration searchResults) { //Logger.info("Formatting the data as List", LDAPUtils.class ); List<String> resultAttr = null; int totalResultLogger = 0; if (searchResults == null) { return null; }/*w w w .j a va2 s. c o m*/ // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { if (resultAttr == null) { resultAttr = new ArrayList(); } try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { String attrValue = (String) e.next(); resultAttr.add(attrValue); } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } return resultAttr; }
From source file:com.wfp.utils.LDAPUtils.java
public static Map<String, String> parseAsMap(NamingEnumeration searchResults, String keyAttribute, String valueAttribute) {//from w w w . ja v a 2s.c om Logger.debug("# START parseAsMap : Formatting the data as MAP", LDAPUtils.class); //System.out.println("# START parseAsMap : Formatting the data as MAP: "+searchResults ); Map<String, String> resultMap = new HashMap<String, String>(); if (searchResults == null) { return null; } // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; List<String> strList = new ArrayList<String>(); try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); e.next()) ; //System.out.println(" attrs : "+attrs.get(keyAttribute) + ": "+ attrs.get(valueAttribute)); //if(attrs.get(keyAttribute)!=null && attrs.get(keyAttribute)!=null) resultMap.put(attrs.get(keyAttribute).toString(), attrs.get(valueAttribute).toString()); } } catch (NamingException ne) { ne.printStackTrace(); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } //Logger.debug("# END parseAsMap : Formatting the data as MAP", LDAPUtils.class ); return resultMap; }