Java Code Examples for javax.naming.InitialContext

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project bam, under directory /content/services/service-dependency-rests/src/main/java/org/overlord/bam/service/dependency/rest/.

Source file: RESTServiceDependencyServer.java

  20 
vote

/** 
 * This is the default constructor.
 */
public RESTServiceDependencyServer(){
  try {
    InitialContext ctx=new InitialContext();
    _acmManager=(ActiveCollectionManager)ctx.lookup(ACT_COLL_MANAGER);
  }
 catch (  Exception e) {
    LOG.log(Level.SEVERE,java.util.PropertyResourceBundle.getBundle("service-dependency-rests.Messages").getString("SERVICE-DEPENDENCY-RESTS-1"),e);
  }
}
 

Example 2

From project hornetq-version-tests, under directory /src/test/java/org/hornetq/integration/.

Source file: ConnectionFactoryJNDITestIT.java

  19 
vote

@Test public void testHaCf() throws Exception {
  Hashtable<String,String> env=new Hashtable<String,String>();
  env.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
  env.put("java.naming.provider.url","jnp://localhost:1099");
  env.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
  InitialContext context=new InitialContext(env);
  HornetQJMSConnectionFactory cf=(HornetQJMSConnectionFactory)context.lookup("/NettyHAConnectionFactory");
  assertNotNull(cf.getServerLocator());
  ServerLocatorImpl locator=(ServerLocatorImpl)cf.getServerLocator();
  assertNotNull(locator.getTopology());
  assertTrue(cf.isHA());
}
 

Example 3

From project arquillian-container-jbossas, under directory /jbossas-remote-5/src/test/java/org/jboss/arquillian/container/jbossas/remote_5_0/.

Source file: ProfileServiceTestCase.java

  18 
vote

@Test public void shouldBeAbleToExtractData() throws Exception {
  InitialContext ctx=createContext();
  MBeanServerConnection serverConnection=getServerConnection(ctx);
  String deploymentName="test.ear";
  ProtocolMetaData metaData=ManagementViewParser.parse(deploymentName,serverConnection);
  Assert.assertNotNull(metaData);
  HTTPContext context=metaData.getContext(HTTPContext.class);
  Assert.assertNotNull(context);
  Assert.assertEquals("127.0.0.1",context.getHost());
  Assert.assertEquals(8080,context.getPort());
  Assert.assertEquals(1,context.getServlets().size());
}
 

Example 4

From project arquillian_deprecated, under directory /containers/jbossas-remote-5/src/main/java/org/jboss/arquillian/container/jbossas/remote_5_0/.

Source file: JBossASRemoteContainer.java

  18 
vote

private void initDeploymentManager() throws Exception {
  String profileName=configuration.getProfileName();
  InitialContext ctx=createContext();
  profileService=(ProfileService)ctx.lookup("ProfileService");
  deploymentManager=profileService.getDeploymentManager();
  ProfileKey defaultKey=new ProfileKey(profileName);
  deploymentManager.loadProfile(defaultKey,false);
  VFS.init();
}
 

Example 5

From project autopatch, under directory /src/test/java/com/tacitknowledge/util/migration/jdbc/.

Source file: WebAppServletContextFactoryTest.java

  18 
vote

/** 
 * @see junit.framework.TestCase#setUp()
 */
public void setUp() throws Exception {
  super.setUp();
  MockContextFactory.setAsInitial();
  InitialContext context=new InitialContext();
  context.createSubcontext("java");
}
 

Example 6

From project components, under directory /jca/src/main/java/org/switchyard/component/jca/processor/.

Source file: CCIProcessor.java

  18 
vote

@Override public void initialize(){
  try {
    Class<?> clazz=getApplicationClassLoader().loadClass(_recordClassName);
    _recordHandler=RecordHandlerFactory.createRecordHandler(clazz,getApplicationClassLoader());
    InitialContext ic=new InitialContext();
    _connectionFactory=(ConnectionFactory)ic.lookup(getConnectionFactoryJNDIName());
    _recordFactory=_connectionFactory.getRecordFactory();
  }
 catch (  Exception e) {
    throw new SwitchYardException("Failed to initialize " + this.getClass().getName(),e);
  }
}
 

Example 7

From project core_1, under directory /test/src/main/java/org/switchyard/test/mixins/jca/.

Source file: JCAMixIn.java

  18 
vote

/** 
 * get UserTransaction.
 * @return UserTransaction
 */
