List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY
String INITIAL_CONTEXT_FACTORY
To view the source code for javax.naming Context INITIAL_CONTEXT_FACTORY.
Click Source Link
From source file:com.adaptris.core.SharedComponentListTest.java
public void testRemoveConnection_unbindsJNDI() throws Exception { Adapter adapter = new Adapter(); adapter.setUniqueId(getName());/*from ww w.j a v a2 s . c om*/ adapter.getSharedComponents().addConnection(new NullConnection(getName())); Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName()); InitialContext initialContext = new InitialContext(env); try { start(adapter); NullConnection lookedup = (NullConnection) initialContext.lookup("adapter:comp/env/" + getName()); assertNotNull(lookedup); assertEquals(getName(), lookedup.getUniqueId()); adapter.getSharedComponents().removeConnection(getName()); try { initialContext.lookup("adapter:comp/env/" + getName()); fail(); } catch (NamingException expected) { } } finally { stop(adapter); } }
From source file:org.apache.synapse.commons.datasource.JNDIBasedDataSourceRepository.java
private Properties createJNDIEnvironment(Properties dsProperties, String name) { String namingFactory = DataSourceConstants.DEFAULT_IC_FACTORY; String providerUrl = null;/*from w w w.ja v a2s . c om*/ int port = DataSourceConstants.DEFAULT_PROVIDER_PORT; String providerPort = null; // setting naming provider Properties jndiEvn = new Properties(); //This is needed for PerUserPoolDatasource if (dsProperties != null && !dsProperties.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Using properties " + dsProperties + " to create JNDI Environment"); } StringBuffer buffer = new StringBuffer(); buffer.append(DataSourceConstants.PROP_SYNAPSE_PREFIX_DS); buffer.append(DataSourceConstants.DOT_STRING); if (name != null && !"".equals(name)) { buffer.append(name); buffer.append(DataSourceConstants.DOT_STRING); } // The prefix for root level jndiProperties String rootPrefix = buffer.toString(); namingFactory = MiscellaneousUtil.getProperty(dsProperties, rootPrefix + DataSourceConstants.PROP_IC_FACTORY, DataSourceConstants.DEFAULT_IC_FACTORY); //Provider URL providerUrl = MiscellaneousUtil.getProperty(dsProperties, rootPrefix + DataSourceConstants.PROP_PROVIDER_URL, null); providerPort = MiscellaneousUtil.getProperty(dsProperties, rootPrefix + DataSourceConstants.PROP_PROVIDER_PORT, String.valueOf(DataSourceConstants.DEFAULT_PROVIDER_PORT)); } jndiEvn.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory); if (providerUrl != null && !"".equals(providerUrl)) { if (log.isDebugEnabled()) { log.debug("Using provided initial context provider url :" + providerUrl); } } else { if (log.isDebugEnabled()) { log.debug("No initial context provider url...creaeting a new one"); } String providerHost = "localhost"; try { InetAddress addr = InetAddress.getLocalHost(); if (addr != null) { String hostname = addr.getHostName(); if (hostname == null) { String ipAddr = addr.getHostAddress(); if (ipAddr != null) { providerHost = ipAddr; } } else { providerHost = hostname; } } } catch (UnknownHostException e) { log.warn("Unable to determine hostname or IP address.. Using localhost", e); } // default port for RMI registry if (providerPort != null) { try { port = Integer.parseInt(providerPort); } catch (NumberFormatException ignored) { } } // Create a RMI local registry RMIRegistryController.getInstance().createLocalRegistry(port); cachedPorts.add(port); providerUrl = "rmi://" + providerHost + ":" + port; } jndiEvn.put(Context.PROVIDER_URL, providerUrl); log.info("DataSources will be registered in the JNDI context with provider PROP_URL : " + providerUrl); return jndiEvn; }
From source file:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java
public void createSampleEntity() throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.SECURITY_PRINCIPAL, securityPrincipal); env.put(Context.SECURITY_CREDENTIALS, securityCredentials); DirContext ctx = new InitialDirContext(env); Attributes entry = new BasicAttributes(); Attribute obClassAttr = new BasicAttribute("objectClass"); obClassAttr.add("inetOrgPerson"); entry.put(obClassAttr);/*from w ww . j a v a2s .c o m*/ Attribute mailAttr = new BasicAttribute("mail"); mailAttr.add(testUserId + "@wso2.com"); entry.put(mailAttr); Attribute passAttr = new BasicAttribute("userPassword"); passAttr.add("12345"); entry.put(passAttr); Attribute snAttr = new BasicAttribute("sn"); snAttr.add("dim"); entry.put(snAttr); Attribute cnAttr = new BasicAttribute("cn"); cnAttr.add("dim"); entry.put(cnAttr); String dn = "uid=" + testUserId + "," + userBase; ctx.createSubcontext(dn, entry); }
From source file:org.apache.synapse.transport.jms.JMSConnectionFactory.java
/** * Return the provider specific [physical] Destination if any * for the destination with the given JNDI name * * @param destinationJndi the JNDI name of the destination * @return the provider specific Destination or null if cannot be found *//*from w w w .ja v a 2 s. c om*/ private Destination getPhysicalDestination(String destinationJndi) { Destination destination = null; try { destination = (Destination) context.lookup(destinationJndi); } catch (NamingException e) { // if we are using ActiveMQ, check for dynamic Queues and Topics String provider = (String) jndiProperties.get(Context.INITIAL_CONTEXT_FACTORY); if (provider.indexOf("activemq") != -1) { try { destination = (Destination) context .lookup(JMSConstants.ACTIVEMQ_DYNAMIC_QUEUE + destinationJndi); } catch (NamingException ne) { try { destination = (Destination) context .lookup(JMSConstants.ACTIVEMQ_DYNAMIC_TOPIC + destinationJndi); } catch (NamingException e1) { log.warn("Error looking up destination for JNDI name : " + destinationJndi); } } } } return destination; }
From source file:org.apache.openaz.xacml.admin.view.components.LDAPPIPConfigurationComponent.java
protected void testLDAPConnection() { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, this.textFieldFactory.getValue()); env.put(Context.PROVIDER_URL, this.textFieldProviderURL.getValue()); env.put(Context.SECURITY_PRINCIPAL, this.textFieldPrincipal.getValue()); env.put(Context.SECURITY_CREDENTIALS, this.textFieldCredentials.getValue()); String auth = this.comboBoxAuthentication.getValue().toString(); env.put(Context.SECURITY_AUTHENTICATION, auth); ///*w w w .j av a 2s . c om*/ // Do we need to do anything? // /* if (auth.equals(LDAP_AUTH_ANONYMOUS)) { } else if (auth.equals(LDAP_AUTH_SIMPLE)) { } else if (auth.equals(LDAP_AUTH_SASL)) { } */ DirContext ctx = null; try { ctx = new InitialDirContext(env); new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true) .show(Page.getCurrent()); } catch (NamingException e) { logger.error(e); new Notification("Connection Failed", "<br/>" + e.getLocalizedMessage(), Type.ERROR_MESSAGE, true) .show(Page.getCurrent()); } finally { try { if (ctx != null) { ctx.close(); } } catch (NamingException idontcare) { //NOPMD } } }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return false if user or password is wrong * /* w ww .jav a 2 s . c om*/ * here we expand attributes: %u, %d, %s * if defined userSearch, retrieve user's DN and try to bind with it * @param username * @param password * @return */ private boolean ldapBind(String username, String password) { String userDN = null; try { TempParams t = new TempParams(); // if username is an email substitute %u e %d in baseDn: expandSearchAndBaseDn(username, t); // setup the default LdapInterface configured with bean data ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName()); ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(), isFollowReferral(), isConnectionPooling(), null); // set the userDN when custom user search if (!StringUtils.isEmpty(getUserSearch())) { // customize the field used to search the user. SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" }, SearchControls.SUBTREE_SCOPE); if (sr == null) { log.info("Username " + username + " not found"); return false; } userDN = sr.getNameInNamespace().trim(); log.info("binding with dn:" + userDN); } // on failure, set the user DN with append if (userDN == null) { userDN = "uid=" + username + "," + baseDn; } } catch (Exception e) { log.error("Can't instantiate LdapInterface: " + e.getMessage()); return false; } // Set up environment for creating initial context Hashtable<String, String> env = new Hashtable<String, String>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, getLdapUrl()); // Authenticate as User and password env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, password); try { DirContext ctx = new InitialDirContext(env); log.debug(ctx.lookup(userDN)); ctx.close(); } catch (AuthenticationException e) { log.info("User not authenticated: " + e.getMessage()); return false; } catch (NamingException e) { log.warn("User not authenticated: problem while accessing ldap " + e.getMessage()); e.printStackTrace(); return false; } return true; }
From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java
protected DirContext getConnection() { //JNDI boilerplate to connect to an initial context DirContext context = (DirContext) contexts.get("context"); if (context == null) { Hashtable jndienv = new Hashtable(); jndienv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); jndienv.put(Context.SECURITY_AUTHENTICATION, "simple"); if (url.startsWith("ldaps")) { // Handle SSL connections String newurl = url.substring(0, 4) + url.substring(5); jndienv.put(Context.SECURITY_PROTOCOL, "ssl"); jndienv.put(Context.PROVIDER_URL, newurl); } else {/*from w w w .j av a2s. c o m*/ jndienv.put(Context.PROVIDER_URL, url); } if (logonid != null) jndienv.put(Context.SECURITY_PRINCIPAL, logonid); if (logonpassword != null) jndienv.put(Context.SECURITY_CREDENTIALS, logonpassword); try { context = new InitialDirContext(jndienv); } catch (NamingException nex) { log.error("LDAPGroupStore: unable to get context", nex); } contexts.put("context", context); } return context; }
From source file:com.adaptris.core.SharedComponentListTest.java
public void testRemoveService_unbindsJNDI() throws Exception { Adapter adapter = new Adapter(); adapter.setUniqueId(getName());/* w w w.j av a 2s . c o m*/ MockService mockService = new MockService(); adapter.getSharedComponents().addService(mockService); Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName()); InitialContext initialContext = new InitialContext(env); try { start(adapter); Service lookedup = (Service) initialContext.lookup("adapter:comp/env/" + mockService.getUniqueId()); assertNotNull(lookedup); assertEquals(mockService.getUniqueId(), lookedup.getUniqueId()); adapter.getSharedComponents().removeService(mockService.getUniqueId()); try { initialContext.lookup("adapter:comp/env/" + mockService.getUniqueId()); fail(); } catch (NamingException expected) { } } finally { stop(adapter); } }
From source file:net.sf.farrago.namespace.jdbc.MedJdbcDataServer.java
private void initializeDataSource() throws SQLException { assert (!disableConnectionPool); if (jndiName != null) { try {/* w w w . jav a2s .c om*/ // TODO: Allow specification of initial context factory and // provider URL via addition options. These should be stored // in jndiEnv before the initJndi call and the names (keys) of // the those properties would be used in the JndiUtil // constructor. Can also allow artibrary env properties. JndiUtil jndiUtil = new JndiUtil("", Context.INITIAL_CONTEXT_FACTORY, Context.PROVIDER_URL); Properties jndiEnv = new Properties(); jndiUtil.initJndi(jndiEnv); InitialContext initCtx = jndiUtil.newInitialContext(jndiEnv); dataSource = jndiUtil.lookup(initCtx, jndiName, DataSource.class); if (dataSource == null) { throw FarragoResource.instance().MedJdbc_InvalidDataSource.ex(jndiName); } return; } catch (NamingException e) { throw FarragoResource.instance().MedJdbc_InvalidDataSource.ex(jndiName, e); } } String userName = getUserName(); String password = getPassword(); ConnectionFactory connectionFactory; if (connectProps != null) { if (userName != null) { connectProps.setProperty("user", userName); } if (password != null) { connectProps.setProperty("password", password); } connectionFactory = new DriverManagerConnectionFactory(url, connectProps); } else if (userName == null) { connectionFactory = new DriverManagerConnectionFactory(url, new Properties()); } else { if (password == null) { password = ""; } connectionFactory = new DriverManagerConnectionFactory(url, userName, password); } if (validateWhileIdle && (evictionTimerPeriodMillis <= 0L)) { logger.warning("Request to validate on idle ignored: property " + PROP_EVICTION_TIMER_PERIOD_MILLIS + " must be > 0"); if ((validationQuery != null) && !validateOnBorrow && !validateOnReturn) { validateOnBorrow = true; logger.warning("Enabling validation on request"); } } connectionPool = new GenericObjectPool(); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW); connectionPool.setMaxActive(-1); connectionPool.setTestOnBorrow(validateOnBorrow); connectionPool.setTestOnReturn(validateOnReturn); connectionPool.setTestWhileIdle(validateWhileIdle); connectionPool.setMaxIdle(maxIdleConnections); connectionPool.setTimeBetweenEvictionRunsMillis(evictionTimerPeriodMillis); connectionPool.setMinEvictableIdleTimeMillis(minEvictionIdleMillis); CustomPoolableConnectionFactory poolableConnectionFactory = new CustomPoolableConnectionFactory( connectionFactory, connectionPool, validationQuery, autocommit, null); connectionPool.setFactory(poolableConnectionFactory); PoolingDataSource pds = new PoolingDataSource(connectionPool); pds.setAccessToUnderlyingConnectionAllowed(true); dataSource = pds; }