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.wso2.carbon.oc.agent.publisher.mb.MBPublisher.java

/**
 * @param queueName   - String mb queue name
 * @param jsonMessage - String mb queue message json string
 */// w  w  w .  ja  v  a2s . c o m
public void sendMessages(String queueName, String jsonMessage) {

    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(username, password));
        properties.put(QUEUE_NAME_PREFIX + queueName, queueName);
        InitialContext ctx = new InitialContext(properties);
        // lookup connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        QueueConnection queueConnection = connFactory.createQueueConnection();
        queueConnection.start();
        QueueSession queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        // send message
        Queue queue = (Queue) ctx.lookup(queueName);
        // create the message to send

        TextMessage textMessage = queueSession.createTextMessage(jsonMessage);
        QueueSender queueSender = queueSession.createSender(queue);
        queueSender.send(textMessage);
        queueSender.close();
        queueSession.close();
        queueConnection.close();
    } catch (JMSException e) {
        logger.error("MBPublisher connection down", e);
    } catch (NamingException e) {
        logger.error("Naming error", e);
    }

}

From source file:org.compass.core.jndi.NamingHelper.java

/**
 * Transform JNDI properties passed in the form
 * <code>compass.jndi. [vaules]</code> to the format accepted by
 * <code>InitialContext</code> by triming the leading "<code>compass.jndi</code>".
 */// www . j a va 2  s  .  co m
public static Properties getJndiProperties(CompassSettings settings) {
    HashSet specialProps = new HashSet();
    specialProps.add(CompassEnvironment.Jndi.CLASS);
    specialProps.add(CompassEnvironment.Jndi.URL);
    specialProps.add(CompassEnvironment.Jndi.ENABLE);

    Iterator iter = settings.keySet().iterator();
    Properties result = new Properties();
    while (iter.hasNext()) {
        String prop = (String) iter.next();
        if (prop.indexOf(CompassEnvironment.Jndi.PREFIX) > -1 && !specialProps.contains(prop)) {
            result.setProperty(prop.substring(CompassEnvironment.Jndi.PREFIX.length() + 1),
                    settings.getSetting(prop));
        }
    }

    String jndiClass = settings.getSetting(CompassEnvironment.Jndi.CLASS);
    String jndiURL = settings.getSetting(CompassEnvironment.Jndi.URL);
    // we want to be able to just use the defaults,
    // if JNDI environment properties are not supplied
    // so don't put null in anywhere
    if (jndiClass != null)
        result.put(Context.INITIAL_CONTEXT_FACTORY, jndiClass);
    if (jndiURL != null)
        result.put(Context.PROVIDER_URL, jndiURL);

    return result;
}

From source file:net.identio.server.service.authentication.ldap.LdapConnectionFactory.java

private InitialLdapContext createContext(LdapAuthMethod ldapAuthMethod, String userDn, String password)
        throws NamingException {

    LOG.debug("Begin creation of an LDAP connection to: {}", ldapAuthMethod.getName());

    int currentUrlIndexTs = currentUrlIndex;

    String currentUrl = ldapAuthMethod.getLdapUrl().get(currentUrlIndexTs);

    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, currentUrl);

    if (currentUrl.startsWith("ldaps://")) {

        // Add a custom SSL Socket factory to validate server CA
        env.put("java.naming.ldap.factory.socket",
                "net.identio.server.service.authentication.ldap.LdapSslSocketFactory");
    }//ww w .  ja v a 2  s .c  o m

    if (userDn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, userDn);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    InitialLdapContext ctx;

    try {
        ctx = new InitialLdapContext(env, null);
    } catch (CommunicationException e) {

        LOG.error("Error when contacting LDAP server {}", ldapAuthMethod.getLdapUrl().get(currentUrlIndexTs));

        if (ldapAuthMethod.getLdapUrl().size() > 1) {
            int newCurrentUrlIndex = currentUrlIndexTs < ldapAuthMethod.getLdapUrl().size() - 1
                    ? currentUrlIndexTs + 1
                    : 0;

            LOG.error("Switching to LDAP server {}", ldapAuthMethod.getLdapUrl().get(newCurrentUrlIndex));

            currentUrlIndex = newCurrentUrlIndex;

            env.put(Context.PROVIDER_URL, ldapAuthMethod.getLdapUrl().get(newCurrentUrlIndex));

            ctx = new InitialLdapContext(env, null);
        } else {
            throw e;
        }
    }

    return ctx;
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