public UserTransaction getUserTransaction(){
  try {
    InitialContext ic=new InitialContext();
    return (UserTransaction)ic.lookup(JNDI_USER_TRANSACTION);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 8

From project core_4, under directory /impl/src/main/java/org/richfaces/application/push/impl/jms/.

Source file: JMSTopicsContextImpl.java

  18 
vote

public static JMSTopicsContextImpl getInstanceInitializedFromContext(ThreadFactory threadFactory,FacesContext facesContext) throws NamingException {
  ConfigurationService configurationService=ServiceTracker.getService(ConfigurationService.class);
  InitialContext initialContext=new InitialContext();
  NameParser nameParser=initialContext.getNameParser("");
  Name connectionFactoryName=nameParser.parse(getConnectionFactory(facesContext,configurationService));
  Name topicsNamespace=nameParser.parse(getTopicsNamespace(facesContext,configurationService));
  String username=getUserName(facesContext,configurationService);
  String password=getPassword(facesContext,configurationService);
  return new JMSTopicsContextImpl(threadFactory,initialContext,connectionFactoryName,topicsNamespace,username,password);
}
 

Example 9

From project droolsjbpm-integration, under directory /drools-pipeline/src/main/java/org/drools/runtime/pipeline/impl/.

Source file: JmsMessenger.java

  18 
vote

public JmsMessenger(Pipeline pipeline,Properties properties,String destinationName,ResultHandlerFactory resultHandlerFactory){
  super();
  this.pipeline=pipeline;
  this.resultHandlerFactory=resultHandlerFactory;
  try {
    InitialContext jndiContext=new InitialContext(properties);
    this.connectionFactory=(ConnectionFactory)jndiContext.lookup("ConnectionFactory");
    this.destination=(Destination)jndiContext.lookup(destinationName);
  }
 catch (  Exception e) {
    throw new RuntimeException("Unable to instantiate JmsFeeder",e);
  }
}
 

Example 10

From project edg-examples, under directory /chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/jsf/.

Source file: InitializeCache.java

  18 
vote

private BeanManager getBeanManagerFromJNDI(){
  InitialContext context;
  Object result;
  try {
    context=new InitialContext();
    result=context.lookup("java:comp/BeanManager");
  }
 catch (  NamingException e) {
    throw new RuntimeException("BeanManager could not be found in JNDI",e);
  }
  return (BeanManager)result;
}
 

Example 11

From project faces_1, under directory /impl/src/main/java/org/jboss/seam/faces/projectstage/.

Source file: JNDIProjectStageDetector.java

  18 
vote

/** 
 * Performs a JNDI lookup to obtain the current project stage. The method use the standard JNDI name for the JSF project stage for the lookup
 * @return name bound to JNDI or <code>null</code>
 */
private String getProjectStageNameFromJNDI(){
  try {
    InitialContext context=new InitialContext();
    Object obj=context.lookup(ProjectStage.PROJECT_STAGE_JNDI_NAME);
    if (obj != null) {
      return obj.toString().trim();
    }
  }
 catch (  NamingException e) {
  }
  return null;
}
 

Example 12

From project gemini.web.gemini-web-container, under directory /test-bundles/war-with-resource-references/src/main/java/test/.

Source file: Bug52792Servlet.java

  18 
vote

/** 
 * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response)
 */
@Override protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  try {
    InitialContext ctx=new InitialContext();
    ctx.lookup("java:comp/env/unknown-resource");
  }
 catch (  NamingException e) {
    response.getWriter().println(e.getMessage());
  }
}
 

Example 13

From project geronimo-xbean, under directory /xbean-naming/src/test/java/org/apache/xbean/naming/global/.

Source file: GlobalContextManagerTest.java

  18 
vote

public void testNoGlobalContextSet() throws Exception {
  Hashtable env=new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY,GlobalContextManager.class.getName());
  try {
    InitialContext initialContext=new InitialContext(env);
    initialContext.lookup("");
    fail("expected a NoInitialContextException");
  }
 catch (  NoInitialContextException expected) {
  }
}
 

Example 14

From project guice-automatic-injection, under directory /examples/src/main/java/de/devsurf/injection/guice/integrations/example/guicy/jndi/.

Source file: ExampleApp.java

  18 
vote

@Override public void run(){
  try {
    InitialContext context=new InitialContext();
    Example example=(Example)context.lookup(Example.class.getName());
    System.out.println(example.sayHello());
  }
 catch (  NamingException e) {
    e.printStackTrace();
  }
}
 

Example 15

From project human-task-poc-proposal, under directory /human-task-switchard/src/test/java/org/jboss/humantaskswitchyard/.

Source file: SwitchardCamelCDISimpleTest.java

  18 
vote

private MessageConsumer createNotificationConsumer(final String queueName) throws Exception {
  InitialContext initialContext=null;
  Connection connection=null;
  Session session=null;
  MessageConsumer consumer=null;
  initialContext=new InitialContext();
  final Topic testTopic=(Topic)initialContext.lookup(queueName);
  final ConnectionFactory connectionFactory=(ConnectionFactory)initialContext.lookup("ConnectionFactory");
  connection=connectionFactory.createConnection();
  connection.start();
  session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
  consumer=session.createConsumer(testTopic);
  return consumer;
}
 

Example 16

From project infinispan-examples, under directory /carmart-tx-jdbc/src/jbossas/java/org/infinispan/examples/carmart/jsf/.

Source file: PopulateCache.java

  18 
vote

private BeanManager getBeanManagerFromJNDI(){
  InitialContext context;
  Object result;
  try {
    context=new InitialContext();
    result=context.lookup("java:comp/BeanManager");
  }
 catch (  NamingException e) {
    throw new RuntimeException("BeanManager could not be found in JNDI",e);
  }
  return (BeanManager)result;
}
 

Example 17

From project java-maven-tests, under directory /src/jboss/esb/hello-sample-client/src/main/java/com/mysite/jbossesb/.

Source file: JmsClientSample.java

  18 
vote

private void setupConnection() throws JMSException, NamingException {
  final Properties properties=new Properties();
  properties.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
  properties.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
  properties.put(Context.PROVIDER_URL,"jnp://127.0.0.1:1099");
  InitialContext initialContext=new InitialContext(properties);
  final Object tmp=initialContext.lookup("ConnectionFactory");
  final QueueConnectionFactory connectionFactory=(QueueConnectionFactory)tmp;
  queueConnection=connectionFactory.createQueueConnection();
  queue=(Queue)initialContext.lookup("queue/quickstart_helloworld_Request_gw");
  queueSession=queueConnection.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
  queueConnection.start();
  System.out.println("Connection Started");
}
 

Example 18

From project jboss-as-quickstart, under directory /carmart-tx/src/jbossas/java/org/jboss/as/quickstarts/datagrid/carmart/jsf/.

Source file: PopulateCache.java

  18 
vote

private BeanManager getBeanManagerFromJNDI(){
  InitialContext context;
  Object result;
  try {
    context=new InitialContext();
    result=context.lookup("java:comp/BeanManager");
  }
 catch (  NamingException e) {
    throw new RuntimeException("BeanManager could not be found in JNDI",e);
  }
  return (BeanManager)result;
}
 

Example 19

From project jboss-ejb3-tutorial, under directory /blob/src/org/jboss/tutorial/blob/client/.

Source file: Client.java

  18 
vote

public static void main(String[] args) throws Exception {
  InitialContext ctx=new InitialContext();
  LobTester test=(LobTester)ctx.lookup("LobTesterBean/remote");
  long blobId=test.create();
  HashMap map=test.findBlob(blobId);
  System.out.println("is hello in map: " + map.get("hello"));
  System.out.println(test.findClob(blobId));
  System.out.println("creating and getting a BlobEntity2 that uses byte[] and String instead of Clob/Blob");
  blobId=test.create2();
  BlobEntity2 entity=test.findBlob2(blobId);
}
 

