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:com.liferay.portal.util.LocalizationImpl.java

public String removeLocalization(String xml, String key, String requestedLanguageId, boolean cdata,
        boolean localized) {

    if (Validator.isNull(xml)) {
        return StringPool.BLANK;
    }/*from   w ww .j  ava  2s  . c  om*/

    xml = _sanitizeXML(xml);

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = 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));

        String availableLocales = StringPool.BLANK;
        String defaultLanguageId = StringPool.BLANK;

        // Read root node

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

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);
            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        if ((availableLocales != null) && (availableLocales.indexOf(requestedLanguageId) != -1)) {

            availableLocales = StringUtil.remove(availableLocales, requestedLanguageId, StringPool.COMMA);

            UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

            XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

            xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

            xmlStreamWriter.writeStartDocument();
            xmlStreamWriter.writeStartElement(_ROOT);

            if (localized) {
                xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
                xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
            }

            _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.writeEndDocument();

            xmlStreamWriter.close();
            xmlStreamWriter = null;

            xml = unsyncStringWriter.toString();
        }
    } 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 (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}

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

public String updateLocalization(String xml, String key, String value, String requestedLanguageId,
        String defaultLanguageId, boolean cdata, boolean localized) {

    xml = _sanitizeXML(xml);/*from   w w w . j a  v  a2s .  co  m*/

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = 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));

        String availableLocales = StringPool.BLANK;

        // Read root node

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

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);

            if (Validator.isNull(availableLocales)) {
                availableLocales = defaultLanguageId;
            }

            if (availableLocales.indexOf(requestedLanguageId) == -1) {
                availableLocales = StringUtil.add(availableLocales, requestedLanguageId, StringPool.COMMA);
            }
        }

        UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

        xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

        xmlStreamWriter.writeStartDocument();
        xmlStreamWriter.writeStartElement(_ROOT);

        if (localized) {
            xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
            xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
        }

        _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

        xmlStreamWriter.writeStartElement(key);

        if (localized) {
            xmlStreamWriter.writeAttribute(_LANGUAGE_ID, requestedLanguageId);
        }

        if (cdata) {
            xmlStreamWriter.writeCData(value);
        } else {
            xmlStreamWriter.writeCharacters(value);
        }

        xmlStreamWriter.writeEndElement();
        xmlStreamWriter.writeEndElement();
        xmlStreamWriter.writeEndDocument();

        xmlStreamWriter.close();
        xmlStreamWriter = null;

        xml = unsyncStringWriter.toString();
    } 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 (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}

From source file:architecture.ee.plugin.impl.PluginManagerImpl.java

public void preInit() throws PluginException {

    if (ApplicationHelper.isSetupComplete()) {
        log.debug("Pre initializing");
        if (!pluginDao.doesPluginTableExist()) {
            log.warn(/*from   w w w .j  a  v a2 s .  c  om*/
                    "Plugin table does not exist, this is probably do to an upgrade task not being completed yet.");
        } else {
            File deployDir = ApplicationHelper.getRepository().getFile("plugins");
            if (deployDir.exists()) {
                File files[] = deployDir.listFiles(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.endsWith(".jar");
                    }
                });
                for (File file : files) {
                    try {
                        installPlugin(file);
                        try {
                            log.debug((new StringBuilder()).append("Deleting plugin jar ")
                                    .append(file.getName()).toString());
                            FileUtils.forceDelete(file);
                        } catch (IOException e) {
                            log.error(e.getMessage(), e);
                        }
                    } catch (Exception e) {
                        log.error(e);
                        log.warn((new StringBuilder()).append("Renaming broken plugin ").append(file.getName())
                                .append(" to ").append(file.getName()).append("_broken.").toString());
                    }
                    if (!file.renameTo(new File(deployDir,
                            (new StringBuilder()).append(file.getName()).append("_broken").toString()))) {
                        log.error((new StringBuilder()).append("Unable to rename plugin ")
                                .append(file.getName()).toString());
                    }
                }
            }
            pluginDirs.clear();
            plugins.clear();
            pluginMeta.clear();

            File pluginDirectory = ApplicationHelper.getRepository().getFile("plugins");
            try {
                FileUtils.deleteDirectory(pluginDirectory);
            } catch (IOException e) {
                throw new PluginException(e);
            }

            pluginDirectory.mkdirs();
            List<PluginEntityObject> pluginBeans = getPluginBeans();
            createPluginCacheDirectories(pluginBeans);

            Thread currentThread = Thread.currentThread();
            currentThread.setContextClassLoader(createPluginChainingClassloader());

            PluginCacheConfigurator configurator = new PluginCacheConfigurator(pluginCache);
            for (PluginEntityObject bean : pluginBeans) {
                File currentDir = new File(pluginDirectory, bean.getName());
                configurator.configure(currentDir, bean.getName());
            }
            List<String> paths = PluginUtils.getDevPluginPaths();
            for (String path : paths) {
                File dir = new File(path);
                if (dir.exists())
                    configurator.configure(dir, dir.getName());
            }
        }
    }
}

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

