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.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 *//*  ww  w  .  j  a v  a  2  s . com*/
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
    if (namingEnum.hasMore()) {
        SearchResult sr = (SearchResult) namingEnum.next();
        Attributes attrs = sr.getAttributes();
        assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence,
                new Integer(attrs.get("telephoneNumber").get().toString()));
        assertEquals("Unexpected hash value in LDAP attribute",
                Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString());
    } else {
        fail("User not found in LDAP");
    }

    namingEnum.close();
    ctx.close();
}

From source file:org.jboss.as.quickstarts.secured.ejb.remote.client.RemoteEJBClient.java

private void initLookupContextProps() {
    props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
    if (this.useSSLOnRemoteEJBProps) {
        initSSLParams();/*w  w  w .  j  a  v a2  s.  c  o m*/
        CommandLineArgumentsParserUtils.printSysProps(props);
    }

    if (!this.setRemoteEJBProps) {
        return;
    }
    props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");

    String url = "remote://" + this.host + STR_COLON_SEPARATOR + this.port;

    props.put(Context.PROVIDER_URL, url);
    props.put("remote.connections", "default");
    props.put("remote.connection.default.host", this.host);
    props.put("remote.connection.default.port", this.port);
    props.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");

    if (this.useSSLOnRemoteEJBProps) {

        props.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "true");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_ENABLED", "true");

        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS",
                "false");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS",
                "JBOSS-LOCAL-USER");

    } else {
        props.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_ENABLED", "false");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_STARTTLS", "false");
        props.put("remote.connection.default.username", this.username);
        props.put("remote.connection.default.password", this.password);
    }
    EJBClientConfiguration cc = new PropertiesBasedEJBClientConfiguration(props);
    ContextSelector<EJBClientContext> sel = new ConfigBasedEJBClientContextSelector(cc);
    EJBClientContext.setSelector(sel);

    CommandLineArgumentsParserUtils.printSysProps(props);
    CommandLineArgumentsParserUtils.printProps(props);
}

From source file:org.wso2.extension.siddhi.store.rdbms.util.RDBMSTableTestUtils.java

public static void setupJNDIDatasource(String url, String driverClassName) {
    try {//from w w w .  j  a v  a  2  s .  c o m
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        InitialContext context = new InitialContext();
        context.createSubcontext("java:");
        context.createSubcontext("java:comp");
        context.createSubcontext("java:comp/env");
        context.createSubcontext("java:comp/env/jdbc");
        Properties connectionProperties = new Properties();
        connectionProperties.setProperty("jdbcUrl", url);
        connectionProperties.setProperty("dataSource.user", user);
        connectionProperties.setProperty("dataSource.password", password);
        connectionProperties.setProperty("driverClassName", driverClassName);
        connectionProperties.setProperty("poolName", "JNDI_Pool");
        HikariConfig config = new HikariConfig(connectionProperties);
        DataSource testDataSourceJNDI = new HikariDataSource(config);
        context.bind(JNDI_RESOURCE, testDataSourceJNDI);
    } catch (NamingException e) {
        log.error("Error while bind the datasource as JNDI resource." + e.getMessage(), e);
    }
}

From source file:com.communote.server.test.ldap.AbstractApacheDSServer.java

/**
 * Common code to get an initial context via a simple bind to the server over the wire using the
 * SUN JNDI LDAP provider. Do not use this method until after the setUp() method is called to
 * start the server otherwise it will fail.
 *
 * @param bindPrincipalDn//from w w w  .j  a va2  s  . c o m
 *            the DN of the principal to bind as
 * @param password
 *            the password of the bind principal
 * @return an LDAP context as the the administrator to the rootDSE
 * @throws Exception
 *             if the server cannot be contacted
 */
protected LdapContext getWiredContext(String bindPrincipalDn, String password) throws Exception {
    // if ( ! apacheDS.isStarted() )
    // {
    // throw new ConfigurationException( "The server is not online! Cannot connect to it." );
    // }

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY);
    env.put(Context.PROVIDER_URL, "ldap://localhost:" + getPort());
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipalDn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    return new InitialLdapContext(env, null);
}

