Example usage for javax.naming.directory DirContext getAttributes

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

Introduction

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

Prototype

public Attributes getAttributes(String name) throws NamingException;

Source Link

Document

Retrieves all of the attributes associated with a named object.

Usage

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

/**
 * Get next free uidNumber.//from  w ww  .j av 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.//from   www  .j av a2s . c  om
 */
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

private boolean isPasswordCorrectForAuthWithoutTLS(Hashtable<String, String> env, User user, String password) {
    if (ConfigCore.getBooleanParameter(ParameterCore.LDAP_USE_SIMPLE_AUTH, false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
        // TODO: test for password
    } else {//  w w  w.j  a  v a 2 s . c o m
        env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user));
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    logger.debug("ldap environment set");

    try {
        logger.debug("start classic ldap authentication");
        logger.debug("user DN is {}", buildUserDN(user));

        if (Objects.isNull(ConfigCore.getParameter(ParameterCore.LDAP_ATTRIBUTE_TO_TEST))) {
            logger.debug("ldap attribute to test is null");
            DirContext ctx = new InitialDirContext(env);
            ctx.close();
            return true;
        } else {
            logger.debug("ldap attribute to test is not null");
            DirContext ctx = new InitialDirContext(env);

            Attributes attrs = ctx.getAttributes(buildUserDN(user));
            Attribute la = attrs.get(ConfigCore.getParameter(ParameterCore.LDAP_ATTRIBUTE_TO_TEST));
            logger.debug("ldap attributes set");
            String test = (String) la.get(0);
            if (test.equals(ConfigCore.getParameter(ParameterCore.LDAP_VALUE_OF_ATTRIBUTE))) {
                logger.debug("ldap ok");
                ctx.close();
                return true;
            } else {
                logger.debug("ldap not ok");
                ctx.close();
                return false;
            }
        }
    } catch (NamingException e) {
        logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e);
        return false;
    }
}

From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java

boolean isLdapValid(final Credentials credentials) throws RepositoryException {
    LdapUser ldapUser = getLdapAuthData(credentials);
    if (ldapUser != null) {
        Hashtable<String, String> authEnv = new Hashtable<String, String>(11);
        //String dn = "uid=" + ldapUser.getUserName() + "," + ldapBase;
        String dn = StringUtils.replace(ldapBase, "${userName}", ldapUser.getUserName());
        authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        authEnv.put(Context.PROVIDER_URL, ldapUrl);
        authEnv.put(Context.SECURITY_AUTHENTICATION, ldapAuthenticationType);
        authEnv.put(Context.SECURITY_PRINCIPAL, dn);
        authEnv.put(Context.SECURITY_CREDENTIALS, ldapUser.getPassword());
        try {/*from w  w  w . j  a v a2  s . c  o  m*/
            DirContext ctx = new InitialDirContext(authEnv);
            Attributes attributes = ctx.getAttributes(dn);
            ldapUser.setAttributes(attributes);
            return true;
        } catch (AuthenticationException authEx) {
            return false;

        } catch (NamingException namEx) {
            throw new RepositoryException("Ldap Error:" + namEx.getExplanation());
        }
    }
    // no authdata, not valid
    return false;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@SuppressWarnings("unchecked")
protected List<String> getMandatoryAttributes(Attribute objectClassesAttribute) throws DirectoryException {
    try {/*from  ww  w .  j ava 2  s  .  c  om*/
        List<String> mandatoryAttributes = new ArrayList<String>();

        DirContext schema = dirContext.getSchema("");
        List<String> objectClasses = new ArrayList<String>();
        if (objectClassesAttribute == null) {
            // use the creation classes as reference schema for this entry
            objectClasses.addAll(Arrays.asList(getDirectory().getDescriptor().getCreationClasses()));
        } else {
            // introspec the objectClass definitions to find the mandatory
            // attributes for this entry
            NamingEnumeration<Object> values = null;
            try {
                values = (NamingEnumeration<Object>) objectClassesAttribute.getAll();
                while (values.hasMore()) {
                    objectClasses.add(values.next().toString().trim());
                }
            } catch (NamingException e) {
                throw new DirectoryException(e);
            } finally {
                if (values != null) {
                    values.close();
                }
            }
        }
        objectClasses.remove("top");
        for (String creationClass : objectClasses) {
            Attributes attributes = schema.getAttributes("ClassDefinition/" + creationClass);
            Attribute attribute = attributes.get("MUST");
            if (attribute != null) {
                NamingEnumeration<String> values = (NamingEnumeration<String>) attribute.getAll();
                try {
                    while (values.hasMore()) {
                        String value = values.next();
                        mandatoryAttributes.add(value);
                    }
                } finally {
                    values.close();
                }
            }
        }
        return mandatoryAttributes;
    } catch (NamingException e) {
        throw new DirectoryException("getMandatoryAttributes failed", e);
    }
}

From source file:org.springframework.ldap.core.LdapTemplate.java

public Object lookup(final Name dn, final AttributesMapper mapper) {
    return executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            Attributes attributes = ctx.getAttributes(dn);
            return mapper.mapFromAttributes(attributes);
        }/*from   w  w w  .j a va 2  s.c  o m*/
    });
}

