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.metrics.impl.ReporterTest.java

public static Test suite() {
    return new TestSetup(new TestSuite(ReporterTest.class)) {

        protected void setUp() throws Exception {
            DataSource dataSource = JdbcConnectionPool.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "");
            template = new JdbcTemplate(dataSource);
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
            populator.addScript(new ClassPathResource("dbscripts/h2.sql"));
            populator.populate(dataSource.getConnection());

            // Create initial context
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
            InitialContext ic = new InitialContext();
            ic.createSubcontext("jdbc");
            ic.bind("jdbc/WSO2MetricsDB", dataSource);

            // Set setup system property to cover database creator logic
            System.setProperty("setup", "");
        }//from www .  j a  va 2s . com

        protected void tearDown() throws Exception {
            InitialContext ic = new InitialContext();
            ic.unbind("jdbc/WSO2MetricsDB");
            ic.unbind("jdbc");
        }
    };
}

From source file:com.constellio.model.services.users.sync.FastBindConnectionControl.java

@SuppressWarnings("unchecked")
public LDAPFastBind(String ldapurl, Boolean followReferences, boolean activeDirectory) {
    env = new Hashtable();
    //This can make LDAP search slow : http://stackoverflow.com/questions/16412236/how-to-resolve-javax-naming-partialresultexception
    //env.put(Context.REFERRAL, "follow");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.PROVIDER_URL, ldapurl);
    env.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
    if (followReferences) {
        env.put(Context.REFERRAL, "follow");
    }/*from  ww  w .j a  v  a2s . com*/

    if (StringUtils.startsWith(ldapurl, "ldaps")) {
        //env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put("java.naming.ldap.factory.socket",
                "com.constellio.model.services.users.sync.ldaps.DummySSLSocketFactory");
    }

    if (activeDirectory) {
        connCtls = new Control[] { new FastBindConnectionControl() };
    } else {
        connCtls = new Control[] {};
    }

    //first time we initialize the context, no credentials are supplied
    //therefore it is an anonymous bind.      

    /*try {
       ctx = new InitialLdapContext(env, connCtls);
            
    } catch (NamingException e) {
       throw new RuntimeNamingException(e.getMessage());
    }*/
    //FIX de Vincent pour o a q
    try {
        ctx = new InitialLdapContext(env, connCtls);
    } catch (NamingException e) {
        if (activeDirectory) {
            connCtls = new Control[] {};
            try {
                ctx = new InitialLdapContext(env, connCtls);
            } catch (NamingException e2) {
                throw new RuntimeException(e);
            }
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.jaeksoft.searchlib.util.ActiveDirectory.java

public ActiveDirectory(String username, String password, String domain) throws NamingException {
    if (StringUtils.isEmpty(domain))
        throw new NamingException("The domain is empty");
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    properties.put(Context.PROVIDER_URL, StringUtils.fastConcat("LDAP://", domain));
    properties.put(Context.SECURITY_PRINCIPAL, StringUtils.fastConcat(username, "@", domain));
    properties.put(Context.SECURITY_CREDENTIALS, password);
    properties.put("java.naming.ldap.attributes.binary", "objectSID");
    properties.put(Context.REFERRAL, "follow");
    dirContext = new InitialDirContext(properties);
    domainSearchName = getDomainSearch(domain);
}

From source file:com.mycompany.mockitotomee.service.GreetingServiceIT.java

@Configuration
public Properties configuration() {
    return new Properties() {
        private static final long serialVersionUID = 3109256773218160485L;

        {//from   w  w w .  ja va2  s . com
            setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
            setProperty("MailProvider", "new://Resource=type=javax.mail.Session");
            setProperty("MailProvider.mail.smtp.host", "127.0.0.1");
            setProperty("MailProvider.mail.smtp.port", "25");
            setProperty("MailProvider.mail.transport.protocol", "smtp");
            setProperty("MailProvider.mail.smtp.auth", "false");
            setProperty("MailProvider.mail.smtp.user", "someuser");
            setProperty("MailProvider.password", "mypassword");
            setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
            String providers = String.format("%s", JacksonJsonProvider.class.getName());
            setProperty("cxf.jaxrs.providers", providers);
        }
    };
}

From source file:it.unipmn.di.dcs.sharegrid.web.model.StandardEnvironment.java

private Context getContext() throws NamingException {
    if (this.envCtx == null) {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, ManagementContextFactory.class.getName());
        //env.put(Context.PROVIDER_URL, "");
        //env.put(Context.OBJECT_FACTORIES, "foo.bar.ObjFactory");
        //System.err.println( "INITIAL_CONTEXT_FACTORY: " + Context.INITIAL_CONTEXT_FACTORY );//XXX
        //System.err.println( "URL_PKG_PREFIXES: " + Context.URL_PKG_PREFIXES );//XXX
        env.put(Context.URL_PKG_PREFIXES, ManagementContextFactory.class.getName());

        //System.err.println("ENV URI: " + envUri);//XXX
        Context ctx = new InitialContext(env);
        if (ctx != null) {
            //System.err.println("CONTEXT NOT NULL");//XXX
            String[] parts = this.envUri.split("/");
            Context[] ctxs = new Context[parts.length + 1];
            ctxs[0] = ctx;/*  ww  w. ja va2 s.co  m*/
            int i = 1;
            for (String envPart : parts) {
                //System.err.println("ENV PART: " + envPart);//XXX
                ctxs[i] = (Context) this.getOrCreateSubcontext(envPart, ctxs[i - 1]);
                i++;
            }
            this.envCtx = (Context) this.getOrCreateSubcontext(this.envUri, ctx);
            //System.err.println("ENV CONTEXT: " + this.envCtx);//XXX

            //Properties properties = new Properties();
            //properties.put( "driverClassName", "com.mysql.jdbc.Driver" );
            //properties.put( "url", "jdbc:mysql://localhost:3306/sharegrid" );
            //properties.put( "username", "root" );
            //properties.put( "password", "" );
            //javax.sql.DataSource dataSource = org.apache.commons.dbcp.BasicDataSourceFactory.createDataSource( properties );
            //this.envCtx.rebind( "jdbc/mysql", dataSource );
        }
    }

    return this.envCtx;
}

From source file:org.sonar.server.database.JndiDatabaseConnectorTest.java

@Before
public void setup() {
    conf = mock(Configuration.class);
    when(conf.getString(eq(DatabaseProperties.PROP_JNDI_NAME), anyString())).thenReturn("test");
    when(conf.getString(eq(DatabaseProperties.PROP_DIALECT))).thenReturn(DatabaseProperties.DIALECT_HSQLDB);
    currentInitialContextFacto = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    connector = getTestJndiConnector(conf);
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestInitialContextFactory.class.getName());
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

private static DirContext getAuthContext(String userCN, String password, boolean dedicatedAdminUser)
        throws NamingException {
    ResourceBundle rb = ResourceBundle.getBundle("ldap");
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, rb.getString("url"));
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    if (dedicatedAdminUser) {
        env.put(Context.SECURITY_PRINCIPAL, rb.getString("bindDN"));
        env.put(Context.SECURITY_CREDENTIALS, rb.getString("bindPass"));
    } else {//from   ww  w . ja  v  a2  s  .  c o  m
        env.put(Context.SECURITY_PRINCIPAL, "cn=" + userCN + "," + rb.getString("peopleRoot"));
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    return new InitialDirContext(env);

}

From source file:org.mule.object.JndiObjectFactory.java

public void initialise() throws InitialisationException {
    if (_context == null) {
        Hashtable props = new Hashtable();

        if (initialFactory != null) {
            props.put(Context.INITIAL_CONTEXT_FACTORY, initialFactory);
        } else if (properties == null || !properties.containsKey(Context.INITIAL_CONTEXT_FACTORY)) {
            throw new InitialisationException(CoreMessages.objectIsNull("jndiInitialFactory"), this);
        }//from  w ww .  j  a  v a2s  .  c  o m

        if (url != null) {
            props.put(Context.PROVIDER_URL, url);
        }

        if (properties != null) {
            props.putAll(properties);
        }

        try {
            _context = new InitialContext(props);
        } catch (NamingException e) {
            throw new InitialisationException(e, this);
        }
    }
}

From source file:org.wso2.carbon.appfactory.eventing.jms.TopicPublisher.java

public void publishMessage(Event event) throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, Util.getTCPConnectionURL());
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
    try {/*from   w  w w  . j  a va2  s .com*/
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(CF_NAME);
    } catch (NamingException e) {
        throw new AppFactoryEventException("Failed to initialize InitialContext.", e);
    }

    TopicConnection topicConnection = null;
    TopicSession topicSession = null;
    try {
        topicConnection = connFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
        // Send message
        String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        Topic topic = topicSession.createTopic(event.getTarget());

        //Until MB supports 'Dynamic Topics' we have to create a subscription, therefore forcing Message broker to
        // create the topic.
        String defaultSubscriptionId = tenantDomain + "/" + DEFAULT_SUBSCRIPTION + UUID.randomUUID();
        topicSubscriber = topicSession.createDurableSubscriber(topic, defaultSubscriptionId);
        // We are unsubscribing from the Topic as soon as
        topicSession.unsubscribe(defaultSubscriptionId);

        // create the message to send
        MapMessage mapMessage = topicSession.createMapMessage();
        mapMessage.setString(MESSAGE_TITLE, event.getMessageTitle());
        mapMessage.setString(MESSAGE_BODY, event.getMessageBody());
        javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicConnection.start();
        topicPublisher.publish(mapMessage);
        if (log.isDebugEnabled()) {
            log.debug("Message with Id:" + mapMessage.getJMSMessageID() + ", with title:"
                    + event.getMessageTitle() + " was successfully published.");
        }

    } catch (JMSException e) {
        log.error("Failed to publish message due to " + e.getMessage(), e);
        throw new AppFactoryEventException("Failed to publish message due to " + e.getMessage(), e);
    } finally {
        if (topicSubscriber != null) {
            try {
                topicSubscriber.close();
            } catch (JMSException e) {
                log.error("Failed to close default topic subscriber", e);
            }
        }
        if (topicSession != null) {
            try {
                topicSession.close();
            } catch (JMSException e) {
                log.error("Failed to close topic session", e);
            }
        }
        if (topicConnection != null) {
            try {
                topicConnection.close();
            } catch (JMSException e) {
                log.error("Failed to close topic connection", e);
            }
        }
    }
}

