Java Code Examples for javax.naming.Context

The following are top voted examples for showing how to use javax.naming.Context. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: apache-tomcat-7.0.73-with-comment   File: TestNamingContext.java   Source Code and License 16 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        Object obj = ctx.lookup("java:comp/env/bug50351");
        TesterObject to = (TesterObject) obj;
        out.print(to.getFoo());
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 2
Project: BibliotecaPS   File: DataSourceTest.java   Source Code and License 9 votes vote down vote up
/**
 * This method is separated from the rest of the example since you normally
 * would NOT register a JDBC driver in your code. It would likely be
 * configered into your naming and directory service using some GUI.
 * 
 * @throws Exception
 *             if an error occurs
 */
private void registerDataSource() throws Exception {
    this.tempDir = File.createTempFile("jnditest", null);
    this.tempDir.delete();
    this.tempDir.mkdir();
    this.tempDir.deleteOnExit();

    com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, this.tempDir.toURI().toString());
    this.ctx = new InitialContext(env);
    assertTrue("Naming Context not created", this.ctx != null);
    ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    ds.setUrl(dbUrl); // from BaseTestCase
    this.ctx.bind("_test", ds);
}
 
Example 3
Project: tomcat7   File: TestNamingContext.java   Source Code and License 8 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        Object obj = ctx.lookup("java:comp/env/bug50351");
        TesterObject to = (TesterObject) obj;
        out.print(to.getFoo());
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 4
Project: tomcat7   File: TesterFactory.java   Source Code and License 7 votes vote down vote up
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
        Hashtable<?,?> environment) throws Exception {

    if (obj instanceof Reference) {
        Reference ref = (Reference)obj;
        String className = ref.getClassName();

        if (className == null) {
            throw new RuntimeException();
        }

        if (className.equals("org.apache.naming.resources.TesterObject")) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            Class<?> clazz =
                cl.loadClass("org.apache.naming.resources.TesterObject");
            return clazz.newInstance();
        }
    }
    return null;
}
 
Example 5
Project: unitimes   File: LocalContext.java   Source Code and License 6 votes vote down vote up
@Override
public Context createSubcontext(Name name) throws NamingException {
	if (name.isEmpty())
		throw new InvalidNameException("Cannot bind empty name");

	Name nm = getMyComponents(name);
	String atom = nm.get(0);
	Object inter = iBindings.get(atom);

	if (nm.size() == 1) {
		if (inter != null)
			throw new NameAlreadyBoundException("Use rebind to override");

		Context child = createCtx(this, atom, iEnv);

		iBindings.put(atom, child);

		return child;
	} else {
		if (!(inter instanceof Context))
			throw new NotContextException(atom + " does not name a context");

		return ((Context) inter).createSubcontext(nm.getSuffix(1));
	}
}
 
Example 6
Project: lams   File: NamingContext.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves the parser associated with the named context. In a 
 * federation of namespaces, different naming systems will parse names 
 * differently. This method allows an application to get a parser for 
 * parsing names into their atomic components using the naming convention 
 * of a particular naming system. Within any single naming system, 
 * NameParser objects returned by this method must be equal (using the 
 * equals() test).
 * 
 * @param name the name of the context from which to get the parser
 * @return a name parser that can parse compound names into their atomic 
 * components
 * @exception NamingException if a naming exception is encountered
 */
public NameParser getNameParser(Name name)
    throws NamingException {

    while ((!name.isEmpty()) && (name.get(0).length() == 0))
        name = name.getSuffix(1);
    if (name.isEmpty())
        return nameParser;

    if (name.size() > 1) {
        Object obj = bindings.get(name.get(0));
        if (obj instanceof Context) {
            return ((Context) obj).getNameParser(name.getSuffix(1));
        } else {
            throw new NotContextException
                (sm.getString("namingContext.contextExpected"));
        }
    }

    return nameParser;

}
 
Example 7
Project: the-vigilantes   File: DataSourceTest.java   Source Code and License 6 votes vote down vote up
/**
 * This method is separated from the rest of the example since you normally
 * would NOT register a JDBC driver in your code. It would likely be
 * configered into your naming and directory service using some GUI.
 * 
 * @throws Exception
 *             if an error occurs
 */
