List of usage examples for javax.naming.directory SearchResult getNameInNamespace
public String getNameInNamespace()
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 {//from w w w . j a va2 s .c om 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.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Remove existing statically defined links for the given source id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForSource(String) *//*w w w .j a v a 2s .c om*/ @Override public void removeLinksForSource(String sourceId) throws DirectoryException { LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { if (sourceSession.isReadOnly() || attributeId == null) { // do not try to do anything on a read only server or to a // purely dynamic reference return; } // get the dn of the entry that matches sourceId SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId); if (sourceLdapEntry == null) { throw new DirectoryException( String.format("cannot edit the links hold by missing entry '%s' in directory '%s'", sourceId, ldapSourceDirectory.getName())); } String sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace()); Attribute oldAttr = sourceLdapEntry.getAttributes().get(attributeId); if (oldAttr == null) { // consider it as an empty attribute to simplify the following // code oldAttr = new BasicAttribute(attributeId); } Attribute attrToRemove = new BasicAttribute(attributeId); NamingEnumeration<?> oldAttrs = oldAttr.getAll(); String targetBaseDn = pseudoNormalizeDn(ldapTargetDirectory.getDescriptor().getSearchBaseDn()); try { while (oldAttrs.hasMore()) { String targetKeyAttr = oldAttrs.next().toString(); if (staticAttributeIdIsDn) { String dn = pseudoNormalizeDn(targetKeyAttr); if (forceDnConsistencyCheck) { String id = getIdForDn(targetSession, dn); if (id != null && targetSession.hasEntry(id)) { // this is an entry managed by the current // reference attrToRemove.add(dn); } } else if (dn.endsWith(targetBaseDn)) { // this is an entry managed by the current // reference attrToRemove.add(dn); } } else { attrToRemove.add(targetKeyAttr); } } } finally { oldAttrs.close(); } try { if (attrToRemove.size() == oldAttr.size()) { // use the empty ref marker to avoid empty attr String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes key='%s' " + " mod_op='REPLACE_ATTRIBUTE' attrs='%s' [%s]", sourceId, sourceDn, emptyAttribute, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REPLACE_ATTRIBUTE, emptyAttribute); } else if (attrToRemove.size() > 0) { // remove the attribute managed by the current reference Attributes attrsToRemove = new BasicAttributes(); attrsToRemove.put(attrToRemove); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes dn='%s' " + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", sourceId, sourceDn, attrsToRemove, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, attrsToRemove); } } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static part log.warn(String.format("cannot remove dynamic reference in field %s for source %s", getFieldName(), sourceId)); } else { // this is a real schma configuration problem, wrapup the // exception throw new DirectoryException(e); } } } catch (NamingException e) { throw new DirectoryException("removeLinksForSource failed: " + e.getMessage(), e); } }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.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 {//from ww w . j a va 2s . 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); String defaultAttribute = attributeDefaults.get(key); if (attribute != null) { String value = (String) attribute.get(0); if (value != null) { properties.put(keyQName, value); } } 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 { String defaultValue = attributeDefaults.get(key); if (defaultValue != null) { properties.put(keyQName, defaultValue); } } } return nodeDescription; }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java
protected void importFromLDAPByGroup(LDAPImportContext ldapImportContext) throws Exception { byte[] cookie = new byte[0]; while (cookie != null) { List<SearchResult> searchResults = new ArrayList<>(); Properties groupMappings = ldapImportContext.getGroupMappings(); String groupMappingsGroupName = GetterUtil.getString(groupMappings.getProperty("groupName")); groupMappingsGroupName = StringUtil.toLowerCase(groupMappingsGroupName); cookie = _portalLDAP.getGroups(ldapImportContext.getLdapServerId(), ldapImportContext.getCompanyId(), ldapImportContext.getLdapContext(), cookie, 0, new String[] { groupMappingsGroupName }, searchResults);//from w w w . ja v a2 s . c o m for (SearchResult searchResult : searchResults) { try { Attributes groupAttributes = _portalLDAP.getGroupAttributes(ldapImportContext.getLdapServerId(), ldapImportContext.getCompanyId(), ldapImportContext.getLdapContext(), searchResult.getNameInNamespace(), true); UserGroup userGroup = importUserGroup(ldapImportContext.getCompanyId(), groupAttributes, groupMappings); Attribute usersAttribute = getUsers(ldapImportContext, groupAttributes, userGroup); if (usersAttribute == null) { if (_log.isInfoEnabled()) { _log.info("No users found in " + userGroup.getName()); } continue; } importUsers(ldapImportContext, userGroup.getUserGroupId(), usersAttribute); } catch (Exception e) { _log.error("Unable to import group " + searchResult, e); } } } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Store new links using the LDAP staticAttributeId strategy. * * @see org.nuxeo.ecm.directory.Reference#addLinks(List, String) *///from w w w . j ava 2 s . c om @Override public void addLinks(List<String> sourceIds, String targetId) throws DirectoryException { String attributeId = getStaticAttributeId(); if (attributeId == null && !sourceIds.isEmpty()) { log.warn("trying to edit a non-static reference: ignoring"); return; } LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (!sourceSession.isReadOnly()) { // compute the target dn to add to all the matching source // entries SearchResult ldapEntry = targetSession.getLdapEntry(targetId); if (ldapEntry == null) { throw new DirectoryException( String.format("could not add links to unexisting %s in directory %s", targetId, ldapTargetDirectory.getName())); } String targetAttributeValue; if (staticAttributeIdIsDn) { targetAttributeValue = ldapEntry.getNameInNamespace(); } else { targetAttributeValue = targetId; } for (String sourceId : sourceIds) { // fetch the entry to be able to run the security policy // implemented in an entry adaptor DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false); if (sourceEntry == null) { log.warn(String.format( "entry %s in directory %s not found: could not add link to %s in directory %s", sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName())); continue; } if (BaseSession.isReadOnlyEntry(sourceEntry)) { // skip this entry since it cannot be edited to add the // reference to targetId log.warn(String.format( "entry %s in directory %s is readonly: could not add link to %s in directory %s", sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName())); continue; } ldapEntry = sourceSession.getLdapEntry(sourceId); String sourceDn = ldapEntry.getNameInNamespace(); Attribute storedAttr = ldapEntry.getAttributes().get(attributeId); if (storedAttr.contains(targetAttributeValue)) { // no need to readd continue; } try { // add the new dn Attributes attrs = new BasicAttributes(attributeId, targetAttributeValue); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.addLinks([%s], %s): LDAP modifyAttributes dn='%s'" + " mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]", StringUtils.join(sourceIds, ", "), targetId, sourceDn, attrs, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrs); // robustly clean any existing empty marker now that we // are sure that the list in not empty if (storedAttr.contains(emptyRefMarker)) { Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.addLinks(%s, %s): LDAP modifyAttributes dn='%s'" + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", StringUtils.join(sourceIds, ", "), targetId, sourceDn, cleanAttrs.toString(), this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, cleanAttrs); } } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static part log.warn(String.format("cannot add dynamic reference in field %s for target %s", getFieldName(), targetId)); } else { // this is a real schema configuration problem, // wrap the exception throw new DirectoryException(e); } } } } } catch (NamingException e) { throw new DirectoryException("addLinks failed: " + e.getMessage(), e); } }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void goUpGroupHierarchyLdap(Set<String> groupDNs, int groupHierarchyLevels) throws Throwable { if (groupHierarchyLevels <= 0 || groupDNs.isEmpty()) { return;/* www .ja va2 s . c o m*/ } Set<String> nextLevelGroups = new HashSet<String>(); NamingEnumeration<SearchResult> groupSearchResultEnum = null; try { createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } String groupFilter = "(&(objectclass=" + groupObjectClass + ")"; if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) { String customFilter = groupSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } groupFilter += customFilter + "(|"; } StringBuilder filter = new StringBuilder(); for (String groupDN : groupDNs) { filter.append("(").append(groupMemberAttributeName).append("=").append(groupDN).append(")"); } filter.append("))"); groupFilter += filter; LOG.info("extendedAllGroupsSearchFilter = " + groupFilter); for (int ou = 0; ou < groupSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { do { groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], groupFilter, groupSearchControls); while (groupSearchResultEnum.hasMore()) { final SearchResult groupEntry = groupSearchResultEnum.next(); if (groupEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("groupEntry null, skipping sync for the entry"); } continue; } counter++; Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute); if (groupNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(groupNameAttribute + " empty for entry " + groupEntry.getNameInNamespace() + ", skipping sync"); } continue; } nextLevelGroups.add(groupEntry.getNameInNamespace()); String gName = (String) groupNameAttr.get(); Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName); int userCount = 0; if (groupMemberAttr == null || groupMemberAttr.size() <= 0) { LOG.info("No members available for " + gName); continue; } NamingEnumeration<?> userEnum = groupMemberAttr.getAll(); while (userEnum.hasMore()) { String originalUserFullName = (String) userEnum.next(); if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) { continue; } userCount++; originalUserFullName = originalUserFullName.toLowerCase(); if (userNameMap.get(originalUserFullName) != null) { groupUserTable.put(gName, originalUserFullName, userNameMap.get(originalUserFullName)); } else { groupUserTable.put(gName, originalUserFullName, originalUserFullName); } groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName); } LOG.info("No. of members in the group " + gName + " = " + userCount); } // 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) { ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() completed with group count: " + counter); } catch (RuntimeException re) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with runtime exception: ", re); throw re; } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", t); LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() group count: " + counter); } } } catch (RuntimeException re) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", re); throw re; } finally { if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } goUpGroupHierarchyLdap(nextLevelGroups, groupHierarchyLevels - 1); }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
protected Organisation convertSearchResultToOrganization(final SearchResult sr) throws ExecutionException, NameNotFoundException { if (sr == null) { throw new ExecutionException("SearchResult sr == NULL", new NullPointerException()); }// w w w. j a va2 s . c o m Organisation vOrganisation = null; try { Attributes attributes = sr.getAttributes(); Attribute attr; String vStr; String vOrgName = ((attr = attributes.get(Constants.ldap_ddbOrg_Id)) != null ? String.valueOf(attr.get()) : null); String vName = sr.getName(); String vNameInNamespace = sr.getNameInNamespace(); // --- EntryDN String vEntryDN = ((attr = attributes.get(Constants.ldap_ddb_EntryDN)) != null ? String.valueOf(attr.get()) : ""); int idx; // -- Parent node detections: String vParent = null; //vParent = sr.getName(); //LOG.log(Level.INFO, "getNameInNamespace() = '" + sr.getNameInNamespace() + "'"); //LOG.log(Level.INFO, "getName() = '" + sr.getName() + "'"); // -- getNameInNamespace() = 'o=99900711,o=00008125,o=00050350,ou=Organizations,dc=de' // -- getName() = 'o=99900711,o=00008125,o=00050350' //sr.getName(): 'o=00000116', //sr.getNameInNamespace(): 'o=00000116,o=00050350,ou=Organizations,dc=de', //vOrgEntryDN: 'o=00000116,o=00050350,ou=Organizations,dc=de' vParent = sr.getNameInNamespace(); if ((idx = vParent.indexOf(",ou=")) >= 0) { vParent = vParent.substring(0, idx); } vParent = vParent.replaceAll(Constants.ldap_ddbOrg_Id + "=", ""); // -- 99900711,00008125,00050350' String[] vParents = vParent.split(","); if (vParents.length >= 2) { vParent = vParents[1]; } else { vParent = null; } LOG.log(Level.INFO, "convertLdapOrganizationToOrganisation: o: '" + vOrgName + "', vParent: '" + vParent + "', sr.getName(): '" + vName + "', sr.getNameInNamespace(): '" + vNameInNamespace + "', vOrgEntryDN: '" + vEntryDN + "', sr.isRelative(): '" + sr.isRelative() + "'"); /* * if ( (vOrgName != null)&&(!vOrgName.isEmpty()) ) { vOrganisation = new Organisation(vOrgName, * vDescription, vParent); */ if ((vEntryDN != null) && (!vEntryDN.isEmpty())) { vOrganisation = new Organisation(vEntryDN, (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null ? String.valueOf(attr.get()) : null); // Public-ID: (s.o.) // vOrganisation.setOrgPID( (attr = attributes.get(ddbOrg_PID)) != null ? String.valueOf(attr.get()) : // ""); // Parent (s.o.) vOrganisation.setOrgParent(vParent); // Kurzbeschreibung der Einrichtung vOrganisation.setDescription((attr = attributes.get(Constants.ldap_ddbOrg_Description)) != null ? String.valueOf(attr.get()) : null); // -- Rechtsform try { vOrganisation.setBusinessCategory( (attr = attributes.get(Constants.ldap_ddbOrg_BusinessCategory)) != null ? ConstEnumOrgSector.valueOf(String.valueOf(attr.get())) : null); } catch (IllegalArgumentException ex) { LOG.log(Level.WARNING, "Organisation-Sector-Error: {0}", ex.getMessage()); vOrganisation.setStatus(null); } // -- Sub-Sectors: if ((attr = attributes.get(Constants.ldap_ddbOrg_SubBusinessCategory)) != null) { ConstEnumOrgSubSector vSubSector; NamingEnumeration<?> allSubSectors = attr.getAll(); while (allSubSectors.hasMore()) { try { vSubSector = ConstEnumOrgSubSector.valueOf((String) allSubSectors.next()); vOrganisation.addSubSectors(vSubSector); } catch (IllegalArgumentException ex) { LOG.log(Level.WARNING, "Organisation-SubSector-Error: {0}", ex.getMessage()); } } } // -- Funding Agency vOrganisation.setFundingAgency((attr = attributes.get(Constants.ldap_ddbOrg_FundingAgency)) != null ? String.valueOf(attr.get()) : null); // Name der Einrichtung vOrganisation.setDisplayName((attr = attributes.get(Constants.ldap_ddbOrg_DisplayName)) != null ? String.valueOf(attr.get()) : ""); // E-Mail vOrganisation.setEmail( (attr = attributes.get(Constants.ldap_ddbOrg_Email)) != null ? String.valueOf(attr.get()) : null); // Telefonnummer vOrganisation.setTel((attr = attributes.get(Constants.ldap_ddbOrg_TelephoneNumber)) != null ? String.valueOf(attr.get()) : null); // -- FAX vOrganisation.setFax((attr = attributes.get(Constants.ldap_ddbOrg_FaxNumber)) != null ? String.valueOf(attr.get()) : null); // -- PLZ vOrganisation.getAddress() .setPostalCode((attr = attributes.get(Constants.ldap_ddbOrg_PostalCode)) != null ? String.valueOf(attr.get()) : ""); // -- City/Ortsname [l, localityName] if ((attr = attributes.get(Constants.ldap_ddbOrg_LocalityName)) != null) { vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get())); } else if ((attr = attributes.get("l")) != null) { vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get())); } // -- HouseIdentifier vOrganisation.getAddress() .setHouseIdentifier((attr = attributes.get(Constants.ldap_ddbOrg_HouseIdentifier)) != null ? String.valueOf(attr.get()) : ""); // -- Strasse vOrganisation.getAddress() .setStreet((attr = attributes.get(Constants.ldap_ddbOrg_Street)) != null ? String.valueOf(attr.get()) : ""); // -- Bundesland [stateOrProvinceName, st] if ((attr = attributes.get(Constants.ldap_ddbOrg_StateOrProvinceName)) != null) { vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get())); } else if ((attr = attributes.get("st")) != null) { vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get())); } // -- Land [countryName, c] if ((attr = attributes.get(Constants.ldap_ddbOrg_CountryName)) != null) { vOrganisation.getAddress().setCountryName(String.valueOf(attr.get())); } // -- AddressSuplement vOrganisation.getAddress() .setAddressSuplement((attr = attributes.get(Constants.ldap_ddbOrg_AddressSuplement)) != null ? String.valueOf(attr.get()) : ""); // -- Geokoordinaten try { vOrganisation.getAddress() .setLatitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLatitude)) != null ? Double.valueOf(String.valueOf(attr.get())) : 0.0); } catch (NumberFormatException ex) { LOG.log(Level.WARNING, "GeoLatitude-Error: {0}", ex.getMessage()); } try { vOrganisation.getAddress() .setLongitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLongitude)) != null ? Double.valueOf(String.valueOf(attr.get())) : 0.0); } catch (NumberFormatException ex) { LOG.log(Level.WARNING, "GeoLongitude-Error: {0}", ex.getMessage()); } vOrganisation.getAddress().setLocationDisplayName( (attr = attributes.get(Constants.ldap_ddbOrg_LocationDisplayName)) != null ? String.valueOf(attr.get()) : null); vOrganisation.setAbbreviation((attr = attributes.get(Constants.ldap_ddbOrg_Abbreviation)) != null ? String.valueOf(attr.get()) : null); vOrganisation.setLegalStatus((attr = attributes.get(Constants.ldap_ddbOrg_LegalStatus)) != null ? String.valueOf(attr.get()) : null); if ((attr = attributes.get(Constants.ldap_ddbOrg_URL)) != null) { NamingEnumeration<?> allURLs = attr.getAll(); while (allURLs.hasMore()) { vOrganisation.addURLs((String) allURLs.next()); } } vOrganisation.setLogo( (attr = attributes.get(Constants.ldap_ddbOrg_Logo)) != null ? String.valueOf(attr.get()) : null); // -- org-Status: //vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? String // .valueOf(attr.get()) : ""); try { vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? ConstEnumOrgStatus.valueOf(String.valueOf(attr.get())) : ConstEnumOrgStatus.pending); } catch (IllegalArgumentException ex) { LOG.log(Level.WARNING, "Organisation-Status-Error: {0}", ex.getMessage()); vOrganisation.setStatus(null); } vOrganisation.setCreatedBy((attr = attributes.get(Constants.ldap_ddb_CreatorsName)) != null ? String.valueOf(attr.get()) : ""); try { // createTimestamp-Error: For input string: "20120620142810Z" // 1340205676692 - 20120620152116Z - 2012-06-20-15-21-16Z // vOrganisation.setCreated( (attr = attributes.get(ddbOrg_CreateTimestamp)) != null ? // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1)); if ((attr = attributes.get(Constants.ldap_ddb_CreateTimestamp)) != null) { vStr = String.valueOf(attr.get()); vOrganisation.setCreated(convertLdapDateToLong(vStr)); } } catch (NumberFormatException ex) { LOG.log(Level.WARNING, "createTimestamp-Error: {0}", ex.getMessage()); } vOrganisation.setModifiedBy((attr = attributes.get(Constants.ldap_ddb_ModifiersName)) != null ? String.valueOf(attr.get()) : ""); try { // modifyTimestamp-Error: For input string: "20120620142810Z" // vOrganisation.setModified( (attr = attributes.get(ddbOrg_ModifyTimestamp)) != null ? // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1)); if ((attr = attributes.get(Constants.ldap_ddb_ModifyTimestamp)) != null) { vStr = String.valueOf(attr.get()); vOrganisation.setModified(convertLdapDateToLong(vStr)); } } catch (NumberFormatException ex) { LOG.log(Level.WARNING, "modifyTimestamp-Error: {0}", ex.getMessage()); } if ((attr = attributes.get(Constants.ldap_ddbOrg_Properties)) != null && attributes.get(Constants.ldap_ddbOrg_Properties).get() != null) { vOrganisation.setProperties(serializer.deserialize((String) attr.get())); } } else { throw new NameNotFoundException(); } } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, null, ex); throw new ExecutionException(ex.getMessage(), ex.getCause()); } catch (NameNotFoundException ex) { LOG.log(Level.SEVERE, null, ex); throw ex; } catch (NamingException ne) { LOG.log(Level.SEVERE, null, ne); throw new ExecutionException(ne.getMessage(), ne.getCause()); } return vOrganisation; }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void getGroups(UserGroupSink sink) throws Throwable { NamingEnumeration<SearchResult> groupSearchResultEnum = null; DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); long highestdeltaSyncGroupTime = deltaSyncGroupTime; try {//from ww w. j a v a 2 s . c o m createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")"; if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) { String customFilter = groupSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter; } extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>=" + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))"; LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter); for (int ou = 0; ou < groupSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { int paged = 0; do { groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], extendedAllGroupsSearchFilter, groupSearchControls); while (groupSearchResultEnum.hasMore()) { final SearchResult groupEntry = groupSearchResultEnum.next(); if (groupEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("groupEntry null, skipping sync for the entry"); } continue; } counter++; Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute); if (groupNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(groupNameAttribute + " empty for entry " + groupEntry.getNameInNamespace() + ", skipping sync"); } continue; } String gName = (String) groupNameAttr.get(); String transformGroupName = groupNameTransform(gName); // If group based search is enabled, then // update the group name to ranger admin // check for group members and populate userInfo object with user's full name and group mapping if (groupSearchFirstEnabled) { LOG.debug("Update Ranger admin with " + transformGroupName); sink.addOrUpdateGroup(transformGroupName); } Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged"); if (timeStampAttr != null) { String uSNChangedVal = (String) timeStampAttr.get(); long currentDeltaSyncTime = Long.parseLong(uSNChangedVal); if (currentDeltaSyncTime > highestdeltaSyncGroupTime) { highestdeltaSyncGroupTime = currentDeltaSyncTime; } } else { timeStampAttr = groupEntry.getAttributes().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 > highestdeltaSyncGroupTime) { highestdeltaSyncGroupTime = currentDeltaSyncTime; deltaSyncGroupTimeStamp = timeStampVal; } } } Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName); int userCount = 0; if (groupMemberAttr == null || groupMemberAttr.size() <= 0) { LOG.info("No members available for " + gName); continue; } NamingEnumeration<?> userEnum = groupMemberAttr.getAll(); while (userEnum.hasMore()) { String originalUserFullName = (String) userEnum.next(); if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) { continue; } userCount++; String userName = getShortUserName(originalUserFullName); originalUserFullName = originalUserFullName.toLowerCase(); if (groupSearchFirstEnabled && !userSearchEnabled) { 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(originalUserFullName, transformUserName); } //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName); if (userNameMap.get(originalUserFullName) != null) { groupUserTable.put(gName, originalUserFullName, userNameMap.get(originalUserFullName)); } else { groupUserTable.put(gName, originalUserFullName, originalUserFullName); } groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName); } LOG.info("No. of members in the group " + gName + " = " + userCount); } // 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.getGroups() completed with group count: " + counter); } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t); LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter); } } } finally { if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } if (groupHierarchyLevels > 0) { LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime); if (deltaSyncGroupTime > 0) { LOG.info( "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync"); goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1); } } if (deltaSyncGroupTime < highestdeltaSyncGroupTime) { // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle. deltaSyncGroupTime = highestdeltaSyncGroupTime + 1; // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle. deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l)); } }
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 {/* w ww . j ava 2s.c om*/ 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:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java
@Override public User importUserByScreenName(long companyId, String screenName) throws Exception { long ldapServerId = _portalLDAP.getLdapServerId(companyId, screenName, StringPool.BLANK); SearchResult result = (SearchResult) _portalLDAP.getUser(ldapServerId, companyId, screenName, StringPool.BLANK);/*from ww w.j a va 2 s .c o m*/ if (result == null) { if (_log.isWarnEnabled()) { _log.warn("No user was found in LDAP with screenName " + screenName); } return null; } LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId); String fullUserDN = result.getNameInNamespace(); Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN); User user = importUser(ldapServerId, companyId, ldapContext, attributes, null); ldapContext.close(); return user; }