List of usage examples for javax.naming.directory BasicAttribute add
public boolean add(Object attrVal)
From source file:openscim.restful.server.resources.user.ldap.LdapUserResource.java
@Override public Response createUser(UriInfo uriInfo, User user) { // 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 UserAttributesMapper(properties); // build the user dn String dn = user.getId(); if (properties .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS) .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) { // utilise ldap formated dn dn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE, UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + user.getId() + "," + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN, UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN); }/*from ww w . j a va 2s .c om*/ try { try { // create the mapper if it doesn't already exists if (mapper == null) mapper = new UserAttributesMapper(properties); // retrieve the user User lookedUser = (User) ldapTemplate.lookup(dn, mapper); // check if the user was found if (lookedUser != null) { // user already exists return ResourceUtilities.buildErrorResponse(HttpStatus.CONFLICT, HttpStatus.CONFLICT.getMessage() + ": Resource " + user.getId() + " already exists"); } } catch (Exception nException) { // user not found, do nothing } Attributes userAttributes = new BasicAttributes(); // get the objectclasses String objectclasses = properties.getProperty(UserAttributesMapper.ACCOUNT_OBJECTCLASS_ATTRIBUTE, UserAttributesMapper.DEFAULT_ACCOUNT_OBJECTCLASS_ATTRIBUTE); // set the objectclass of the user /* Attribute objectclassAttribute = new BasicAttribute("objectclass"); Scanner scanner = new Scanner(objectclasses); scanner.useDelimiter(","); while(scanner.hasNext()) { objectclassAttribute.add(scanner.next()); } */ BasicAttribute objectclassAttribute = new BasicAttribute("objectclass"); objectclassAttribute.add("inetOrgPerson"); objectclassAttribute.add("organizationalPerson"); objectclassAttribute.add("person"); objectclassAttribute.add("top"); userAttributes.put(objectclassAttribute); // get the uid attribute name String uidAtttributeName = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE, UserAttributesMapper.DEFAULT_UID_ATTRIBUTE); // set the uid userAttributes.put(uidAtttributeName, user.getId()); // get the display name attribute name String displayAtttributeName = properties.getProperty(UserAttributesMapper.DISPLAYNAME_ATTRIBUTE, UserAttributesMapper.DEFAULT_DISPLAYNAME_ATTRIBUTE); // set the display name if (user.getDisplayName() != null) userAttributes.put(displayAtttributeName, user.getDisplayName()); // get the surname attribute name String surnameAtttributeName = properties.getProperty(UserAttributesMapper.FAMILYNAME_ATTRIBUTE, UserAttributesMapper.DEFAULT_FAMILYNAME_ATTRIBUTE); // get the given name attribute name String givenAtttributeName = properties.getProperty(UserAttributesMapper.GIVENNAME_ATTRIBUTE, UserAttributesMapper.DEFAULT_GIVENNAME_ATTRIBUTE); // set the names if (user.getName() != null) { if (user.getName().getFamilyName() != null) userAttributes.put(surnameAtttributeName, user.getName().getFamilyName()); if (user.getName().getGivenName() != null) userAttributes.put(givenAtttributeName, user.getName().getGivenName()); } // get the email attribute name String mailAtttributeName = properties.getProperty(UserAttributesMapper.MAIL_ATTRIBUTE, UserAttributesMapper.DEFAULT_MAIL_ATTRIBUTE); // set the emails if (user.getEmails() != null) { Attribute attribute = new BasicAttribute(mailAtttributeName); List<PluralAttribute> emails = user.getEmails().getEmail(); for (PluralAttribute email : emails) { attribute.add(email.getValue()); } userAttributes.put(attribute); } // get the telephone attribute name String telephoneAtttributeName = properties.getProperty(UserAttributesMapper.TELEPHONE_ATTRIBUTE, UserAttributesMapper.DEFAULT_TELEPHONE_ATTRIBUTE); // set the telephones if (user.getPhoneNumbers() != null) { Attribute attribute = new BasicAttribute(telephoneAtttributeName); List<PluralAttribute> telephones = user.getPhoneNumbers().getPhoneNumber(); for (PluralAttribute telephone : telephones) { attribute.add(telephone.getValue()); } userAttributes.put(attribute); } // get the password attribute name String passwordAtttributeName = properties.getProperty(UserAttributesMapper.PASSWORD_ATTRIBUTE, UserAttributesMapper.DEFAULT_PASSWORD_ATTRIBUTE); // set the password if (user.getPassword() != null) userAttributes.put(passwordAtttributeName, user.getPassword()); // create the user ldapTemplate.bind(dn, null, userAttributes); // determine the url of the new resource URI location = new URI("/User/" + dn); if (properties .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS) .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) { location = new URI("/User/" + user.getId()); } // set the internal id to the dn user.setId(dn); if (properties .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS) .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) { user.setId(user.getId()); } // user stored successfully, return the user return Response.created(location).entity(user).build(); } catch (URISyntaxException usException) { // problem generating entity location logger.error("problem generating entity location"); usException.printStackTrace(System.out); // return a server error return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider problem generating entity location"); } catch (Exception nException) { // problem creating user logger.error("problem creating user"); nException.printStackTrace(System.out); // return a server error return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider problem creating user"); } } 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 user ldap repository not configured"); } }
From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java
/** * @param attribute/*from w w w.j a va2 s. c o m*/ * @return * @throws LDAPException */ private BasicAttribute buildBasicAttribute(LDAPEntryAttribute attribute) throws LDAPException { if (attribute != null) { if (attribute.isMultiValued()) { BasicAttribute basicAttribute = new BasicAttribute(attribute.getName()); for (Iterator<Object> it = attribute.getValues().iterator(); it.hasNext();) { basicAttribute.add(it.next()); } return basicAttribute; } else { return new BasicAttribute(attribute.getName(), attribute.getValue()); } } else { return null; } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * *//*from w ww .j a va 2 s . c om*/ public void doAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims, String profileName, boolean requirePasswordChange) throws UserStoreException { boolean isUserBinded = false; /* getting search base directory context */ DirContext dirContext = getSearchBaseDirectoryContext(); /* getting add user basic attributes */ BasicAttributes basicAttributes = getAddUserBasicAttributes(userName); if (!isADLDSRole) { // creating a disabled user account in AD DS BasicAttribute userAccountControl = new BasicAttribute( LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL); userAccountControl.add(LDAPConstants.ACTIVE_DIRECTORY_DISABLED_NORMAL_ACCOUNT); basicAttributes.put(userAccountControl); } /* setting claims */ setUserClaims(claims, basicAttributes, userName); Name compoundName = null; try { NameParser ldapParser = dirContext.getNameParser(""); compoundName = ldapParser.parse("cn=" + escapeSpecialCharactersForDN(userName)); /* bind the user. A disabled user account with no password */ dirContext.bind(compoundName, null, basicAttributes); isUserBinded = true; /* update the user roles */ doUpdateRoleListOfUser(userName, null, roleList); /* reset the password and enable the account */ if (!isSSLConnection) { logger.warn("Unsecured connection is being used. Enabling user account operation will fail"); } ModificationItem[] mods = new ModificationItem[2]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, createUnicodePassword((String) credential))); if (isADLDSRole) { mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_MSDS_USER_ACCOUNT_DISSABLED, "FALSE")); } else { mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute( LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL, userAccountControl)); } dirContext.modifyAttributes(compoundName, mods); } catch (NamingException e) { String errorMessage = "Error while adding the user to the Active Directory for user : " + userName; if (isUserBinded) { try { dirContext.unbind(compoundName); } catch (NamingException e1) { errorMessage = "Error while accessing the Active Directory for user : " + userName; throw new UserStoreException(errorMessage, e); } errorMessage = "Error while enabling the user account. Please check password policy at DC for user : " + userName; } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeContext(dirContext); } }
From source file:org.springframework.ldap.core.DirContextAdapter.java
public void setAttributeValue(String name, Object value) { // new entry//from ww w . ja va2 s . c om 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); } }
From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java
/** {@inheritDoc} */ public void execute(AddRequest addRequest, AddResponse addResponse) { try {/*w w w. j av a 2s . c om*/ handleEmptyReferences(addRequest); } catch (DSMLProfileException e) { fail(addResponse, ErrorCode.CUSTOM_ERROR, e); return; } catch (PspException e) { fail(addResponse, ErrorCode.CUSTOM_ERROR, e); return; } Ldap ldap = null; try { SortedLdapBeanFactory ldapBeanFactory = new SortedLdapBeanFactory(); LdapAttributes ldapAttributes = ldapBeanFactory.newLdapAttributes(); Extensible data = addRequest.getData(); // data Map<String, DSMLAttr> dsmlAttrs = PSPUtil.getDSMLAttrMap(data); for (DSMLAttr dsmlAttr : dsmlAttrs.values()) { BasicAttribute basicAttribute = new BasicAttribute(dsmlAttr.getName()); for (DSMLValue dsmlValue : dsmlAttr.getValues()) { basicAttribute.add(dsmlValue.getValue()); } LdapAttribute ldapAttribute = ldapBeanFactory.newLdapAttribute(); ldapAttribute.setAttribute(basicAttribute); ldapAttributes.addAttribute(ldapAttribute); } // references Map<String, List<Reference>> references = PSPUtil.getReferences(addRequest.getCapabilityData()); for (String typeOfReference : references.keySet()) { BasicAttribute basicAttribute = new BasicAttribute(typeOfReference); for (Reference reference : references.get(typeOfReference)) { if (reference.getToPsoID().getTargetID().equals(getId())) { String id = reference.getToPsoID().getID(); // fake empty string since the spml toolkit ignores an empty string psoID if (id == null) { id = ""; } basicAttribute.add(id); } } LdapAttribute ldapAttribute = ldapBeanFactory.newLdapAttribute(); ldapAttribute.setAttribute(basicAttribute); ldapAttributes.addAttribute(ldapAttribute); } // create // assume the psoID is a DN String dn = addRequest.getPsoID().getID(); String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn); ldap = ldapPool.checkOut(); LOG.debug("Target '{}' - Create '{}'", getId(), PSPUtil.toString(addRequest)); LOG.debug("Target '{}' - Create DN '{}'", getId(), escapedDn); ldap.create(escapedDn, ldapAttributes.toAttributes()); LOG.info("Target '{}' - Created '{}'", getId(), PSPUtil.toString(addRequest)); if (this.isLogLdif()) { LdapEntry ldapEntry = ldapBeanFactory.newLdapEntry(); ldapEntry.setDn(dn); ldapEntry.setLdapAttributes(ldapAttributes); LdapResult result = ldapBeanFactory.newLdapResult(); result.addEntry(ldapEntry); Ldif ldif = new Ldif(); LOG.info("Target '{}' - LDIF\n{}", getId(), ldif.createLdif(result)); } // response PSO if (addRequest.getReturnData().equals(ReturnData.IDENTIFIER)) { PSO responsePSO = new PSO(); responsePSO.setPsoID(addRequest.getPsoID()); addResponse.setPso(responsePSO); } else { LookupRequest lookupRequest = new LookupRequest(); lookupRequest.setPsoID(addRequest.getPsoID()); lookupRequest.setReturnData(addRequest.getReturnData()); LookupResponse lookupResponse = this.execute(lookupRequest); if (lookupResponse.getStatus() == StatusCode.SUCCESS) { addResponse.setPso(lookupResponse.getPso()); } else { fail(addResponse, lookupResponse.getError(), "Unable to lookup object after create."); } } } catch (LdapPoolException e) { fail(addResponse, ErrorCode.CUSTOM_ERROR, e); } catch (NameAlreadyBoundException e) { fail(addResponse, ErrorCode.ALREADY_EXISTS, e); } catch (NamingException e) { fail(addResponse, ErrorCode.CUSTOM_ERROR, e); } catch (PspException e) { // from PSO.getReferences, an unhandled capability data fail(addResponse, ErrorCode.CUSTOM_ERROR, e); } finally { ldapPool.checkIn(ldap); } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * Sets the set of claims provided at adding users * * @param claims/* www .j a va2 s . c o m*/ * @param basicAttributes * @throws UserStoreException */ protected void setUserClaims(Map<String, String> claims, BasicAttributes basicAttributes, String userName) throws UserStoreException { if (claims != null) { BasicAttribute claim; for (Map.Entry<String, String> entry : claims.entrySet()) { // avoid attributes with empty values if (EMPTY_ATTRIBUTE_STRING.equals(entry.getValue())) { continue; } // needs to get attribute name from claim mapping String claimURI = entry.getKey(); // skipping profile configuration attribute if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) { continue; } 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); } claim = new BasicAttribute(attributeName); claim.add(claims.get(entry.getKey())); if (logger.isDebugEnabled()) { logger.debug( "AttributeName: " + attributeName + " AttributeValue: " + claims.get(entry.getKey())); } basicAttributes.put(claim); } } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims, String profileName, boolean requirePasswordChange) throws UserStoreException { /* getting search base directory context */ DirContext dirContext = getSearchBaseDirectoryContext(); /* getting add user basic attributes */ BasicAttributes basicAttributes = getAddUserBasicAttributes(escapeSpecialCharactersForDN(userName)); BasicAttribute userPassword = new BasicAttribute("userPassword"); userPassword.add(UserCoreUtil.getPasswordToStore((String) credential, this.realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD), kdcEnabled)); basicAttributes.put(userPassword);//from w ww.j a v a 2s .co m /* setting claims */ setUserClaims(claims, basicAttributes, userName); try { NameParser ldapParser = dirContext.getNameParser(""); Name compoundName = ldapParser.parse(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE) + "=" + escapeSpecialCharactersForDN(userName)); if (log.isDebugEnabled()) { log.debug("Binding user: " + compoundName); } dirContext.bind(compoundName, null, basicAttributes); } catch (NamingException e) { String errorMessage = "Cannot access the directory context or " + "user already exists in the system for user :" + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeContext(dirContext); } try { /* update the user roles */ doUpdateRoleListOfUser(userName, null, roleList); if (log.isDebugEnabled()) { log.debug("Roles are added for user : " + userName + " successfully."); } } catch (UserStoreException e) { String errorMessage = "User is added. But error while updating role list of user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Returns a BasicAttributes object with basic required attributes * * @param userName//from ww w. ja v a 2 s.c o m * @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.ldap.ReadWriteLDAPUserStoreManager.java
/** * Sets the set of claims provided at adding users * * @param claims//from w w w . j ava 2 s . c om * @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); } }