Example usage for javax.naming.spi NamingManager hasInitialContextFactoryBuilder

List of usage examples for javax.naming.spi NamingManager hasInitialContextFactoryBuilder

Introduction

In this page you can find the example usage for javax.naming.spi NamingManager hasInitialContextFactoryBuilder.

Prototype

public static boolean hasInitialContextFactoryBuilder() 

Source Link

Document

Determines whether an initial context factory builder has been set.

Usage

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

/**
 * Will create a JNDI Context and register it as the initial context factory builder
 * /*ww w  .j  av a2  s.c o  m*/
 * @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:io.pivotal.poc.gemfire.gtx.jndi.SimpleNamingContextBuilder.java

/**
 * Register the context builder by registering it with the JNDI NamingManager.
 * Note that once this has been done, {@code new InitialContext()} will always
 * return a context from this factory. Use the {@code emptyActivatedContextBuilder()}
 * static method to get an empty context (for example, in test methods).
 * @throws IllegalStateException if there's already a naming context builder
 * registered with the JNDI NamingManager
 *//*w  w  w .  ja v  a  2s . com*/
public void activate() throws IllegalStateException, NamingException {
    logger.info("Activating simple JNDI environment");
    synchronized (initializationLock) {
        if (!initialized) {
            if (NamingManager.hasInitialContextFactoryBuilder()) {
                throw new IllegalStateException(
                        "Cannot activate SimpleNamingContextBuilder: there is already a JNDI provider registered. "
                                + "Note that JNDI is a JVM-wide service, shared at the JVM system class loader level, "
                                + "with no reset option. As a consequence, a JNDI provider must only be registered once per JVM.");
            }
            NamingManager.setInitialContextFactoryBuilder(this);
            initialized = true;
        }
    }
    activated = this;
}

From source file:org.pentaho.reporting.engine.classic.core.testsupport.gold.GoldTestBase.java

@Before
public void setUp() throws Exception {
    Locale.setDefault(Locale.US);
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    // enforce binary compatibility for the xml-files so that comparing them can be faster.

    ClassicEngineBoot.getInstance().start();
    if (NamingManager.hasInitialContextFactoryBuilder() == false) {
        NamingManager.setInitialContextFactoryBuilder(new DebugJndiContextFactoryBuilder());
    }/*  www  .j  a  va  2s.c om*/

    localFontRegistry = new LocalFontRegistry();
    localFontRegistry.initialize();
}

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

public static void bruteForceInitialContextFactoryBuilder() {
    LOG.info("Modifying the naming subsystem to enable secure execution of scripts inside the server...");

    //it is important to synchronize on the NamingManager class because the get/setInitialContextFactoryBuilder
    //methods in that class are static synchronized. By holding the lock on the NamingManager class we prevent
    //any other thread to check for the initial context factory builder (and therefore de-facto do any JNDI lookup).
    synchronized (NamingManager.class) {

        if (NamingManager.hasInitialContextFactoryBuilder()) {
            //if anyone ever changes the implementation of the NamingManager, we will break here...
            //but as of now, we have no other option but to do this and wait for 
            //https://issues.jboss.org/browse/AS7-6109 to be resolved and incorporated into our underlying container

            try {
                Field f = NamingManager.class.getDeclaredField("initctx_factory_builder");
                f.setAccessible(true);//from  ww  w  . j  av  a  2s. co m

                if (originalBuilder == null) {
                    originalBuilder = (InitialContextFactoryBuilder) f.get(null);
                }

                f.set(null, null);
            } catch (Exception e) {
                LOG.error(
                        "Failed to install a custom initial context factory builder. RHQ installation is unsecure!",
                        e);

                return;
            }
        }

        try {
            InitialContextFactory defaultFactory = null;
            if (originalBuilder != null) {
                defaultFactory = originalBuilder.createInitialContextFactory(new Hashtable<String, String>());
            }

            NamingManager.setInitialContextFactoryBuilder(
                    new AccessCheckingInitialContextFactoryBuilder(defaultFactory, originalBuilder == null));
        } catch (Exception e) {
            LOG.error(
                    "Failed to install a custom initial context factory builder. RHQ installation is unsecure!",
                    e);

            if (originalBuilder != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Trying to restore the original initial context factory builder: "
                            + originalBuilder);
                }

                try {
                    NamingManager.setInitialContextFactoryBuilder(originalBuilder);
                } catch (Exception e2) {
                    LOG.error(
                            "Failed to restore the original initial context factory builder. The JNDI lookup may"
                                    + " not function properly from this point on...",
                            e2);
                }
            }
        }
    }
}

