Example usage for java.awt GraphicsEnvironment isHeadless

List of usage examples for java.awt GraphicsEnvironment isHeadless

Introduction

In this page you can find the example usage for java.awt GraphicsEnvironment isHeadless.

Prototype

public static boolean isHeadless() 

Source Link

Document

Tests whether or not a display, keyboard, and mouse can be supported in this environment.

Usage

From source file:org.eobjects.datacleaner.test.scenario.OpenAnalysisResultTest.java

/**
 * A very broad integration test which opens a result with (more or less)
 * all built-in analyzer results./*from www. j  a  v  a  2s  .c  o m*/
 * 
 * @throws Exception
 */
public void testOpenJobWithAllAnalyzers() throws Exception {
    if (GraphicsEnvironment.isHeadless()) {
        System.out.println("!!! Skipping test because environment is headless: " + getName());
        return;
    }

    DCModule module = new DCModule();

    FileObject file = VFSUtils.getFileSystemManager()
            .resolveFile("src/test/resources/all_analyzers.analysis.result.dat");

    OpenAnalysisJobActionListener listener = new OpenAnalysisJobActionListener(null, null, null, null,
            new UserPreferencesImpl(null));
    ResultWindow window = listener.openAnalysisResult(file, module);
    assertNotNull(window);

    assertEquals("all_analyzers.analysis.result.dat | Analysis results", window.getWindowTitle());
}

From source file:org.eobjects.datacleaner.widgets.properties.MultipleMappedEnumsPropertyWidgetTest.java

public void testRestoreEnumValuesFromFile() throws Exception {
    final DCModule dcModule = new DCModule();
    final FileObject file = VFS.getManager().resolveFile("src/test/resources/mapped_columns_job.analysis.xml");
    final Injector injector1 = Guice.createInjector(dcModule);
    final AnalyzerBeansConfiguration configuration = injector1.getInstance(AnalyzerBeansConfiguration.class);

    final Injector injector2 = OpenAnalysisJobActionListener.open(file, configuration, injector1);

    final List<AnalyzerJobBuilder<?>> analyzers;
    if (GraphicsEnvironment.isHeadless()) {
        analyzers = injector2.getInstance(AnalysisJobBuilder.class).getAnalyzerJobBuilders();
    } else {//from  w  w  w . j  a v  a  2 s . c o  m
        final AnalysisJobBuilderWindow window = injector2.getInstance(AnalysisJobBuilderWindow.class);
        analyzers = window.getAnalysisJobBuilder().getAnalyzerJobBuilders();
    }

    assertEquals(2, analyzers.size());

    final AnalyzerJobBuilder<?> completenessAnalyzer = analyzers.get(0);
    assertEquals("Completeness analyzer", completenessAnalyzer.getDescriptor().getDisplayName());

    final Set<ConfiguredPropertyDescriptor> enumProperties = completenessAnalyzer.getDescriptor()
            .getConfiguredPropertiesByType(CompletenessAnalyzer.Condition[].class, false);
    assertEquals(1, enumProperties.size());

    final Set<ConfiguredPropertyDescriptor> inputProperties = completenessAnalyzer.getDescriptor()
            .getConfiguredPropertiesForInput(false);
    assertEquals(1, inputProperties.size());

    final ConfiguredPropertyDescriptor enumProperty = enumProperties.iterator().next();
    final Enum<?>[] enumValue = (Enum<?>[]) completenessAnalyzer.getConfiguredProperty(enumProperty);
    assertEquals("{NOT_NULL,NOT_BLANK_OR_NULL}", ArrayUtils.toString(enumValue));

    final ConfiguredPropertyDescriptor inputProperty = inputProperties.iterator().next();
    final InputColumn<?>[] inputValue = (InputColumn<?>[]) completenessAnalyzer
            .getConfiguredProperty(inputProperty);

    final MultipleMappedEnumsPropertyWidget<Enum<?>> inputWidget = new MultipleMappedEnumsPropertyWidget<Enum<?>>(
            completenessAnalyzer, inputProperty, enumProperty);
    final PropertyWidget<Enum<?>[]> enumWidget = inputWidget.getMappedEnumsPropertyWidget();
    enumWidget.initialize(enumValue);
    inputWidget.initialize(inputValue);
    inputWidget.onValueTouched(inputValue);
    enumWidget.onValueTouched(enumValue);

    assertEquals("{NOT_NULL,NOT_BLANK_OR_NULL}", ArrayUtils.toString(enumWidget.getValue()));
}

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. j  av a  2 s .  c  om
    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:org.gcaldaemon.core.sendmail.SendMail.java