public String getLocalization(String xml, String requestedLanguageId, boolean useDefault) {

    String value = _getCachedValue(xml, requestedLanguageId, useDefault);

    if (value != null) {
        return value;
    } else {/* w  w  w.j a  v a  2 s .  c o m*/
        value = StringPool.BLANK;
    }

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    String priorityLanguageId = null;

    Locale requestedLocale = LocaleUtil.fromLanguageId(requestedLanguageId);

    if (useDefault && LanguageUtil.isDuplicateLanguageCode(requestedLocale.getLanguage())) {

        Locale priorityLocale = LanguageUtil.getLocale(requestedLocale.getLanguage());

        if (!requestedLanguageId.equals(priorityLanguageId)) {
            priorityLanguageId = LocaleUtil.toLanguageId(priorityLocale);
        }
    }

    if (!Validator.isXml(xml)) {
        if (useDefault || requestedLanguageId.equals(systemDefaultLanguageId)) {

            value = xml;
        }

        _setCachedValue(xml, requestedLanguageId, useDefault, value);

        return value;
    }

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

        String defaultLanguageId = StringPool.BLANK;

        // Skip root node

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

            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        // Find specified language and/or default language

        String defaultValue = StringPool.BLANK;
        String priorityValue = StringPool.BLANK;

        while (xmlStreamReader.hasNext()) {
            int event = xmlStreamReader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

                if (Validator.isNull(languageId)) {
                    languageId = defaultLanguageId;
                }

                if (languageId.equals(defaultLanguageId) || languageId.equals(priorityLanguageId)
                        || languageId.equals(requestedLanguageId)) {

                    String text = xmlStreamReader.getElementText();

                    if (languageId.equals(defaultLanguageId)) {
                        defaultValue = text;
                    }

                    if (languageId.equals(priorityLanguageId)) {
                        priorityValue = text;
                    }

                    if (languageId.equals(requestedLanguageId)) {
                        value = text;
                    }

                    if (Validator.isNotNull(value)) {
                        break;
                    }
                }
            } else if (event == XMLStreamConstants.END_DOCUMENT) {
                break;
            }
        }

        if (useDefault && Validator.isNotNull(priorityLanguageId) && Validator.isNull(value)
                && Validator.isNotNull(priorityValue)) {

            value = priorityValue;
        }

        if (useDefault && Validator.isNull(value)) {
            value = defaultValue;
        }
    } 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) {
            }
        }
    }

    _setCachedValue(xml, requestedLanguageId, useDefault, value);

    return value;
}

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

/** Find sessions that have timed out and invalidate them.
 *  This runs in the SessionScavenger thread.
 *//* w ww  .  j a v  a2  s .  c o m*/
