Java Code Examples for javax.naming.NamingException#setRootCause()

The following examples show how to use javax.naming.NamingException#setRootCause() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JndiContext.java    From jqm with Apache License 2.0 6 votes vote down vote up
/**
 * Will create a JNDI Context and register it as the initial context factory builder
 *
 * @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;
    }
}
 
Example 2
Source File: JndiContext.java    From jqm with Apache License 2.0 6 votes vote down vote up
@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
        {
            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);
    }
}
 
Example 3
Source File: JndiContext.java    From jqm with Apache License 2.0 6 votes vote down vote up
@Override
public void unbind(String name) throws NamingException
{
    if (r != null && name.startsWith("rmi://"))
    {
        try
        {
            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);
    }
}
 
Example 4
Source File: JndiRequestHandler.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public Response processRequest(final ObjectInputStream in, final ProtocolMetaData metaData) {

    final JNDIRequest req = new JNDIRequest();
    final JNDIResponse res = new JNDIResponse();
    res.setRequest(req);

    try {
        req.setMetaData(metaData);
        req.readExternal(in);
    } catch (Throwable e) {
        res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
        final NamingException namingException = new NamingException("Could not read jndi request");
        namingException.setRootCause(e);
        res.setResult(new ThrowableArtifact(namingException));

        if (LOGGER.isDebugEnabled()) {
            try {
                logRequestResponse(req, res);
            } catch (Exception ignore) {
                // no-op
            }
        }
    }
    return res;
}
 
Example 5
Source File: TomcatDataSource.java    From mdw with Apache License 2.0 5 votes vote down vote up
public DataSource getDataSource(String dataSourceName) throws NamingException {
    if (dataSources.get(dataSourceName) == null) {
        try {
            dataSources.put(dataSourceName, (DataSource)SpringAppContext.getInstance().getBean(dataSourceName));
        }
        catch (IOException ex) {
            NamingException ne = new NamingException(ex.getMessage());
            ne.setRootCause(ex);
            throw ne;
        }
    }
    return dataSources.get(dataSourceName);
}
 
Example 6
Source File: LocalContext.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public Object lookup(Name name) throws NamingException {
	if (name.isEmpty())
		return cloneCtx();

	Name nm = getMyComponents(name);
	String atom = nm.get(0);
	Object inter = iBindings.get(atom);

	if (nm.size() == 1) {
		if (inter == null)
			throw new NameNotFoundException(name + " not found");

		try {
			return NamingManager.getObjectInstance(inter, new CompositeName().add(atom), this, iEnv);
		} catch (Exception e) {
			NamingException ne = new NamingException("getObjectInstance failed");
			ne.setRootCause(e);
			throw ne;
		}
	} else {
		if (!(inter instanceof Context))
			throw new NotContextException(atom + " does not name a context");

		return ((Context) inter).lookup(nm.getSuffix(1));
	}
}
 
Example 7
Source File: LocalContext.java    From unitime with Apache License 2.0 5 votes vote down vote up
public Object next() throws NamingException {
	String name = (String) iNames.nextElement();
	Object obj = iBindings.get(name);

	try {
		obj = NamingManager.getObjectInstance(obj, new CompositeName().add(name), LocalContext.this, LocalContext.this.iEnv);
	} catch (Exception e) {
		NamingException ne = new NamingException("getObjectInstance failed");
		ne.setRootCause(e);
		throw ne;
	}

	return new Binding(name, obj);
}
 
Example 8
Source File: ResourceParser.java    From jqm with Apache License 2.0 5 votes vote down vote up
private static JndiResourceDescriptor fromDatabase(String alias) throws NamingException
{
    JndiObjectResource resource = null;

    try
    {
        if (!Helpers.isDbInitialized())
        {
            throw new IllegalStateException("cannot fetch a JNDI resource from DB when DB is not initialized");
        }

        try (DbConn cnx = Helpers.getNewDbSession())
        {
            resource = JndiObjectResource.select_alias(cnx, alias);

            JndiResourceDescriptor d = new JndiResourceDescriptor(resource.getType(), resource.getDescription(), null, resource.getAuth(),
                    resource.getFactory(), resource.getSingleton());
            for (JndiObjectResourceParameter prm : resource.getParameters(cnx))
            {
                d.add(new StringRefAddr(prm.getKey(), prm.getValue() != null ? prm.getValue() : ""));
                // null values forbidden (but equivalent to "" in Oracle!)
            }

            return d;
        }
    }
    catch (Exception e)
    {
        NamingException ex = new NamingException("Could not find a JNDI object resource of name " + alias);
        ex.setRootCause(e);
        throw ex;
    }
}
 
Example 9
Source File: IvmContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static ObjectFactory[] getFederatedFactories() throws NamingException {
    if (federatedFactories == null) {
        final Set<ObjectFactory> factories = new HashSet<>();
        final String urlPackagePrefixes = getUrlPackagePrefixes();
        if (urlPackagePrefixes == null) {
            return new ObjectFactory[0];
        }
        for (final StringTokenizer tokenizer = new StringTokenizer(urlPackagePrefixes, ":"); tokenizer.hasMoreTokens(); ) {
            final String urlPackagePrefix = tokenizer.nextToken();
            final String className = urlPackagePrefix + ".java.javaURLContextFactory";
            if (className.equals("org.apache.openejb.core.ivm.naming.java.javaURLContextFactory")) {
                continue;
            }
            try {
                final ClassLoader cl = ClassLoaderUtil.getContextClassLoader();
                final Class factoryClass = Class.forName(className, true, cl);
                final ObjectFactory factoryInstance = (ObjectFactory) factoryClass.newInstance();
                factories.add(factoryInstance);
            } catch (final ClassNotFoundException cnfe) {
                // no-op

            } catch (final Throwable e) {
                final NamingException ne = new NamingException("Federation failed: Cannot instantiate " + className);
                ne.setRootCause(e);
                throw ne;
            }
        }
        final Object[] temp = factories.toArray();
        federatedFactories = new ObjectFactory[temp.length];
        System.arraycopy(temp, 0, federatedFactories, 0, federatedFactories.length);
    }
    return federatedFactories;
}
 
Example 10
Source File: DelegatingContext.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.naming.Context#close()
 */
