Example usage for javax.naming Context close

List of usage examples for javax.naming Context close

Introduction

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

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this context.

Usage

From source file:com.wabacus.config.database.datasource.JNDIDataSource.java

public DataSource getDataSource() {
    Context context = null;
    try {//  w ww.  j  a  v a 2 s  .c o m
        if (ds != null) {
            return ds;
        }
        context = new InitialContext();
        ds = (DataSource) context.lookup(jndi);
        return ds;
    } catch (Exception e) {
        log.error("????", e);
        return null;
    } finally {
        try {
            if (context != null) {
                context.close();
            }
        } catch (Exception ex) {
            log.error("????", ex);
        }
    }

}

From source file:com.clican.pluto.common.util.JndiUtils.java

/**
 * Look up the object with the specified JNDI name in the JNDI server.
 * /* w  ww .  j  a  v a 2  s  . c o  m*/
 * @param jndiName
 *            the JNDI name specified
 * @return the object bound with the name specified, null if this method
 *         fails
 */
public static Object lookupObject(String jndiName) {
    Context ctx = null;
    try {
        Hashtable<String, String> ht = new Hashtable<String, String>();
        // If a special JNDI initial context factory was specified in the
        // constructor, then use it.
        if (jndiInitialContextFactory != null) {
            ht.put(Context.INITIAL_CONTEXT_FACTORY, jndiInitialContextFactory);
        }
        ctx = new InitialContext(ht);
        Object obj = null;
        try {
            obj = ctx.lookup(jndiName);
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.info(
                        "Lookup for an object from Non-Serializable JNDI (relookup from Serializable JNDI) using the JNDI name ["
                                + jndiName + "] : ");
            }
            obj = NonSerializableFactory.lookup(jndiName);
        }

        if (log.isDebugEnabled()) {
            log.debug("JNDI lookup with path [" + jndiName + "] returned object [" + obj + "].");
        }
        return obj;
    } catch (NamingException ex) {
        log.debug("Failed to lookup for an object using the JNDI name [" + jndiName + "] : " + ex);
        return null;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException ne) {
                log.error("Close context error:", ne);
            }
        }
    }
}

From source file:net.fender.sql.ManagedConnectionDataSource.java

/**
 * Sub-classes that implement init() should make sure to call super.init()
 * to ensure JNDI publication./*  w w  w. j av  a  2 s.  c o  m*/
 * 
 * @throws Exception
 */
public void init() throws Exception {
    if (jndiName != null) {
        Context context = null;
        try {
            if (jndiProperties == null) {
                context = new InitialContext();
            } else {
                context = new InitialContext(jndiProperties);
            }
            context.rebind(jndiName, this);
        } finally {
            if (context != null) {
                try {
                    context.close();
                } catch (NamingException ignore) {
                    // ignore
                }
            }
        }
    }
}

From source file:com.mirth.connect.connectors.jms.JmsDispatcher.java

private void closeJmsConnection(String connectionKey) throws Exception {
    JmsConnection jmsConnection = jmsConnections.get(connectionKey);

    if (jmsConnection != null) {
        try {//from  w  ww.  j  a  va2  s. co  m
            Exception firstException = null;

            Connection connection = jmsConnection.getConnection();
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    firstException = e;
                    logger.debug("Failed to close the JMS connection", e);
                }
            }

            Context initialContext = jmsConnection.getInitialContext();
            if (initialContext != null) {
                try {
                    initialContext.close();
                } catch (NamingException e) {
                    if (firstException == null) {
                        firstException = e;
                    }
                    logger.debug("Failed to close the initial context", e);
                }

                initialContext = null;
            }

            if (firstException != null) {
                throw firstException;
            }
        } finally {
            jmsConnections.remove(connectionKey);
        }
    }
}

From source file:com.clican.pluto.common.util.JndiUtils.java

/**
 * Bind the resource manager instance to the JNDI directory.
 * <p>/* ww  w  . j  a va 2 s  .co m*/
 * This method will use the full JNDI path provided for the resource
 * manager, and will create if necessary the individual segments of that
 * path.
 * 
 * @param jndiName
 *            The full JNDI path at which the resource manager instance will
 *            be bound in the JNDI directory. JNDI clients can use that path
 *            to obtain the resource manager instance.
 * @param obj
 *            The object to be bound.
 * @return <b>true</b> if the resource manager was successfully bound to
 *         JNDI using the provided path; otherwise <b>false</b>.
 * 
 * @see #unbind(String)
 */
public static boolean bind(String jndiName, Object obj) {
    if (log.isDebugEnabled()) {
        log.debug("Binding object [" + obj + "] in JNDI at path [" + jndiName + "].");
    }
    Context ctx = null;

    try {
        // Create a binding that is local to this host only.
        Hashtable<String, String> ht = new Hashtable<String, String>();
        // If a special JNDI initial context factory was specified in the
        // constructor, then use it.
        if (jndiInitialContextFactory != null) {
            ht.put(Context.INITIAL_CONTEXT_FACTORY, jndiInitialContextFactory);
        }
        // Turn off binding replication .
        // ht.put(WLContext.REPLICATE_BINDINGS, "false");
        ctx = new InitialContext(ht);

        String[] arrJndiNames = jndiName.split("/");
        String subContext = "";

        for (int i = 0; i < arrJndiNames.length - 1; i++) {
            subContext = subContext + "/" + arrJndiNames[i];
            try {
                ctx.lookup(subContext);
            } catch (NameNotFoundException e) {
                ctx.createSubcontext(subContext);
            }

        }

        if (obj instanceof Serializable || jndiInitialContextFactory != null) {
            ctx.bind(jndiName, obj);
        } else {
            NonSerializableFactory.bind(jndiName, obj);
        }
    } catch (NamingException ex) {
        log.error("An error occured while binding [" + jndiName + "] to JNDI:", ex);
        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException ne) {
                log.error("Close context error:", ne);
            }
        }
    }
    return true;
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * Setup environment.//from ww w . jav  a  2 s .  co m
 * @param props 
 * @throws SourceUnavailableException
 */