From source file:org.springframework.mock.jndi.SimpleNamingContextBuilder.java

/**
 * Register the context builder by registering it with the JNDI NamingManager.
 * Note that once this has been done, {@code new InitialContext()} will always
 * return a context from this factory. Use the {@code emptyActivatedContextBuilder()}
 * static method to get an empty context (for example, in test methods).
 * @throws IllegalStateException if there's already a naming context builder
 * registered with the JNDI NamingManager
 *//*  ww  w . j a v a2s.  c  om*/
public void activate() throws IllegalStateException, NamingException {
    logger.info("Activating simple JNDI environment");
    synchronized (initializationLock) {
        if (!initialized) {
            Assert.state(!NamingManager.hasInitialContextFactoryBuilder(),
                    "Cannot activate SimpleNamingContextBuilder: there is already a JNDI provider registered. "
                            + "Note that JNDI is a JVM-wide service, shared at the JVM system class loader level, "
                            + "with no reset option. As a consequence, a JNDI provider must only be registered once per JVM.");
            NamingManager.setInitialContextFactoryBuilder(this);
            initialized = true;
        }
    }
    activated = this;
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

public static void configureHibernate(Properties properties) throws Exception {
    if (sSessionFactory != null) {
        sSessionFactory.close();/* ww w. j  ava  2s  .  c  om*/
        sSessionFactory = null;
    }

    if (!NamingManager.hasInitialContextFactoryBuilder())
        NamingManager.setInitialContextFactoryBuilder(new LocalContext(null));

    sLog.info("Connecting to " + getProperty(properties, "connection.url"));
    ClassLoader classLoader = HibernateUtil.class.getClassLoader();
    sLog.debug("  -- class loader retrieved");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    sLog.debug("  -- document factory created");
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- document builder created");
    Document document = builder.parse(classLoader.getResource("hibernate.cfg.xml").openStream());
    sLog.debug("  -- hibernate.cfg.xml parsed");

    String dialect = getProperty(properties, "dialect");
    if (dialect != null)
        setProperty(document, "dialect", dialect);

    String idgen = getProperty(properties, "tmtbl.uniqueid.generator");
    if (idgen != null)
        setProperty(document, "tmtbl.uniqueid.generator", idgen);

    if (ApplicationProperty.HibernateClusterEnabled.isFalse())
        setProperty(document, "net.sf.ehcache.configurationResourceName", "ehcache-nocluster.xml");

    // Remove second level cache
    setProperty(document, "hibernate.cache.use_second_level_cache", "false");
    setProperty(document, "hibernate.cache.use_query_cache", "false");
    removeProperty(document, "hibernate.cache.region.factory_class");

    for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        if (name.startsWith("hibernate.") || name.startsWith("connection.")
                || name.startsWith("tmtbl.hibernate.")) {
            String value = properties.getProperty(name);
            if ("NULL".equals(value))
                removeProperty(document, name);
            else
                setProperty(document, name, value);
            if (!name.equals("connection.password"))
                sLog.debug("  -- set " + name + ": " + value);
            else
                sLog.debug("  -- set " + name + ": *****");
        }
    }

    String default_schema = getProperty(properties, "default_schema");
    if (default_schema != null)
        setProperty(document, "default_schema", default_schema);

    sLog.debug("  -- hibernate.cfg.xml altered");

    Configuration cfg = new Configuration();
    sLog.debug("  -- configuration object created");

    cfg.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- added entity resolver");

    cfg.configure(document);
    sLog.debug("  -- hibernate configured");

    fixSchemaInFormulas(cfg);

    UniqueIdGenerator.configure(cfg);

    (new _BaseRootDAO() {
        void setConf(Configuration cfg) {
            _BaseRootDAO.sConfiguration = cfg;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setConf(cfg);
    sLog.debug("  -- configuration set to _BaseRootDAO");

    sSessionFactory = cfg.buildSessionFactory();
    sLog.debug("  -- session factory created");

    (new _BaseRootDAO() {
        void setSF(SessionFactory fact) {
            _BaseRootDAO.sSessionFactory = fact;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setSF(sSessionFactory);
    sLog.debug("  -- session factory set to _BaseRootDAO");

    addBitwiseOperationsToDialect();
    sLog.debug("  -- bitwise operation added to the dialect if needed");

    DatabaseUpdate.update();
}