Example 20

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/.

Source file: DB.java

  17 
vote

/** 
 * Opens a connection from JNDI based on a registered name. This assumes that there is a <code>jndi.properties</code> file with proper JNDI configuration in it.
 * @param jndiName name of a configured data source. 
 */
public void open(String jndiName){
  checkExistingConnection(dbName);
  try {
    Context ctx=new InitialContext();
    DataSource ds=(DataSource)ctx.lookup(jndiName);
    Connection connection=ds.getConnection();
    ConnectionsAccess.attach(dbName,connection);
  }
 catch (  Exception e) {
    throw new InitException(e);
  }
}
 

Example 21

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/servlets/.

Source file: AppController.java

  17 
vote

/** 
 * init() is called once automatically by the servlet container (e.g. Tomcat) at servlet startup. We use it to initialise various things, namely: a) create the DatabaseDefn object which is the top level application object. The DatabaseDefn object will load the list of tables & reports into memory when it is constructed. It will also configure and load the object database b) create a DataSource object here to pass to the DatabaseDefn. This data source then acts as a pool of connections from which a connection to the relational database can be called up whenever needed.
 */
public void init() throws ServletException {
  logger.info("Initialising " + AppProperties.applicationName);
  ServletContext servletContext=getServletContext();
  this.webAppRoot=servletContext.getRealPath("/");
  DataSource relationalDataSource=null;
  InitialContext initialContext=null;
  try {
    initialContext=new InitialContext();
    relationalDataSource=(DataSource)initialContext.lookup("java:comp/env/jdbc/agileBaseData");
    if (relationalDataSource == null) {
      throw new ServletException("Can't get data source");
    }
    this.relationalDataSource=relationalDataSource;
    this.databaseDefn=new DatabaseDefn(relationalDataSource,this.webAppRoot);
    servletContext.setAttribute("com.gtwm.pb.servlets.databaseDefn",this.databaseDefn);
    servletContext.setAttribute("com.gtwm.pb.servlets.relationalDataSource",this.relationalDataSource);
  }
 catch (  NullPointerException npex) {
    ServletUtilMethods.logException(npex,"Error initialising controller servlet");
    throw new ServletException("Error initialising controller servlet",npex);
  }
catch (  SQLException sqlex) {
    ServletUtilMethods.logException(sqlex,"Database error loading schema");
    throw new ServletException("Database error loading schema",sqlex);
  }
catch (  NamingException neex) {
    ServletUtilMethods.logException(neex,"Can't get initial context");
    throw new ServletException("Can't get initial context");
  }
catch (  RuntimeException rtex) {
    ServletUtilMethods.logException(rtex,"Runtime initialisation error");
    throw new ServletException("Runtime initialisation error",rtex);
  }
catch (  Exception ex) {
    ServletUtilMethods.logException(ex,"General initialisation error");
    throw new ServletException("General initialisation error",ex);
  }
  logger.info("Application fully loaded");
}
 

Example 22

From project arquillian-container-glassfish, under directory /glassfish-embedded-3.1/src/test/java/org/jboss/arquillian/container/glassfish/embedded_3_1/app/.

Source file: AsAdminCommandTestCase.java

  17 
vote

@Test public void shouldBeAbleToIssueAsAdminCommand() throws Exception {
  Assert.assertNotNull("Verify that the asadmin CommandRunner resource is available",commandRunner);
  CommandResult result=commandRunner.run("create-jdbc-connection-pool","--datasourceclassname=org.apache.derby.jdbc.EmbeddedXADataSource","--restype=javax.sql.XADataSource","--property=portNumber=1527:password=APP:user=APP" + ":serverName=localhost:databaseName=my_database" + ":connectionAttributes=create\\=true","my_derby_pool");
  Assert.assertEquals("Verify 'create-jdbc-connection-pool' asadmin command",ExitStatus.SUCCESS,result.getExitStatus());
  result=commandRunner.run("create-jdbc-resource","--connectionpoolid","my_derby_pool","jdbc/my_database");
  Assert.assertEquals("Verify 'create-jdbc-resource' asadmin command",ExitStatus.SUCCESS,result.getExitStatus());
  result=commandRunner.run("ping-connection-pool","my_derby_pool");
  Assert.assertEquals("Verify asadmin command 'ping-connection-pool'",ExitStatus.SUCCESS,result.getExitStatus());
  Context ctx=new InitialContext();
  DataSource myDatabase=(DataSource)ctx.lookup("jdbc/my_database");
  Assert.assertNotNull(myDatabase);
}
 

Example 23

From project arquillian-core, under directory /container/test-impl-base/src/test/java/org/jboss/arquillian/container/test/impl/enricher/resource/.

Source file: InitialContextProviderTestCase.java

  17 
vote

@Test public void shouldBeAbleToInjectContextQualified() throws Exception {
  Context contextZ=new InitialContext();
  Context contextX=new InitialContext();
  ContextClassQualifed test=execute(ContextClassQualifed.class,Context.class,contextZ,contextX);
  Assert.assertEquals(contextX,test.context);
}
 

Example 24

From project blacktie, under directory /jatmibroker-xatmi/src/main/java/org/jboss/narayana/blacktie/jatmibroker/core/transport/.

Source file: JtsTransactionImple.java

  17 
vote

/** 
 * Lookup the JTA transaction manager
 * @return the JTA transaction manager in the VM
 * @throws NamingException
 */
private synchronized static TransactionManager getTransactionManager() throws NamingException {
  if (tm == null) {
    Context ctx=new InitialContext();
    tm=(TransactionManager)ctx.lookup("java:/TransactionManager");
  }
  return tm;
}
 

Example 25

From project bpm-console, under directory /server/integration/src/main/java/org/jboss/bpm/console/server/util/.

Source file: InvocationProxy.java

  17 
vote

public Object invoke(Object proxy,Method m,Object[] args) throws Throwable {
  Object result;
  InitialContext ctx=new InitialContext();
  UserTransaction tx=(UserTransaction)ctx.lookup("UserTransaction");
  try {
    tx.begin();
    result=m.invoke(obj,args);
    tx.commit();
  }
 catch (  Exception e) {
    if (tx != null) {
      try {
        tx.rollback();
      }
 catch (      SystemException e1) {
      }
    }
    throw new RuntimeException("Unexpected invocation exception: " + e.getMessage(),e);
  }
 finally {
  }
  return result;
}
 

