Example usage for javax.naming Context PROVIDER_URL

List of usage examples for javax.naming Context PROVIDER_URL

Introduction

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

Prototype

String PROVIDER_URL

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying configuration information for the service provider to use.

Usage

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   w  ww. j a  v a2  s. c  o m*/

    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:com.headstrong.fusion.messaging.model.endpoint.binding.JmsBindingEndPointModeler.java

/**
 * Creates a {@link JmsComponent} using the parameters set.
 * /*from   w ww .  j av a 2 s.  c om*/
 * @param routeBuilder
 * @return {@link JmsComponent}
 * @throws ProcessModellingException
 */
@SuppressWarnings("unchecked")
private Component getJmsComponent(RouteBuilder routeBuilder) throws ProcessModellingException {
    JmsComponent jmsComponent = null;
    if (this.getProvider().equals(Provider.activemq.toString())) {
        jmsComponent = ActiveMQComponent.activeMQComponent();
        jmsComponent.setConnectionFactory(new PooledConnectionFactory(this.getBrokerUrl()));
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    } else if (this.getProvider().equals(Provider.ibmmq.toString())) {
        JmsConnectionFactory factory = null;
        try {
            JmsFactoryFactory jmsFactoryFactory;
            jmsFactoryFactory = JmsFactoryFactory.getInstance(JmsConstants.WMQ_PROVIDER);
            factory = jmsFactoryFactory.createConnectionFactory();
            factory.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            factory.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, this.getQueueManager());
            factory.setStringProperty(WMQConstants.WMQ_HOST_NAME, this.getBrokerUrl());
            factory.setIntProperty(WMQConstants.WMQ_PORT, this.getPort());
            if (this.getChannel() != null && !this.getChannel().isEmpty())
                factory.setStringProperty(WMQConstants.WMQ_CHANNEL, this.getChannel());
            factory.setIntProperty(WMQConstants.DELIVERY_MODE, this.getDeliveryMode());
        } catch (JMSException e) {
            logger.error("Error connecting to JMS provider.", e);
            throw new ProcessModellingException("Error connecting to JMS provider.", e);
        }
        UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter();
        adapter.setTargetConnectionFactory(factory);
        if (this.getUserName() != null) {
            adapter.setUsername(this.getUserName());
        }
        if (this.getPassword() != null) {
            adapter.setPassword(this.getPassword());
        }
        jmsComponent = JmsComponent.jmsComponent();
        jmsComponent.setConnectionFactory(adapter);
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    } else {
        Hashtable<String, String> prop = new Hashtable<String, String>();
        // Mandatory property.
        prop.put(Context.PROVIDER_URL, this.getLdapConfiguration().getProviderUrl());
        prop.put(Context.INITIAL_CONTEXT_FACTORY, this.getLdapConfiguration().getInitialContextFactory());

        // Only these optional properties supported now.
        if (this.getLdapConfiguration().getSecurityAuthentication() != null) {
            prop.put(Context.SECURITY_AUTHENTICATION, this.getLdapConfiguration().getSecurityAuthentication());
        }
        if (this.getLdapConfiguration().getSecutiryPrincipal() != null) {
            prop.put(Context.SECURITY_PRINCIPAL, this.getLdapConfiguration().getSecutiryPrincipal());
        }
        if (this.getLdapConfiguration().getSecutiryCredentials() != null) {
            prop.put(Context.SECURITY_CREDENTIALS, this.getLdapConfiguration().getSecutiryCredentials());
        }
        Context context;
        ConnectionFactory connectionFactory;
        try {
            // HACK required to avoid ClassNotFoundException while
            // retrieving the
            // InitialContext.
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
                context = new InitialContext(prop);
                connectionFactory = (ConnectionFactory) context
                        .lookup(this.getLdapConfiguration().getConnectionFactoryJndiName());
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
            // HACK -- Finished
        } catch (NamingException e) {
            logger.error("Error connecting to JMS provider.", e);
            throw new ProcessModellingException("Error connecting to JMS provider.", e);
        }
        UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter();
        adapter.setTargetConnectionFactory(connectionFactory);
        if (this.getUserName() != null) {
            adapter.setUsername(this.getUserName());
        }
        if (this.getPassword() != null) {
            adapter.setPassword(this.getPassword());
        }
        jmsComponent = JmsComponent.jmsComponent();
        jmsComponent.setConnectionFactory(adapter);
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    }

    if (jmsComponent != null) {
        jmsComponent.setConcurrentConsumers(getThreadCount());
    }
    return jmsComponent;
}

