List of usage examples for javax.naming InitialContext close
public void close() throws NamingException
From source file:jdao.JDAO.java
/** * Looks for a DataSource in Jndi/* www . j av a2s. c o m*/ * * @param name of the datasource * @return datasource or null */ public static DataSource lookupDataSourceFromJndi(String name) throws Exception { InitialContext ctx = new InitialContext(); try { return lookupDataSourceFromJndi(ctx, name); } finally { ctx.close(); } }
From source file:com.flexive.shared.EJBLookup.java
/** * Lookup the EJB found under the given Class's name. Uses default flexive naming scheme. * * @param type EJB interface class instance * @param appName EJB application name * @param environment optional environment for creating the initial context * @param <T> EJB interface type * @return a reference to the given EJB/* w ww . java 2 s . c o m*/ */ protected static <T> T getInterface(Class<T> type, String appName, Hashtable<String, String> environment) { // Try to obtain interface from the lookup cache Object ointerface = ejbCache.get(type.getName()); if (ointerface != null) { return type.cast(ointerface); } // Cache miss: obtain interface and store it in the cache Hashtable<String, String> env; synchronized (EJBLookup.class) { String name; InitialContext ctx = null; env = new Hashtable<String, String>(10); try { if (environment != null) env.putAll(environment); if (used_strategy == null) { appName = discoverStrategy(appName, env, type); if (used_strategy != null) { LOG.info("Working lookup strategy: " + used_strategy); } else { LOG.error("No working lookup strategy found! Possibly because of pending redeployment."); } } prepareEnvironment(used_strategy, env); ctx = new InitialContext(env); name = buildName(appName, type); ointerface = ctx.lookup(name); ejbCache.putIfAbsent(type.getName(), ointerface); return type.cast(ointerface); } catch (Exception exc) { //try one more time with a strategy rediscovery for that bean //this can happen if some beans use mapped names and some not used_strategy = null; try { env.clear(); if (environment != null) env.putAll(environment); appName = discoverStrategy(appName, env, type); if (used_strategy != null) { prepareEnvironment(used_strategy, env); ctx = new InitialContext(env); name = buildName(appName, type); ointerface = ctx.lookup(name); ejbCache.putIfAbsent(type.getName(), ointerface); return type.cast(ointerface); } } catch (Exception e) { LOG.warn("Attempt to rediscover lookup strategy for " + type + " failed!", e); } throw new FxLookupException(LOG, exc, "ex.ejb.lookup.failure", type, exc).asRuntimeException(); } finally { if (ctx != null) try { ctx.close(); } catch (NamingException e) { LOG.error("Failed to close context: " + e.getMessage(), e); } } } }
From source file:org.miloss.fgsms.bueller.Bueller.java
private String doJmsURL(boolean pooled, String endpoint) { try {/* w w w . jav a 2 s. com*/ 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:org.apache.ode.bpel.extvar.jdbc.JdbcExternalVariableModule.java
public void configure(QName pid, String extVarId, Element config) throws ExternalVariableModuleException { EVarId evarId = new EVarId(pid, extVarId); DataSource ds = null;//from ww w. jav a 2 s. c o m Element jndiDs = DOMUtils.findChildByName(config, new QName(JDBC_NS, "datasource-jndi")); Element jndiRef = DOMUtils.findChildByName(config, new QName(JDBC_NS, "datasource-ref")); Element initMode = DOMUtils.findChildByName(config, new QName(JDBC_NS, "init-mode")); if (jndiRef != null) { String refname = jndiRef.getTextContent().trim(); ds = _dataSources.get(refname); if (ds == null) throw new ExternalVariableModuleException( "Data source reference \"" + refname + "\" not found for external variable " + evarId + "; make sure to register the data source with the engine!"); } else if (jndiDs != null) { String name = jndiDs.getTextContent().trim(); Object dsCandidate; InitialContext ctx; try { ctx = new InitialContext(); } catch (Exception ex) { throw new ExternalVariableModuleException( "Unable to access JNDI context for external variable " + evarId, ex); } try { dsCandidate = ctx.lookup(name); } catch (Exception ex) { throw new ExternalVariableModuleException("Lookup of data source for " + evarId + " failed.", ex); } finally { try { ctx.close(); } catch (NamingException e) { /* ignore */ } } if (dsCandidate == null) throw new ExternalVariableModuleException("Data source \"" + name + "\" not found in JNDI!"); if (!(dsCandidate instanceof DataSource)) throw new ExternalVariableModuleException( "JNDI object \"" + name + "\" does not implement javax.sql.DataSource"); ds = (DataSource) dsCandidate; } if (ds == null) { throw new ExternalVariableModuleException( "No valid data source configuration for JDBC external varible " + evarId); } Connection conn = null; DatabaseMetaData metaData; try { conn = ds.getConnection(); metaData = conn.getMetaData(); } catch (Exception ex) { try { if (conn != null) conn.close(); } catch (SQLException e) { // ignore } throw new ExternalVariableModuleException( "Unable to open database connection for external variable " + evarId, ex); } try { DbExternalVariable dbev = new DbExternalVariable(evarId, ds); if (initMode != null) try { dbev._initType = InitType.valueOf(initMode.getTextContent().trim()); } catch (Exception ex) { throw new ExternalVariableModuleException( "Invalid <init-mode> value: " + initMode.getTextContent().trim()); } Element tableName = DOMUtils.findChildByName(config, new QName(JDBC_NS, "table")); if (tableName == null || tableName.getTextContent().trim().equals("")) throw new ExternalVariableModuleException("Must specify <table> for external variable " + evarId); String table = tableName.getTextContent().trim(); String schema = null; if (table.indexOf('.') != -1) { schema = table.substring(0, table.indexOf('.')); table = table.substring(table.indexOf('.') + 1); } if (metaData.storesLowerCaseIdentifiers()) { table = table.toLowerCase(); if (schema != null) schema = table.toLowerCase(); } else if (metaData.storesUpperCaseIdentifiers()) { table = table.toUpperCase(); if (schema != null) schema = schema.toUpperCase(); } dbev.generatedKeys = metaData.supportsGetGeneratedKeys(); ResultSet tables = metaData.getTables(null, schema, table, null); if (tables.next()) { dbev.table = tables.getString("TABLE_NAME"); dbev.schema = tables.getString("TABLE_SCHEM"); } else throw new ExternalVariableModuleException("Table \"" + table + "\" not found in database."); tables.close(); List<Element> columns = DOMUtils.findChildrenByName(config, new QName(JDBC_NS, "column")); for (Element col : columns) { String name = col.getAttribute("name"); String colname = col.getAttribute("column-name"); String key = col.getAttribute("key"); String gentype = col.getAttribute("generator"); String expression = col.getAttribute("expression"); if (key == null || "".equals(key)) key = "no"; if (gentype == null || "".equals(gentype)) gentype = GenType.none.toString(); if (colname == null || "".equals(colname)) colname = name; if (name == null || "".equals(name)) throw new ExternalVariableModuleException( "External variable " + evarId + " <column> element must have \"name\" attribute. "); if (metaData.storesLowerCaseIdentifiers()) colname = colname.toLowerCase(); else if (metaData.storesUpperCaseIdentifiers()) colname = colname.toUpperCase(); GenType gtype; try { gtype = GenType.valueOf(gentype); } catch (Exception ex) { throw new ExternalVariableModuleException("External variable " + evarId + " column \"" + name + "\" generator type \"" + gentype + "\" is unknown."); } if (gtype == GenType.expression && (expression == null || "".equals(expression))) throw new ExternalVariableModuleException("External variable " + evarId + " column \"" + name + "\" used \"expression\" generator, but did not specify an expression"); Column c = dbev.new Column(name, colname, key.equalsIgnoreCase("yes"), gtype, expression); ResultSet cmd = metaData.getColumns(null, dbev.schema, dbev.table, colname); try { if (cmd.next()) { c.dataType = cmd.getInt("DATA_TYPE"); c.nullok = cmd.getInt("NULLABLE") != 0; } else throw new ExternalVariableModuleException("External variable " + evarId + " referenced " + "non-existant column \"" + colname + "\"!"); } finally { cmd.close(); } dbev.addColumn(c); } if (dbev.numColumns() == 0) throw new ExternalVariableModuleException( "External variable " + evarId + " did not have any <column> elements!"); _vars.put(evarId, dbev); } catch (SQLException se) { throw new ExternalVariableModuleException("SQL Error", se); } finally { try { conn.close(); } catch (SQLException e) { } } }
From source file:org.collectionspace.authentication.realm.db.CSpaceDbRealm.java
private Connection getConnection() throws LoginException, SQLException { InitialContext ctx = null; Connection conn = null;/*from ww w . jav a 2s. com*/ try { ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(getDataSourceName()); if (ds == null) { throw new IllegalArgumentException("datasource not found: " + getDataSourceName()); } conn = ds.getConnection(); return conn; } catch (NamingException ex) { LoginException le = new LoginException("Error looking up DataSource from: " + getDataSourceName()); le.initCause(ex); throw le; } finally { if (ctx != null) { try { ctx.close(); } catch (Exception e) { } } } }
From source file:org.hibersap.ejb.interceptor.HibersapSessionInterceptor.java
private SessionManager lookupSessionManager(final String jndiName) { InitialContext context = null; try {/*from w ww . ja va2s.co m*/ context = new InitialContext(); Object object = context.lookup(jndiName); if (object == null) { throw new HibersapException( format("Lookup for JNDI name '%s' returned null. Expected to find an instance of %s", jndiName, SessionManager.class.getName())); } if (!SessionManager.class.isAssignableFrom(object.getClass())) { throw new HibersapException( format("Object bound under JNDI name '%s' is not a %s but an instance of %s", jndiName, SessionManager.class.getName(), object.getClass().getName())); } return (SessionManager) object; } catch (NamingException e) { throw new HibersapException("Error creating InitialContext", e); } finally { if (context != null) { try { context.close(); } catch (NamingException e) { LOGGER.warn("Error closing InitialContext", e); } } } }
From source file:org.hyperic.hq.plugin.jboss.JBossUtil.java
public static MBeanServerConnection getMBeanServerConnection(Properties config) throws NamingException, RemoteException { MBeanServerConnection adaptor; Properties props = new Properties(); for (int i = 0; i < NAMING_PROPS.length; i++) { props.setProperty(NAMING_PROPS[i][0], NAMING_PROPS[i][1]); }// ww w.j a v a 2s. c o m props.putAll(config); if (props.getProperty(Context.SECURITY_PRINCIPAL) != null) { props.setProperty(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY); } InitialContext ctx = new InitialContext(props); try { Object o = ctx.lookup(props.getProperty(PROP_NAMING_CONNECTOR)); log.debug("=> " + Arrays.asList(o.getClass().getInterfaces())); adaptor = (MBeanServerConnection) o; } finally { ctx.close(); } return adaptor; }
From source file:org.hyperic.hq.plugin.tomcat.JBossUtil.java
public static MBeanServerConnection getMBeanServerConnection(Properties config) throws NamingException, RemoteException { MBeanServerConnection adaptor; Properties props = new Properties(); for (int i = 0; i < NAMING_PROPS.length; i++) { props.setProperty(NAMING_PROPS[i][0], NAMING_PROPS[i][1]); }/*from ww w . j a v a 2 s .c o m*/ props.putAll(config); props.put("java.naming.provider.url", config.get("jmx.url")); if (props.getProperty(Context.SECURITY_PRINCIPAL) != null) { props.setProperty(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY); } InitialContext ctx = new InitialContext(props); try { Object o = ctx.lookup(props.getProperty(PROP_NAMING_CONNECTOR)); log.debug("=> " + Arrays.asList(o.getClass().getInterfaces())); adaptor = (MBeanServerConnection) o; } finally { ctx.close(); } return adaptor; }
From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java
/** * Tests that an authorized user has access to an EJB method. * * @throws Exception/* ww w .ja va 2 s .c o m*/ */ @Test public void testAuthorizedClient() throws Exception { final Properties env = configureEjbClient(CLIENT_AUTHORIZED_NAME); InitialContext ctx = new InitialContext(env); final Hello helloBean = (Hello) ctx.lookup(HELLOBEAN_LOOKUP_NAME); assertEquals(HelloBean.HELLO_WORLD, helloBean.sayHelloWorld()); ctx.close(); }
From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java
/** * Tests if role check is done correctly for authenticated user. * * @throws Exception/*from w ww.j ava2 s . c om*/ */ @Test public void testNotAuthorizedClient() throws Exception { final Properties env = configureEjbClient(CLIENT_NOT_AUTHORIZED_NAME); InitialContext ctx = new InitialContext(env); final Hello helloBean = (Hello) ctx.lookup(HELLOBEAN_LOOKUP_NAME); try { helloBean.sayHelloWorld(); fail("The EJB call should fail for unauthorized client."); } catch (EJBAccessException e) { //OK } ctx.close(); }