public SendMail(ThreadGroup mainGroup, Configurator configurator) throws Exception {
    super(mainGroup, "Sendmail agent");
    this.configurator = configurator;

    // Show animated progress bar while sending
    if (configurator.getConfigProperty(Configurator.PROGRESS_ENABLED, false)) {
        if (GraphicsEnvironment.isHeadless()) {
            monitor = null;//from w ww .  j a  v  a 2  s.c  o m
            log.warn("Unable to use progress monitor in headless mode!");
        } else {
            monitor = new ProgressMonitor();
            setPriority(NORM_PRIORITY - 1);
        }
    } else {
        monitor = null;
    }

    // Get polling time
    long timeout = configurator.getConfigProperty(Configurator.SENDMAIL_POLLING_DIR, 10000L);
    if (timeout < 1000L) {
        log.warn("The fastest outgoing directory polling period is '1 sec'!");
        timeout = 1000L;
    }
    pollingTimeout = timeout;

    // Get username
    username = configurator.getConfigProperty(Configurator.SENDMAIL_GOOGLE_USERNAME, null);
    if (username == null) {
        throw new NullPointerException("Missing username (" + Configurator.SENDMAIL_GOOGLE_USERNAME + ")!");
    }

    // Get password
    password = configurator.getPasswordProperty(Configurator.SENDMAIL_GOOGLE_PASSWORD);

    // Get directory
    String path = configurator.getConfigProperty(Configurator.SENDMAIL_DIR_PATH, null);
    if (path == null) {
        throw new NullPointerException("Missing parameter (" + Configurator.SENDMAIL_DIR_PATH + ")!");
    }
    directory = new File(path);
    if (!directory.isDirectory()) {
        directory.mkdirs();
        if (!directory.isDirectory()) {
            throw new Exception("Unable to read the sendmail directory (" + path + ")! Permission denied!");
        }
    }
    log.info("Start listening directory " + path + "...");
    log.info("Sendmail service started successfully.");

    // Start listener
    start();
}

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

Synchronizer(ThreadGroup mainGroup, Configurator configurator) throws Exception {
    super(mainGroup, "Synchronizer");
    setDaemon(true);/* ww  w . java 2 s  .  c  om*/

    // Show animated progress bar while synching
    if (configurator.getConfigProperty(Configurator.PROGRESS_ENABLED, false)) {
        if (GraphicsEnvironment.isHeadless()) {
            monitor = null;
            log.warn("Unable to use progress monitor in headless mode!");
        } else {
            monitor = new ProgressMonitor();
            setPriority(NORM_PRIORITY - 1);
        }
    } else {
        monitor = null;
    }

    // Pointer to the offline history file
    eventRegistryFile = new File(configurator.getWorkDirectory(), "event-registry.txt");

    // Enable to remove remote events in gCal (hidden feature)
    deleteEnabled = configurator.getConfigProperty(Configurator.REMOTE_DELETE_ENABLED, true);
    if (!deleteEnabled) {
        log.info("Remote event removal disabled.");
    }

    // Init global static variables
    GCalUtilities.globalInit();
    ICalUtilities.globalInit();
    if (configurator.isFeedConverterEnabled()) {
        FeedUtilities.globalInit();
    }

    // Start synchronizer's thread
    start();
}

From source file:org.jajuk.util.UtilSystem.java

/**
 * Return whether the Desktop BROWSE action is actually supported
 * Note this bug : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6486393
 * under KDE : isSupported returns true but we get an exception when actually browsing
 * /* www.  jav  a 2  s .com*/
 * @return true, if checks if is browser supported
 */
public static boolean isBrowserSupported() {
    // value stored for perf
    if (browserSupported != null) {
        return browserSupported;
    }
    // In server UT mode, just return false
    if (GraphicsEnvironment.isHeadless()) {
        return false;
    } else {
        if (Desktop.isDesktopSupported()) {
            // If under Linux, check if we're under KDE because of a sun bug,
            // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6486393 and #1612
            if (isUnderLinux() && isUnderKDE()) {
                return false;
            } else {
                return (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE));
            }
        } else {
            return false;
        }
    }
}

