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:de.dal33t.powerfolder.Controller.java

/**
 * Answers if controller is started in console mode
 *
 * @return true if in console mode//from  w w w  . j a  v a2 s  .  com
 */
public boolean isConsoleMode() {
    if (commandLine != null) {
        if (commandLine.hasOption('s')) {
            return true;
        }
    }
    if (config != null) {
        if (ConfigurationEntry.DISABLE_GUI.getValueBoolean(this)) {
            return true;
        }
    }
    if (Feature.UI_ENABLED.isDisabled()) {
        return true;
    }
    return GraphicsEnvironment.isHeadless();
}

From source file:ffx.ui.MainPanel.java

/**
 * Save preferences to the user node/*  w ww.j a va 2 s  . c o m*/
 */
private void savePrefs() {
    String c = MainPanel.class.getName();
    if (!GraphicsEnvironment.isHeadless()) {
        preferences.putInt(c + ".x", frame.getLocation().x);
        preferences.putInt(c + ".y", frame.getLocation().y);
        preferences.putInt(c + ".width", frame.getWidth());
        preferences.putInt(c + ".height", frame.getHeight());
        preferences.putBoolean(c + ".system", mainMenu.isSystemShowing());
        preferences.putInt(c + ".divider", splitPane.getDividerLocation());
        preferences.putBoolean(c + ".menu", mainMenu.isMenuShowing());
        preferences.putBoolean(c + ".axis", mainMenu.isAxisShowing());
    }
    if (ip == null) {
        ip = new String("");
    }
    if (address != null) {
        String s = address.getHostAddress();
        if (s != null) {
            preferences.put(c + ".ip", s);
        }
        preferences.putInt(c + ".port", socketAddress.getPort());
    }
    preferences.put(c + ".cwd", pwd.toString());

    if (modelingPanel != null) {
        modelingPanel.savePrefs();
    }
    if (keywordPanel != null) {
        keywordPanel.savePrefs();
    }
    if (modelingShell != null) {
        modelingShell.savePrefs();
    }
    if (graphicsCanvas != null) {
        graphicsCanvas.savePrefs();
    }
}

From source file:org.apache.marmotta.splash.startup.StartupListener.java

/**
 * React on the AFTER_START_EVENT of Tomcat and startup the browser to point to the Marmotta installation. Depending
 * on the state of the Marmotta installation, the following actions are carried out:
 * <ul>/*from  ww  w  .  ja v  a 2s  . c o m*/
 *     <li>in case the Marmotta is started for the first time, show a dialog box with options to select which IP-address to use for
 *     configuring the Marmotta; the IP address will be stored in a separate properties file in MARMOTTA_HOME</li>
 *     <li>in case the Marmotta has already been configured but the IP address that was used is no longer existing on the server,
 *     show a warning dialog (this can happen e.g. for laptops with dynamically changing network configurations)</li>
 *     <li>otherwise, open a browser using the network address that was used previously</li>
 * </ul>
 *
 * @param event LifecycleEvent that has occurred
 */