public void close() throws NamingException {
    final Context context = this.getInnermostDelegateContext();
    if (context == null) {
        return;
    }
    
    //Get a local reference so the member can be nulled earlier
    this.delegateContext = null;

    //Return the object to the Pool and then null the pool reference
    try {
        boolean valid = true;

        if (context instanceof FailureAwareContext) {
            FailureAwareContext failureAwareContext = (FailureAwareContext) context;
            if(failureAwareContext.hasFailed()) {
                valid = false;
            }
        }

        if (valid) {
            this.keyedObjectPool.returnObject(this.dirContextType, context);
        } else {
            this.keyedObjectPool.invalidateObject(this.dirContextType, context);
        }
    }
    catch (Exception e) {
        final NamingException namingException = new NamingException("Failed to return delegate Context to pool.");
        namingException.setRootCause(e);
        throw namingException;
    }
    finally {
        this.keyedObjectPool = null;
    }
}
 
Example 11
Source File: JavaStoredProcUtils.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Invoke a Stored Procedure
 *
 * @param ctx The execution context
 * @param procedureName The procedure to execute
 * @param arguments The procedure's arguments
 * @return The execution resut
 * @throws NamingException If we have had an error whil executing the stored procedure
 */
public static Object callStoredProcedure( LdapContext ctx, String procedureName, Object[] arguments )
    throws NamingException
{
    String language = "Java";

    Object responseObject;
    try
    {
        /**
         * Create a new stored procedure execution request.
         */
        StoredProcedureRequestImpl req = new StoredProcedureRequestImpl( 0, procedureName, language );

        /**
         * For each argument UTF-8-encode the type name
         * and Java-serialize the value
         * and add them to the request as a parameter object.
         */
        for ( int i = 0; i < arguments.length; i++ )
        {
            byte[] type;
            byte[] value;
            type = arguments[i].getClass().getName().getBytes( StandardCharsets.UTF_8 );
            value = SerializationUtils.serialize( ( Serializable ) arguments[i] );
            req.addParameter( type, value );
        }

        /**
         * Call the stored procedure via the extended operation
         * and get back its return value.
         */
        ExtendedRequest jndiReq = LdapApiServiceFactory.getSingleton().toJndi( req );
        ExtendedResponse resp = ctx.extendedOperation( jndiReq );

        /**
         * Restore a Java object from the return value.
         */
        byte[] responseStream = resp.getEncodedValue();
        responseObject = SerializationUtils.deserialize( responseStream );
    }
    catch ( Exception e )
    {
        NamingException ne = new NamingException();
        ne.setRootCause( e );
        throw ne;
    }

    return responseObject;
}
 
Example 12
Source File: ResourceParser.java    From jqm with Apache License 2.0 4 votes vote down vote up
private static void importXml() throws NamingException
{
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    try (InputStream is = ResourceParser.class.getClassLoader().getResourceAsStream(Helpers.resourceFile))
    {
        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<>();

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