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:org.globus.examples.services.filebuy.seller.impl.FilesForSaleFactoryService.java

protected ResourceHome getInstanceResourceHome() throws NoResourceHomeException, ResourceContextException {
    ResourceHome home;/*w w w . j a  v a  2 s  .c  om*/
    ResourceContext ctx;
    FilesForSaleConfiguration config;

    // The path for the instance service is contained in the configuration object
    try {
        config = FilesForSaleConfiguration.getConfObject();
    } catch (Exception e) {
        throw new NoResourceHomeException(
                "Unable to access configuration object to retrieve instance service path.");
    }
    String instanceService = config.getInstanceServicePath();

    // Lookup resource home
    String homeLoc = Constants.JNDI_SERVICES_BASE_NAME + instanceService + "/home";
    try {
        Context initialContext = new InitialContext();
        home = (ResourceHome) initialContext.lookup(homeLoc);
    } catch (NameNotFoundException e) {
        throw new NoResourceHomeException();
    } catch (NamingException e) {
        throw new ResourceContextException("", e);
    }

    return home;
}

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

/**
 * Initialize implementation with configuration.
 * //from  w  ww . j a  v  a2s  .  c  om
 * @param configuration
 *            configuration properties
 * @param initializeStore
 *            truncate and initialize persistent store
 */
public static void initialize(Configuration configuration, boolean initializeStore) {
    try {
        // configuration
        cacheSize = configuration.getString(PERSISTENCE_MANAGER_CACHE_SIZE_PROPERTY_NAME);
        dbType = configuration.getString(PERSISTENCE_MANAGER_DB_TYPE_PROPERTY_NAME);
        dictionaryType = ((dbType != null) ? DB_TYPE_TO_JPA_DICTIONARY_MAP.get(dbType) : null);
        if ((dbType != null) && (dictionaryType == null)) {
            throw new IllegalArgumentException("Unsupported database type: " + dbType);
        }

        // initialize persistent store
        if (initializeStore && (dbType != null)) {
            // get datasource connection
            Context initialContext = new InitialContext();
            DataSource dataSource = (DataSource) initialContext
                    .lookup(WIDGET_DATABASE_JNDI_DATASOURCE_FULL_NAME);
            Connection connection = dataSource.getConnection();
            connection.setAutoCommit(true);

            // execute initialization scripts
            String sqlScriptResource = dbType + "-wookie-schema.sql";
            InputStream sqlStream = JPAPersistenceManager.class.getResourceAsStream(sqlScriptResource);
            if (sqlStream == null) {
                throw new IllegalArgumentException(
                        "Unsupported persistent store initialization script: " + sqlScriptResource);
            }
            SQLScriptReader reader = new SQLScriptReader(sqlStream);
            int statementCount = 0;
            int statementErrorCount = 0;
            for (;;) {
                String scriptStatement = reader.readSQLStatement();
                if (scriptStatement != null) {
                    Statement statement = connection.createStatement();
                    statementCount++;
                    try {
                        statement.execute(scriptStatement);
                    } catch (SQLException sqle) {
                        statementErrorCount++;
                    }
                } else {
                    break;
                }
            }
            logger.info("Persistent store initialized from " + sqlScriptResource + ", (" + statementCount
                    + " statements, " + statementErrorCount + " errors)");

            // close datasource connection
            connection.close();
        }

        // initialize entity manager factory
        Properties persistenceProperties = new Properties();
        InputStream propertiesStream = JPAPersistenceManager.class
                .getResourceAsStream("persistence.properties");
        if (propertiesStream == null) {
            throw new IllegalArgumentException("Unable to load configuration: persistence.properties");
        }
        persistenceProperties.load(propertiesStream);
        if (cacheSize != null) {
            int dataCacheSize = Integer.parseInt(cacheSize);
            persistenceProperties.setProperty("openjpa.DataCache",
                    "true(CacheSize=" + dataCacheSize + ",SoftReferenceSize=0)");
            int queryCacheSize = Integer.parseInt(cacheSize) / 10;
            persistenceProperties.setProperty("openjpa.QueryCache",
                    "CacheSize=" + queryCacheSize + ",SoftReferenceSize=0");
        }
        if (dictionaryType != null) {
            persistenceProperties.setProperty("openjpa.jdbc.DBDictionary", dictionaryType);
        }
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("wookie", persistenceProperties);
        entityManagerFactory = OpenJPAPersistence.cast(factory);

        logger.info("Initialized");
    } catch (Exception e) {
        throw new RuntimeException("Unable to initialize 1: " + e, e);
    }
}

From source file:org.apache.juddi.v3.auth.jboss.JBossAuthenticator.java

private void init() throws NamingException, ConfigurationException {
    String securityDomain = AppConfig.getConfiguration().getString(Property.JUDDI_SECURITY_DOMAIN,
            Property.DEFAULT_SECURITY_DOMAIN);

    // lookup the authentication manager.
    Context ctx = new InitialContext();
    authManager = (AuthenticationManager) ctx.lookup(securityDomain);
    ctx.close();//from w w w .ja  va  2 s. co  m
}

From source file:Controllers.myAppointmentController.java

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

    Appointment[] Appoint = null;//from   ww  w  . ja v  a  2  s . c  om

    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.sktelecom.cep.notebook.repo.JDBCNotebookRepo.java

