Example usage for javax.naming NamingException setRootCause

List of usage examples for javax.naming NamingException setRootCause

Introduction

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

Prototype

public void setRootCause(Throwable e) 

Source Link

Document

Records the root cause of this NamingException.

Usage

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

private static JndiResourceDescriptor fromDatabase(String alias) throws NamingException {
    JndiObjectResource resource = null;/*  w  w  w  . j av  a2s  . co  m*/
    EntityManager em = null;
    try {
        // Using the horrible CriteriaBuilder API instead of a string query. This avoids classloading issues - Hibernate binds
        // the entities at run time with the thread current classloader...
        em = Helpers.getNewEm();

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<JndiObjectResource> q = cb.createQuery(JndiObjectResource.class);
        Root<JndiObjectResource> c = q.from(JndiObjectResource.class);
        ParameterExpression<String> p = cb.parameter(String.class);
        q.select(c).where(cb.equal(c.get("name"), p));

        TypedQuery<JndiObjectResource> query = em.createQuery(q);
        query.setParameter(p, alias);
        resource = query.getSingleResult();
    } catch (Exception e) {
        NamingException ex = new NamingException("Could not find a JNDI object resource of name " + alias);
        ex.setRootCause(e);
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }

    // Create the ResourceDescriptor from the JPA object
    JndiResourceDescriptor d = new JndiResourceDescriptor(resource.getType(), resource.getDescription(), null,
            resource.getAuth(), resource.getFactory(), resource.getSingleton());
    for (JndiObjectResourceParameter prm : resource.getParameters()) {
        d.add(new StringRefAddr(prm.getKey(), prm.getValue()));
    }

    return d;
}

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