From source file:org.messic.service.MessicMain.java

public static void main(String[] args) throws BundleException, InterruptedException, IOException {

    File f = new File(".");
    String absolutePath = f.getAbsolutePath();
    System.setProperty("messic.app.folder", absolutePath.substring(0, absolutePath.length() - 2));

    String musicFolder = "";
    if (args.length > 0) {
        musicFolder = args[0];//from ww w .j  ava 2  s . c  o m
        File fMusicFolder = new File(musicFolder);
        if (!fMusicFolder.exists()) {
            fMusicFolder.mkdirs();
        }
    }
    System.setProperty("messic.musicfolder", musicFolder);

    File flagStarted = new File("./conf/messicStarted");
    if (flagStarted.exists()) {
        flagStarted.delete();
    }

    AnimatedGifSplashScreen agss = null;
    System.out.println("isHeadless?" + GraphicsEnvironment.isHeadless());
    if (!GraphicsEnvironment.isHeadless()) {
        //agss = new AnimatedGifSplashScreen();
    }

    deleteFelixCache();
    setJettyConfig();
    final Framework framework = createFramework();
    installBundles(framework);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println("[MESSIC] stopping service");
            closingEvent(framework);
            System.out.println("[MESSIC] service stopped");
        }
    });

    if (agss != null) {
        agss.dispose();
    }

    System.out.println(END_LOG);

    // just a file to know that it has been started
    FileOutputStream fos = new FileOutputStream(flagStarted);
    fos.write(END_LOG.getBytes());
    fos.close();
}

From source file:org.messic.starter.Starter.java

public static void main(String[] args) throws Exception {
    try {//ww w  . j av  a2 s  .c o  m
        CommandLine cmd = readOptions(args);
        if (cmd.hasOption(STARTER_OPTION_HELP) || cmd.hasOption(STARTER_OPTION_HELP2)) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("messic", createOptions());
            return;
        }

        boolean showGUI = Boolean.valueOf(cmd.getOptionValue(STARTER_OPTION_GUI, "true"));

        if (showGUI && !GraphicsEnvironment.isHeadless()) {
            System.out.println("[messic-monitor] Starting Messic Monitor");
            final boolean messicRunning = Util.isMessicRunning();
            showMonitor(messicRunning);
        } else {
            if (!showGUI) {
                System.out.println("Welcome to messic without GUI... ;D ");
                System.out.println("");
                System.out.println();
            }

            if (cmd.hasOption(STARTER_OPTION_CREATECONFIG)) {
                MessicConfig mc = new MessicConfig(true);
                Properties p = mc.getConfiguration();
                p.setProperty(MessicConfig.MESSIC_MUSICFOLDER,
                        System.getProperty("user.home") + File.separatorChar + "messic-data");
                mc.setConfiguration(p);
                mc.save();
                System.out.println("The default configuration has been created at the 'conf' folder.");
                return;
            }

            if (cmd.hasOption(STARTER_OPTION_STOP)) {
                System.out.println("Stopping Messic Service....");
                Util.stopMessicService();
                System.out.println("Done.");
                return;
            }
            if (cmd.hasOption(STARTER_OPTION_START)) {
                System.out.println("Launching Messic Service....");
                Util.launchMessicService(null, cmd.getOptionValue(STARTER_OPTION_JAVA));
                return;
            }

            // finally, if no options specified, we show the help message
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("messic", createOptions());
            return;
        }
    } finally {
        System.out.println();
        System.out.println("bye!");
    }

}

From source file:org.ngrinder.recorder.Recorder.java

private static void initEnvironment() throws Exception {
    if (GraphicsEnvironment.isHeadless()) {
        throw new NGrinderRuntimeException("nGrinder Recorder can not run in the headless environment");
    }//from  w w  w  .j av  a 2s . c  om
    System.setProperty("com.apple.eawt.CocoaComponent.CompatibilityMode", "false");
    System.setProperty("apple.laf.useScreenMenuBar", "false");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "nGrinder Recorder");
    System.setProperty("python.cachedir.skip", "true");
    System.setProperty("jxbrowser.ie.compatibility-disabled", "true");
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    UIManager.setLookAndFeel(getLookAndFeelClassName());
    // Make the jython is loaded in the background
    AsyncUtil.invokeAsync(new Runnable() {
        @Override
        public void run() {
            org.python.core.ParserFacade.parse("print 'hello'", CompileMode.exec, "unnamed",
                    new CompilerFlags(CompilerFlags.PyCF_DONT_IMPLY_DEDENT | CompilerFlags.PyCF_ONLY_AST));
        }

    });
}