From source file:org.apache.syncope.core.rest.AbstractTest.java

@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" })
protected Object getLdapRemoteObject(final String bindDn, final String bindPwd, final String objectDn) {
    ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP);
    final Map<String, ConnConfProperty> ldapConnConf = connectorService.read(ldapRes.getConnectorId())
            .getConfigurationMap();/* w w w .  j av a 2 s  .  c o m*/

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://" + ldapConnConf.get("host").getValues().get(0) + ":"
            + ldapConnConf.get("port").getValues().get(0) + "/");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
            bindDn == null ? ldapConnConf.get("principal").getValues().get(0) : bindDn);
    env.put(Context.SECURITY_CREDENTIALS,
            bindPwd == null ? ldapConnConf.get("credentials").getValues().get(0) : bindPwd);

    try {
        final InitialDirContext ctx = new InitialDirContext(env);
        return ctx.lookup(objectDn);
    } catch (Exception e) {
        return null;
    }
}

From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

public LdapContext getContextWithCredentials(String userDN, String password)
        throws UserStoreException, NamingException, AuthenticationException {
    LdapContext context = null;// w  ww. jav a  2s . c om

    //create a temp env for this particular authentication session by copying the original env
    Hashtable<String, String> tempEnv = new Hashtable<String, String>();
    for (Object key : environment.keySet()) {
        tempEnv.put((String) key, (String) environment.get(key));
    }
    //replace connection name and password with the passed credentials to this method
    tempEnv.put(Context.SECURITY_PRINCIPAL, userDN);
    tempEnv.put(Context.SECURITY_CREDENTIALS, password);

    //if dcMap is not populated, it is not DNS case
    if (dcMap == null) {

        //replace environment properties with these credentials
        context = new InitialLdapContext(tempEnv, null);

    } else if (dcMap != null && dcMap.size() != 0) {
        try {
            //first try the first entry in dcMap, if it fails, try iteratively
            Integer firstKey = dcMap.firstKey();
            SRVRecord firstRecord = dcMap.get(firstKey);
            //compose the connection URL
            tempEnv.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord));
            context = new InitialLdapContext(tempEnv, null);

        } catch (AuthenticationException e) {
            throw e;

        } catch (NamingException e) {
            log.error("Error obtaining connection to first Domain Controller." + e.getMessage(), e);
            log.info("Trying to connect with other Domain Controllers");

            for (Integer integer : dcMap.keySet()) {
                try {
                    SRVRecord srv = dcMap.get(integer);
                    environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv));
                    context = new InitialLdapContext(environment, null);
                    break;
                } catch (AuthenticationException e2) {
                    throw e2;
                } catch (NamingException e1) {
                    if (integer == (dcMap.lastKey())) {
                        log.error("Error obtaining connection for all " + integer + " Domain Controllers."
                                + e1.getMessage(), e1);
                        throw new UserStoreException("Error obtaining connection. " + e1.getMessage(), e1);
                    }
                }
            }
        }
    }
    return (context);
}

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

/**
 * Get the JmsConnection from the cache if one exists, otherwise a new one will be created. This
 * method is synchronized otherwise multiple threads may try to create the same connection
 * simultaneously. Only one thread is allowed to create a connection at a time. Subsequent
 * threads will then retrieve the connection that was already created.
 *//*from  w w  w  .  ja v  a  2s  .c  o  m*/