private void registerDataSource() throws Exception {
    this.tempDir = File.createTempFile("jnditest", null);
    this.tempDir.delete();
    this.tempDir.mkdir();
    this.tempDir.deleteOnExit();

    com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, this.tempDir.toURI().toString());
    this.ctx = new InitialContext(env);
    assertTrue("Naming Context not created", this.ctx != null);
    ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    ds.setUrl(dbUrl); // from BaseTestCase
    this.ctx.bind("_test", ds);
}
 
Example 8
Project: jboss-eap7.1-playground   File: LegacyClusterJBossEjbClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws NamingException {
	checkArgs(args);
	final Hashtable<String, String> jndiProperties = new Hashtable<>();
	jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
	final Context ic = new InitialContext(jndiProperties);

	Simple proxy = (Simple) ic.lookup("ejb:EAP71-PLAYGROUND-server/ejb/SimpleBean!" + Simple.class.getName());

	HashSet<String> serverList = new HashSet<>();

	for (int i = 0; i < 20; i++) {
		serverList.add(proxy.getJBossServerName());
	}

	if (serverList.size() > 1) {
		log.info("Server should be part of a cluster or multiple URL's as the invocation was executed on the following servers : " + serverList);
	} else if (serverList.size() == 1) {
		log.warning("Server is not part of a cluster with multiple nodes, or did not have multiple PROVIDER URL's, as the invocation was executed on a single server : " + new ArrayList<String>(serverList).get(0));
	} else {
		throw new RuntimeException("Unexpected result, no server list!");
	}
}
 
Example 9
Project: oscm   File: ServiceFactory.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T connectToEJB(Class<T> remoteInterface, String userName,
        String password) throws Exception {
    try {
        props.put(Context.SECURITY_PRINCIPAL, userName);
        props.put(Context.SECURITY_CREDENTIALS, password);
        props.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.RemoteInitialContextFactory");
        props.put("java.naming.provider.url", "http://127.0.0.1:8080/tomee/ejb");
        props.put("openejb.authentication.realmName", "bss-realm");

        Context context = new InitialContext(props);
        T service = (T) context.lookup(remoteInterface.getName());
        return service;
    } catch (NamingException e) {
        throw new SaaSSystemException("Service lookup failed!", e);
    }
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: TesterFactory.java   Source Code and License 6 votes vote down vote up
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
        Hashtable<?,?> environment) throws Exception {

    if (obj instanceof Reference) {
        Reference ref = (Reference)obj;
        String className = ref.getClassName();

        if (className == null) {
            throw new RuntimeException();
        }

        if (className.equals("org.apache.naming.resources.TesterObject")) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            Class<?> clazz =
                cl.loadClass("org.apache.naming.resources.TesterObject");
            return clazz.newInstance();
        }
    }
    return null;
}
 
Example 11
Project: lazycat   File: DefaultInstanceManager.java   Source Code and License 6 votes vote down vote up
public DefaultInstanceManager(Context context, Map<String, Map<String, String>> injectionMap,
		org.apache.catalina.Context catalinaContext, ClassLoader containerClassLoader) {
	classLoader = catalinaContext.getLoader().getClassLoader();
	privileged = catalinaContext.getPrivileged();
	this.containerClassLoader = containerClassLoader;
	ignoreAnnotations = catalinaContext.getIgnoreAnnotations();
	Log log = catalinaContext.getLogger();
	Set<String> classNames = new HashSet<String>();
	loadProperties(classNames, "org/apache/catalina/core/RestrictedServlets.properties",
			"defaultInstanceManager.restrictedServletsResource", log);
	loadProperties(classNames, "org/apache/catalina/core/RestrictedListeners.properties",
			"defaultInstanceManager.restrictedListenersResource", log);
	loadProperties(classNames, "org/apache/catalina/core/RestrictedFilters.properties",
			"defaultInstanceManager.restrictedFiltersResource", log);
	restrictedClasses = Collections.unmodifiableSet(classNames);
	this.context = context;
	this.injectionMap = injectionMap;
	this.postConstructMethods = catalinaContext.findPostConstructMethods();
	this.preDestroyMethods = catalinaContext.findPreDestroyMethods();
}
 
