Example usage for java.lang Thread getContextClassLoader

List of usage examples for java.lang Thread getContextClassLoader

Introduction

In this page you can find the example usage for java.lang Thread getContextClassLoader.

Prototype

@CallerSensitive
public ClassLoader getContextClassLoader() 

Source Link

Document

Returns the context ClassLoader for this thread.

Usage

From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected void executeTool(String toolClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        public void checkPermission(Permission permission) {
        }//from w  ww  .  j  a  v a  2s  .c  om

        public void checkExit(int status) {
            throw new SecurityException();
        }

    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(toolClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (ite.getCause() instanceof SecurityException) {
        } else {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.clearProperty("org.apache.commons.logging.Log");

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:org.apache.solr.handler.clustering.carrot2.CarrotClusteringEngine.java

@Override
@SuppressWarnings("rawtypes")
public String init(NamedList config, final SolrCore core) {
    this.core = core;

    String result = super.init(config, core);
    final SolrParams initParams = SolrParams.toSolrParams(config);

    // Initialization attributes for Carrot2 controller.
    HashMap<String, Object> initAttributes = new HashMap<>();

    // Customize Carrot2's resource lookup to first look for resources
    // using Solr's resource loader. If that fails, try loading from the classpath.
    ResourceLookup resourceLookup = new ResourceLookup(
            // Solr-specific resource loading.
            new SolrResourceLocator(core, initParams),
            // Using the class loader directly because this time we want to omit the prefix
            new ClassLoaderLocator(core.getResourceLoader().getClassLoader()));

    DefaultLexicalDataFactoryDescriptor.attributeBuilder(initAttributes).resourceLookup(resourceLookup);

    // Make sure the requested Carrot2 clustering algorithm class is available
    String carrotAlgorithmClassName = initParams.get(CarrotParams.ALGORITHM);
    try {/*from w  ww.j  a  va  2  s  .c  o  m*/
        this.clusteringAlgorithmClass = core.getResourceLoader().findClass(carrotAlgorithmClassName,
                IClusteringAlgorithm.class);
    } catch (SolrException s) {
        if (!(s.getCause() instanceof ClassNotFoundException)) {
            throw s;
        }
    }

    // Load Carrot2-Workbench exported attribute XMLs based on the 'name' attribute
    // of this component. This by-name convention lookup is used to simplify configuring algorithms.
    String componentName = initParams.get(ClusteringEngine.ENGINE_NAME);
    log.info("Initializing Clustering Engine '"
            + MoreObjects.firstNonNull(componentName, "<no 'name' attribute>") + "'");

    if (!Strings.isNullOrEmpty(componentName)) {
        IResource[] attributeXmls = resourceLookup.getAll(componentName + "-attributes.xml");
        if (attributeXmls.length > 0) {
            if (attributeXmls.length > 1) {
                log.warn("More than one attribute file found, first one will be used: "
                        + Arrays.toString(attributeXmls));
            }

            Thread ct = Thread.currentThread();
            ClassLoader prev = ct.getContextClassLoader();
            try {
                ct.setContextClassLoader(core.getResourceLoader().getClassLoader());

                AttributeValueSets avs = AttributeValueSets.deserialize(attributeXmls[0].open());
                AttributeValueSet defaultSet = avs.getDefaultAttributeValueSet();
                initAttributes.putAll(defaultSet.getAttributeValues());
            } catch (Exception e) {
                throw new SolrException(ErrorCode.SERVER_ERROR,
                        "Could not read attributes XML for clustering component: " + componentName, e);
            } finally {
                ct.setContextClassLoader(prev);
            }
        }
    }

    // Extract solrconfig attributes, they take precedence.
    extractCarrotAttributes(initParams, initAttributes);

    // Customize the stemmer and tokenizer factories. The implementations we provide here
    // are included in the code base of Solr, so that it's possible to refactor
    // the Lucene APIs the factories rely on if needed.
    // Additionally, we set a custom lexical resource factory for Carrot2 that
    // will use both Carrot2 default stop words as well as stop words from
    // the StopFilter defined on the field.
    final AttributeBuilder attributeBuilder = BasicPreprocessingPipelineDescriptor
            .attributeBuilder(initAttributes);
    attributeBuilder.lexicalDataFactory(SolrStopwordsCarrot2LexicalDataFactory.class);
    if (!initAttributes.containsKey(BasicPreprocessingPipelineDescriptor.Keys.TOKENIZER_FACTORY)) {
        attributeBuilder.tokenizerFactory(LuceneCarrot2TokenizerFactory.class);
    }
    if (!initAttributes.containsKey(BasicPreprocessingPipelineDescriptor.Keys.STEMMER_FACTORY)) {
        attributeBuilder.stemmerFactory(LuceneCarrot2StemmerFactory.class);
    }

    // Pass the schema (via the core) to SolrStopwordsCarrot2LexicalDataFactory.
    initAttributes.put("solrCore", core);

    // Carrot2 uses current thread's context class loader to get
    // certain classes (e.g. custom tokenizer/stemmer) at initialization time.
    // To make sure classes from contrib JARs are available,
    // we swap the context class loader for the time of clustering.
    Thread ct = Thread.currentThread();
    ClassLoader prev = ct.getContextClassLoader();
    try {
        ct.setContextClassLoader(core.getResourceLoader().getClassLoader());
        this.controller.init(initAttributes);
    } finally {
        ct.setContextClassLoader(prev);
    }

    SchemaField uniqueField = core.getLatestSchema().getUniqueKeyField();
    if (uniqueField == null) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                CarrotClusteringEngine.class.getSimpleName() + " requires the schema to have a uniqueKeyField");
    }
    this.idFieldName = uniqueField.getName();

    return result;
}

From source file:org.nuxeo.ecm.activity.ActivityStreamServiceImpl.java

protected void activatePersistenceProvider() {
    Thread thread = Thread.currentThread();
    ClassLoader last = thread.getContextClassLoader();
    try {//www.j a v a  2s.  com
        thread.setContextClassLoader(PersistenceProvider.class.getClassLoader());
        PersistenceProviderFactory persistenceProviderFactory = Framework
                .getLocalService(PersistenceProviderFactory.class);
        persistenceProvider = persistenceProviderFactory.newProvider(ACTIVITIES_PROVIDER);
        persistenceProvider.openPersistenceUnit();
    } finally {
        thread.setContextClassLoader(last);
    }
}

From source file:com.liferay.portlet.InvokerPortletImpl.java

public void init(PortletConfig portletConfig) throws PortletException {
    _portletConfigImpl = (PortletConfigImpl) portletConfig;

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    ClassLoader portletClassLoader = getPortletClassLoader();

    try {//from  w  w w  .  jav  a  2 s . c om
        if (portletClassLoader != null) {
            currentThread.setContextClassLoader(portletClassLoader);
        }

        _portlet.init(portletConfig);
    } finally {
        if (portletClassLoader != null) {
            currentThread.setContextClassLoader(contextClassLoader);
        }
    }

    _destroyable = true;
}

From source file:com.liferay.portlet.InvokerPortletImpl.java

public void destroy() {
    if (_destroyable) {
        Thread currentThread = Thread.currentThread();

        ClassLoader contextClassLoader = currentThread.getContextClassLoader();

        ClassLoader portletClassLoader = getPortletClassLoader();

        try {/*  w  ww .j  ava  2 s.  c o m*/
            if (portletClassLoader != null) {
                currentThread.setContextClassLoader(portletClassLoader);
            }

            removePortletFilters();

            _portlet.destroy();
        } finally {
            if (portletClassLoader != null) {
                currentThread.setContextClassLoader(contextClassLoader);
            }
        }
    }

    _destroyable = false;
}

From source file:org.jahia.services.usermanager.facebook.JahiaUserManagerFacebookProvider.java

private JahiaFacebookUser facebookToJahiaUser(User facebookUser, String facebookToken) {
    JahiaFacebookUser jfu = null;//  w w w. jav  a 2s.  com

    // Map facebook properties to jahia properties
    UserProperties userProps = new FacebookPropertiesMapping(facebookUser, facebookToken).getUserProperties();

    // Create the jahia facebook user with the proper properties
    jfu = new JahiaFacebookUser(JahiaUserManagerFacebookProvider.PROVIDER_NAME, facebookUser.getId(),
            facebookUser.getId(), userProps);

    try {

        Thread currentThread = null;
        ClassLoader backupClassLoader = null;
        ClassLoader classLoader = this.getClass().getClassLoader();

        try {
            if (classLoader != null) {
                currentThread = Thread.currentThread();
                backupClassLoader = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(classLoader);
            }
            // Update cache
            if (jfu != null) {
                // new cache to populate : cross providers only based upon names...
                mProvidersUserCache.put("k" + jfu.getUserKey(), jfu);

                // name storage for speed
                mUserCache.put("n" + jfu.getUsername(), new JahiaUserWrapper(jfu));
                mProvidersUserCache.put("n" + jfu.getUsername(), jfu);
            }
            // use wrappers in local cache
            mUserCache.put("k" + jfu.getUserKey(), new JahiaUserWrapper(jfu));
        } finally {
            if (backupClassLoader != null) {
                currentThread.setContextClassLoader(backupClassLoader);
            }
        }
    } catch (Exception e) {
        logger.error("Error updating user cache for JFU=" + jfu.toString(), e);
    }

    // Perform a lookup to check if we already have this user in the JCR
    JCRUser jcrUser = (JCRUser) jcrUserManagerProvider.lookupExternalUser(jfu);

    // If we don't have this user yet in the JCR, perform the deploy
    if (jcrUser == null) {

        try {
            // Deploy and then lookup to get the JCR User instance
            JCRStoreService.getInstance().deployExternalUser(jfu);
            jcrUser = (JCRUser) jcrUserManagerProvider.lookupExternalUser(jfu);
        } catch (RepositoryException e) {
            logger.error("Error deploying external user '" + jfu.getUsername() + "' for provider '"
                    + PROVIDER_NAME + "' into JCR repository. Cause: " + e.getMessage(), e);
        }
    }
    return jfu;
}

From source file:org.batoo.jpa.community.test.BaseCoreTest.java

/**
 * Sets up the entity manager factory./*  w w  w . j a  va2s  .c  o m*/
 * 
 * @param puName
 *            the persistence unit name
 * @return the entity manager factory
 * 
 * @since 2.0.0
 */
protected EntityManagerFactoryImpl setupEmf(String puName) {
    final Thread currentThread = Thread.currentThread();

    if (this.oldContextClassLoader != null) {
        currentThread.setContextClassLoader(this.oldContextClassLoader);
    }

    this.oldContextClassLoader = currentThread.getContextClassLoader();

    final TestClassLoader cl = new TestClassLoader(this.oldContextClassLoader);
    currentThread.setContextClassLoader(cl);
    cl.setRoot(this.getRootPackage());

    return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(puName);
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.WebApplicationContext.java

/** Stop the web application.
 * Handlers for resource, servlet, filter and security are removed
 * as they are recreated and configured by any subsequent call to start().
 * @exception InterruptedException /*from w ww. j av a  2 s  .co  m*/
 */
protected void doStop() throws Exception {
    MultiException mex = new MultiException();

    Thread thread = Thread.currentThread();
    ClassLoader lastContextLoader = thread.getContextClassLoader();

    try {
        // Context listeners
        if (_contextListeners != null) {
            if (_webAppHandler != null) {
                ServletContextEvent event = new ServletContextEvent(getServletContext());

                for (int i = LazyList.size(_contextListeners); i-- > 0;) {
                    try {
                        ((ServletContextListener) LazyList.get(_contextListeners, i)).contextDestroyed(event);
                    } catch (Exception e) {
                        mex.add(e);
                    }
                }
            }
        }
        _contextListeners = null;

        // Stop the context
        try {
            super.doStop();
        } catch (Exception e) {
            mex.add(e);
        }

        // clean up
        clearSecurityConstraints();

        if (_webAppHandler != null)
            removeHandler(_webAppHandler);
        _webAppHandler = null;

        if (_errorPages != null)
            _errorPages.clear();
        _errorPages = null;

        _webApp = null;
        _webInf = null;

        _configurations = null;

    } finally {
        thread.setContextClassLoader(lastContextLoader);
    }

    if (mex != null)
        mex.ifExceptionThrow();
}

From source file:io.github.divinespear.maven.plugin.JpaSchemaGeneratorMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
        log.info("schema generation is skipped.");
        return;/*from   w  ww  .  j  ava2 s  . c om*/
    }

    if (this.outputDirectory != null && !this.outputDirectory.exists()) {
        this.outputDirectory.mkdirs();
    }

    final ClassLoader classLoader = this.getProjectClassLoader();
    // driver load hack
    // http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
    if (StringUtils.isNotBlank(this.jdbcDriver)) {
        try {
            Driver driver = (Driver) classLoader.loadClass(this.jdbcDriver).newInstance();
            DriverManager.registerDriver(driver);
        } catch (Exception e) {
            throw new MojoExecutionException("Dependency for driver-class " + this.jdbcDriver + " is missing!",
                    e);
        }
    }

    // generate schema
    Thread thread = Thread.currentThread();
    ClassLoader currentClassLoader = thread.getContextClassLoader();
    try {
        thread.setContextClassLoader(classLoader);
        this.generate();
    } catch (Exception e) {
        throw new MojoExecutionException("Error while running", e);
    } finally {
        thread.setContextClassLoader(currentClassLoader);
    }

    // post-process
    try {
        this.postProcess();
    } catch (IOException e) {
        throw new MojoExecutionException("Error while post-processing script file", e);
    }
}