List of usage examples for javax.naming.directory Attributes put
Attribute put(Attribute attr);
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); }// w ww .ja v a 2 s.c o m 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.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * Either delete or add user from/to group. * * @param userNameDN : distinguish name of user entry. * @param groupRDN : relative distinguish name of group entry * @param modifyType : modify attribute type in DirCOntext. * @throws UserStoreException If an error occurs while updating. *//* ww w .j a va 2 s .com*/ protected void modifyUserInRole(String userNameDN, String groupRDN, int modifyType, String searchBase) throws UserStoreException { if (log.isDebugEnabled()) { log.debug("Modifying role: " + groupRDN + " with type: " + modifyType + " user: " + userNameDN + " in search base: " + searchBase); } DirContext mainDirContext = null; DirContext groupContext = null; try { mainDirContext = this.connectionSource.getContext(); groupContext = (DirContext) mainDirContext.lookup(searchBase); String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); Attributes modifyingAttributes = new BasicAttributes(true); Attribute memberAttribute = new BasicAttribute(memberAttributeName); memberAttribute.add(userNameDN); modifyingAttributes.put(memberAttribute); groupContext.modifyAttributes(groupRDN, modifyType, modifyingAttributes); if (log.isDebugEnabled()) { log.debug("User: " + userNameDN + " was successfully " + "modified in LDAP group: " + groupRDN); } } catch (NamingException e) { String errorMessage = "Error occurred while modifying user entry: " + userNameDN + " in LDAP role: " + groupRDN; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage); } finally { JNDIUtil.closeContext(groupContext); JNDIUtil.closeContext(mainDirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Either delete or add user from/to group. * * @param userNameDN : distinguish name of user entry. * @param groupRDN : relative distinguish name of group entry * @param modifyType : modify attribute type in DirCOntext. * @throws UserStoreException// ww w.ja v a 2s.c o m */ protected void modifyUserInRole(String userNameDN, String groupRDN, int modifyType, String searchBase) throws UserStoreException { if (log.isDebugEnabled()) { logger.debug("Modifying role: " + groupRDN + " with type: " + modifyType + " user: " + userNameDN + " in search base: " + searchBase); } DirContext mainDirContext = null; DirContext groupContext = null; try { mainDirContext = this.connectionSource.getContext(); groupContext = (DirContext) mainDirContext.lookup(searchBase); String memberAttributeName = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); Attributes modifyingAttributes = new BasicAttributes(true); Attribute memberAttribute = new BasicAttribute(memberAttributeName); memberAttribute.add(userNameDN); modifyingAttributes.put(memberAttribute); groupContext.modifyAttributes(groupRDN, modifyType, modifyingAttributes); if (log.isDebugEnabled()) { logger.debug("User: " + userNameDN + " was successfully " + "modified in LDAP group: " + groupRDN); } } catch (NamingException e) { String errorMessage = "Error occurred while modifying user entry: " + userNameDN + " in LDAP role: " + groupRDN; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage); } finally { JNDIUtil.closeContext(groupContext); JNDIUtil.closeContext(mainDirContext); } }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private String performOperationDelete(String entryName, ParameterResolutionContext prc, Map paramValueMap, Attributes attrs) throws SenderException, ParameterException { if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) { String result = null;//from w ww.java2 s . co m NamingEnumeration na = attrs.getAll(); while (na.hasMoreElements()) { Attribute a = (Attribute) na.nextElement(); log.debug("Delete attribute: " + a.getID()); NamingEnumeration values; try { values = a.getAll(); } catch (NamingException e1) { storeLdapException(e1, prc); throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1); } while (values.hasMoreElements()) { Attributes partialAttrs = new BasicAttributes(); Attribute singleValuedAttribute; String id = a.getID(); Object value = values.nextElement(); if (log.isDebugEnabled()) { if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) { log.debug("Delete value: ***"); } else { log.debug("Delete value: " + value); } } if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) { singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value)); } else { singleValuedAttribute = new BasicAttribute(id, value); } partialAttrs.put(singleValuedAttribute); DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.modifyAttributes(entryName, DirContext.REMOVE_ATTRIBUTE, partialAttrs); } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 16 LDAP_NO_SUCH_ATTRIBUTE Indicates that the attribute specified in the modify or compare operation does not exist in the entry. // 32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. // Sun: // [LDAP: error code 16 - No Such Attribute... // [LDAP: error code 32 - No Such Object... // AD: // [LDAP: error code 16 - 00002085: AtrErr: DSID-03151F03, #1... if (e.getMessage().startsWith("[LDAP: error code 16 - ") || e.getMessage().startsWith("[LDAP: error code 32 - ")) { if (log.isDebugEnabled()) log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage()); result = DEFAULT_RESULT_DELETE; } else { storeLdapException(e, prc); throw new SenderException( "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e); } } finally { closeDirContext(dirContext); } } } if (result != null) { return result; } return DEFAULT_RESULT; } else { DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.unbind(entryName); return DEFAULT_RESULT; } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. // Sun: // [LDAP: error code 32 - No Such Object... if (e.getMessage().startsWith("[LDAP: error code 32 - ")) { if (log.isDebugEnabled()) log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage()); return DEFAULT_RESULT_DELETE; } else { storeLdapException(e, prc); throw new SenderException( "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e); } } finally { closeDirContext(dirContext); } } }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private String performOperationCreate(String entryName, ParameterResolutionContext prc, Map paramValueMap, Attributes attrs) throws SenderException, ParameterException { if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) { String result = null;//from w ww. ja v a2s .c o m NamingEnumeration na = attrs.getAll(); while (na.hasMoreElements()) { Attribute a = (Attribute) na.nextElement(); log.debug("Create attribute: " + a.getID()); NamingEnumeration values; try { values = a.getAll(); } catch (NamingException e1) { storeLdapException(e1, prc); throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1); } while (values.hasMoreElements()) { Attributes partialAttrs = new BasicAttributes(); Attribute singleValuedAttribute; String id = a.getID(); Object value = values.nextElement(); if (log.isDebugEnabled()) { if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) { log.debug("Create value: ***"); } else { log.debug("Create value: " + value); } } if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) { singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value)); } else { singleValuedAttribute = new BasicAttribute(id, value); } partialAttrs.put(singleValuedAttribute); DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.modifyAttributes(entryName, DirContext.ADD_ATTRIBUTE, partialAttrs); } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 20 LDAP_TYPE_OR_VALUE_EXISTS Indicates that the attribute value specified in a modify or add operation already exists as a value for that attribute. // Sun: // [LDAP: error code 20 - Attribute Or Value Exists] if (e.getMessage().startsWith("[LDAP: error code 20 - ")) { if (log.isDebugEnabled()) log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage()); result = DEFAULT_RESULT_CREATE_OK; } else { storeLdapException(e, prc); throw new SenderException( "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e); } } finally { closeDirContext(dirContext); } } } if (result != null) { return result; } return DEFAULT_RESULT; } else { DirContext dirContext = null; try { if (unicodePwd) { Enumeration enumeration = attrs.getIDs(); while (enumeration.hasMoreElements()) { String id = (String) enumeration.nextElement(); if ("unicodePwd".equalsIgnoreCase(id)) { Attribute attr = attrs.get(id); for (int i = 0; i < attr.size(); i++) { attr.set(i, encodeUnicodePwd(attr.get(i))); } } } } dirContext = getDirContext(paramValueMap); dirContext.bind(entryName, null, attrs); return DEFAULT_RESULT; } catch (NamingException e) { // if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e); if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation() + "] entryName [" + entryName + "]: " + e.getMessage()); // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists. // Sun: // [LDAP: error code 68 - Entry Already Exists] if (e.getMessage().startsWith("[LDAP: error code 68 - ")) { return DEFAULT_RESULT_CREATE_OK; } else { storeLdapException(e, prc); throw new SenderException(e); } } finally { closeDirContext(dirContext); } } }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private String performOperationUpdate(String entryName, ParameterResolutionContext prc, Map paramValueMap, Attributes attrs) throws SenderException, ParameterException { String entryNameAfter = entryName; if (paramValueMap != null) { String newEntryName = (String) paramValueMap.get("newEntryName"); if (newEntryName != null && StringUtils.isNotEmpty(newEntryName)) { if (log.isDebugEnabled()) log.debug("newEntryName=[" + newEntryName + "]"); DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.rename(entryName, newEntryName); entryNameAfter = newEntryName; } catch (NamingException e) { String msg;/*from w w w .ja v a 2s . co m*/ // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. // Sun: // [LDAP: error code 32 - No Such Object... if (e.getMessage().startsWith("[LDAP: error code 32 - ")) { msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryName + "]"; } else { msg = "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]"; } storeLdapException(e, prc); throw new SenderException(msg, e); } finally { closeDirContext(dirContext); } } } if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) { NamingEnumeration na = attrs.getAll(); while (na.hasMoreElements()) { Attribute a = (Attribute) na.nextElement(); log.debug("Update attribute: " + a.getID()); NamingEnumeration values; try { values = a.getAll(); } catch (NamingException e1) { storeLdapException(e1, prc); throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1); } while (values.hasMoreElements()) { Attributes partialAttrs = new BasicAttributes(); Attribute singleValuedAttribute; String id = a.getID(); Object value = values.nextElement(); if (log.isDebugEnabled()) { if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) { log.debug("Update value: ***"); } else { log.debug("Update value: " + value); } } if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) { singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value)); } else { singleValuedAttribute = new BasicAttribute(id, value); } partialAttrs.put(singleValuedAttribute); DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.modifyAttributes(entryNameAfter, DirContext.REPLACE_ATTRIBUTE, partialAttrs); } catch (NamingException e) { String msg; // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. // Sun: // [LDAP: error code 32 - No Such Object... if (e.getMessage().startsWith("[LDAP: error code 32 - ")) { msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryNameAfter + "]"; } else { msg = "Exception in operation [" + getOperation() + "] entryName [" + entryNameAfter + "]"; } //result = DEFAULT_RESULT_UPDATE_NOK; storeLdapException(e, prc); throw new SenderException(msg, e); } finally { closeDirContext(dirContext); } } } return DEFAULT_RESULT; } else { DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); //dirContext.rename(newEntryName, oldEntryName); //result = DEFAULT_RESULT; dirContext.rename(entryName, entryName); return "<LdapResult>Deze functionaliteit is nog niet beschikbaar - naam niet veranderd.</LdapResult>"; } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists. // Sun: // [LDAP: error code 68 - Entry Already Exists] if (!e.getMessage().startsWith("[LDAP: error code 68 - ")) { storeLdapException(e, prc); throw new SenderException(e); } return DEFAULT_RESULT_CREATE_NOK; } finally { closeDirContext(dirContext); } } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
protected void addLDAPRole(RoleContext context) throws UserStoreException { String roleName = context.getRoleName(); String[] userList = context.getMembers(); String groupEntryObjectClass = ((LDAPRoleContext) context).getGroupEntryObjectClass(); String groupNameAttribute = ((LDAPRoleContext) context).getRoleNameProperty(); String searchBase = ((LDAPRoleContext) context).getSearchBase(); if ((userList == null || userList.length == 0) && !emptyRolesAllowed) { String errorMessage = "Can not create empty role. There should be at least " + "one user for the role."; throw new UserStoreException(errorMessage); } else if (userList == null && emptyRolesAllowed || userList != null && userList.length > 0 && !emptyRolesAllowed || emptyRolesAllowed) { // if (userList.length > 0) { DirContext mainDirContext = this.connectionSource.getContext(); DirContext groupContext = null; NamingEnumeration<SearchResult> results = null; try {/*from w w w . j a va 2 s . c o m*/ // create the attribute set for group entry Attributes groupAttributes = new BasicAttributes(true); // create group entry's object class attribute Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME); objectClassAttribute.add(groupEntryObjectClass); groupAttributes.put(objectClassAttribute); // create cn attribute Attribute cnAttribute = new BasicAttribute(groupNameAttribute); cnAttribute.add(roleName); groupAttributes.put(cnAttribute); // following check is for if emptyRolesAllowed made this // code executed. if (userList != null && userList.length > 0) { String memberAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); Attribute memberAttribute = new BasicAttribute(memberAttributeName); for (String userName : userList) { if (userName == null || userName.trim().length() == 0) { continue; } // search the user in user search base String searchFilter = realmConfig .getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); results = searchInUserBase(searchFilter, new String[] {}, SearchControls.SUBTREE_SCOPE, mainDirContext); // we assume only one user with the given user // name under user search base. SearchResult userResult = null; if (results.hasMore()) { userResult = results.next(); } else { String errorMsg = "There is no user with the user name: " + userName + " to be added to this role."; logger.error(errorMsg); throw new UserStoreException(errorMsg); } // get his DN String userEntryDN = userResult.getNameInNamespace(); // put it as member-attribute value memberAttribute.add(userEntryDN); } groupAttributes.put(memberAttribute); } groupContext = (DirContext) mainDirContext.lookup(searchBase); NameParser ldapParser = groupContext.getNameParser(""); /* * Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" + * roleName); */ Name compoundGroupName = ldapParser.parse("cn=" + roleName); groupContext.bind(compoundGroupName, null, groupAttributes); } catch (NamingException e) { String errorMsg = "Role: " + roleName + " could not be added."; if (log.isDebugEnabled()) { log.debug(errorMsg, e); } throw new UserStoreException(errorMsg, e); } catch (Exception e) { String errorMsg = "Role: " + roleName + " could not be added."; if (log.isDebugEnabled()) { log.debug(errorMsg, e); } throw new UserStoreException(errorMsg, e); } finally { JNDIUtil.closeNamingEnumeration(results); JNDIUtil.closeContext(groupContext); JNDIUtil.closeContext(mainDirContext); } } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
@Override public void doSetUserClaimValue(String userName, String claimURI, String value, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {// w w w .j a va 2s. c om returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned returnedUserEntry = returnedResultList.next().getName(); } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI String attributeName = getClaimAtrribute(claimURI, userName, null); if ("CN".equals(attributeName)) { subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.rename(returnedUserEntry, "CN=" + value); return; } Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(value)) { currentUpdatedAttribute.clear(); } else { String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (value.contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(value, userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(value); } } updatedAttributes.put(currentUpdatedAttribute); // update the attributes in the relevant entry of the directory // store subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes); } catch (org.wso2.carbon.user.api.UserStoreException e) { String errorMessage = "Error in obtaining claim mapping for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } catch (NamingException e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doDeleteUserClaimValue(String userName, String claimURI, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {//www .j a va2 s. com returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI String attributeName = null; attributeName = getClaimAtrribute(claimURI, userName, null); Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); updatedAttributes.put(currentUpdatedAttribute); subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doDeleteUserClaimValues(String userName, String[] claims, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {/* w w w . j av a 2 s.co m*/ returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI for (String claimURI : claims) { String attributeName = getClaimAtrribute(claimURI, userName, null); Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); updatedAttributes.put(currentUpdatedAttribute); } subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }