Example usage for javax.naming Context createSubcontext

List of usage examples for javax.naming Context createSubcontext

Introduction

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

Prototype

public Context createSubcontext(String name) throws NamingException;

Source Link

Document

Creates and binds a new context.

Usage

From source file:org.jboss.test.NamingUtil.java

/**
 * Create test data. It needs to use org.jboss.naming.HttpNamingContextFactory since JNDI through RMI
 * is already secured and disallow bind/unbind/rebind operations.
 * // www  .  j a v a2s . c  o m
 *   
 *   
 * @param jndiName JNDI path where to bind data.
 * @param dataKey key under which data is bound
 * @param data Data object to bind. In case data is null last path element is considered subContext. 
 * @param serverHost host on which to create binding 
 * @throws Exception
 */
public static void createTestJNDIBinding(String jndiName, String dataKey, Object data, String serverHost,
        boolean useHAJNDI) throws Exception {

    log.debug("XXX");

    Context ctx = null;
    if (useHAJNDI) {
        ctx = NamingUtil.getFullHAInitialContext(serverHost);
    } else {
        ctx = NamingUtil.getFullInitialContext(serverHost);
    }

    String[] path = jndiName.split("/");
    String subPath = "";
    for (int i = 0; i < path.length; i++) {

        if (path[i].equals("")) {
            continue;
        }

        subPath = subPath + "/" + path[i];
        log.debug("creating subcontext=" + subPath);
        try {
            ctx.createSubcontext(subPath);
            log.debug("subcontext=" + subPath + " created.");
        } catch (NameAlreadyBoundException e) {
            // ignore
        }
    }

    if (data != null) {
        log.debug("bind s=" + subPath + ", dataKey=" + dataKey + ", data=" + data);
        ctx.bind(subPath + "/" + dataKey, data);
        log.debug(data + " bound.");
    }

    ctx.close();

}

From source file:org.josso.jb32.agent.JBossCatalinaNativeRealm.java

/** This creates a java:comp/env/security context that contains a
 securityMgr binding pointing to an AuthenticationManager implementation
 and a realmMapping binding pointing to a RealmMapping implementation.
 *//* w  w w . j av a  2s  .  c  o m*/
protected Context prepareENC() throws NamingException {

    if (logger.isDebugEnabled())
        logger.debug("JBossCatalinaRealm.prepareENC, Start");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    InitialContext iniCtx = new InitialContext();

    boolean securityContextExists = false;
    boolean isJaasSecurityManager = false;
    try {
        Context envCtx = (Context) iniCtx.lookup("java:comp/env");
        Context securityCtx = (Context) envCtx.lookup("security");
        securityContextExists = true;

        AuthenticationManager securityMgr = (AuthenticationManager) securityCtx.lookup("securityMgr");

        // If the Security Manager set in the web application ENC is not
        // a JaasSecurityManager, unbind the Security context and rebind it
        // with the JaasSecurityManager associated with the JOSSO Security Domain.
        // Note: the jboss-web.xml file of the partner application MUST not have an
        // entry referring to a security domain.
        if (!(securityMgr instanceof JaasSecurityManager)) {
            Util.unbind(envCtx, "security");
        } else
            isJaasSecurityManager = true;
    } catch (NamingException e) {
        // No Security Context found
    }

    // If we do not have a SecurityContext create it
    Context envCtx = null;
    if (!securityContextExists) {
        Thread currentThread = Thread.currentThread();
        if (logger.isDebugEnabled())
            logger.debug("Creating ENC using ClassLoader: " + loader);
        ClassLoader parent = loader.getParent();
        while (parent != null) {

            if (logger.isDebugEnabled())
                logger.debug(".." + parent);

            parent = parent.getParent();
        }

        envCtx = (Context) iniCtx.lookup("java:comp");
        envCtx = envCtx.createSubcontext("env");
    } else
        envCtx = (Context) iniCtx.lookup("java:comp/env");

    // If the Security Manager binded is not a JaasSecurityManager, rebind using
    // the Security Manager associated with the JOSSO Security Domain.
    if (!isJaasSecurityManager) {
        // Prepare the Security JNDI subcontext
        if (logger.isDebugEnabled())
            logger.debug("Linking security/securityMgr to JNDI name: " + JOSSO_SECURITY_DOMAIN);

        Util.bind(envCtx, "security/securityMgr", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/realmMapping", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/security-domain", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/subject", new LinkRef(JOSSO_SECURITY_DOMAIN + "/subject"));
    }

    if (logger.isDebugEnabled())
        logger.debug("JBossCatalinaRealm.prepareENC, End");

    return (Context) iniCtx.lookup("java:comp/env/security");
}

From source file:org.josso.jb32.agent.JBossCatalinaRealm.java

/** This creates a java:comp/env/security context that contains a
 securityMgr binding pointing to an AuthenticationManager implementation
 and a realmMapping binding pointing to a RealmMapping implementation.
 */// ww w.j  a v  a2  s  .co m
protected Context prepareENC() throws NamingException {

    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    InitialContext iniCtx = new InitialContext();

    boolean securityContextExists = false;
    boolean isJaasSecurityManager = false;
    try {
        Context envCtx = (Context) iniCtx.lookup("java:comp/env");
        Context securityCtx = (Context) envCtx.lookup("security");
        securityContextExists = true;

        AuthenticationManager securityMgr = (AuthenticationManager) securityCtx.lookup("securityMgr");

        // If the Security Manager set in the web application ENC is not
        // a JaasSecurityManager, unbind the Security context and rebind it
        // with the JaasSecurityManager associated with the JOSSO Security Domain.
        // Note: the jboss-web.xml file of the partner application MUST not have an
        // entry referring to a security domain.
        if (!(securityMgr instanceof JaasSecurityManager)) {
            Util.unbind(envCtx, "security");
        } else
            isJaasSecurityManager = true;
    } catch (NamingException e) {
        // No Security Context found
    }

    // If we do not have a SecurityContext create it
    Context envCtx = null;
    if (!securityContextExists) {
        Thread currentThread = Thread.currentThread();
        logger.debug("Creating ENC using ClassLoader: " + loader);
        ClassLoader parent = loader.getParent();
        while (parent != null) {
            logger.debug(".." + parent);
            parent = parent.getParent();
        }

        envCtx = (Context) iniCtx.lookup("java:comp");
        envCtx = envCtx.createSubcontext("env");
    } else
        envCtx = (Context) iniCtx.lookup("java:comp/env");

    // If the Security Manager binded is not a JaasSecurityManager, rebind using
    // the Security Manager associated with the JOSSO Security Domain.
    if (!isJaasSecurityManager) {
        // Prepare the Security JNDI subcontext
        logger.debug("Linking security/securityMgr to JNDI name: " + JOSSO_SECURITY_DOMAIN);
        Util.bind(envCtx, "security/securityMgr", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/realmMapping", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/security-domain", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/subject", new LinkRef(JOSSO_SECURITY_DOMAIN + "/subject"));
    }

    logger.debug("JBossCatalinaRealm.prepareENC, End");

    return (Context) iniCtx.lookup("java:comp/env/security");
}

From source file:org.nuxeo.runtime.binding.ServiceBindings.java

public static void createAlias(InitialContext ctx, String existingName, String aliasName)
        throws NamingException {
    LinkRef link = new LinkRef(existingName);
    Context aliasCtx = ctx;
    Name name = ctx.getNameParser("").parse(aliasName);
    int len = name.size() - 1;
    String atom = name.get(len);//  www.  j  a  v  a2s  .co m
    for (int i = 0; i < len; i++) {
        String comp = name.get(i);
        try {
            aliasCtx = (Context) aliasCtx.lookup(comp);
        } catch (NameNotFoundException e) {
            aliasCtx = aliasCtx.createSubcontext(comp);
        }
    }

    aliasCtx.rebind(atom, link);

    if (log.isDebugEnabled()) {
        log.debug("Created JNDI link [" + aliasName + "] pointing to [" + existingName + "]");
    }
}

From source file:org.nuxeo.runtime.datasource.DataSourceComponent.java

@Override
public void applicationStarted(ComponentContext context) {
    if (namingContext != null) {
        return;//from w w  w  .ja va  2 s .  c  om
    }
    namingContext = NuxeoContainer.getRootContext();
    // allocate datasource sub-contexts
    Name comp;
    try {
        comp = new CompositeName(DataSourceHelper.getDataSourceJNDIPrefix());
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
    Context ctx = namingContext;
    for (int i = 0; i < comp.size(); i++) {
        try {
            ctx = (Context) ctx.lookup(comp.get(i));
        } catch (NamingException e) {
            try {
                ctx = ctx.createSubcontext(comp.get(i));
            } catch (NamingException e1) {
                throw new RuntimeException(e1);
            }
        }
    }
    // bind datasources
    for (DataSourceDescriptor datasourceDesc : datasources.values()) {
        bindDataSource(datasourceDesc);
    }
    // bind links
    for (DataSourceLinkDescriptor linkDesc : links.values()) {
        bindDataSourceLink(linkDesc);
    }
}

From source file:org.settings4j.connector.JNDIConnector.java

private static void createParentContext(final Context ctx, final String key) throws NamingException {
    // here we need to break by the specified delimiter

    LOG.debug("createParentContext: {}", key);

    final String[] path = key.split("/");

    final int lastIndex = path.length - 1;

    Context tmpCtx = ctx;

    for (int i = 0; i < lastIndex; i++) {
        Object obj = null;//from   w w w. j a  v  a2  s  .c om
        try {
            obj = tmpCtx.lookup(path[i]);
        } catch (@SuppressWarnings("unused") final NameNotFoundException e) {
            LOG.debug("obj is null and subcontext will be generated: {}", path[i]);
        }

        if (obj == null) {
            tmpCtx = tmpCtx.createSubcontext(path[i]);
            LOG.debug("createSubcontext: {}", path[i]);
        } else if (obj instanceof Context) {
            tmpCtx = (Context) obj;
        } else {
            throw new RuntimeException(
                    "Illegal node/branch clash. At branch value '" + path[i] + "' an Object was found: " + obj);
        }
    }
}

From source file:org.settings4j.connector.JNDIConnectorTest.java

/**
 * SmokeTest: tests if the {@link #setTomcatJNDIContextProperties()} works which is required for all other
 * TestCases.//from w w  w .j  av  a2s  . c  o m
 *
 * @throws Exception in case of an error
 */
@Test
public void testSmokeTest() throws Exception {
    LOG.info("START: testJNDIConnectorWithoutJNDI");
    // Set JNDI Tomcat Configs
    setTomcatJNDIContextProperties();
    final InitialContext initialContext = new InitialContext();
    Context tmpCtx = initialContext.createSubcontext("java:");
    tmpCtx = tmpCtx.createSubcontext("comp");
    tmpCtx = tmpCtx.createSubcontext("env");
    tmpCtx.bind("testKey", "testValue");

    // start getting the JNDI Resource
    final Context envCtx = (Context) new InitialContext().lookup("java:/comp/env");
    final Object testValue = envCtx.lookup("testKey");

    assertThat(testValue, is((Object) "testValue"));

}

From source file:org.sonar.server.database.JndiDatabaseConnector.java

private void createJNDISubContexts(Context ctx, String jndiBinding) throws NamingException {
    Name name = new CompositeName(jndiBinding);
    for (int i = 0; i < name.size() - 1; i++) {
        String namingContext = name.get(i);
        try {//ww w .j av  a2  s.  c o  m
            Object obj = ctx.lookup(namingContext);
            if (!(obj instanceof Context)) {
                throw new NamingException(namingContext + " is not a JNDI Context");
            }
        } catch (NameNotFoundException ex) {
            ctx = ctx.createSubcontext(namingContext);
        }
    }
}

From source file:org.squale.jraf.bootstrap.naming.NamingHelper.java

/**
 * Bind le couple nom/valeur dans le contexte jndi.
 * @param in_context contexte jndi racine
 * @param in_name nom/*from  ww  w.ja  v  a  2 s.  c  om*/
 * @param in_value valeur
 * @throws NamingException
 */
public static void bind(Context in_context, String in_name, Object in_value) throws JrafConfigException {

    if (log.isDebugEnabled()) {
        log.debug("binding : " + in_name);
    }
    String lc_name = in_name;

    try {
        in_context.rebind(lc_name, in_value);
    } catch (NamingException e) {

        try {
            Name n = in_context.getNameParser("").parse(lc_name);
            while (n.size() > 1) {
                String ctxName = n.get(0);

                Context subctx = null;
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("lookup: " + ctxName);
                    }
                    subctx = (Context) in_context.lookup(ctxName);
                } catch (NameNotFoundException nfe) {
                }

                if (subctx != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Found subcontext: " + ctxName);
                    }
                    in_context = subctx;
                } else {
                    //               log.info("Creating subcontext: " + ctxName);
                    in_context = in_context.createSubcontext(ctxName);
                }
                n = n.getSuffix(1);
            }
            if (log.isDebugEnabled()) {
                log.debug("binding: " + n);
            }
            in_context.rebind(n, in_value);
        } catch (NamingException e1) {
            log.error("Impossible de recupere l'objet dans JNDI.", e);
            throw new JrafConfigException("Impossible de recupere l'objet dans JNDI.", e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Bound name: " + in_name);
    }
}

From source file:org.wso2.carbon.appfactory.ext.datasource.ApplicationAwareDataSourceRepository.java

private void checkAndCreateJNDISubContexts(Context context, String jndiName) throws DataSourceException {
    String[] tokens = jndiName.split("/");
    Context tmpCtx;/*from w w  w  .j ava 2 s .  c o  m*/
    String token;
    for (int i = 0; i < tokens.length - 1; i++) {
        token = tokens[i];
        tmpCtx = this.lookupJNDISubContext(context, token);
        if (tmpCtx == null) {
            try {
                tmpCtx = context.createSubcontext(token);
            } catch (NamingException e) {
                throw new DataSourceException(
                        "Error in creating JNDI subcontext '" + context + "/" + token + ": " + e.getMessage(),
                        e);
            }
        }
        context = tmpCtx;
    }
}