private void scavenge() {
    Thread thread = Thread.currentThread();
    ClassLoader old_loader = thread.getContextClassLoader();
    try {
        if (_handler == null)
            return;

        ClassLoader loader = _handler.getClassLoader();
        if (loader != null)
            thread.setContextClassLoader(loader);

        long now = System.currentTimeMillis();

        // Since Hashtable enumeration is not safe over deletes,
        // we build a list of stale sessions, then go back and invalidate them
        Object stale = null;

        synchronized (AbstractSessionManager.this) {
            // For each session
            for (Iterator i = _sessions.values().iterator(); i.hasNext();) {
                Session session = (Session) i.next();
                long idleTime = session._maxIdleMs;
                if (idleTime > 0 && session._accessed + idleTime < now) {
                    // Found a stale session, add it to the list
                    stale = LazyList.add(stale, session);
                }
            }
        }

        // Remove the stale sessions
        for (int i = LazyList.size(stale); i-- > 0;) {
            // check it has not been accessed in the meantime
            Session session = (Session) LazyList.get(stale, i);
            long idleTime = session._maxIdleMs;
            if (idleTime > 0 && session._accessed + idleTime < System.currentTimeMillis()) {
                session.invalidate();
                int nbsess = this._sessions.size();
                if (nbsess < this._minSessions)
                    this._minSessions = nbsess;
            }
        }
    } finally {
        thread.setContextClassLoader(old_loader);
    }
}

From source file:org.nebulaframework.grid.cluster.manager.services.jobs.unbounded.UnboundedJobExecutionManager.java

/**
 * Starts given {@code UnboundedGridJob} on the Grid.
 * //from w w  w.j a va2 s.  c  o  m
 * @param profile GridJobProfile
 */
@Override
public boolean startExecution(final GridJobProfile profile, ClassLoader classLoader) {

    // If Valid GridJob Type
    if (profile.getJob() instanceof UnboundedGridJob) {

        // Disallow Final Results
        profile.getFuture().setFinalResultSupported(false);

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

        Thread t = new Thread(new Runnable() {
            public void run() {

                log.info("[UnboundedJobService] Starting Processsor");

                // Create Processor
                UnboundedJobProcessor processor = new UnboundedJobProcessor(profile);
                processors.put(profile.getJobId(), processor);

                // Add Service Hook to Remove Processor When Done
                ServiceEventsSupport.addServiceHook(new ServiceHookCallback() {

                    @Override
                    public void onServiceEvent(ServiceMessage message) {
                        // Remove Processor
                        processors.remove(profile.getJobId());
                    }

                }, profile.getJobId(), ServiceMessageType.JOB_END);

                // Start Processor
                processor.start();
            }
        });
        t.setContextClassLoader(classLoader);
        t.start();

        // Register as Execution Manager
        profile.setExecutionManager(this);

        return true;
    } else {
        return false;
    }
}

From source file:org.kalaider.desktop.scheduler.runner.Runner.java

