Example usage for java.lang Thread setContextClassLoader

List of usage examples for java.lang Thread setContextClassLoader

Introduction

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

Prototype

public void setContextClassLoader(ClassLoader cl) 

Source Link

Document

Sets the context ClassLoader for this Thread.

Usage

From source file:org.efaps.esjp.common.jasperreport.StandartReport_Base.java

/**
 * Gets the file.//from w w  w .  j a  v  a  2  s  .c om
 *
 * @param _parameter Parameter as passed by the eFasp API
 * @return file created
 * @throws EFapsException on error
 */
public File getFile(final Parameter _parameter) throws EFapsException {
    File ret = null;

    final String dataSourceClass = getDataSourceClass(_parameter);

    add2ReportParameter(_parameter);

    final Instance jasperInst = getJasperReportInstance(_parameter);
    if (jasperInst != null && jasperInst.isValid()) {
        final Checkout checkout = new Checkout(jasperInst);
        final InputStream iin = checkout.execute();
        try {
            DefaultJasperReportsContext.getInstance().setProperty(
                    "net.sf.jasperreports.query.executer.factory.eFaps",
                    EQLQueryExecuterFactory.class.getName());
            final LocalJasperReportsContext ctx = new LocalJasperReportsContext(
                    DefaultJasperReportsContext.getInstance());
            ctx.setFileResolver(new JasperFileResolver());
            ctx.setClassLoader(EFapsClassLoader.getInstance());

            ctx.setProperty("net.sf.jasperreports.subreport.runner.factory",
                    SubReportRunnerFactory.class.getName());
            ctx.setProperty("net.sf.jasperreports.query.executer.factory.eFaps",
                    EQLQueryExecuterFactory.class.getName());

            final JasperReport jasperReport = (JasperReport) JRLoader.loadObject(iin);
            iin.close();

            IeFapsDataSource dataSource = null;
            if (dataSourceClass != null) {
                final Class<?> clazz = Class.forName(dataSourceClass);
                final Method method = clazz.getMethod("init",
                        new Class[] { JasperReport.class, Parameter.class, JRDataSource.class, Map.class });
                dataSource = (IeFapsDataSource) clazz.newInstance();
                method.invoke(dataSource, jasperReport, _parameter, null, this.jrParameters);
            }
            if (dataSource != null) {
                this.jrParameters.put("EFAPS_SUBREPORT",
                        new SubReportContainer(_parameter, dataSource, this.jrParameters));
            }
            final ReportRunner runner = new ReportRunner(ctx, jasperReport, this.jrParameters, dataSource);
            final Thread t = new Thread(runner);
            t.setContextClassLoader(EFapsClassLoader.getInstance());
            t.start();

            while (t.isAlive()) {
                // add an abort criteria
            }

            // check for a file name, if null search in the properties
            if (getFileName() == null) {
                setFileName(getProperty(_parameter, "FileName"));
                // last chance search in the jasper Parameters
                if (getFileName() == null) {
                    setFileName((String) this.jrParameters.get("FileName"));
                }
            }
            final JasperPrint print = runner.getJasperPrint();
            LOG.debug("print created: '{}'", print);
            if (print != null) {
                ret = getFile(print, getMime(_parameter));
            }

        } catch (final ClassNotFoundException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.ClassNotFoundException", e);
        } catch (final SecurityException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.SecurityException", e);
        } catch (final NoSuchMethodException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.NoSuchMethodException", e);
        } catch (final InstantiationException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.InstantiationException", e);
        } catch (final IllegalAccessException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.IllegalAccessException", e);
        } catch (final IllegalArgumentException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.IllegalArgumentException", e);
        } catch (final InvocationTargetException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.InvocationTargetException", e);
        } catch (final JRException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.JRException", e);
        } catch (final IOException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.IOException", e);
        }
    }
    return ret;
}

From source file:org.rhq.enterprise.server.agent.EmbeddedAgentBootstrapService.java

/**
 * This starts the agent in a completely isolated classloader in a completely isolated thread.
 *
 * @see EmbeddedAgentBootstrapServiceMBean#startAgent()
 *//*from   w  w  w.j a v a 2 s.  co m*/
