List of usage examples for javax.naming.directory BasicAttribute BasicAttribute
public BasicAttribute(String id)
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@Override @SuppressWarnings("unchecked") public void updateEntry(DocumentModel docModel) { checkPermission(SecurityConstants.WRITE); List<String> updateList = new ArrayList<String>(); List<String> referenceFieldList = new LinkedList<String>(); try {//from w ww . j a va 2s .c o m for (String fieldName : schemaFieldMap.keySet()) { if (!docModel.getPropertyObject(schemaName, fieldName).isDirty()) { continue; } if (getDirectory().isReference(fieldName)) { referenceFieldList.add(fieldName); } else { updateList.add(fieldName); } } if (!isReadOnlyEntry(docModel) && !updateList.isEmpty()) { Attributes attrs = new BasicAttributes(); SearchResult ldapEntry = getLdapEntry(docModel.getId()); if (ldapEntry == null) { throw new DirectoryException(docModel.getId() + " not found"); } Attributes oldattrs = ldapEntry.getAttributes(); String dn = ldapEntry.getNameInNamespace(); Attributes attrsToDel = new BasicAttributes(); for (String f : updateList) { Object value = docModel.getProperty(schemaName, f); String backendField = getDirectory().getFieldMapper().getBackendField(f); if (LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY.equals(backendField)) { // skip special LDAP DN field that is readonly log.warn(String.format("field %s is mapped to read only DN field: ignored", f)); continue; } if (value == null || value.equals("")) { Attribute objectClasses = oldattrs.get("objectClass"); Attribute attr; if (getMandatoryAttributes(objectClasses).contains(backendField)) { attr = new BasicAttribute(backendField); // XXX: this might fail if the mandatory attribute // is typed integer for instance attr.add(" "); attrs.put(attr); } else if (oldattrs.get(backendField) != null) { attr = new BasicAttribute(backendField); attr.add(oldattrs.get(backendField).get()); attrsToDel.put(attr); } } else if (f.equals(getPasswordField())) { // The password has been updated, it has to be encrypted Attribute attr = new BasicAttribute(backendField); attr.add(PasswordHelper.hashPassword((String) value, passwordHashAlgorithm)); attrs.put(attr); } else { attrs.put(getAttributeValue(f, value)); } } if (log.isDebugEnabled()) { log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' " + "mod_op='REMOVE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrsToDel, this)); } dirContext.modifyAttributes(dn, DirContext.REMOVE_ATTRIBUTE, attrsToDel); if (log.isDebugEnabled()) { log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' " + "mod_op='REPLACE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrs, this)); } dirContext.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs); } // update reference fields for (String referenceFieldName : referenceFieldList) { List<Reference> references = directory.getReferences(referenceFieldName); if (references.size() > 1) { // not supported } else { Reference reference = references.get(0); List<String> targetIds = (List<String>) docModel.getProperty(schemaName, referenceFieldName); reference.setTargetIdsForSource(docModel.getId(), targetIds); } } } catch (NamingException e) { handleException(e, "updateEntry failed:"); } getDirectory().invalidateCaches(); }
From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java
@Deprecated protected void createAdminGroup(String dnOfGroupContext, String adminUserDN, DirContext initialDirContext) throws UserStoreException { //create set of attributes required to create admin group Attributes adminGroupAttributes = new BasicAttributes(true); //admin entry object class Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME); objectClassAttribute.add(realmConfig.getUserStoreProperty(LDAPConstants.GROUP_ENTRY_OBJECT_CLASS)); adminGroupAttributes.put(objectClassAttribute); //group name attribute String groupNameAttributeName = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE); Attribute groupNameAttribute = new BasicAttribute(groupNameAttributeName); String adminRoleName = realmConfig.getAdminRoleName(); groupNameAttribute.add(UserCoreUtil.removeDomainFromName(adminRoleName)); adminGroupAttributes.put(groupNameAttribute); //membership attribute Attribute membershipAttribute = new BasicAttribute( realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE)); membershipAttribute.add(adminUserDN); adminGroupAttributes.put(membershipAttribute); DirContext groupContext = null; try {/* w w w . j a v a 2s . c om*/ groupContext = (DirContext) initialDirContext.lookup(dnOfGroupContext); String rdnOfAdminGroup = groupNameAttributeName + "=" + UserCoreUtil.removeDomainFromName(adminRoleName); groupContext.bind(rdnOfAdminGroup, null, adminGroupAttributes); } catch (NamingException e) { String errorMessage = "Error occurred while creating the admin group."; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { closeContext(groupContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Sets the set of claims provided at adding users * * @param claims//w ww . jav a2 s .c o m * @param basicAttributes * @throws UserStoreException */ protected void setUserClaims(Map<String, String> claims, BasicAttributes basicAttributes, String userName) throws UserStoreException { BasicAttribute claim; boolean debug = log.isDebugEnabled(); log.debug("Processing user claims"); /* * we keep boolean values to know whether compulsory attributes 'sn' and 'cn' are set during * setting claims. */ boolean isSNExists = false; boolean isCNExists = false; if (claims != null) { for (Map.Entry<String, String> entry : claims.entrySet()) { /* * LDAP does not allow for empty values. If an attribute has a value its stored * with the entry, otherwise it is not. Hence needs to check for empty values before * storing the attribute. */ if (EMPTY_ATTRIBUTE_STRING.equals(entry.getValue())) { continue; } // needs to get attribute name from claim mapping String claimURI = entry.getKey(); if (debug) { log.debug("Claim URI: " + claimURI); } String attributeName = null; try { attributeName = getClaimAtrribute(claimURI, userName, null); } catch (org.wso2.carbon.user.api.UserStoreException e) { String errorMessage = "Error in obtaining claim mapping."; throw new UserStoreException(errorMessage, e); } if (ATTR_NAME_CN.equals(attributeName)) { isCNExists = true; } else if (ATTR_NAME_SN.equals(attributeName)) { isSNExists = true; } if (debug) { log.debug("Mapped attribute: " + attributeName); log.debug("Attribute value: " + claims.get(entry.getKey())); } claim = new BasicAttribute(attributeName); claim.add(claims.get(entry.getKey())); basicAttributes.put(claim); } } // If required attributes cn, sn are not set during claim mapping, // set them as user names if (!isCNExists) { BasicAttribute cn = new BasicAttribute("cn"); cn.add(escapeSpecialCharactersForDNWithStar(userName)); basicAttributes.put(cn); } if (!isSNExists) { BasicAttribute sn = new BasicAttribute("sn"); sn.add(escapeSpecialCharactersForDNWithStar(userName)); basicAttributes.put(sn); } }
From source file:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java
public void createSampleEntity() throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.SECURITY_PRINCIPAL, securityPrincipal); env.put(Context.SECURITY_CREDENTIALS, securityCredentials); DirContext ctx = new InitialDirContext(env); Attributes entry = new BasicAttributes(); Attribute obClassAttr = new BasicAttribute("objectClass"); obClassAttr.add("inetOrgPerson"); entry.put(obClassAttr);/*from w w w .j a v a 2 s. co m*/ Attribute mailAttr = new BasicAttribute("mail"); mailAttr.add(testUserId + "@wso2.com"); entry.put(mailAttr); Attribute passAttr = new BasicAttribute("userPassword"); passAttr.add("12345"); entry.put(passAttr); Attribute snAttr = new BasicAttribute("sn"); snAttr.add("dim"); entry.put(snAttr); Attribute cnAttr = new BasicAttribute("cn"); cnAttr.add("dim"); entry.put(cnAttr); String dn = "uid=" + testUserId + "," + userBase; ctx.createSubcontext(dn, entry); }
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "group.add", required = { "groupId" }) @SecuredMethod(constraints = "administrator.by_domain") public HashMap<String, Object> addGroup(OperationContext opContext) throws NamingException { String groupId = (String) opContext.getParams().get("groupId"); GroupDn groupDn = nameHelper.newGroupDnFromId(groupId); DomainDn domainDn = nameHelper.newDomainDnFromDomain(groupDn.getDomain()); DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal(); Attributes attrs = new BasicAttributes(); BasicAttribute ocattr = new BasicAttribute("objectclass"); for (String objectClassName : ldapConfiguration.getGroupObjectClassList()) { ocattr.add(objectClassName);/*w ww. j av a 2 s. c o m*/ } attrs.put(ocattr); String description = (String) opContext.getParams().get("description"); if (description != null && !description.isEmpty()) { BasicAttribute descattr = new BasicAttribute("description"); descattr.add(description); attrs.put(descattr); } userDirContext.bind(groupDn, null, attrs); HashMap<String, Object> response = new HashMap<String, Object>(); response.put("success", true); return response; }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean saveUserRole(String roleName, String username, DirContext context) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { log.warn("no group found for role '{}", roleName); groupName = roleName;/*from w w w . ja v a 2s.co m*/ } NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember()); if (attribute == null) { BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.ADD_ATTRIBUTE, basicAttribute) }); } else { attribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) }); } return true; } return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
protected void updateUser(String user, String encryptedPassword, DirContext dirContext, SearchControls controls) { NamingEnumeration<SearchResult> namingEnum = null; try {//from w w w . j a v a 2s . c o m String ldapPeople = getLDAPPeople(); String ldapSuffix = getLDAPSuffix(); boolean schemaExists = false; try { namingEnum = dirContext.search(ldapPeople + "," + ldapSuffix, "uid=" + user, controls); schemaExists = namingEnum.hasMore(); } catch (NamingException ex) { throw new RuntimeException("Could find schema for: " + user, ex); } if (schemaExists) { logger.info("LDAP schema for user " + user + " already exists"); } else { String dn = "uid=" + user + "," + ldapPeople + "," + ldapSuffix; Attributes attributes = new BasicAttributes(); Attribute objclass = new BasicAttribute("objectclass"); objclass.add("inetOrgPerson"); attributes.put(objclass); attributes.put("uid", user); attributes.put("sn", user); attributes.put("cn", user); attributes.put("userPassword", encryptedPassword); try { dirContext.createSubcontext(dn, attributes); } catch (NamingException ex) { throw new RuntimeException("Could not create schema for: " + user, ex); } logger.info("Created LDAP schema for " + user); } } finally { if (namingEnum != null) { try { namingEnum.close(); } catch (NamingException ex) { throw new RuntimeException( "Could not close the naming enumeration for the ldap schema: " + user, ex); } } } }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static boolean registerUser(LDAPUser lus, UserRequest userReq, String OrgDN, String OrgUDN) { boolean registration = false; DirContext ctx = null;//w ww .java 2 s .c o m try { ctx = getAuthContext(lus.getUsername(), lus.getPassword()); Attributes attrsBag = new BasicAttributes(); Attribute oc = new BasicAttribute("objectClass"); oc.add("inetOrgPerson"); oc.add("organizationalPerson"); oc.add("person"); oc.add("top"); attrsBag.put(oc); Attribute sn = new BasicAttribute("sn", userReq.getSurname()); attrsBag.put(sn); Attribute cn = new BasicAttribute("cn", userReq.getUsername()); attrsBag.put(cn); Attribute dispName = new BasicAttribute("displayName", userReq.getUsername()); attrsBag.put(dispName); Attribute uPass = new BasicAttribute("userPassword", userReq.getPassword()); attrsBag.put(uPass); Attribute regAdd = new BasicAttribute("registeredAddress", userReq.getPreferredMail()); attrsBag.put(regAdd); if (userReq.getTitle() != null && !userReq.getTitle().isEmpty()) { Attribute title = new BasicAttribute("title", userReq.getTitle()); attrsBag.put(title); } Attribute gName = new BasicAttribute("givenName", userReq.getGivenname()); attrsBag.put(gName); Attribute inits = new BasicAttribute("initials", userReq.getGivenname().substring(0, 1).toUpperCase() + userReq.getSurname().substring(0, 1).toUpperCase()); attrsBag.put(inits); Attribute mails = new BasicAttribute("mail"); mails.add(userReq.getPreferredMail()); for (String adMail : userReq.getAdditionalMails().split("[,\\s;]")) if (!adMail.isEmpty()) mails.add(adMail.trim()); attrsBag.put(mails); Attribute org = new BasicAttribute("o", OrgDN); attrsBag.put(org); if (OrgUDN != null && !OrgUDN.isEmpty()) { Attribute orgU = new BasicAttribute("ou", OrgUDN); attrsBag.put(orgU); } ResourceBundle rb = ResourceBundle.getBundle("ldap"); ctx.createSubcontext("cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot"), attrsBag); ModificationItem[] modItems = new ModificationItem[1]; modItems[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("uniqueMember", "cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot"))); ctx.modifyAttributes(rb.getString("usersGroup"), modItems); registration = true; } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } finally { if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return registration; }
From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java
public void addSharedGroupForTenant(Tenant tenant, DirContext mainDirContext) throws UserStoreException { if (!isSharedGroupEnabled()) { return;//from ww w . j a v a 2 s . c o m } Attributes groupAttributes = new BasicAttributes(true); String domainName = tenant.getDomain(); // create ou attribute String groupNameAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.SHARED_TENANT_NAME_ATTRIBUTE); // create group entry's object class attribute Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME); objectClassAttribute.add(realmConfig.getUserStoreProperty(LDAPConstants.SHARED_TENANT_OBJECT_CLASS)); groupAttributes.put(objectClassAttribute); DirContext groupContext = null; String searchBase = realmConfig.getUserStoreProperties().get(LDAPConstants.SHARED_GROUP_SEARCH_BASE); try { groupContext = (DirContext) mainDirContext.lookup(searchBase); NameParser ldapParser = groupContext.getNameParser(""); Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" + domainName); groupContext.bind(compoundGroupName, null, groupAttributes); } catch (Exception e) { String errorMsg = "Shared tenant: " + domainName + "could not be added."; if (logger.isDebugEnabled()) { logger.debug(errorMsg, e); } throw new UserStoreException(errorMsg, e); } finally { JNDIUtil.closeContext(groupContext); } }
From source file:org.springframework.ldap.core.DirContextAdapter.java
public void setAttributeValue(String name, Object value) { // new entry//from ww w . j a v a2 s .c o m if (!updateMode && value != null) { originalAttrs.put(name, value); } // updating entry if (updateMode) { BasicAttribute attribute = new BasicAttribute(name); if (value != null) { attribute.add(value); } updatedAttrs.put(attribute); } }