@Override
public void lifecycleEvent(LifecycleEvent event) {
    if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) {
        if (!GraphicsEnvironment.isHeadless()) {

            String serverName = null;
            int serverPort = 0;

            // open browser window
            if (Desktop.isDesktopSupported()) {

                Properties startupProperties = getStartupProperties();
                if (startupProperties.getProperty("startup.host") != null
                        && startupProperties.getProperty("startup.port") != null) {

                    serverName = startupProperties.getProperty("startup.host");
                    serverPort = Integer.parseInt(startupProperties.getProperty("startup.port"));

                    if (!checkServerName(serverName) || serverPort != getServerPort()) {
                        MessageDialog.show("Warning", "Configured server name not found", "The host name ("
                                + serverName + ") that has been used to configure this \n"
                                + "installation is no longer available on this server. The system \n"
                                + "might behave unexpectedly. Please consider using a localhost configuration \n"
                                + "for systems with dynamic IP addresses!");
                    }

                } else {
                    // show a dialog listing all available addresses of this server and allowing the user to
                    // chose
                    List<Option> choices = new ArrayList<>();

                    Map<String, List<InetAddress>> addressList = listHostAddresses();

                    List<String> hostNames = new ArrayList<String>(addressList.keySet());
                    Collections.sort(hostNames);

                    int loopback = -1;
                    for (int i = 0; i < hostNames.size(); i++) {
                        String hostName = hostNames.get(i);
                        List<InetAddress> addresses = addressList.get(hostName);
                        String label = hostName + " \n(";
                        for (Iterator<InetAddress> it = addresses.iterator(); it.hasNext();) {
                            label += it.next().getHostAddress();
                            if (it.hasNext()) {
                                label += ", ";
                            }
                        }
                        label += ")";

                        String text;

                        if (addresses.get(0).isLoopbackAddress()) {
                            text = "Local IP-Address. Recommended for Laptop use or Demonstration purposes";
                            loopback = loopback < 0 ? i : loopback;
                        } else {
                            text = "Public IP-Address. Recommended for Workstation or Server use";
                        }

                        choices.add(new Option(label, text));
                    }

                    int choice = SelectionDialog.select("Select Server Address",
                            "Select host address to use for configuring the\nApache Marmotta Platform.",
                            WordUtils.wrap(
                                    "For demonstration purposes or laptop installations it is recommended to select \""
                                            + (loopback < 0 ? "localhost" : hostNames.get(loopback))
                                            + "\" below. For server and workstation installations, please select a public IP address.",
                                    60),
                            choices, loopback);

                    if (choice < 0) {
                        log.error("No Server Address selected, server will shut down.");
                        throw new IllegalArgumentException("No Server Addess was selected");
                    }

                    serverName = hostNames.get(choice);
                    serverPort = getServerPort();

                    startupProperties.setProperty("startup.host", serverName);
                    startupProperties.setProperty("startup.port", serverPort + "");

                    storeStartupProperties(startupProperties);
                }

                final Desktop desktop = Desktop.getDesktop();
                if (desktop.isSupported(Desktop.Action.BROWSE) && serverName != null && serverPort > 0) {
                    try {

                        URI uri = new URI("http", null, serverName, serverPort, "/", null, null);
                        desktop.browse(uri);

                    } catch (Exception e1) {
                        System.err.println("could not open browser window, message was: " + e1.getMessage());
                    }

                }
            }
        }

    }
}

From source file:org.apache.sling.reqanalyzer.impl.RequestAnalyzerWebConsole.java

private boolean canOpenSwingGui(final ServletRequest request) {
    try {//from   w  w w .  j a v  a 2 s .  co m
        return !GraphicsEnvironment.isHeadless()
                && InetAddress.getByName(request.getLocalAddr()).isLoopbackAddress();
    } catch (UnknownHostException e) {
        // unexpected, but still fall back to fail-safe false
        return false;
    }
}

From source file:org.apache.taverna.raven.plugins.ui.CheckForNoticeStartupHook.java

public boolean startup() {

    if (GraphicsEnvironment.isHeadless()) {
        return true; // if we are running headlessly just return
    }/*from   ww  w .  java2s.  c  o  m*/

    long noticeTime = -1;
    long lastCheckedTime = -1;

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(TIMEOUT);
    client.setTimeout(TIMEOUT);
    PluginManager.setProxy(client);
    String message = null;

    try {
        URI noticeURI = new URI(BASE_URL + "/" + version + "/" + SUFFIX);
        HttpMethod method = new GetMethod(noticeURI.toString());
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("HTTP status " + statusCode + " while getting " + noticeURI);
            return true;
        }
        String noticeTimeString = null;
        Header h = method.getResponseHeader("Last-Modified");
        message = method.getResponseBodyAsString();
        if (h != null) {
            noticeTimeString = h.getValue();
            noticeTime = format.parse(noticeTimeString).getTime();
            logger.info("NoticeTime is " + noticeTime);
        }

    } catch (URISyntaxException e) {
        logger.error("URI problem", e);
        return true;
    } catch (IOException e) {
        logger.info("Could not read notice", e);
    } catch (ParseException e) {
        logger.error("Could not parse last-modified time", e);
    }

    if (lastNoticeCheckFile.exists()) {
        lastCheckedTime = lastNoticeCheckFile.lastModified();
    }

    if ((message != null) && (noticeTime != -1)) {
        if (noticeTime > lastCheckedTime) {
            // Show the notice dialog
            JOptionPane.showMessageDialog(null, message, "Taverna notice", JOptionPane.INFORMATION_MESSAGE,
                    WorkbenchIcons.tavernaCogs64x64Icon);
            try {
                FileUtils.touch(lastNoticeCheckFile);
            } catch (IOException e) {
                logger.error("Unable to touch file", e);
            }
        }
    }
    return true;
}