From source file:org.springframework.ldap.core.LdapTemplate.java

public Object lookup(final String dn, final AttributesMapper mapper) {

    return executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            Attributes attributes = ctx.getAttributes(dn);
            return mapper.mapFromAttributes(attributes);
        }/*from   w  w w  . j  a va  2  s  . co  m*/
    });
}

From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java

public Person findByPrimaryKey(String country, String company, String fullname) {

    DirContext ctx = createAnonymousContext();
    String dn = buildDn(country, company, fullname);
    try {/*  w w w  . j  a  v  a2s  .c  o  m*/
        Attributes attributes = ctx.getAttributes(dn);
        return mapToPerson(dn, attributes);
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Did not find entry with primary key '" + dn + "'", e);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
}

From source file:org.webterm.core.plugin.authentication.LdapAuthentication.java

/**
 * Attribute reader/*from   www .j  av a2 s .c  om*/
 * 
 * @param username User name
 * @return Attribute password associated with the login.
 */
public Attribute fetch(final String username) {
    Attribute pwd = null; // NOPMD - init
    if (StringUtils.isNotBlank(username)) {
        try {
            final DirContext obj = (DirContext) this.ldapContext
                    .lookup(this.attrUser + "=" + username + "," + this.baseDn); //$NON-NLS-1$ //$NON-NLS-2$
            final Attributes attributes = obj.getAttributes(ConstString.EMPTY);
            pwd = attributes.get(this.attrPwd);
        } catch (Exception ex) {
            LOG.error(ex, ex);
        }
    }
    return pwd;
}

From source file:pl.umk.mat.zawodyweb.ldap.LdapConnector.java

/**
 * Check user password and return that user
 *
 * Example of LDAP data://from  w ww.j ava  2  s.c  o m
 * <pre>
 * dn: uid=faramir,ou=People,ou=int,dc=mat,dc=uni,dc=torun,dc=pl
 * objectClass: top
 * objectClass: account
 * objectClass: posixAccount
 * objectClass: shadowAccount
 * objectClass: radiusprofile
 * objectClass: sambaSamAccount
 * dialupAccess: yes
 * uid: faramir
 * cn: Marek Nowicki
 * loginShell: /bin/tcsh
 * uidNumber: 30030
 * sambaSID: S-1-30030
 * gecos: Marek Nowicki, doktorant Info.
 * gidNumber: 160
 * homeDirectory: /studdok/faramir
 * radiusSimultaneousUse: 1</pre>
 * @param login login
 * @param pass user password
 * @return Users if user found and password is OK or null if anything failed
 */
public static Users retieveUser(String login, String pass) {
    if (pass == null || pass.isEmpty() || login == null || login.isEmpty() || login.contains(",")) {
        return null;
    }

    Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
    String dn = String.format("uid=%s,%s", login, baseDN);

    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, ldapURL);
    ldapEnv.put(Context.SECURITY_PRINCIPAL, dn);
    ldapEnv.put(Context.SECURITY_CREDENTIALS, pass);

    try {
        DirContext authContext = new InitialDirContext(ldapEnv);
        Attributes userAttributes = authContext.getAttributes(dn);

        if (userAttributes.get("uidNumber") == null) {
            return null;
        }

        Attribute cn = userAttributes.get("cn"); // commonName - eg. Marek Nowicki

        String name = ((String) cn.get());
        String firstName = name;
        String lastName = "(LDAP)";

        int index = name.lastIndexOf(" ");
        if (index > 0) {
            firstName = name.substring(0, index).trim();
            lastName = name.substring(index + 1).trim();
        }

        Users user = new Users();

        user.setLogin(login);
        user.setFirstname(firstName);
        user.setLastname(lastName);
        user.setEmail(login + emailSuffix);

        return user;
    } catch (AuthenticationException ex) {
    } catch (NamingException ex) {
    } catch (NullPointerException ex) {
    } catch (ClassCastException ex) {
    } catch (Exception ex) {
        log.fatal("LDAP Exception:", ex);
    }
    return null;
}