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.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Creates the directory context configuration.
 * /*from   w ww  .  j  av a2s .  com*/
 * @param loginId
 *            the user principal ID to use when establishing the connection
 * @param loginPassword
 *            the password credentials to use when establishing the connection
 * @param isConnectionRetry
 *            if true, the alternate URL will be employed
 * @return Hashtable<String,String>
 */
protected Hashtable<String, String> getDirectoryContextEnvironment(String loginId, String loginPassword,
        boolean isConnectionRetry) {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

    if (!isConnectionRetry) {
        env.put(Context.PROVIDER_URL, connectionUrl);

    } else if (alternateUrl != null) {
        env.put(Context.PROVIDER_URL, alternateUrl);
    }
    if (loginId != null) {
        env.put(Context.SECURITY_PRINCIPAL, loginId);
    }
    if (loginPassword != null) {
        env.put(Context.SECURITY_CREDENTIALS, loginPassword);
    }
    if (securityAuthentication != null) {
        env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);
    }
    if (connectionProtocol != null) {
        env.put(Context.SECURITY_PROTOCOL, connectionProtocol);
    }
    if (referralStrategy != null) {
        env.put(Context.REFERRAL, referralStrategy);
    }
    if (connectionTimeout > 0) {
        env.put("com.sun.jndi.ldap.connect.timeout", connectionTimeout + "");
    }
    return env;
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided
 * username and credential./*  ww  w.  j  a  va2s.  c om*/
 *
 * @return the Initial Ldap Context to be used to perform searches, etc.
 * @throws NamingException LDAP binding error.
 */
protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential)
        throws NamingException {

    Properties env = new Properties();

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication());
    env.setProperty(Context.PROVIDER_URL, getProviderUrl());
    env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol()));

    // Set defaults for key values if they are missing

    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
    }

    String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);

    if (authType == null)
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");

    String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
    String providerURL = getProviderUrl();
    // Use localhost if providerUrl not set
    if (providerURL == null) {
        providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
    } else {
        // In case user configured provided URL
        if (providerURL.startsWith("ldaps")) {
            protocol = "ssl";
            env.setProperty(Context.SECURITY_PROTOCOL, "ssl");
        }

    }

    env.setProperty(Context.PROVIDER_URL, providerURL);

    if (securityPrincipal != null && !"".equals(securityPrincipal))
        env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);

    if (securityCredential != null && !"".equals(securityCredential))
        env.put(Context.SECURITY_CREDENTIALS, securityCredential);

    // always follow referrals transparently
    env.put(Context.REFERRAL, "follow");

    // Logon into LDAP server
    if (logger.isDebugEnabled())
        logger.debug("Logging into LDAP server, env=" + env);

    InitialLdapContext ctx = new InitialLdapContext(env, null);

    if (logger.isDebugEnabled())
        logger.debug("Logged into LDAP server, " + ctx);

    return ctx;
}

From source file:com.adaptris.core.SharedComponentListTest.java

private JmsConnection createPtpConnection(String uniqueId) throws PasswordException {
    JmsConnection c = new JmsConnection();
    StandardJndiImplementation jndi = new StandardJndiImplementation();
    jndi.setJndiName("Connection_Factory_To_Lookup");
    KeyValuePairSet kvps = jndi.getJndiParams();
    kvps.addKeyValuePair(new KeyValuePair(Context.SECURITY_PRINCIPAL, "Administrator"));
    kvps.addKeyValuePair(new KeyValuePair(Context.SECURITY_CREDENTIALS, "Administrator"));
    kvps.addKeyValuePair(new KeyValuePair("com.sonicsw.jndi.mfcontext.domain", "Domain1"));
    kvps.addKeyValuePair(//  www .j  a v  a 2s.  co m
            new KeyValuePair(Context.INITIAL_CONTEXT_FACTORY, "com.sonicsw.jndi.mfcontext.MFContextFactory"));
    jndi.getJndiParams().addKeyValuePair(new KeyValuePair(Context.PROVIDER_URL, "tcp://localhost:2506"));
    c.setVendorImplementation(jndi);
    if (!isEmpty(uniqueId)) {
        c.setUniqueId(uniqueId);
    }
    return c;
}

