Example usage for javax.naming InitialContext InitialContext

List of usage examples for javax.naming InitialContext InitialContext

Introduction

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

Prototype

public InitialContext() throws NamingException 

Source Link

Document

Constructs an initial context.

Usage

From source file:com.sun.socialsite.business.EmfProvider.java

/**
 * Called once (and only once) to find and initialize our EMF.
 *//*from w w  w.  j a  va 2s .  c  o  m*/
private static EntityManagerFactory initEmf() throws SocialSiteException {

    String jpaConfigurationType = Config.getProperty("jpa.configurationType");
    log.info("jpaConfigurationType=" + jpaConfigurationType);

    if ("jndi".equals(jpaConfigurationType)) {

        String emfJndiName = "java:comp/env/" + Config.getProperty("jpa.emf.jndi.name");
        log.info("emfJndiName=" + emfJndiName);
        try {
            return (EntityManagerFactory) new InitialContext().lookup(emfJndiName);
        } catch (NamingException e) {
            throw new SocialSiteException("Could not look up EntityManagerFactory in jndi at " + emfJndiName,
                    e);
        }

    } else {

        DatabaseProvider dbProvider = Startup.getDatabaseProvider();

        // Pull in any settings defined in our EMF properties file
        Properties emfProps = loadPropertiesFromResourceName(EMF_PROPS, getContextClassLoader());

        // Add all OpenJPA and Toplinks properties found in Config
        for (String key : Config.keySet()) {
            if (key.startsWith("openjpa.") || key.startsWith("toplink.")) {
                String value = Config.getProperty(key);
                log.info(key + ": " + value);
                emfProps.setProperty(key, value);
            }
        }

        if (dbProvider.getType() == DatabaseProvider.ConfigurationType.JNDI_NAME) {

            // We're doing JNDI, so set OpenJPA JNDI name property
            String jndiName = "java:comp/env/" + dbProvider.getJndiName();
            emfProps.setProperty("openjpa.ConnectionFactoryName", jndiName);

        } else {

            // So set JDBC properties for OpenJPA
            emfProps.setProperty("openjpa.ConnectionDriverName", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("openjpa.ConnectionURL", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("openjpa.ConnectionUserName", dbProvider.getJdbcUsername());
            emfProps.setProperty("openjpa.ConnectionPassword", dbProvider.getJdbcPassword());

            // And Toplink JPA
            emfProps.setProperty("eclipselink.jdbc.driver", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("eclipselink.jdbc.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("eclipselink.jdbc.user", dbProvider.getJdbcUsername());
            emfProps.setProperty("eclipselink.jdbc.password", dbProvider.getJdbcPassword());

            // And Toplink JPA
            emfProps.setProperty("toplink.jdbc.driver", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("toplink.jdbc.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("toplink.jdbc.user", dbProvider.getJdbcUsername());
            emfProps.setProperty("toplink.jdbc.password", dbProvider.getJdbcPassword());

            // And Hibernate JPA
            emfProps.setProperty("hibernate.connection.driver_class", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("hibernate.connection.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("hibernate.connection.username", dbProvider.getJdbcUsername());
            emfProps.setProperty("hibernate.connection.password", dbProvider.getJdbcPassword());
        }

        try {
            String puName = Config.getProperty("socialsite.puname", "SocialSite_PU");
            return Persistence.createEntityManagerFactory(puName, emfProps);
        } catch (PersistenceException pe) {
            log.error("Failed to create entity manager", pe);
            throw new SocialSiteException(pe);
        }

    }

}

From source file:com.wegas.core.Helper.java

/**
 * @param <T>/*from w ww . j  ava2  s.c o  m*/
 * @param type
 * @param service
 * @return looked-up EJB instance
 * @throws NamingException
 */
public static <T> T lookupBy(Class<T> type, Class<?> service) throws NamingException {
    return lookupBy(new InitialContext(), type, service);
}

From source file:org.hawkular.apm.server.jms.AbstractPublisherJMS.java

@PostConstruct
public void init() {
    try {//  w  ww  . j  a  v a  2  s .com
        InitialContext context = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("java:/APMJMSCF");
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // TODO: Transacted?
        Destination destination = (Destination) context.lookup(getDestinationURI());
        producer = session.createProducer(destination);
        connection.start();
    } catch (Exception e) {
        msgLog.errorFailedToInitPublisher(getDestinationURI(), e);
    }
}

From source file:Controllers.myAppointmentController.java

public Appointment[] fetchAppointments(java.sql.Date date) {

    Appointment[] Appoint = null;//  w w  w  .j  av a2 s  .  c o m

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource");
        connection = ds.getConnection();

        PreparedStatement pstmt = connection
                .prepareStatement("SELECT appointments.message," + "FROM appointments JOIN accounts\n"
                        + "WHERE appointments.date = ? and email=${sessionScope.user};");

        pstmt.setDate(1, date);

        ResultSet resultSet = pstmt.executeQuery();

        List<Appointment> appointmentsList = new ArrayList<Appointment>();
        while (resultSet.next()) {
            Appointment appoint = new Appointment();
            appoint.setAppointmentId(resultSet.getInt("appointmentId"));
            appoint.setMessage(resultSet.getString("message"));
            appoint.setDepartmentId(resultSet.getInt("depoartmentId"));

            appointmentsList.add(appoint);
        }

        Appoint = new Appointment[appointmentsList.size()];
        Appoint = appointmentsList.toArray(Appoint);

        pstmt.close();

    } catch (NamingException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return Appoint;
}

From source file:com.wso2telco.core.dbutils.DbUtils.java

/**
 * Gets the db connection.//  w w w.j a va2s .  c  om
 *
 * @return the db connection
 * @throws SQLException
 *             the SQL exception
 */
public static synchronized Connection getDbConnection(DataSourceNames dataSourceName) throws Exception {

    try {
        if (!dbDataSourceMap.containsKey(dataSourceName)) {

            Context ctx = new InitialContext();
            dbDataSourceMap.put(dataSourceName, (DataSource) ctx.lookup(dataSourceName.jndiName()));
        }

        DataSource dbDatasource = dbDataSourceMap.get(dataSourceName);

        if (dbDatasource != null) {

            log.info(dataSourceName.toString() + " DB Initialize successfully.");
            return dbDatasource.getConnection();
        } else {

            log.info(dataSourceName.toString() + " DB NOT Initialize successfully.");
            return null;
        }
    } catch (Exception e) {

        log.info("Error while looking up the data source: " + dataSourceName.toString(), e);
        throw e;
    }
}

From source file:io.apiman.servers.gateway_h2.Starter.java

/**
 * Creates a datasource and binds it to JNDI.
 *//*from   w  w w .  j a  va  2s .c o m*/
private static void createDataSource() {
    HikariConfig config = new HikariConfig("src/main/resources/hikari.properties");
    HikariDataSource ds = new HikariDataSource(config);

    //        Connection connection = null;
    //        try {
    //            connection = ds.getConnection();
    //            connection.setAutoCommit(true);
    //            
    //            PreparedStatement statement = connection.prepareStatement("SELECT * FROM information_schema.tables WHERE table_name = 'APIS'");
    //            ResultSet rs = statement.executeQuery();
    //            if (!rs.next()) {
    //                initDB(connection);
    //            }
    //            
    //            connection.close();
    //        } catch (Exception e1) {
    //            if (connection != null) {
    //                try { connection.close(); } catch (Exception e) {}
    //            }
    //            ds.close();
    //            throw new RuntimeException(e1);
    //        }

    try {
        InitialContext ctx = new InitialContext();
        ensureCtx(ctx, "java:/comp/env");
        ensureCtx(ctx, "java:/comp/env/jdbc");
        ctx.bind("java:/comp/env/jdbc/ApiGatewayDS", ds);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.chrisrichardson.foodToGo.ejb3.facadeWithSpringDI.PlaceOrderFacadeUsingIntegratedDependencyInjectImpl.java

private void lookForEM() {
    try {//from   w  ww .j av  a  2s.  co m
        InitialContext initialContext = new InitialContext();
        String root = "java:comp.ejb3";
        logger.debug("Starting listing");
        listContext(initialContext, root);
        logger.debug("End listing");
        EntityManager em = (EntityManager) initialContext.lookup("java:comp.ejb3/env/ejb/EntityManager");
        logger.debug("Got entity manager2");
    } catch (NamingException e) {
        logger.error(e);
    }
}

From source file:com.dattack.naming.StandaloneJndiTest.java

@Test
public void testCreateMultiContext() {
    try {/*  w ww .  j ava 2 s .c om*/
        final InitialContext context = new InitialContext();
        final String name = getCompositeName(VALID_CONTEXT, "testCreateMultiContext");
        final Context subcontext = context.createSubcontext(name);
        assertNotNull(subcontext);
    } catch (final NamingException e) {
        fail(e.getMessage());
    }
}

From source file:minor.eft.ETFQuote.java

private ETFDetailsFacadeLocal lookupETFDetailsFacadeLocal() {
    try {/*from   w ww  .  j  ava2 s. c  om*/
        Context c = new InitialContext();
        return (ETFDetailsFacadeLocal) c
                .lookup("java:global/MinorTest/ETFDetailsFacade!minor.session.ETFDetailsFacadeLocal");
    } catch (NamingException ne) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
        throw new RuntimeException(ne);
    }
}

From source file:edu.byu.wso2.apim.extensions.CheckActorPermissions.java

public void init(SynapseEnvironment synapseEnvironment) {
    if (log.isInfoEnabled()) {
        log.info("Initializing CheckActorPermissions Mediator");
    }//from w ww.  ja v a 2  s.  c  o  m
    if (log.isDebugEnabled())
        log.debug("CheckActorPermissions: looking up Person/GRO datasource" + PRODsName);
    try {
        this.proDs = (DataSource) new InitialContext().lookup(PRODsName);
    } catch (NamingException e) {
        e.printStackTrace();
    }
    if (log.isDebugEnabled())
        log.debug("CheckActorPermissions: acquired datasource");

}