Example usage for javax.naming.directory DirContext REPLACE_ATTRIBUTE

List of usage examples for javax.naming.directory DirContext REPLACE_ATTRIBUTE

Introduction

In this page you can find the example usage for javax.naming.directory DirContext REPLACE_ATTRIBUTE.

Prototype

int REPLACE_ATTRIBUTE

To view the source code for javax.naming.directory DirContext REPLACE_ATTRIBUTE.

Click Source Link

Document

This constant specifies to replace an attribute with specified values.

Usage

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationUpdate.java

private void updateOrg() throws NameNotFoundException, AASUnauthorizedException, AttributeModificationException,
        ExecutionException {//from w  w  w. j a  v a 2s  .  c  o m
    boolean vChange = false;
    InitialLdapContext vCtx = null;
    try {

        if (this._oldOrganisation == null) {
            LOG.log(Level.WARNING, "No such organization ''{0}'' with oid: ''{1}''.",
                    new Object[] { this._organisation.getDisplayName(), this._organisation.getOIDs() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        GeoAdresse vGeoAdresse;
        String vLocalDispalyName = null;
        if (_submit != null) { // hier ist "GeoLocationDisplayName" breits ausgefhrt
            try {
                vGeoAdresse = _submit.get(10, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._organisation.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._organisation.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._organisation.getAddress()
                            .setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._organisation.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            }
        } else if (_submitGeoLocDisplayName != null) {
            try {
                vLocalDispalyName = _submitGeoLocDisplayName.get(5, TimeUnit.SECONDS);
                this._organisation.getAddress().setLocationDisplayName(vLocalDispalyName);
                //LOG.info("LocalDisplayName='" + vLocalDispalyName + "'" + vLocalDispalyName + "'");
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (ExecutionException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            }

        }

        LOG.info("newOIDs: '" + this._organisation.getOIDs() + "'");
        LOG.info("oldOIDs: '" + this._oldOrganisation.getOIDs() + "'");

        if (this._organisation.getOrgRDN() == null) {
            // -- Ansonsten eine nicht gesetzte RDN kann zum Knall fhren...
            this._organisation.setOrgRDN(this._oldOrganisation.getOrgRDN());
        } else if (!this._organisation.getOrgRDN().equals(this._oldOrganisation.getOrgRDN())) {
            // -- Hier ist etwas faul...
            LOG.log(Level.WARNING,
                    "The organization ''{0}'' has RDN: ''{1}'', but there exist an organization ''{0}'' with RDN: ''{2}''!",
                    new Object[] { this._organisation.getId(), this._organisation.getOrgRDN(),
                            this._oldOrganisation.getOrgRDN() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        if (this.isPrivilegesUpdate()) {
            Set<PrivilegeEnum> removePrivileges = this.privilegeDiff(this._organisation.getPrivilegesSet(),
                    this._oldOrganisation.getPrivilegesSet());
            Set<PrivilegeEnum> addPrivileges = this.privilegeDiff(this._oldOrganisation.getPrivilegesSet(),
                    this._organisation.getPrivilegesSet());
            if (!removePrivileges.isEmpty() || !addPrivileges.isEmpty()) {
                vChange = true;
                for (PrivilegeEnum p : removePrivileges) {
                    ThreadSinglePrivilegeDelete threadSinglePrivilegeDelete = new ThreadSinglePrivilegeDelete(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeDelete.call();
                }
                for (PrivilegeEnum p : addPrivileges) {
                    ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeCreate.call();
                }
            }
        }

        Attributes orgAttributes = new BasicAttributes(true);
        Attributes orgRemoveAttributes = new BasicAttributes(true);

        if (vChange = this.convertOrganizationToLdapOrgAttrsForUpdate(this._organisation, this._oldOrganisation,
                orgAttributes, orgRemoveAttributes, getPerformer())) {

            // -- If any changes, the status is set to 'revised'
            //    but not if status will be explicitly changed or by a update operation on Licenses directory
            if (!isChangeOfStatus() && !isUpdatingOfLicensedOrgs()) {
                if ((ConstEnumOrgStatus.approved.equals(this._organisation.getStatus()))) {
                    // -- ...then go retrospectively into "revised" status:
                    this._organisation.setStatus(ConstEnumOrgStatus.revised);

                    orgAttributes.put(Constants.ldap_ddbOrg_Status,
                            String.valueOf(this._organisation.getStatus().name()));
                }
            }
        }
        // ---------------------------------------------------------------------
        if (vChange) {

            // -- Save changes to the corresponding directory:
            StringBuilder vOrgEntryDN = (isUpdatingOfLicensedOrgs()
                    ? this.getLicensedOrgsDN(this._organisation.getOIDs())
                    : this.getOrgDN(this._organisation.getOIDs()));
            LOG.log(Level.INFO, "DEBUG-Info: destination OrgEntryDN = '" + vOrgEntryDN + "'");

            vCtx = LDAPConnector.getSingletonInstance().takeCtx();
            if (orgRemoveAttributes.size() > 0) {
                vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REMOVE_ATTRIBUTE, orgRemoveAttributes);
            }
            vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REPLACE_ATTRIBUTE, orgAttributes);
        } else {
            throw new AttributeModificationException(
                    "Not modified: oid = '" + this._organisation.getOIDs() + "'");
        }

    } catch (RejectedExecutionException ex) {
        LOG.log(Level.SEVERE, "RejectedExecutionException\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.WARNING, null, ex);
        throw ex;
    } catch (AttributeModificationException ex) {
        LOG.log(Level.WARNING, "AttributeModificationException\n{0}", ex.getMessage());
        // !!!!AttributeModificationException extends NamingExeption:
        //throw ex;
        throw new AttributeModificationException(ex.getMessage());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "NamingException\n{0}", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", 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  www  . j a  v  a  2  s. c om*/
        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:openscim.restful.server.resources.user.ldap.LdapUserResource.java

@Override
public Response updateUser(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 = 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 w ww .  ja  v a2s  . c o m*/

        try {
            // retrieve the user
            User lookedupUser = (User) ldapTemplate.lookup(dn, mapper);

            // check if the user was found
            if (lookedupUser == null) {
                logger.debug("Resource " + dn + " not found");

                // user not found, return an error message
                return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND,
                        "Resource " + uid + " not found");
            }

            List<ModificationItem> items = new ArrayList<ModificationItem>();

            // get the uid attribute name
            //String uidAtttributeName = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE, UserAttributesMapper.DEFAULT_UID_ATTRIBUTE);

            // build a uid modification
            //if(user.getId() != null)
            //{
            //   Attribute uidAttribute = new BasicAttribute(uidAtttributeName, user.getId());            
            //   ModificationItem uidItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uidAttribute);
            //   items.add(uidItem);
            //}

            // get the display name attribute name
            String displayAtttributeName = properties.getProperty(UserAttributesMapper.DISPLAYNAME_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_DISPLAYNAME_ATTRIBUTE);

            // build a cn modification
            if (user.getDisplayName() != null) {
                Attribute cnAttribute = new BasicAttribute(displayAtttributeName, user.getDisplayName());
                ModificationItem cnItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, cnAttribute);
                items.add(cnItem);
            }

            // build names modification
            if (user.getName() != null) {
                // 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);

                if (user.getName().getFamilyName() != null) {
                    Attribute snAttribute = new BasicAttribute(surnameAtttributeName,
                            user.getName().getFamilyName());
                    ModificationItem snItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, snAttribute);
                    items.add(snItem);
                }

                if (user.getName().getGivenName() != null) {
                    Attribute gnAttribute = new BasicAttribute(givenAtttributeName,
                            user.getName().getGivenName());
                    ModificationItem gnItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, gnAttribute);
                    items.add(gnItem);
                }
            }

            // set the emails
            if (user.getEmails() != null) {
                // get the email attribute name
                String mailAtttributeName = properties.getProperty(UserAttributesMapper.MAIL_ATTRIBUTE,
                        UserAttributesMapper.DEFAULT_MAIL_ATTRIBUTE);

                Attribute emailAttribute = new BasicAttribute(mailAtttributeName);
                List<PluralAttribute> emails = user.getEmails().getEmail();
                for (PluralAttribute email : emails) {
                    emailAttribute.add(email.getValue());
                }
                ModificationItem emailItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, emailAttribute);
                items.add(emailItem);
            }

            // set the telephones
            if (user.getPhoneNumbers() != null) {
                // get the telephone attribute name
                String telephoneAtttributeName = properties.getProperty(
                        UserAttributesMapper.TELEPHONE_ATTRIBUTE,
                        UserAttributesMapper.DEFAULT_TELEPHONE_ATTRIBUTE);

                Attribute telephoneAttribute = new BasicAttribute(telephoneAtttributeName);
                List<PluralAttribute> telephones = user.getPhoneNumbers().getPhoneNumber();
                for (PluralAttribute telephone : telephones) {
                    telephoneAttribute.add(telephone.getValue());
                }
                ModificationItem telephoneItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                        telephoneAttribute);
                items.add(telephoneItem);
            }

            // build a password modification
            if (user.getPassword() != null) {
                // get the password attribute name
                String passwordAtttributeName = properties.getProperty(UserAttributesMapper.PASSWORD_ATTRIBUTE,
                        UserAttributesMapper.DEFAULT_PASSWORD_ATTRIBUTE);

                Attribute passwordAttribute = new BasicAttribute(passwordAtttributeName, user.getPassword());
                ModificationItem passwordItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                        passwordAttribute);
                items.add(passwordItem);
            }

            // 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);

            // 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:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public boolean saveUserRole(String roleName, String username, DirContext context) throws MappingException {

    String groupName = findGroupName(roleName);

    if (groupName == null) {
        log.warn("no group found for role '{}", roleName);
        groupName = roleName;//from   w  ww  . j a va 2 s . c om
    }

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {
        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();
            Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember());
            if (attribute == null) {
                BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember());
                basicAttribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.ADD_ATTRIBUTE, basicAttribute) });
            } else {
                attribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) });
            }
            return true;
        }

        return false;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * change password of given user, needs old password for authentication.
 *
 * @param inUser//from   w  w w. j  a v  a  2  s . c om
 *            User object
 * @param inOldPassword
 *            String
 * @param inNewPassword
 *            String
 * @return boolean about result of change
 */