From source file:hermes.browser.HermesBrowser.java

/**
 * Initialise the underlying Hermes that we're gonna do all our work with
 * /*from   w  ww . ja v  a  2s  . c om*/
 * @throws HermesException
 * @throws NamingException
 */
public void loadConfig() throws NamingException, HermesException {
    Properties props = new Properties();
    Context oldContext = context;
    HermesConfig oldConfig = null;

    props.put(Context.INITIAL_CONTEXT_FACTORY, HermesInitialContextFactory.class.getName());
    props.put(Context.PROVIDER_URL, getCurrentConfigURL());
    props.put("hermes.loader", JAXBHermesLoader.class.getName());

    log.debug("props=" + props);

    Iterator listeners = null;

    if (loader != null) {
        listeners = loader.getConfigurationListeners();
        oldConfig = loader.getConfig();
    }

    if (oldConfig != null) {
        Set naming = new HashSet();
        naming.addAll(oldConfig.getNaming());

        for (Iterator iter = naming.iterator(); iter.hasNext();) {
            NamingConfig oldNaming = (NamingConfig) iter.next();

            loader.notifyNamingRemoved(oldNaming);
        }
    }

    context = new InitialContext(props);
    loader = (HermesLoader) context.lookup(HermesContext.LOADER);

    if (listeners != null) {
        while (listeners.hasNext()) {
            loader.addConfigurationListener((HermesConfigurationListener) listeners.next());
        }
    }

    if (oldContext != null) {
        for (NamingEnumeration iter = oldContext.listBindings(""); iter.hasMoreElements();) {
            Binding binding = (Binding) iter.next();

            try {
                if (oldContext.lookup(binding.getName()) instanceof Hermes) {
                    Hermes hermes = (Hermes) oldContext.lookup(binding.getName());
                    Hermes newHermes = null;

                    try {
                        newHermes = (Hermes) context.lookup(hermes.getId());
                    } catch (NamingException e) {
                        // NOP
                    }

                    if (newHermes == null) {
                        loader.notifyHermesRemoved(hermes);
                    }
                }
            } catch (NamingException ex) {
                // NOP
            }
        }
    }

    if (!firstLoad) {
        closeWatches();
        final ArrayList tmpList = new ArrayList();
        tmpList.addAll(loader.getConfig().getWatch());
        loader.getConfig().getWatch().clear();

        for (Iterator iter = tmpList.iterator(); iter.hasNext();) {
            WatchConfig wConfig = (WatchConfig) iter.next();
            createWatch(wConfig);
        }
    }

    setTitle("HermesJMS - " + TextUtils.crumble(getCurrentConfigURL(), 100));
}

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 {//  ww w.  j  av  a 2  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:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * get the context for connection//from   w w w .ja  va  2  s  .c  om
 *
 * @return
 */
@SuppressWarnings("unchecked")
public Hashtable getEnvironment() {
    Properties env = new Properties();

    env.put(Context.INITIAL_CONTEXT_FACTORY, _contextFactory);
    String url = null;
    if (_providerUrl != null) {
        url = _providerUrl;
    } else {
        if (_hostname != null) {
            url = "ldap://" + _hostname + "/";
            if (_port != 0) {
                url += ":" + _port + "/";
            }

            LOG.warn("Using hostname and port.  Use providerUrl instead: " + url);
        }
    }
    env.put(Context.PROVIDER_URL, url);

    if (_authenticationMethod != null) {
        env.put(Context.SECURITY_AUTHENTICATION, _authenticationMethod);
    }

    if (_bindDn != null) {
        env.put(Context.SECURITY_PRINCIPAL, _bindDn);
    }

    if (_bindPassword != null) {
        env.put(Context.SECURITY_CREDENTIALS, _bindPassword);
    }
    env.put("com.sun.jndi.ldap.read.timeout", Long.toString(_timeoutRead));
    env.put("com.sun.jndi.ldap.connect.timeout", Long.toString(_timeoutConnect));

    // Set the SSLContextFactory to implementation that validates cert subject
    if (url != null && url.startsWith("ldaps") && _ldapsVerifyHostname) {
        try {
            URI uri = new URI(url);
            HostnameVerifyingSSLSocketFactory.setTargetHost(uri.getHost());
            env.put("java.naming.ldap.factory.socket",
                    "com.dtolabs.rundeck.jetty.jaas.HostnameVerifyingSSLSocketFactory");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    return env;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided
 * username and credential.//  w  w  w.j av  a 2s.com
 *
 * @return the Initial Ldap Context to be used to perform searches, etc.
 * @throws NamingException LDAP binding error.
 */
protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential)
        throws NamingException {

    Properties env = new Properties();

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication());
    env.setProperty(Context.PROVIDER_URL, getProviderUrl());
    env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol()));

    // Set defaults for key values if they are missing

    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
    }

    String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
    if (authType == null)
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");

    String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
    String providerURL = getProviderUrl();
    // Use localhost if providerUrl not set
    if (providerURL == null) {
        //providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
        if (protocol != null && protocol.equals("ssl")) {
            // We should use Start TLS extension?
            providerURL = "ldaps://localhost:636";
        } else {
            providerURL = "ldap://localhost:389";
        }
    }

    env.setProperty(Context.PROVIDER_URL, providerURL);
    env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredential);

    // always follow referrals transparently
    env.put(Context.REFERRAL, "follow");

    // Logon into LDAP server
    if (logger.isDebugEnabled())
        logger.debug("Logging into LDAP server, env=" + env);

    InitialLdapContext ctx = new InitialLdapContext(env, null);

    if (logger.isDebugEnabled())
        logger.debug("Logged into LDAP server, " + ctx);

    return ctx;
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * This method uses JNDI to look up an address in DNS and return its name
 * /*from  w  w w  . ja  v  a2 s .  c o m*/
 * @param addr
 *
 * @return the host name associated with the address or null if lookup isn't possible or there is
 *         no host name for this address
 */