Example 12
Project: lams   File: JNDIConnectionProvider.java   Source Code and License 6 votes vote down vote up
private void init() {

        if (!isAlwaysLookup()) {
            Context ctx = null;
            try {
                ctx = (props != null) ? new InitialContext(props) : new InitialContext(); 

                datasource = (DataSource) ctx.lookup(url);
            } catch (Exception e) {
                getLog().error(
                        "Error looking up datasource: " + e.getMessage(), e);
            } finally {
                if (ctx != null) {
                    try { ctx.close(); } catch(Exception ignore) {}
                }
            }
        }
    }
 
Example 13
Project: alfresco-repository   File: LDAPUserRegistry.java   Source Code and License 6 votes vote down vote up
@Override
public void process(SearchResult result) throws NamingException, ParseException
{
    try
    {
        doProcess(result);
    }
    finally
    {
        Object obj = result.getObject();
        
        if (obj != null && obj instanceof Context)
        {
            try
            {
                ((Context)obj).close();
            }
            catch (NamingException e)
            {
                logger.debug("error when closing result block context", e);
            }
            obj = null;
        }
        result = null;
    }
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: NamingContext.java   Source Code and License 6 votes vote down vote up
/**
 * Enumerates the names bound in the named context, along with the 
 * objects bound to them. The contents of any subcontexts are not 
 * included.
 * <p>
 * If a binding is added to or removed from this context, its effect on 
 * an enumeration previously returned is undefined.
 * 
 * @param name the name of the context to list
 * @return an enumeration of the bindings in this context. 
 * Each element of the enumeration is of type Binding.
 * @exception NamingException if a naming exception is encountered
 */
@Override
public NamingEnumeration<Binding> listBindings(Name name)
    throws NamingException {
    // Removing empty parts
    while ((!name.isEmpty()) && (name.get(0).length() == 0))
        name = name.getSuffix(1);
    if (name.isEmpty()) {
        return new NamingContextBindingsEnumeration(bindings.values().iterator(), this);
    }
    
    NamingEntry entry = bindings.get(name.get(0));
    
    if (entry == null) {
        throw new NameNotFoundException
            (sm.getString("namingContext.nameNotBound", name, name.get(0)));
    }
    
    if (entry.type != NamingEntry.CONTEXT) {
        throw new NamingException
            (sm.getString("namingContext.contextExpected"));
    }
    return ((Context) entry.value).listBindings(name.getSuffix(1));
}
 
Example 15
Project: monarch   File: CleanUpJUnitTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testBlockingTimeOut() {
  try {
    Context ctx = cache.getJNDIContext();
    GemFireConnPooledDataSource ds =
        (GemFireConnPooledDataSource) ctx.lookup("java:/PooledDataSource");
    GemFireConnectionPoolManager provider =
        (GemFireConnectionPoolManager) ds.getConnectionProvider();
    ConnectionPoolCacheImpl poolCache =
        (ConnectionPoolCacheImpl) provider.getConnectionPoolCache();
    poolCache.getPooledConnectionFromPool();
    Thread.sleep(40000);
    if (!(poolCache.activeCache.isEmpty())) {
      fail("Clean-up on expiration not done");
    }
  } catch (Exception e) {
    fail("Exception occured in testBlockingTimeOut due to " + e);
    e.printStackTrace();
  }
}
 
Example 16
Project: lazycat   File: DataSourceLinkFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Create a new DataSource instance.
 * 
 * @param obj
 *            The reference object describing the DataSource
 */
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment)
		throws NamingException {
	Object result = super.getObjectInstance(obj, name, nameCtx, environment);
	// Can we process this request?
	if (result != null) {
		Reference ref = (Reference) obj;
		RefAddr userAttr = ref.get("username");
		RefAddr passAttr = ref.get("password");
		if (userAttr.getContent() != null && passAttr.getContent() != null) {
			result = wrapDataSource(result, userAttr.getContent().toString(), passAttr.getContent().toString());
		}
	}
	return result;
}
 
Example 17
Project: jboss-eap7.1-playground   File: SimpleWildFlyInitialContextClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws NamingException {
	checkArgs(args);
	
	Properties p = new Properties();
	
	p.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
	InitialContext ic = new WildFlyInitialContext(p);
	
	Simple proxy = (Simple) ic.lookup("ejb:EAP71-PLAYGROUND-server/ejb/SimpleBean!" + Simple.class.getName());
	
	try {
		proxy.logText("Simple invocation without security at " + new Date());
		log.info("Expected to work with the default configuration, to get a security failure remote the <local> element from the ApplicationRealm!");
	} catch (Exception e) {
		log.severe("Expected to fail if no <local> configuration in ApplicationRealm, unfortunately no good Exception");
		e.printStackTrace();
	}
}
 
