Example usage for javax.naming Context INITIAL_CONTEXT_FACTORY

List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY

Introduction

In this page you can find the example usage for javax.naming Context INITIAL_CONTEXT_FACTORY.

Prototype

String INITIAL_CONTEXT_FACTORY

To view the source code for javax.naming Context INITIAL_CONTEXT_FACTORY.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the initial context factory to use.

Usage

From source file:org.olat.ldap.LDAPLoginManagerImpl.java

/**
 * Connect to LDAP with the User-Name and Password given as parameters Configuration: LDAP URL = olatextconfig.xml (property=ldapURL) LDAP Base = olatextconfig.xml
 * (property=ldapBase) LDAP Attributes Map = olatextconfig.xml (property=userAttrs)
 * /*  ww w. j a v a  2s. c o m*/
 * @param uid The users LDAP login name (can't be null)
 * @param pwd The users LDAP password (can't be null)
 * @return After successful bind Attributes otherwise NULL
 * @throws NamingException
 */
public Attributes bindUser(final String uid, final String pwd, final LDAPError errors) {
    // get user name, password and attributes
    final String ldapUrl = LDAPLoginModule.getLdapUrl();
    final String[] userAttr = LDAPLoginModule.getUserAttrs();

    if (uid == null || pwd == null) {
        if (isLogDebugEnabled()) {
            logDebug("Error when trying to bind user, missing username or password. Username::" + uid + " pwd::"
                    + pwd);
        }
        errors.insert("Username and password must be selected");
        return null;
    }

    final LdapContext ctx = bindSystem();
    if (ctx == null) {
        errors.insert("LDAP connection error");
        return null;
    }
    final String userDN = searchUserDN(uid, ctx);
    if (userDN == null) {
        logInfo("Error when trying to bind user with username::" + uid + " - user not found on LDAP server"
                + (LDAPLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider"
                        : ""));
        errors.insert("Username or password incorrect");
        return null;
    }

    // Ok, so far so good, user exists. Now try to fetch attributes using the
    // users credentials
    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, pwd);
    if (LDAPLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        final Control[] connectCtls = new Control[] {};
        final LdapContext userBind = new InitialLdapContext(env, connectCtls);
        final Attributes attributes = userBind.getAttributes(userDN, userAttr);
        userBind.close();
        return attributes;
    } catch (final AuthenticationException e) {
        logInfo("Error when trying to bind user with username::" + uid + " - invalid LDAP password");
        errors.insert("Username or password incorrect");
        return null;
    } catch (final NamingException e) {
        logError("NamingException when trying to get attributes after binding user with username::" + uid, e);
        errors.insert("Username or password incorrect");
        return null;
    }
}

From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

/**
 * @param dn/* w  w  w .j  a  va  2  s  .c  om*/
 * @param password
 * @return
 * @throws LDAPException
 */
private Hashtable<String, String> buildEnvironment(String dn, String password) throws LDAPException {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.REFERRAL, getReferral());
    env.put(Context.SECURITY_AUTHENTICATION, getAuthentication());
    if (!isNoAuthentication()) {
        env.put(Context.SECURITY_PRINCIPAL, dn);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.put(Context.PROVIDER_URL, getProviderUrl());

    if (isConnectionPoolEnabled()) {
        env.put(POOL_ENABLED_ENV_PARAM, "true");

        env.put(AUTHENTICATION_ENV_PARAM, getAuthentication());

        if (getMaxPoolConnections() > 0) {
            env.put(MAX_POOL_SIZE_ENV_PARAM, String.valueOf(getMaxPoolConnections()));
        }

        if (getInitialPoolSizeConnections() > 0) {
            env.put(INIT_POOL_SIZE_ENV_PARAM, String.valueOf(getInitialPoolSizeConnections()));
        }

        if (getPoolTimeout() > 0) {
            env.put(TIME_OUT_ENV_PARAM, String.valueOf(getPoolTimeout()));
        }
    } else {
        env.put(POOL_ENABLED_ENV_PARAM, "false");
    }

    if (extendedEnvironment != null && extendedEnvironment.size() > 0) {
        env.putAll(extendedEnvironment);
    }

    return env;

}

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

public void login(String userid, String password) throws AuthenticationException {
    try {/*  w w w .jav a2 s  .  c om*/
        LDAPAccount user = (LDAPAccount) getUser(userid);
        if (user == null) {
            throw new AuthenticationException(userid + " is not found.");
        }
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, this.connectionURL);
        env.put("java.naming.ldap.version", "3");
        env.put(Context.SECURITY_PRINCIPAL, user.getDn());
        env.put(Context.SECURITY_CREDENTIALS, password);

        new InitialDirContext(env);

    } catch (NamingException e) {
        throw new AuthenticationException(e);
    }
}

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