Example 26

From project c3p0, under directory /src/java/com/mchange/v2/c3p0/jboss/.

Source file: C3P0PooledDataSource.java

  17 
vote

private void rebind(String unbindName) throws NamingException {
  InitialContext ictx=new InitialContext();
  if (unbindName != null)   ictx.unbind(unbindName);
  if (jndiName != null) {
    Name name=ictx.getNameParser(jndiName).parse(jndiName);
    Context ctx=ictx;
    for (int i=0, max=name.size() - 1; i < max; i++) {
      try {
        ctx=ctx.createSubcontext(name.get(i));
      }
 catch (      NameAlreadyBoundException ignore) {
        ctx=(Context)ctx.lookup(name.get(i));
      }
    }
    ictx.rebind(jndiName,combods);
  }
}
 

Example 27

From project camelpe, under directory /examples/loan-broker-jboss7/src/main/java/net/camelpe/examples/jboss7/loanbroker/queue/.

Source file: JBoss7CamelContextConfiguration.java

  17 
vote

private synchronized InitialContext getInitialContext() throws NamingException {
  if (this.initialContext == null) {
    this.initialContext=new InitialContext();
  }
  return this.initialContext;
}
 

Example 28

From project capedwarf-green, under directory /javax-cache/src/main/java/org/jboss/capedwarf/cache/infinispan/tx/.

Source file: JBossAS7TransactionManagerLookup.java

  17 
vote

public TransactionManager getTransactionManager() throws Exception {
  Context context=new InitialContext();
  try {
    Object lookup=context.lookup("java:jboss/TransactionManager");
    return TransactionManager.class.cast(lookup);
  }
  finally {
    context.close();
  }
}
 

Example 29

From project cipango, under directory /cipango-plus/src/test/java/org/cipango/plus/sipapp/.

Source file: PlusConfigurationTest.java

  17 
vote

@Test public void testConfig() throws Exception {
  ClassLoader old_loader=Thread.currentThread().getContextClassLoader();
  try {
    InitialContext ic=new InitialContext();
    SipServer server=new SipServer();
    SipAppContext context=new SipAppContext();
    WebAppContext webAppContext=new WebAppContext();
    context.setWebAppContext(webAppContext);
    context.setServer(server);
    context.getMetaData().setAppName("myApp");
    webAppContext.setClassLoader(new WebAppClassLoader(Thread.currentThread().getContextClassLoader(),webAppContext));
    context.getOverrideDescriptors().add(getClass().getResource("/sip.xml").toString());
    Thread.currentThread().setContextClassLoader(webAppContext.getClassLoader());
    PlusConfiguration plusConfiguration=new PlusConfiguration();
    EnvConfiguration envConfiguration=new EnvConfiguration();
    envConfiguration.setJettyEnvXml(getClass().getResource("/jetty-env.xml"));
    context.getMetaData().addListener("org.cipango.plus.sipapp.Listener");
    webAppContext.setConfigurations(new Configuration[]{envConfiguration,plusConfiguration,new SipXmlConfiguration()});
    webAppContext.preConfigure();
    webAppContext.configure();
    webAppContext.postConfigure();
    context.getMetaData().resolve(context);
    Object lookup=ic.lookup("java:comp/env/resource/sample");
    Assert.assertNotNull(lookup);
    Assert.assertEquals("1234",lookup);
    Assert.assertEquals(context.getSipFactory(),ic.lookup("java:comp/env/sip/myApp/SipFactory"));
    Assert.assertEquals(context.getTimerService(),ic.lookup("java:comp/env/sip/myApp/TimerService"));
    Assert.assertEquals(context.getSipSessionsUtil(),ic.lookup("java:comp/env/sip/myApp/SipSessionsUtil"));
  }
  finally {
    Thread.currentThread().setContextClassLoader(old_loader);
  }
}
 

Example 30

From project core_5, under directory /exo.core.component.database/src/main/java/org/exoplatform/services/database/jdbc/.

Source file: DBSchemaCreator.java

  17 
vote

public void createTables(String dsName,String script) throws NamingException, SQLException {
  InitialContext context=new InitialContext();
  DataSource ds=(DataSource)context.lookup(dsName);
  Connection conn=ds.getConnection();
  String sql="";
  try {
    String[] scripts=JDBCUtils.splitWithSQLDelimiter(script);
    for (    String scr : scripts) {
      String s=JDBCUtils.cleanWhitespaces(scr.trim());
      if (s.length() < 1)       continue;
      sql=s;
      if (LOG.isDebugEnabled())       LOG.debug("Execute script: \n[" + sql + "]");
      try {
        conn.setAutoCommit(false);
        conn.createStatement().executeUpdate(sql);
        conn.commit();
      }
 catch (      SQLException e) {
        conn.rollback();
        Matcher aeMatcher=pattern.matcher(e.getMessage().trim());
        if (!aeMatcher.matches())         throw e;
        if (LOG.isDebugEnabled())         LOG.debug(e.getMessage());
      }
    }
    LOG.info("DB schema of DataSource: '" + dsName + "' created succesfully. context "+ context);
  }
 catch (  SQLException e) {
    LOG.error("Could not create db schema of DataSource: '" + dsName + "'. Reason: "+ e.getMessage()+ "; "+ JDBCUtils.getFullMessage(e)+ ". Last command: "+ sql,e);
  }
 finally {
    conn.close();
  }
}
 

Example 31

From project crash, under directory /cmdline/src/main/java/org/crsh/cmdline/completers/.

Source file: JNDICompleter.java

  17 
vote

/** 
 * Search JNDI Path in Context and put the result in ValueCompletion.
 * @return ValueCompletion
 */