From source file:org.datacleaner.bootstrap.Bootstrap.java

private void runInternal() throws FileSystemException {
    logger.info("Welcome to DataCleaner {}", Version.getVersion());

    // determine whether to run in command line interface mode
    final boolean cliMode = _options.isCommandLineMode();
    final CliArguments arguments = _options.getCommandLineArguments();

    logger.info("CLI mode={}, use -usage to view usage options", cliMode);

    if (cliMode) {

        try {//  w  ww  .  j  a  v a2  s  . c  om
            if (!GraphicsEnvironment.isHeadless()) {
                // hide splash screen
                final SplashScreen splashScreen = SplashScreen.getSplashScreen();
                if (splashScreen != null) {
                    splashScreen.close();
                }
            }
        } catch (Exception e) {
            // ignore this condition - may happen rarely on e.g. X windows
            // systems when the user is not authorized to access the
            // graphics environment.
            logger.trace("Swallowing exception caused by trying to hide splash screen", e);
        }

        if (arguments.isUsageMode()) {
            final PrintWriter out = new PrintWriter(System.out);
            try {
                CliArguments.printUsage(out);
            } finally {
                FileHelper.safeClose(out);
            }

            exitCommandLine(null, 1);
            return;
        }

        if (arguments.isVersionMode()) {
            final PrintWriter out = new PrintWriter(System.out);
            try {
                CliArguments.printVersion(out);
            } finally {
                FileHelper.safeClose(out);
            }

            exitCommandLine(null, 1);
            return;
        }
    }

    if (!cliMode) {
        // set up error handling that displays an error dialog
        final DCUncaughtExceptionHandler exceptionHandler = new DCUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

        // init the look and feel
        LookAndFeelManager.get().init();
    }

    // initially use a temporary non-persistent user preferences object.
    // This is just to have basic settings available for eg. resolving
    // files.
    final UserPreferences initialUserPreferences = new UserPreferencesImpl(null);

    final String configurationFilePath = arguments.getConfigurationFile();
    final FileObject configurationFile = resolveFile(configurationFilePath, "conf.xml", initialUserPreferences);

    Injector injector = Guice.createInjector(new DCModuleImpl(DataCleanerHome.get(), configurationFile));

    // configuration loading can be multithreaded, so begin early
    final DataCleanerConfiguration configuration = injector.getInstance(DataCleanerConfiguration.class);

    // log usage
    final UsageLogger usageLogger = injector.getInstance(UsageLogger.class);
    usageLogger.logApplicationStartup();

    if (cliMode) {
        // run in CLI mode

        int exitCode = 0;
        try (final CliRunner runner = new CliRunner(arguments)) {
            runner.run(configuration);
        } catch (Throwable e) {
            logger.error("Error occurred while running DataCleaner command line mode", e);
            exitCode = 1;
        } finally {
            exitCommandLine(configuration, exitCode);
        }
        return;
    } else {
        // run in GUI mode
        final AnalysisJobBuilderWindow analysisJobBuilderWindow;

        // initialize Mac OS specific settings
        final MacOSManager macOsManager = injector.getInstance(MacOSManager.class);
        macOsManager.init();

        // check for job file
        final String jobFilePath = _options.getCommandLineArguments().getJobFile();
        if (jobFilePath != null) {
            final FileObject jobFile = resolveFile(jobFilePath, null, initialUserPreferences);
            injector = OpenAnalysisJobActionListener.open(jobFile, configuration, injector);
        }

        final UserPreferences userPreferences = injector.getInstance(UserPreferences.class);

        analysisJobBuilderWindow = injector.getInstance(AnalysisJobBuilderWindow.class);

        final Datastore singleDatastore;
        if (_options.isSingleDatastoreMode()) {
            DatastoreCatalog datastoreCatalog = configuration.getDatastoreCatalog();
            singleDatastore = _options.getSingleDatastore(datastoreCatalog);
            if (singleDatastore == null) {
                logger.info("Single datastore mode was enabled, but datastore was null!");
            } else {
                logger.info("Initializing single datastore mode with {}", singleDatastore);
                analysisJobBuilderWindow.setDatastoreSelectionEnabled(false);
                analysisJobBuilderWindow.setDatastore(singleDatastore, true);
            }
        } else {
            singleDatastore = null;
        }

        // show the window
        analysisJobBuilderWindow.open();

        if (singleDatastore != null) {
            // this part has to be done after displaying the window (a lot
            // of initialization goes on there)
            final AnalysisJobBuilder analysisJobBuilder = analysisJobBuilderWindow.getAnalysisJobBuilder();
            try (final DatastoreConnection con = singleDatastore.openConnection()) {
                final InjectorBuilder injectorBuilder = injector.getInstance(InjectorBuilder.class);
                _options.initializeSingleDatastoreJob(analysisJobBuilder, con.getDataContext(),
                        injectorBuilder);
            }
        }

        final Image welcomeImage = _options.getWelcomeImage();
        if (welcomeImage != null) {
            // Ticket #834: make sure to show welcome dialog in swing's
            // dispatch thread.
            WidgetUtils.invokeSwingAction(new Runnable() {
                @Override
                public void run() {
                    final WelcomeDialog welcomeDialog = new WelcomeDialog(analysisJobBuilderWindow,
                            welcomeImage);
                    welcomeDialog.setVisible(true);
                }
            });
        }

        final WindowContext windowContext = injector.getInstance(WindowContext.class);

        // set up HTTP service for ExtensionSwap installation
        loadExtensionSwapService(userPreferences, windowContext, configuration, usageLogger);

        final ExitActionListener exitActionListener = _options.getExitActionListener();
        if (exitActionListener != null) {
            windowContext.addExitActionListener(exitActionListener);
        }
    }
}

