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:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
 * Creates an LDAP authenticator for the specified server, base DN and given
 * identifier attribute//www . j a  va  2 s  .  c  om
 * 
 * @param baseUrl
 *            LDAP server URL
 * @param baseDn
 *            LDAP base DN
 * @param ldapSecurityPrincipal
 *            LDAP Security Principal
 * @param ldapSecurityCredentials
 *            Credentials for Security Principal
 * @param ldapRoleAttr
 *            Name of the LDAP attribute that defines the role
 * @param idAttr
 *            LDAP user identifier attribute
 */
public CustomLdapAuthenticationHandler(String baseUrl, String baseDn, String ldapSecurityPrincipal,
        String ldapSecurityCredentials, String ldapRoleAttr, String idAttr) {
    // Set public variables      
    this.baseDn = baseDn;
    this.idAttr = idAttr;
    this.ldapRoleAttr = ldapRoleAttr;
    this.baseUrl = baseUrl;
    this.ldapSecurityPrincipal = ldapSecurityPrincipal;
    this.ldapSecurityCredentials = ldapSecurityCredentials;
    if (CustomLdapAuthenticationHandler.credentialCache == null) {
        CacheManager singletonManager = CacheManager.create();
        CustomLdapAuthenticationHandler.credentialCache = new Cache("credentialCache", 500, false, false, 3600,
                1800);
        singletonManager.addCache(CustomLdapAuthenticationHandler.credentialCache);
    }

    // Initialise the LDAP environment
    env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, baseUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    if (!ldapSecurityPrincipal.equals("")) {
        env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
        env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);
    }

}

From source file:org.squale.jraf.bootstrap.naming.NamingHelper.java

/**
 * Retourne les proprietes JNDI associees a partir de l'url d'un annuaire et de la factory d'acces
 * @param jndiUrl url de l'annuaire/*from   www  . j  a va2 s. com*/
 * @param jndiClass factory d'acces
 * @return
 */
public static Properties getJndiProperties(String jndiUrl, String jndiClass) {

    Properties properties = new Properties();

    // context factory
    if (jndiClass != null) {
        properties.put(Context.INITIAL_CONTEXT_FACTORY, jndiClass);
    }

    // URL
    if (jndiUrl != null) {
        properties.put(Context.PROVIDER_URL, jndiUrl);
    }

    return properties;
}

From source file:ldap.SearchUtility.java

/**
 * open the directory connection./*  w  w  w.  ja va 2 s .  c  o  m*/
 *
 * @param url
 * @param tracing
 * @return
 * @throws javax.naming.NamingException
 */
private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
        throws NamingException {
    /*
    * First, set up a large number of environment variables to sensible default valuse
    */

    Hashtable env = new Hashtable();
    // sanity check
    if (url == null)
        throw new NamingException("URL not specified in openContext()!");

    // set the tracing level now, since it can't be set once the connection is open.
    if (tracing)
        env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output

    env.put("java.naming.ldap.version", "3"); // always use ldap v3 - v2 too limited
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // use default jndi provider
    env.put("java.naming.ldap.deleteRDN", "false"); // usually what we want
    env.put(Context.REFERRAL, "ignore"); //could be: follow, ignore, throw
    env.put("java.naming.ldap.derefAliases", "finding"); // could be: finding, searching, etc.
    env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 'simple' = username + password
    env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn
    env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string-
    env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389"

    /*
    *  Open the actual LDAP session using the above environment variables
    */

    DirContext newContext = new InitialDirContext(env);

    if (newContext == null)
        throw new NamingException(
                "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");

    return newContext;

}

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