public void startAgent() throws Exception {
    //-- if this method signature changes, you must also change StartupServlet.startEmbeddedAgent

    if (!enabled.booleanValue()) {
        log.info("Will not start the embedded RHQ agent - it is disabled");
        return;
    }

    if ((agent == null) && (embeddedAgentDirectory != null)) {
        log.info("Starting the embedded RHQ Agent...");

        // we need to store the preferences prior to starting the agent
        if (resetConfigurationAtStartup.booleanValue()) {
            log.debug("Resetting the embedded agent's configuration back to its original factory settings");
            reloadAgentConfiguration();
            cleanDataDirectory();
        } else {
            log.debug("Loading the embedded agent's pre-existing configuration from preferences");
            prepareConfigurationPreferences();
        }

        // We need to build the agent's classloader so it is completely isolated.
        final URL[] jars = getEmbeddedAgentClasspath();
        final URL[] nativeDirs = getEmbeddedAgentNativeLibraryDirectories();
        final ClassLoader agentClassLoader = new EmbeddedAgentClassLoader(jars, nativeDirs);

        // we need to instantiate and start the agent in its own thread so it can have
        // a default context classloader that is our isolated classloader
        final Exception[] error = new Exception[1];
        final Object[] agentObject = new Object[1];

        Runnable agentRunnable = new Runnable() {
            public void run() {
                try {
                    Class<?> agentClass = agentClassLoader.loadClass("org.rhq.enterprise.agent.AgentMain");
                    Constructor<?> agentConstructor = agentClass.getConstructor(new Class[] { String[].class });
                    Object agentInstance = agentConstructor.newInstance(new Object[] { getAgentArguments() });

                    agentClass.getMethod("start", new Class[0]).invoke(agentInstance, new Object[0]);

                    agentObject[0] = agentInstance;
                    error[0] = null;
                } catch (Throwable t) {
                    agentObject[0] = null;
                    error[0] = new Exception("Cannot start the embedded agent. Cause: " + t, t);
                }
            }
        };

        // create our thread that starts the agent with the isolated class loader as its context
        Thread agentThread = new Thread(agentRunnable, "Embedded RHQ Agent Main");
        agentThread.setDaemon(true);
        agentThread.setContextClassLoader(agentClassLoader);
        agentThread.start();
        agentThread.join();

        // at this point in time, the embedded agent bootstrap thread has finished and
        // the agent should have been started
        if (error[0] != null) {
            log.error("Failed to start the embedded RHQ Agent. Cause: " + error[0]);
            throw error[0];
        }

        log.info("Embedded RHQ Agent has been started!");
        this.agent = agentObject[0];
    }

    return;
}

From source file:br.com.uol.runas.classloader.ClassLoaderGC.java

@SuppressWarnings({ "unchecked", "deprecation" })
private void releaseFromShutdownHooks(WeakReference<ClassLoader> classLoader) {
    final Map<Thread, Thread> hooks = (Map<Thread, Thread>) Reflections
            .getStaticFieldValue("java.lang.ApplicationShutdownHooks", "hooks");

    if (hooks != null) {
        final List<Thread> shutdownHooks = new ArrayList<>(hooks.keySet());

        for (Thread shutdownHook : shutdownHooks) {
            if (Objects.equals(classLoader.get(), shutdownHook.getContextClassLoader())) {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
                shutdownHook.start();//ww  w  .j av  a  2s. c  om
                try {
                    shutdownHook.join(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    shutdownHook.stop();
                }
                shutdownHook.setContextClassLoader(null);
            }
        }
    }
}

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

private JahiaFacebookUser facebookToJahiaUser(User facebookUser, String facebookToken) {
    JahiaFacebookUser jfu = null;//from   w  ww.  j  a v a  2  s  .  c  o  m

    // 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.nebulaframework.grid.cluster.manager.services.jobs.splitaggregate.SplitAggregateJobManager.java

/**
 * Starts given {@code SplitAggregateJob} on the Grid.
 * /* w ww  .  j  a  v a 2 s . co m*/
 * @param profile
 *            GridJobProfile
 */
@Override
public boolean startExecution(final GridJobProfile profile, ClassLoader classLoader) {

    // If valid GridJob Type
    if (profile.getJob() instanceof SplitAggregateGridJob) {

        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {

                // Allow Final Results
                profile.getFuture().setFinalResultSupported(true);

                // Create Task Tracker
                profile.setTaskTracker(GridJobTaskTracker.startTracker(profile, SplitAggregateJobManager.this));

                // Start Splitter & Aggregator for GridJob
                splitter.startSplitter(profile);
                aggregator.startAggregator(profile, SplitAggregateJobManager.this);

            }

        });

        t.setContextClassLoader(classLoader);
        t.start();

        return true;
    } else {
        return false;
    }

}

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 a  v  a 2s  .  co  m*/
    }

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

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 {// ww w .j av  a 2  s .  c  o m
        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 a  v a 2 s  .com*/
            if (portletClassLoader != null) {
                currentThread.setContextClassLoader(portletClassLoader);
            }

            removePortletFilters();

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

    _destroyable = false;
}

From source file:com.liferay.portal.util.LocalizationImpl.java

private String _getRootAttribute(String xml, String name, String defaultValue) {

    String value = null;//from   w  ww. jav a2  s .  c  o m

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            value = xmlStreamReader.getAttributeValue(null, name);
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }
    }

    if (Validator.isNull(value)) {
        value = defaultValue;
    }

    return value;
}