From source file:org.jsecurity.realm.ldap.DefaultLdapContextFactory.java

public LdapContext getLdapContext(String username, String password) throws NamingException {
    if (searchBase == null) {
        throw new IllegalStateException("A search base must be specified.");
    }// w ww.  j  av a 2s  .  co m
    if (url == null) {
        throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>");
    }

    if (username != null && principalSuffix != null) {
        username += principalSuffix;
    }

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

    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (username != null) {
        env.put(Context.SECURITY_PRINCIPAL, username);
    }
    if (password != null) {
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName);
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.REFERRAL, referral);

    // Only pool connections for system contexts
    if (usePooling && username != null && username.equals(systemUsername)) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
    }

    if (additionalEnvironment != null) {
        env.putAll(additionalEnvironment);
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing LDAP context using URL [" + url + "] and username [" + systemUsername + "] "
                + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]");
    }

    return new InitialLdapContext(env, null);
}

From source file:org.springframework.mock.jndi.SimpleNamingContextBuilder.java

/**
 * Simple InitialContextFactoryBuilder implementation,
 * creating a new SimpleNamingContext instance.
 * @see SimpleNamingContext/* w w w.  j av  a  2 s .c o m*/
 */
@Override
public InitialContextFactory createInitialContextFactory(@Nullable Hashtable<?, ?> environment) {
    if (activated == null && environment != null) {
        Object icf = environment.get(Context.INITIAL_CONTEXT_FACTORY);
        if (icf != null) {
            Class<?> icfClass;
            if (icf instanceof Class) {
                icfClass = (Class<?>) icf;
            } else if (icf instanceof String) {
                icfClass = ClassUtils.resolveClassName((String) icf, getClass().getClassLoader());
            } else {
                throw new IllegalArgumentException("Invalid value type for environment key ["
                        + Context.INITIAL_CONTEXT_FACTORY + "]: " + icf.getClass().getName());
            }
            if (!InitialContextFactory.class.isAssignableFrom(icfClass)) {
                throw new IllegalArgumentException("Specified class does not implement ["
                        + InitialContextFactory.class.getName() + "]: " + icf);
            }
            try {
                return (InitialContextFactory) ReflectionUtils.accessibleConstructor(icfClass).newInstance();
            } catch (Throwable ex) {
                throw new IllegalStateException("Unable to instantiate specified InitialContextFactory: " + icf,
                        ex);
            }
        }
    }

    // Default case...
    return new InitialContextFactory() {
        @Override
        @SuppressWarnings("unchecked")
        public Context getInitialContext(Hashtable<?, ?> environment) {
            return new SimpleNamingContext("", boundObjects, (Hashtable<String, Object>) environment);
        }
    };
}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

@SuppressWarnings("unused")
private ApacheDS startKerberos() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    kdcServer.setDirectoryService(directoryService);
    // FIXME hard-coded ports
    kdcServer.setTransports(new TcpTransport(6088), new UdpTransport(6088));
    kdcServer.setEnabled(true);//w w w . j a v  a  2s .  c om
    kdcServer.setPrimaryRealm(realm);
    kdcServer.setSearchBaseDn(baseDn);
    kdcServer.setKdcPrincipal("krbtgt/" + realm + "@" + baseDn);
    kdcServer.start();

    // -------------------------------------------------------------------
    // Enable the krb5kdc schema
    // -------------------------------------------------------------------

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, directoryService);
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    InitialLdapContext schemaRoot = new InitialLdapContext(env, null);

    // check if krb5kdc is disabled
    Attributes krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");
    boolean isKrb5KdcDisabled = false;
    if (krb5kdcAttrs.get("m-disabled") != null) {
        isKrb5KdcDisabled = ((String) krb5kdcAttrs.get("m-disabled").get()).equalsIgnoreCase("TRUE");
    }

    // if krb5kdc is disabled then enable it
    if (isKrb5KdcDisabled) {
        Attribute disabled = new BasicAttribute("m-disabled");
        ModificationItem[] mods = new ModificationItem[] {
                new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled) };
        schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
    }
    return this;
}

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