public boolean changeUserPassword(User inUser, String inOldPassword, String inNewPassword)
        throws NoSuchAlgorithmException {
    MD4 digester = new MD4();
    Hashtable<String, String> env = getLdapConnectionSettings();
    if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) {
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

        try {
            DirContext ctx = new InitialDirContext(env);

            /*
             * Encryption of password and Base64-Encoding
             */
            MessageDigest md = MessageDigest.getInstance(ConfigCore.getParameter("ldap_encryption", "SHA"));
            md.update(inNewPassword.getBytes(StandardCharsets.UTF_8));
            String digestBase64 = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8);
            ModificationItem[] mods = new ModificationItem[4];

            /*
             * UserPasswort-Attribut ndern
             */
            BasicAttribute userpassword = new BasicAttribute("userPassword",
                    "{" + ConfigCore.getParameter("ldap_encryption", "SHA") + "}" + digestBase64);

            /*
             * LanMgr-Passwort-Attribut ndern
             */
            BasicAttribute lanmgrpassword = null;
            try {
                lanmgrpassword = new BasicAttribute("sambaLMPassword",
                        LdapUser.toHexString(LdapUser.lmHash(inNewPassword)));
                // TODO: Don't catch super class exception, make sure that
                // the password isn't logged here
            } catch (Exception e) {
                logger.error(e);
            }

            /*
             * NTLM-Passwort-Attribut ndern
             */
            BasicAttribute ntlmpassword = null;
            try {
                byte hmm[] = digester.digest(inNewPassword.getBytes("UnicodeLittleUnmarked"));
                ntlmpassword = new BasicAttribute("sambaNTPassword", LdapUser.toHexString(hmm));
            } catch (UnsupportedEncodingException e) {
                // TODO: Make sure that the password isn't logged here
                logger.error(e);
            }

            BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet",
                    String.valueOf(System.currentTimeMillis() / 1000l));

            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userpassword);
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrpassword);
            mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmpassword);
            mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet);
            ctx.modifyAttributes(getUserDN(inUser), mods);

            // Close the context when we're done
            ctx.close();
            return true;
        } catch (NamingException e) {
            logger.debug("Benutzeranmeldung nicht korrekt oder Passwortnderung nicht mglich", e);
            return false;
        }
    }
    return false;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean resetPassword(String cn, String newPassword) {
    DirContext ctx = null;/*  www  . ja va 2  s .  c  o  m*/
    try {
        ctx = getMainAuthContext();

        ModificationItem[] modItems = new ModificationItem[1];
        modItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute("userPassword", newPassword));

        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        ctx.modifyAttributes("cn=" + cn + "," + 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 updatePassword(LDAPUser user, String newPassword) {
    DirContext ctx = null;// ww w  .j  a va  2  s.  c  om
    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:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

/**
 * set attributes of given resource.//from ww  w.j  a  v a2 s .  c o m
 * 
 * @param scope
 *            scope
 * @param id
 *            id of resource
 * @param attributeNames
 *            attribute-names and values to set
 * 
 * @throws NamingException
 * @throws IllegalAccessException
 */
public void setResourceAttributes(Scope scope, String entryDn, Map<String, String> attributes)
        throws NamingException, IllegalAccessException {
    InitialLdapContext ctx = null;
    try {
        ctx = LDAPConnector.getSingletonInstance().takeCtx();
        BasicAttributes saveAttributes = new BasicAttributes(true);
        for (Entry<String, String> entry : attributes.entrySet()) {
            saveAttributes.put(new BasicAttribute(entry.getKey(), entry.getValue()));
        }
        ctx.modifyAttributes(entryDn, DirContext.REPLACE_ATTRIBUTE, saveAttributes);
    } finally {
        if (ctx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(ctx);
            } catch (IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
    }
}

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;/*from  w ww  .  ja va  2  s . co  m*/
        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:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

/**
 * set modification-properties in LDAP.//w ww  .  j  a v a2s  .  c o m
 * 
 * @param isCreate
 *            if also createProperties should be set.
 * @param performer
 *            performer.
 * @param id
 *            id to set properties for.
 * @param scope
 *            scope.
 * 
 * @return
 * @throws
 */
public void setModificationPropertiesInLdap(boolean isCreate, AasPrincipal performer, String id, Scope scope)
        throws NamingException, IllegalAccessException {
    String propertiesAttName = null;
    if (scope == Scope.PERSON) {
        propertiesAttName = Constants.ldap_ddbPerson_Properties;
    } else if (scope == Scope.ORGANIZATION) {
        propertiesAttName = Constants.ldap_ddbOrg_Properties;
    } else {
        throw new IllegalAccessException("scope does not match");
    }

    Map<String, String> attributes = getResourceAttributes(scope, id,
            new String[] { propertiesAttName, Constants.ldap_ddb_EntryDN });
    DdbProperties properties = null;
    String entryDn = null;
    if (attributes != null && StringUtils.isNotBlank(attributes.get(Constants.ldap_ddb_EntryDN))) {
        if (StringUtils.isNotBlank(attributes.get(propertiesAttName))) {
            properties = serializer.deserialize(attributes.get(propertiesAttName));
        }
        properties = PropertiesHelper.setModificationProperties(properties, isCreate, performer);
        entryDn = attributes.get(Constants.ldap_ddb_EntryDN);
    } else {
        throw new NameNotFoundException("entry with id=" + id + " not found");
    }
    InitialLdapContext ctx = null;
    try {
        ctx = LDAPConnector.getSingletonInstance().takeCtx();
        Attributes saveAttributes = new BasicAttributes(true);
        saveAttributes.put(new BasicAttribute(propertiesAttName, serializer.serialize(properties)));
        ctx.modifyAttributes(entryDn, DirContext.REPLACE_ATTRIBUTE, saveAttributes);
    } finally {
        if (ctx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(ctx);
            } catch (IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
    }

}