From source file:org.openscience.jmol.app.JmolApp.java

private void checkOptions(CommandLine line, Options options) {
    if (line.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptSort());
        formatter.printHelp("Jmol", options);

        // now report on the -D options
        System.out.println();//from w  w w. java2s .c  om
        System.out.println(GT._("For example:"));
        System.out.println();
        System.out.println("Jmol -ions myscript.spt -w JPEG:myfile.jpg > output.txt");
        System.out.println();
        System.out.println(GT._(
                "The -D options are as follows (defaults in parenthesis) and must be called preceding '-jar Jmol.jar':"));
        System.out.println();
        System.out.println("  cdk.debugging=[true|false] (false)");
        System.out.println("  cdk.debug.stdout=[true|false] (false)");
        System.out.println("  display.speed=[fps|ms] (ms)");
        //System.out.println("  JmolConsole=[true|false] (true)");
        System.out.println("  logger.debug=[true|false] (false)");
        System.out.println("  logger.error=[true|false] (true)");
        System.out.println("  logger.fatal=[true|false] (true)");
        System.out.println("  logger.info=[true|false] (true)");
        System.out.println("  logger.logLevel=[true|false] (false)");
        System.out.println("  logger.warn=[true|false] (true)");
        System.out.println("  plugin.dir (unset)");
        System.out.println("  user.language=[ca|cs|de|en_GB|en_US|es|fr|hu|it|ko|nl|pt_BR|tr|zh_TW] (en_US)");

        System.exit(0);
    }

    if (line.hasOption("a")) {
        autoAnimationDelay = PT.parseFloat(line.getOptionValue("a"));
        if (autoAnimationDelay > 10)
            autoAnimationDelay /= 1000;
        Logger.info("setting autoAnimationDelay to " + autoAnimationDelay + " seconds");
    }

    // Process more command line arguments
    // these are also passed to vwr

    // debug mode
    if (line.hasOption("d")) {
        Logger.setLogLevel(Logger.LEVEL_DEBUG);
    }

    // note that this is set up so that if JmolApp is 
    // invoked with just new JmolApp(), we can 
    // set options ourselves. 

    info.put(isDataOnly ? "JmolData" : "Jmol", Boolean.TRUE);

    // kiosk mode -- no frame

    if (line.hasOption("k"))
        info.put("isKiosk", Boolean.valueOf(isKiosk = true));

    // port for JSON mode communication

    if (line.hasOption("P"))
        port = PT.parseInt(line.getOptionValue("P"));
    if (port > 0)
        info.put("port", Integer.valueOf(port));

    // print command output only (implies silent)

    if (line.hasOption("p"))
        isPrintOnly = true;
    if (isPrintOnly) {
        info.put("printOnly", Boolean.TRUE);
        isSilent = true;
    }

    // silent startup
    if (line.hasOption("i"))
        isSilent = true;
    if (isSilent)
        info.put("silent", Boolean.TRUE);

    // output to sysout
    if (line.hasOption("o"))
        haveConsole = false;
    if (!haveConsole) // might also be set in JmolData
        info.put("noConsole", Boolean.TRUE);

    // transparent background
    if (line.hasOption("b"))
        info.put("transparentBackground", Boolean.TRUE);

    // restricted file access
    if (line.hasOption("R"))
        info.put("access:NONE", Boolean.TRUE);

    // restricted file access (allow reading of SPT files)
    if (line.hasOption("r"))
        info.put("access:READSPT", Boolean.TRUE);

    // independent command thread
    if (line.hasOption("t"))
        info.put("useCommandThread", Boolean.TRUE);

    // list commands during script operation
    if (line.hasOption("l"))
        info.put("listCommands", Boolean.TRUE);

    // no splash screen
    if (line.hasOption("L"))
        splashEnabled = false;

    // check script only -- don't open files
    if (line.hasOption("c"))
        info.put("check", Boolean.TRUE);
    if (line.hasOption("C"))
        info.put("checkLoad", Boolean.TRUE);

    // menu file
    if (line.hasOption("m"))
        menuFile = line.getOptionValue("m");

    // run pre Jmol script
    if (line.hasOption("J"))
        script1 = line.getOptionValue("J");

    // use SparshUI
    if (line.hasOption("M"))
        info.put("multitouch", line.getOptionValue("M"));

    // run script from file
    if (line.hasOption("s")) {
        scriptFilename = line.getOptionValue("s");
    }

    // run post Jmol script
    if (line.hasOption("j")) {
        script2 = line.getOptionValue("j");
    }

    //Point b = null;    
    if (haveDisplay && historyFile != null) {
        Dimension size;
        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.1.2") < 0) {
            System.out.println("!!!WARNING: Swing components require a " + "1.1.2 or higher version VM!!!");
        }

        if (!isKiosk) {
            size = historyFile.getWindowSize("Jmol");
            if (size != null) {
                startupWidth = size.width;
                startupHeight = size.height;
            }
            historyFile.getWindowBorder("Jmol");
            // first one is just approximate, but this is set in doClose()
            // so it will reset properly -- still, not perfect
            // since it is always one step behind.
            //if (b == null || b.x > 50)
            border = new Point(12, 116);
            //else
            //border = new Point(b.x, b.y);
            // note -- the first time this is run after changes it will not work
            // because there is a bootstrap problem.
        }
    }
    // INNER frame dimensions
    int width = (isKiosk ? 0 : 500);
    int height = 500;

    if (line.hasOption("g")) {
        String geometry = line.getOptionValue("g");
        int indexX = geometry.indexOf('x');
        if (indexX > 0) {
            width = PT.parseInt(geometry.substring(0, indexX));
            height = PT.parseInt(geometry.substring(indexX + 1));
        } else {
            width = height = PT.parseInt(geometry);
        }
        startupWidth = -1;
    }

    if (startupWidth <= 0 || startupHeight <= 0) {
        if (haveDisplay && !isKiosk && border != null) {
            startupWidth = width + border.x;
            startupHeight = height + border.y;
        } else {
            startupWidth = width;
            startupHeight = height;
        }
    }

    // write image to clipboard or image file
    if (line.hasOption("w")) {
        int quality = -1;
        if (line.hasOption("q"))
            quality = PT.parseInt(line.getOptionValue("q"));
        String type_name = line.getOptionValue("w");
        if (type_name != null) {
            if (type_name.length() == 0)
                type_name = "JPG:jpg";
            if (type_name.indexOf(":") < 0)
                type_name += ":jpg";
            int i = type_name.indexOf(":");
            String type = type_name.substring(0, i).toUpperCase();
            type_name = type_name.substring(i + 1).trim();
            if (type.indexOf(" ") >= 0) {
                quality = PT.parseInt(type.substring(type.indexOf(" ")).trim());
                type.substring(0, type.indexOf(" "));
            }
            if (GraphicsEnvironment.isHeadless()) {
                Map<String, Object> data = new Hashtable<String, Object>();
                data.put("fileName", type_name);
                data.put("type", type);
                data.put("quality", Integer.valueOf(quality));
                data.put("width", Integer.valueOf(width));
                data.put("height", Integer.valueOf(height));
                info.put("headlessImage", data);
            } else
                script2 += ";write image " + (width > 0 && height > 0 ? width + " " + height : "") + " " + type
                        + " " + quality + " " + PT.esc(type_name);
        }
    }
    if (GraphicsEnvironment.isHeadless())
        info.put("headlistMaxTimeMs",
                Integer.valueOf(1000 * (line.hasOption("T") ? PT.parseInt(line.getOptionValue("T")) : 60)));

    // the next three are coupled -- if the -n command line option is 
    // given, but -I is not, then the -x is added, but not vice-versa. 
    // however, if this is an application-embedded object, then
    // it is ok to have no display and no exit.

    // scanner input
    if (line.hasOption("I"))
        scanInput = true;

    boolean exitUponCompletion = false;
    if (line.hasOption("n")) {
        // no display (and exit)
        haveDisplay = false;
        exitUponCompletion = !scanInput;
    }
    if (line.hasOption("x"))
        // exit when script completes (or file is read)
        exitUponCompletion = true;

    if (!haveDisplay)
        info.put("noDisplay", Boolean.TRUE);
    if (exitUponCompletion) {
        info.put("exit", Boolean.TRUE);
        script2 += ";exitJmol;";
    }

}