private synchronized JmsConnection getJmsConnection(JmsDispatcherProperties jmsDispatcherProperties,
        String connectionKey, Long dispatcherId, boolean replace) throws Exception {
    // If the connection needs to be replaced, clean up the old connection and remove it from the cache.
    if (replace) {
        closeJmsConnectionQuietly(connectionKey);
    }

    JmsConnection jmsConnection = jmsConnections.get(connectionKey);

    if (jmsConnection == null) {
        if (jmsConnections.size() >= maxConnections) {
            throw new Exception("Cannot create new connection. Maximum number (" + maxConnections
                    + ") of cached connections reached.");
        }

        Context initialContext = null;
        ConnectionFactory connectionFactory = null;
        Connection connection = null;

        Map<String, String> connectionProperties = jmsDispatcherProperties.getConnectionProperties();
        if (jmsDispatcherProperties.isUseJndi()) {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

            try {
                MirthContextFactory contextFactory = contextFactoryController
                        .getContextFactory(getResourceIds());
                Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

                Hashtable<String, Object> env = new Hashtable<String, Object>();
                env.put(Context.PROVIDER_URL, jmsDispatcherProperties.getJndiProviderUrl());
                env.put(Context.INITIAL_CONTEXT_FACTORY,
                        jmsDispatcherProperties.getJndiInitialContextFactory());
                env.put(Context.SECURITY_PRINCIPAL, jmsDispatcherProperties.getUsername());
                env.put(Context.SECURITY_CREDENTIALS, jmsDispatcherProperties.getPassword());

                initialContext = new InitialContext(env);

                String connectionFactoryName = jmsDispatcherProperties.getJndiConnectionFactoryName();
                connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName);
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
        } else {
            String className = jmsDispatcherProperties.getConnectionFactoryClass();

            MirthContextFactory contextFactory = contextFactoryController.getContextFactory(getResourceIds());
            connectionFactory = (ConnectionFactory) Class
                    .forName(className, true, contextFactory.getApplicationClassLoader()).newInstance();
        }

        BeanUtil.setProperties(connectionFactory, connectionProperties);

        try {
            logger.debug("Creating JMS connection and session");
            connection = connectionFactory.createConnection(jmsDispatcherProperties.getUsername(),
                    jmsDispatcherProperties.getPassword());
            String clientId = jmsDispatcherProperties.getClientId();

            if (!clientId.isEmpty()) {
                connection.setClientID(clientId);
            }

            logger.debug("Starting JMS connection");
            connection.start();
        } catch (JMSException e) {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e1) {
                logger.debug("Failed to close JMS connection.", e);
            }

            try {
                if (initialContext != null) {
                    initialContext.close();
                }
            } catch (Exception e1) {
                logger.debug("Failed to close initial context.", e);
            }

            throw e;
        }

        // Create the new JmsConnection and add it to the cache.
        jmsConnection = new JmsConnection(connection, initialContext);
        jmsConnections.put(connectionKey, jmsConnection);
    }

    return jmsConnection;
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

@Test
public void testRunning() throws Exception {
    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
    DirContext ctx = new InitialDirContext(env);

    HashSet<String> set = new HashSet<>();

    NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

    while (list.hasMore()) {
        NameClassPair ncp = list.next();
        set.add(ncp.getName());/*from   w  w  w  .  j av a2 s  .  c o m*/
    }

    Assert.assertTrue(set.contains("uid=admin"));
    Assert.assertTrue(set.contains("ou=users"));
    Assert.assertTrue(set.contains("ou=groups"));
    Assert.assertTrue(set.contains("ou=configuration"));
    Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));

    ctx.close();
}

From source file:org.apache.axis.providers.java.EJBProvider.java

/**
 * Common routine to do the JNDI lookup on the Home interface object
 * username and password for jndi lookup are got from the configuration or from
 * the messageContext if not found in the configuration
 *//* w  ww  . j a v a  2s  .  c om*/
private Object getEJBHome(SOAPService serviceHandler, MessageContext msgContext, String beanJndiName)
        throws AxisFault {
    Object ejbHome = null;

    // Set up an InitialContext and use it get the beanJndiName from JNDI
    try {
        Properties properties = null;

        // collect all the properties we need to access JNDI:
        // username, password, factoryclass, contextUrl

        // username
        String username = getStrOption(jndiUsername, serviceHandler);
        if ((username == null) && (msgContext != null))
            username = msgContext.getUsername();
        if (username != null) {
            if (properties == null)
                properties = new Properties();
            properties.setProperty(Context.SECURITY_PRINCIPAL, username);
        }

        // password
        String password = getStrOption(jndiPassword, serviceHandler);
        if ((password == null) && (msgContext != null))
            password = msgContext.getPassword();
        if (password != null) {
            if (properties == null)
                properties = new Properties();
            properties.setProperty(Context.SECURITY_CREDENTIALS, password);
        }

        // factory class
        String factoryClass = getStrOption(jndiContextClass, serviceHandler);
        if (factoryClass != null) {
            if (properties == null)
                properties = new Properties();
            properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryClass);
        }

        // contextUrl
        String contextUrl = getStrOption(jndiURL, serviceHandler);
        if (contextUrl != null) {
            if (properties == null)
                properties = new Properties();
            properties.setProperty(Context.PROVIDER_URL, contextUrl);
        }

        // get context using these properties 
        InitialContext context = getContext(properties);

        // if we didn't get a context, fail
        if (context == null)
            throw new AxisFault(Messages.getMessage("cannotCreateInitialContext00"));

        ejbHome = getEJBHome(context, beanJndiName);

        if (ejbHome == null)
            throw new AxisFault(Messages.getMessage("cannotFindJNDIHome00", beanJndiName));
    }
    // Should probably catch javax.naming.NameNotFoundException here 
    catch (Exception exception) {
        entLog.info(Messages.getMessage("toAxisFault00"), exception);
        throw AxisFault.makeFault(exception);
    }

    return ejbHome;
}

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

