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:alpine.auth.LdapConnectionWrapper.java

/**
 * Asserts a users credentials. Returns an LdapContext if assertion is successful
 * or an exception for any other reason.
 *
 * @param userDn the users DN to assert//from w w  w  .j a  v a  2  s .com
 * @param password the password to assert
 * @return the LdapContext upon a successful connection
 * @throws NamingException when unable to establish a connection
 * @since 1.4.0
 */
public LdapContext createLdapContext(String userDn, String password) throws NamingException {
    if (StringUtils.isEmpty(userDn) || StringUtils.isEmpty(password)) {
        throw new NamingException("Username or password cannot be empty or null");
    }
    final Hashtable<String, String> env = new Hashtable<>();
    if (StringUtils.isNotBlank(LDAP_SECURITY_AUTH)) {
        env.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTH);
    }
    env.put(Context.SECURITY_PRINCIPAL, userDn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    if (IS_LDAP_SSLTLS) {
        env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory");
    }
    try {
        return new InitialLdapContext(env, null);
    } catch (CommunicationException e) {
        LOGGER.error("Failed to connect to directory server", e);
        throw (e);
    } catch (NamingException e) {
        throw new NamingException("Failed to authenticate user");
    }
}

From source file:org.mc4j.ems.impl.jmx.connection.support.providers.JBossConnectionProvider.java

private InitialContext getInitialContext() throws NamingException {
    Properties props = this.connectionSettings.getAdvancedProperties();
    if (!NAMING_CONTEXT_FACTORY_CLASS_NAME.equals(this.connectionSettings.getInitialContextName())) {
        log.warn("Unsupported initial context factory [" + this.connectionSettings.getInitialContextName()
                + "] - only " + NAMING_CONTEXT_FACTORY_CLASS_NAME
                + " is supported for JBoss connections; using that instead...");
    }//from  w  ww  .ja v a  2 s.  c o m
    props.put(Context.INITIAL_CONTEXT_FACTORY, NAMING_CONTEXT_FACTORY_CLASS_NAME);
    props.put(Context.PROVIDER_URL, this.connectionSettings.getServerUrl());

    try {
        InitialContext context = new InitialContext(props);
        return context;
    } catch (NoInitialContextException e) {
        // Try to be more helpful, indicating the reason we couldn't make the connection in this
        // common case of missing libraries.
        if (e.getCause() instanceof ClassNotFoundException) {
            throw new ConnectionException(
                    "Necessary classes not found for remote connection, check installation path configuration.",
                    e.getCause());
        }
        throw e;
    }
}

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