ValueCompletion getJndiList(String prefix){
  HashSet<String> contextNames=initJndicontextNames();
  if (prefix != null) {
    contextNames.add(prefix);
  }
  ValueCompletion completions=new ValueCompletion();
  for (  String contextName : contextNames) {
    if (!contextName.endsWith("/")) {
      contextName=contextName + "/";
    }
    try {
      InitialContext ctx=new InitialContext();
      NamingEnumeration<NameClassPair> list=ctx.list(contextName);
      while (list.hasMore()) {
        NameClassPair nc=list.next();
        if (null == nc) {
          continue;
        }
        String jndiPath=getJndiPath(contextName,nc.getName(),prefix);
        if (jndiPath != null) {
          completions.put(jndiPath,false);
        }
      }
    }
 catch (    NamingException e1) {
    }
  }
  return completions;
}
 

Example 32

From project des, under directory /daemon/lib/apache-log4j-1.2.16/contribs/Jamie Tsao/.

Source file: JMSQueueAppender.java

  17 
vote

protected InitialContext getInitialContext() throws NamingException {
  try {
    Hashtable ht=new Hashtable();
    ht.put(Context.INITIAL_CONTEXT_FACTORY,initialContextFactory);
    ht.put(Context.PROVIDER_URL,providerUrl);
    return (new InitialContext(ht));
  }
 catch (  NamingException ne) {
    LogLog.error("Could not get initial context with [" + initialContextFactory + "] and ["+ providerUrl+ "].");
    throw ne;
  }
}
 

Example 33

From project drools-chance, under directory /drools-informer/human-task-helpers/src/main/java/org/jbpm/task/.

Source file: HumanTaskServiceLookup.java

  17 
vote

public static TaskService lookup(){
  try {
    Context initCtx=new InitialContext();
    Context envCtx=(Context)initCtx.lookup("java:comp/env");
    TaskService service=(TaskService)envCtx.lookup("bean/HumanTaskService");
    System.out.println("GETTING JNDI TASK SERVICE INSTANCE = " + service);
    return service;
  }
 catch (  NamingException ne) {
    System.err.println(ne.getMessage());
    return null;
  }
}
 

Example 34

From project ehour, under directory /eHour-standalone/src/main/java/net/rrm/ehour/.

Source file: EhourServer.java

  17 
vote

private void registerJndiDS(ServerConfig config) throws IOException, NamingException {
  DataSource dataSource=createDataSource(config);
  Context context;
  context=new InitialContext();
  Context compCtx=(Context)context.lookup("java:comp");
  Context envCtx=compCtx.createSubcontext("env");
  NamingUtil.bind(envCtx,"jdbc/eHourDS",dataSource);
}
 

Example 35

From project Empire, under directory /sql/src/com/clarkparsia/empire/sql/.

Source file: DSC3poContext.java

  17 
vote

public void init() throws NamingException {
  try {
    InitialContext aContext=new InitialContext();
    setInitialContext(aContext);
    ComboPooledDataSource cpds=new ComboPooledDataSource();
    cpds.setDriverClass(getConfig().getDriver());
    cpds.setJdbcUrl(getConfig().getUrl());
    cpds.setUser(getConfig().getUser());
    cpds.setPassword(getConfig().getPassword());
    cpds.setMaxPoolSize(Integer.valueOf(getConfig().getMaxActive()));
    cpds.setMinPoolSize(Integer.valueOf(getConfig().getMaxIdle()));
    cpds.setAcquireIncrement(1);
    aContext.rebind(getContextName(),cpds);
    setDataSource((DataSource)aContext.lookup(getContextName()));
  }
 catch (  PropertyVetoException e) {
    e.printStackTrace();
  }
catch (  NamingException ne) {
    ne.printStackTrace();
  }
}
 

Example 36

From project fedora-client, under directory /fedora-client-messaging/src/main/java/com/yourmediashelf/fedora/client/messaging/.

Source file: JMSManager.java

  17 
vote

protected Context getContext() throws MessagingException {
  try {
    InitialContext initCtx;
    if (jndiProps != null) {
      return new InitialContext(jndiProps);
    }
    initCtx=new InitialContext();
    Context envCtx=(Context)initCtx.lookup("java:comp/env");
    if (logger.isDebugEnabled()) {
      logger.debug("InitalContext properties:");
      logger.debug("----------------");
      Hashtable<?,?> props=initCtx.getEnvironment();
      Set<?> keys=props.keySet();
      for (      Object key : keys) {
        logger.debug(key.toString() + "=" + props.get(key));
      }
      logger.debug("java:comp/env context properties:");
      logger.debug("----------------");
      props=envCtx.getEnvironment();
      keys=props.keySet();
      for (      Object key : keys) {
        logger.debug(key.toString() + "=" + props.get(key));
      }
      logger.debug("----------------");
    }
    return envCtx;
  }
 catch (  Exception e) {
    logger.error("getContext() failed with: " + e.getMessage());
    throw new MessagingException(e.getMessage(),e);
  }
}
 

Example 37

From project GoFleetLSServer, under directory /configuration/src/main/java/org/gofleet/configuration/.

Source file: Configuration.java

  17 
vote

protected AbstractConfiguration getConfiguration(){
  if (configuration == null) {
    configuration=new CompositeConfiguration();
    try {
      if (dataSource != null && dataSource.isAccessToUnderlyingConnectionAllowed() && !dataSource.isClosed())       configuration.addConfiguration(new DatabaseConfiguration(dataSource,"configuration","key","value"));
    }
 catch (    Throwable t) {
      log.error("Error loading database configuration",t);
    }
    try {
      configuration.addConfiguration(new JNDIConfiguration(new InitialContext()));
    }
 catch (    Throwable t) {
      log.error("Error loading jndi configuration",t);
    }
    try {
      final PropertiesConfiguration configurator=new PropertiesConfiguration();
      InitialContext icontext=new InitialContext();
      Context context=(Context)icontext.lookup("java:comp/env");
      NamingEnumeration<NameClassPair> propiedadesJDNI=context.list("");
      while (propiedadesJDNI.hasMoreElements()) {
        NameClassPair propiety=propiedadesJDNI.nextElement();
        configurator.addProperty(propiety.getName(),context.lookup(propiety.getName()));
        log.trace("Configuring '" + propiety.getName() + "' as '"+ configurator.getString(propiety.getName().toString())+ "'");
      }
      configuration.addConfiguration(configurator);
    }
 catch (    NamingException e) {
      log.error("Error loading configuration from context: " + e,e);
    }
  }
  return configuration;
}
 