/**
 * Reproduces the problem with//w w  w.j  a  v  a2s.  c o m
 * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>.
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAdminAccessBug() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous

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

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    Attributes attributes = new BasicAttributes(true);
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");
    attributes.put(objectClass);
    attributes.put("ou", "blah");
    InitialDirContext ctx = new InitialDirContext(env);
    ctx.createSubcontext("ou=blah,ou=system", attributes);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls.setReturningAttributes(new String[] { "+" });
    NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls);
    SearchResult result = list.next();
    list.close();
    Attribute creatorsName = result.getAttributes().get("creatorsName");
    assertEquals("", creatorsName.get());
    ctx.destroySubcontext("ou=blah,ou=system");
}

From source file:com.springsource.insight.plugin.ldap.LdapOperationCollectionAspectTestSupport.java

protected static final Hashtable<String, Object> createEnvironment() {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_PRINCIPAL, LDAP_USERNAME);
    env.put(Context.SECURITY_CREDENTIALS, LDAP_PASSWORD);
    return env;//from ww w.  ja v  a 2  s  .co  m
}

From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java

private Hashtable getEnvironment(String userid, String password) {
    String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " getEnvironment() ";
    Hashtable env = null;//  w  ww .j  a  v  a  2  s  .  c o m

    try {
        env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

        if (VERSION != null && !"".equals(VERSION)) {
            log.debug(m + "ldap explicit version==" + VERSION);
            env.put(CONTEXT_VERSION_KEY, VERSION);
        }
        log.debug(m + "ldap version==" + env.get(CONTEXT_VERSION_KEY));

        env.put(Context.PROVIDER_URL, URL);
        log.debug(m + "ldap url==" + env.get(Context.PROVIDER_URL));

        if (!bindRequired()) {
            log.debug(m + "\"binding\" anonymously");
        } else {
            env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);

            String userForBind = null;
            String passwordForBind = null;
            if (!individualUserBind()) {
                userForBind = SECURITY_PRINCIPAL;
                passwordForBind = SECURITY_CREDENTIALS;
                log.debug(m + "binding to protected directory");
            } else {
                passwordForBind = password;
                if (SECURITY_PRINCIPAL == null || "".equals(SECURITY_PRINCIPAL)) {
                    userForBind = userid;
                    log.debug(m + "binding for real user");
                } else {
                    //simulate test against user-bind at directory server
                    userForBind = SECURITY_PRINCIPAL;
                    log.debug(m + "binding for --test-- user");
                }
            }
            env.put(Context.SECURITY_CREDENTIALS, passwordForBind);
            String[] parms = { userForBind };
            String userFormattedForBind = applyFilter(BIND_FILTER, parms);
            env.put(Context.SECURITY_PRINCIPAL, userFormattedForBind);
        }
        log.debug(m + "bind w " + env.get(Context.SECURITY_AUTHENTICATION));
        log.debug(m + "user== " + env.get(Context.SECURITY_PRINCIPAL));
        log.debug(m + "passwd==" + env.get(Context.SECURITY_CREDENTIALS));
    } catch (Throwable th) {
        if (LOG_STACK_TRACES) {
            log.error(m + "couldn't set up env for DirContext", th);
        } else {
            log.error(m + "couldn't set up env for DirContext" + th.getMessage());
        }
    } finally {
        log.debug(m + "< " + env);
    }
    return env;
}

From source file:org.openiam.spml2.spi.ldap.LdapConnectorImpl.java

public LdapContext connect(String userName, String password) {

    //LdapContext ctxLdap = null;
    Hashtable<String, String> envDC = new Hashtable();

    //keystore = secres.getString("KEYSTORE");
    System.setProperty("javax.net.ssl.trustStore", keystore);

    log.debug("Connecting to ldap using principal=" + userName);

    //envDC.put(Context.PROVIDER_URL,host);
    envDC.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    envDC.put(Context.SECURITY_AUTHENTICATION, "simple"); // simple
    envDC.put(Context.SECURITY_PRINCIPAL, userName); //"administrator@diamelle.local"
    envDC.put(Context.SECURITY_CREDENTIALS, password);
    //   if (protocol != null && protocol.equalsIgnoreCase("SSL")) {
    //      envDC.put(Context.SECURITY_PROTOCOL, protocol);
    //   }//from  w  ww  .  j a va  2  s  .c o  m

    try {
        return (new InitialLdapContext(envDC, null));
    } catch (NamingException ne) {
        log.error(ne.getMessage());

    }
    return null;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets the initial context//  ww  w  . j a  v  a  2  s . c  om
 * 
 * @param providerUrl
 * @param bindDN
 * @param bindPassword
 * @return
 */
