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:nl.nn.adapterframework.ldap.LdapFindMemberPipe.java

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind,
        boolean recursiveSearch) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {//from  w  w  w. j a v a 2s .  com
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}

From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java

private boolean isMemberOf(DirContext ctx, String dnUser, String dnGroup) throws NamingException {
    DirContext lookedContext = (DirContext) (ctx.lookup(dnGroup));
    Attribute attrs = lookedContext.getAttributes("").get("member");
    for (int i = 0; i < attrs.size(); i++) {
        String foundMember = (String) attrs.get(i);
        if (foundMember.equalsIgnoreCase(dnUser)) {
            return true;
        }/*from   ww w. ja v  a2s  .  c  om*/
    }
    return false;
}

From source file:org.apache.catalina.startup.HostConfig.java

/**
 * Check deployment descriptors last modified date.
 *//*w  ww .j  a  v  a  2  s .c  om*/
protected void checkContextLastModified() {

    if (!(host instanceof Deployer))
        return;

    Deployer deployer = (Deployer) host;

    String[] contextNames = deployer.findDeployedApps();

    for (int i = 0; i < contextNames.length; i++) {

        String contextName = contextNames[i];
        Context context = deployer.findDeployedApp(contextName);

        if (!(context instanceof Lifecycle))
            continue;

        try {
            DirContext resources = context.getResources();
            if (resources == null) {
                // This can happen if there was an error initializing
                // the context
                continue;
            }
            ResourceAttributes webXmlAttributes = (ResourceAttributes) resources
                    .getAttributes("/WEB-INF/web.xml");
            ResourceAttributes webInfAttributes = (ResourceAttributes) resources.getAttributes("/WEB-INF");
            long newLastModified = webXmlAttributes.getLastModified();
            long webInfLastModified = webInfAttributes.getLastModified();
            Long lastModified = (Long) webXmlLastModified.get(contextName);
            if (lastModified == null) {
                webXmlLastModified.put(contextName, new Long(newLastModified));
            } else {
                if (lastModified.longValue() != newLastModified) {
                    if (newLastModified > (webInfLastModified + 5000)) {
                        webXmlLastModified.remove(contextName);
                        restartContext(context);
                    } else {
                        webXmlLastModified.put(contextName, new Long(newLastModified));
                    }
                }
            }
        } catch (NamingException e) {
            ; // Ignore
        }

        Long lastModified = (Long) contextXmlLastModified.get(contextName);
        String configBase = configBase().getPath();
        String configFileName = context.getConfigFile();
        if (configFileName != null) {
            File configFile = new File(configFileName);
            if (!configFile.isAbsolute()) {
                configFile = new File(System.getProperty("catalina.base"), configFile.getPath());
            }
            long newLastModified = configFile.lastModified();
            if (lastModified == null) {
                contextXmlLastModified.put(contextName, new Long(newLastModified));
            } else {
                if (lastModified.longValue() != newLastModified) {
                    contextXmlLastModified.remove(contextName);
                    String fileName = configFileName;
                    if (fileName.startsWith(configBase)) {
                        fileName = fileName.substring(configBase.length() + 1);
                        try {
                            deployed.remove(fileName);
                            if (host.findChild(contextName) != null) {
                                ((Deployer) host).remove(contextName);
                            }
                        } catch (Throwable t) {
                            log.error(sm.getString("hostConfig.undeployJar.error", fileName), t);
                        }
                        deployApps();
                    }
                }
            }
        }

    }

    // Check for WAR modification
    if (isUnpackWARs()) {
        File appBase = appBase();
        if (!appBase.exists() || !appBase.isDirectory())
            return;
        String files[] = appBase.list();

        for (int i = 0; i < files.length; i++) {
            if (files[i].endsWith(".war")) {
                File dir = new File(appBase, files[i]);
                Long lastModified = (Long) warLastModified.get(files[i]);
                long dirLastModified = dir.lastModified();
                if (lastModified == null) {
                    warLastModified.put(files[i], new Long(dir.lastModified()));
                } else if (dirLastModified > lastModified.longValue()) {
                    // The WAR has been modified: redeploy
                    String expandedDir = files[i];
                    int period = expandedDir.lastIndexOf(".");
                    if (period >= 0)
                        expandedDir = expandedDir.substring(0, period);
                    File expanded = new File(appBase, expandedDir);
                    String contextPath = "/" + expandedDir;
                    if (contextPath.equals("/ROOT"))
                        contextPath = "";
                    if (dirLastModified > expanded.lastModified()) {
                        try {
                            // Undeploy current application
                            deployed.remove(files[i]);
                            deployed.remove(expandedDir + ".xml");
                            if (host.findChild(contextPath) != null) {
                                ((Deployer) host).remove(contextPath, false);
                                ExpandWar.deleteDir(expanded);
                            }
                        } catch (Throwable t) {
                            log.error(sm.getString("hostConfig.undeployJar.error", files[i]), t);
                        }
                        deployApps();
                    }
                    // If deployment was successful, reset 
                    // the last modified values
                    if (host.findChild(contextPath) != null) {
                        webXmlLastModified.remove(contextPath);
                        warLastModified.put(files[i], new Long(dir.lastModified()));
                    }
                }
            }
        }
    }

}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