Example 18
Project: oscm   File: APPlatformServiceFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves an <code>APPlatformService</code> instance.
 * 
 * @return the service instance
 */
public static APPlatformService getInstance() {
    try {

        Properties p = new Properties();
        p.setProperty (Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");

        InitialContext context = new InitialContext(p);
        Object lookup = context.lookup(JNDI_NAME);
        if (!APPlatformService.class.isAssignableFrom(lookup.getClass())) {
            throw new IllegalStateException(
                    "Failed to look up APPlatformService. The returned service is not implementing correct interface");
        }
        return (APPlatformService) lookup;
    } catch (NamingException e) {
        logger.error("Service lookup failed: " + JNDI_NAME);
        throw new IllegalStateException(
                "No valid platform service available", e);
    }
}
 
Example 19
Project: Byter   File: JmxConnectionHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the jmxConnector with passed parameters.
 * @param host host address
 * @param port port of the host
 * @param user username (null possible)
 * @param pass password (null possible)
 * @return connected JMXConnector
 * @throws IOException IOException
 */
public static JMXConnector buildJmxMPConnector(final String host, final int port, final String user, final String pass) throws IOException {
    try {
        final JMXServiceURL serviceURL = new JMXServiceURL("jmxmp", host,port);
        if("null".equals(user) || "null".equals(pass) || user == null || pass == null){
            return JMXConnectorFactory.connect(serviceURL);
        }
        final Map<String, Object> environment = new HashMap<>();
        environment.put("jmx.remote.credentials", new String[]{user,pass});
        environment.put(Context.SECURITY_PRINCIPAL, user);
        environment.put(Context.SECURITY_CREDENTIALS, pass);
        return JMXConnectorFactory.connect(serviceURL,environment);
    } catch (MalformedURLException e) {
        log.log(Level.WARNING, "Malformed ServiceURL in buildJmxConnector");
        return null;
    }
}
 
Example 20
Project: lazycat   File: DefaultInstanceManager.java   Source Code and License 6 votes vote down vote up
/**
 * Inject resources in specified method.
 *
 * @param context
 *            jndi context to extract value from
 * @param instance
 *            object to inject into
 * @param method
 *            field target for injection
 * @param name
 *            jndi name value is bound under
 * @param clazz
 *            class annotation is defined in
 * @throws IllegalAccessException
 *             if method is inaccessible
 * @throws javax.naming.NamingException
 *             if value is not accessible in naming context
 * @throws java.lang.reflect.InvocationTargetException
 *             if setter call fails
 */
protected static void lookupMethodResource(Context context, Object instance, Method method, String name,
		Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException {

	if (!Introspection.isValidSetter(method)) {
		throw new IllegalArgumentException(sm.getString("defaultInstanceManager.invalidInjection"));
	}

	Object lookedupResource;
	boolean accessibility;

	String normalizedName = normalize(name);

	if ((normalizedName != null) && (normalizedName.length() > 0)) {
		lookedupResource = context.lookup(normalizedName);
	} else {
		lookedupResource = context.lookup(clazz.getName() + "/" + Introspection.getPropertyName(method));
	}

	synchronized (method) {
		accessibility = method.isAccessible();
		method.setAccessible(true);
		method.invoke(instance, lookedupResource);
		method.setAccessible(accessibility);
	}
}
 
Example 21
Project: monarch   File: QueryAndJtaJUnitTest.java   Source Code and License 6 votes vote down vote up
@Ignore
@Test
public void testFailedIndexUpdateOnJTACommitForPut() throws Exception {
  Person.THROW_ON_INDEX = true;
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "index", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  try {
    utx.commit();
    fail("Commit should have thrown an exception because the index update threw");
  } catch (Exception e) {
    // this is desired
  }
}
 
Example 22
Project: apache-tomcat-7.0.73-with-comment   File: NamingContext.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves the parser associated with the named context. In a 
 * federation of namespaces, different naming systems will parse names 
 * differently. This method allows an application to get a parser for 
 * parsing names into their atomic components using the naming convention 
 * of a particular naming system. Within any single naming system, 
 * NameParser objects returned by this method must be equal (using the 
 * equals() test).
 * 
 * @param name the name of the context from which to get the parser
 * @return a name parser that can parse compound names into their atomic 
 * components
 * @exception NamingException if a naming exception is encountered
 */
@Override
public NameParser getNameParser(Name name)
    throws NamingException {

    while ((!name.isEmpty()) && (name.get(0).length() == 0))
        name = name.getSuffix(1);
    if (name.isEmpty())
        return nameParser;

    if (name.size() > 1) {
        Object obj = bindings.get(name.get(0));
        if (obj instanceof Context) {
            return ((Context) obj).getNameParser(name.getSuffix(1));
        } else {
            throw new NotContextException
                (sm.getString("namingContext.contextExpected"));
        }
    }

    return nameParser;

}
 
Example 23
Project: lams   File: NamingContext.java   Source Code and License 6 votes vote down vote up
/**
 * Enumerates the names bound in the named context, along with the class 
 * names of objects bound to them. The contents of any subcontexts are 
 * not included.
 * <p>
 * If a binding is added to or removed from this context, its effect on 
 * an enumeration previously returned is undefined.
 * 
 * @param name the name of the context to list
 * @return an enumeration of the names and class names of the bindings in 
 * this context. Each element of the enumeration is of type NameClassPair.
 * @exception NamingException if a naming exception is encountered
 */
public NamingEnumeration list(Name name)
    throws NamingException {
    // Removing empty parts
    while ((!name.isEmpty()) && (name.get(0).length() == 0))
        name = name.getSuffix(1);
    if (name.isEmpty()) {
        return new NamingContextEnumeration(bindings.values().iterator());
    }
    
    NamingEntry entry = (NamingEntry) bindings.get(name.get(0));
    
    if (entry == null) {
        throw new NameNotFoundException
            (sm.getString("namingContext.nameNotBound", name.get(0)));
    }
    
    if (entry.type != NamingEntry.CONTEXT) {
        throw new NamingException
            (sm.getString("namingContext.contextExpected"));
    }
    return ((Context) entry.value).list(name.getSuffix(1));
}
 
Example 24
Project: monarch   File: QueryAndJtaJUnitTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testIndexOnCommitForInvalidate() throws Exception {
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  utx.commit();
  Query q = qs.newQuery("select * from /sample where age < 50");
  assertEquals(1, ((SelectResults) q.execute()).size());
  Person dsample = (Person) CopyHelper.copy(region.get(x));
  dsample.setAge(55);
  utx.begin();
  region.invalidate(x);
  utx.commit();
  CacheUtils.log(((Person) region.get(x)));
  assertEquals(0, ((SelectResults) q.execute()).size());
}
 
Example 25
Project: oscm   File: OrganizationSettingQueryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void verifyResultMapping_CheckProperties() throws Exception {
    addEntry(SettingType.LDAP_URL, "url", "url");
    addEntry(SettingType.LDAP_PRINCIPAL, "principal", "principal");
    addEntry(SettingType.LDAP_CREDENTIALS, "credentials", "credentials");
    addEntry(SettingType.LDAP_ATTR_REFERRAL, "ignore", "ignore");
    query.execute();
    Properties properties = query.getProperties();
    assertEquals("url", properties.get(Context.PROVIDER_URL));
    assertEquals("com.sun.jndi.ldap.LdapCtxFactory",
            properties.get(Context.INITIAL_CONTEXT_FACTORY));
    assertEquals("principal", properties.get(Context.SECURITY_PRINCIPAL));
    assertEquals("credentials",
            properties.get(Context.SECURITY_CREDENTIALS));
    assertEquals("ignore", properties.get(Context.REFERRAL));
}
 
Example 26
Project: OpenVertretung   File: DataSourceTest.java   Source Code and License 6 votes vote down vote up
/**
 * This method is separated from the rest of the example since you normally
 * would NOT register a JDBC driver in your code. It would likely be
 * configered into your naming and directory service using some GUI.
 * 
 * @throws Exception
 *             if an error occurs
 */
private void registerDataSource() throws Exception {
    this.tempDir = File.createTempFile("jnditest", null);
    this.tempDir.delete();
    this.tempDir.mkdir();
    this.tempDir.deleteOnExit();

    com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, this.tempDir.toURI().toString());
    this.ctx = new InitialContext(env);
    assertTrue("Naming Context not created", this.ctx != null);
    ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    ds.setUrl(dbUrl); // from BaseTestCase
    this.ctx.bind("_test", ds);
}
 
Example 27
Project: lucene-demo   File: JdbcUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 获取连接,使用数据库连接池
 * @param jndi 配置在tomcat的context.xml里面的东西
 * @return 创建的连接对象
 */
public Connection getConnection(String jndi)
{
	try
	{
		log.debug("开始尝试连接数据库!");
		Context context=new InitialContext();
		DataSource dataSource=(DataSource)context.lookup("java:comp/env/"+jndi);
		con=dataSource.getConnection();
		log.debug("连接成功!");
	}
	catch (Exception e)
	{
		log.error("连接数据库失败!", e);
	}
	return con;
}
 
Example 28
Project: tomcat7   File: TestNamingContext.java   Source Code and License 6 votes vote down vote up
@Test
public void testBug53465() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();

    File appDir =
        new File("test/webapp-3.0");
    // app dir is relative to server home
    org.apache.catalina.Context ctxt =
            tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() +
            "/test/bug5nnnn/bug53465.jsp", bc, null);

    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertTrue(bc.toString().contains("<p>10</p>"));

    ContextEnvironment ce =
            ctxt.getNamingResources().findEnvironment("bug53465");
    Assert.assertEquals("Bug53465MappedName", ce.getProperty("mappedName"));
}
 