From source file:de.tuttas.util.LDAPUtil.java

/**
 * Benutzer aus der LDAP Abfragen/*from w ww.  j  a v  a  2 s .c om*/
 *
 * @param username Benutzername
 * @param password Kennwort
 * @return der Benutzer
 * @throws Exception Wenn etwas schief ging
 */
public LDAPUser authenticateJndi(String username, String password) throws Exception {
    // Anbindung ans LDAP
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost);
    props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user
    props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password
    try {
        context = new InitialDirContext(props);
        ctrls = new SearchControls();
        ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName",
                "memberOf", "userPrincipalName", "distinguishedName" });
        ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } catch (NamingException ex) {
        Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    NamingEnumeration<javax.naming.directory.SearchResult> answers = context
            .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls);
    Log.d("answers=" + answers);
    Log.d("answers=" + answers.hasMore());

    if (!answers.hasMore()) {
        return null;
    }

    javax.naming.directory.SearchResult result = answers.nextElement();

    try {
        for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) {
            Attribute attr = (Attribute) ae.next();
            Log.d("attribute: " + attr.getID());

            /* print each value */
            for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next()))
                ;
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }

    String inititials = "";
    if (result.getAttributes().get("initials") != null) {
        inititials = result.getAttributes().get("initials").getAll().next().toString();
    }
    LDAPUser u;
    if (result.getAttributes().get("mail") == null) {
        u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(),
                result.getAttributes().get("givenName").getAll().next().toString(), "", inititials);
    } else {
        u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(),
                result.getAttributes().get("givenName").getAll().next().toString(),
                result.getAttributes().get("mail").getAll().next().toString(), inititials);
    }

    String dName = result.getAttributes().get("distinguishedName").getAll().next().toString();
    Log.d("dName=" + dName);
    if (dName.contains("OU=Lehrer")) {
        Log.d("Ich bin ein Lehrer");
        u.setRole(Roles.toString(Roles.LEHRER));
    } else {
        Log.d("Ich bin ein Schler");
        u.setRole(Roles.toString(Roles.SCHUELER));
        if (result.getAttributes().get("memberOf") != null) {
            String memberOf = result.getAttributes().get("memberOf").getAll().next().toString();
            String courseName = memberOf.split(",")[0];
            courseName = courseName.substring(courseName.indexOf("=") + 1);
            Log.d("Name der Klasse ist " + courseName);
            u.setCourse(courseName);
        }
    }

    String user = result.getNameInNamespace();

    try {

        props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost);
        props.put(Context.SECURITY_PRINCIPAL, user);
        props.put(Context.SECURITY_CREDENTIALS, password);

        context = new InitialDirContext(props);
    } catch (Exception e) {
        return null;
    }
    return u;
}