protected void setupEnvironment(Properties props) throws SourceUnavailableException {
    this.environment.put("com.sun.jndi.ldap.connect.pool", "true");

    this.environment.put(Context.INITIAL_CONTEXT_FACTORY, props.getProperty("INITIAL_CONTEXT_FACTORY"));
    this.environment.put(Context.PROVIDER_URL, props.getProperty("PROVIDER_URL"));
    this.environment.put(Context.SECURITY_AUTHENTICATION, props.getProperty("SECURITY_AUTHENTICATION"));
    this.environment.put(Context.SECURITY_PRINCIPAL, props.getProperty("SECURITY_PRINCIPAL"));

    String password = props.getProperty("SECURITY_CREDENTIALS");
    password = Morph.decryptIfFile(password);

    this.environment.put(Context.SECURITY_CREDENTIALS, password);
    if (props.getProperty("SECURITY_PROTOCOL") != null) {
        this.environment.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    Context context = null;
    try {
        log.debug("Creating Directory Context");
        context = new InitialDirContext(this.environment);
    } catch (AuthenticationException ex) {
        log.error("Error with Authentication " + ex.getMessage(), ex);
        throw new SourceUnavailableException("Error with Authentication ", ex);
    } catch (NamingException ex) {
        log.error("Naming Error " + ex.getMessage(), ex);
        throw new SourceUnavailableException("Naming Error", ex);
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ne) {
                // squelch, since it is already closed
            }
        }
    }
    log.info("Success in connecting to LDAP");

    this.nameAttributeName = props.getProperty("Name_AttributeType");
    if (this.nameAttributeName == null) {
        log.error("Name_AttributeType not defined");
    }
    this.subjectIDAttributeName = props.getProperty("SubjectID_AttributeType");
    if (this.subjectIDAttributeName == null) {
        log.error("SubjectID_AttributeType not defined");
    }
    this.descriptionAttributeName = props.getProperty("Description_AttributeType");
    if (this.descriptionAttributeName == null) {
        log.error("Description_AttributeType not defined");
    }

}

From source file:de.griffel.confluence.plugins.plantuml.AbstractDatabaseStructureMacroImpl.java

/**
 * Returns database meta data./*from   w  ww. ja v a 2s .  co m*/
 *
 * Returned object must be closed using "closeDatabaseMetaData"
 *
 * @param jdbcName Database which is configured at "java:comp/env/jdbc/<jdbcName>"
 * @return Connection or null if none could be made. _errorMessage contains reason in the latter case.
 */
private DatabaseMetaData openDatabaseMetaData() {
    Context jndiContext = null;
    DatabaseMetaData dbmd = null;
    try {
        jndiContext = new InitialContext();
        javax.sql.DataSource ds = (javax.sql.DataSource) jndiContext
                .lookup("java:comp/env/jdbc/" + _macroParams.getDatasource());
        try {
            _con = ds.getConnection();
            dbmd = _con.getMetaData();
        } catch (SQLException e) {
            sqlException(_macroParams.getDatasource(), e);
        }
    } catch (NamingException e) {
        _errorMessage = e.getMessage();
        log.error("NamingException " + _macroParams.getDatasource() + _errorMessage, e);
    } finally {
        if (jndiContext != null) {
            try {
                jndiContext.close();
            } catch (NamingException e2) {
                log.debug("Exception closing JNDI context", e2);
            }
        }
    }
    return dbmd;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected void commonCloseSearchResult(final SearchResult result) throws NamingException {
    // Close the contexts, see ALF-20682
    final Context context = (Context) result.getObject();
    if (context != null) {
        context.close();
    }// w w  w .  j  av  a  2 s  .c o m
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback//w  w w .  java 2 s.co  m
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws org.alfresco.error.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 (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
        LDAPMultiBaseUserRegistry.logger.debug("Processing query");
        LDAPMultiBaseUserRegistry.logger.debug("Search base: " + searchBase);
        LDAPMultiBaseUserRegistry.logger.debug("    Return result limit: " + searchControls.getCountLimit());
        LDAPMultiBaseUserRegistry.logger.debug("    DerefLink: " + searchControls.getDerefLinkFlag());
        LDAPMultiBaseUserRegistry.logger
                .debug("    Return named object: " + searchControls.getReturningObjFlag());
        LDAPMultiBaseUserRegistry.logger.debug("    Time limit for search: " + searchControls.getTimeLimit());
        LDAPMultiBaseUserRegistry.logger
                .debug("    Attributes to return: " + returningAttributes.length + " items.");
        for (String ra : returningAttributes) {
            LDAPMultiBaseUserRegistry.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);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }/*from  w ww  .ja v a  2  s . co 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 });

    InitialDirContext ctx = null;

    for (String userSearchBase : this.userSearchBases) {

        String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))";

        NamingEnumeration<SearchResult> searchResults = null;
        SearchResult result = 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(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 {
                        LDAPMultiBaseUserRegistry.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;
            }
        } 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);
        }

        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);
        }
    }

    // failed to search
    //        Object[] args = {e.getLocalizedMessage()};
    throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic);
}