Example usage for javax.naming InitialContext lookup

List of usage examples for javax.naming InitialContext lookup

Introduction

In this page you can find the example usage for javax.naming InitialContext lookup.

Prototype

public Object lookup(Name name) throws NamingException 

Source Link

Usage

From source file:org.miloss.fgsms.bueller.Bueller.java

private String doJmsURL(boolean pooled, String endpoint) {
    try {/*w ww . ja  v  a2  s. c om*/

        boolean ok = false;
        String server = endpoint.split("#")[0];
        server = server.replace("jms:", "jnp://");
        String name = endpoint.split("#")[1];
        String msg = "";
        String[] info = DBSettingsLoader.GetCredentials(pooled, endpoint);
        String username = null;
        String password = null;
        if (info != null) {
            username = info[0];
            password = info[1];
        } else {
            info = DBSettingsLoader.GetDefaultBuellerCredentials(pooled);
            if (info != null) {
                username = info[0];
                password = info[1];
            }
        }

        if (name.startsWith("topic")) {
            try {
                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                //properties1.put(Context.PROVIDER_URL, "jnp://127.0.0.1:1099");
                properties1.put(Context.PROVIDER_URL, server);

                InitialContext iniCtx = new InitialContext(properties1);

                TopicConnectionFactory tcf = (TopicConnectionFactory) iniCtx.lookup("TopicConnectionFactory");
                TopicConnection createTopicConnection = null;
                if (info != null) {
                    createTopicConnection = tcf.createTopicConnection(username, Utility.DE(password)); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                } else {
                    createTopicConnection = tcf.createTopicConnection(); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                }
                createTopicConnection.start();
                createTopicConnection.stop();
                createTopicConnection.close();
                //Topic topic = (Topic) iniCtx.lookup("//" + name);
                ok = true;

                //topic = null;
                iniCtx.close();

            } catch (Exception ex) {
                System.out.println(ex);
                msg = ex.getLocalizedMessage();
                //return ex.getLocalizedMessage();
            }
        } else if (name.startsWith("queue")) {
            try {

                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                properties1.put(Context.PROVIDER_URL, server);
                InitialContext iniCtx = new InitialContext(properties1);
                QueueConnection conn;
                QueueSession session;
                Queue que;

                Object tmp = iniCtx.lookup("ConnectionFactory");
                QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
                if (info != null) {
                    conn = qcf.createQueueConnection(username, Utility.DE(password));
                } else {
                    conn = qcf.createQueueConnection();
                }

                que = (Queue) iniCtx.lookup(name);
                session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
                conn.start();

                //System.out.println("Connection Started");
                ok = true;

                conn.stop();
                session.close();
                iniCtx.close();

            } catch (Exception ex) {
                log.log(Level.WARN, "Could not bind to jms queue", ex);
                msg = ex.getLocalizedMessage();
            }
            if (ok) {
                return "OK";
            }
            return "Unable to bind to JMS queue: " + msg;
        } else {
            return "Unsupported Protocol";
        }
    } catch (Exception ex) {
        log.log(Level.WARN, "service " + endpoint + " is offline or an error occured", ex);
        return "Offline " + ex.getLocalizedMessage();
    }
    return "undeterminable";
}

From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.MainTestCase.java

protected DataSource createJNDIDataSource(String jndiName) throws Exception {
    InitialContext ctx = new InitialContext();
    Object dataSourceObject = (DataSource) ctx.lookup(jndiName);

    if (dataSourceObject == null) {
        throw new NullPointerException("JNDI Data Source Lookup for '" + jndiName + "' not found.");
    }/*from   w  w  w. ja  va  2s  .  com*/

    if (!DataSource.class.isAssignableFrom(dataSourceObject.getClass())) {
        throw new Exception("The JNDI Lookup '" + jndiName + "' is of type '" + dataSourceObject.getClass()
                + "' and not a DataSource");
    }

    return (DataSource) dataSourceObject;
}

From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.MainTestCase.java

protected Object jndiLookup(String jndiName) throws Exception {
    InitialContext ctx = new InitialContext();
    Object ret = null;//from  ww  w . ja v a2 s . c  om

    try {
        ret = ctx.lookup(jndiName);
    } catch (NamingException ne) {
        //ne.printStackTrace();
    }

    return ret;
}