Example 38

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/.

Source file: ContextDatabaseClusterConfigurationFactory.java

  17 
vote

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
  input.defaultReadObject();
  int size=input.readInt();
  Hashtable<String,String> env=(size > 0) ? new Hashtable<String,String>() : null;
  for (int i=0; i < input.readInt(); ++i) {
    env.put(input.readUTF(),input.readUTF());
  }
  try {
    this.context=new InitialContext(env);
  }
 catch (  NamingException e) {
    throw new IOException(e);
  }
}
 

Example 39

From project heritrix3, under directory /commons/src/main/java/org/archive/util/.

Source file: JndiUtils.java

  17 
vote

/** 
 * Get subcontext.  Only looks down one level.
 * @param subContext Name of subcontext to return.
 * @return Sub context.
 * @throws NamingException 
 */
public static Context getSubContext(final CompoundName subContext) throws NamingException {
  Context context=new InitialContext();
  try {
    context=(Context)context.lookup(subContext);
  }
 catch (  NameNotFoundException e) {
    context=context.createSubcontext(subContext);
  }
  return context;
}
 

Example 40

From project hibernate-validator, under directory /integration/src/test/java/org/hibernate/validator/integration/jbossas7/.

Source file: JndiLookupOfValidatorFactoryIT.java

  17 
vote

@Test public void testDefaultValidatorFactoryLookup() throws Exception {
  log.debug("Running testDefaultValidatorFactoryLookup...");
  try {
    Context ctx=new InitialContext();
    Object obj=ctx.lookup(DEFAULT_JNDI_NAME_OF_VALIDATOR_FACTORY);
    assertTrue("The default validator factory should be bound",obj != null);
    ValidatorFactory factory=(ValidatorFactory)obj;
    assertEquals("The Hibernate Validator implementation should be used","ValidatorImpl",factory.getValidator().getClass().getSimpleName());
  }
 catch (  NamingException e) {
    fail("The default validator factory should be bound");
  }
  log.debug("testDefaultValidatorFactoryLookup completed");
}
 

Example 41

From project incubator-deltaspike, under directory /deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/.

Source file: BeanManagerProvider.java

  17 
vote

/** 
 * Get the BeanManager from the JNDI registry.
 * @return current {@link BeanManager} which is provided via JNDI
 */
private BeanManager resolveBeanManagerViaJndi(){
  try {
    return (BeanManager)new InitialContext().lookup("java:comp/BeanManager");
  }
 catch (  NamingException e) {
    return null;
  }
}
 

Example 42

From project integration-tests, under directory /picketlink-sts-tests/src/test/java/org/picketlink/test/integration/sts/.

Source file: CacheInvalidationUnitTestCase.java

  17 
vote

/** 
 * <p> This test checks the invalidation of expired cache entries by requesting a short-lived assertion to the STS and then using this assertion to authenticate to the  {@code JaasSecurityManagerService} MBean. The test checksif the cache contains the entry right after authentication takes place and then sleeps till the assertion expires. After that, the test checks the cache again to verify if the entry has been removed. </p>
 * @throws Exception if an error occurs while running the test.
 */
@Test public void testCacheInvalidation() throws Exception {
  Properties props=new Properties();
  props.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
  props.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
  props.put("java.naming.provider.url","localhost:1099");
  MBeanServerConnection server=null;
  InitialContext ic=new InitialContext(props);
  Object obj=ic.lookup("jmx/invoker/RMIAdaptor");
  server=(MBeanServerConnection)obj;
  Assert.assertNotNull("RMIAdaptor is null, lookup failed",server);
  WSTrustClient client=new WSTrustClient("PicketLinkSTS","PicketLinkSTSPort","http://localhost:8080/picketlink-sts/PicketLinkSTS",new SecurityInfo("tomcat","tomcat"));
  RequestSecurityToken request=new RequestSecurityToken();
  request.setRequestType(URI.create(WSTrustConstants.ISSUE_REQUEST));
  request.setTokenType(URI.create(SAMLUtil.SAML2_TOKEN_TYPE));
  request.setLifetime(WSTrustUtil.createDefaultLifetime(10000));
  Element assertionElement=client.issueToken(request);
  Assert.assertNotNull("SAML assertion is null, token request failed",assertionElement);
  ObjectName name=new ObjectName("jboss.security:service=JaasSecurityManager");
  String[] methodSignature={"java.lang.String","java.security.Principal","java.lang.Object"};
  Object[] methodParams={"picketlink-sts",new SimplePrincipal("tomcat"),new SamlCredential(assertionElement)};
  Object result=server.invoke(name,"isValid",methodParams,methodSignature);
  Assert.assertTrue("isValid returned an invalid result object",result instanceof Boolean);
  Assert.assertTrue("Authentication failed",(Boolean)result);
  methodSignature=new String[]{"java.lang.String"};
  methodParams=new Object[]{"picketlink-sts"};
  result=server.invoke(name,"getAuthenticationCachePrincipals",methodParams,methodSignature);
  Assert.assertTrue("getAuthenticationCachePrincipals returned an invalid result object",result instanceof List<?>);
  List<?> resultList=(List<?>)result;
  Assert.assertEquals("Unexpected cache size",1,resultList.size());
  Assert.assertEquals("Unexpected cached principal","tomcat",resultList.get(0).toString());
  Thread.sleep(12000);
  result=server.invoke(name,"getAuthenticationCachePrincipals",methodParams,methodSignature);
  Assert.assertTrue("getAuthenticationCachePrincipals returned an invalid result object",result instanceof List<?>);
  resultList=(List<?>)result;
  Assert.assertEquals("Unexpected cache size",0,resultList.size());
}
 

Example 43

From project java-cas-client, under directory /cas-client-core/src/main/java/org/jasig/cas/client/util/.

Source file: AbstractConfigurationFilter.java

  17 
vote

