List of usage examples for javax.naming.directory BasicAttribute BasicAttribute
public BasicAttribute(String id)
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "user.mod", required = { "userId" }) @RequiresAuthentication/* w w w . jav a2 s. c om*/ @SecuredMethod(constraints = "administrator.by_domain") public HashMap<String, Object> modifyUser(OperationContext opContext) throws NamingException { String userId = (String) opContext.getParams().get("userId"); UserDn userDn = nameHelper.newUserDnFromId(userId); DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain()); DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal(); HashMap<String, Object> response = new HashMap<String, Object>(); DirContextAdapter dca = (DirContextAdapter) userDirContext.lookup(userDn); HashMap<String, Object> modValues = displayAttributeHelper .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("mod")); HashMap<String, Object> addValues = displayAttributeHelper .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("add")); HashMap<String, Object> removeValues = displayAttributeHelper .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("remove")); List<String> removeAttrs = (List<String>) opContext.getParams().get("removeAttr"); IntegrityCheckUtil integrityCheckUtil = new IntegrityCheckUtil(userDirContext); HashMap<String, String> busyValues = new HashMap<String, String>(); LinkedList<ModificationItem> removeAttrList = new LinkedList<ModificationItem>(); if (removeAttrs != null) { for (String apiName : removeAttrs) { BasicAttribute attr = new BasicAttribute(displayAttributeHelper.getLdapName(apiName)); ModificationItem mi = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attr); removeAttrList.add(mi); } } for (Entry<String, Object> entry : modValues.entrySet()) { if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) { if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), entry.getValue().toString())) { busyValues.put(entry.getKey(), entry.getValue().toString()); } } dca.setAttributeValue(entry.getKey(), entry.getValue().toString()); } for (Entry<String, Object> entry : removeValues.entrySet()) { if (entry.getValue() instanceof List) { for (Object value : (List) entry.getValue()) { dca.removeAttributeValue(entry.getKey(), value); } } else { dca.removeAttributeValue(entry.getKey(), entry.getValue()); } } for (Entry<String, Object> entry : addValues.entrySet()) { if (entry.getValue() instanceof List) { for (Object value : (List) entry.getValue()) { if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) { if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), (String) value)) { busyValues.put(entry.getKey(), (String) value); } } dca.addAttributeValue(entry.getKey(), value); } } else { if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) { if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), (String) entry.getValue())) { busyValues.put(entry.getKey(), (String) entry.getValue()); } } dca.addAttributeValue(entry.getKey(), entry.getValue()); } } if (busyValues.size() > 0) { response.put("success", false); response.put("busyValues", busyValues); } else { userDirContext.modifyAttributes(userDn, removeAttrList.toArray(new ModificationItem[0])); userDirContext.modifyAttributes(userDn, dca.getModificationItems()); response.put("success", true); } return response; }
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(String, List) *//* ww w. j a v a 2 s .c om*/ @Override public void addLinks(String sourceId, List<String> targetIds) throws DirectoryException { if (targetIds.isEmpty()) { // optim: nothing to do, return silently without further creating // session instances return; } LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); if (attributeId == null) { if (log.isTraceEnabled()) { log.trace(String.format("trying to edit a non-static reference from %s in directory %s: ignoring", sourceId, ldapSourceDirectory.getName())); } return; } try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { // 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) { throw new DirectoryException(String.format("could not add links from unexisting %s in directory %s", sourceId, ldapSourceDirectory.getName())); } if (!BaseSession.isReadOnlyEntry(sourceEntry)) { SearchResult ldapEntry = sourceSession.getLdapEntry(sourceId); String sourceDn = ldapEntry.getNameInNamespace(); Attribute storedAttr = ldapEntry.getAttributes().get(attributeId); String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attribute attrToAdd = new BasicAttribute(attributeId); for (String targetId : targetIds) { if (staticAttributeIdIsDn) { // TODO optim: avoid LDAP search request when targetDn // can be forged client side (rdnAttribute = idAttribute and scope is onelevel) ldapEntry = targetSession.getLdapEntry(targetId); if (ldapEntry == null) { log.warn(String.format( "entry '%s' in directory '%s' not found: could not add link from '%s' in directory '%s' for '%s'", targetId, ldapTargetDirectory.getName(), sourceId, ldapSourceDirectory.getName(), this)); continue; } String dn = ldapEntry.getNameInNamespace(); if (storedAttr == null || !storedAttr.contains(dn)) { attrToAdd.add(dn); } } else { if (storedAttr == null || !storedAttr.contains(targetId)) { attrToAdd.add(targetId); } } } if (attrToAdd.size() > 0) { try { // do the LDAP request to store missing dns Attributes attrsToAdd = new BasicAttributes(); attrsToAdd.put(attrToAdd); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s' " + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]", sourceId, StringUtils.join(targetIds, ", "), sourceDn, attrsToAdd, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrsToAdd); // 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]", sourceId, StringUtils.join(targetIds, ", "), sourceDn, cleanAttrs, 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 update dynamic reference in field %s for source %s", getFieldName(), sourceId)); } else { // this is a real schema configuration problem, // wrap up the exception throw new DirectoryException(e); } } } } } catch (NamingException e) { throw new DirectoryException("addLinks failed: " + e.getMessage(), e); } }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
private void constructBasicAttributes(BasicAttributes basicAttributes, String id, String principleName, Object credential, String commonName, String surName) throws DirectoryServerManagerException { // set the objectClass type for schema BasicAttribute objectClass = new BasicAttribute(LDAPServerManagerConstants.LDAP_OBJECT_CLASS); objectClass.add(LDAPServerManagerConstants.LDAP_INTET_ORG_PERSON); objectClass.add(LDAPServerManagerConstants.LDAP_ORG_PERSON); objectClass.add(LDAPServerManagerConstants.LDAP_PERSON); objectClass.add(LDAPServerManagerConstants.LDAP_TOP); // Add Kerberos specific object classes objectClass.add(LDAPServerManagerConstants.LDAP_KRB5_PRINCIPLE); objectClass.add(LDAPServerManagerConstants.LDAP_KRB5_KDC); objectClass.add(LDAPServerManagerConstants.LDAP_SUB_SCHEMA); basicAttributes.put(objectClass);/*from w ww .jav a 2 s .co m*/ BasicAttribute uid = new BasicAttribute(LDAPServerManagerConstants.LDAP_UID); uid.add(id); basicAttributes.put(uid); String principal = getFullyQualifiedPrincipalName(principleName); BasicAttribute principalAttribute = new BasicAttribute( LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE); principalAttribute.add(principal); basicAttributes.put(principalAttribute); BasicAttribute versionNumberAttribute = new BasicAttribute( LDAPServerManagerConstants.KRB5_KEY_VERSION_NUMBER_ATTRIBUTE); versionNumberAttribute.add("0"); basicAttributes.put(versionNumberAttribute); BasicAttribute userPassword = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD); //Since we are using the KDC, we will always use plain text password. //KDC does not support other types of passwords String password = getPasswordToStore((String) credential, LDAPServerManagerConstants.PASSWORD_HASH_METHOD_PLAIN_TEXT); userPassword.add(password.getBytes()); basicAttributes.put(userPassword); if (commonName == null || commonName.isEmpty()) { commonName = principleName + " Service"; } BasicAttribute cn = new BasicAttribute(LDAPServerManagerConstants.LDAP_COMMON_NAME); cn.add(commonName); basicAttributes.put(cn); BasicAttribute sn = new BasicAttribute(LDAPServerManagerConstants.SERVER_PRINCIPAL_ATTRIBUTE_NAME); sn.add(surName); basicAttributes.put(sn); }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
protected void updateSuffix(DirContext dirContext) { String ldapSuffix = getLDAPSuffix(); NamingEnumeration<SearchResult> namingEnum = null; try {/* w w w.jav a2 s .com*/ try { String dn = ldapSuffix; Attributes attributes = new BasicAttributes(); Attribute objclass = new BasicAttribute("objectclass"); objclass.add("organization"); objclass.add("dcObject"); attributes.put(objclass); attributes.put("dc", "tolven"); attributes.put("o", "myOrg"); dirContext.createSubcontext(dn, attributes); logger.info("Executed a createSubContext LDAP schema for " + ldapSuffix); } catch (NamingException ex) { //For some reason the search can fail, when the suffix is available, and when not available // The only certainty is to attempt to create it for now } } finally { if (namingEnum != null) { try { namingEnum.close(); } catch (NamingException ex) { throw new RuntimeException("Could not close the naming enumeration for the ldap suffix schema", ex); } } } }
From source file:org.easy.ldap.LdapDao.java
/** * @param rootDn/*from w w w . j av a 2 s .c om*/ * @param type * @return */ public List<String> findRdnValue(LdapName rootDn, RdnType type) { NamingEnumeration<SearchResult> result = null; List<String> out = new ArrayList<String>(0); DirContext ctx = null; try { ctx = contextFactory.createContext(rootDn.toString()); Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(type.toString())); result = ctx.search("", attributes); while (result.hasMore()) { attributes = result.next().getAttributes(); out.add(attributes.get(type.toString()).get().toString()); } } catch (NamingException e) { throw new RuntimeException(type.toString() + "," + rootDn.toString(), e); } finally { if (contextFactory != null) contextFactory.closeContext(ctx); } return out; }
From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java
/** * Create sub contexts under the tenant's main context. * * @param dnOfParentContext domain name of the parent context. * @param nameOfCurrentContext name of the current context. * @param initialDirContext The directory connection. * @throws UserStoreException if an error occurs while creating context. */// w w w . java 2 s .c o m protected void createOrganizationalSubContext(String dnOfParentContext, String nameOfCurrentContext, DirContext initialDirContext) throws UserStoreException { DirContext subContext = null; DirContext organizationalContext = null; try { //get the connection for tenant's main context subContext = (DirContext) initialDirContext.lookup(dnOfParentContext); Attributes contextAttributes = new BasicAttributes(true); //create sub unit object class attribute Attribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME); objectClass.add(tenantMgtConfig.getTenantStoreProperties() .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORG_SUB_CONTEXT_OBJ_CLASS)); contextAttributes.put(objectClass); //create org sub unit name attribute String orgSubUnitAttributeName = tenantMgtConfig.getTenantStoreProperties() .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORG_SUB_CONTEXT_ATTRIBUTE); Attribute organizationSubUnit = new BasicAttribute(orgSubUnitAttributeName); organizationSubUnit.add(nameOfCurrentContext); contextAttributes.put(organizationSubUnit); //construct the rdn of org sub context String rdnOfOrganizationalContext = orgSubUnitAttributeName + "=" + nameOfCurrentContext; if (logger.isDebugEnabled()) { logger.debug("Adding sub context: " + rdnOfOrganizationalContext + " under " + dnOfParentContext + " ..."); } //create sub context organizationalContext = subContext.createSubcontext(rdnOfOrganizationalContext, contextAttributes); if (logger.isDebugEnabled()) { logger.debug("Sub context: " + rdnOfOrganizationalContext + " was added under " + dnOfParentContext + " successfully."); } } catch (NamingException e) { String errorMsg = "Error occurred while adding the organizational unit " + "sub context."; if (logger.isDebugEnabled()) { logger.debug(errorMsg, e); } throw new UserStoreException(errorMsg, e); } finally { closeContext(organizationalContext); closeContext(subContext); } }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Test case for <a href="http://issues.apache.org/jira/browse/DIREVE-284" where users in * mixed case partitions were not able to authenticate properly. This test case creates * a new partition under dc=aPache,dc=org, it then creates the example user in the JIRA * issue and attempts to authenticate as that user. * * @throws Exception if the user cannot authenticate or test fails */// www. ja v a 2s. c om @Test public void testUserAuthOnMixedCaseSuffix() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/dc=aPache,dc=org"); env.put("java.naming.ldap.version", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialDirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(""); assertTrue(attrs.get("dc").get().equals("aPache")); Attributes user = new BasicAttributes("cn", "Kate Bush", true); Attribute oc = new BasicAttribute("objectClass"); oc.add("top"); oc.add("person"); oc.add("organizationalPerson"); oc.add("inetOrgPerson"); user.put(oc); user.put("sn", "Bush"); user.put("userPassword", "Aerial"); ctx.createSubcontext("cn=Kate Bush", user); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_CREDENTIALS, "Aerial"); env.put(Context.SECURITY_PRINCIPAL, "cn=Kate Bush,dc=aPache,dc=org"); InitialDirContext userCtx = new InitialDirContext(env); assertNotNull(userCtx); ctx.destroySubcontext("cn=Kate Bush"); }
From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java
private void loadSingleAttribute(Attributes attrs, String attrID, Object value, boolean oneWayEncrypted, boolean forUpdate, String encrypted, LdapAttributeValueTranslator translator) throws LdapMappingException { if (value != null) { value = translator.toLdap(value); if (oneWayEncrypted) { value = encrypt(value);//from w w w. ja va2s .co m } else if (ENCRYPTION_ALGORITHM.equals(encrypted)) { value = preparePassword(value); } else if (value.getClass().isEnum()) { value = value.toString(); } else if (Boolean.class.equals(value.getClass())) { value = ((Boolean) value) ? "TRUE" : "FALSE"; } else if (value instanceof Number) { value = value.toString(); } Attribute attr = attrs.get(attrID); if (attr == null) { attrs.put(attrID, value); } else { attr.add(value); } } else if (!USERPASSWORD.equals(attrID) && forUpdate) { attrs.put(new BasicAttribute(attrID)); } }
From source file:org.springframework.ldap.core.DirContextAdapter.java
private void collectModifications(Attribute originalAttr, Attribute changedAttr, List modificationList) throws NamingException { Attribute originalClone = (Attribute) originalAttr.clone(); Attribute addedValuesAttribute = new BasicAttribute(originalAttr.getID()); for (int i = 0; i < changedAttr.size(); i++) { Object attributeValue = changedAttr.get(i); if (!originalClone.remove(attributeValue)) { addedValuesAttribute.add(attributeValue); }/* w ww . ja va2s.c om*/ } // We have now traversed and removed all values from the original that // were also present in the new values. The remaining values in the // original must be the ones that were removed. if (originalClone.size() > 0) { modificationList.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, originalClone)); } if (addedValuesAttribute.size() > 0) { modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, addedValuesAttribute)); } }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
protected void updateGroups(DirContext dirContext, SearchControls controls) { String ldapSuffix = getLDAPSuffix(); String ldapGroups = getLDAPGroups(); NamingEnumeration<SearchResult> namingEnum = null; try {/*w w w .j av a 2s. co m*/ boolean schemaExists = false; try { namingEnum = dirContext.search(ldapSuffix, ldapGroups, controls); schemaExists = namingEnum.hasMore(); } catch (NamingException ex) { throw new RuntimeException("Could find groups schema", ex); } if (schemaExists) { logger.info("LDAP schema for " + ldapGroups + " already exists"); } else { String dn = ldapGroups + "," + ldapSuffix; Attributes attributes = new BasicAttributes(); Attribute objclass = new BasicAttribute("objectclass"); objclass.add("organizationalUnit"); attributes.put(objclass); attributes.put(ldapGroups.substring(0, ldapGroups.indexOf("=")), ldapGroups.substring(ldapGroups.indexOf("=") + 1)); try { dirContext.createSubcontext(dn, attributes); } catch (NamingException ex) { throw new RuntimeException("Could not create groups schema", ex); } logger.info("Created LDAP schema for " + ldapGroups); } } finally { if (namingEnum != null) { try { namingEnum.close(); } catch (NamingException ex) { throw new RuntimeException("Could not close the naming enumeration for the ldap groups schema", ex); } } } }