List of usage examples for javax.naming InitialContext InitialContext
public InitialContext() throws NamingException
From source file:it.infn.ct.security.actions.PassRecovery.java
private void sendMail(String code) throws MailException { javax.mail.Session session = null;//from w ww . j a v a2s . c o m try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (javax.mail.Session) envCtx.lookup("mail/Users"); } catch (Exception ex) { _log.error("Mail resource lookup error"); _log.error(ex.getMessage()); throw new MailException("Mail Resource not available"); } Message mailMsg = new MimeMessage(session); try { String title = user.getTitle() == null ? "" : user.getTitle(); mailMsg.setFrom(new InternetAddress(mailFrom)); InternetAddress mailTo[] = new InternetAddress[1]; mailTo[0] = new InternetAddress(user.getPreferredMail(), title + user.getGivenname() + " " + user.getSurname()); mailMsg.setRecipients(Message.RecipientType.TO, mailTo); mailMsg.setSubject(mailSubject); mailBody = mailBody.replaceAll("_USER_", title + " " + user.getGivenname() + " " + user.getSurname()); mailBody = mailBody.replaceAll("_CODE_", code); mailMsg.setText(mailBody); Transport.send(mailMsg); } catch (UnsupportedEncodingException ex) { _log.error(ex); throw new MailException("Mail from address format not valid"); } catch (MessagingException ex) { _log.error(ex); throw new MailException("Mail message has problems"); } }
From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java
public DBStore(BaseConnector connector) { Connection connection = null; logger = Logger.getLogger(this.getClass().getPackage().getName()); logger.log(Level.INFO, "Initialize DBStore "); this.connector = connector; //each connector instance has its own table in the same database this.instance_table = "i_" + connector.getInstanceName(); Statement Stmt = null;/*from w ww .j av a 2 s . c o m*/ ResultSet RS = null; DatabaseMetaData dbm = null; boolean table_exists = false; try { //check if the datasource/database exists Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); ds = (DataSource) envCtx.lookup(BaseConstants.CONNECTOR_DATASOURCE); connection = ds.getConnection(); connection.setAutoCommit(true); dbm = connection.getMetaData(); logger.log(Level.INFO, "Connected to databaseType " + dbm.getDatabaseProductName()); } catch (Exception ex) { logger.log(Level.SEVERE, "Exception initializing Store Datasource " + ex); connection = null; return; } try { if (dbm.getDatabaseProductName().equals("MySQL")) { //check if the per-connector table exists logger.log(Level.FINE, "Checking to see if connector DB exists..."); Stmt = connection.createStatement(); RS = Stmt.executeQuery("desc " + instance_table); ResultSetMetaData rsMetaData = RS.getMetaData(); if (rsMetaData.getColumnCount() > 0) table_exists = true; RS.close(); Stmt.close(); } else { logger.log(Level.SEVERE, "Unsupported DATABASE TYPE..." + dbm.getDatabaseProductName()); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception initializing Store " + ex); } try { //if the per-instance table doesn't exist, create it if (!table_exists) { logger.log(Level.INFO, "Creating Instance Table " + instance_table); if (dbm.getDatabaseProductName().equals("MySQL")) { Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String create_stmt = ""; create_stmt = "CREATE TABLE `" + this.instance_table + "` (" + "`crawl_set` decimal(19,5) NOT NULL," + "`insert_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP," + "`crawl_data` MEDIUMTEXT default NULL," + "PRIMARY KEY (`crawl_set`)," + "KEY `set_index` (`crawl_set`)" + ") ENGINE=MyISAM;"; statement.addBatch(create_stmt); statement.executeBatch(); statement.close(); } else { logger.log(Level.INFO, "Instance Table " + instance_table + " already exists"); //connection.close(); //TODO: somehow figure out if we should delete this table here } } boolean qrtz_table_exists = false; if (dbm.getDatabaseProductName().equals("MySQL")) { //check if the per-connector table exists logger.log(Level.FINE, "Checking to see if quartz tables exists..."); Stmt = connection.createStatement(); try { RS = Stmt.executeQuery("desc QRTZ_JOB_DETAILS"); ResultSetMetaData rsMetaData = RS.getMetaData(); if (rsMetaData.getColumnCount() > 0) qrtz_table_exists = true; } catch (Exception ex) { logger.log(Level.INFO, "Could not find Quartz Tables...creating now.."); } RS.close(); Stmt.close(); } else { logger.log(Level.SEVERE, "Unsupported DATABASE TYPE..." + dbm.getDatabaseProductName()); } if (!qrtz_table_exists) { logger.log(Level.INFO, "Creating Global Quartz Table "); //the quartz db setup scripts are at //quartz-1.8.0/docs/dbTables/tables_mysql.sql //one set of Quartz tables can handle any number of triggers/crons Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String create_stmt = "CREATE TABLE QRTZ_JOB_DETAILS (JOB_NAME VARCHAR(200) NOT NULL,JOB_GROUP VARCHAR(200) NOT NULL,DESCRIPTION VARCHAR(250) NULL,JOB_CLASS_NAME VARCHAR(250) NOT NULL,IS_DURABLE VARCHAR(1) NOT NULL,IS_VOLATILE VARCHAR(1) NOT NULL,IS_STATEFUL VARCHAR(1) NOT NULL,REQUESTS_RECOVERY VARCHAR(1) NOT NULL,JOB_DATA BLOB NULL,PRIMARY KEY (JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_JOB_LISTENERS ( JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, JOB_LISTENER VARCHAR(200) NOT NULL, PRIMARY KEY (JOB_NAME,JOB_GROUP,JOB_LISTENER), FOREIGN KEY (JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_FIRED_TRIGGERS ( ENTRY_ID VARCHAR(95) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, IS_VOLATILE VARCHAR(1) NOT NULL, INSTANCE_NAME VARCHAR(200) NOT NULL, FIRED_TIME BIGINT(13) NOT NULL, PRIORITY INTEGER NOT NULL, STATE VARCHAR(16) NOT NULL, JOB_NAME VARCHAR(200) NULL, JOB_GROUP VARCHAR(200) NULL, IS_STATEFUL VARCHAR(1) NULL, REQUESTS_RECOVERY VARCHAR(1) NULL, PRIMARY KEY (ENTRY_ID));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, IS_VOLATILE VARCHAR(1) NOT NULL, DESCRIPTION VARCHAR(250) NULL, NEXT_FIRE_TIME BIGINT(13) NULL, PREV_FIRE_TIME BIGINT(13) NULL, PRIORITY INTEGER NULL, TRIGGER_STATE VARCHAR(16) NOT NULL, TRIGGER_TYPE VARCHAR(8) NOT NULL, START_TIME BIGINT(13) NOT NULL, END_TIME BIGINT(13) NULL, CALENDAR_NAME VARCHAR(200) NULL, MISFIRE_INSTR SMALLINT(2) NULL, JOB_DATA BLOB NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_SIMPLE_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, REPEAT_COUNT BIGINT(7) NOT NULL, REPEAT_INTERVAL BIGINT(12) NOT NULL, TIMES_TRIGGERED BIGINT(10) NOT NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_CRON_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, CRON_EXPRESSION VARCHAR(200) NOT NULL, TIME_ZONE_ID VARCHAR(80), PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_BLOB_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, BLOB_DATA BLOB NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_TRIGGER_LISTENERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, TRIGGER_LISTENER VARCHAR(200) NOT NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_LISTENER), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_CALENDARS ( CALENDAR_NAME VARCHAR(200) NOT NULL, CALENDAR BLOB NOT NULL, PRIMARY KEY (CALENDAR_NAME));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS ( TRIGGER_GROUP VARCHAR(200) NOT NULL, PRIMARY KEY (TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_SCHEDULER_STATE ( INSTANCE_NAME VARCHAR(200) NOT NULL, LAST_CHECKIN_TIME BIGINT(13) NOT NULL, CHECKIN_INTERVAL BIGINT(13) NOT NULL, PRIMARY KEY (INSTANCE_NAME));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_LOCKS ( LOCK_NAME VARCHAR(40) NOT NULL, PRIMARY KEY (LOCK_NAME));"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('TRIGGER_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('JOB_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('CALENDAR_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('STATE_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('MISFIRE_ACCESS');"; statement.addBatch(create_stmt); statement.executeBatch(); statement.close(); } else { logger.log(Level.INFO, "Global Quartz Table already exists "); } connection.close(); } catch (Exception ex) { logger.log(Level.SEVERE, "Exception Creating StoreTable " + ex); } }
From source file:com.jaspersoft.jasperserver.api.engine.common.virtualdatasourcequery.teiid.TeiidEmbeddedServer.java
public TeiidEmbeddedServer(EmbeddedConfiguration config, MemoryConfig memoryConfig, ServerConfig serverConfig, TransactionManagerConfiguration transactionManagerConfiguration) { // allow user to plugin their own customizable for teiid embedded server if ((serverConfig != null) && (serverConfig.getServerInit() != null)) serverConfig.getServerInit().init(this); // transaction manager is required for derived table if (config.getTransactionManager() == null) { boolean useMockTranscationManager = true; String transactionManagerLookup = null; if (serverConfig != null) transactionManagerLookup = serverConfig.getTransactionManagerJNDILookup(); if ((transactionManagerLookup != null) && (!transactionManagerLookup.trim().equals(""))) { try { InitialContext ic = new InitialContext(); Object utm = ic.lookup(transactionManagerLookup); if ((utm != null) && (utm instanceof TransactionManager)) { log.debug("Teiid Embedded Server: set transaction manager = " + transactionManagerLookup); config.setTransactionManager((TransactionManager) utm); useMockTranscationManager = false; }/*from w w w .j a va2s . c o m*/ } catch (Exception ex) { log.debug( "Teiid Embedded Server: fail to set transaction manager = " + transactionManagerLookup, ex); } } if (useMockTranscationManager) { log.debug("Teiid Embedded Server: use simple transaction manager"); try { config.setTransactionManager(createTransactionManager(transactionManagerConfiguration)); } catch (Exception ex) { log.debug("Fail to initialize transaction manager for teiid engine", ex); } } if ((serverConfig != null) && (serverConfig.getXaTerminator() != null)) { setXaTerminator(serverConfig.getXaTerminator()); } } this.repo.odbcEnabled(); this.memoryConfig = memoryConfig; start(config); }
From source file:com.techm.cadt.pizzahut.db.PizzaDAO.java
private Connection getConnection() throws Exception { if (ds == null) { Context initCtx = new InitialContext(); //Context envCtx = (Context) initCtx.lookup("java:comp/env"); ds = (DataSource) initCtx.lookup("java:jboss/datasources/pizzahutDS"); }/* w ww. j a v a2 s .c om*/ return ds.getConnection(); }
From source file:com.caricah.iotracah.datastore.ignitecache.internal.AbstractHandler.java
public void initiate(Class<T> t, Ignite ignite) { try {/* w w w . ja va 2 s . c o m*/ Context ic = new InitialContext(); DataSource dataSource; if (isPersistanceEnabled()) dataSource = (DataSource) ic.lookup("jdbc_commonpool"); else dataSource = null; CacheConfiguration<K, T> clCfg = getCacheConfiguration(isPersistanceEnabled(), dataSource); clCfg = extraCacheSettingsConfigure(clCfg); ignite.createCache(clCfg); IgniteCache<K, T> clientIgniteCache = ignite.cache(getCacheName()); clientIgniteCache.loadCache(null); setDatastoreCache(clientIgniteCache); classType = t; String nameOfSequence = getCacheName() + "-sequence"; initializeSequence(nameOfSequence, ignite); } catch (NamingException e) { log.error(" getFactory : problems obtaining appropriate jdbc context"); throw new UnRetriableException(e); } }
From source file:com.dattack.naming.StandaloneJndiTest.java
@Test public void testLookupInvalidContextAndName() throws NamingException { exception.expect(NamingException.class); exception.expectMessage(String.format("Invalid subcontext '%s' in context '/'", INVALID_CONTEXT)); final InitialContext context = new InitialContext(); final String name = getCompositeName(INVALID_CONTEXT, INVALID_OBJECT_NAME); final Object obj = context.lookup(name); fail(String.format("This test must fail because the name '%s' not exists (object: %s)", INVALID_CONTEXT, ObjectUtils.toString(obj))); }
From source file:com.funambol.server.db.DataSourceContextHelper.java
/** * Binds the given object with the given name * @param obj the object to bind/*from w ww .j a va 2 s . c o m*/ * @param jndiName the name * @throws javax.naming.NamingException if an error occurs */ private static void bind(Object obj, String jndiName) throws NamingException { InitialContext context = new InitialContext(); createSubcontexts(context, jndiName); context.bind(jndiName, obj); }
From source file:hudson.model.AbstractModelObject.java
/** * Checks jndi,environment, hudson environment and system properties for specified key. * Property is checked in direct order:/* w w w. j a v a2 s . c o m*/ * <ol> * <li>JNDI ({@link InitialContext#lookup(String)})</li> * <li>Hudson environment ({@link EnvVars#masterEnvVars})</li> * <li>System properties ({@link System#getProperty(String)})</li> * </ol> * @param key - the name of the configured property. * @return the string value of the configured property, or null if there is no property with that key. */ protected String getConfiguredHudsonProperty(String key) { if (StringUtils.isNotBlank(key)) { String resultValue; try { InitialContext iniCtxt = new InitialContext(); Context env = (Context) iniCtxt.lookup("java:comp/env"); resultValue = StringUtils.trimToNull((String) env.lookup(key)); if (null != resultValue) { return resultValue; } // look at one more place. See http://issues.hudson-ci.org/browse/HUDSON-1314 resultValue = StringUtils.trimToNull((String) iniCtxt.lookup(key)); if (null != resultValue) { return resultValue; } } catch (NamingException e) { // ignore } // look at the env var next resultValue = StringUtils.trimToNull(EnvVars.masterEnvVars.get(key)); if (null != resultValue) { return resultValue; } // finally check the system property resultValue = StringUtils.trimToNull(System.getProperty(key)); if (null != resultValue) { return resultValue; } } return null; }
From source file:de.iai.ilcd.configuration.ConfigurationService.java
ConfigurationService() { try {/* w w w . j a v a 2 s .c om*/ this.appConfig = new PropertiesConfiguration("app.properties"); } catch (ConfigurationException e) { throw new RuntimeException("FATAL ERROR: application properties could not be initialized", e); } // log application version message this.versionTag = this.appConfig.getString("version.tag"); this.logger.info(this.versionTag); // validate/migrate database schema this.migrateDatabaseSchema(); URL resourceUrl = Thread.currentThread().getContextClassLoader().getResource("log4j.properties"); String decodedPath = ""; // now extract path and decode it try { // note, that URLs getPath() method does not work, because it don't // decode encoded Urls, but URI's does this decodedPath = resourceUrl.toURI().getPath(); } catch (URISyntaxException ex) { this.logger.error("Cannot extract base path from resource files", ex); } // base path it relative to web application root directory this.basePath = decodedPath.replace("/WEB-INF/classes/log4j.properties", ""); this.logger.info("base path of web application: {}", this.basePath); // Obtain our environment naming context Context initCtx; Context envCtx; String propertiesFilePath = null; try { initCtx = new InitialContext(); envCtx = (Context) initCtx.lookup("java:comp/env"); propertiesFilePath = (String) envCtx.lookup("soda4LCAProperties"); } catch (NamingException e1) { this.logger.error(e1.getMessage()); } if (propertiesFilePath == null) { this.logger.info("using default application properties at {}", this.defaultPropertiesFile); propertiesFilePath = this.defaultPropertiesFile; } else { this.logger.info("reading application configuration properties from {}", propertiesFilePath); } try { // OK, now load configuration file this.fileConfig = new PropertiesConfiguration(propertiesFilePath); this.featureNetworking = this.fileConfig.getString("feature.networking"); configureLanguages(); } catch (ConfigurationException ex) { this.logger.error( "Cannot find application configuration properties file under {}, either put it there or set soda4LCAProperties environment entry via JNDI.", propertiesFilePath, ex); throw new RuntimeException("application configuration properties not found", ex); } }
From source file:edu.mayo.cts2.framework.core.config.ConfigInitializer.java
/** * Gets the variable.//from ww w.j a va 2s.c om * * @param jndiName the jndi name * @param systemVariableName the system variable name * @param defaultValue the default value * @return the variable */ private String getVariable(String jndiName, String systemVariableName, String defaultValue) { String sysVarValue = System.getProperty(systemVariableName); if (StringUtils.isNotBlank(sysVarValue)) { log.info("Using value: " + sysVarValue + " for Environment Variable: " + systemVariableName); return sysVarValue; } String jndiValue = null; try { InitialContext ctx = new InitialContext(); jndiValue = (String) ctx.lookupLink("java:/comp/env/" + jndiName); } catch (NoInitialContextException e) { log.warn("No JNDI Context found."); } catch (NameNotFoundException e) { // this is ok, it means there is no JNDI name registered } catch (NamingException e) { // this is also ok, it means there is no JNDI name registered } if (StringUtils.isNotBlank(jndiValue)) { log.info("Using value: " + jndiValue + " for JNDI Variable: " + jndiName); return jndiValue; } log.info("Using default value: " + defaultValue); return defaultValue; }