Example usage for javax.naming.directory DirContext close

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

Introduction

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

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this context.

Usage

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn/*ww w. j a  va2  s . c  o m*/
 * @param type
 * @param rdnValue
 */
public void removeRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());

        ModificationItem[] modifications = new ModificationItem[1];

        Attribute attribute = new BasicAttribute(type.toString(), rdnValue);

        modifications[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute);

        ctx.modifyAttributes("", modifications);

    }

    catch (NamingException e) {
        throw new RuntimeException(type.toString() + "=" + rdnValue + "," + rootDn.toString(), e);
    }

    finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.debug(e);
            }
        }
    }

}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

private void addNewSchema() throws NamingException {
    DirContext ctx = getLdapContext();
    try {//from  ww w  .j  av  a 2s .c  o  m
        Attributes atAttrs = new BasicAttributes(true);
        atAttrs.put("attributeTypes",
                "( 1.2.840.113556.1.4.8 NAME 'userAccountControl' DESC 'Flags that control the behavior of the user account' EQUALITY integerMatch SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )");
        ctx.modifyAttributes("cn=schema", DirContext.ADD_ATTRIBUTE, atAttrs);
        Attributes ocAttrs = new BasicAttributes(true);
        ocAttrs.put("objectClasses",
                "( 1.2.840.113556.1.5.9 NAME 'user' SUP inetOrgPerson STRUCTURAL MAY (userAccountControl) )");
        ctx.modifyAttributes("cn=schema", DirContext.ADD_ATTRIBUTE, ocAttrs);
    } finally {
        ctx.close();
    }
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

public IAccount getUser(String uid) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration searchResultEnum;
    Map filters = new HashMap();

    String uidAttrName = "uid";
    if (this.propAttrMap.containsKey("user_id")) {
        try {//  w w  w .j  a v a 2 s . com
            uidAttrName = (String) this.propAttrMap.get("user_id");
        } catch (Exception ex) {
            //ignore
        }
    }
    if (uid != null && !"".equals(uid))
        filters.put(uidAttrName, uid);

    DirContext context = null;
    try {
        context = this.initContext();
        searchResultEnum = context.search(userBase, buildFilterByUid(filters), searchControls);
        //roop of retrieval result

        while (searchResultEnum.hasMore()) {
            SearchResult searchResult = (SearchResult) searchResultEnum.next();

            String dn = searchResult.getName() + "," + userBase;
            LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes());
            setGroup(context, user);

            return user;
        }

        return null;
    } finally {
        if (context != null)
            context.close();
    }
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

public List searchUser(Map searchConditionMap) throws Exception {
    Map confitionForBase = getConditionForSearchBase(searchConditionMap);

    Collection users = new TreeSet(new Comparator() {

        public int compare(Object o1, Object o2) {
            try {
                LDAPAccount user1 = (LDAPAccount) o1;
                LDAPAccount user2 = (LDAPAccount) o2;

                return user1.getUid().compareTo(user2.getUid());
            } catch (Exception e) {
                log.error("", e);
                return 0;
            }//from w ww  .java2  s .  c  o m
        }

    });

    DirContext context = null;
    try {
        context = this.initContext();

        Map groupFilterMap = (Map) confitionForBase.get(GROUP_SEARCH_BASE_KEY);
        Collection groupMembers = null;
        if (groupFilterMap != null) {
            groupMembers = searchGroupMember(context, groupFilterMap);
        }
        Map userFilterMap = (Map) confitionForBase.get(USER_SEARCH_BASE_KEY);

        if (userFilterMap != null) {
            users = searchFromUsers(context, userFilterMap);

            if (groupMembers != null) {
                users.retainAll(groupMembers);
            }
        } else if (groupMembers != null) {
            users.addAll(groupMembers);
        }

        List result = new ArrayList();
        for (Iterator it = users.iterator(); it.hasNext();) {
            LDAPAccount user = (LDAPAccount) it.next();
            if (user.getGroupName() == null)
                setGroup(context, user);
            result.add(user);
        }

        return result;
    } finally {
        context.close();
    }

}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * create new user in LDAP-directory./*w w  w.j  a  va 2s.  co  m*/
 *
 * @param user
 *            User object
 * @param password
 *            String
 */