void activate(Map<?, ?> configuration) throws NamingException {
    this.idSuffix = (String) configuration.get(CONFIG_ID_SUFFIX);
    this.url = (String) configuration.get(CONFIG_URL);
    this.baseDN = (String) configuration.get(CONFIG_BASE_DN);
    this.userSearchBase = (String) configuration.get(CONFIG_USER_SEARCH_BASE);
    this.userFilter = (String) configuration.get(CONFIG_USER_FILTER);

    String managerDN = (String) configuration.get(CONFIG_MANAGER_DN);
    String managerPassword = (String) configuration.get(CONFIG_MANAGER_PASSWORD);

    searchEnvironment = new Hashtable<String, String>();
    searchEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    searchEnvironment.put(Context.PROVIDER_URL, url);

    if (managerDN != null) {
        searchEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        searchEnvironment.put(Context.SECURITY_PRINCIPAL, managerDN);
        searchEnvironment.put(Context.SECURITY_CREDENTIALS, managerPassword);
    } else//from  w w  w.j a  v a2s.  c  om
        searchEnvironment.put(Context.SECURITY_AUTHENTICATION, "none");
}

From source file:org.jboss.test.NamingUtil.java

/**
 * Returns initial context which is able to perform all JNDI operations.
 * @param serverHost - use getServerHostForURL() from inside JBoss Testsuite
 * @param jndiFactoryUrlSuffix - URL suffix to get proper invoker invoker/JNDIFactory or invoker/HAJNDIFactory
 * @return//from  w  ww .ja v  a  2  s.  co m
 * @throws Exception
 */
public static InitialContext getFullInitialContext(String serverHost, String jndiFactoryUrlSuffix)
        throws Exception {

    if (jndiFactoryUrlSuffix == null) {
        jndiFactoryUrlSuffix = JNDI_INVOKER;
    }

    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.HttpNamingContextFactory");

    env.setProperty(Context.PROVIDER_URL, "http://" + serverHost + ":8080/" + jndiFactoryUrlSuffix);
    log.debug("Creating InitialContext with env=" + env);
    InitialContext ctx = new InitialContext(env);

    return ctx;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;// ww w .j  av a  2 s  . co m

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}

From source file:org.exoplatform.services.naming.InitialContextTest.java