private static void runScheduler(Path configFilePath, String profile, int nThreads) throws Exception {
    Path libs = Paths.get("./lib");
    Path plugins = Paths.get("./plugin");

    LOG.log(Level.INFO, "Libraries found: {}.", Arrays.asList(getUrlsInDirectory(libs)));
    LOG.log(Level.INFO, "Plugins found: {}.", Arrays.asList(getUrlsInDirectory(plugins)));

    ClassLoader libsLoader = URLClassLoader.newInstance(getUrlsInDirectory(libs),
            Thread.currentThread().getContextClassLoader());
    ClassLoader pluginsLoader = URLClassLoader.newInstance(getUrlsInDirectory(plugins), libsLoader);

    Thread newDaemon = new Thread(() -> {
        synchronized (lock) {
            Class<?> schedulerInstanceClass;

            try {
                schedulerInstanceClass = pluginsLoader
                        .loadClass("org.kalaider.desktop.scheduler.SchedulerInstance");
            } catch (ClassNotFoundException ex) {
                LOG.fatal("Class not found.", ex);
                return;
            }//from  w  ww. ja  va2  s . c  o  m

            Method getDefaultInstanceMethod;

            try {
                getDefaultInstanceMethod = schedulerInstanceClass.getMethod("getDefaultInstance", Path.class,
                        String.class, int.class);
            } catch (NoSuchMethodException | SecurityException ex) {
                LOG.fatal("Method not found.", ex);
                return;
            }

            try {
                schedulerInstance = getDefaultInstanceMethod.invoke(null, configFilePath, profile, nThreads);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.fatal("Illegal method call.", ex);
                return;
            }

            Method startupMethod;

            try {
                startupMethod = schedulerInstanceClass.getMethod("startup");
            } catch (NoSuchMethodException | SecurityException ex) {
                LOG.fatal("Method not found.", ex);
                return;
            }
            try {
                startupMethod.invoke(schedulerInstance);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.fatal("Illegal method call.", ex);
                return;
            }
        }
    });
    newDaemon.setName("SchedulerRunnerThread");
    newDaemon.setContextClassLoader(pluginsLoader);
    newDaemon.setDaemon(true);
    newDaemon.start();
}

From source file:com.saysth.commons.quartz.SchedulerFactoryBean.java

/**
 * Create the Scheduler instance for the given factory and scheduler name.
 * Called by {@link #afterPropertiesSet}.
 * <p>/*w w w .j  a va2 s. c o m*/
 * The default implementation invokes SchedulerFactory's
 * <code>getScheduler</code> method. Can be overridden for custom Scheduler
 * creation.
 * 
 * @param schedulerFactory
 *            the factory to create the Scheduler with
 * @param schedulerName
 *            the name of the scheduler to create
 * @return the Scheduler instance
 * @throws SchedulerException
 *             if thrown by Quartz methods
 * @see #afterPropertiesSet
 * @see org.quartz.SchedulerFactory#getScheduler
 */
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName)
        throws SchedulerException {

    // Override thread context ClassLoader to work around naive Quartz
    // ClassLoadHelper loading.
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (this.resourceLoader != null
            && !this.resourceLoader.getClassLoader().equals(threadContextClassLoader));
    if (overrideClassLoader) {
        currentThread.setContextClassLoader(this.resourceLoader.getClassLoader());
    }
    try {
        SchedulerRepository repository = SchedulerRepository.getInstance();
        synchronized (repository) {
            Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);
            Scheduler newScheduler = schedulerFactory.getScheduler();
            if (newScheduler == existingScheduler) {
                throw new IllegalStateException("Active Scheduler of name '" + schedulerName
                        + "' already registered "
                        + "in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");
            }
            if (!this.exposeSchedulerInRepository) {
                // Need to remove it in this case, since Quartz shares the
                // Scheduler instance by default!
                SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());
            }
            return newScheduler;
        }
    } finally {
        if (overrideClassLoader) {
            // Reset original thread context ClassLoader.
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
    }
}

From source file:org.apache.hadoop.hbase.master.MasterCoprocessorHost.java

private boolean execOperation(final CoprocessorOperation ctx) throws IOException {
    if (ctx == null)
        return false;
    boolean bypass = false;
    for (MasterEnvironment env : coprocessors) {
        if (env.getInstance() instanceof MasterObserver) {
            ctx.prepare(env);//from   w  w w.  ja  va  2  s . c  om
            Thread currentThread = Thread.currentThread();
            ClassLoader cl = currentThread.getContextClassLoader();
            try {
                currentThread.setContextClassLoader(env.getClassLoader());
                ctx.call((MasterObserver) env.getInstance(), ctx);
            } catch (Throwable e) {
                handleCoprocessorThrowable(env, e);
            } finally {
                currentThread.setContextClassLoader(cl);
            }
            bypass |= ctx.shouldBypass();
            if (ctx.shouldComplete()) {
                break;
            }
        }
        ctx.postEnvCall(env);
    }
    return bypass;
}