List of usage examples for javax.naming.directory DirContext rename
public void rename(Name oldName, Name newName) throws NamingException;
From source file:RenameInterior.java
public static void main(String[] args) { // Set up environment for creating initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try {/*from w w w .java 2s .co m*/ // Create initial context DirContext ctx = new InitialDirContext(env); // Perform rename ctx.rename("ou=NewHires", "ou=OldHires"); // Check that it worked System.out.println(ctx.lookup("ou=OldHires")); // Revert change ctx.rename("ou=OldHires", "ou=NewHires"); // Check that we are back at our original setup System.out.println(ctx.lookup("ou=NewHIres")); // Close the context when we're done ctx.close(); } catch (NamingException e) { e.printStackTrace(); } }
From source file:RenameDiffParent.java
public static void main(String[] args) { // Set up environment for creating initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try {//from ww w. ja v a 2s . co m // Create initial context DirContext ctx = new InitialDirContext(env); // Perform rename ctx.rename("cn=C. User, ou=NewHires", "cn=C. User, ou=People"); // Check that it worked System.out.println(ctx.lookup("cn=C. User, ou=People")); // Revert change ctx.rename("cn=C. User, ou=People", "cn=C. User, ou=NewHires"); // Check that we are back at our original setup System.out.println(ctx.lookup("cn=C. User, ou=NewHires")); // Close the context when we're done ctx.close(); } catch (NamingException e) { e.printStackTrace(); } }
From source file:RenameKeepRDN.java
public static void main(String[] args) { // Set up environment for creating initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); // Set property to keep RDN env.put("java.naming.ldap.deleteRDN", "false"); try {/* w ww .jav a 2 s . c o m*/ // Create initial context DirContext ctx = new InitialDirContext(env); // Perform rename ctx.rename("cn=C. User, ou=NewHires", "cn=Claude User,ou=NewHires"); // Check that it worked System.out.println(ctx.getAttributes("cn=Claude User,ou=NewHires")); // Revert change // Make sure new name doesn't get converted into attribute ctx.removeFromEnvironment("java.naming.ldap.deleteRDN"); ctx.rename("cn=Claude User, ou=NewHires", "cn=C. User,ou=NewHires"); // Check that we are back at our original setup System.out.println(ctx.getAttributes("cn=C. User,ou=NewHires")); // Close the context when we're done ctx.close(); } catch (NamingException e) { e.printStackTrace(); } }
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 2 s.com*/ // 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.projectforge.business.ldap.LdapDao.java
public void move(final DirContext ctx, final T obj, final String newOrganizationalUnit) throws NamingException { final Object id = getId(obj); // The dn is may-be changed, so find the original dn by id: final T origObject = findById(id, obj.getOrganizationalUnit()); if (origObject == null) { throw new RuntimeException("Object with id " + id + " not found in search base '" + StringHelper.listToString(",", obj.getOrganizationalUnit()) + "'. Can't move the object: " + obj);//from ww w. ja v a 2 s . c o m } final String ou = LdapUtils.getOrganizationalUnit(newOrganizationalUnit); final String origOu = LdapUtils.getOu(origObject.getOrganizationalUnit()); if (StringUtils.equals(origOu, ou) == false) { log.info("Move object with id '" + obj.getId() + "' from '" + origOu + "' to '" + ou); final String dnIdentifier = buildDnIdentifier(obj); ctx.rename(dnIdentifier + "," + origOu, dnIdentifier + "," + ou); } }
From source file:org.projectforge.business.ldap.LdapDao.java
public void rename(final DirContext ctx, final T obj, final T oldObj) throws NamingException { final String newDnIdentifier = buildDnIdentifier(obj); final String oldDnIdentifier = buildDnIdentifier(oldObj); if (StringUtils.equals(newDnIdentifier, oldDnIdentifier) == true) { // Nothing to rename. return;/* w w w. jav a 2 s . c o m*/ } final Object id = getId(obj); // The dn is may-be changed, so find the original dn by id: final T origObject = findById(id, obj.getOrganizationalUnit()); if (origObject == null) { throw new RuntimeException("Object with id " + id + " not found in search base '" + StringHelper.listToString(",", obj.getOrganizationalUnit()) + "'. Can't rename the object: " + obj); } final String ou = LdapUtils.getOu(origObject.getOrganizationalUnit()); log.info("Rename object with id '" + obj.getId() + "' from '" + oldDnIdentifier + "' to '" + newDnIdentifier); ctx.rename(oldDnIdentifier + "," + ou, newDnIdentifier + "," + ou); }
From source file:org.springframework.ldap.core.LdapTemplate.java
public void rename(final Name oldDn, final Name newDn) { executeReadWrite(new ContextExecutor() { public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException { ctx.rename(oldDn, newDn); return null; }// w ww .j a v a 2 s .co m }); }
From source file:org.springframework.ldap.core.LdapTemplate.java
public void rename(final String oldDn, final String newDn) { executeReadWrite(new ContextExecutor() { public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException { ctx.rename(oldDn, newDn); return null; }//from w w w . j a v a 2 s . com }); }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * This method overwrites the method in LDAPUserStoreManager. This implements the functionality * of updating user's profile information in LDAP user store. * * @param userName//from w w w. j a v a 2 s . c om * @param claims * @param profileName * @throws org.wso2.carbon.user.core.UserStoreException */ @Override public void doSetUserClaimValues(String userName, Map<String, 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); // if user name contains domain name, remove domain name String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR); if (userNames.length > 1) { userName = userNames[1]; } userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; boolean cnModified = false; String cnValue = null; try { 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); } if (profileName == null) { profileName = UserCoreConstants.DEFAULT_PROFILE; } if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) { claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION); } try { Attributes updatedAttributes = new BasicAttributes(true); String domainName = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > -1 ? userName.split(UserCoreConstants.DOMAIN_SEPARATOR)[0] : realmConfig.getUserStoreProperty(UserStoreConfigConstants.DOMAIN_NAME); for (Map.Entry<String, String> claimEntry : claims.entrySet()) { String claimURI = claimEntry.getKey(); // if there is no attribute for profile configuration in LDAP, // skip updating it. if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) { continue; } // get the claimMapping related to this claimURI String attributeName = getClaimAtrribute(claimURI, userName, null); //remove user DN from cache if changing username attribute if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) { userCache.remove(userName); } // if mapped attribute is CN, then skip treating as a modified // attribute - // it should be an object rename if ("CN".toLowerCase().equals(attributeName.toLowerCase())) { cnModified = true; cnValue = claimEntry.getValue(); continue; } Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) { currentUpdatedAttribute.clear(); } else { if (claimEntry.getValue() != null) { String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (claimEntry.getValue().contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(claimEntry.getValue()); } } else { currentUpdatedAttribute.add(claimEntry.getValue()); } } 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); if (cnModified && cnValue != null) { subDirContext.rename(returnedUserEntry, "CN=" + escapeSpecialCharactersForDN(cnValue)); } } 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.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 {/*from w ww .j av a2s. 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 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); } }