Example usage for javax.naming NamingException initCause

List of usage examples for javax.naming NamingException initCause

Introduction

In this page you can find the example usage for javax.naming NamingException initCause.

Prototype

public Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this exception to the specified value.

Usage

From source file:com.enioka.jqm.tools.JndiContext.java

@Override
public Object lookup(String name) throws NamingException {
    if (name == null) {
        throw new IllegalArgumentException("name cannot be null");
    }/* ww w  .j a v  a  2  s . co m*/
    jqmlogger.trace("Looking up a JNDI element named " + name);

    // Special delegated cases
    if (name.startsWith("rmi:")) {
        try {
            return this.r.lookup(name.split("/")[3]);
        } catch (Exception e) {
            NamingException e1 = new NamingException();
            e1.setRootCause(e);
            throw e1;
        }
    }
    if (name.endsWith("serverName")) {
        return JqmEngine.latestNodeStartedName;
    }

    // If in cache...
    if (singletons.containsKey(name)) {
        jqmlogger.trace("JNDI element named " + name + " found in cache.");
        return singletons.get(name);
    }

    // Retrieve the resource description from the database or the XML file
    JndiResourceDescriptor d = ResourceParser.getDescriptor(name);
    jqmlogger.trace("JNDI element named " + name + " not found in cache. Will be created. Singleton status: "
            + d.isSingleton());

    // Singleton handling is synchronized to avoid double creation
    if (d.isSingleton()) {
        synchronized (singletons) {
            if (singletons.containsKey(name)) {
                return singletons.get(name);
            }

            // We use the current thread loader to find the resource and resource factory class - ext is inside that CL.
            // This is done only for payload CL - engine only need ext, not its own CL (as its own CL does NOT include ext).
            Object res = null;
            try {
                ResourceFactory rf = new ResourceFactory(Thread.currentThread()
                        .getContextClassLoader() instanceof com.enioka.jqm.tools.JarClassLoader
                                ? Thread.currentThread().getContextClassLoader()
                                : extResources);
                res = rf.getObjectInstance(d, null, this, new Hashtable<String, Object>());
            } catch (Exception e) {
                jqmlogger.warn("Could not instanciate singleton JNDI object resource " + name, e);
                NamingException ex = new NamingException(e.getMessage());
                ex.initCause(e);
                throw ex;
            }

            // Cache result
            if (res.getClass().getClassLoader() instanceof JarClassLoader) {
                jqmlogger.warn(
                        "A JNDI resource was defined as singleton but was loaded by a payload class loader - it won't be cached to avoid class loader leaks");
            } else {
                singletons.put(name, res);

                // Pool JMX registration (only if cached - avoids leaks)
                if ("org.apache.tomcat.jdbc.pool.DataSourceFactory".equals(d.getFactoryClassName())
                        && (d.get("jmxEnabled") == null ? true
                                : Boolean.parseBoolean((String) d.get("jmxEnabled").getContent()))) {
                    try {
                        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
                        ObjectName jmxname = new ObjectName("com.enioka.jqm:type=JdbcPool,name=" + name);
                        mbs.registerMBean(res.getClass().getMethod("getPool").invoke(res).getClass()
                                .getMethod("getJmxPool")
                                .invoke(res.getClass().getMethod("getPool").invoke(res)), jmxname);
                        jmxNames.add(jmxname);
                    } catch (Exception e) {
                        jqmlogger.warn("Could not register JMX MBean for resource.", e);
                    }
                }
            }

            // Done
            return res;
        }
    }

    // Non singleton
    try {
        // We use the current thread loader to find the resource and resource factory class - ext is inside that CL.
        // This is done only for payload CL - engine only need ext, not its own CL (as its own CL does NOT include ext).
        ResourceFactory rf = new ResourceFactory(
                Thread.currentThread().getContextClassLoader() instanceof com.enioka.jqm.tools.JarClassLoader
                        ? Thread.currentThread().getContextClassLoader()
                        : extResources);
        return rf.getObjectInstance(d, null, this, new Hashtable<String, Object>());
    } catch (Exception e) {
        jqmlogger.warn("Could not instanciate JNDI object resource " + name, e);
        NamingException ex = new NamingException(e.getMessage());
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.rhq.enterprise.server.naming.AccessCheckingInitialContextFactoryBuilder.java

private static InitialContextFactory getJbossDefaultInitialContextFactory() throws NamingException {
    try {// w w  w  . j  ava2  s.  c om
        Class<?> cls = Class.forName("org.jboss.as.naming.InitialContextFactory");
        return (InitialContextFactory) cls.newInstance();
    } catch (Exception e) {
        NamingException ne = new NamingException(
                "Failed to obtain the default initial context factory from JBoss AS.");
        ne.initCause(e);

        throw ne;
    }
}

From source file:org.rhq.enterprise.server.naming.AccessCheckingInitialContextFactoryBuilder.java

/**
 * Create a InitialContext factory.  If the environment does not override the factory class it will use the
 * default context factory./*from  w  w  w . j  av  a  2  s.c om*/
 * 
 * @param environment The environment
 * @return An initial context factory
 * @throws NamingException If an error occurs loading the factory class.
 */
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException {
    final String factoryClassName = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryClassName == null || factoryClassName.equals(defaultFactoryClassName)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No " + Context.INITIAL_CONTEXT_FACTORY + " set. Using the default factory.");
        }
        return defaultFactory;
    }
    final ClassLoader classLoader = getContextClassLoader();
    try {
        final Class<?> factoryClass = Class.forName(factoryClassName, true, classLoader);
        InitialContextFactory configuredFactory = (InitialContextFactory) factoryClass.newInstance();
        return FactoryType.detect(environment, pretendNoFactoryBuilder).wrap(configuredFactory);
    } catch (Exception e) {
        NamingException ne = new NamingException("Failed instantiate InitialContextFactory " + factoryClassName
                + " from classloader " + classLoader);
        ne.initCause(e);

        throw ne;
    }
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContext(String principal, String credentials, boolean pooling)
        throws NamingException {
    final InitialLdapContext ctx;
    if (startTLS) {
        // Note that pooling is not enabled for such connections, because "Stop TLS" is not performed.
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, providerUrl);
        env.put(Context.REFERRAL, DEFAULT_REFERRAL);
        // At this point env should not contain properties SECURITY_AUTHENTICATION, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS to avoid "bind" operation prior to StartTLS:
        ctx = new InitialLdapContext(env, null);
        // http://docs.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        try {// ww  w .  j a v  a  2  s .  co  m
            tls.negotiate();
        } catch (IOException e) {
            NamingException ex = new NamingException("StartTLS failed");
            ex.initCause(e);
            throw ex;
        }
        // Explicitly initiate "bind" operation:
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, authentication);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
        ctx.reconnect(null);
    } else {
        ctx = new InitialLdapContext(getEnvironment(principal, credentials, pooling), null);
    }
    return ctx;
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials)
        throws NamingException {
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    InitialDirContext initialDirContext;
    try {//from  w w  w.  j  ava2  s.c o m
        LoginContext lc = new LoginContext(getClass().getName(),
                new CallbackHandlerImpl(principal, credentials));
        lc.login();
        initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() {
            @Override
            public InitialDirContext run() throws NamingException {
                Properties env = new Properties();
                env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
                env.put(Context.PROVIDER_URL, providerUrl);
                env.put(Context.REFERRAL, DEFAULT_REFERRAL);
                return new InitialLdapContext(env, null);
            }
        });
    } catch (LoginException | PrivilegedActionException e) {
        NamingException namingException = new NamingException(e.getMessage());
        namingException.initCause(e);
        throw namingException;
    }
    return initialDirContext;
}