@Test
public void testFailureWithUnsupportedControl() throws Exception {
    Control unsupported = new OpaqueControl("1.1.1.1");
    unsupported.setCritical(true);//from ww w .  ja  v a  2  s . c  om

    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/ou=system");
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    InitialLdapContext ctx = new InitialLdapContext(env, null);

    Attributes user = new BasicAttributes("cn", "Kate Bush", true);
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("person");
    oc.add("organizationalPerson");
    oc.add("inetOrgPerson");
    user.put(oc);
    user.put("sn", "Bush");
    user.put("userPassword", "Aerial");
    ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[] { unsupported }));

    try {
        ctx.createSubcontext("cn=Kate Bush", user);
        fail();
    } catch (OperationNotSupportedException e) {
    }

    unsupported.setCritical(false);
    ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[] { unsupported }));

    DirContext kate = ctx.createSubcontext("cn=Kate Bush", user);
    assertNotNull(kate);
    assertTrue(ArrayUtils.isEquals(Asn1StringUtils.getBytesUtf8("Aerial"),
            kate.getAttributes("").get("userPassword").get()));

    ctx.destroySubcontext("cn=Kate Bush");
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Gets the common, phone and email for the
 * @param uid To use for searching in LDAP  
 * @return An array containing the 3 strings
 * @throws NamingException On error//w  w w  . j a  va 2 s .c  om
 */
@SuppressWarnings("unchecked")
public UserLogin getUserLogin(String uid) throws NamingException {
    DirContext ctx = getUserContext();
    try {
        Attributes attributes = ctx.getAttributes("uid=" + uid);

        debugAttributes(attributes);

        UserLogin ul = new UserLogin();
        ul.setSurname((String) attributes.get("sn").get());
        ul.setFirstName((String) attributes.get("givenName").get());
        ul.setEmail((String) attributes.get("mail").get());
        ul.setUsername(uid);
        return ul;
    } catch (Exception e) {
        //expected behaviour for bad username
        logger.debug(e.getMessage(), e);
        return null;
    }
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Creates a user. String array contains:
 * 1) first name/* w  w  w .  ja  v  a  2s  .  c  o  m*/
 * 2) surname
 * 3) email
 * 4) username
 * 5) password
 * 
 * @param userDetails
 * @return
 * @throws NamingException
 */
public boolean createNewUser(UserLogin userLogin) throws NamingException {
    DirContext ctx = getUserContext();
    Attributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("sn", userLogin.getSurname()));
    attributes.put(new BasicAttribute("givenName", userLogin.getFirstName()));
    attributes.put(new BasicAttribute("cn", userLogin.getFirstName() + " " + userLogin.getSurname()));
    attributes.put(new BasicAttribute("mail", userLogin.getEmail()));
    if (userLogin.getTelephone() != null) {
        attributes.put(new BasicAttribute("telephoneNumber", userLogin.getTelephone()));
    }
    attributes.put(new BasicAttribute("userPassword", userLogin.getPassword()));
    attributes.put(new BasicAttribute("objectClass", "top"));
    attributes.put(new BasicAttribute("objectClass", "person"));
    attributes.put(new BasicAttribute("objectClass", "organizationalPerson"));
    attributes.put(new BasicAttribute("objectClass", "inetorgperson"));
    String contextName = "uid=" + userLogin.getUsername();
    String fullContextName = contextName + "," + ctx.getNameInNamespace();

    //add the user to ldap
    ctx.createSubcontext(contextName, attributes);

    //need to add user to group
    for (int i = 0; i < userGroups.length; i++) {
        DirContext groupContext = getGroupContext();
        Attributes groupAttributes = groupContext.getAttributes(userGroups[i]);
        groupAttributes.get("uniqueMember").add(fullContextName);
        groupContext.modifyAttributes(userGroups[i], DirContext.REPLACE_ATTRIBUTE, groupAttributes);
    }
    return true;
}

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