public void testGetContext() throws Exception {
    assertNotNull(System.getProperty(Context.INITIAL_CONTEXT_FACTORY));
    InitialContext ctx = new InitialContext();
    assertNotNull(ctx);/* w  ww  . ja v a2 s. co m*/
    ctx.bind("test", "test");
    assertEquals("test", ctx.lookup("test"));
    try {
        ctx.bind("test", "test2");
        fail("A NameAlreadyBoundException is expected here");
    } catch (NameAlreadyBoundException e) {
        // expected exception
    }
    assertEquals("test", ctx.lookup("test"));
    ctx.rebind("test", "test2");
    assertEquals("test2", ctx.lookup("test"));

    initializer.getInitialContext().bind("test", "test3");
    assertEquals("test3", ctx.lookup("test"));
    ctx.rebind("test", "test4");
    assertEquals("test3", ctx.lookup("test"));
    initializer.getInitialContext().rebind("test", "test5");
    assertEquals("test5", ctx.lookup("test"));
    initializer.getInitialContext().unbind("test");
    try {
        initializer.getInitialContext().lookup("test");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    assertEquals("test4", ctx.lookup("test"));
    ctx.unbind("test");
    try {
        ctx.lookup("test");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    try {
        initializer.getInitialContext().unbind("test2");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    initializer.getInitialContext().bind("foo", "foo");
    assertEquals("foo", ctx.lookup("foo"));
    initializer.getInitialContext().bind("foo2", "foo2");
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().rename("foo", "foo2");
        fail("A NameAlreadyBoundException is expected here");
    } catch (NameAlreadyBoundException e) {
        // expected exception
    }
    assertEquals("foo", ctx.lookup("foo"));
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().rename("foo3", "foo4");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    initializer.getInitialContext().rename("foo", "foo3");
    assertEquals("foo", ctx.lookup("foo3"));
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().lookup("foo");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }

    // check same instance
    initializer.getInitialContext().bind("bla", "bla");
    Object obj1 = initializer.getInitialContext().lookup("bla");
    Object obj2 = initializer.getInitialContext().lookup("bla");
    assertTrue(obj1 == obj2);
}

From source file:com.stratelia.silverpeas.versioning.jcr.impl.AbstractJcrTestCase.java

@Resource
public void setDataSource(DataSource datasource) {
    this.datasource = datasource;
    try {//  w w w. j a v a  2 s. co  m
        prepareJndi();
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
        InitialContext ic = new InitialContext(env);
        Properties properties = new Properties();
        properties.load(PathTestUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
        // Construct BasicDataSource reference
        Reference ref = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory",
                null);
        ref.add(new StringRefAddr("driverClassName",
                properties.getProperty("driverClassName", "org.postgresql.Driver")));
        ref.add(new StringRefAddr("url",
                properties.getProperty("url", "jdbc:postgresql://localhost:5432/postgres")));
        ref.add(new StringRefAddr("username", properties.getProperty("username", "postgres")));
        ref.add(new StringRefAddr("password", properties.getProperty("password", "postgres")));
        ref.add(new StringRefAddr("maxActive", "4"));
        ref.add(new StringRefAddr("maxWait", "5000"));
        ref.add(new StringRefAddr("removeAbandoned", "true"));
        ref.add(new StringRefAddr("removeAbandonedTimeout", "5000"));
        rebind(ic, JNDINames.DATABASE_DATASOURCE, ref);
        rebind(ic, JNDINames.ADMIN_DATASOURCE, ref);
    } catch (NamingException nex) {
        nex.printStackTrace();
    } catch (IOException nex) {
        nex.printStackTrace();
    }
}

From source file:org.apache.ftpserver.usermanager.LdapUserManager.java

/**
 * Instantiate LDAP based <code>UserManager</code> implementation.
 *///from   w ww.java 2s.c om
public void configure(Configuration config) throws FtpException {

    try {

        // get admin name 
        m_adminName = config.getString("admin", "admin");

        // get ldap parameters
        String url = config.getString("ldap-url");
        String admin = config.getString("ldap-admin-dn");
        String password = config.getString("ldap-admin-password");
        String auth = config.getString("ldap-authentication", "simple");

        m_userBaseDn = config.getString("ldap-user-base-dn");

        // create connection
        Properties adminEnv = new Properties();
        adminEnv.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        adminEnv.setProperty(Context.PROVIDER_URL, url);
        adminEnv.setProperty(Context.SECURITY_AUTHENTICATION, auth);
        adminEnv.setProperty(Context.SECURITY_PRINCIPAL, admin);
        adminEnv.setProperty(Context.SECURITY_CREDENTIALS, password);
        m_adminContext = new InitialDirContext(adminEnv);

        // create objectClass attribute
        m_objClassAttr = new BasicAttribute(OBJ_CLASS, false);
        m_objClassAttr.add("javaObject");
        m_objClassAttr.add("top");

        m_log.info("LDAP user manager opened.");
    } catch (FtpException ex) {
        throw ex;
    } catch (Exception ex) {
        m_log.fatal("LdapUserManager.configure()", ex);
        throw new FtpException("LdapUserManager.configure()", ex);
    }
}

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

public DirContext getDirContext(Properties props) throws NamingException {
    if (this.ctx == null) {
        synchronized (this) {
            if (this.ctx == null) {
                log.debug("[getDirContext] creating new connection");
                Collection rtn = new TreeSet();
                Hashtable ldapEnv = new Hashtable();
                String ldapDriver = props.getProperty("ldapDriver"),
                        ldapHostURL = props.getProperty("ldapHostURL"),
                        ldapAuthType = props.getProperty("ldapAuthType"),
                        ldapPasswd = props.getProperty("ldapPasswd"),
                        ldapTreePathToDN = props.getProperty("ldapTreePathToDN");
                ldapTreePathToDN = (ldapTreePathToDN == null) ? "" : ldapTreePathToDN;
                ldapPasswd = (ldapPasswd == null) ? "" : ldapPasswd;
                ldapPasswd = (ldapPasswd.matches("^\\s*$")) ? "" : ldapPasswd;
                ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, ldapDriver);
                ldapEnv.put(Context.PROVIDER_URL, ldapHostURL);
                ldapEnv.put(Context.SECURITY_AUTHENTICATION, ldapAuthType);
                ldapEnv.put(Context.SECURITY_PRINCIPAL, ldapTreePathToDN);
                ldapEnv.put(Context.SECURITY_CREDENTIALS, ldapPasswd);
                this.ctx = new InitialDirContext(ldapEnv);
            }//w ww .  j  a va2  s .  c  o  m
        }
    }
    return this.ctx;
}