public void createNewUser(User user, String password)
        throws NamingException, NoSuchAlgorithmException, IOException {

    if (!user.getLdapGroup().getLdapServer().isReadOnly()) {
        Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(
                user.getLdapGroup().getLdapServer());

        LdapUser ldapUser = new LdapUser();
        ldapUser.configure(user, password, getNextUidNumber(user.getLdapGroup().getLdapServer()));
        DirContext ctx = new InitialDirContext(ldapEnvironment);
        ctx.bind(buildUserDN(user), ldapUser);
        ctx.close();
        setNextUidNumber(user.getLdapGroup().getLdapServer());
        Helper.setMessage(
                Helper.getTranslation("ldapWritten") + " " + ServiceManager.getUserService().getFullName(user));
        /*
         * check if HomeDir exists, else create it
         */
        logger.debug("HomeVerzeichnis pruefen");

        URI homePath = getUserHomeDirectory(user);

        if (!new File(homePath).exists()) {
            logger.debug("HomeVerzeichnis existiert noch nicht");
            ServiceManager.getFileService().createDirectoryForUser(homePath, user.getLogin());
            logger.debug("HomeVerzeichnis angelegt");
        } else {
            logger.debug("HomeVerzeichnis existiert schon");
        }
    } else {
        Helper.setMessage("ldapIsReadOnly");
    }
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Retrieve home directory of given user.
 *
 * @param user//from   w  ww. j  a  v  a  2 s. c o  m
 *            User object
 * @return path as URI
 */
public URI getUserHomeDirectory(User user) {
    String userFolderBasePath = ConfigCore.getParameter(ParameterCore.DIR_USERS);

    if (ConfigCore.getBooleanParameterOrDefaultValue(ParameterCore.LDAP_USE_LOCAL_DIRECTORY)) {
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    }
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (ConfigCore.getBooleanParameterOrDefaultValue(ParameterCore.LDAP_USE_TLS)) {
        return getUserHomeDirectoryWithTLS(env, userFolderBasePath, user);
    }

    if (ConfigCore.getBooleanParameter(ParameterCore.LDAP_USE_SIMPLE_AUTH, false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx;
    URI userFolderPath = null;
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute ldapAttribute = attrs.get("homeDirectory");
        userFolderPath = URI.create((String) ldapAttribute.get(0));
        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

    if (Objects.nonNull(userFolderPath) && !userFolderPath.isAbsolute()) {
        if (userFolderPath.getPath().startsWith("/")) {
            userFolderPath = ServiceManager.getFileService().deleteFirstSlashFromPath(userFolderPath);
        }
        return Paths.get(userFolderBasePath, userFolderPath.getRawPath()).toUri();
    } else {
        return userFolderPath;
    }
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Check if User already exists on system.
 *
 * @param user//from www.  j  av  a 2  s . c  om
 *            The User.
 * @return result as boolean
 */
public boolean isUserAlreadyExists(User user) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(
            user.getLdapGroup().getLdapServer());
    DirContext ctx;
    boolean result = false;
    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search(buildUserDN(user), matchAttrs);
        result = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            logger.debug(">>>{}", sr.getName());
            Attributes attrs = sr.getAttributes();
            String givenName = getStringForAttribute(attrs, "givenName");
            String surName = getStringForAttribute(attrs, "sn");
            String mail = getStringForAttribute(attrs, "mail");
            String cn = getStringForAttribute(attrs, "cn");
            String homeDirectory = getStringForAttribute(attrs, "homeDirectory");

            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(homeDirectory);
        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }
    return result;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Get next free uidNumber.//w w w.ja v a 2 s . co  m
 *
 * @return next free uidNumber
 */
private String getNextUidNumber(LdapServer ldapServer) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer);
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern());
        Attribute la = attrs.get("uidNumber");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        Helper.setErrorMessage(e.getMessage(), logger, e);
    }
    return rueckgabe;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Set next free uidNumber./*w  w w . j  a  v a  2  s  .  c o  m*/
 */
private void setNextUidNumber(LdapServer ldapServer) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer);
    DirContext ctx;

    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern());
        Attribute la = attrs.get("uidNumber");
        String oldValue = (String) la.get(0);
        int bla = Integer.parseInt(oldValue) + 1;

        BasicAttribute attrNeu = new BasicAttribute("uidNumber", String.valueOf(bla));
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attrNeu);
        ctx.modifyAttributes(ldapServer.getNextFreeUnixIdPattern(), mods);

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * change password of given user, needs old password for authentication.
 *
 * @param user/* w w  w.j a  v a 2  s.c o m*/
 *            User object
 * @param inNewPassword
 *            String
 * @return boolean about result of change
 */
public boolean changeUserPassword(User user, String inNewPassword) throws NoSuchAlgorithmException {
    JDKMessageDigest.MD4 digester = new JDKMessageDigest.MD4();
    PasswordEncryption passwordEncryption = user.getLdapGroup().getLdapServer().getPasswordEncryption();
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (!user.getLdapGroup().getLdapServer().isReadOnly()) {
        try {
            ModificationItem[] mods = new ModificationItem[4];

            // encryption of password and Base64-Encoding
            MessageDigest md = MessageDigest.getInstance(passwordEncryption.getTitle());
            md.update(inNewPassword.getBytes(StandardCharsets.UTF_8));
            String encryptedPassword = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8);

            // change attribute userPassword
            BasicAttribute userPassword = new BasicAttribute("userPassword",
                    "{" + passwordEncryption + "}" + encryptedPassword);
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword);

            // change attribute lanmgrPassword
            BasicAttribute lanmgrPassword = proceedPassword("sambaLMPassword", inNewPassword, null);
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrPassword);

            // change attribute ntlmPassword
            BasicAttribute ntlmPassword = proceedPassword("sambaNTPassword", inNewPassword, digester);
            mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmPassword);

            BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet",
                    String.valueOf(System.currentTimeMillis() / 1000L));
            mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet);

            DirContext ctx = new InitialDirContext(env);
            ctx.modifyAttributes(buildUserDN(user), 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;
}