public static String reverseDNS(InetAddress addr) {
    byte[] addrBytes = addr.getAddress();
    // reverse the address suitable for reverse lookup
    String lookup = "";
    for (int index = addrBytes.length - 1; index >= 0; index--) {
        lookup = lookup + (addrBytes[index] & 0xff) + '.';
    }
    lookup += "in-addr.arpa";
    // System.out.println("Looking up: " + lookup);

    try {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        DirContext ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(lookup, new String[] { "PTR" });
        for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) {
            Attribute attr = (Attribute) ae.next();
            for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                Object elem = vals.nextElement();
                if ("PTR".equals(attr.getID()) && elem != null) {
                    return elem.toString();
                }
            }
        }
        ctx.close();
    } catch (Exception e) {
        // ignored
    }
    return null;
}

From source file:org.akaza.openclinica.controller.SystemController.java

public HashMap<String, Object> getLdapModule(StudyBean studyBean) {
    String enabled = CoreResources.getField("ldap.enabled");
    String ldapHost = CoreResources.getField("ldap.host");
    String username = CoreResources.getField("ldap.userDn");
    String password = CoreResources.getField("ldap.password");

    String result = "";
    Properties env = new Properties();

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapHost);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username); // replace with user DN
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = null;//from  w  w w.  j ava 2  s  .c o  m
    try {
        ctx = new InitialDirContext(env);
        result = "ACTIVE";
    } catch (Exception e) {
        result = "INACTIVE";
    }

    HashMap<String, String> mapMetadata = new HashMap<>();
    mapMetadata.put("ldap.host", ldapHost);

    HashMap<String, Object> mapWebService = new HashMap<>();
    mapWebService.put("enabled", enabled.equalsIgnoreCase("true") ? "True" : "False");
    mapWebService.put("status", result);
    mapWebService.put("metadata", mapMetadata);

    HashMap<String, Object> mapModule = new HashMap<>();
    mapModule.put("Ldap", mapWebService);

    return mapModule;
}