private ConnectionFactory lookupConnectionFactoryWithJndi() throws Exception {
    String channelId = connector.getChannelId();
    String channelName = connector.getChannel().getName();

    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {/*from ww  w .  j a v  a  2 s.com*/
        MirthContextFactory contextFactory = contextFactoryController.getContextFactory(resourceIds);
        Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.PROVIDER_URL,
                replacer.replaceValues(connectorProperties.getJndiProviderUrl(), channelId, channelName));
        env.put(Context.INITIAL_CONTEXT_FACTORY, replacer
                .replaceValues(connectorProperties.getJndiInitialContextFactory(), channelId, channelName));
        env.put(Context.SECURITY_PRINCIPAL,
                replacer.replaceValues(connectorProperties.getUsername(), channelId, channelName));
        env.put(Context.SECURITY_CREDENTIALS,
                replacer.replaceValues(connectorProperties.getPassword(), channelId, channelName));

        initialContext = new InitialContext(env);
        String connectionFactoryName = replacer
                .replaceValues(connectorProperties.getJndiConnectionFactoryName(), channelId, channelName);
        return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizConn() throws Exception {

    Hashtable<String, String> vars = new Hashtable<String, String>();
    Context ctx;//from w  w w.  ja  va 2 s.c o m
    Object obj;

    if (!isEmpty(_ctxFac)) {
        vars.put(Context.INITIAL_CONTEXT_FACTORY, _ctxFac);
    }

    if (!isEmpty(_url)) {
        vars.put(Context.PROVIDER_URL, _url);
    }

    if (!isEmpty(_JNDIPwd)) {
        vars.put("jndi.password", _JNDIPwd);
    }

    if (!isEmpty(_JNDIUser)) {
        vars.put("jndi.user", _JNDIUser);
    }

    ctx = new InitialContext(vars);
    obj = ctx.lookup(_connFac);

    if (obj instanceof QueueConnectionFactory) {
        inizQueue(ctx, obj);
    } else if (obj instanceof TopicConnectionFactory) {
        inizTopic(ctx, obj);
    } else if (obj instanceof ConnectionFactory) {
        inizFac(ctx, obj);
    } else {
        throw new Exception("JmsIO: unsupported JMS Connection Factory");
    }

    if (_conn != null) {
        _conn.start();
    }
}

From source file:org.apache.torque.JndiConfigurationTest.java

/**
 * Binds a DataSource to the jndi and checks that we have successfully
 * bound it. Then Torque is configured to lookup the DataSource in jndi,
 * and it is checked if Torque can read from the database. Finally,
 * the DataSource is closed and unbound.
 * @throws Exception if the test fails/*from ww w.  j  a  va2  s  .c o  m*/
 */
public void testExternalBindTorqueLookup() throws Exception {
    // compose the correct configuration
    Configuration torqueConfiguration = getTorqueConfiguraton();
    String defaultDatabase = getDefaultDatabase(torqueConfiguration);

    // remove the dsfactory configuration from the configuration
    {
        Configuration dsfactoryConfiguration = torqueConfiguration
                .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase);
        dsfactoryConfiguration.clear();
    }

    // add the jndi configuration to the configuration
    torqueConfiguration.setProperty(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "."
            + defaultDatabase + "." + DataSourceFactory.FACTORY_KEY, JndiDataSourceFactory.class.getName());
    torqueConfiguration.setProperty(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "."
            + defaultDatabase + "." + JndiDataSourceFactory.JNDI_KEY + "." + JndiDataSourceFactory.PATH_KEY,
            JNDI_PATH);
    torqueConfiguration.setProperty(
            Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                    + JndiDataSourceFactory.JNDI_KEY + "." + Context.INITIAL_CONTEXT_FACTORY,
            org.apache.naming.java.javaURLContextFactory.class.getName());

    //System.out.println("Configuration for testExternalBindTorqueLookup:");
    //debugConfiguration(torqueConfiguration);
    //System.out.println();

    try {
        // bind datasource and check bind.
        bindDataSource();
        BasicDataSource dataSource = retrieveDataSource();
        dataSourceConnect(dataSource);

        if (Torque.isInit()) {
            Torque.shutdown();
        }
        // initialize torque with the created configuration
        // and check that we can connect to the database.
        try {
            Torque.init(torqueConfiguration);
            torqueConnect();
        } finally {
            Torque.shutdown();
        }
    } finally {
        unbindDataSource();
    }
}

From source file:net.sf.taverna.t2.provenance.api.ProvenanceAccess.java

/**
 * Initialises a named JNDI DataSource if not already set up externally.
 * The DataSource is named jdbc/taverna//www.  ja v  a 2 s  .com
 *
 * @param driverClassName - the classname for the driver to be used.
 * @param jdbcUrl - the jdbc connection url
 * @param username - the username, if required (otherwise null)
 * @param password - the password, if required (oteherwise null)
 * @param minIdle - if the driver supports multiple connections, then the minumum number of idle connections in the pool
 * @param maxIdle - if the driver supports multiple connections, then the maximum number of idle connections in the pool
 * @param maxActive - if the driver supports multiple connections, then the minumum number of connections in the pool
 */
public static void initDataSource(String driverClassName, String jdbcUrl, String username, String password,
        int minIdle, int maxIdle, int maxActive) {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setMaxIdle(maxIdle);
    ds.setDefaultAutoCommit(true);
    if (username != null) {
        ds.setUsername(username);
    }
    if (password != null) {
        ds.setPassword(password);
    }

    ds.setUrl(jdbcUrl);

    InitialContext context;
    try {
        context = new InitialContext();
        context.rebind("jdbc/taverna", ds);
    } catch (NamingException ex) {
        logger.error("Problem rebinding the jdbc context: " + ex);
    }

}

From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.LdapCommentAuthenticator.java