/** 
 * Retrieves the property from the FilterConfig.  First it checks the FilterConfig's initParameters to see if it has a value. If it does, it returns that, otherwise it retrieves the ServletContext's initParameters and returns that value if any. <p> Finally, it will check JNDI if all other methods fail.  All the JNDI properties should be stored under either java:comp/env/cas/SHORTFILTERNAME/{propertyName} or java:comp/env/cas/{propertyName} <p> Essentially the documented order is: <ol> <li>FilterConfig.getInitParameter</li> <li>ServletContext.getInitParameter</li> <li>java:comp/env/cas/SHORTFILTERNAME/{propertyName}</li> <li>java:comp/env/cas/{propertyName}</li> <li>Default Value</li> </ol>
 * @param filterConfig the Filter Configuration.
 * @param propertyName the property to retrieve.
 * @param defaultValue the default value if the property is not found.
 * @return the property value, following the above conventions.  It will always return the more specific value (i.e.filter vs. context).
 */
protected final String getPropertyFromInitParams(final FilterConfig filterConfig,final String propertyName,final String defaultValue){
  final String value=filterConfig.getInitParameter(propertyName);
  if (CommonUtils.isNotBlank(value)) {
    log.info("Property [" + propertyName + "] loaded from FilterConfig.getInitParameter with value ["+ value+ "]");
    return value;
  }
  final String value2=filterConfig.getServletContext().getInitParameter(propertyName);
  if (CommonUtils.isNotBlank(value2)) {
    log.info("Property [" + propertyName + "] loaded from ServletContext.getInitParameter with value ["+ value2+ "]");
    return value2;
  }
  InitialContext context;
  try {
    context=new InitialContext();
  }
 catch (  final NamingException e) {
    log.warn(e,e);
    return defaultValue;
  }
  final String shortName=this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".") + 1);
  final String value3=loadFromContext(context,"java:comp/env/cas/" + shortName + "/"+ propertyName);
  if (CommonUtils.isNotBlank(value3)) {
    log.info("Property [" + propertyName + "] loaded from JNDI Filter Specific Property with value ["+ value3+ "]");
    return value3;
  }
  final String value4=loadFromContext(context,"java:comp/env/cas/" + propertyName);
  if (CommonUtils.isNotBlank(value4)) {
    log.info("Property [" + propertyName + "] loaded from JNDI with value ["+ value4+ "]");
    return value4;
  }
  log.info("Property [" + propertyName + "] not found.  Using default value ["+ defaultValue+ "]");
  return defaultValue;
}
 

Example 44

From project jbosgi, under directory /testsuite/example/src/test/java/org/jboss/test/osgi/example/ejb3/.

Source file: StatelessBeanTestCase.java

  17 
vote

@Test public void testStatelessBean() throws Exception {
  String jndiname="java:global/ejb3-osgi/SimpleStatelessSessionBean!org.jboss.test.osgi.example.ejb3.bundle.SimpleStatelessSessionBean";
  Echo service=(Echo)new InitialContext().lookup(jndiname);
  assertNotNull("StatelessBean not null",service);
  assertEquals("ejb3-osgi-target",service.echo(BUNDLE_SYMBOLICNAME));
  assertEquals("foo",service.echo("foo"));
}
 

Example 45

From project jboss-ejb-client, under directory /src/test/java/org/jboss/ejb/client/.

Source file: EjbNamespaceTestCase.java

  17 
vote

@Test public void testEjbNamespaceLookup() throws NamingException {
  Object result=new InitialContext().lookup("ejb:app/module/distinct/MyEjb!org.jboss.ejb.client.SimpleInterface");
  Assert.assertTrue(result instanceof SimpleInterface);
  final EJBInvocationHandler handler=(EJBInvocationHandler)Proxy.getInvocationHandler(result);
  final EJBLocator<SimpleInterface> locator=(EJBLocator<SimpleInterface>)handler.getLocator();
  Assert.assertEquals("app",locator.getAppName());
  Assert.assertEquals("module",locator.getModuleName());
  Assert.assertEquals("distinct",locator.getDistinctName());
  Assert.assertEquals("MyEjb",locator.getBeanName());
}
 

Example 46

From project jboss-ejb3-singleton, under directory /impl/src/main/java/org/jboss/ejb3/singleton/impl/container/.

Source file: SingletonContainer.java

  17 
vote