public JDBCNotebookRepo(ZeppelinConfiguration conf) throws IOException, NamingException {
    this.conf = conf;

    Context ctx = new InitialContext();
    dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/cepDS");
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

From source file:it.infn.ct.futuregateway.apiserver.APIContextListener.java

@Override
public final void contextInitialized(final ServletContextEvent sce) {
    log.info("Creation of the Hibernate SessionFactory for the context");
    try {//from  w ww  .  j a  v a2  s  . co  m
        entityManagerFactory = Persistence
                .createEntityManagerFactory("it.infn.ct.futuregateway.apiserver.container");
    } catch (Exception ex) {
        log.warn("Resource 'jdbc/FutureGatewayDB' not accessuible or"
                + " not properly configured for the application. An"
                + " alternative resource is created on the fly.");
        entityManagerFactory = Persistence.createEntityManagerFactory("it.infn.ct.futuregateway.apiserver.app");
    }
    sce.getServletContext().setAttribute(Constants.SESSIONFACTORY, entityManagerFactory);
    String path = sce.getServletContext().getInitParameter("CacheDir");
    if (path == null || path.isEmpty()) {
        path = sce.getServletContext().getRealPath("/") + ".." + FileSystems.getDefault().getSeparator() + ".."
                + FileSystems.getDefault().getSeparator() + "FutureGatewayData";
    }
    log.info("Created the cache directory: " + path);
    sce.getServletContext().setAttribute(Constants.CACHEDIR, path);
    try {
        Files.createDirectories(Paths.get(path));
        log.info("Cache dir enabled");
    } catch (FileAlreadyExistsException faee) {
        log.debug("Message for '" + path + "':" + faee.getMessage());
        log.info("Cache dir enabled");
    } catch (Exception e) {
        log.error("Impossible to initialise the temporary store");
    }
    ExecutorService tpe;
    try {
        Context ctx = new InitialContext();
        tpe = (ExecutorService) ctx.lookup("java:comp/env/threads/Submitter");
    } catch (NamingException ex) {
        log.warn("Submitter thread not defined in the container. A thread "
                + "pool is created using provided configuration parameters " + "and defaults values");
        int threadPoolSize = Constants.DEFAULTTHREADPOOLSIZE;
        try {
            threadPoolSize = Integer
                    .parseInt(sce.getServletContext().getInitParameter("SubmissioneThreadPoolSize"));
        } catch (NumberFormatException nfe) {
            log.info("Parameter 'SubmissioneThreadPoolSize' has a wrong"
                    + " value or it is not present. Default value " + "10 is used");
        }
        tpe = ThreadPoolFactory.getThreadPool(threadPoolSize, Constants.MAXTHREADPOOLSIZETIMES * threadPoolSize,
                Constants.MAXTHREADIDLELIFE);
    }
    sce.getServletContext().setAttribute(Constants.SUBMISSIONPOOL, tpe);
}

From source file:org.accada.epcis.repository.query.QueryInitServlet.java

/**
 * Loads the data source from the application context via JNDI.
 * /*from   w w w .ja v a 2 s.c  om*/
 * @param jndiName
 *            The name of the JNDI data source holding the connection to the
 *            database.
 * @return The application DataSource instance.
 */
private DataSource loadDataSource(String jndiName) {
    DataSource dataSource = null;
    try {
        Context ctx = new InitialContext();
        dataSource = (DataSource) ctx.lookup(jndiName);
        LOG.info("Loaded data source via JNDI from " + jndiName);
    } catch (NamingException e) {
        LOG.error("Unable to load data source via JNDI from " + jndiName, e);
    }
    return dataSource;
}

From source file:org.spring.data.gemfire.app.dao.provider.DatabaseGemstoneDao.java

@PostConstruct
public void init() {
    try {/*  w  w  w.ja v  a  2  s  .  c  o  m*/
        Context jndiContext = getCache().getJNDIContext();
        Object dataSourceObject = jndiContext.lookup(GEMFIREDB_JNDI_LOCATION);

        Assert.isTrue(dataSourceObject instanceof DataSource,
                String.format("Expected a javax.sql.DataSource object; but was %1$s%n",
                        ObjectUtils.nullSafeClassName(dataSourceObject)));

        databaseTemplate = new JdbcTemplate((DataSource) dataSourceObject);

        System.out.printf("%1$s initialized!%n", getClass().getSimpleName());
    } catch (NamingException e) {
        throw new InitializationException(
                String.format("Failed to initialize %1$s!", getClass().getSimpleName()), e);
    }
}

From source file:com.mycompany.FacebookManager.java

public FacebookManager() {
    byteStream = new ByteArrayOutputStream();

    try {/*from  www. java  2 s  . c  om*/
        javax.naming.Context con = new InitialContext();
        facade = (EmpeopleFacadeRemote) con.lookup("com.mycompany.EmpeopleFacadeRemote");
        faceManager = (FaceManagerRemote) con.lookup("com.mycompany.FaceManagerRemote");
    } catch (NamingException ex) {
        Logger.getLogger(FacebookManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.peopleList = facade.findAll();
}

From source file:com.commoncoupon.mail.EmailProcessor.java

/**
 * Retrieves a Mail session from Tomcat's Resource Factory (JNDI)
 *//* ww  w .ja v a  2 s .  c  o m*/
protected Session getSession() {
    Session session = null;
    try {
        Context envCtx = (Context) (new InitialContext()).lookup("java:comp/env/");
        session = (Session) envCtx.lookup("mail/Session");
        /*If you get exception here remove activation.jar and mail.jar from web-inf lib
        *It should be present in only tomcat/lib
        */
        log.info("Returning session");
    } catch (NamingException ex) {
        log.error("cannot locate resource named 'mail/Session'.", ex);
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        // Get the Session object.
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("search2let@gmail.com", "Tol3t@dm!n321");
            }
        });
    }
    return session;
}