Example 29
Project: cli-java   File: AocConnectionManager.java   Source Code and License 5 votes vote down vote up
protected void setInitialContext(String userConnectionFactory) {
    properties = new Properties();
    try {
        String jndiFilePath;
        if ((jndiFilePath = System.getProperty(EXTERNAL_JNDI_PROPERTY)) != null) {
            // load property file from an absolute path to the file
            try (FileInputStream stream = new FileInputStream(jndiFilePath)) {
                properties.load(stream);
            }
        } else {
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            String JNDIFile = "JAMQ6JNDI.properties";
            LOG.trace("Using " + JNDIFile);
            // fallback to use resources/ArtemisJNDI.properties file
            properties.load(classloader.getResourceAsStream(JNDIFile));
            LOG.trace(properties.toString());
        }
        LOG.trace(userConnectionFactory);
        if (userConnectionFactory.contains("://")) {
            // override connectionFactory by this option in jndi/properties
            properties.setProperty(Context.PROVIDER_URL, userConnectionFactory);
            properties.setProperty("connectionFactory." + amqConnectionFactoryJNDI, userConnectionFactory);
        }
        initialContext = new InitialContext(properties);
    } catch (NamingException | IOException e) {
        e.printStackTrace();
    }
}
 
Example 30
Project: ipack   File: LDAPStoreHelper.java   Source Code and License 5 votes vote down vote up
private DirContext connectLDAP() throws NamingException
{
    Properties props = new Properties();
    props.setProperty(Context.INITIAL_CONTEXT_FACTORY, LDAP_PROVIDER);
    props.setProperty(Context.BATCHSIZE, "0");

    props.setProperty(Context.PROVIDER_URL, params.getLdapURL());
    props.setProperty(Context.URL_PKG_PREFIXES, URL_CONTEXT_PREFIX);
    props.setProperty(Context.REFERRAL, REFERRALS_IGNORE);
    props.setProperty(Context.SECURITY_AUTHENTICATION,
        SEARCH_SECURITY_LEVEL);

    DirContext ctx = new InitialDirContext(props);
    return ctx;
}
 
