List of usage examples for javax.naming.directory Attribute get
Object get() throws NamingException;
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Retrieve the elements referenced by the filter/BaseDN/Scope request. * * @param attributes Attributes of the referencer element * @param directoryDn Dn of the Directory * @param linkDn Dn specified in the parent * @param filter Filter expression specified in the parent * @param scope scope for the search/*from w ww .j av a 2 s .c o m*/ * @return The list of the referenced elements. * @throws DirectoryException * @throws NamingException */ private Set<String> getReferencedElements(Attributes attributes, String directoryDn, String linkDn, String filter, int scope) throws DirectoryException, NamingException { Set<String> targetIds = new TreeSet<>(); LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor(); LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); // use the most specific scope between the one specified in the // Directory and the specified in the Parent String dn = directoryDn.endsWith(linkDn) && directoryDn.length() > linkDn.length() ? directoryDn : linkDn; // combine the ldapUrl search query with target // directory own constraints SearchControls scts = new SearchControls(); // use the most specific scope scts.setSearchScope(Math.min(scope, targetDirconfig.getSearchScope())); // only fetch the ids of the targets scts.setReturningAttributes(new String[] { targetSession.idAttribute }); // combine the filter of the target directory with the // provided filter if any String targetFilter = targetDirconfig.getSearchFilter(); if (filter == null || filter.length() == 0) { filter = targetFilter; } else if (targetFilter != null && targetFilter.length() > 0) { filter = String.format("(&(%s)(%s))", targetFilter, filter); } // perform the request and collect the ids if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getLdapTargetIds(%s): LDAP search dn='%s' " + " filter='%s' scope='%s' [%s]", attributes, dn, dn, scts.getSearchScope(), this)); } Name name = new CompositeName().add(dn); NamingEnumeration<SearchResult> results = targetSession.dirContext.search(name, filter, scts); try { while (results.hasMore()) { // NXP-2461: check that id field is filled Attribute attr = results.next().getAttributes().get(targetSession.idAttribute); if (attr != null) { String collectedId = attr.get().toString(); if (collectedId != null) { targetIds.add(collectedId); } } } } finally { results.close(); } return targetIds; }
From source file:com.funambol.LDAP.dao.impl.ContactDAO.java
/** * Compares two attribute sets/* w w w .ja v a 2 s. c o m*/ * * @param authoritativeSet * reference set * @param compareSet * comparative set * @return list of modifications to commit * @throws NamingException */ public Map<String, Attributes> compareAttributeSets(Attributes authoritativeSet, Attributes compareSet) throws NamingException { Map<String, Attributes> modifications = new HashMap<String, Attributes>(); Attributes delAttributes = new BasicAttributes(); Attributes addAttributes = new BasicAttributes(); Attributes replaceAttributes = new BasicAttributes(); // List<LDAPModification> modifications = new // ArrayList<LDAPModification>(); List<String> supportedAttrs = Arrays.asList(getSupportedAttributes()); Iterator<String> it = supportedAttrs.iterator(); // loop over supported attributes while (it.hasNext()) { String attribute = it.next(); // skip unmodifiable attrs if (attribute.equals("modifyTimestamp")) continue; Attribute authoritaveAttribute = authoritativeSet.get(attribute); Attribute compareAttribute = compareSet.get(attribute); if (authoritaveAttribute == null || compareAttribute == null) { // remove an old attribute if (authoritaveAttribute == null && compareAttribute != null) { delAttributes.put(compareAttribute); } // add a new attribute if (authoritaveAttribute != null && compareAttribute == null) { addAttributes.put(authoritaveAttribute); } } else { // replace an attribute String authValue = (String) authoritaveAttribute.get(); String compareValue = (String) compareAttribute.get(); if (!authValue.equals(compareValue)) { replaceAttributes.put(authoritaveAttribute); } } } modifications.put(DEL_ATTRIBUTE, delAttributes); modifications.put(REPLACE_ATTRIBUTE, replaceAttributes); modifications.put(ADD_ATTRIBUTE, addAttributes); return modifications; }
From source file:org.springframework.ldap.core.DirContextAdapter.java
public Object getObjectAttribute(String name) { Attribute oneAttr = originalAttrs.get(name); if (oneAttr == null || oneAttr.size() == 0) { // LDAP-215 return null; }/* ww w. j a v a 2s. co m*/ try { return oneAttr.get(); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } }
From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java
/** * /*from w w w . j a v a2s . c o m*/ * Creates list of all OLAT Users which have been deleted out of the LDAP * directory but still exits in OLAT * * Configuration: Required Attributes = ldapContext.xml (property=reqAttrs) * LDAP Base = ldapContext.xml (property=ldapBase) * * @param syncTime The time to search in LDAP for changes since this time. * SyncTime has to formatted: JJJJMMddHHmm * @param ctx The LDAP system connection, if NULL or closed NamingExecpiton is * thrown * * @return Returns list of Identity from the user which have been deleted in * LDAP * * @throws NamingException */ public List<Identity> getIdentitysDeletedInLdap(LdapContext ctx) { if (ctx == null) return null; // Find all LDAP Users String userID = syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); String userFilter = syncConfiguration.getLdapUserFilter(); final List<String> ldapList = new ArrayList<String>(); ldapDao.searchInLdap(new LDAPVisitor() { @Override public void visit(SearchResult result) throws NamingException { Attributes attrs = result.getAttributes(); NamingEnumeration<? extends Attribute> aEnum = attrs.getAll(); while (aEnum.hasMore()) { Attribute attr = aEnum.next(); // use lowercase username ldapList.add(attr.get().toString().toLowerCase()); } } }, (userFilter == null ? "" : userFilter), new String[] { userID }, ctx); if (ldapList.isEmpty()) { log.warn("No users in LDAP found, can't create deletionList!!", null); return null; } // Find all User in OLAT, members of LDAPSecurityGroup SecurityGroup ldapGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP); if (ldapGroup == null) { log.error("Error getting users from OLAT security group '" + LDAPConstants.SECURITY_GROUP_LDAP + "' : group does not exist", null); return null; } List<Identity> identityListToDelete = new ArrayList<Identity>(); List<Identity> olatListIdentity = securityManager.getIdentitiesOfSecurityGroup(ldapGroup); for (Identity ida : olatListIdentity) { // compare usernames with lowercase if (!ldapList.contains(ida.getName().toLowerCase())) { identityListToDelete.add(ida); } } return identityListToDelete; }
From source file:org.lsc.jndi.JndiServices.java
public Map<String, LscDatasets> doGetAttrsList(final String base, final String filter, final int scope, final List<String> attrsNames) throws NamingException { // sanity checks String searchBase = base == null ? "" : rewriteBase(base); String searchFilter = filter == null ? DEFAULT_FILTER : filter; Map<String, LscDatasets> res = new LinkedHashMap<String, LscDatasets>(); if (attrsNames == null || attrsNames.size() == 0) { LOGGER.error("No attribute names to read! Check configuration."); return res; }/* ww w.j a va 2 s . c o m*/ String[] attributes = new String[attrsNames.size()]; attributes = attrsNames.toArray(attributes); SearchControls constraints = new SearchControls(); constraints.setDerefLinkFlag(false); constraints.setReturningAttributes(attributes); constraints.setSearchScope(scope); constraints.setReturningObjFlag(true); try { boolean requestPagedResults = false; List<Control> extControls = new ArrayList<Control>(); if (pageSize > 0) { requestPagedResults = true; LOGGER.debug("Using pagedResults control for {} entries at a time", pageSize); } if (requestPagedResults) { extControls.add(new PagedResultsControl(pageSize, Control.CRITICAL)); } if (sortedBy != null) { extControls.add(new SortControl(sortedBy, Control.CRITICAL)); } if (extControls.size() > 0) { ctx.setRequestControls(extControls.toArray(new Control[extControls.size()])); } byte[] pagedResultsResponse = null; do { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, constraints); if (results != null) { Map<String, Object> attrsValues = null; while (results.hasMoreElements()) { attrsValues = new HashMap<String, Object>(); SearchResult ldapResult = (SearchResult) results.next(); // get the value for each attribute requested for (String attributeName : attrsNames) { Attribute attr = ldapResult.getAttributes().get(attributeName); if (attr != null && attr.get() != null) { attrsValues.put(attributeName, attr.get()); } } res.put(ldapResult.getNameInNamespace(), new LscDatasets(attrsValues)); } } Control[] respCtls = ctx.getResponseControls(); if (respCtls != null) { for (Control respCtl : respCtls) { if (requestPagedResults && respCtl instanceof PagedResultsResponseControl) { pagedResultsResponse = ((PagedResultsResponseControl) respCtl).getCookie(); } } } if (requestPagedResults && pagedResultsResponse != null) { ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, pagedResultsResponse, Control.CRITICAL) }); } } while (pagedResultsResponse != null); // clear requestControls for future use of the JNDI context if (requestPagedResults) { ctx.setRequestControls(null); } } catch (CommunicationException e) { // Avoid handling the communication exception as a generic one throw e; } catch (ServiceUnavailableException e) { // Avoid handling the service unavailable exception as a generic one throw e; } catch (NamingException e) { // clear requestControls for future use of the JNDI context ctx.setRequestControls(null); LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); } catch (IOException e) { // clear requestControls for future use of the JNDI context ctx.setRequestControls(null); LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); } return res; }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
private <T> T fromAttributesToEntity(Class<T> clazz, Attributes attributes) throws NamingException { try {// w w w . j av a 2s .c om Map.Entry<Object, SetterInterceptor> pair = EntityProxyFactory.getProxiedEntity(clazz); T entity = (T) pair.getKey(); EntityMetaData metaData = EntityMetaData.get(clazz); Set<String> multipleLdapAttrNames = new HashSet<String>(); for (EntityPropertyMetaData propMetaData : metaData) { if (propMetaData.isMultiple()) { multipleLdapAttrNames.add(propMetaData.getLdapPropName()); } } for (NamingEnumeration<? extends Attribute> attrs = attributes.getAll(); attrs.hasMore();) { Attribute attr = attrs.next(); EntityPropertyMetaData propMetaData = metaData.getProperty(attr.getID()); if (null == propMetaData) { // current attribute exist in LDAP but not defined in our // POJO. continue; } if (propMetaData.isId()) { propMetaData.setter().set(entity, attr.get()); if (entity instanceof Distinguishable) { ((Distinguishable) entity) .setDN(attr.getID() + "=" + attr.get().toString() + "," + metaData.context()); } } else { List<String> attrValues = new ArrayList<String>(); for (NamingEnumeration<?> all = attr.getAll(); all.hasMore();) { attrValues.add(propMetaData.getSyntaxer().ldapStringToJavaString(all.next().toString())); } if (!propMetaData.isReference()) { if (!propMetaData.isMultiple()) { propMetaData.setter().set(entity, attrValues.get(0)); } else { propMetaData.setter().set(entity, new MoniteredList<String>(attrValues)); multipleLdapAttrNames.remove(propMetaData.getLdapPropName()); } } else { final Class<?> referenceType = propMetaData.getValueClass(); if (!propMetaData.isMultiple()) { propMetaData.setter().set(entity, EntityProxyFactory.getLazyLoadingProxiedEntity(this, referenceType, attrValues.get(0))); } else { List references = new ArrayList(); for (String dn : attrValues) { references.add( EntityProxyFactory.getLazyLoadingProxiedEntity(this, referenceType, dn)); } propMetaData.setter().set(entity, new MoniteredList(references)); multipleLdapAttrNames.remove(propMetaData.getLdapPropName()); } } } /* * The rest attribute names in multipleLdapAttrNames are those * not presented in LDAP side. In order to track what changes * occurred to these attributes, we need to use MoniteredList. */ for (String notPresentedMultipleLdapAttrName : multipleLdapAttrNames) { metaData.getProperty(notPresentedMultipleLdapAttrName).setter().set(entity, new MoniteredList()); } } /* * Once all the properties have been initialized, we should turn on * the switch of SetterInterceptor to monitor changes. */ pair.getValue().turnOn(); return entity; } catch (NamingException e) { LogUtils.debug(LOG, "failed to go through attributes when fromAttributesToEntity"); throw e; } }
From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java
/** * Map ldap attributes to jahia properties * * @param attributes// www . j av a 2 s. c o m * @param isUser * @return */ private Properties attributesToJahiaProperties(Attributes attributes, boolean isUser) { Properties props = new Properties(); Map<String, String> attributesMapper = isUser ? userConfig.getAttributesMapper() : groupConfig.getAttributesMapper(); for (String propertyKey : attributesMapper.keySet()) { Attribute ldapAttribute = attributes.get(attributesMapper.get(propertyKey)); try { if (ldapAttribute != null && ldapAttribute.get() instanceof String) { props.put(propertyKey, ldapAttribute.get()); } } catch (NamingException e) { logger.error("Error reading LDAP attribute:" + ldapAttribute.toString()); } } return props; }
From source file:org.springframework.ldap.core.DirContextAdapter.java
/** * @see java.lang.Object#toString()//from www . j av a2 s . c o m */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getClass().getName()); buf.append(":"); if (dn != null) { buf.append(" dn=" + dn); } buf.append(" {"); try { for (NamingEnumeration i = originalAttrs.getAll(); i.hasMore();) { Attribute attribute = (Attribute) i.next(); if (attribute.size() == 1) { buf.append(attribute.getID()); buf.append('='); buf.append(attribute.get()); } else { for (int j = 0; j < attribute.size(); j++) { if (j > 0) { buf.append(", "); } buf.append(attribute.getID()); buf.append('['); buf.append(j); buf.append("]="); buf.append(attribute.get(j)); } } if (i.hasMore()) { buf.append(", "); } } } catch (NamingException e) { log.warn("Error in toString()"); } buf.append('}'); return buf.toString(); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Fetch both statically and dynamically defined references and merge the results. * * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String) */// w ww .ja v a2 s . c o m @Override public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException { // container to hold merged references Set<String> sourceIds = new TreeSet<>(); SearchResult targetLdapEntry = null; String targetDn = null; // step #1: resolve static references String staticAttributeId = getStaticAttributeId(); if (staticAttributeId != null) { // step #1.1: fetch the dn of the targetId entry in the target // directory by the static dn valued strategy LDAPDirectory targetDir = getTargetLDAPDirectory(); if (staticAttributeIdIsDn) { try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) { targetLdapEntry = targetSession.getLdapEntry(targetId, false); if (targetLdapEntry == null) { String msg = String.format( "Failed to perform inverse lookup on LDAPReference" + " resolving field '%s' of '%s' to entries of '%s'" + " using the static content of attribute '%s':" + " entry '%s' cannot be found in '%s'", fieldName, sourceDirectory, targetDirectoryName, staticAttributeId, targetId, targetDirectoryName); throw new DirectoryEntryNotFoundException(msg); } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException( "error fetching " + targetId + " from " + targetDirectoryName + ": " + e.getMessage(), e); } } // step #1.2: search for entries that reference that dn in the // source directory and collect their ids LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); String filterExpr = String.format("(&(%s={0})%s)", staticAttributeId, ldapSourceDirectory.getBaseFilter()); String[] filterArgs = new String[1]; if (staticAttributeIdIsDn) { filterArgs[0] = targetDn; } else { filterArgs[0] = targetId; } String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn(); SearchControls sctls = ldapSourceDirectory.getSearchControls(); 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, searchBaseDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, 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()); } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + filterArgs[0], e); } } // step #2: resolve dynamic references String dynamicAttributeId = this.dynamicAttributeId; if (dynamicAttributeId != null) { LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory(); String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn(); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { // step #2.1: fetch the target entry to apply the ldap url // filters of the candidate sources on it if (targetLdapEntry == null) { // only fetch the entry if not already fetched by the // static // attributes references resolution targetLdapEntry = targetSession.getLdapEntry(targetId, false); } if (targetLdapEntry == null) { String msg = String.format( "Failed to perform inverse lookup on LDAPReference" + " resolving field '%s' of '%s' to entries of '%s'" + " using the dynamic content of attribute '%s':" + " entry '%s' cannot be found in '%s'", fieldName, ldapSourceDirectory, targetDirectoryName, dynamicAttributeId, targetId, targetDirectoryName); throw new DirectoryException(msg); } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); Attributes targetAttributes = targetLdapEntry.getAttributes(); // step #2.2: find the list of entries that hold candidate // dynamic links in the source directory SearchControls sctls = ldapSourceDirectory.getSearchControls(); sctls.setReturningAttributes(new String[] { sourceSession.idAttribute, dynamicAttributeId }); String filterExpr = String.format("%s=*", dynamicAttributeId); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' scope='%s' [%s]", targetId, searchBaseDn, filterExpr, sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr, sctls); try { while (results.hasMore()) { // step #2.3: for each sourceId and each ldapUrl test // whether the current target entry matches the // collected // URL Attributes sourceAttributes = results.next().getAttributes(); NamingEnumeration<?> ldapUrls = sourceAttributes.get(dynamicAttributeId).getAll(); try { while (ldapUrls.hasMore()) { LdapURL ldapUrl = new LdapURL(ldapUrls.next().toString()); String candidateDN = pseudoNormalizeDn(ldapUrl.getDN()); // check base URL if (!targetDn.endsWith(candidateDN)) { continue; } // check onelevel scope constraints if ("onelevel".equals(ldapUrl.getScope())) { int targetDnSize = new LdapName(targetDn).size(); int urlDnSize = new LdapName(candidateDN).size(); if (targetDnSize - urlDnSize > 1) { // target is not a direct child of the // DN of the // LDAP URL continue; } } // check that the target entry matches the // filter if (getFilterMatcher().match(targetAttributes, ldapUrl.getFilter())) { // the target match the source url, add it // to the // collected ids sourceIds.add(sourceAttributes.get(sourceSession.idAttribute).get().toString()); } } } finally { ldapUrls.close(); } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + targetId, e); } } /* * This kind of reference is not supported because Active Directory use filter expression not yet supported by * LDAPFilterMatcher. See NXP-4562 */ if (dynamicReferences != null && dynamicReferences.length > 0) { log.error("This kind of reference is not supported."); } return new ArrayList<>(sourceIds); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@SuppressWarnings("unchecked") protected Object getFieldValue(Attribute attribute, String fieldName, String entryId, boolean fetchReferences) throws DirectoryException { Field field = schemaFieldMap.get(fieldName); Type type = field.getType();//from w ww .j av a 2s. c om Object defaultValue = field.getDefaultValue(); String typeName = type.getName(); if (attribute == null) { return defaultValue; } Object value; try { value = attribute.get(); } catch (NamingException e) { throw new DirectoryException("Could not fetch value for " + attribute, e); } if (value == null) { return defaultValue; } String trimmedValue = value.toString().trim(); if ("string".equals(typeName)) { return trimmedValue; } else if ("integer".equals(typeName) || "long".equals(typeName)) { if ("".equals(trimmedValue)) { return defaultValue; } try { return Long.valueOf(trimmedValue); } catch (NumberFormatException e) { log.error(String.format( "field %s of type %s has non-numeric value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, trimmedValue)); return defaultValue; } } else if (type.isListType()) { List<String> parsedItems = new LinkedList<String>(); NamingEnumeration<Object> values = null; try { values = (NamingEnumeration<Object>) attribute.getAll(); while (values.hasMore()) { parsedItems.add(values.next().toString().trim()); } return parsedItems; } catch (NamingException e) { log.error(String.format( "field %s of type %s has non list value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, values != null ? values.toString() : trimmedValue)); return defaultValue; } finally { if (values != null) { try { values.close(); } catch (NamingException e) { log.error(e, e); } } } } else if ("date".equals(typeName)) { if ("".equals(trimmedValue)) { return defaultValue; } try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'"); dateFormat.setTimeZone(new SimpleTimeZone(0, "Z")); Date date = dateFormat.parse(trimmedValue); Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; } catch (ParseException e) { log.error(String.format( "field %s of type %s has invalid value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, trimmedValue)); return defaultValue; } } else if ("content".equals(typeName)) { return Blobs.createBlob((byte[]) value); } else { throw new DirectoryException("Field type not supported in directories: " + typeName); } }