private List searchGroupMember(DirContext context, Map filters) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    Set userList = new HashSet();
    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls);

    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        Attributes attrs = searchResult.getAttributes();
        String dn = searchResult.getName() + "," + groupBase;
        String uniquememberAttrName = "uniqueMember";
        if (this.propAttrMap.containsKey("org_member")) {
            try {
                uniquememberAttrName = (String) this.propAttrMap.get("org_member");
            } catch (Exception ex) {
                //ignore
            }//from www.  j  a v  a 2s  .c om
        }
        Attribute uniquememberAttr = attrs.get(uniquememberAttrName);
        if (uniquememberAttr == null)
            continue;
        NamingEnumeration memberDNs = uniquememberAttr.getAll();
        while (memberDNs.hasMoreElements()) {
            //System.out.println(memberDNs[j]);
            userList.add(memberDNs.next());//DN of user
        }
    }

    List members = new ArrayList();

    for (Iterator userDns = userList.iterator(); userDns.hasNext();) {

        /* Next directory entry */
        String userDn = (String) userDns.next();
        Attributes userEntry = null;
        try {
            userEntry = context.getAttributes(userDn);//DN of user
        } catch (Exception e) {
            log.error(userDn + ": " + e.getMessage());
        }
        if (userEntry == null)
            continue;

        LDAPAccount user = createLDAPUser(userDn, userEntry);
        if (user.getUid() == null)
            continue;

        members.add(user);

    }

    return members;

}

From source file:org.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java

/**
 * Infer the root DN.//from  w  w w.j a va2 s  .  c o m
 *
 * @return null if not found.
 */
private String inferRootDN(String server) {
    try {
        Hashtable<String, String> props = new Hashtable<String, String>();
        if (managerDN != null) {
            props.put(Context.SECURITY_PRINCIPAL, managerDN);
            props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
        }
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, toProviderUrl(fixNull(getServerUrl()), ""));

        DirContext ctx = new InitialDirContext(props);
        Attributes atts = ctx.getAttributes("");
        Attribute a = atts.get("defaultNamingContext");
        if (a != null && a.get() != null) { // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
            return a.get().toString();
        }

        a = atts.get("namingcontexts");
        if (a == null) {
            LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
            return null;
        }
        return a.get().toString();
    } catch (NamingException e) {
        LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
        return null;
    }
}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static void logLdap(Log plog, int level, int nth, Object dirEntry) throws NamingException {
    try {/*from  w  w w.j  av  a2s .c  o m*/
        if (dirEntry instanceof NamingEnumeration) {
            NamingEnumeration nameEnum = (NamingEnumeration) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "Naming Enumeration: " + nameEnum);
            try {
                int nthThis = 0;
                List nameList = new Vector(Collections.list(nameEnum));
                Collections.sort(nameList, new Comparator() {
                    public int compare(Object o1, Object o2) {
                        if (o1 instanceof Attribute) {
                            return String.CASE_INSENSITIVE_ORDER.compare(((Attribute) o1).getID(),
                                    ((Attribute) o2).getID());
                        }
                        return 0;
                    }
                });
                Iterator nameIter = nameList.iterator();
                while (nameIter.hasNext()) {
                    logLdap(plog, level + 1, nthThis++, nameIter.next());
                }
            } catch (NamingException ex) {
                plog.error("Exception iterating thru NamingEnumeration: " + ex.getMessage());
            }
        } else if (dirEntry instanceof Attribute) {
            Attribute dirAttr = (Attribute) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "Attribute: [" + dirAttr + "]");
        } else if (dirEntry instanceof DirContext) {
            DirContext lctx = (DirContext) dirEntry;
            JndiHelper.logLevel(plog, level, nth,
                    "LDAP Context: DN [" + lctx.getNameInNamespace() + "]" + " Attributes ==>");
            logLdap(plog, level, nth, lctx.getAttributes("").getAll());
        } else if (dirEntry instanceof SearchResult) {
            SearchResult sr = (SearchResult) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "SearchResult: ClassName of Bound Object ["
                    + sr.getClassName() + "]" + " Name: [" + sr.getName() + "]" + " Bound Object ==>");
            //                sr.s
            logLdap(plog, level, nth, sr.getObject());
            logLdap(plog, level, nth, sr.getAttributes().getAll());
        } else {
            JndiHelper.logLevel(plog, level, nth, "(?) class of entry: [" + dirEntry + "]");
        }
        nth++;
    } catch (NamingException e1) {
        plog.error("Naming Exception (will try to continue): " + e1.getMessage());
    }
}

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

/**
 * Retrieve home directory of given user.
 *
 * @param user//  w ww.  ja va2s. 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;
    }
}