public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) {
    List<String> trace = new ArrayList<String>();
    LOGGER.debug("providerURL: " + providerUrl);
    trace.add("Attempting to connect to the LDAP server...");
    if (providerUrl != null && providerUrl.startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
        trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE);
        File ks = new File(PATH_TO_KEY_STORE);
        if (!ks.exists()) {
            trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE);
        }
    }
    if (providerUrl == null) {
        LOGGER.warn("LDAP provider URL should not be null.");
        return null;
    }
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    if (LOGGER.isDebugEnabled()) {
        env.put("com.sun.jndi.ldape.trace.ber", System.err);
    }
    env.put("java.naming.ldap.version", "3");
    env.put("com.sun.jndi.ldap.connect.timeout", "10000");
    env.put("com.sun.jndi.dns.timeout.initial", "2000");
    env.put("com.sun.jndi.dns.timeout.retries", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    if ((bindDN != null) && !bindDN.equals("")) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, bindDN);
        env.put(Context.SECURITY_CREDENTIALS, bindPassword);
        LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*"));
        trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****");
    } else {
        LOGGER.debug("bind anonymous");
        trace.add("Preparing to bind anonymously to the LDAP server");
    }
    try {
        return new InitialLdapContext(env, null);
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.error(msg);
        }
        LOGGER.error("Getting the initial ldap context failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        try {
            new InitialDirContext(env);
        } catch (NamingException e1) {
            LOGGER.error("Getting the initial dir context failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }
}

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

/**
 * Gets and returns the entries from the server.
 * //from  w  w w. ja  v  a  2s  . c o  m
 * @throws ToolCommandException
 * @throws NamingException
 */
public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException {
    // Connecting to the LDAP Server
    if (isDebugEnabled()) {
        notifyOutputListener("Connecting to LDAP server");
        notifyOutputListener("Host: " + host);
        notifyOutputListener("Port: " + port);
        notifyOutputListener("User DN: " + user);
        notifyOutputListener("Base DN: " + baseDN);
        notifyOutputListener("Authentication: " + auth);
    }
    Hashtable env = new Hashtable();
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    DirContext ctx;
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not connect to the server.\nError: " + e.getMessage());
    }

    // Setting up search scope
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(scope);

    // Fetching entries
    try {
        return ctx.search(exportPoint, "(objectClass=*)", ctls);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not retreive entries");
    }
}

From source file:org.miloss.fgsms.bueller.Bueller.java

private String doJmsURL(boolean pooled, String endpoint) {
    try {// w w  w . j  a  v a2s. co  m

        boolean ok = false;
        String server = endpoint.split("#")[0];
        server = server.replace("jms:", "jnp://");
        String name = endpoint.split("#")[1];
        String msg = "";
        String[] info = DBSettingsLoader.GetCredentials(pooled, endpoint);
        String username = null;
        String password = null;
        if (info != null) {
            username = info[0];
            password = info[1];
        } else {
            info = DBSettingsLoader.GetDefaultBuellerCredentials(pooled);
            if (info != null) {
                username = info[0];
                password = info[1];
            }
        }

        if (name.startsWith("topic")) {
            try {
                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                //properties1.put(Context.PROVIDER_URL, "jnp://127.0.0.1:1099");
                properties1.put(Context.PROVIDER_URL, server);

                InitialContext iniCtx = new InitialContext(properties1);

                TopicConnectionFactory tcf = (TopicConnectionFactory) iniCtx.lookup("TopicConnectionFactory");
                TopicConnection createTopicConnection = null;
                if (info != null) {
                    createTopicConnection = tcf.createTopicConnection(username, Utility.DE(password)); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                } else {
                    createTopicConnection = tcf.createTopicConnection(); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                }
                createTopicConnection.start();
                createTopicConnection.stop();
                createTopicConnection.close();
                //Topic topic = (Topic) iniCtx.lookup("//" + name);
                ok = true;

                //topic = null;
                iniCtx.close();

            } catch (Exception ex) {
                System.out.println(ex);
                msg = ex.getLocalizedMessage();
                //return ex.getLocalizedMessage();
            }
        } else if (name.startsWith("queue")) {
            try {

                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                properties1.put(Context.PROVIDER_URL, server);
                InitialContext iniCtx = new InitialContext(properties1);
                QueueConnection conn;
                QueueSession session;
                Queue que;

                Object tmp = iniCtx.lookup("ConnectionFactory");
                QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
                if (info != null) {
                    conn = qcf.createQueueConnection(username, Utility.DE(password));
                } else {
                    conn = qcf.createQueueConnection();
                }

                que = (Queue) iniCtx.lookup(name);
                session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
                conn.start();

                //System.out.println("Connection Started");
                ok = true;

                conn.stop();
                session.close();
                iniCtx.close();

            } catch (Exception ex) {
                log.log(Level.WARN, "Could not bind to jms queue", ex);
                msg = ex.getLocalizedMessage();
            }
            if (ok) {
                return "OK";
            }
            return "Unable to bind to JMS queue: " + msg;
        } else {
            return "Unsupported Protocol";
        }
    } catch (Exception ex) {
        log.log(Level.WARN, "service " + endpoint + " is offline or an error occured", ex);
        return "Offline " + ex.getLocalizedMessage();
    }
    return "undeterminable";
}