List of usage examples for javax.naming.directory ModificationItem ModificationItem
public ModificationItem(int mod_op, Attribute attr)
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static boolean updatePassword(LDAPUser user, String newPassword) { DirContext ctx = null;/*from ww w . java2s . com*/ try { ctx = getAuthContext(user.getUsername(), user.getPassword()); ModificationItem[] modItems = new ModificationItem[1]; modItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", newPassword)); ResourceBundle rb = ResourceBundle.getBundle("ldap"); ctx.modifyAttributes("cn=" + user.getUsername() + "," + rb.getString("peopleRoot"), modItems); } catch (NamingException ex) { _log.error(ex); return false; } return true; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static boolean addMail(LDAPUser user, String newMail) { DirContext ctx = null;/*from w ww .j a va 2 s . co m*/ try { ctx = getAuthContext(user.getUsername(), user.getPassword()); ModificationItem[] modItems = new ModificationItem[1]; modItems[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("mail", newMail)); ResourceBundle rb = ResourceBundle.getBundle("ldap"); ctx.modifyAttributes("cn=" + user.getUsername() + "," + rb.getString("peopleRoot"), modItems); } catch (NamingException ex) { _log.error(ex); return false; } return true; }
From source file:openscim.restful.server.resources.user.ldap.LdapUserResource.java
@Override public Response changePassword(UriInfo uriInfo, String uid, 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 = uid;/* www. j a v a2 s . c om*/ 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) + "=" + uid + "," + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN, UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN); } try { // retrieve the user User lookedUser = (User) ldapTemplate.lookup(dn, mapper); // check if the user was found if (lookedUser == null) { logger.debug("Resource " + dn + " not found"); // user not found, return an error message return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + uid + " not found"); } // build a password modification Attribute passwordAttribute = new BasicAttribute("userPassword", user.getPassword()); ModificationItem passwordItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, passwordAttribute); // update the user password ldapTemplate.modifyAttributes(dn, new ModificationItem[] { passwordItem }); // password changed successfully return Response.status(HttpStatus.NO_CONTENT.getCode()).build(); } catch (Exception nException) { logger.debug("Resource " + dn + " not found"); nException.printStackTrace(System.out); //logger.debug(nException); // user not found, return an error message return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + uid + " 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 user ldap repository not configured"); } }
From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java
/** * Converts spml modifications to jndi modifications. * // w w w .j a v a2 s . c o m * @param modification the spml modification * @return the jndi modifications * @throws PspException if a psp error occurs */ protected List<ModificationItem> getDsmlMods(Modification modification) throws PspException { List<ModificationItem> mods = new ArrayList<ModificationItem>(); for (Object object : modification.getOpenContentElements(DSMLModification.class)) { DSMLModification dsmlModification = (DSMLModification) object; Attribute attribute = new BasicAttribute(dsmlModification.getName()); DSMLValue[] dsmlValues = dsmlModification.getValues(); for (DSMLValue dsmlValue : dsmlValues) { // for example, when <dsmlValue><dsmlValue/> and op is a replace if (!DatatypeHelper.isEmpty(dsmlValue.getValue())) { attribute.add(dsmlValue.getValue()); } } int op = -1; if (dsmlModification.getOperation().equals(ModificationMode.ADD)) { op = DirContext.ADD_ATTRIBUTE; } else if (dsmlModification.getOperation().equals(ModificationMode.DELETE)) { op = DirContext.REMOVE_ATTRIBUTE; } else if (dsmlModification.getOperation().equals(ModificationMode.REPLACE)) { op = DirContext.REPLACE_ATTRIBUTE; } else { throw new PspException("Unknown dsml modification operation : " + dsmlModification.getOperation()); } mods.add(new ModificationItem(op, attribute)); } return mods; }
From source file:CreateJavaSchema.java
/** * Writes schema modifications to the Active Directory schema immediately. *///from w w w . jav a 2 s . co m protected void flushADSchemaMods(DirContext rootCtx) throws NamingException { rootCtx.modifyAttributes("", new ModificationItem[] { new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("schemaUpdateNow", "1")) }); }
From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java
/** * Converts spml modifications to jndi modifications. * /*from w w w. j av a 2 s . c o m*/ * @param modification the spml modification * @return the jndi modifications * @throws PspException if a psp error occurs */ protected List<ModificationItem> getReferenceMods(Modification modification) throws PspException { List<ModificationItem> mods = new ArrayList<ModificationItem>(); Map<String, List<Reference>> references = PSPUtil.getReferences(modification.getCapabilityData()); if (references.isEmpty()) { return mods; } for (String typeOfReference : references.keySet()) { List<String> ids = new ArrayList<String>(); 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.equals(PSOReferencesDefinition.EMPTY_STRING)) { // id = ""; // } if (id == null) { id = ""; } ids.add(id); } } Attribute attribute = new BasicAttribute(typeOfReference); for (String id : ids) { attribute.add(id); } int op = -1; if (modification.getModificationMode().equals(ModificationMode.ADD)) { op = DirContext.ADD_ATTRIBUTE; } else if (modification.getModificationMode().equals(ModificationMode.DELETE)) { op = DirContext.REMOVE_ATTRIBUTE; } else if (modification.getModificationMode().equals(ModificationMode.REPLACE)) { op = DirContext.REPLACE_ATTRIBUTE; } else { throw new PspException("Unknown modification operation : " + modification.getModificationMode()); } mods.add(new ModificationItem(op, attribute)); } return mods; }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private String performOperationChangeUnicodePwd(String entryName, ParameterResolutionContext prc, Map paramValueMap) throws SenderException, ParameterException { ModificationItem[] modificationItems = new ModificationItem[2]; modificationItems[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", encodeUnicodePwd((String) paramValueMap.get("oldPassword")))); modificationItems[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", encodeUnicodePwd((String) paramValueMap.get("newPassword")))); DirContext dirContext = null; try {/*from w w w. ja v a2s . co m*/ dirContext = getDirContext(paramValueMap); dirContext.modifyAttributes(entryName, modificationItems); return DEFAULT_RESULT_CHANGE_UNICODE_PWD_OK; } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 19 LDAP_CONSTRAINT_VIOLATION Indicates that the attribute value specified in a modify, add, or modify DN operation violates constraints placed on the attribute. The constraint can be one of size or content (string only, no binary). // AD: // [LDAP: error code 19 - 0000052D: AtrErr: DSID-03191041, #1... if (e.getMessage().startsWith("[LDAP: error code 19 - ")) { if (log.isDebugEnabled()) log.debug("Operation [" + getOperation() + "] old password doesn't match or new password doesn't comply with policy for: " + entryName); return DEFAULT_RESULT_CHANGE_UNICODE_PWD_NOK; } else { storeLdapException(e, prc); throw new SenderException( "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e); } } finally { closeDirContext(dirContext); } }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Updates the password for an existing principal in a previously configured KDC * <p/>//from w ww . j ava 2s .co m * The implementation is specific to a particular type of KDC. * * @param principal a String containing the principal to update * @param password a String containing the password to set * @return an Integer declaring the new key number * @throws KerberosOperationException */ @Override public Integer setPrincipalPassword(String principal, String password) throws KerberosOperationException { if (!isOpen()) { throw new KerberosOperationException("This operation handler has not been opened"); } if (principal == null) { throw new KerberosOperationException("principal is null"); } if (password == null) { throw new KerberosOperationException("principal password is null"); } DeconstructedPrincipal deconstructPrincipal = createDeconstructPrincipal(principal); try { String dn = findPrincipalDN(deconstructPrincipal.getNormalizedPrincipal()); if (dn != null) { ldapContext.modifyAttributes(escapeDNCharacters(dn), new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", String.format("\"%s\"", password).getBytes("UTF-16LE"))) }); } else { throw new KerberosOperationException( String.format("Can not set password for principal %s: Not Found", principal)); } } catch (NamingException e) { throw new KerberosOperationException( String.format("Can not set password for principal %s: %s", principal, e.getMessage()), e); } catch (UnsupportedEncodingException e) { throw new KerberosOperationException("Unsupported encoding UTF-16LE", e); } return 0; }
From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportDsmlRunnable.java
/** * Processes a modify request./*from w w w . j a v a2 s .com*/ * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be <code>null</code>) */ private void processModifyRequest(ModifyRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor) { // Creating the modification items List<ModificationItem> modificationItems = new ArrayList<ModificationItem>(); for (Modification modification : request.getModifications()) { modificationItems.add(new ModificationItem(convertModificationOperation(modification.getOperation()), AttributeUtils.toJndiAttribute(modification.getAttribute()))); } // Executing the modify request browserConnection.getConnection().getConnectionWrapper().modifyEntry(request.getName().getName(), modificationItems.toArray(new ModificationItem[0]), getControls(request), monitor, null); // Creating the response if (batchResponseDsml != null) { ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml(codec); LdapResult ldapResult = modifyResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor(ldapResult, monitor, MessageTypeEnum.ADD_REQUEST); modifyResponseDsml.getLdapResult().setMatchedDn(request.getName()); batchResponseDsml.addResponse(modifyResponseDsml); } Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache(dn); if (e != null) { e.setAttributesInitialized(false); } }
From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportLdifRunnable.java
/** * Imports the LDIF record.//from www .j a v a 2s .c o m * * @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); } } }