/**
 * Infer the root DN./*w  ww .j a v  a  2  s .  c om*/
 *
 * @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:com.stimulus.archiva.security.realm.ADRealm.java

public ArrayList<AttributeValue> getADAttributes(Config config, ADIdentity identity, String username,
        String password) throws ArchivaException {
    logger.debug("getADAttributes()");
    validateLoginName(username);//from w  w w. j a  v a  2 s .c  o m
    validatePassword(password);
    LoginContext serverLC = kereberosLogin(config, identity, identity.getServiceDN(),
            identity.getServicePassword());
    Hashtable<String, String> env = new Hashtable<String, String>(11);
    String ldapAddress = identity.getLDAPAddress();
    if (!ldapAddress.toLowerCase(Locale.ENGLISH).startsWith("ldap://"))
        ldapAddress = "ldap://" + ldapAddress;
    logger.debug("finding DN of user from LDAP using Kereberos token {ldapAddress='" + ldapAddress
            + "', username='" + username + "'}");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapAddress);
    env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
    int at = username.indexOf('@');
    String uname = username;
    if (uname.indexOf("@") != -1) {
        uname = username.substring(0, at).toLowerCase(Locale.ENGLISH);
    }
    logger.debug("findUserDN {loginname='" + uname + "'}");
    String bindDN = null;
    try {
        bindDN = (String) Subject.doAs(serverLC.getSubject(), new FindDNAction(identity, uname, env));
    } catch (Exception e) {
        throw new ArchivaException("failed to bind to ldap server {uname='" + username + "''}", e, logger);
    }
    try {
        serverLC.logout();
    } catch (Exception e) {
        throw new ArchivaException("failed to logout from kerberos server:" + e.getMessage() + " {uname='"
                + username + "',kdcAddress='" + identity.getKDCAddress() + "'}", e, logger);
    }
    ArrayList<AttributeValue> attributes = new ArrayList<AttributeValue>();
    serverLC = kereberosLogin(config, identity, username, password);
    if (bindDN != null) {
        env.clear();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapAddress);
        env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");

        try {
            attributes = (ArrayList<AttributeValue>) Subject.doAs(serverLC.getSubject(),
                    new GetAttributesAction(identity, username, env, bindDN));
        } catch (Exception e) {
            throw new ArchivaException("failed to bind to ldap server:" + e.getMessage() + " {uname='"
                    + username + "',ldapAddress='" + identity.getLDAPAddress() + "'}", e, logger);
        }
    }
    try {
        serverLC.logout();
    } catch (Exception e) {
        throw new ArchivaException("failed to logout from kerberos server:" + e.getMessage() + " {uname='"
                + username + "',kdcAddress='" + identity.getKDCAddress() + "'}", e, logger);
    }
    logger.debug("getADAttributes() return");
    return attributes;

}

From source file:ldap.ActiveLoginImpl.java

/**
 * open the directory connection./* w ww . j  a va 2 s .  c  o  m*/
 * @param url
 * @param tracing
 * @return
 * @throws 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(LdapConstants.ldapVersionStr, LdapConstants.ldapVersion); // always use ldap v3 - v2 too limited

    //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");  // use default jndi provider
    env.put(Context.INITIAL_CONTEXT_FACTORY, LdapConstants.ldapContext); // use default jndi provider

    //env.put("java.naming.ldap.deleteRDN", "false");         // usually what we want
    env.put(LdapConstants.ldapDeleteRdn, LdapConstants.ldapDeleteRdnValue); // usually what we want

    //env.put(Context.REFERRAL, "ignore");                    //could be: follow, ignore, throw
    env.put(Context.REFERRAL, LdapConstants.ldapIgnore); //could be: follow, ignore, throw

    // env.put("java.naming.ldap.derefAliases", "finding");    // could be: finding, searching, etc.
    env.put(LdapConstants.ldapFindingAliases, LdapConstants.ldapFindingStr); // could be: finding, searching, etc.

    //env.put(Context.SECURITY_AUTHENTICATION, "simple");         // 'simple' = username + password
    env.put(Context.SECURITY_AUTHENTICATION, LdapConstants.ldapSecurityAuth); // '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;

}