public boolean authenticate(HttpServletRequest request) {
    boolean validUser = false;
    LdapContext context = null;/*from  w ww  .jav a 2 s . c o m*/

    String ldapDc = WebloggerConfig.getProperty("comment.authenticator.ldap.dc");
    String ldapOu = WebloggerConfig.getProperty("comment.authenticator.ldap.ou");
    String ldapPort = WebloggerConfig.getProperty("comment.authenticator.ldap.port");
    String ldapHost = WebloggerConfig.getProperty("comment.authenticator.ldap.host");
    String ldapSecurityLevel = WebloggerConfig.getProperty("comment.authenticator.ldap.securityLevel");

    boolean rollerPropertiesValid = validateRollerProperties(ldapDc, ldapOu, ldapPort, ldapHost);

    String ldapUser = request.getParameter("ldapUser");
    String ldapPass = request.getParameter("ldapPass");

    boolean userDataValid = validateUsernamePass(ldapUser, ldapPass);

    if (rollerPropertiesValid && userDataValid) {
        try {
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            if (ldapSecurityLevel != null && (ldapSecurityLevel.equalsIgnoreCase("none")
                    || ldapSecurityLevel.equalsIgnoreCase("simple")
                    || ldapSecurityLevel.equalsIgnoreCase("strong"))) {
                env.put(Context.SECURITY_AUTHENTICATION, ldapSecurityLevel);
            }
            env.put(Context.SECURITY_PRINCIPAL, getQualifedDc(ldapDc, ldapOu, ldapUser));
            env.put(Context.SECURITY_CREDENTIALS, ldapPass);
            env.put(Context.PROVIDER_URL, "ldap://" + ldapHost + ":" + ldapPort);
            context = new InitialLdapContext(env, null);
            validUser = true;
            LOG.info("LDAP Authentication Successful. user: " + ldapUser);
        } catch (Exception e) {
            // unexpected
            LOG.error(e);
        } finally {
            if (context != null) {
                try {
                    context.close();
                } catch (NamingException e) {
                    LOG.error(e);
                }
            }
        }
    }
    return validUser;
}

From source file:eu.europa.ec.markt.dss.validation.crl.OnlineCRLSource.java

/**
 * Downloads a CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 *
 * @throws CertificateException//from w w w. jav  a2 s . c  o  m
 * @throws CRLException
 */

private static X509CRL downloadCRLFromLDAP_(final String ldapURL) throws DSSException {

    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);
    try {

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes("");
        final javax.naming.directory.Attribute attribute = attributes.get("certificateRevocationList;binary");
        final byte[] val = (byte[]) attribute.get();
        if (val == null || val.length == 0) {

            throw new DSSException("Can not download CRL from: " + ldapURL);
        }
        final InputStream inStream = new ByteArrayInputStream(val);
        return DSSUtils.loadCRL(inStream);
    } catch (Exception e) {

        LOG.warning(e.getMessage());
        e.printStackTrace();
    }
    return null;
}

From source file:org.andromda.timetracker.test.EJB3Container.java

private static Hashtable<String, String> getInitialContextProperties() {
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.LocalOnlyContextFactory");
    props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
    return props;
}

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

private Hashtable<String, String> initializeWithLdapConnectionSettings(LdapServer ldapServer) {
    Hashtable<String, String> env = new Hashtable<>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapServer.getUrl());
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, ldapServer.getManagerLogin());

    String encryptedManagerPassword = ldapServer.getManagerPassword();
    String decryptedManagerPassword = passwordEncoder.decrypt(encryptedManagerPassword);

    env.put(Context.SECURITY_CREDENTIALS, decryptedManagerPassword);

    if (ldapServer.isUseSsl()) {
        String keystorepath = ldapServer.getKeystore();
        String keystorepasswd = ldapServer.getKeystorePassword();

        // add all necessary certificates first
        loadCertificates(keystorepath, keystorepasswd, ldapServer);

        // set properties, so that the current keystore is used for SSL
        System.setProperty("javax.net.ssl.keyStore", keystorepath);
        System.setProperty("javax.net.ssl.trustStore", keystorepath);
        System.setProperty("javax.net.ssl.keyStorePassword", keystorepasswd);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }/*from w  w w  . j a  v a 2s  .c om*/
    return env;
}