Example usage for java.lang ThreadGroup getParent

List of usage examples for java.lang ThreadGroup getParent

Introduction

In this page you can find the example usage for java.lang ThreadGroup getParent.

Prototype

public final ThreadGroup getParent() 

Source Link

Document

Returns the parent of this thread group.

Usage

From source file:org.zywx.wbpalmstar.engine.EBrowserActivity.java

public Thread[] findAllVMThreads() {
    ThreadGroup group = Thread.currentThread().getThreadGroup();
    ThreadGroup topGroup = group;
    while (group != null) {
        topGroup = group;/*from   www.jav a2s . c  om*/
        group = group.getParent();
    }
    int estimatedSize = topGroup.activeCount() * 2;
    Thread[] slackList = new Thread[estimatedSize];
    int actualSize = topGroup.enumerate(slackList);
    Thread[] list = new Thread[actualSize];
    System.arraycopy(slackList, 0, list, 0, actualSize);
    return list;
}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * destroy the loader tree/*from w w  w .java  2  s.  c o m*/
 */
public static final void destroy() {
    if (CClassLoader.rootLoader == null) {
        return;
    }
    System.out.println("Destroying YAHP ClassLoader Tree");

    CClassLoader.urlLoader = null;

    try {
        Field f = Class.forName("java.lang.Shutdown").getDeclaredField("hooks");
        f.setAccessible(true);
        ArrayList l = (ArrayList) f.get(null);
        for (Iterator it = l.iterator(); it.hasNext();) {
            Object o = it.next();
            if ((o != null) && (o.getClass().getClassLoader() != null)
                    && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) {
                it.remove();
            }
        }
    } catch (Throwable ignore) {
    }

    try {
        Field f = Class.forName("java.lang.ApplicationShutdownHooks").getDeclaredField("hooks");
        f.setAccessible(true);
        IdentityHashMap l = (IdentityHashMap) f.get(null);
        for (Iterator it = l.entrySet().iterator(); it.hasNext();) {
            Entry e = (Entry) it.next();
            Thread o = (Thread) e.getKey();
            if ((o != null) && (o.getClass().getClassLoader() != null)
                    && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) {
                it.remove();
                continue;
            }
            o = (Thread) e.getValue();
            if ((o != null) && (o.getClass().getClassLoader() != null)
                    && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) {
                it.remove();
            }
        }
    } catch (Throwable ignore) {
    }

    try {
        if ((UIManager.getLookAndFeel() != null)
                && (UIManager.getLookAndFeel().getClass().getClassLoader() != null)
                && (UIManager.getLookAndFeel().getClass().getClassLoader().getClass() == CClassLoader.class)) {
            UIManager.setLookAndFeel((LookAndFeel) null);
        }
        Field f = UIManager.class.getDeclaredField("currentLAFState");
        f.setAccessible(true);
        Object lafstate = f.get(null);
        if (lafstate != null) {
            Field fmultiUIDefaults = lafstate.getClass().getDeclaredField("multiUIDefaults");
            fmultiUIDefaults.setAccessible(true);
            Object multiUIDefaults = fmultiUIDefaults.get(lafstate);
            Method clear = multiUIDefaults.getClass().getDeclaredMethod("clear", (Class[]) null);
            clear.setAccessible(true);
            clear.invoke(multiUIDefaults, (Object[]) null);
            Field tbl = lafstate.getClass().getDeclaredField("tables");
            tbl.setAccessible(true);
            Hashtable[] tables = (Hashtable[]) tbl.get(lafstate);
            if (tables != null) {
                for (int i = 0; i < tables.length; i++) {
                    Hashtable element = tables[i];
                    if (element != null) {
                        element.clear();
                    }
                }
            }
        }
    } catch (Throwable ignore) {
    }

    try {
        Hashtable tb = UIManager.getDefaults();
        Object cl = tb.get("ClassLoader");
        if (cl.getClass() == CClassLoader.class) {
            tb.put("ClassLoader", CClassLoader.rootLoader.getParent());
        }
    } catch (Throwable ignore) {
    }

    Method logFactoryRelease = null;

    try {
        logFactoryRelease = CClassLoader.rootLoader.loadClass("org.apache.commons.logging.LogFactory")
                .getMethod("release", new Class[] { ClassLoader.class });
    } catch (final Throwable ignore) {
    }

    CClassLoader.rootLoader._destroy(logFactoryRelease);
    CClassLoader.mandatoryLoadersMap.clear();
    CClassLoader.rootLoader = null;

    // deregister any sql driver loaded
    try {
        final List deregisterList = new ArrayList();
        for (final Enumeration it = DriverManager.getDrivers(); it.hasMoreElements();) {
            final Driver d = (Driver) it.nextElement();

            if ((d != null) && (d.getClass().getClassLoader() != null)
                    && (d.getClass().getClassLoader().getClass() == CClassLoader.class)) {
                deregisterList.add(d);
            }
        }

        for (int i = 0; i < deregisterList.size(); i++) {
            final Driver driver = (Driver) deregisterList.get(i);
            DriverManager.deregisterDriver(driver);
        }
    } catch (final Throwable ignore) {
    }

    // stop dandling thread created with this classloader
    // tested only on sun jdk
    ThreadGroup tg = Thread.currentThread().getThreadGroup();
    while ((tg != null) && (tg.getParent() != null)) {
        tg = tg.getParent();
    }
    List ltg = new ArrayList();
    ltg.add(tg);
    CClassLoader.getThreadGroups(tg, ltg);
    for (int ii = 0; ii < ltg.size(); ii++) {
        try {
            final ThreadGroup g = (ThreadGroup) ltg.get(ii);
            final Field fthreads = ThreadGroup.class.getDeclaredField("threads");
            fthreads.setAccessible(true);

            final List toStop = new ArrayList();
            Object threads[] = null;

            if (fthreads.getType() == Vector.class) {
                // in gnu classpath
                threads = ((Vector) fthreads.get(g)).toArray();
            } else {
                // sun
                threads = (Object[]) fthreads.get(g);
            }

            for (int i = 0; i < threads.length; i++) {
                if (threads[i] == null) {
                    continue;
                }
                if ((threads[i] != null) && (((Thread) threads[i]).getContextClassLoader() != null)
                        && (((Thread) threads[i]).getContextClassLoader().getClass() == CClassLoader.class)) {
                    ((Thread) threads[i]).setContextClassLoader(null);
                }
                if ((threads[i] != null) && (threads[i].getClass().getClassLoader() != null)
                        && (threads[i].getClass().getClassLoader().getClass() == CClassLoader.class)) {
                    toStop.add((Thread) threads[i]);
                }

                // remove any object in threadLocal referring an object
                // loaded
                // by this classloader tree
                try {
                    final Field fthreadLocals = Thread.class.getDeclaredField("threadLocals");
                    fthreadLocals.setAccessible(true);

                    final Object threadLocals = fthreadLocals.get(threads[i]);
                    if (threadLocals != null) {
                        final Field ftable = threadLocals.getClass().getDeclaredField("table");
                        ftable.setAccessible(true);

                        final Object table[] = (Object[]) ftable.get(threadLocals);

                        for (int kk = 0; kk < table.length; kk++) {
                            final Object element = table[kk];
                            if (element != null) {
                                final Field fvalue = element.getClass().getDeclaredField("value");
                                fvalue.setAccessible(true);

                                final Object value = fvalue.get(element);

                                if ((value != null) && (value.getClass().getClassLoader() != null) && (value
                                        .getClass().getClassLoader().getClass() == CClassLoader.class)) {
                                    fvalue.set(element, null);
                                }
                                if (value instanceof Map) {
                                    clearMap((Map) value);
                                } else if (value instanceof List) {
                                    clearList((List) value);
                                } else if (value instanceof Set) {
                                    clearSet((Set) value);
                                } else if (value instanceof Object[]) {
                                    clearArray((Object[]) value);
                                }

                                fvalue.setAccessible(false);
                            }
                        }
                        ftable.setAccessible(false);
                    }
                    fthreadLocals.setAccessible(false);
                } catch (final Throwable ignore) {
                    ignore.printStackTrace();
                }

                // remove any object in threadLocal referring an object
                // loaded
                // by this classloader tree
                try {
                    final Field fthreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals");
                    fthreadLocals.setAccessible(true);

                    final Object threadLocals = fthreadLocals.get(threads[i]);
                    if (threadLocals != null) {
                        final Field ftable = threadLocals.getClass().getDeclaredField("table");
                        ftable.setAccessible(true);

                        final Object table[] = (Object[]) ftable.get(threadLocals);

                        for (int kk = 0; kk < table.length; kk++) {
                            final Object element = table[kk];
                            if (element != null) {
                                final Field fvalue = element.getClass().getDeclaredField("value");
                                fvalue.setAccessible(true);

                                final Object value = fvalue.get(element);

                                if ((value != null) && (value.getClass().getClassLoader() != null) && (value
                                        .getClass().getClassLoader().getClass() == CClassLoader.class)) {
                                    fvalue.set(element, null);
                                }
                                if (value instanceof Map) {
                                    clearMap((Map) value);
                                } else if (value instanceof List) {
                                    clearList((List) value);
                                } else if (value instanceof Set) {
                                    clearSet((Set) value);
                                } else if (value instanceof Object[]) {
                                    clearArray((Object[]) value);
                                }

                                fvalue.setAccessible(false);
                            }
                        }

                        ftable.setAccessible(false);
                    }
                    fthreadLocals.setAccessible(false);
                } catch (final Throwable ignore) {
                    ignore.printStackTrace();
                }

                // remove any protection domain referring this loader tree
                try {
                    final Field finheritedAccessControlContext = Thread.class
                            .getDeclaredField("inheritedAccessControlContext");
                    finheritedAccessControlContext.setAccessible(true);

                    final Object inheritedAccessControlContext = finheritedAccessControlContext.get(threads[i]);

                    if (inheritedAccessControlContext != null) {
                        final Field fcontext = AccessControlContext.class.getDeclaredField("context");
                        fcontext.setAccessible(true);

                        final Object context[] = (Object[]) fcontext.get(inheritedAccessControlContext);

                        if (context != null) {
                            for (int k = 0; k < context.length; k++) {
                                if (context[k] == null)
                                    continue;
                                final Field fclassloader = ProtectionDomain.class
                                        .getDeclaredField("classloader");
                                fclassloader.setAccessible(true);

                                final Object classloader = fclassloader.get(context[k]);

                                if ((classloader != null) && (classloader.getClass() == CClassLoader.class)) {
                                    context[k] = null;
                                }

                                fclassloader.setAccessible(false);
                            }
                        }

                        fcontext.setAccessible(false);
                    }

                    finheritedAccessControlContext.setAccessible(false);
                } catch (final Throwable ignore) {
                    ignore.printStackTrace();
                }
            }

            fthreads.setAccessible(false);
            for (int i = 0; i < toStop.size(); i++) {
                try {
                    final Thread t = (Thread) toStop.get(i);
                    final Method stop = t.getClass().getMethod("stop", (Class[]) null);
                    stop.invoke(t, (Object[]) null);
                } catch (final Throwable ignore) {
                }
            }
        } catch (final Throwable ignore) {
        }
    }
    try {
        CThreadContext.destroy();
    } catch (Throwable ignore) {
    }
    System.runFinalization();
    System.gc();
    Introspector.flushCaches();
    System.out.println("Destroying YAHP ClassLoader Tree : done");
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Get a Collection with all Threads.//from www.  j a  v a2  s . c o m
 * This method is heavily inspired by org.apache.catalina.loader.WebappClassLoader.getThreads()
 */
protected Collection<Thread> getAllThreads() {
    // This is some orders of magnitude slower...
    // return Thread.getAllStackTraces().keySet();

    // Find root ThreadGroup
    ThreadGroup tg = Thread.currentThread().getThreadGroup();
    while (tg.getParent() != null)
        tg = tg.getParent();

    // Note that ThreadGroup.enumerate() silently ignores all threads that does not fit into array
    int guessThreadCount = tg.activeCount() + 50;
    Thread[] threads = new Thread[guessThreadCount];
    int actualThreadCount = tg.enumerate(threads);
    while (actualThreadCount == guessThreadCount) { // Map was filled, there may be more
        guessThreadCount *= 2;
        threads = new Thread[guessThreadCount];
        actualThreadCount = tg.enumerate(threads);
    }

    // Filter out nulls
    final List<Thread> output = new ArrayList<Thread>();
    for (Thread t : threads) {
        if (t != null) {
            output.add(t);
        }
    }
    return output;
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Destroy any ThreadGroups that are loaded by the application classloader
 *///ww  w  . j a  v  a 2 s. c om
public void destroyThreadGroups() {
    try {
        ThreadGroup systemThreadGroup = Thread.currentThread().getThreadGroup();
        while (systemThreadGroup.getParent() != null) {
            systemThreadGroup = systemThreadGroup.getParent();
        }
        // systemThreadGroup should now be the topmost ThreadGroup, "system"

        int enumeratedGroups;
        ThreadGroup[] allThreadGroups;
        int noOfGroups = systemThreadGroup.activeGroupCount(); // Estimate no of groups
        do {
            noOfGroups += 10; // Make room for 10 extra
            allThreadGroups = new ThreadGroup[noOfGroups];
            enumeratedGroups = systemThreadGroup.enumerate(allThreadGroups);
        } while (enumeratedGroups >= noOfGroups); // If there was not room for all groups, try again

        for (ThreadGroup threadGroup : allThreadGroups) {
            if (isLoadedInWebApplication(threadGroup) && !threadGroup.isDestroyed()) {
                warn("ThreadGroup '" + threadGroup + "' was loaded inside application, needs to be destroyed");

                int noOfThreads = threadGroup.activeCount();
                if (noOfThreads > 0) {
                    warn("There seems to be " + noOfThreads + " running in ThreadGroup '" + threadGroup
                            + "'; interrupting");
                    try {
                        threadGroup.interrupt();
                    } catch (Exception e) {
                        error(e);
                    }
                }

                try {
                    threadGroup.destroy();
                    info("ThreadGroup '" + threadGroup + "' successfully destroyed");
                } catch (Exception e) {
                    error(e);
                }
            }
        }
    } catch (Exception ex) {
        error(ex);
    }
}

From source file:org.gcaldaemon.core.Configurator.java

public Configurator(String configPath, Properties properties, boolean userHome, byte mode) throws Exception {
    this.mode = mode;
    int i;//from   w  w w . ja v a  2 s. c o m
    File programRootDir = null;
    if (mode == MODE_EMBEDDED) {

        // Embedded mode
        standaloneMode = false;
        config = properties;
        String workPath = getConfigProperty(WORK_DIR, null);
        workDirectory = new File(workPath);
    } else {

        // Load config
        if (configPath != null) {
            configFile = new File(configPath);
        }
        InputStream in = null;
        boolean configInClassPath = false;
        if (configFile == null || !configFile.isFile()) {
            try {
                in = Configurator.class.getResourceAsStream("/gcal-daemon.cfg");
                configInClassPath = in != null;
            } catch (Exception ignored) {
                in = null;
            }
            if (in == null) {
                System.out.println("INFO  | Searching main configuration file...");
                String path = (new File("x")).getAbsolutePath().replace('\\', '/');
                i = path.lastIndexOf('/');
                if (i > 1) {
                    i = path.lastIndexOf('/', i - 1);
                    if (i > 1) {
                        configFile = new File(path.substring(0, i), "conf/gcal-daemon.cfg");
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/usr/local/sbin/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    File root = new File("/");
                    String[] dirs = root.list();
                    if (dirs != null) {
                        for (i = 0; i < dirs.length; i++) {
                            configFile = new File('/' + dirs[i] + "/GCALDaemon/conf/gcal-daemon.cfg");
                            if (configFile.isFile()) {
                                break;
                            }
                        }
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    throw new FileNotFoundException("Missing main configuration file: " + configPath);
                }
                if (!userHome) {

                    // Open global config file
                    in = new FileInputStream(configFile);
                }
            }
        } else {
            if (!userHome) {

                // Open global config file
                in = new FileInputStream(configFile);
            }
        }
        standaloneMode = !configInClassPath;
        if (in != null) {

            // Load global config file
            config.load(new BufferedInputStream(in));
            in.close();
        }

        // Loading config from classpath
        if (configFile == null) {
            try {
                URL url = Configurator.class.getResource("/gcal-daemon.cfg");
                configFile = new File(url.getFile());
            } catch (Exception ignored) {
            }
        }
        programRootDir = configFile.getParentFile().getParentFile();
        System.setProperty("gcaldaemon.program.dir", programRootDir.getAbsolutePath());
        String workPath = getConfigProperty(WORK_DIR, null);
        File directory;
        if (workPath == null) {
            directory = new File(programRootDir, "work");
        } else {
            directory = new File(workPath);
        }
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                directory = new File("work");
                directory.mkdirs();
            }
        }
        workDirectory = directory;

        // User-specific config file handler
        if (userHome) {
            boolean useGlobal = true;
            try {
                String home = System.getProperty("user.home", null);
                if (home != null) {
                    File userConfig = new File(home, ".gcaldaemon/gcal-daemon.cfg");
                    if (!userConfig.isFile()) {

                        // Create new user-specific config
                        File userDir = new File(home, ".gcaldaemon");
                        userDir.mkdirs();
                        copyFile(configFile, userConfig);
                        if (!userConfig.isFile()) {
                            userConfig.delete();
                            userDir.delete();
                        }
                    }
                    if (userConfig.isFile()) {

                        // Load user-specific config
                        configFile = userConfig;
                        in = new FileInputStream(configFile);
                        config.load(new BufferedInputStream(in));
                        in.close();
                        useGlobal = false;
                    }
                }
            } catch (Exception ignored) {
            }
            if (useGlobal) {

                // Load global config file
                config.load(new BufferedInputStream(in));
                in.close();
            }
        }
    }

    // Init logger
    ProgressMonitor monitor = null;
    if (standaloneMode && mode != MODE_CONFIGEDITOR) {

        // Compute log config path
        String logConfig = getConfigProperty(LOG_CONFIG, "logger-config.cfg");
        logConfig = logConfig.replace('\\', '/');
        File logConfigFile;
        if (logConfig.indexOf('/') == -1) {
            logConfigFile = new File(programRootDir, "conf/" + logConfig);
        } else {
            logConfigFile = new File(logConfig);
        }
        if (logConfigFile.isFile()) {
            String logConfigPath = logConfigFile.getAbsolutePath();
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
            System.setProperty("log4j.defaultInitOverride", "false");
            System.setProperty("log4j.configuration", logConfigPath);
            try {
                PropertyConfigurator.configure(logConfigPath);
            } catch (Throwable ignored) {
            }
        }
    }
    if (mode == MODE_CONFIGEDITOR) {

        // Show monitor
        try {
            monitor = new ProgressMonitor();
            monitor.setVisible(true);
            Thread.sleep(400);
        } catch (Exception ignored) {
        }

        // Init simple logger
        try {
            System.setProperty("log4j.defaultInitOverride", "false");
            Logger root = Logger.getRootLogger();
            root.removeAllAppenders();
            root.addAppender(new ConsoleAppender(new SimpleLayout()));
            root.setLevel(Level.INFO);
        } catch (Throwable ingored) {
        }
    }

    // Disable unnecessary INFO messages of the GData API
    try {
        java.util.logging.Logger logger = java.util.logging.Logger.getLogger("com.google");
        logger.setLevel(java.util.logging.Level.WARNING);
    } catch (Throwable ingored) {
    }

    Log log = LogFactory.getLog(Configurator.class);
    log.info(VERSION + " starting...");
    if (configFile != null && log.isDebugEnabled()) {
        log.debug("Config loaded successfully (" + configFile + ").");
    }

    // Check Java version
    double jvmVersion = 1.5;
    try {
        jvmVersion = Float.valueOf(System.getProperty("java.version", "1.5").substring(0, 3)).floatValue();
    } catch (Exception ignored) {
    }
    if (jvmVersion < 1.5) {
        log.fatal("GCALDaemon requires at least Java 1.5! Current version: "
                + System.getProperty("java.version"));
        throw new Exception("Invalid JVM version!");
    }

    // Check permission
    if (workDirectory.isDirectory() && !workDirectory.canWrite()) {
        if (System.getProperty("os.name", "unknown").toLowerCase().indexOf("windows") == -1) {
            String path = workDirectory.getCanonicalPath();
            if (programRootDir != null) {
                path = programRootDir.getCanonicalPath();
            }
            log.warn("Please check the file permissions on the '" + workDirectory.getCanonicalPath()
                    + "' folder!\r\n" + "Hint: [sudo] chmod -R 777 " + path);
        }
    }

    // Disable all ICS file syntax validators
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_NOTES_COMPATIBILITY, true);

    // Disable SSL validation
    try {

        // Create a trust manager that does not validate certificate chains
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[] {
                new javax.net.ssl.X509TrustManager() {

                    public final java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public final void checkClientTrusted(java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }

                    public final void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }
                } };

        // Install the all-trusting trust manager
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Throwable ignored) {
    }

    // Replace hostname verifier
    try {
        javax.net.ssl.HostnameVerifier hv[] = new javax.net.ssl.HostnameVerifier[] {
                new javax.net.ssl.HostnameVerifier() {

                    public final boolean verify(String hostName, javax.net.ssl.SSLSession session) {
                        return true;
                    }
                } };
        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv[0]);
    } catch (Throwable ignored) {
    }

    // Setup proxy
    String proxyHost = getConfigProperty(PROXY_HOST, null);
    if (proxyHost != null) {
        String proxyPort = getConfigProperty(PROXY_PORT, null);
        if (proxyPort == null) {
            log.warn("Missing 'proxy.port' configuration property!");
        } else {

            // HTTP proxy server properties
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            System.setProperty("http.proxySet", "true");

            // HTTPS proxy server properties
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort);
            System.setProperty("https.proxySet", "true");

            // Setup proxy credentials
            String username = getConfigProperty(PROXY_USERNAME, null);
            String encodedPassword = getConfigProperty(PROXY_PASSWORD, null);
            if (username != null) {
                if (encodedPassword == null) {
                    log.warn("Missing 'proxy.password' configuration property!");
                } else {
                    String password = StringUtils.decodePassword(encodedPassword);

                    // HTTP auth credentials
                    System.setProperty("http.proxyUser", username);
                    System.setProperty("http.proxyUserName", username);
                    System.setProperty("http.proxyPassword", password);

                    // HTTPS auth credentials
                    System.setProperty("https.proxyUser", username);
                    System.setProperty("https.proxyUserName", username);
                    System.setProperty("https.proxyPassword", password);
                }
            }
        }
    }

    // Get iCal cache timeout
    long timeout = getConfigProperty(CACHE_TIMEOUT, 180000L);
    if (timeout < 60000L) {
        log.warn("The enabled minimal cache timeout is '1 min'!");
        timeout = 60000L;
    }
    calendarCacheTimeout = timeout;

    // Get backup file timeout
    timeout = getConfigProperty(ICAL_BACKUP_TIMEOUT, 604800000L);
    if (timeout < 86400000L && timeout != 0) {
        log.warn("The enabled minimal backup timeout is '1 day'!");
        timeout = 86400000L;
    }
    backupTimeout = timeout;

    // Get extended syncronization mode (alarms, url, category, etc)
    boolean enable = getConfigProperty(EXTENDED_SYNC_ENABLED, false);
    System.setProperty("gcaldaemon.extended.sync", Boolean.toString(enable));
    if (enable) {
        log.info("Extended synchronization enabled.");
    }

    // Google send an email to the attendees to invite them to attend
    enable = getConfigProperty(SEND_INVITATIONS, false);
    System.setProperty("gcaldaemon.send.invitations", Boolean.toString(enable));

    // Enabled alarm types in the Google Calendar (e.g. 'sms,popup,email')
    System.setProperty("gcaldaemon.remote.alarms", getConfigProperty(REMOTE_ALARM_TYPES, "email,sms,popup"));

    // Get parameters of the feed to iCal converter
    feedEnabled = getConfigProperty(FEED_ENABLED, true);
    feedEventLength = getConfigProperty(FEED_EVENT_LENGTH, 2700000L);
    timeout = getConfigProperty(FEED_CACHE_TIMEOUT, 3600000L);
    if (timeout < 60000L) {
        log.warn("The enabled minimal feed timeout is '1 min'!");
        timeout = 60000L;
    }
    feedCacheTimeout = timeout;
    if (feedEnabled) {
        log.info("RSS/ATOM feed converter enabled.");
    } else {
        log.info("RSS/ATOM feed converter disabled.");
    }

    // Get feed event duplication ratio
    String percent = getConfigProperty(FEED_DUPLICATION_FILTER, "70").trim();
    if (percent.endsWith("%")) {
        percent = percent.substring(0, percent.length() - 1).trim();
    }
    double ratio = Double.parseDouble(percent) / 100;
    if (ratio < 0.4) {
        ratio = 0.4;
        log.warn("The smallest enabled filter percent is '40%'!");
    } else {
        if (ratio > 1) {
            log.warn("The largest filter percent is '100%'!");
            ratio = 1;
        }
    }
    duplicationRatio = ratio;
    if (feedEnabled) {
        if (duplicationRatio == 1) {
            log.debug("Duplication filter disabled.");
        } else {
            log.debug("Sensibility of the duplication filter is " + percent + "%.");
        }
    }

    // Delete backup files
    if (backupTimeout == 0) {
        File backupDirectory = new File(workDirectory, "backup");
        if (backupDirectory.isDirectory()) {
            File[] backups = backupDirectory.listFiles();
            if (backups != null && backups.length != 0) {
                for (i = 0; i < backups.length; i++) {
                    backups[i].delete();
                }
            }
        }
    }

    // Displays time zone
    log.info("Local time zone is " + TimeZone.getDefault().getDisplayName() + ".");

    // Get main thread group
    ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
    while (mainGroup.getParent() != null) {
        mainGroup = mainGroup.getParent();
    }

    // Configurator mode - launch ConfigTool's window
    if (mode == MODE_CONFIGEDITOR) {
        synchronizer = new Synchronizer(mainGroup, this);
        gmailPool = startService(log, mainGroup, "org.gcaldaemon.core.GmailPool");
        new ConfigEditor(this, monitor);
        return;
    }

    // Init synchronizer
    boolean enableHTTP = getConfigProperty(HTTP_ENABLED, true);
    boolean enableFile = getConfigProperty(FILE_ENABLED, false);
    if (enableHTTP || enableFile || !standaloneMode) {
        synchronizer = new Synchronizer(mainGroup, this);
        if (mode == MODE_EMBEDDED) {
            return;
        }
    }

    // On demand mode - run once then quit
    if (mode == MODE_RUNONCE) {
        fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OfflineFileListener");
        return;
    }

    // Init Gmail pool
    boolean enableLDAP = getConfigProperty(LDAP_ENABLED, false);
    boolean enableSendMail = getConfigProperty(SENDMAIL_ENABLED, false);
    boolean enableMailTerm = getConfigProperty(MAILTERM_ENABLED, false);
    if (enableLDAP || enableSendMail || enableMailTerm) {
        gmailPool = startService(log, mainGroup, "org.gcaldaemon.core.GmailPool");
    }

    if (standaloneMode) {

        // Init HTTP listener
        if (enableHTTP) {
            httpListener = startService(log, mainGroup, "org.gcaldaemon.core.http.HTTPListener");
        } else {
            log.info("HTTP server disabled.");
        }
    } else {

        // Init J2EE servlet listener
        servletListener = startService(log, mainGroup, "org.gcaldaemon.core.servlet.ServletListener");
    }

    // Init file listener
    if (enableFile) {
        if (getConfigProperty(FILE_OFFLINE_ENABLED, true)) {
            fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OfflineFileListener");
        } else {
            fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OnlineFileListener");
        }
    } else {
        if (standaloneMode) {
            log.info("File listener disabled.");
        }
    }

    // Init LDAP listener
    if (enableLDAP) {
        contactLoader = startService(log, mainGroup, "org.gcaldaemon.core.ldap.ContactLoader");
    } else {
        if (standaloneMode) {
            log.info("LDAP server disabled.");
        }
    }

    // Init Gmail notifier
    if (getConfigProperty(NOTIFIER_ENABLED, false)) {
        if (GraphicsEnvironment.isHeadless()) {
            log.warn("Unable to use Gmail notifier in headless mode!");
        } else {
            mailNotifier = startService(log, mainGroup, "org.gcaldaemon.core.notifier.GmailNotifier");
        }
    } else {
        if (standaloneMode) {
            log.info("Gmail notifier disabled.");
        }
    }

    // Init sendmail service
    if (enableSendMail) {
        sendMail = startService(log, mainGroup, "org.gcaldaemon.core.sendmail.SendMail");
    } else {
        if (standaloneMode) {
            log.info("Sendmail service disabled.");
        }
    }

    // Init mailterm service
    if (enableMailTerm) {
        mailTerm = startService(log, mainGroup, "org.gcaldaemon.core.mailterm.MailTerminal");
    } else {
        if (standaloneMode) {
            log.info("Mail terminal disabled.");
        }
    }

    // Clear configuration holder
    config.clear();
}

From source file:com.cyberway.issue.crawler.Heritrix.java

public String interrupt(String threadName) {
    String result = "Thread " + threadName + " not found";
    ThreadGroup group = Thread.currentThread().getThreadGroup();
    if (group == null) {
        return result;
    }/*w  w  w. ja  v  a  2  s.  co m*/
    // Back up to the root threadgroup before starting
    // to iterate over threads.
    ThreadGroup parent = null;
    while ((parent = group.getParent()) != null) {
        group = parent;
    }
    // Do an array that is twice the size of active
    // thread count.  That should be big enough.
    final int max = group.activeCount() * 2;
    Thread[] threads = new Thread[max];
    int threadCount = group.enumerate(threads, true);
    if (threadCount >= max) {
        logger.info("Some threads not found...array too small: " + max);
    }
    for (int j = 0; j < threadCount; j++) {
        if (threads[j].getName().equals(threadName)) {
            threads[j].interrupt();
            result = "Interrupt sent to " + threadName;
            break;
        }
    }
    return result;
}