List of usage examples for javax.naming.directory Attribute get
Object get() throws NamingException;
From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java
private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx) throws NamingException { String uid;/* w ww .j a v a 2s. c o m*/ SearchControls ctls = new SearchControls(); ctls.setReturningObjFlag(true); ctls.setSearchScope(searchScope); String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login)); log.debug("Searching LDAP for " + search); NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls); try { if (!answer.hasMore()) throw new NoSuchElementException(); log.debug("LDAP returned >=1 record."); SearchResult result = answer.next(); uid = result.getName(); for (Map.Entry<String, String> e : attributeMap.entrySet()) { log.debug("found LDAP attribute: " + e.getKey()); Attribute a = result.getAttributes().get(e.getKey()); if (a != null) userAttrs.put(e.getValue(), a.get().toString()); } } finally { answer.close(); } return uid; }
From source file:ca.tnt.ldaputils.impl.LdapEntry.java
public String getStringAttribute(final Attributes attributes, final String attribute) throws NamingException { final Attribute temp; final String attributeValue; temp = attributes.get(attribute);/*from w w w . ja v a 2s .co m*/ if (temp != null) { attributeValue = (String) temp.get(); logger.debug(attribute + ": " + getStringValue("cn")); } else { attributeValue = null; } return attributeValue; }
From source file:ru.runa.wfe.security.logic.LdapLogic.java
private String getStringAttribute(SearchResult searchResult, String name) throws NamingException { if (Utils.isNullOrEmpty(name)) { return null; }/*w w w . j a va 2s . com*/ Attribute attribute = searchResult.getAttributes().get(name); if (attribute != null) { return attribute.get().toString(); } return null; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches single parent, cutting the dn and trying to get the given entry. * * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String) */// w w w .j a va2 s. c om @Override public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException { Set<String> sourceIds = new TreeSet<>(); String targetDn = null; // step #1: fetch the dn of the targetId entry in the target // directory by the static dn valued strategy LDAPDirectory targetDir = getTargetLDAPDirectory(); try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId, true); if (targetLdapEntry == null) { // no parent accessible => return empty list return EMPTY_STRING_LIST; } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + targetId, e); } // step #2: search for entries that reference parent dn in the // source directory and collect its id LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); String parentDn = getParentDn(targetDn); String filterExpr = String.format("(&%s)", ldapSourceDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapSourceDirectory.getSearchControls(true); sctls.setSearchScope(SearchControls.OBJECT_SCOPE); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", targetId, parentDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(parentDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(sourceSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { sourceIds.add(value.toString()); // only supposed to get one result anyway break; } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + targetDn, e); } return new ArrayList<>(sourceIds); }
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 a2s . co 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:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches children, onelevel or subtree given the reference configuration. * <p>//w w w . j a va 2 s. c om * Removes entries with same id than parent to only get real children. * * @see org.nuxeo.ecm.directory.Reference#getTargetIdsForSource(String) */ // TODO: optimize reusing the same ldap session (see LdapReference optim // method) @Override public List<String> getTargetIdsForSource(String sourceId) throws DirectoryException { Set<String> targetIds = new TreeSet<>(); String sourceDn = null; // step #1: fetch the dn of the sourceId entry in the source // directory by the static dn valued strategy LDAPDirectory sourceDir = getSourceLDAPDirectory(); try (LDAPSession sourceSession = (LDAPSession) sourceDir.getSession()) { SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId, true); if (sourceLdapEntry == null) { throw new DirectoryException(sourceId + " does not exist in " + sourceDirectoryName); } sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + sourceId, e); } // step #2: search for entries with sourceDn as base dn and collect // their ids LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory(); String filterExpr = String.format("(&%s)", ldapTargetDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapTargetDirectory.getSearchControls(true); sctls.setSearchScope(getScope()); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getTargetIdsForSource(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", sourceId, sourceDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = targetSession.dirContext.search(sourceDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(targetSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { // always remove self as child String targetId = value.toString(); if (!sourceId.equals(targetId)) { targetIds.add(targetId); } } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + sourceDn, e); } return new ArrayList<>(targetIds); }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups// w ww . j a v a 2 s .com * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean, String baseDnGroup, String ldapFilterGroups, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap) throws Exception { if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) { ldapFilterGroups = "(" + groupAttributeName + "=*)"; } String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword); HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); if (context == null) { LOGGER.warn("Context is null"); return ldapGroupsMap; } int recordCount = 0; SearchControls ctls = null; String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { groupMemberAttributName = DEFAULT_GROUP_MEMBER; } try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); return null; } TPersonBean personBean = new TPersonBean(); try { Attribute groupNameAttribute = attributes.get(groupAttributeName); if (groupNameAttribute != null) { String groupName = (String) groupNameAttribute.get(); LOGGER.debug("Groupname: " + groupName); if (groupName == null || "".equals(groupName)) { LOGGER.info("No value for group name attribute " + groupAttributeName); return null; } else { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); } Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName() + " " + personBean.getLastName() + ")"); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { context.close(); } return ldapGroupsMap; }
From source file:org.springframework.ldap.ldif.parser.LdifParser.java
private void addAttributeToRecord(String buffer, LdapAttributes record) { try {//from ww w. j a v a 2 s . c om if (StringUtils.isNotEmpty(buffer) && record != null) { //Validate previous attribute and add to record. Attribute attribute = attributePolicy.parse(buffer); if (attribute.getID().equalsIgnoreCase("dn")) { log.trace("...adding DN to record."); String dn; if (attribute.get() instanceof byte[]) { dn = new String((byte[]) attribute.get()); } else { dn = (String) attribute.get(); } record.setDN(new DistinguishedName(dn)); } else { log.trace("...adding attribute to record."); Attribute attr = record.get(attribute.getID()); if (attr != null) { attr.add(attribute.get()); } else { record.put(attribute); } } } } catch (NamingException e) { log.error(e); } catch (NoSuchElementException e) { log.error(e); } }
From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java
private void populateDCMap() throws UserStoreException { try {// w ww. j a v a2 s. c o m //get the directory context for DNS DirContext dnsContext = new InitialDirContext(environmentForDNS); //compose the DNS service to be queried String DNSServiceName = LDAPConstants.ACTIVE_DIRECTORY_DOMAIN_CONTROLLER_SERVICE + DNSDomainName; //query the DNS Attributes attributes = dnsContext.getAttributes(DNSServiceName, new String[] { LDAPConstants.SRV_ATTRIBUTE_NAME }); Attribute srvRecords = attributes.get(LDAPConstants.SRV_ATTRIBUTE_NAME); //there can be multiple records with same domain name - get them all NamingEnumeration srvValues = srvRecords.getAll(); dcMap = new TreeMap<Integer, SRVRecord>(); //extract all SRV Records for _ldap._tcp service under the specified domain and populate dcMap //int forcedPriority = 0; while (srvValues.hasMore()) { String value = srvValues.next().toString(); SRVRecord srvRecord = new SRVRecord(); String valueItems[] = value.split(" "); String priority = valueItems[0]; if (priority != null) { int priorityInt = Integer.parseInt(priority); /*if ((priorityInt == forcedPriority) || (priorityInt < forcedPriority)) { forcedPriority++; priorityInt = forcedPriority; }*/ srvRecord.setPriority(priorityInt); } /* else { forcedPriority++; srvRecord.setPriority(forcedPriority); }*/ String weight = valueItems[1]; if (weight != null) { srvRecord.setWeight(Integer.parseInt(weight)); } String port = valueItems[2]; if (port != null) { srvRecord.setPort(Integer.parseInt(port)); } String host = valueItems[3]; if (host != null) { srvRecord.setHostName(host); } //we index dcMap on priority basis, therefore, priorities must be different dcMap.put(srvRecord.getPriority(), srvRecord); } //iterate over the SRVRecords for Active Directory Domain Controllers and figure out the //host records for that for (SRVRecord srvRecord : dcMap.values()) { Attributes hostAttributes = dnsContext.getAttributes(srvRecord.getHostName(), new String[] { LDAPConstants.A_RECORD_ATTRIBUTE_NAME }); Attribute hostRecord = hostAttributes.get(LDAPConstants.A_RECORD_ATTRIBUTE_NAME); //we know there is only one IP value for a given host. So we do just get, not getAll srvRecord.setHostIP((String) hostRecord.get()); } } catch (NamingException e) { log.error("Error obtaining information from DNS Server" + e.getMessage(), e); throw new UserStoreException("Error obtaining information from DNS Server " + e.getMessage(), e); } }
From source file:edu.internet2.middleware.subject.provider.ESCOJNDISourceAdapter.java
/** * Creates a subject with a custom implementation. * //from w w w . ja v a 2 s .c o m * @param attrs * The attributes associated to the subject. * @return The Subject. */ private Subject createSubject(final Attributes attrs) { String subjectName = ""; String subjectID = ""; String description = ""; try { Attribute attribute = attrs.get(this.subjectIDAttributeName); if (attribute == null) { LOGGER.error("The LDAP attribute \"" + this.subjectIDAttributeName + "\" does not have a value. " + "It is beging used as the Grouper special attribute \"SubjectID\"."); return null; } subjectID = (String) attribute.get(); attribute = attrs.get(this.nameAttributeName); if (attribute == null) { LOGGER.error("The LDAP attribute \"" + this.nameAttributeName + "\" does not have a value. z" + "It is being used as the Grouper special attribute \"name\"."); return null; } subjectName = (String) attribute.get(); attribute = attrs.get(this.descriptionAttributeName); if (attribute == null) { LOGGER.error("The LDAP attribute \"" + this.descriptionAttributeName + "\" does not have a value. " + "It is being used as the Grouper special attribute \"description\"."); } else { description = (String) attribute.get(); } } catch (NamingException ex) { LOGGER.error("LDAP Naming Except: " + ex.getMessage(), ex); } return new ESCOJNDISubject(subjectID, subjectName, description, this.getSubjectType(), this); }