List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
public Collection<String> getGroupNames() { final List<String> groupNames = new LinkedList<String>(); processQuery(new SearchCallback() { public void process(SearchResult result) throws NamingException, ParseException { Attribute nameAttribute = result.getAttributes() .get(LDAPMultiBaseUserRegistry.this.groupIdAttributeName); if (nameAttribute == null) { if (LDAPMultiBaseUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPMultiBaseUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params); } else { LDAPMultiBaseUserRegistry.logger.warn("Missing GID on " + result.getNameInNamespace()); }/* w ww.j ava2 s.com*/ } else { String authority = "GROUP_" + (String) nameAttribute.get(); if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger.debug("Group DN recognized: " + authority); } groupNames.add(authority); } } public void close() throws NamingException { } }, this.groupSearchBases, this.groupQuery, new String[] { this.groupIdAttributeName }); return groupNames; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected UidNodeDescription mapToNode(final SearchResult searchResult, final String idAttributeName, final Map<String, String> attributeMapping, final Map<String, String> attributeDefaults) throws NamingException { final Attributes attributes = searchResult.getAttributes(); final Collection<String> uidValues = this.mapAttribute(attributes.get(idAttributeName), String.class); final String uid = uidValues.iterator().next(); final UidNodeDescription nodeDescription = new UidNodeDescription(searchResult.getNameInNamespace(), uid); final Attribute modifyTimestamp = attributes.get(this.modifyTimestampAttributeName); if (modifyTimestamp != null) { try {//from ww w . j a v a 2 s.c o m nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString())); LOGGER.debug("Setting last modified of node {} to {}", uid, nodeDescription.getLastModified()); } catch (final ParseException e) { throw new AlfrescoRuntimeException("Failed to parse timestamp.", e); } } final PropertyMap properties = nodeDescription.getProperties(); for (final String key : attributeMapping.keySet()) { final QName keyQName = QName.createQName(key, this.namespaceService); final String attributeName = attributeMapping.get(key); if (attributeName != null) { final Attribute attribute = attributes.get(attributeName); final String defaultAttribute = attributeDefaults.get(key); if (attribute != null) { final Collection<Object> mappedAttributeValue = this.mapAttribute(attribute); if (mappedAttributeValue.size() == 1) { final Object singleValue = mappedAttributeValue.iterator().next(); if (singleValue instanceof Serializable) { properties.put(keyQName, (Serializable) singleValue); } else { properties.put(keyQName, DefaultTypeConverter.INSTANCE.convert(String.class, singleValue)); } } else if (!mappedAttributeValue.isEmpty()) { final ArrayList<Serializable> values = new ArrayList<>(); mappedAttributeValue.forEach((x) -> { if (x instanceof Serializable) { values.add((Serializable) x); } else { values.add(DefaultTypeConverter.INSTANCE.convert(String.class, x)); } }); properties.put(keyQName, values); } else if (defaultAttribute != null) { properties.put(keyQName, defaultAttribute); } else { // Make sure that a 2nd sync, updates deleted ldap attributes (MNT-14026) properties.put(keyQName, null); } } else if (defaultAttribute != null) { LOGGER.debug("Node {} does not provide attriute {} - using default value", uid, attributeName); properties.put(keyQName, defaultAttribute); } else { LOGGER.debug("Node {} does not provide attriute {} - setting to null", uid, attributeName); // Make sure that a 2nd sync, updates deleted ldap attributes (MNT-14026) properties.put(keyQName, null); } } else { LOGGER.debug("No attribute name has been configured for property {}", keyQName); final String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { LOGGER.debug("Using default value for {} on node {}", keyQName, uid); properties.put(keyQName, defaultValue); } } } return nodeDescription; }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void getUsers(UserGroupSink sink) throws Throwable { NamingEnumeration<SearchResult> userSearchResultEnum = null; NamingEnumeration<SearchResult> groupSearchResultEnum = null; try {//ww w . j a v a2 s . c o m createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); extendedUserSearchFilter = "(objectclass=" + userObjectClass + ")(|(uSNChanged>=" + deltaSyncUserTime + ")(modifyTimestamp>=" + deltaSyncUserTimeStamp + "Z))"; if (userSearchFilter != null && !userSearchFilter.trim().isEmpty()) { String customFilter = userSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } extendedUserSearchFilter = "(&" + extendedUserSearchFilter + customFilter + ")"; } else { extendedUserSearchFilter = "(&" + extendedUserSearchFilter + ")"; } LOG.info("extendedUserSearchFilter = " + extendedUserSearchFilter); long highestdeltaSyncUserTime = deltaSyncUserTime; // When multiple OUs are configured, go through each OU as the user search base to search for users. for (int ou = 0; ou < userSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { int paged = 0; do { userSearchResultEnum = ldapContext.search(userSearchBase[ou], extendedUserSearchFilter, userSearchControls); while (userSearchResultEnum.hasMore()) { // searchResults contains all the user entries final SearchResult userEntry = userSearchResultEnum.next(); if (userEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("userEntry null, skipping sync for the entry"); } continue; } //System.out.println("userEntry = " + userEntry); Attributes attributes = userEntry.getAttributes(); if (attributes == null) { if (LOG.isInfoEnabled()) { LOG.info("attributes missing for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } Attribute userNameAttr = attributes.get(userNameAttribute); if (userNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(userNameAttribute + " missing for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } String userFullName = (userEntry.getNameInNamespace()).toLowerCase(); String userName = (String) userNameAttr.get(); if (userName == null || userName.trim().isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info(userNameAttribute + " empty for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } Attribute timeStampAttr = attributes.get("uSNChanged"); if (timeStampAttr != null) { String uSNChangedVal = (String) timeStampAttr.get(); long currentDeltaSyncTime = Long.parseLong(uSNChangedVal); LOG.info("uSNChangedVal = " + uSNChangedVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncUserTime) { highestdeltaSyncUserTime = currentDeltaSyncTime; } } else { timeStampAttr = attributes.get("modifytimestamp"); if (timeStampAttr != null) { String timeStampVal = (String) timeStampAttr.get(); Date parseDate = dateFormat.parse(timeStampVal); long currentDeltaSyncTime = parseDate.getTime(); LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncUserTime) { highestdeltaSyncUserTime = currentDeltaSyncTime; deltaSyncUserTimeStamp = timeStampVal; } } } if (!groupSearchFirstEnabled) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } //System.out.println("Adding user fullname = " + userFullName + " username = " + transformUserName); userNameMap.put(userFullName, transformUserName); Set<String> groups = new HashSet<String>(); // Get all the groups from the group name attribute of the user only when group search is not enabled. if (!groupSearchEnabled) { for (String useGroupNameAttribute : userGroupNameAttributeSet) { Attribute userGroupfAttribute = userEntry.getAttributes() .get(useGroupNameAttribute); if (userGroupfAttribute != null) { NamingEnumeration<?> groupEnum = userGroupfAttribute.getAll(); while (groupEnum.hasMore()) { String gName = getShortGroupName((String) groupEnum.next()); String transformGroupName = groupNameTransform(gName); groups.add(transformGroupName); } } } } List<String> groupList = new ArrayList<String>(groups); try { sink.addOrUpdateUser(transformUserName, groupList); } catch (Throwable t) { LOG.error("sink.addOrUpdateUserGroups failed with exception: " + t.getMessage() + ", for user: " + transformUserName + " and groups: " + groupList); } counter++; if (counter <= 2000) { if (LOG.isInfoEnabled()) { LOG.info("Updating user count: " + counter + ", userName: " + userName + ", groupList: " + groupList); } if (counter == 2000) { LOG.info( "===> 2000 user records have been synchronized so far. From now on, only a summary progress log will be written for every 100 users. To continue to see detailed log for every user, please enable Trace level logging. <==="); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Updating user count: " + counter + ", userName: " + userName + ", groupList: " + groupList); } else { if (counter % 100 == 0) { LOG.info("Synced " + counter + " users till now"); } } } } else { // If the user from the search result is present in the group user table, // then addorupdate user to ranger admin. LOG.debug("Chekcing if the user " + userFullName + " is part of the retrieved groups"); if (groupUserTable.containsColumn(userFullName) || groupUserTable.containsColumn(userName)) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } userNameMap.put(userFullName, transformUserName); //Also update the username in the groupUserTable with the one from username attribute. Map<String, String> userMap = groupUserTable.column(userFullName); for (Map.Entry<String, String> entry : userMap.entrySet()) { LOG.debug("Updating groupUserTable " + entry.getValue() + " with: " + transformUserName + " for " + entry.getKey()); groupUserTable.put(entry.getKey(), userFullName, transformUserName); } } } } // Examine the paged results control response Control[] controls = ldapContext.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) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { LOG.debug(String.format("Fetched paged results round: %s", ++paged)); ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.getUsers() completed with user count: " + counter); } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.getUsers() failed with exception: " + t); LOG.info("LdapDeltaUserGroupBuilder.getUsers() user count: " + counter); } } if (deltaSyncUserTime < highestdeltaSyncUserTime) { // Incrementing highestdeltaSyncUserTime (for AD) in order to avoid search record repetition for next sync cycle. deltaSyncUserTime = highestdeltaSyncUserTime + 1; // Incrementing the highest timestamp value (for Openldap) with 1sec in order to avoid search record repetition for next sync cycle. deltaSyncUserTimeStamp = dateFormat.format(new Date(highestdeltaSyncUserTime + 60l)); } } finally { if (userSearchResultEnum != null) { userSearchResultEnum.close(); } if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private XmlBuilder searchResultsToXml(NamingEnumeration entries) throws NamingException { XmlBuilder entriesElem = new XmlBuilder("entries"); int row = 0;//w w w . j a v a 2 s . co m while ((getMaxEntriesReturned() == 0 || row < getMaxEntriesReturned()) && entries.hasMore()) { SearchResult searchResult = (SearchResult) entries.next(); XmlBuilder entryElem = new XmlBuilder("entry"); entryElem.addAttribute("name", searchResult.getName()); entryElem.addSubElement(attributesToXml(searchResult.getAttributes())); entriesElem.addSubElement(entryElem); row++; } return entriesElem; }
From source file:org.cggh.repo.security.sync.ldap.LDAPUserRegistry.java
public Collection<String> getGroupNames() { final List<String> groupNames = new LinkedList<String>(); processQuery(new AbstractSearchCallback() { protected void doProcess(SearchResult result) throws NamingException, ParseException { Attribute nameAttribute = result.getAttributes().get(LDAPUserRegistry.this.groupIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params); } else { LDAPUserRegistry.logger.warn("Missing GID1 on " + result.getNameInNamespace()); }/*from w w w . j a v a 2 s . c o m*/ } else { String authority = "GROUP_" + (String) nameAttribute.get(); if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Group DN recognized: " + authority); } groupNames.add(authority); } } public void close() throws NamingException { } }, this.groupSearchBase, this.groupQuery, new String[] { this.groupIdAttributeName }); return groupNames; }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public Collection<String> getPersonNames() { final List<String> personNames = new LinkedList<String>(); processQuery(new AbstractSearchCallback() { protected void doProcess(SearchResult result) throws NamingException, ParseException { Attribute nameAttribute = result.getAttributes().get(LDAPUserRegistry.this.userIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingUID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.userIdAttributeName }; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.user.id.missing", params); } else { LDAPUserRegistry.logger .warn("User missing user id attribute DN =" + result.getNameInNamespace() + " att = " + LDAPUserRegistry.this.userIdAttributeName); }//from ww w .java 2 s . c om } else { if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Person DN recognized: " + nameAttribute.get()); } personNames.add((String) nameAttribute.get()); } } public void close() throws NamingException { } }, this.userSearchBase, this.personQuery, new String[] { this.userIdAttributeName }); return personNames; }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public Collection<String> getGroupNames() { final List<String> groupNames = new LinkedList<String>(); processQuery(new AbstractSearchCallback() { protected void doProcess(SearchResult result) throws NamingException, ParseException { Attribute nameAttribute = result.getAttributes().get(LDAPUserRegistry.this.groupIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params); } else { LDAPUserRegistry.logger.warn("Missing GID on " + result.getNameInNamespace()); }/* w ww . jav a 2 s . c om*/ } else { String authority = "GROUP_" + (String) nameAttribute.get(); if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Group DN recognized: " + authority); } groupNames.add(authority); } } public void close() throws NamingException { } }, this.groupSearchBase, this.groupQuery, new String[] { this.groupIdAttributeName }); return groupNames; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults, SearchResult result) throws NamingException { NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace()); Attributes ldapAttributes = result.getAttributes(); // Parse the timestamp Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName); if (modifyTimestamp != null) { try {// w ww .j a va2 s . com nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString())); } catch (ParseException e) { throw new AlfrescoRuntimeException("Failed to parse timestamp.", e); } } // Apply the mapped attributes PropertyMap properties = nodeDescription.getProperties(); for (String key : attributeMapping.keySet()) { QName keyQName = QName.createQName(key, this.namespaceService); // cater for null String attributeName = attributeMapping.get(key); if (attributeName != null) { Attribute attribute = ldapAttributes.get(attributeName); if (attribute != null) { String value = (String) attribute.get(0); if (value != null) { properties.put(keyQName, value); } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } return nodeDescription; }
From source file:org.cggh.repo.security.sync.ldap.LDAPUserRegistry.java
protected NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults, SearchResult result) throws NamingException { NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace()); Attributes ldapAttributes = result.getAttributes(); // Parse the timestamp Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName); if (modifyTimestamp != null) { try {/*ww w . ja va 2s .c o m*/ nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString())); } catch (ParseException e) { throw new AlfrescoRuntimeException("Failed to parse timestamp.", e); } } // Apply the mapped attributes PropertyMap properties = nodeDescription.getProperties(); for (String key : attributeMapping.keySet()) { QName keyQName = QName.createQName(key, this.namespaceService); // cater for null String attributeName = attributeMapping.get(key); if (attributeName != null) { Attribute attribute = ldapAttributes.get(attributeName); if (attribute != null) { String value = (String) attribute.get(0); if (value != null) { properties.put(keyQName, value); } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } else { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } return nodeDescription; }
From source file:edu.vt.middleware.ldap.dsml.Dsmlv1.java
/** * This will take a DSML <code>Element</code> containing an entry of type * <dsml:entry name="name"/> and convert it to a LDAP search result. * * @param entryElement <code>Element</code> of DSML content * * @return <code>SearchResult</code> *//*from ww w . j a v a 2 s. c o m*/ protected SearchResult createSearchResult(final Element entryElement) { String name = ""; final Attributes entryAttributes = new BasicAttributes(true); SearchResult attrResults = null; if (entryElement != null) { name = entryElement.attributeValue("dn"); if (name == null) { name = ""; } if (entryElement.hasContent()) { final Iterator<?> ocIterator = entryElement.elementIterator("objectclass"); while (ocIterator.hasNext()) { final Element ocElement = (Element) ocIterator.next(); if (ocElement != null && ocElement.hasContent()) { final String ocName = "objectClass"; final Attribute entryAttribute = new BasicAttribute(ocName); final Iterator<?> valueIterator = ocElement.elementIterator("oc-value"); while (valueIterator.hasNext()) { final Element valueElement = (Element) valueIterator.next(); if (valueElement != null) { final String value = valueElement.getText(); if (value != null) { entryAttribute.add(value); } } } entryAttributes.put(entryAttribute); } } attrResults = super.createSearchResult(entryElement); } } if (attrResults != null) { final Attributes attrs = attrResults.getAttributes(); if (attrs != null) { final NamingEnumeration<? extends Attribute> ae = attrs.getAll(); if (ae != null) { try { while (ae.hasMore()) { entryAttributes.put(ae.next()); } } catch (NamingException e) { if (LOG.isDebugEnabled()) { LOG.debug("Could not read attribute in SearchResult from parent"); } } } } } return new SearchResult(name, null, entryAttributes); }