Example usage for javax.naming Context lookup

List of usage examples for javax.naming Context lookup

Introduction

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

Prototype

public Object lookup(String name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:com.netspective.axiom.connection.JndiConnectionProvider.java

public DataSource getDataSource(ValueContext vc, String dataSourceId) throws NamingException, SQLException {
    if (dataSourceId == null)
        throw new NamingException(
                "dataSourceId is NULL in " + this.getClass().getName() + ".getConnection(String)");

    Context env = getRootContext();
    return (DataSource) env.lookup(dataSourceId);
}

From source file:com.duroty.lucene.parser.ParserFactory.java

/**
 * Creates a new instance of ParserFactory
 *//*from w  w  w.j  a v  a  2 s.  c  om*/
public ParserFactory() {
    Map options = ApplicationConstants.options;

    try {
        Context ctx = new InitialContext();

        this.parseFactoryConfig = (HashMap) ctx.lookup((String) options.get(Constants.PARSE_FACTORY_CONFIG));
    } catch (Exception e) {
        this.parseFactoryConfig = new HashMap();
    }
}

From source file:org.alinous.plugin.postgres.PostgreSQLConnectionFactory.java

public PostgreSQLConnectionFactory(AlinousCore core, Driver driver, String user, String pass, String uri,
        int maxclients, boolean resultUpper) throws Exception {
    this.core = core;

    this.uri = uri;
    this.user = user;
    this.pass = pass;

    this.maxclients = maxclients;
    this.resultUpper = resultUpper;

    if (uri.startsWith("java:")) {
        Context initialContext = new InitialContext();
        this.dataSource = (DataSource) initialContext.lookup(uri);
    } else {/*from   w  w w  .j a v a 2  s .  c o  m*/
        this.driver = driver;
    }
}

From source file:opa.DatabaseResourceBundle.java

/**
 * Return a database connection. null if one cannot be achieved.
 * //from  w ww. j  a  va  2s .c o  m
 * @return
 */
private Connection createConnection() {
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + jndiJdbc);
        return ds.getConnection();
    } catch (NamingException e) {
        log.error("java:comp/env/" + jndiJdbc + " not found!", e);
    } catch (SQLException e) {
        log.error(e, e);
    }

    return null;
}

From source file:org.gss_project.gss.server.admin.AdminServiceImpl.java

/**
 * A helper method that retrieves a reference to the AdminAPI bean and
 * stores it for future use./*w  w  w.j ava  2 s  . c  om*/
 *
 * @return an AdminAPI instance
 * @throws RpcException in case an error occurs
 */
protected AdminAPI getService() throws RpcException {
    try {
        final Context ctx = new InitialContext();
        final Object ref = ctx.lookup(getConfiguration().getString("adminApiPath"));
        return (AdminAPI) PortableRemoteObject.narrow(ref, AdminAPI.class);
    } catch (final NamingException e) {
        logger.error("Unable to retrieve the AdminAPI EJB", e);
        throw new RpcException("An error occurred while contacting the naming service");
    }
}

From source file:com.jaspersoft.jasperserver.remote.dbservices.impl.JndiConnectionServiceImpl.java

/**
 *
 * @param resource/*from w ww.j  ava  2s  .co  m*/
 * @return Connection object, guaranteed to be non-null (not found or not supported resource indicated by exception)
 * @throws ResourceNotFoundException if no resource found 
 * @throws RemoteException in case of unclassified error
 */
@SuppressWarnings("unused")
public Connection getConnection(Resource resource) {
    Connection result = null;
    String DATASOURCE_CONTEXT = null;
    long startTime = System.currentTimeMillis();
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Enter getConnection .. Start Time" + System.currentTimeMillis());
        }
        if (resource instanceof JndiJdbcReportDataSource) {
            JndiJdbcReportDataSource jndiDataSource = (JndiJdbcReportDataSource) resource;
            DATASOURCE_CONTEXT = "java:comp/env/" + jndiDataSource.getJndiName();
            Context initialContext = new InitialContext();
            if (initialContext != null) {
                DataSource datasource = (DataSource) initialContext.lookup(DATASOURCE_CONTEXT);
                if (datasource != null) {
                    result = datasource.getConnection();
                } else {
                    throw new RemoteException("Cannot get database connection: Please check datasource url");
                }
            } else {
                throw new RemoteException("Cannot get jndi context: Please check datasource url");
            }

        } else {
            throw new RemoteException("Invalid Resource: Please check datasource url");
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new RemoteException("Cannot get jndi connection:" + ex.getMessage());
    } finally {
        if (logger.isDebugEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.debug("Exit getConnection .. Total Time Spent: " + elapsedTime);
        }
    }
    return result;

}

From source file:org.easybatch.jms.JmsIntegrationTest.java

