List of usage examples for javax.naming.directory BasicAttribute BasicAttribute
public BasicAttribute(String id)
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
@Test public void testFailureWithUnsupportedControl() throws Exception { Control unsupported = new OpaqueControl("1.1.1.1"); unsupported.setCritical(true);/* ww w. j a v a 2 s. c o m*/ getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/ou=system"); env.put("java.naming.ldap.version", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_CREDENTIALS, "secret"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); InitialLdapContext ctx = new InitialLdapContext(env, null); 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.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(), new Control[] { unsupported })); try { ctx.createSubcontext("cn=Kate Bush", user); fail(); } catch (OperationNotSupportedException e) { } unsupported.setCritical(false); ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(), new Control[] { unsupported })); DirContext kate = ctx.createSubcontext("cn=Kate Bush", user); assertNotNull(kate); assertTrue(ArrayUtils.isEquals(Asn1StringUtils.getBytesUtf8("Aerial"), kate.getAttributes("").get("userPassword").get())); ctx.destroySubcontext("cn=Kate Bush"); }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Returns a BasicAttributes object with basic required attributes * * @param userName//from ww w . j a v a 2 s . c om * @return */ protected BasicAttributes getAddUserBasicAttributes(String userName) { BasicAttributes basicAttributes = new BasicAttributes(true); String userEntryObjectClassProperty = realmConfig .getUserStoreProperty(LDAPConstants.USER_ENTRY_OBJECT_CLASS); BasicAttribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME); String[] objectClassHierarchy = userEntryObjectClassProperty.split("/"); for (String userObjectClass : objectClassHierarchy) { if (userObjectClass != null && !userObjectClass.trim().equals("")) { objectClass.add(userObjectClass.trim()); } } // If KDC is enabled we have to set KDC specific object classes also if (kdcEnabled) { // Add Kerberos specific object classes objectClass.add("krb5principal"); objectClass.add("krb5kdcentry"); objectClass.add("subschema"); } basicAttributes.put(objectClass); BasicAttribute userNameAttribute = new BasicAttribute( realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE)); userNameAttribute.add(userName); basicAttributes.put(userNameAttribute); if (kdcEnabled) { CarbonContext cc = CarbonContext.getThreadLocalCarbonContext(); if (cc != null) { String tenantDomainName = cc.getTenantDomain(); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomainName)) { userName = userName + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR + tenantDomainName; } else { userName = userName + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } } String principal = userName + "@" + this.getRealmName(); BasicAttribute principalAttribute = new BasicAttribute(KRB5_PRINCIPAL_NAME_ATTRIBUTE); principalAttribute.add(principal); basicAttributes.put(principalAttribute); BasicAttribute versionNumberAttribute = new BasicAttribute(KRB5_KEY_VERSION_NUMBER_ATTRIBUTE); versionNumberAttribute.add("0"); basicAttributes.put(versionNumberAttribute); } return basicAttributes; }
From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java
@Deprecated protected String createAdminEntry(String dnOfUserContext, Tenant tenant, DirContext initialDirContext) throws UserStoreException { String userDN = null;//from w ww . j a v a2 s.c o m DirContext organizationalUsersContext = null; try { //get connection to tenant's user context organizationalUsersContext = (DirContext) initialDirContext.lookup(dnOfUserContext); Attributes userAttributes = new BasicAttributes(true); //create person object class attribute Attribute objClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME); objClass.add(realmConfig.getUserStoreProperty(LDAPConstants.USER_ENTRY_OBJECT_CLASS)); if (UserCoreUtil.isKdcEnabled(realmConfig)) { // Add Kerberos specific object classes objClass.add("krb5principal"); objClass.add("krb5kdcentry"); objClass.add("subschema"); String principal = tenant.getAdminName() + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR + tenant.getDomain() + UserCoreConstants.TENANT_DOMAIN_COMBINER + getRealmName(); Attribute kerberosPrincipalName = new BasicAttribute("krb5PrincipalName"); kerberosPrincipalName.add(principal); Attribute keyVersionNumber = new BasicAttribute("krb5KeyVersionNumber"); keyVersionNumber.add("0"); userAttributes.put(kerberosPrincipalName); userAttributes.put(keyVersionNumber); } userAttributes.put(objClass); //create user password attribute Attribute password = new BasicAttribute(USER_PASSWORD_ATTRIBUTE_NAME); String passwordHashMethod = realmConfig.getUserStoreProperty(LDAPConstants.PASSWORD_HASH_METHOD); String passwordToStore = UserCoreUtil.getPasswordToStore(tenant.getAdminPassword(), passwordHashMethod, isKDCEnabled()); password.add(passwordToStore); userAttributes.put(password); //create mail attribute Attribute adminEmail = new BasicAttribute(EMAIL_ATTRIBUTE_NAME); adminEmail.add(tenant.getEmail()); userAttributes.put(adminEmail); //create compulsory attribute: sn-last name Attribute lastName = new BasicAttribute(SN_ATTRIBUTE_NAME); lastName.add(tenant.getAdminLastName()); userAttributes.put(lastName); //read user name attribute in user-mgt.xml String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); //if user name attribute is not cn, add it to attribute list if (!(CN_ATTRIBUTE_NAME.equals(userNameAttribute))) { Attribute firstName = new BasicAttribute(CN_ATTRIBUTE_NAME); firstName.add(tenant.getAdminFirstName()); userAttributes.put(firstName); } String userRDN = userNameAttribute + "=" + tenant.getAdminName(); organizationalUsersContext.bind(userRDN, null, userAttributes); userDN = userRDN + "," + dnOfUserContext; //return (userRDN + dnOfUserContext); } catch (NamingException e) { String errorMsg = "Error occurred while creating Admin entry"; if (logger.isDebugEnabled()) { logger.debug(errorMsg, e); } throw new UserStoreException(errorMsg, e); } finally { closeContext(organizationalUsersContext); } return userDN; }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
protected void updatePeople(DirContext dirContext, SearchControls controls) { String ldapSuffix = getLDAPSuffix(); String ldapPeople = getLDAPPeople(); NamingEnumeration<SearchResult> namingEnum = null; try {//from w w w.jav a 2s . c o m boolean schemaExists = false; try { namingEnum = dirContext.search(ldapSuffix, ldapPeople, controls); schemaExists = namingEnum.hasMore(); } catch (NamingException ex) { throw new RuntimeException("Could find people schema", ex); } if (schemaExists) { logger.info("LDAP schema for " + ldapPeople + " already exists"); } else { String dn = ldapPeople + "," + ldapSuffix; Attributes attributes = new BasicAttributes(); Attribute objclass = new BasicAttribute("objectclass"); objclass.add("organizationalUnit"); attributes.put(objclass); attributes.put(ldapPeople.substring(0, ldapPeople.indexOf("=")), ldapPeople.substring(ldapPeople.indexOf("=") + 1)); try { dirContext.createSubcontext(dn, attributes); } catch (NamingException ex) { throw new RuntimeException("Could not create people schema", ex); } logger.info("Created LDAP schema for " + ldapPeople); } } finally { if (namingEnum != null) { try { namingEnum.close(); } catch (NamingException ex) { throw new RuntimeException("Could not close the naming enumeration for the ldap people schema", ex); } } } }
From source file:openscim.restful.server.resources.group.ldap.LdapGroupResource.java
@Override public Response updateGroup(UriInfo uriInfo, String gid, Group group) { // check the ldap template has been setup correctly if (ldapTemplate != null) { // create the mapper if it doesn't already exists if (mapper == null) mapper = new GroupAttributesMapper(properties); // build the group dn String dn = gid;/*from w ww . j a va 2 s . co m*/ if (properties .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS, GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS) .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) { // utilise ldap formated dn dn = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE, GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE) + "=" + gid + "," + properties.getProperty(GroupAttributesMapper.GROUP_BASEDN, GroupAttributesMapper.DEFAULT_GROUP_BASEDN); } try { // retrieve the group Group lookedupGroup = (Group) ldapTemplate.lookup(dn, mapper); // check if the group was found if (lookedupGroup == null) { // user not found, return an error message return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + dn + " not found"); } List<ModificationItem> items = new ArrayList<ModificationItem>(); // build a gid modification //if(group.getId() != null) //{ // // get the gid attribute name // String gidAtttributeName = GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE; // if(properties.containsKey(GroupAttributesMapper.GID_ATTRIBUTE)) gidAtttributeName = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE); // // Attribute uidAttribute = new BasicAttribute(gidAtttributeName, group.getId()); // ModificationItem uidItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uidAttribute); // items.add(uidItem); //} // get the member attribute name String memberAtttributeName = properties.getProperty(GroupAttributesMapper.MEMBER_ATTRIBUTE, GroupAttributesMapper.DEFAULT_MEMBER_ATTRIBUTE); // set the members if (group.getAny() instanceof List) { List members = (List) group.getAny(); Attribute memberAttribute = new BasicAttribute(memberAtttributeName); for (Object object : members) { if (object instanceof PluralAttribute) { PluralAttribute member = (PluralAttribute) object; String uid = member.getValue(); // build the user dn String userdn = uid; if (properties .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS) .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) { // utilise ldap formated dn userdn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE, UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + uid + "," + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN, UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN); } memberAttribute.add(userdn); } } ModificationItem memberItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, memberAttribute); items.add(memberItem); } // update the user password ModificationItem[] itemsArray = items.toArray(new ModificationItem[items.size()]); ldapTemplate.modifyAttributes(dn, itemsArray); // password changed successfully return Response.status(HttpStatus.NO_CONTENT.getCode()).build(); } catch (Exception nException) { logger.debug("Resource " + dn + " not found"); logger.debug(nException); // group not found, return an error message return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + dn + " not found"); } } else { // ldap not configured logger.error("ldap not configured"); // return a server error return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider group ldap repository not configured"); } }
From source file:com.funambol.LDAP.dao.impl.ContactDAO.java
/** * Convert a <i>Contact</i> into a LDAP inetOrgPerson set of attributes. * This method is used in from Client to Server * // www .j ava2 s. c om * @param contact * contact to transform into Attributes * @return Attributes representation of the contact */ public Attributes createEntry(Contact contact) { if (logger.isTraceEnabled()) logger.trace("Working on contact:" + contact.getUid()); Attributes attributeSet = new BasicAttributes(); Attribute objClass = new BasicAttribute("objectClass"); if (logger.isDebugEnabled()) logger.debug("Ok let's add objectclass"); objClass.add("inetOrgPerson"); objClass.add("person"); attributeSet.put(objClass); try { if (contact.getUid() == null) { contact.setUid(createUniqueId(contact)); logger.info("UID is now: " + contact.getUid()); } // Split contact object into sub-objects Name name = contact.getName(); PersonalDetail personal = contact.getPersonalDetail(); BusinessDetail business = contact.getBusinessDetail(); List phones = personal.getPhones(); List businessPhones = business.getPhones(); List mails = personal.getEmails(); List note = contact.getNotes(); // personal address Address addr = personal.getAddress(); // if displayname doesn't exist and the firstname and the lastname // are not both defined, this will result in a NullPointerException // I don't want to support any other ways of doing this right now. // a solution could be to use an UID for the rdn if (name != null) { if (propertyCheck(name.getLastName())) { attributeSet.put(new BasicAttribute("sn", name.getLastName().getPropertyValueAsString())); } else { attributeSet.put(new BasicAttribute("sn", "")); } if (propertyCheck(name.getFirstName())) { attributeSet .put(new BasicAttribute("givenName", name.getFirstName().getPropertyValueAsString())); } else { attributeSet.put(new BasicAttribute("givenName", "")); } attributeSet.put(new BasicAttribute("cn", name.getFirstName().getPropertyValueAsString() + " " + name.getLastName().getPropertyValueAsString())); } // Company name if (business != null && propertyCheck(business.getCompany())) { attributeSet.put(new BasicAttribute("o", business.getCompany().getPropertyValueAsString())); } // Adding phones if (phones != null && !phones.isEmpty()) { Iterator iter2 = phones.iterator(); while (iter2.hasNext()) { Phone phone = (Phone) iter2.next(); // if empty, no need to check type if (!propertyCheck(phone)) continue; // Home phones if (phone.getPhoneType().equals("HomeTelephoneNumber")) { attributeSet.put(new BasicAttribute("homePhone", phone.getPropertyValueAsString())); } // MobilePhones if (phone.getPhoneType().equals("MobileTelephoneNumber")) attributeSet.put(new BasicAttribute("mobile", phone.getPropertyValueAsString())); } } // Adding business phones if (businessPhones != null && !businessPhones.isEmpty()) { Iterator iter2 = businessPhones.iterator(); while (iter2.hasNext()) { Phone phone = (Phone) iter2.next(); // if empty, no need to check type if (!propertyCheck(phone)) continue; // Business phones if (phone.getPhoneType().equals("BusinessTelephoneNumber")) { attributeSet.put(new BasicAttribute("telephoneNumber", phone.getPropertyValueAsString())); } // Fax if (phone.getPhoneType().equals("BusinessFaxNumber")) { attributeSet.put( new BasicAttribute("facsimiletelephonenumber", phone.getPropertyValueAsString())); } } } if (mails != null && !mails.isEmpty()) { Iterator iter1 = mails.iterator(); // For each email address, add it while (iter1.hasNext()) { Email mail = (Email) iter1.next(); if (propertyCheck(mail)) attributeSet.put(new BasicAttribute("mail", mail.getPropertyValueAsString())); } } // Address if (addr != null) { if (propertyCheck(personal.getAddress().getPostalCode())) attributeSet.put(new BasicAttribute("postalCode", personal.getAddress().getPostalCode().getPropertyValueAsString())); if (propertyCheck(personal.getAddress().getStreet())) attributeSet.put(new BasicAttribute("postalAddress", personal.getAddress().getStreet().getPropertyValueAsString())); if (propertyCheck(personal.getAddress().getCity())) attributeSet.put( new BasicAttribute("l", personal.getAddress().getCity().getPropertyValueAsString())); } // Notes if (note != null && !note.isEmpty()) { Iterator note1 = note.iterator(); while (note1.hasNext()) { Note nota = (Note) note1.next(); if (propertyCheck(nota)) attributeSet.put(new BasicAttribute("description", nota.getPropertyValueAsString())); } } logger.info("Resulting LDAPAttributeSet is:"); NamingEnumeration<String> ids = attributeSet.getIDs(); while (ids.hasMoreElements()) { String attrID = ids.nextElement(); logger.info(attrID + ": " + ((String) attributeSet.get(attrID).get())); } // Create the LDAPEntry with dn and attributes // THE DN is the DisplayName return attributeSet; } catch (Exception e) { logger.warn("Unable to create LDAPEntry from Contact: " + e.toString(), e); return null; } }
From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportLdifRunnable.java
/** * Imports the LDIF record./* ww w . ja v a 2 s. com*/ * * @param browserConnection the browser connection * @param record the LDIF record * @param updateIfEntryExists the update if entry exists flag * @param monitor the progress monitor * * @throws NamingException the naming exception * @throws LdapInvalidDnException */ static void importLdifRecord(IBrowserConnection browserConnection, LdifRecord record, boolean updateIfEntryExists, StudioProgressMonitor monitor) throws NamingException, LdapInvalidDnException { if (!record.isValid()) { throw new NamingException( BrowserCoreMessages.bind(BrowserCoreMessages.model__invalid_record, record.getInvalidString())); } String dn = record.getDnLine().getValueAsString(); if (record instanceof LdifContentRecord || record instanceof LdifChangeAddRecord) { LdifAttrValLine[] attrVals; IEntry dummyEntry; if (record instanceof LdifContentRecord) { LdifContentRecord attrValRecord = (LdifContentRecord) record; attrVals = attrValRecord.getAttrVals(); try { dummyEntry = ModelConverter.ldifContentRecordToEntry(attrValRecord, browserConnection); } catch (LdapInvalidDnException e) { monitor.reportError(e); return; } } else { LdifChangeAddRecord changeAddRecord = (LdifChangeAddRecord) record; attrVals = changeAddRecord.getAttrVals(); try { dummyEntry = ModelConverter.ldifChangeAddRecordToEntry(changeAddRecord, browserConnection); } catch (LdapInvalidDnException e) { monitor.reportError(e); return; } } Attributes jndiAttributes = new BasicAttributes(); for (LdifAttrValLine attrVal : attrVals) { String attributeName = attrVal.getUnfoldedAttributeDescription(); Object realValue = attrVal.getValueAsObject(); if (jndiAttributes.get(attributeName) != null) { jndiAttributes.get(attributeName).add(realValue); } else { jndiAttributes.put(attributeName, realValue); } } browserConnection.getConnection().getConnectionWrapper().createEntry(dn, jndiAttributes, getControls(record), monitor, null); if (monitor.errorsReported() && updateIfEntryExists && monitor.getException() instanceof NameAlreadyBoundException) { // creation failed with Error 68, now try to update the existing entry monitor.reset(); ModificationItem[] mis = ModelConverter.entryToReplaceModificationItems(dummyEntry); browserConnection.getConnection().getConnectionWrapper().modifyEntry(dn, mis, getControls(record), monitor, null); } } else if (record instanceof LdifChangeDeleteRecord) { LdifChangeDeleteRecord changeDeleteRecord = (LdifChangeDeleteRecord) record; browserConnection.getConnection().getConnectionWrapper().deleteEntry(dn, getControls(changeDeleteRecord), monitor, null); } else if (record instanceof LdifChangeModifyRecord) { LdifChangeModifyRecord modifyRecord = (LdifChangeModifyRecord) record; LdifModSpec[] modSpecs = modifyRecord.getModSpecs(); ModificationItem[] mis = new ModificationItem[modSpecs.length]; for (int ii = 0; ii < modSpecs.length; ii++) { LdifModSpecTypeLine modSpecType = modSpecs[ii].getModSpecType(); LdifAttrValLine[] attrVals = modSpecs[ii].getAttrVals(); Attribute attribute = new BasicAttribute(modSpecType.getUnfoldedAttributeDescription()); for (int x = 0; x < attrVals.length; x++) { attribute.add(attrVals[x].getValueAsObject()); } if (modSpecType.isAdd()) { mis[ii] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attribute); } else if (modSpecType.isDelete()) { mis[ii] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute); } else if (modSpecType.isReplace()) { mis[ii] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute); } } browserConnection.getConnection().getConnectionWrapper().modifyEntry(dn, mis, getControls(modifyRecord), monitor, null); } else if (record instanceof LdifChangeModDnRecord) { LdifChangeModDnRecord modDnRecord = (LdifChangeModDnRecord) record; if (modDnRecord.getNewrdnLine() != null && modDnRecord.getDeloldrdnLine() != null) { String newRdn = modDnRecord.getNewrdnLine().getValueAsString(); boolean deleteOldRdn = modDnRecord.getDeloldrdnLine().isDeleteOldRdn(); Dn newDn; if (modDnRecord.getNewsuperiorLine() != null) { newDn = new Dn(newRdn, modDnRecord.getNewsuperiorLine().getValueAsString()); } else { Dn dnObject = new Dn(dn); Dn parent = dnObject.getParent(); newDn = new Dn(newRdn, parent.getName()); } browserConnection.getConnection().getConnectionWrapper().renameEntry(dn, newDn.toString(), deleteOldRdn, getControls(modDnRecord), monitor, null); } } }
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "user.add", required = { "userId" }) @SecuredMethod(constraints = "administrator.by_domain") public HashMap<String, Object> addUser(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(); Attributes attrs = new BasicAttributes(); BasicAttribute ocattr = new BasicAttribute("objectclass"); for (String objectClassName : ldapConfiguration.getUserObjectClassList()) { ocattr.add(objectClassName);//from w w w . ja va2 s. c o m } attrs.put(ocattr); for (DisplayAttribute displayAttribute : displayAttributeHelper.getApiNameIndexedAttrDef().values()) { Object attrValue = opContext.getParams().get(displayAttribute.getApiName()); if (attrValue != null) { BasicAttribute attr = new BasicAttribute(displayAttribute.getLdapName()); if (attrValue instanceof List) { for (Object attrOneValue : (List) attrValue) { attr.add(attrOneValue); } } else { attr.add(attrValue); } attrs.put(attr); } else if (displayAttribute.isMustHave()) { throw new RuntimeException(displayAttribute.getApiName() + " is required!"); } } userDirContext.bind(userDn, 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 saveRole(String roleName, DirContext context) throws MappingException { if (hasRole(context, roleName)) { return true; }/*from w w w.j a v a 2s. c o m*/ String groupName = findGroupName(roleName); if (groupName == null) { if (this.useDefaultRoleName) { groupName = roleName; } else { log.warn("skip group creation as no mapping for roleName:'{}'", roleName); return false; } } List<String> allGroups = getAllGroups(context); if (allGroups.contains(groupName)) { log.info("group {} already exists for role.", groupName, roleName); return false; } Attributes attributes = new BasicAttributes(true); BasicAttribute objectClass = new BasicAttribute("objectClass"); objectClass.add("top"); objectClass.add("groupOfUniqueNames"); attributes.put(objectClass); attributes.put("cn", groupName); // attribute mandatory when created a group so add admin as default member BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=admin," + getBaseDn()); attributes.put(basicAttribute); try { String dn = "cn=" + groupName + "," + this.groupsDn; context.createSubcontext(dn, attributes); log.info("created group with dn:'{}", dn); return true; } catch (NameAlreadyBoundException e) { log.info("skip group '{}' creation as already exists", groupName); return true; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
protected void updateRootDN(DirContext dirContext, SearchControls controls) { String ldapRootDN = getRootDN(); NamingEnumeration<SearchResult> namingEnum = null; try {/* w w w . j a v a 2s. com*/ boolean schemaExists = false; String name = null; String base = null; try { int index = ldapRootDN.indexOf(","); if (index == -1) { throw new RuntimeException("Expected to find at least one comma in the rootDN"); } else { name = ldapRootDN.substring(0, index); base = ldapRootDN.substring(index + 1); } namingEnum = dirContext.search(base, name, controls); schemaExists = namingEnum.hasMore(); } catch (NamingException ex) { throw new RuntimeException("Could find rootDN schema", ex); } if (schemaExists) { logger.info("LDAP schema for " + ldapRootDN + " already exists"); } else { String dn = name + "," + base; Attributes attributes = new BasicAttributes(); Attribute objclass = new BasicAttribute("objectclass"); objclass.add("organizationalRole"); attributes.put(objclass); attributes.put(name.substring(0, name.indexOf("=")), name.substring(name.indexOf("=") + 1)); try { dirContext.createSubcontext(dn, attributes); } catch (NamingException ex) { throw new RuntimeException("Could not create rootDN schema", ex); } logger.info("Created LDAP schema for " + ldapRootDN); } } finally { if (namingEnum != null) { try { namingEnum.close(); } catch (NamingException ex) { throw new RuntimeException("Could not close the naming enumeration for the ldap rootDN schema", ex); } } } }