private static void importXml() throws NamingException {
    InputStream is = ResourceParser.class.getClassLoader().getResourceAsStream(Helpers.resourceFile);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    try {/*from ww  w . j a  v  a2 s. c  om*/
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(is);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("resource");

        String jndiAlias = null, resourceClass = null, description = "no description", scope = null,
                auth = "Container", factory = null;
        boolean singleton = false;

        for (int i = 0; i < nList.getLength(); i++) {
            Node n = nList.item(i);
            Map<String, String> otherParams = new HashMap<String, String>();

            NamedNodeMap attrs = n.getAttributes();
            for (int j = 0; j < attrs.getLength(); j++) {
                Node attr = attrs.item(j);
                String key = attr.getNodeName();
                String value = attr.getNodeValue();

                if ("name".equals(key)) {
                    jndiAlias = value;
                } else if ("type".equals(key)) {
                    resourceClass = value;
                } else if ("description".equals(key)) {
                    description = value;
                } else if ("factory".equals(key)) {
                    factory = value;
                } else if ("auth".equals(key)) {
                    auth = value;
                } else if ("singleton".equals(key)) {
                    singleton = Boolean.parseBoolean(value);
                } else {
                    otherParams.put(key, value);
                }
            }

            if (resourceClass == null || jndiAlias == null || factory == null) {
                throw new NamingException("could not load the resource.xml file");
            }

            JndiResourceDescriptor jrd = new JndiResourceDescriptor(resourceClass, description, scope, auth,
                    factory, singleton);
            for (Map.Entry<String, String> prm : otherParams.entrySet()) {
                jrd.add(new StringRefAddr(prm.getKey(), prm.getValue()));
            }
            xml.put(jndiAlias, jrd);
        }
    } catch (Exception e) {
        NamingException pp = new NamingException("could not initialize the JNDI local resources");
        pp.setRootCause(e);
        throw pp;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

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

/**
 * Will create a JNDI Context and register it as the initial context factory builder
 * /* w w w .  j  a va 2  s.  c  om*/
 * @return the context
 * @throws NamingException
 *             on any issue during initial context factory builder registration
 */
static JndiContext createJndiContext() throws NamingException {
    try {
        if (!NamingManager.hasInitialContextFactoryBuilder()) {
            JndiContext ctx = new JndiContext();
            NamingManager.setInitialContextFactoryBuilder(ctx);
            return ctx;
        } else {
            return (JndiContext) NamingManager.getInitialContext(null);
        }
    } catch (Exception e) {
        jqmlogger.error("Could not create JNDI context: " + e.getMessage());
        NamingException ex = new NamingException("Could not initialize JNDI Context");
        ex.setRootCause(e);
        throw ex;
    }
}

From source file:de.escidoc.core.admin.common.util.spring.RemoteJndiLocator.java

/**
 * Business interface is required for casting. If the interface does not
 * exist an exception is thrown./*  ww  w .  j  a  v  a 2s  . c  o m*/
 * 
 * @throws NamingException
 *             From the lookup
 */
public void afterPropertiesSet() throws NamingException {
    try {
        setInitialContextJndiProperties();
    } catch (WebserverSystemException e) {
        NamingException ex = new NamingException();
        ex.setRootCause(e);
        throw ex;
    }
    super.afterPropertiesSet();
}

From source file:org.alfresco.config.JndiObjectFactoryBean.java

@Override
protected Object lookup() throws NamingException {
    Object candidate = super.lookup();
    if (candidate instanceof DataSource) {
        Connection con = null;//from   w w w .  j a v  a 2  s  . c  om
        try {
            con = ((DataSource) candidate).getConnection();
        } catch (Exception e) {
            NamingException e1 = new NamingException("Unable to get connection from " + getJndiName());
            e1.setRootCause(e);
            throw e1;
        } finally {
            try {
                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
            }
        }
    }
    return candidate;
}

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

@Override
public void unbind(String name) throws NamingException {
    if (r != null && name.startsWith("rmi://")) {
        try {/*  www. ja  v a2s . c  o  m*/
            jqmlogger.debug("unbinding RMI name " + name);
            this.r.unbind(name.split("/")[3]);
        } catch (Exception e) {
            NamingException e1 = new NamingException("could not unbind RMI name");
            e1.setRootCause(e);
            throw e1;
        }
    } else {
        this.singletons.remove(name);
    }
}

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

@Override
public void bind(String name, Object obj) throws NamingException {
    jqmlogger.debug("binding [" + name + "] to a [" + obj.getClass().getCanonicalName() + "]");
    if (r != null && name.startsWith("rmi://")) {
        try {//from   www.ja va  2 s  .c  o m
            jqmlogger.debug(
                    "binding [" + name.split("/")[3] + "] to a [" + obj.getClass().getCanonicalName() + "]");
            this.r.bind(name.split("/")[3], (Remote) obj);
        } catch (Exception e) {
            NamingException e1 = new NamingException("could not bind RMI object");
            e1.setRootCause(e);
            throw e1;
        }
    } else {
        this.singletons.put(name, obj);
    }
}

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");
    }//  w  w  w.  ja  v a  2s. com
    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.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

private void doGssapiBind(final InnerRunnable innerRunnable) throws NamingException {
    File configFile = null;//from   w ww.j a v a2 s .  co  m
    try {
        Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences();
        boolean useKrb5SystemProperties = preferences
                .getBoolean(ConnectionCoreConstants.PREFERENCE_USE_KRB5_SYSTEM_PROPERTIES);
        String krb5LoginModule = preferences.getString(ConnectionCoreConstants.PREFERENCE_KRB5_LOGIN_MODULE);

        if (!useKrb5SystemProperties) {
            // Kerberos Configuration
            switch (connection.getConnectionParameter().getKrb5Configuration()) {
            case DEFAULT:
                // nothing 
                System.clearProperty("java.security.krb5.conf"); //$NON-NLS-1$
                break;
            case FILE:
                // use specified krb5.conf
                System.setProperty("java.security.krb5.conf", connection.getConnectionParameter() //$NON-NLS-1$
                        .getKrb5ConfigurationFile());
                break;
            case MANUAL:
                // write manual config parameters to connection specific krb5.conf file
                String fileName = Utils.getFilenameString(connection.getId()) + ".krb5.conf"; //$NON-NLS-1$
                configFile = ConnectionCorePlugin.getDefault().getStateLocation().append(fileName).toFile();
                String realm = connection.getConnectionParameter().getKrb5Realm();
                String host = connection.getConnectionParameter().getKrb5KdcHost();
                int port = connection.getConnectionParameter().getKrb5KdcPort();
                StringBuilder sb = new StringBuilder();
                sb.append("[libdefaults]").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$
                sb.append("default_realm = ").append(realm).append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$
                sb.append("[realms]").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$
                sb.append(realm).append(" = {").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$
                sb.append("kdc = ").append(host).append(":").append(port).append( //$NON-NLS-1$ //$NON-NLS-2$
                        ConnectionCoreConstants.LINE_SEPARATOR);
                sb.append("}").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$
                try {
                    FileUtils.writeStringToFile(configFile, sb.toString());
                } catch (IOException ioe) {
                    NamingException ne = new NamingException();
                    ne.setRootCause(ioe);
                    throw ne;
                }
                System.setProperty("java.security.krb5.conf", configFile.getAbsolutePath()); //$NON-NLS-1$
            }

            // Use our custom configuration so we don't need to mess with external configuration
            Configuration.setConfiguration(new InnerConfiguration(krb5LoginModule));
        }

        // Gets the TGT, either from native ticket cache or obtain new from KDC
        LoginContext lc = null;
        try {
            lc = new LoginContext(this.getClass().getName(), new InnerCallbackHandler());
            lc.login();
        } catch (LoginException le) {
            NamingException ne = new NamingException();
            ne.setRootCause(le);
            throw ne;
        }

        // Login to LDAP server, obtains a service ticket from KDC
        Subject.doAs(lc.getSubject(), (PrivilegedAction<Object>) () -> {
            try {
                context.reconnect(context.getConnectControls());
            } catch (NamingException ne) {
                innerRunnable.namingException = ne;
            }
            return null;
        });
    } finally {
        // delete temporary config file
        if (configFile != null && configFile.exists()) {
            configFile.delete();
        }
    }
}

From source file:org.mule.providers.ldap.util.DSManager.java

/**
 * Imports the LDIF entries packaged with the Eve JNDI provider jar into the
 * newly created system partition to prime it up for operation. Note that
 * only ou=system entries will be added - entries for other partitions
 * cannot be imported and will blow chunks.
 * /*www .  ja  va2 s.c  o  m*/
 * @throws NamingException
 *             if there are problems reading the ldif file and adding those
 *             entries to the system partition
 */
protected void importLdif(InputStream in) throws NamingException {
    try {
        Iterator iterator = new LdifReader(in);

        while (iterator.hasNext()) {
            Entry entry = (Entry) iterator.next();

            LdapDN dn = new LdapDN(entry.getDn());

            rootDSE.createSubcontext(dn, entry.getAttributes());
        }
    } catch (Exception e) {
        String msg = "failed while trying to parse system ldif file";
        NamingException ne = new LdapConfigurationException(msg);
        ne.setRootCause(e);
        throw ne;
    }
}