Example usage for javax.naming InitialContext close

List of usage examples for javax.naming InitialContext close

Introduction

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

Prototype

public void close() throws NamingException 

Source Link

Usage

From source file:com.codeasylum.stress.api.OuroborosImpl.java

public static Ouroboros getRemoteInterface(String rmiHost) throws NamingException {

    Ouroboros ouroboros;//from www  . j  ava2  s.c o m
    InitialContext initContext;
    Context rmiContext;

    initContext = new InitialContext();
    rmiContext = (Context) initContext.lookup("rmi://" + rmiHost + ':' + registryPort.get());
    ouroboros = (Ouroboros) PortableRemoteObject.narrow(rmiContext.lookup(Ouroboros.class.getName()),
            Ouroboros.class);
    rmiContext.close();
    initContext.close();

    return ouroboros;
}

From source file:Util.java

/**
 * Lookup an object in the default initial context
 * //from  ww  w . j  ava 2s.  c om
 * @param name
 *          the name to lookup
 * @param clazz
 *          the expected type
 * @return the object
 * @throws Exception
 *           for any error
 */
public static Object lookup(String name, Class<?> clazz) throws Exception {
    InitialContext ctx = new InitialContext();
    try {
        return lookup(ctx, name, clazz);
    } finally {
        ctx.close();
    }
}

From source file:Util.java

/**
 * Lookup an object in the default initial context
 * //from w  w w . j a  v  a  2 s.com
 * @param name
 *          the name to lookup
 * @param clazz
 *          the expected type
 * @return the object
 * @throws Exception
 *           for any error
 */
public static Object lookup(Name name, Class<?> clazz) throws Exception {
    InitialContext ctx = new InitialContext();
    try {
        return lookup(ctx, name, clazz);
    } finally {
        ctx.close();
    }
}

From source file:com.tdclighthouse.prototype.utils.EmailUtils.java