public void startLdapServer() {
    cfg = new MutableStartupConfiguration();
    cfg.setWorkingDirectory(workingDir);

    log.debug("Working directory is " + workingDir.getAbsolutePath());

    Properties env = new Properties();

    env.setProperty(Context.PROVIDER_URL, BASE_DN);
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    env.setProperty(Context.SECURITY_PRINCIPAL, PartitionNexus.ADMIN_PRINCIPAL);
    env.setProperty(Context.SECURITY_CREDENTIALS, PartitionNexus.ADMIN_PASSWORD);

    try {/*from   w  w  w  .  jav a  2 s  .com*/
        initConfiguration();
        env.putAll(cfg.toJndiEnvironment());
        serverContext = new InitialDirContext(env);
    } catch (NamingException e) {
        log.error("Failed to start Apache DS: ", e);
    }
}

From source file:de.micromata.genome.util.runtime.jndi.SimpleNamingContextBuilder.java

/**
 * Simple InitialContextFactoryBuilder implementation, creating a new SimpleNamingContext instance.
 * /*from w  w  w  . j a v  a  2 s. co  m*/
 * @see SimpleNamingContext
 */
@Override
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) {
    if (activated == null && environment != null) {
        Object icf = environment.get(Context.INITIAL_CONTEXT_FACTORY);
        if (icf != null) {
            Class<?> icfClass;
            if (icf instanceof Class) {
                icfClass = (Class<?>) icf;
            } else if (icf instanceof String) {
                icfClass = resolveClassName((String) icf, getClass().getClassLoader());
            } else {
                throw new IllegalArgumentException("Invalid value type for environment key ["
                        + Context.INITIAL_CONTEXT_FACTORY + "]: " + icf.getClass().getName());
            }
            if (!InitialContextFactory.class.isAssignableFrom(icfClass)) {
                throw new IllegalArgumentException("Specified class does not implement ["
                        + InitialContextFactory.class.getName() + "]: " + icf);
            }
            try {
                return (InitialContextFactory) icfClass.newInstance();
            } catch (Throwable ex) {
                throw new IllegalStateException("Cannot instantiate specified InitialContextFactory: " + icf,
                        ex);
            }
        }
    }

    // Default case...
    return new InitialContextFactory() {
        @Override
        @SuppressWarnings("unchecked")
        public Context getInitialContext(Hashtable<?, ?> environment) {
            return new SimpleNamingContext("", boundObjects, (Hashtable<String, Object>) environment);
        }
    };
}

From source file:jp.terasoluna.fw.web.jndi.DefaultJndiSupport.java

/**
 * JndiTemplate??//from w w w .j  a  v  a  2 s .  c o  m
 */
public void initialize() {

    // JNDI???????Weblogic??
    if (jndiEnvironmentMap != null) {

        // jndiEnvironmentMap???
        String factory = jndiEnvironmentMap.get(JNDI_FACTORY_KEY);
        String url = jndiEnvironmentMap.get(JNDI_URL_KEY);
        String username = jndiEnvironmentMap.get(JNDI_USERNAME_KEY);
        String password = jndiEnvironmentMap.get(JNDI_PASSWORD_KEY);

        Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        environment.put(Context.PROVIDER_URL, url);

        if (!"".equals(username) && username != null) {
            environment.put(Context.SECURITY_PRINCIPAL, username);
            if (password == null) {
                password = "";
            }
            environment.put(Context.SECURITY_CREDENTIALS, password);
        }

        // ??
        getJndiTemplate().setEnvironment(environment);

        // 
        if (log.isInfoEnabled()) {
            log.info("Initialize Weblogic JNDI Resource");
            log.info(Context.INITIAL_CONTEXT_FACTORY + " = " + factory);
            log.info(Context.PROVIDER_URL + " = " + url);
            log.info(Context.SECURITY_PRINCIPAL + " = " + username);
            log.info(Context.SECURITY_CREDENTIALS + " = " + password);
        }
    }
}