From source file:org.mifos.framework.ApplicationInitializer.java

private void initJNDIforPentaho(ApplicationContext applicationContext) {
    try {/* www.  j  av a2 s  .co  m*/
        InitialContext ic = new InitialContext();

        //check if ds is already bound
        boolean dataSourceBound = true;
        boolean dataSourceBoundDw = true;
        try {
            DataSource datasource = (DataSource) ic.lookup("jdbc/SourceDB");

            if (datasource != null) {
                dataSourceBound = true;
            }
        } catch (Exception ex) {
            dataSourceBound = false;
        }
        try {
            DataSource datasourcedw = (DataSource) ic.lookup("jdbc/DestinationDB");
            if (datasourcedw != null) {
                dataSourceBoundDw = true;
            }
        } catch (Exception ex) {
            dataSourceBoundDw = false;
        }

        if (!dataSourceBound) {
            Object dataSource = applicationContext.getBean("dataSource");

            try {
                ic.createSubcontext("jdbc");
            } catch (NameAlreadyBoundException ex) {
                logger.info("Subcontext jdbc was already bound");
            }

            ic.bind("jdbc/SourceDB", dataSource);
            logger.info("Bound datasource to jdbc/SourceDB");
        } else {
            logger.info("jdbc/SourceDB is already bound");
        }

        if (!dataSourceBoundDw) {

            Object dataSourcedw = applicationContext.getBean("dataSourcePentahoDW");

            try {
                ic.createSubcontext("jdbc");
            } catch (NameAlreadyBoundException ex) {
                logger.info("Subcontext jdbc was already bound");
            }

            ic.bind("jdbc/DestinationDB", dataSourcedw);
            logger.info("Bound datasource to jdbc/DestinationDB");
        } else {
            logger.info("jdbc/DestinationDB is already bound");
        }
    } catch (Exception ex) {
        logger.error("Unable to bind dataSource to JNDI");
    }
}

From source file:it.cnr.isti.labse.glimpse.impl.ComplexEventProcessorImpl.java

public void init(TopicConnectionFactory connectionFact, InitialContext initConn) {
    try {//w ww  . j a v  a 2  s .co  m
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating connection object ");
        connection = connectionFact.createTopicConnection();
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating public session object ");
        publishSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating subscribe object ");
        subscribeSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up reading topic ");
        connectionTopic = (Topic) initConn.lookup(topic);
        tSub = subscribeSession.createSubscriber(connectionTopic, null, true);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up destination topic ");
        connectionTopic = publishSession.createTopic(this.topic);
        tPub = publishSession.createPublisher(connectionTopic);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Reading knowledge base ");
        kbase = readKnowledgeBase();
        ksession = kbase.newStatefulKnowledgeSession();
        ksession.setGlobal("EVENTS EntryPoint", eventStream);
        eventStream = ksession.getWorkingMemoryEntryPoint("DEFAULT");
        cepRuleManager = new DroolsRulesManager(kbuilder, kbase, ksession);
        DebugMessages.ok();

    } catch (JMSException e) {
        e.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:com.gtwm.pb.servlets.AppController.java

/**
 * init() is called once automatically by the servlet container (e.g.
 * Tomcat) at servlet startup. We use it to initialise various things,
 * namely:/*from  www .  j  ava2 s.  c  om*/
 * 
 * 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("/");

    // Create and cache a DatabaseDefn object which is an entry point to all
    // application logic
    // and schema information. The relational database is also gotten
    DataSource relationalDataSource = null;
    InitialContext initialContext = null;
    try {
        // Get a data source for the relational database to pass to the
        // DatabaseDefn object
        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;
        // Store 'global objects' data sources and webAppRoot in
        // databaseDefn
        this.databaseDefn = new DatabaseDefn(relationalDataSource, this.webAppRoot);
        // Store top level stuff in the context so that other servlets can
        // access it
        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");
}

From source file:eu.learnpad.simulator.mon.impl.ComplexEventProcessorImpl.java

public void init(TopicConnectionFactory connectionFact, InitialContext initConn) {
    try {/*  w ww  . j  a v  a 2 s. c o  m*/
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating connection object ");
        connection = connectionFact.createTopicConnection();
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating public session object ");
        publishSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating subscribe object ");
        subscribeSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up reading topic ");
        connectionTopic = (Topic) initConn.lookup(topic);
        tSub = subscribeSession.createSubscriber(connectionTopic, null, true);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up destination topic ");
        connectionTopic = publishSession.createTopic(this.topic);
        tPub = publishSession.createPublisher(connectionTopic);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Reading knowledge base ");

        knowledgeBase = createKnowledgeBase();
        ksession = knowledgeBase.newStatefulKnowledgeSession();
        ksession.setGlobal("EVENTS EntryPoint", eventStream);
        eventStream = ksession.getWorkingMemoryEntryPoint("DEFAULT");
        cepRuleManager = new DroolsRulesManager(knowledgeBuilder, knowledgeBase, ksession);
        DebugMessages.ok();

    } catch (JMSException e) {
        DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), e.getMessage());
    } catch (NamingException e) {
        DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), e.getMessage());
    }
}