public static Session getMailSession(final String sessionName) {
    Session result = null;/*ww w.j a  v a2 s  .  c  om*/
    InitialContext initialContext = null;
    try {
        initialContext = new InitialContext();
        Context context = (Context) initialContext.lookup("java:comp/env");
        result = (Session) context.lookup(sessionName);
    } catch (NamingException e) {
        throw new HstComponentException(e);
    } finally {
        try {
            if (initialContext != null) {
                initialContext.close();
            }
        } catch (NamingException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    return result;
}

From source file:com.ikon.module.jcr.stuff.JCRUtils.java

/**
 * Get JCR Session//from   ww w  .  ja  v  a 2  s .com
 */
public static Session getSession()
        throws javax.jcr.LoginException, javax.jcr.RepositoryException, DatabaseException {
    Subject subject = null;
    Object obj = null;

    // Resolve subject
    // Subject userSubject=(Subject)PolicyContext.getContext("javax.security.auth.Subject.container");
    if (EnvironmentDetector.isServerJBoss()) {
        try {
            InitialContext ctx = new InitialContext();
            subject = (Subject) ctx.lookup("java:/comp/env/security/subject");
            ctx.close();
        } catch (NamingException e) {
            throw new javax.jcr.LoginException(e.getMessage());
        }
    } else if (EnvironmentDetector.isServerTomcat()) {
        subject = Subject.getSubject(AccessController.getContext());
    }

    // Obtain JCR session
    if (subject != null) {
        obj = Subject.doAs(subject, new PrivilegedAction<Object>() {
            public Object run() {
                Session s = null;

                try {
                    s = JcrRepositoryModule.getRepository().login();
                } catch (javax.jcr.LoginException e) {
                    return e;
                } catch (javax.jcr.RepositoryException e) {
                    return e;
                }

                return s;
            }
        });
    }

    // Validate JCR session
    if (obj instanceof javax.jcr.LoginException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.RepositoryException) {
        throw (javax.jcr.RepositoryException) obj;
    } else if (obj instanceof javax.jcr.Session) {
        Session session = (javax.jcr.Session) obj;
        log.debug("#{} - {} Create session {} from {}", new Object[] { ++sessionCreationCount, ++activeSessions,
                session, StackTraceUtils.whoCalledMe() });
        JcrAuthModule.loadUserData(session);
        return session;
    } else {
        return null;
    }
}

From source file:info.bunji.jdbc.logger.JdbcLoggerFactory.java

/**
 ********************************************
 * get loggerName from jdbc url./*  w  w w . j  ava2  s .  c  o  m*/
 *
 * @param url connection url
 * @return loggerName(jdbc url or DataSourceName)
 ********************************************
 */
private static String getLoggerName(String url) {
    if (!dsNameMap.containsKey(url)) {
        dsNameMap.put(url, url);

        // datasource????
        InitialContext ctx = null;
        try {
            // JNDI??????
            ctx = new InitialContext();
            NamingEnumeration<NameClassPair> ne = ctx.list("java:comp/env/jdbc");
            while (ne.hasMoreElements()) {
                NameClassPair nc = ne.nextElement();
                DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/" + nc.getName());
                // ?DataSource????getUrl()
                Method method = ds.getClass().getMethod("getUrl");
                String dsUrl = (String) method.invoke(ds);
                if (dsUrl.startsWith(DriverEx.DRIVER_URL_PREFIX)) {
                    dsUrl = dsUrl.replace(DriverEx.DRIVER_URL_PREFIX, "jdbc:");
                    if (dsUrl.equals(url)) {
                        dsNameMap.put(url, nc.getName());
                        break;
                    }
                }
            }
        } catch (Throwable t) {
            printThrowable(t);
        } finally {
            try {
                if (ctx != null)
                    ctx.close();
            } catch (NamingException e) {
            }
        }
    }
    return dsNameMap.get(url);
}

From source file:com.boylesoftware.web.impl.auth.SessionlessAuthenticationService.java

/**
 * Create new authenticator.//w w w.j  a  va  2 s .  c  om
 *
 * @param userRecordHandler User record handler.
 * @param userRecordsCache Authenticated user records cache.
 *
 * @throws UnavailableException If an error happens creating the service.
 */
public SessionlessAuthenticationService(final UserRecordHandler<T> userRecordHandler,
        final UserRecordsCache<T> userRecordsCache) throws UnavailableException {

    // store the references
    this.userRecordHandler = userRecordHandler;
    this.userRecordsCache = userRecordsCache;

    // get configured secret key from the JNDI
    String secretKeyStr;
    try {
        final InitialContext jndi = new InitialContext();
        try {
            secretKeyStr = (String) jndi.lookup("java:comp/env/secretKey");
        } finally {
            jndi.close();
        }
    } catch (final NamingException e) {
        throw new UnavailableException("Error looking up secret key in the JNDI: " + e);
    }
    if (!secretKeyStr.matches("[0-9A-Fa-f]{32}"))
        throw new UnavailableException("Configured secret key is" + " invalid. The key must be a 16 bytes value"
                + " encoded as a hexadecimal string.");
    final Key secretKey = new SecretKeySpec(Hex.decode(secretKeyStr), CipherToolbox.ALGORITHM);

    // create the cipher pool
    this.cipherPool = new FastPool<>(new PoolableObjectFactory<CipherToolbox>() {

        @Override
        public CipherToolbox makeNew(final FastPool<CipherToolbox> pool, final int pooledObjectId) {

            return new CipherToolbox(pool, pooledObjectId, secretKey);
        }
    }, "AuthenticatorCiphersPool");
}

From source file:org.jboss.spring.deployers.AbstractSpringMetaDataDeployer.java

/**
 * Unind factory from non-serializable JNDI context.
 *
 * @param name the jndi name/*from  w w w.  j av  a  2s .  c  o m*/
 */
protected void unbind(String name) {
    InitialContext ctx = null;
    try {
        ctx = new InitialContext();
        ctx.unbind(name);
        NonSerializableFactory.unbind(name);
    } catch (NamingException e) {
        log.warn("Unable to unbind BeanFactory from JNDI", e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Throwable ignored) {
            }
        }
    }
}

From source file:org.jboss.spring.deployers.AbstractSpringMetaDataDeployer.java

/**
 * Bind factory to non-serializable JNDI context.
 *
 * @param beanFactory the bean factory/*from w w w  .  ja  v a  2 s  . c  om*/
 * @param name        the jndi name
 * @throws DeploymentException for any error
 */
protected void bindIfPossible(T beanFactory, String name) throws DeploymentException {
    InitialContext ctx = null;
    try {
        ctx = new InitialContext();
        Object existingObject = NonSerializableFactory.lookup(name);
        if (existingObject != null) {
            throw new DeploymentException(
                    "Unable to bind BeanFactory into JNDI as " + name + " : binding already" + " exists");
        }
        NonSerializableFactory.rebind(ctx, name, beanFactory);
    } catch (NamingException e) {
        throw new DeploymentException("Unable to bind BeanFactory into JNDI", e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Throwable ignored) {
            }
        }
    }
}

From source file:com.francetelecom.clara.cloud.commons.JndiAwarePropertyPlaceholderConfigurer.java

/**
 * Resolve the given placeholder using the given properties. Default
 * implementation simply checks for an environment entry for a corresponding
 * property key./*from   www.  ja  v  a2s  .  c  o m*/
 * <p>
 * Subclasses can override this for customized placeholder-to-key mappings
 * or custom resolution strategies, possibly just using the given lookup as
 * a fallback.
 * 
 * @param placeholder
 *            the placeholder to resolve
 * @return the resolved value, of <code>null</code> if none
 */
protected String resolveJndiProperty(String placeholder) {
    InitialContext initialContext = null;
    try {
        initialContext = new InitialContext();
        try {

            String prefix;
            if (resourceRef) {
                prefix = "java:comp/env/";
            } else {
                prefix = "";
            }
            return (String) initialContext.lookup(prefix + placeholder);
        } catch (NameNotFoundException e) {
            return null;
        } catch (NamingException e) {
            return null;
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (initialContext != null) {
            try {
                initialContext.close();
            } catch (NamingException e) {
            }
        }
    }
}