public Context getENC(){
  try {
    return new InitialContext();
  }
 catch (  NamingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 47

From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/listener/configuration/.

Source file: AdServerModule.java

  16 
vote

private void initTracking(BaseContext context){
  try {
    String classname=RuntimeContext.getProperties().getProperty(AdServerConstants.CONFIG.PROPERTIES.TRACKINGSERVICE_CLASS,"");
    TrackingService trackService=(TrackingService)Class.forName(classname).newInstance();
    if (trackService instanceof H2TrackingService) {
      Context ctx=new InitialContext();
      ctx=(Context)ctx.lookup("java:comp/env");
      DataSource ds=(DataSource)ctx.lookup("jdbc/trackingds");
      context.put(TrackingContextKeys.EMBEDDED_TRACKING_DATASOURCE,ds);
    }
    trackService.open(context);
    bind(TrackingService.class).toInstance(trackService);
  }
 catch (  NamingException se) {
    logger.error("",se);
  }
catch (  ClassCastException cce) {
    logger.error("",cce);
  }
catch (  ServiceException e) {
    logger.error("",e);
  }
catch (  InstantiationException e) {
    logger.error("",e);
  }
catch (  IllegalAccessException e) {
    logger.error("",e);
  }
catch (  ClassNotFoundException e) {
    logger.error("",e);
  }
}
 

Example 48

From project agraph-java-client, under directory /src/test/web/.

Source file: AGExampleServletContextListener.java

  16 
vote

@Override public void contextDestroyed(ServletContextEvent event){
  Closer c=new Closer();
  try {
    Context initCtx=c.closeLater(new InitialContext());
    Context envCtx=(Context)c.closeLater(initCtx.lookup("java:comp/env"));
    AGConnPool pool=(AGConnPool)envCtx.lookup("connection-pool/agraph");
    pool.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    c.close();
  }
}
 

Example 49

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: CDIListener.java

  16 
vote

protected BeanManager getBeanManager(){
  Context nc=null;
  try {
    nc=new InitialContext();
    return (BeanManager)nc.lookup(STANDARD_BEAN_MANAGER_JNDI_NAME);
  }
 catch (  Exception e) {
    log.warning("Cannot find BeanManager: " + e);
    return null;
  }
 finally {
    if (nc != null) {
      try {
        nc.close();
      }
 catch (      NamingException ignored) {
      }
    }
  }
}
 

Example 50

From project cdi-extension-showcase, under directory /src/main/java/com/acme/wicketint/.

Source file: BeanWebApplicationFactory.java

  16 
vote

public WebApplication createApplication(WicketFilter filter){
  BeanManager bm;
  try {
    System.out.println("Trying java:comp/BeanManager...");
    bm=(BeanManager)new InitialContext().lookup("java:comp/BeanManager");
  }
 catch (  NamingException e) {
    try {
      System.out.println("Trying java:comp/env/BeanManager...");
      bm=(BeanManager)new InitialContext().lookup("java:comp/env/BeanManager");
    }
 catch (    NamingException e2) {
      throw new RuntimeException("Could not locate BeanManager in JNDI");
    }
  }
  Bean<WebApplicationBeanResolver> resolverBean=(Bean<WebApplicationBeanResolver>)bm.resolve(bm.getBeans(WebApplicationBeanResolver.class));
  CreationalContext<WebApplicationBeanResolver> cc=bm.createCreationalContext(resolverBean);
  WebApplicationBeanResolver resolver=(WebApplicationBeanResolver)bm.getReference(resolverBean,WebApplicationBeanResolver.class,cc);
  WebApplication webapp=resolver.resolveWebApplication();
  cc.release();
  return webapp;
}
 

Example 51

From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/core/.

Source file: SolrResourceLoader.java

  16 
vote

/** 
 * Finds the solrhome based on looking up the value in one of three places: <ol> <li>JNDI: via java:comp/env/solr/home</li> <li>The system property solr.solr.home</li> <li>Look in the current working directory for a solr/ directory</li>  </ol> The return value is normalized.  Normalization essentially means it ends in a trailing slash.
 * @return A normalized solrhome
 * @see #normalizeDir(String)
 */
public static String locateSolrHome(){
  String home=null;
  try {
    Context c=new InitialContext();
    home=(String)c.lookup("java:comp/env/" + project + "/home");
    log.info("Using JNDI solr.home: " + home);
  }
 catch (  NoInitialContextException e) {
    log.info("JNDI not configured for " + project + " (NoInitialContextEx)");
  }
catch (  NamingException e) {
    log.info("No /" + project + "/home in JNDI");
  }
catch (  RuntimeException ex) {
    log.warn("Odd RuntimeException while testing for JNDI: " + ex.getMessage());
  }
  if (home == null) {
    String prop=project + ".solr.home";
    home=System.getProperty(prop);
    if (home != null) {
      log.info("using system property " + prop + ": "+ home);
    }
  }
  if (home == null) {
    home=project + '/';
    log.info(project + " home defaulted to '" + home+ "' (could not find system property or JNDI)");
  }
  return normalizeDir(home);
}
 

Example 52

From project gatein-naming, under directory /src/main/java/org/gatein/naming/.

Source file: FailoverInitialContextFactory.java

  16 
vote

/** 
 * Get an initial context instance.
 * @param environment The naming environment
 * @return A naming context instance
 * @throws javax.naming.NamingException
 */
@SuppressWarnings("unchecked") public Context getInitialContext(Hashtable<?,?> environment) throws NamingException {
  Context failover;
  String factory=System.getProperty("org.gatein.naming.fallback.factory");
  if (factory != null) {
    Hashtable params=new Hashtable();
    params.put(Context.INITIAL_CONTEXT_FACTORY,factory);
    String url=System.getProperty("org.gatein.naming.fallback.url");
    if (url != null)     params.put(Context.PROVIDER_URL,url);
    failover=new InitialContext(params);
  }
 else {
    Hashtable params=new Hashtable();
    params.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.as.naming.InitialContextFactory");
    failover=new InitialContext(params);
  }
  return new FailoverNamingContext(failover,new NamingContext((Hashtable<String,Object>)environment));
}
 

Example 53

From project hcatalog, under directory /server-extensions/src/main/java/org/apache/hcatalog/listener/.

Source file: NotificationListener.java

  16 
vote

protected void createConnection(){
  Context jndiCntxt;
  try {
    jndiCntxt=new InitialContext();
    ConnectionFactory connFac=(ConnectionFactory)jndiCntxt.lookup("ConnectionFactory");
    Connection conn=connFac.createConnection();
    conn.start();
    conn.setExceptionListener(new ExceptionListener(){
      @Override public void onException(      JMSException jmse){
        LOG.error(jmse.toString());
      }
    }
);
    session=conn.createSession(true,Session.SESSION_TRANSACTED);
  }
 catch (  NamingException e) {
    LOG.error("JNDI error while setting up Message Bus connection. " + "Please make sure file named 'jndi.properties' is in " + "classpath and contains appropriate key-value pairs.",e);
  }
catch (  JMSException e) {
    LOG.error("Failed to initialize connection to message bus",e);
  }
catch (  Throwable t) {
    LOG.error("Unable to connect to JMS provider",t);
  }
}
 

Example 54

From project jBilling, under directory /src/java/com/sapienter/jbilling/common/.

Source file: JNDILookup.java

  16 
vote

/** 
 * EJBHomeFactory private constructor.
 */
private JNDILookup(boolean test) throws NamingException {
  log=Logger.getLogger(JNDILookup.class);
  if (test) {
    Hashtable env=new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
    env.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
    env.put(Context.PROVIDER_URL,"localhost");
    ctx=new InitialContext(env);
    log.info("Context set with environment.");
  }
 else {
    ctx=new InitialContext();
    log.info("Default Context set");
  }
}
 

Example 55

From project guice-jit-providers, under directory /core/test/com/google/inject/example/.

Source file: JndiProviderClient.java

  15 
vote

public static void main(String[] args) throws CreationException {
  Injector injector=Guice.createInjector(new AbstractModule(){
    protected void configure(){
      bind(Context.class).to(InitialContext.class);
      bind(DataSource.class).toProvider(fromJndi(DataSource.class,"..."));
    }
  }
);
}