List of usage examples for javax.naming Context close
public void close() throws NamingException;
From source file:eu.planets_project.tb.impl.system.batch.backends.ifwee.TestbedWEEBatchProcessor.java
public void submitTicketForPollingToQueue(String ticket, String queueName, String batchProcessorSystemID) throws Exception { Context ctx = null; QueueConnection cnn = null;/*from w ww. j ava 2 s . c o m*/ QueueSession sess = null; Queue queue = null; QueueSender sender = null; try { ctx = new InitialContext(); QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(QueueConnectionFactoryName); queue = (Queue) ctx.lookup(queueName); cnn = factory.createQueueConnection(); sess = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); //create the message to send to the MDB e.g. a TextMessage TextMessage message = sess.createTextMessage(ticket); message.setStringProperty(BatchProcessor.QUEUE_PROPERTY_NAME_FOR_SENDING, batchProcessorSystemID); //and finally send the message to the queue. sender = sess.createSender(queue); sender.send(message); log.debug("TestbedWEEBatchProcessor: sent message to queue, ID:" + message.getJMSMessageID()); } finally { try { if (null != sender) sender.close(); } catch (Exception ex) { } try { if (null != sess) sess.close(); } catch (Exception ex) { } try { if (null != cnn) cnn.close(); } catch (Exception ex) { } try { if (null != ctx) ctx.close(); } catch (Exception ex) { } } }
From source file:com.mirth.connect.connectors.jms.JmsDispatcher.java
/** * Get the JmsConnection from the cache if one exists, otherwise a new one will be created. This * method is synchronized otherwise multiple threads may try to create the same connection * simultaneously. Only one thread is allowed to create a connection at a time. Subsequent * threads will then retrieve the connection that was already created. *///w w w.j av a 2 s . c om private synchronized JmsConnection getJmsConnection(JmsDispatcherProperties jmsDispatcherProperties, String connectionKey, Long dispatcherId, boolean replace) throws Exception { // If the connection needs to be replaced, clean up the old connection and remove it from the cache. if (replace) { closeJmsConnectionQuietly(connectionKey); } JmsConnection jmsConnection = jmsConnections.get(connectionKey); if (jmsConnection == null) { if (jmsConnections.size() >= maxConnections) { throw new Exception("Cannot create new connection. Maximum number (" + maxConnections + ") of cached connections reached."); } Context initialContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Map<String, String> connectionProperties = jmsDispatcherProperties.getConnectionProperties(); if (jmsDispatcherProperties.isUseJndi()) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { MirthContextFactory contextFactory = contextFactoryController .getContextFactory(getResourceIds()); Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader()); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, jmsDispatcherProperties.getJndiProviderUrl()); env.put(Context.INITIAL_CONTEXT_FACTORY, jmsDispatcherProperties.getJndiInitialContextFactory()); env.put(Context.SECURITY_PRINCIPAL, jmsDispatcherProperties.getUsername()); env.put(Context.SECURITY_CREDENTIALS, jmsDispatcherProperties.getPassword()); initialContext = new InitialContext(env); String connectionFactoryName = jmsDispatcherProperties.getJndiConnectionFactoryName(); connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } else { String className = jmsDispatcherProperties.getConnectionFactoryClass(); MirthContextFactory contextFactory = contextFactoryController.getContextFactory(getResourceIds()); connectionFactory = (ConnectionFactory) Class .forName(className, true, contextFactory.getApplicationClassLoader()).newInstance(); } BeanUtil.setProperties(connectionFactory, connectionProperties); try { logger.debug("Creating JMS connection and session"); connection = connectionFactory.createConnection(jmsDispatcherProperties.getUsername(), jmsDispatcherProperties.getPassword()); String clientId = jmsDispatcherProperties.getClientId(); if (!clientId.isEmpty()) { connection.setClientID(clientId); } logger.debug("Starting JMS connection"); connection.start(); } catch (JMSException e) { try { if (connection != null) { connection.close(); } } catch (Exception e1) { logger.debug("Failed to close JMS connection.", e); } try { if (initialContext != null) { initialContext.close(); } } catch (Exception e1) { logger.debug("Failed to close initial context.", e); } throw e; } // Create the new JmsConnection and add it to the cache. jmsConnection = new JmsConnection(connection, initialContext); jmsConnections.put(connectionKey, jmsConnection); } return jmsConnection; }
From source file:org.acegisecurity.ldap.LdapUtils.java
public static void closeContext(Context ctx) { try {/*from ww w. j a v a 2 s. com*/ if (ctx != null) { ctx.close(); } } catch (NamingException e) { logger.error("Failed to close context.", e); } }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }/*from w w w . ja va2 s. c o m*/ SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } } }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * /*from w w w.j a va2 s . c om*/ * @param callback * the callback * @param searchBase * the base DN for the search * @param query * the query * @param returningAttributes * the attributes to include in search results * @throws AlfrescoRuntimeException */ private void processQuery(SearchCallback callback, String searchBase, String query, String[] returningAttributes) { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(returningAttributes); if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Processing query"); LDAPUserRegistry.logger.debug("Search base: " + searchBase); LDAPUserRegistry.logger.debug(" Return result limit: " + searchControls.getCountLimit()); LDAPUserRegistry.logger.debug(" DerefLink: " + searchControls.getDerefLinkFlag()); LDAPUserRegistry.logger.debug(" Return named object: " + searchControls.getReturningObjFlag()); LDAPUserRegistry.logger.debug(" Time limit for search: " + searchControls.getTimeLimit()); LDAPUserRegistry.logger.debug(" Attributes to return: " + returningAttributes.length + " items."); for (String ra : returningAttributes) { LDAPUserRegistry.logger.debug(" Attribute: " + ra); } } InitialDirContext ctx = null; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize); do { searchResults = ctx.search(searchBase, query, searchControls); while (searchResults.hasMore()) { result = searchResults.next(); callback.process(result); // Close the contexts, see ALF-20682 Context resultCtx = (Context) result.getObject(); if (resultCtx != null) { resultCtx.close(); } result = null; } } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize)); } catch (NamingException e) { Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } catch (ParseException e) { Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } finally { if (result != null) { try { Context resultCtx = (Context) result.getObject(); if (resultCtx != null) { resultCtx.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } searchResults = null; } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { } } try { callback.close(); } catch (NamingException e) { } } }
From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java
private void authenticateWithoutTlsExtension(String userDN, String password) throws AuthenticationException { Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, password); try {/*from w w w . ja v a 2s . c o m*/ // Create initial context Context ctx = new InitialDirContext(env); ctx.close(); logger.debug("Authentication successful for {}", userDN); } catch (NamingException e) { throw new AuthenticationException("Error validating LDAP user", e); } }
From source file:org.apache.jmeter.protocol.jms.client.InitialContextFactory.java
/** * Look up the context from the local cache, creating it if necessary. * //from www . j a v a2s . c om * @param initialContextFactory used to set the property {@link Context#INITIAL_CONTEXT_FACTORY} * @param providerUrl used to set the property {@link Context#PROVIDER_URL} * @param useAuth set <code>true</code> if security is to be used. * @param securityPrincipal used to set the property {@link Context#SECURITY_PRINCIPAL} * @param securityCredentials used to set the property {@link Context#SECURITY_CREDENTIALS} * @return the context, never <code>null</code> * @throws NamingException when creation of the context fails */ public static Context lookupContext(String initialContextFactory, String providerUrl, boolean useAuth, String securityPrincipal, String securityCredentials) throws NamingException { String cacheKey = createKey(Thread.currentThread().getId(), initialContextFactory, providerUrl, securityPrincipal, securityCredentials); Context ctx = MAP.get(cacheKey); if (ctx == null) { Properties props = new Properties(); props.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); props.setProperty(Context.PROVIDER_URL, providerUrl); if (useAuth && securityPrincipal != null && securityCredentials != null && securityPrincipal.length() > 0 && securityCredentials.length() > 0) { props.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal); props.setProperty(Context.SECURITY_CREDENTIALS, securityCredentials); log.info("authentication properties set"); } try { ctx = new InitialContext(props); } catch (NoClassDefFoundError | Exception e) { throw new NamingException(e.toString()); } // we want to return the context that is actually in the map // if it's the first put we will have a null result Context oldCtx = MAP.putIfAbsent(cacheKey, ctx); if (oldCtx != null) { // There was an object in map, destroy the temporary and return one in map (oldCtx) try { ctx.close(); } catch (Exception e) { // NOOP } ctx = oldCtx; } // else No object in Map, ctx is the one } return ctx; }
From source file:org.apache.jmeter.protocol.jms.client.InitialContextFactory.java
/** * clear all the InitialContext objects. *//*ww w .j av a 2 s .c o m*/ public static void close() { for (Context ctx : MAP.values()) { try { ctx.close(); } catch (NamingException e) { log.error(e.getMessage()); } } MAP.clear(); log.info("InitialContextFactory.close() called and Context instances cleaned up"); }
From source file:org.apache.juddi.subscription.notify.AMQPNotifier.java
@Override public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException { Connection connection = null; Context context = null; boolean success = false; String err = null;// w w w.ja v a 2 s . co m try { if (destination != null && exchangeType != null && exchangeName != null) { log.info("Sending notification AMQP to " + destination); Properties properties = new Properties(); properties.put("java.naming.factory.initial", "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"); properties.put("connectionfactory.qpidConnectionfactory", destination); properties.put("destination." + exchangeName, exchangeType); context = new InitialContext(properties); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionfactory"); connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destinationLocal = (Destination) context.lookup(exchangeName); MessageProducer messageProducer = session.createProducer(destinationLocal); String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES); TextMessage message = session.createTextMessage(subscriptionResultXML); messageProducer.send(message); success = true; } } catch (Exception e) { e.printStackTrace(); log.error("Error deliverying AMQP subscription " + e.getMessage()); log.debug("Error deliverying AMQP subscription " + e.getMessage(), e); err = e.getMessage(); } finally { try { if (connection != null) { connection.close(); } } catch (JMSException ex) { log.error(null, ex); } try { if (context != null) { context.close(); } } catch (NamingException ex) { log.error(null, ex); } } if (!success) { throw new DispositionReportFaultMessage(err, null); } DispositionReport dr = new DispositionReport(); Result res = new Result(); dr.getResult().add(res); return dr; }
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(); }