Example 31
Project: lams   File: JndiObjectFactoryBean.java   Source Code and License 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	Context ctx = (isEligible(invocation.getMethod()) ? this.jndiTemplate.getContext() : null);
	try {
		return invocation.proceed();
	}
	finally {
		this.jndiTemplate.releaseContext(ctx);
	}
}
 
Example 32
Project: lazycat   File: NamingContext.java   Source Code and License 5 votes vote down vote up
/**
 * Unbinds the named object. Removes the terminal atomic name in name from
 * the target context--that named by all but the terminal atomic part of
 * name.
 * <p>
 * This method is idempotent. It succeeds even if the terminal atomic name
 * is not bound in the target context, but throws NameNotFoundException if
 * any of the intermediate contexts do not exist.
 * 
 * @param name
 *            the name to bind; may not be empty
 * @exception NameNotFoundException
 *                if an intermediate context does not exist
 * @exception NamingException
 *                if a naming exception is encountered
 */
@Override
public void unbind(Name name) throws NamingException {

	if (!checkWritable()) {
		return;
	}

	while ((!name.isEmpty()) && (name.get(0).length() == 0))
		name = name.getSuffix(1);
	if (name.isEmpty())
		throw new NamingException(sm.getString("namingContext.invalidName"));

	NamingEntry entry = bindings.get(name.get(0));

	if (entry == null) {
		throw new NameNotFoundException(sm.getString("namingContext.nameNotBound", name, name.get(0)));
	}

	if (name.size() > 1) {
		if (entry.type == NamingEntry.CONTEXT) {
			((Context) entry.value).unbind(name.getSuffix(1));
		} else {
			throw new NamingException(sm.getString("namingContext.contextExpected"));
		}
	} else {
		bindings.remove(name.get(0));
	}

}
 