From source file:org.datacleaner.test.scenario.OpenAnalysisJobTest.java

/**
 * A very broad integration test which opens a job with (more or less) all
 * built-in analyzers.//from  w  ww.  ja  v a2  s  . co m
 * 
 * @throws Exception
 */
public void testOpenJobWithManyAnalyzers() throws Exception {
    if (GraphicsEnvironment.isHeadless()) {
        System.out.println("!!! Skipping test because environment is headless: " + getName());
        return;
    }

    DCModule module = new DCModuleImpl();
    Injector injector = Guice.createInjector(module);
    DataCleanerConfiguration configuration = injector.getInstance(DataCleanerConfiguration.class);

    FileObject file = VFSUtils.getFileSystemManager()
            .resolveFile("src/test/resources/all_analyzers.analysis.xml");
    assertTrue(file.exists());

    injector = OpenAnalysisJobActionListener.open(file, configuration, injector);
    AnalysisJobBuilderWindow window = injector.getInstance(AnalysisJobBuilderWindow.class);

    assertNotNull(window);

    assertEquals("all_analyzers.analysis.xml", window.getJobFile().getName().getBaseName());

    ((AnalysisJobBuilderWindowImpl) window).updateStatusLabel();

    assertEquals("Job is correctly configured", window.getStatusLabelText());
}

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

/**
 * A very broad integration test which opens a result with (more or less)
 * all built-in analyzer results./*from   ww w.  j  av  a2 s .co  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 DCModuleImpl();

    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.datacleaner.widgets.properties.MultipleMappedEnumsPropertyWidgetTest.java

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

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

    final List<AnalyzerComponentBuilder<?>> analyzers;
    if (GraphicsEnvironment.isHeadless()) {
        analyzers = injector2.getInstance(AnalysisJobBuilder.class).getAnalyzerComponentBuilders();
    } else {/* w w w .ja  v a2  s  .  c  o m*/
        final AnalysisJobBuilderWindow window = injector2.getInstance(AnalysisJobBuilderWindow.class);
        analyzers = window.getAnalysisJobBuilder().getAnalyzerComponentBuilders();
    }

    assertEquals(2, analyzers.size());

    final AnalyzerComponentBuilder<?> 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 inputWidget = new MultipleMappedEnumsPropertyWidget(
            completenessAnalyzer, inputProperty, enumProperty);
    final PropertyWidget<Object[]> enumWidget = inputWidget.getMappedEnumsPropertyWidget();
    enumWidget.initialize(EnumerationValue.fromArray(enumValue));
    inputWidget.initialize(inputValue);
    inputWidget.onValueTouched(inputValue);
    enumWidget.onValueTouched(EnumerationValue.fromArray(enumValue));

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

From source file:org.datacleaner.windows.OpenAnalysisJobAsTemplateDialogTest.java

@Test
public void testCreateLoadingIcon() throws Exception {
    if (!GraphicsEnvironment.isHeadless()) {
        assertTrue(OpenAnalysisJobAsTemplateDialog.createLoadingIcon() instanceof LoadingIcon);
    }/*  w w w .  ja  v  a2  s.  c  om*/
}