public static DirContext getDirContext(BehavioralContext bctx, Object principal, Object credentials)
        throws NamingException {
    DirContext ctx = null;//w  ww. j ava2 s . c o m

    Configuration tconfig = bctx.getConfig();
    String ldapProvider = "ldap" + "://" + tconfig.getString(Constants.KEY_AD_HOST) + ":"
            + tconfig.getString(Constants.KEY_AD_PORT) + "/" + tconfig.getString(Constants.KEY_AD_ROOT_DN);

    log.info("Using LDAP url: [" + ldapProvider + "]");

    //        String url, String contextFactoryName,

    Hashtable jndiEnv = new Hashtable();

    jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    jndiEnv.put(Context.PROVIDER_URL, ldapProvider);
    jndiEnv.put(Context.REFERRAL, "follow");

    if (tconfig.getBoolean(Constants.KEY_AD_SSL)) {
        log.info("Using SSL for LDAP");
        jndiEnv.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    jndiEnv.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (principal != null)
        jndiEnv.put(Context.SECURITY_PRINCIPAL, principal);

    if (credentials != null)
        jndiEnv.put(Context.SECURITY_CREDENTIALS, credentials);

    try {
        // Creating the JNDI directory context (with LDAP context
        // factory), performs an LDAP bind to the LDAP provider thereby
        // authenticating the username/pw.
        ctx = new InitialDirContext(jndiEnv);
    } catch (NamingException ex) {
        log.error("Directory context init failed", ex);
        throw ex;
    }

    return ctx;
}

From source file:org.rhq.jndi.AccessCheckingInitialContextFactoryBuilder.java

/**
 * Create a InitialContext factory.  If the environment does not override the factory class it will use the
 * default context factory./*ww w .  jav a 2 s.co m*/
 * 
 * @param environment The environment
 * @return An initial context factory
 * @throws NamingException If an error occurs loading the factory class.
 */
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException {
    final String factoryClassName = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryClassName == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No " + Context.INITIAL_CONTEXT_FACTORY + " set. Using the default factory.");
        }
        return DEFAULT_FACTORY;
    }
    final ClassLoader classLoader = getContextClassLoader();
    try {
        final Class<?> factoryClass = Class.forName(factoryClassName, true, classLoader);
        InitialContextFactory configuredFactory = (InitialContextFactory) factoryClass.newInstance();
        return createSecureWrapper(configuredFactory, environment);
    } catch (Exception e) {
        throw new NamingException("Failed instantiate InitialContextFactory " + factoryClassName
                + " from classloader " + classLoader);
    }
}

From source file:org.grouter.common.hibernate.HibernateUtilContextAware.java

/**
 * Create session factories and configurations and store in hibernateConfigMap. On
 * completion we enter INITIALISED state.
 *///from   ww w.j a  v a2s .  co  m