Example 33
Project: WordnetLoom   File: EJBConnectionProviderService.java   Source Code and License 5 votes vote down vote up
public <E> E lookupForService(Class<E> remoteClass) {
    E bean = null;
    try {
        Context context = getInitialContext();
        String lookupName = getLookupName(remoteClass, "Bean");
        bean = (E) context.lookup(lookupName);
    } catch (Exception ex) {
        logger().error("Service Lookup error:", ex);
    }
    return bean;
}
 
Example 34
Project: lams   File: TransactionRef.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves the class name of the factory of the object to which this 
 * reference refers.
 */
public String getFactoryClassName() {
    String factory = super.getFactoryClassName();
    if (factory != null) {
        return factory;
    } else {
        factory = System.getProperty(Context.OBJECT_FACTORIES);
        if (factory != null) {
            return null;
        } else {
            return DEFAULT_FACTORY;
        }
    }
}
 
Example 35
Project: jerrydog   File: GlobalResourcesLifecycleListener.java   Source Code and License 5 votes vote down vote up
/**
 * Create the MBeans for the interesting global JNDI resources in
 * the specified naming context.
 *
 * @param prefix Prefix for complete object name paths
 * @param context Context to be scanned
 *
 * @exception NamingException if a JNDI exception occurs
 */
protected void createMBeans(String prefix, Context context)
    throws NamingException {

    if (debug >= 1) {
        log("Creating MBeans for Global JNDI Resources in Context '" +
            prefix + "'");
    }

    NamingEnumeration bindings = context.listBindings("");
    while (bindings.hasMore()) {
        Binding binding = (Binding) bindings.next();
        String name = prefix + binding.getName();
        Object value = context.lookup(binding.getName());
        if (debug >= 2) {
            log("Checking resource " + name);
        }
        if (value instanceof Context) {
            createMBeans(name + "/", (Context) value);
        } else if (value instanceof UserDatabase) {
            try {
                createMBeans(name, (UserDatabase) value);
            } catch (Exception e) {
                log("Exception creating UserDatabase MBeans for " + name,
                    e);
            }
        }
    }

}
 
Example 36
Project: unitimes   File: LocalContext.java   Source Code and License 5 votes vote down vote up
@Override
public void rename(Name oldname, Name newname) throws NamingException {
	if (oldname.isEmpty() || newname.isEmpty())
		throw new InvalidNameException("Cannot rename empty name");

	Name oldnm = getMyComponents(oldname);
	Name newnm = getMyComponents(newname);

	if (oldnm.size() != newnm.size())
		throw new OperationNotSupportedException("Do not support rename across different contexts");

	String oldatom = oldnm.get(0);
	String newatom = newnm.get(0);

	if (oldnm.size() == 1) {
		if (iBindings.get(newatom) != null)
			throw new NameAlreadyBoundException(newname.toString() + " is already bound");

		Object oldBinding = iBindings.remove(oldatom);
		if (oldBinding == null)
			throw new NameNotFoundException(oldname.toString() + " not bound");

		iBindings.put(newatom, oldBinding);
	} else {
		if (!oldatom.equals(newatom))
			throw new OperationNotSupportedException("Do not support rename across different contexts");

		Object inter = iBindings.get(oldatom);
		
		if (!(inter instanceof Context))
			throw new NotContextException(oldatom + " does not name a context");

		((Context) inter).rename(oldnm.getSuffix(1), newnm.getSuffix(1));
	}
}
 