@Test
public void testJmsRecordWriter() throws Exception {
    Context jndiContext = getJndiContext();
    Queue queue = (Queue) jndiContext.lookup("q");
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
            .lookup("QueueConnectionFactory");
    QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
    QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    queueConnection.start();/*from ww  w.ja v  a2 s.  com*/

    String dataSource = "foo" + LINE_SEPARATOR + "bar";

    aNewJob().reader(new StringRecordReader(dataSource)).processor(new JmsMessageTransformer(queueSession))
            .writer(new JmsQueueRecordWriter(queueConnectionFactory, queue)).call();

    // Assert that queue contains 2 messages: "foo" and "bar"
    QueueBrowser queueBrowser = queueSession.createBrowser(queue);
    Enumeration enumeration = queueBrowser.getEnumeration();

    assertThat(enumeration.hasMoreElements()).isTrue();
    TextMessage message1 = (TextMessage) enumeration.nextElement();
    assertThat(message1.getText()).isEqualTo("foo");

    assertThat(enumeration.hasMoreElements()).isTrue();
    TextMessage message2 = (TextMessage) enumeration.nextElement();
    assertThat(message2.getText()).isEqualTo("bar");

    assertThat(enumeration.hasMoreElements()).isFalse();

    queueSession.close();
    queueConnection.close();
}

From source file:org.apache.roller.weblogger.business.MailProvider.java

public MailProvider() throws StartupException {

    String connectionTypeString = WebloggerConfig.getProperty("mail.configurationType");
    if ("properties".equals(connectionTypeString)) {
        type = ConfigurationType.MAIL_PROPERTIES;
    }/*  ww  w.j a  v  a2  s . c  o  m*/
    jndiName = WebloggerConfig.getProperty("mail.jndi.name");
    mailHostname = WebloggerConfig.getProperty("mail.hostname");
    mailUsername = WebloggerConfig.getProperty("mail.username");
    mailPassword = WebloggerConfig.getProperty("mail.password");
    try {
        String portString = WebloggerConfig.getProperty("mail.port");
        if (portString != null) {
            mailPort = Integer.parseInt(portString);
        }
    } catch (Throwable t) {
        log.warn("mail server port not a valid integer, ignoring");
    }

    // init and connect now so we fail early
    if (type == ConfigurationType.JNDI_NAME) {
        String name = "java:comp/env/" + jndiName;
        try {
            Context ctx = (Context) new InitialContext();
            session = (Session) ctx.lookup(name);
        } catch (NamingException ex) {
            throw new StartupException("ERROR looking up mail-session with JNDI name: " + name);
        }
    } else {
        Properties props = new Properties();
        props.put("mail.smtp.host", mailHostname);
        if (mailUsername != null && mailPassword != null) {
            props.put("mail.smtp.auth", "true");
        }
        if (mailPort != -1) {
            props.put("mail.smtp.port", "" + mailPort);
        }
        session = Session.getDefaultInstance(props, null);
    }

    try {
        Transport transport = getTransport();
        transport.close();
    } catch (Throwable t) {
        throw new StartupException("ERROR connecting to mail server", t);
    }

}

From source file:org.jbpm.bpel.tutorial.invoice.ComputePricePT_Impl.java

protected void initJmsObjects() throws NamingException, JMSException {
    Context initialContext = new InitialContext();
    try {/*ww  w.  j  a v  a 2s  .  c o  m*/
        Context environmentContext = (Context) initialContext.lookup("java:comp/env");
        invoiceDestination = (Destination) environmentContext.lookup(INVOICE_DESTINATION_NAME);
        log.debug("Retrieved destination: " + INVOICE_DESTINATION_NAME);

        ConnectionFactory jmsConnectionFactory = (ConnectionFactory) environmentContext
                .lookup(CONNECTION_FACTORY_NAME);
        jmsConnection = jmsConnectionFactory.createConnection();
        log.debug("Created JMS connection: factory=" + CONNECTION_FACTORY_NAME);
    } finally {
        initialContext.close();
    }
}

From source file:eu.europa.ec.fisheries.uvms.plugins.ais.service.AisService.java

@PostConstruct
public void init() {
    try {//from w w  w . j  a v a 2 s . c  o m
        Context ctx = new InitialContext();
        AISConnectionFactoryImpl factory = (AISConnectionFactoryImpl) ctx
                .lookup("java:/eis/AISConnectionFactory");
        if (factory != null) {
            LOG.debug("Factory lookup done! {}, {}", factory.toString(), factory.getClass());
            connection = factory.getConnection();

            if (startUp.isEnabled() && connection != null && !connection.isOpen()) {
                String host = startUp.getSetting("HOST");
                int port = Integer.parseInt(startUp.getSetting("PORT"));
                String username = startUp.getSetting("USERNAME");
                String password = startUp.getSetting("PASSWORD");

                connection.open(host, port, username, password);
            }
        }
    } catch (NamingException | ResourceException e) {
        LOG.error("Exception: {}", e);
    }
}