private static void createSessionFactoriesFromConfigMap() {
    // read in all config and create session factories
    Iterator iter = hibernateConfigMap.keySet().iterator();
    while (iter.hasNext()) {
        SessionFactory sessionFactory;
        String key = (String) iter.next();
        HibernateConfigItem hibernateConfigItem = hibernateConfigMap.get(key);
        String file = hibernateConfigItem.getConfigFile();
        Configuration configuration;
        if (file == null) {
            log.info("Loading properties config and not from file ");
            configuration = hibernateConfigItem.getConfiguration();
        } else {
            log.info("Loading properties from : " + file);
            configuration = new Configuration();
            configuration = configuration.configure(file);
        }
        try {
            String sessionFactoryName = configuration.getProperty(Environment.SESSION_FACTORY_NAME);
            if (sessionFactoryName != null) {
                log.debug("Looking up SessionFactory in JNDI with name : " + sessionFactoryName);
                try {
                    Hashtable env = new Hashtable();
                    env.put(Context.INITIAL_CONTEXT_FACTORY, configuration.getProperty(Environment.JNDI_CLASS));
                    env.put(Context.URL_PKG_PREFIXES, configuration.getProperty(Environment.JNDI_PREFIX));
                    env.put(Context.PROVIDER_URL, configuration.getProperty(Environment.JNDI_URL));
                    Context context = new InitialContext(env);
                    JNDIUtils.printJNDI(context, log);
                    sessionFactory = (SessionFactory) context.lookup(sessionFactoryName);
                    if (sessionFactory == null) {
                        throw new IllegalStateException(
                                "SessionFactory from JNDI lookup returned a null implemenation  using file : "
                                        + file);
                    }
                } catch (NamingException ex) {
                    log.error("Failed looking up sessinfactory : " + sessionFactoryName, ex);
                    throw new RuntimeException(ex);
                }
            } else {
                sessionFactory = configuration.buildSessionFactory();
                if (sessionFactory == null) {
                    throw new IllegalStateException(
                            "SessionFactory could not be createed from the configuration using file : " + file);
                }
            }
            hibernateConfigItem.setConfiguration(configuration);
            hibernateConfigItem.setSessionFactory(sessionFactory);
            // We need to have a default sessionfactory / configuration
            if (hibernateConfigItem.isDeafult()) {
                hibernateConfigItemDefault = hibernateConfigItem;
            }
            // setInterceptor(configuration, null);
            // hibernateConfigMap.put(key)
        } catch (Throwable ex) {
            log.error("Failed initializing from configuration.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    currentState = STATE.INITIALISED;
    log.info("Entered state : " + currentState);
}

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

/**
 * @return connection parameters to use for all LDAP queries
 *///from w  ww.j a va  2 s.  c om
protected Properties computeContextProperties() throws DirectoryException {
    LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor();
    // Initialization of LDAP connection parameters from parameters
    // registered in the LDAP "server" extension point
    Properties props = new Properties();
    LDAPServerDescriptor serverConfig = getServer();

    if (null == serverConfig) {
        throw new DirectoryException(
                "LDAP server configuration not found: " + ldapDirectoryDesc.getServerName());
    }

    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /*
     * Get initial connection URLs, dynamic URLs may cause the list to be updated when creating the session
     */
    String ldapUrls = serverConfig.getLdapUrls();
    if (ldapUrls == null) {
        throw new DirectoryException("Server LDAP URL configuration is missing for directory " + getName());
    }
    props.put(Context.PROVIDER_URL, ldapUrls);

    // define how referrals are handled
    if (!getDescriptor().getFollowReferrals()) {
        props.put(Context.REFERRAL, "ignore");
    } else {
        // this is the default mode
        props.put(Context.REFERRAL, "follow");
    }

    /*
     * SSL Connections do not work with connection timeout property
     */
    if (serverConfig.getConnectionTimeout() > -1) {
        if (!serverConfig.useSsl()) {
            props.put("com.sun.jndi.ldap.connect.timeout",
                    Integer.toString(serverConfig.getConnectionTimeout()));
        } else {
            log.warn("SSL connections do not operate correctly"
                    + " when used with the connection timeout parameter, disabling timout");
        }
    }

    String bindDn = serverConfig.getBindDn();
    if (bindDn != null) {
        // Authenticated connection
        props.put(Context.SECURITY_PRINCIPAL, bindDn);
        props.put(Context.SECURITY_CREDENTIALS, serverConfig.getBindPassword());
    }

    if (serverConfig.isPoolingEnabled()) {
        // Enable connection pooling
        props.put("com.sun.jndi.ldap.connect.pool", "true");
        props.put("com.sun.jndi.ldap.connect.pool.protocol", "plain ssl");
        props.put("com.sun.jndi.ldap.connect.pool.authentication", "none simple DIGEST-MD5");
        props.put("com.sun.jndi.ldap.connect.pool.timeout", "1800000"); // 30
        // min
    }

    if (!serverConfig.isVerifyServerCert() && serverConfig.useSsl) {
        props.put("java.naming.ldap.factory.socket",
                "org.nuxeo.ecm.directory.ldap.LDAPDirectory$TrustingSSLSocketFactory");
    }

    return props;
}

From source file:com.mirth.connect.connectors.jms.JmsReceiverTests.java

private static ConnectionFactory lookupConnectionFactoryWithJndi(JmsConnectorProperties connectorProperties)
        throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.PROVIDER_URL, connectorProperties.getJndiProviderUrl());
    env.put(Context.INITIAL_CONTEXT_FACTORY, connectorProperties.getJndiInitialContextFactory());
    env.put(Context.SECURITY_PRINCIPAL, connectorProperties.getUsername());
    env.put(Context.SECURITY_CREDENTIALS, connectorProperties.getPassword());

    initialContext = new InitialContext(env);
    String connectionFactoryName = connectorProperties.getJndiConnectionFactoryName();
    return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
}

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

public static boolean authenticate(TSiteBean siteBean, String loginName, String ppassword)
        throws NamingException {
    boolean userIsOK = false;
    ArrayList<String> trace = new ArrayList<String>();

    trace.add("Ldap trying to authenticate user with loginname >" + loginName + "<");

    if (siteBean.getLdapServerURL().startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
    }//from  w w w .j av  a2  s  . c  o m
    // get the CN
    String keyDn = getCn(siteBean, loginName);

    try {
        if (keyDn != null) {
            trace.add("Using keyDn >" + keyDn + "<");
            // Set up the environment for creating the initial context
            Hashtable<String, String> env = new Hashtable<String, String>(11);
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, siteBean.getLdapServerURL());
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, keyDn);
            env.put(Context.SECURITY_CREDENTIALS, ppassword);
            // Create initial context
            DirContext itest = new InitialDirContext(env);
            itest.close();
            // user was validated
            userIsOK = true;
        }
        return userIsOK;
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.warn(msg);
        }
        throw e;
    }
}

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

/**
 * Test to make sure anonymous binds are disabled when going through
 * the wire protocol./*from   w  ww.  j  a va2s  .c  om*/
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testDisableAnonymousBinds() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(false);

    // 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()) + "/ou=system");
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    try {
        new InitialDirContext(env);
        fail();
    } catch (Exception e) {
        // We should get here
    }

    try {
        // Use the netscape API as JNDI cannot be used to do a search without
        // first binding.
        LDAPUrl url = new LDAPUrl(Network.LOOPBACK_HOSTNAME, getLdapServer().getPort(), "ou=system",
                new String[] { "vendorName" }, 0, "(ObjectClass=*)");
        LDAPConnection.search(url);

        fail();
    } catch (LDAPException e) {
        // Expected result
    }
}