Example 37
Project: lams   File: JndiTemplate.java   Source Code and License 5 votes vote down vote up
/**
 * Rebind the given object to the current JNDI context, using the given name.
 * Overwrites any existing binding.
 * @param name the JNDI name of the object
 * @param object the object to rebind
 * @throws NamingException thrown by JNDI
 */
public void rebind(final String name, final Object object) throws NamingException {
	if (logger.isDebugEnabled()) {
		logger.debug("Rebinding JNDI object with name [" + name + "]");
	}
	execute(new JndiCallback<Object>() {
		@Override
		public Object doInContext(Context ctx) throws NamingException {
			ctx.rebind(name, object);
			return null;
		}
	});
}
 
Example 38
Project: parabuild-ci   File: JNDIAuthenticator.java   Source Code and License 5 votes vote down vote up
/**
 * Create our directory context configuration.
 *
 * @return java.util.Hashtable the configuration for the directory context.
 */
private Hashtable makeDirectoryContextEnvironment() {
  final Hashtable result = new Hashtable(11);
  putIfNotBlank(result, Context.INITIAL_CONTEXT_FACTORY, contextFactory);
  putIfNotBlank(result, Context.SECURITY_PRINCIPAL, connectionPrincipal);
  putIfNotBlank(result, Context.SECURITY_CREDENTIALS, connectionCredentials);
  putIfNotBlank(result, Context.PROVIDER_URL, connectionURL);
  putIfNotBlank(result, Context.SECURITY_AUTHENTICATION, connectionSecurityLevel);
  putIfNotBlank(result, Context.SECURITY_PROTOCOL, protocol);
  putIfNotBlank(result, Context.REFERRAL, referrals);
  putIfNotBlank(result, JAVA_NAMING_DEREF_ALIASES, derefAliases);
  putIfNotBlank(result, JAVA_NAMING_LDAP_VERSION, ldapVersion);
  return result;
}
 
Example 39
Project: message-broker   File: ClientHelper.java   Source Code and License 5 votes vote down vote up
public InitialContextBuilder(String username, String password, String brokerHost, String port) {
    this.username = username;
    this.password = password;
    this.brokerHost = brokerHost;
    this.port = port;
    contextProperties = new Properties();
    contextProperties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_INITIAL_CONTEXT_FACTORY);
    String connectionString = getBrokerConnectionString();
    contextProperties.put(CONNECTION_FACTORY_PREFIX + CONNECTION_FACTORY, connectionString);
}
 
Example 40
Project: Equella   File: LDAP.java   Source Code and License 5 votes vote down vote up
private DirContext _bind(String username, String password, boolean canBeAnonymous, boolean pool)
	throws NamingException
{
	if( !canBeAnonymous && password.length() == 0 )
	{
		throw new BadCredentialsException("Couldn't authenticate with LDAP");
	}

	// We'll ignore Sonar's advice to replace Hashtable with java.util.Map
	Hashtable<String, String> map = new Hashtable<String, String>(env); // NOSONAR
	map.put("com.sun.jndi.ldap.connect.pool", Boolean.toString(pool));
	map.put(Context.SECURITY_PRINCIPAL, username);
	map.put(Context.SECURITY_CREDENTIALS, password);
	map.put(Context.SECURITY_AUTHENTICATION, "simple");

	ClassLoader oldLoader = null;
	try
	{
		if( blind )
		{
			oldLoader = Thread.currentThread().getContextClassLoader();
			Thread.currentThread().setContextClassLoader(LDAP.class.getClassLoader());
		}
		return new InitialDirContext(map);
	}
	catch( AuthenticationException e )
	{
		throw new BadCredentialsException("Couldn't authenticate with LDAP");
	}
	finally
	{
		if( oldLoader != null )
		{
			Thread.currentThread().setContextClassLoader(oldLoader);
		}
	}
}