From source file:pingpong.db.DBAccess.java

/**
 * WAS?? ? DataSource  ./* w ww  .j  a  va 2s.  c  o  m*/
 * @throws SQLException 
 */
private void getDS() throws SQLException {
    if (ds != null)
        return;
    try {
        InitialContext ctx = new InitialContext();
        ds = (DataSource) ctx.lookup("java:comp/env/" + getLookup());
        /*
        BasicDataSource ds1 = null;
        if( ds != null ){
        ds1 = (BasicDataSource) ds;
           StringBuffer buf = new StringBuffer();
           buf.append(ds1.getUrl());
           buf.append("GETB:MaxActive:" + ds1.getMaxActive())
              .append("\tMaxIdle:" + ds1.getMaxIdle())
              .append("\tNumActive:" + ds1.getNumActive())
              .append("\tNumIdle:" + ds1.getNumIdle());
           log.debug(buf.toString());
        }
        */
    } catch (Exception e) {
        ds = null;
        if (usedDataSource) {
            //log.error("Naming service exception: " + e.getMessage());
            log.error("get DataSource fail : " + "java:comp/env/" + getLookup());
            //e.printStackTrace();
        }
        ds = setupDataSource();
    }
}

From source file:it.cnr.isti.labsedc.glimpse.impl.ComplexEventProcessorImpl.java

public void init(TopicConnectionFactory connectionFact, InitialContext initConn) {
    try {/*from  ww w  . j a  va  2s.  c o  m*/
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating connection object ");
        connection = connectionFact.createTopicConnection();
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating public session object ");
        publishSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating subscribe object ");
        subscribeSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up reading topic ");
        connectionTopic = (Topic) initConn.lookup(topic);
        tSub = subscribeSession.createSubscriber(connectionTopic, null, true);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up destination topic ");
        connectionTopic = publishSession.createTopic(this.topic);
        tPub = publishSession.createPublisher(connectionTopic);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Reading knowledge base ");
        knowledgeBase = createKnowledgeBase();
        ksession = knowledgeBase.newStatefulKnowledgeSession();
        ksession.setGlobal("EVENTS EntryPoint", eventStream);
        eventStream = ksession.getWorkingMemoryEntryPoint("DEFAULT");
        cepRuleManager = new DroolsRulesManager(knowledgeBuilder, knowledgeBase, ksession);
        DebugMessages.ok();

    } catch (JMSException e) {
        DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), e.getMessage());
    } catch (NamingException e) {
        DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), e.getMessage());
    }
}

From source file:it.cnr.isti.labse.glimpse.manager.GlimpseManager.java

public void setupConnection(TopicConnectionFactory connectionFact, InitialContext initConn) {
    try {/*from  ww w .  j  av a  2  s.  c o m*/
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating connection object ");
        connection = connectionFact.createTopicConnection();
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating public session object ");
        publishSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating subscribe object");
        subscribeSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up destination topic ");
        connectionTopic = (Topic) initConn.lookup(serviceTopic);
        tPub = publishSession.createPublisher(connectionTopic);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up reading topic ");
        tSub = subscribeSession.createSubscriber(connectionTopic, "DESTINATION = 'monitor'", true);
        tSub.setMessageListener(this);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating response dispatcher ");
        responder = new ResponseDispatcher(initConn, connectionFact, requestMap);
        DebugMessages.ok();

    } catch (JMSException e) {
        e.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}