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.paxle.desktop.impl.Activator.java

public void start(final BundleContext bc) throws Exception {

    // first we check whether the DI-bundle will able to work on the system
    if (GraphicsEnvironment.isHeadless()) {
        logger.fatal(//from  w w w  .  j  a  v a2 s  . com
                "Java runs in a headless environment, cannot initialize any graphical user interfaces, aborting");
        return;
    }

    uiClassLoader = this.getClass().getClassLoader();
    Thread.currentThread().setContextClassLoader(uiClassLoader);

    /* 
     * Configuring the classloader to use by the UIManager.
     * ATTENTION: do not remove this, otherwise we get ClassNotFoundExceptions 
     */
    UIManager.put("ClassLoader", this.getClass().getClassLoader());

    final float javaVersion = getJavaVersion();
    logger.debug(String.format("Detected java version: %f", Float.valueOf(javaVersion)));

    final Iterator<Map.Entry<Float, String>> implIt = KNOWN_IMPLS.entrySet().iterator();
    boolean started = false;

    // TODO: instantiate (and register) ServiceManager, DialogServices and the DICommandProvider here

    while (implIt.hasNext()) {
        final Map.Entry<Float, String> impl = implIt.next();

        // discard if not supported by JRE
        if (impl.getKey().floatValue() > javaVersion) {
            logger.info(String.format("Implementation %s skipped because of missing java version %f.",
                    impl.getValue(), impl.getKey()));
            continue;
        }

        try {
            // display icon
            initUI(bc, impl.getValue());
            started = true;
            logger.info(String.format("Successfully started bundle using backend '%s'", impl));
            break;
        } catch (Exception e) {
            final Throwable ex = ((e instanceof InvocationTargetException) ? e.getCause() : e);
            final String cause = ((ex instanceof UnsupportedOperationException)
                    ? "Java claims your system to not support the system-tray."
                    : ex.toString());
            final String err = String.format(
                    "Error starting bundle using backend '%s': %s Skipping implementation...", impl, cause);
            if (logger.isDebugEnabled()) {
                logger.error(err, ex);
            } else {
                logger.error(err);
            }
        }
    }
    if (!started)
        logger.fatal("No backends left, could not start bundle");
}

From source file:org.pentaho.platform.plugin.action.jfreereport.JFreeReportComponent.java

private boolean generateReport(final MasterReport report, final PentahoTableDataFactory factory)
        throws IOException {
    JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
    boolean result = false;
    try {/*from w ww .  j a v  a2  s.  c o  m*/
        applyThreadPriority();

        // this might be invalid in case the action is contained in a sub-directory.
        final String baseName = IOUtils.getInstance().stripFileExtension(getActionName());
        final String path = getSolutionPath();
        final PentahoResourceBundleFactory bundleFactory = new PentahoResourceBundleFactory(path, baseName,
                getSession());
        report.setResourceBundleFactory(bundleFactory);
        // set the default resourcebundle. This allows users to override the
        // resource-bundle in case they want to keep common strings in a common
        // collection.
        report.getReportConfiguration()
                .setConfigProperty(ResourceBundleFactory.DEFAULT_RESOURCE_BUNDLE_CONFIG_KEY, baseName);

        if (factory != null) {
            report.setDataFactory(factory);
        }

        String printerName = jFreeReportAction.getPrinterName().getStringValue();
        String outputFormat = jFreeReportAction.getOutputType().getStringValue();

        if (printerName != null) {
            result = print(report, getActionTitle(), printerName);
        } else if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_SWING.equals(outputFormat)) {
            if (GraphicsEnvironment.isHeadless()) {
                result = writeSwingPreview(report);
            }
            warn(Messages.getInstance().getString("JFreeReportAllContentComponent.WARN_HEADLESSMODE_ACTIVE")); //$NON-NLS-1$
        } else if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_HTML.equals(outputFormat)
                || AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_PDF.equals(outputFormat)
                || AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_XLS.equals(outputFormat)
                || AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_CSV.equals(outputFormat)
                || AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_RTF.equals(outputFormat)
                || AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_XML.equals(outputFormat)) {
            String mimeType = getMimeType(outputFormat);
            String fileExtention = getFileExtension(outputFormat);
            IContentItem contentItem = getContentItem(mimeType, fileExtention);
            OutputStream outputStream = null;
            if (contentItem != null) {
                outputStream = contentItem.getOutputStream(getActionName());
            } else {
                outputStream = getDefaultOutputStream(mimeType);
            }
            result = writeReport(outputFormat, report, outputStream,
                    jFreeReportAction.getReportGenerationYieldRate().getIntValue(0),
                    jFreeReportAction.getHtmlContentHandlerUrlPattern().getStringValue());
            if (contentItem != null) {
                contentItem.closeOutputStream();
            }
        } else {
            warn(Messages.getInstance().getString("JFreeReportAllContentComponent.WARN_NO_PRINTER_GIVEN")); //$NON-NLS-1$
        }
    } finally {
        if (factory != null) {
            // force close the factory
            factory.closeTables();
        }
    }
    return result;
}

From source file:org.pentaho.platform.plugin.action.jfreereport.outputs.JFreeReportAllContentComponent.java

@Override
protected boolean validateAction() {

    if (isDefinedInput(StandardSettings.PRINTER_NAME)) {
        component = new JFreeReportPrintComponent();
        return initAndValidate(component);
    }//from  w ww  . j  a  v a  2 s. c  o m

    if (isDefinedInput(AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE)) {

        String reportOutputType = getInputStringValue(AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE);
        if (getLogger().isDebugEnabled()) {
            debug(Messages.getInstance().getString("JFreeReport.DEBUG_OUTPUT_TYPE", reportOutputType)); //$NON-NLS-1$
        }
        if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_HTML.equals(reportOutputType)) {
            component = new JFreeReportHtmlComponent();
            return initAndValidate(component);
        } else if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_PDF.equals(reportOutputType)) {
            component = new JFreeReportPdfComponent();
            return initAndValidate(component);
        } else if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_XLS.equals(reportOutputType)) {
            component = new JFreeReportExcelComponent();
            return initAndValidate(component);
        } else if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_CSV.equals(reportOutputType)) {
            component = new JFreeReportCSVComponent();
            return initAndValidate(component);
        } else if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_RTF.equals(reportOutputType)) {
            component = new JFreeReportRTFComponent();
            return initAndValidate(component);
        } else if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_XML.equals(reportOutputType)) {
            component = new JFreeReportXmlComponent();
            return initAndValidate(component);
        } else if (AbstractJFreeReportComponent.REPORTALLCONTENT_OUTPUTTYPE_SWING.equals(reportOutputType)) {
            if (GraphicsEnvironment.isHeadless()) {
                component = new JFreeReportPreviewSwingComponent();
                return initAndValidate(component);
            }
            warn(Messages.getInstance().getString("JFreeReportAllContentComponent.WARN_HEADLESSMODE_ACTIVE")); //$NON-NLS-1$
            return false;
        } else {
            return false;
        }
    }
    warn(Messages.getInstance().getString("JFreeReportAllContentComponent.WARN_NO_PRINTER_GIVEN")); //$NON-NLS-1$
    return false;
}

From source file:org.pentaho.reporting.engine.classic.core.testsupport.DebugReportRunner.java

public static void showDialog(final MasterReport report) {
    if (GraphicsEnvironment.isHeadless()) {
        return;/*from w  w w . j  a  v a  2  s .  co m*/
    }

    final PreviewDialog dialog = new PreviewDialog(report);
    dialog.setModal(true);
    dialog.pack();
    LibSwingUtil.centerFrameOnScreen(dialog);
    dialog.setVisible(true);
}

From source file:org.pentaho.reporting.engine.classic.demo.ancient.demo.swingicons.SwingIconsDemoPanel.java

/**
 * Searches for the 'jlfgr_1_0.jar' file on the classpath, in the classpath directories and the working directory. If
 * that fails, the user is asked to choose the correct file.
 *
 * @return the URL to the graphics repository.
 *//*from  w  w w . jav  a 2 s  .  c  o  m*/
private URL findDataFile() {
    final URL url = ObjectUtilities.getResource("jlfgr-1_0.jar", SwingIconsDemoPanel.class);
    if (url != null) {
        return url;
    }
    final URL urlFromConfig = loadFromConfiguration();
    if (urlFromConfig != null) {
        return urlFromConfig;
    }

    final File localFile = new File("jlfgr-1_0.jar");
    if (localFile.exists() && localFile.canRead() && localFile.isFile()) {
        try {
            return localFile.toURI().toURL();
        } catch (MalformedURLException e) {
            logger.warn("Unable to form local file URL. Is there no local filesystem?");
        }
    }

    final File classpathFile = findFileOnClassPath("jlfgr-1_0.jar");
    if (classpathFile != null) {
        if (classpathFile.exists() && classpathFile.canRead() && classpathFile.isFile()) {
            try {
                return classpathFile.toURI().toURL();
            } catch (MalformedURLException e) {
                logger.warn("Unable to form local file URL. Is there no local filesystem?");
            }
        }
    }

    if (warnedUser == false && GraphicsEnvironment.isHeadless() == false) {
        warnedUser = true;
        final String title = "Unable to load the icons.";
        final String message = ("Unable to find 'jlfgr-1_0.jar'\n"
                + "Please make sure you have the Java Look and Feel Graphics Repository in "
                + "in your classpath, the same directory as the JFreeReport-jar files or in "
                + "the current working directory.\n\n" + "You may download this jar-file from: \n"
                + "http://java.sun.com/developer/techDocs/hi/repository/");
        JOptionPane.showMessageDialog(this, message, title, JOptionPane.ERROR_MESSAGE);
    }
    return null;
}

From source file:org.pentaho.reporting.libraries.base.util.SystemInformation.java

public static Map<String, String> getOtherProperties() {
    final LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
    map.put("File.CurrentDirAbs", new File(".").getAbsolutePath());//NON-NLS
    try {//w ww  .  j  a  v  a 2 s.c  o  m
        map.put("File.CurrentDirCanonical", new File(".").getCanonicalPath());//NON-NLS
    } catch (IOException e) {
        // ignore 
    }
    map.put("UIManager.LookAndFeel", UIManager.getLookAndFeel().getClass().getName());//NON-NLS
    map.put("Toolkit", Toolkit.getDefaultToolkit().getClass().getName());//NON-NLS
    if (GraphicsEnvironment.isHeadless() == false) {
        map.put("Toolkit.MenuShortcutKeyMask", //NON-NLS
                String.valueOf(Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));//NON-NLS
        map.put("Toolkit.ScreenResolution", String.valueOf(Toolkit.getDefaultToolkit().getScreenResolution()));//NON-NLS
        map.put("Toolkit.ScreenSize", String.valueOf(Toolkit.getDefaultToolkit().getScreenSize()));//NON-NLS
    }
    map.put("Runtime.availableProcessors", String.valueOf(Runtime.getRuntime().availableProcessors()));//NON-NLS
    map.put("Runtime.maximumMemory", String.valueOf(Runtime.getRuntime().maxMemory()));//NON-NLS

    addDesktopProperty(map, "awt.mouse.numButtons");//NON-NLS
    addDesktopProperty(map, "awt.multiClickInterval");//NON-NLS
    addDesktopProperty(map, "DnD.Autoscroll.cursorHysteresis");//NON-NLS
    addDesktopProperty(map, "DnD.Autoscroll.initialDelay");//NON-NLS
    addDesktopProperty(map, "DnD.Autoscroll.interval");//NON-NLS
    addDesktopProperty(map, "DnD.Cursor.CopyDrop");//NON-NLS
    addDesktopProperty(map, "DnD.Cursor.CopyNoDrop");//NON-NLS
    addDesktopProperty(map, "DnD.Cursor.LinkDrop");//NON-NLS
    addDesktopProperty(map, "DnD.Cursor.LinkNoDrop");//NON-NLS
    addDesktopProperty(map, "DnD.Cursor.MoveDrop");//NON-NLS
    addDesktopProperty(map, "DnD.Cursor.MoveNoDrop");//NON-NLS
    addDesktopProperty(map, "DnD.gestureMotionThreshold");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/CanChangeAccels");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/CursorThemeName");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/CursorThemeSize");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/FileChooserBackend");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/FontName");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/IMPreeditStyle");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/IMStatusStyle");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/KeyThemeName");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/MenuBarAccel");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/MenuImages");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/ShowInputMethodMenu");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/ShowUnicodeMenu");//NON-NLS
    addDesktopProperty(map, "gnome.Gtk/ToolbarStyle");//NON-NLS
    addDesktopProperty(map, "gnome.Net/CursorBlink");//NON-NLS
    addDesktopProperty(map, "gnome.Net/CursorBlinkTime");//NON-NLS
    addDesktopProperty(map, "gnome.Net/DndDragThreshold");//NON-NLS
    addDesktopProperty(map, "gnome.Net/DoubleClickTime");//NON-NLS
    addDesktopProperty(map, "gnome.Net/FallbackIconTheme");//NON-NLS
    addDesktopProperty(map, "gnome.Net/IconThemeName");//NON-NLS
    addDesktopProperty(map, "gnome.Net/ThemeName");//NON-NLS
    addDesktopProperty(map, "gnome.Xft/Antialias");//NON-NLS
    addDesktopProperty(map, "gnome.Xft/DPI");//NON-NLS
    addDesktopProperty(map, "gnome.Xft/Hinting");//NON-NLS
    addDesktopProperty(map, "gnome.Xft/HintStyle");//NON-NLS
    addDesktopProperty(map, "gnome.Xft/RGBA");//NON-NLS
    addDesktopProperty(map, "Shell.shellFolderManager");//NON-NLS
    addDesktopProperty(map, "win.3d.backgroundColor");//NON-NLS
    addDesktopProperty(map, "win.3d.darkShadowColor");//NON-NLS
    addDesktopProperty(map, "win.3d.highlightColor");//NON-NLS
    addDesktopProperty(map, "win.3d.lightColor");//NON-NLS
    addDesktopProperty(map, "win.3d.shadowColor");//NON-NLS
    addDesktopProperty(map, "win.ansiFixed.font");//NON-NLS
    addDesktopProperty(map, "win.button.textColor");//NON-NLS
    addDesktopProperty(map, "win.defaultGUI.font");//NON-NLS
    addDesktopProperty(map, "win.frame.backgroundColor");//NON-NLS
    addDesktopProperty(map, "win.frame.textColor");//NON-NLS
    addDesktopProperty(map, "win.item.highlightColor");//NON-NLS
    addDesktopProperty(map, "win.item.highlightTextColor");//NON-NLS
    addDesktopProperty(map, "win.menu.backgroundColor");//NON-NLS
    addDesktopProperty(map, "win.menubar.backgroundColor");//NON-NLS
    addDesktopProperty(map, "win.menu.font");//NON-NLS
    addDesktopProperty(map, "win.menu.keyboardCuesOn");//NON-NLS
    addDesktopProperty(map, "win.menu.textColor");//NON-NLS
    addDesktopProperty(map, "win.scrollbar.backgroundColor");//NON-NLS
    addDesktopProperty(map, "win.scrollbar.width");//NON-NLS
    addDesktopProperty(map, "win.text.grayedTextColor");//NON-NLS
    addDesktopProperty(map, "win.xpstyle.colorName");//NON-NLS
    addDesktopProperty(map, "win.xpstyle.dllName");//NON-NLS
    addDesktopProperty(map, "win.xpstyle.sizeName");//NON-NLS
    addDesktopProperty(map, "win.xpstyle.themeActive");//NON-NLS
    return map;
}

From source file:org.pentaho.reporting.libraries.pensol.JCRRepositoryTest.java

public void testJCRRepository() throws FileSystemException {
    if (GraphicsEnvironment.isHeadless()) {
        return;//from   www  . jav  a  2s  .co m
    }

    String url = "http://localhost:8080/pentaho";

    final ClientConfig config = new DefaultClientConfig();
    config.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
    Client client = Client.create(config);
    client.addFilter(new HTTPBasicAuthFilter("joe", "password"));

    final WebResource resource = client.resource(url + "/api/repo/files/children?depth=-1&filter=*");
    final RepositoryFileTreeDto tree = resource.path("").accept(MediaType.APPLICATION_XML_TYPE)
            .get(RepositoryFileTreeDto.class);

    printDebugInfo(tree);

    final List<RepositoryFileTreeDto> children = tree.getChildren();
    for (int i = 0; i < children.size(); i++) {
        final RepositoryFileTreeDto child = children.get(i);
        printDebugInfo(child);
    }

    /*
        final FileSystemOptions fileSystemOptions = new FileSystemOptions();
        final DefaultFileSystemConfigBuilder configBuilder = new DefaultFileSystemConfigBuilder();
        configBuilder.setUserAuthenticator(fileSystemOptions, new StaticUserAuthenticator(url, "joe", "password"));
        FileObject fileObject = VFS.getManager().resolveFile(url, fileSystemOptions);
            
        System.out.println(fileObject);
        FileObject inventoryReport = fileObject.resolveFile("public/steel-wheels/reports/Inventory.prpt");
        System.out.println(inventoryReport);
        System.out.println(inventoryReport.exists());
        final FileContent content = inventoryReport.getContent();
        System.out.println(content.getAttribute("param-service-url"));
        */
}

From source file:org.sonatype.flexmojos.plugin.compiler.AbstractFlexCompilerMojo.java

public Boolean getHeadlessServer() {
    if (headlessServer == null) {
        return GraphicsEnvironment.isHeadless();
    }//from  w  w w . ja  v  a  2s. c  o  m

    return headlessServer;
}

From source file:org.tinymediamanager.core.movie.tasks.MovieScrapeTask.java

@Override
protected void doInBackground() {
    initThreadPool(3, "scrape");
    start();//  w ww. ja  va 2s  .c  o  m

    smartScrapeList = new ArrayList<>(0);

    for (int i = 0; i < moviesToScrape.size(); i++) {
        Movie movie = moviesToScrape.get(i);
        submitTask(new Worker(movie));
    }
    waitForCompletionOrCancel();

    // initiate smart scrape
    if (!smartScrapeList.isEmpty() && !GraphicsEnvironment.isHeadless()) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    for (Movie movie : smartScrapeList) {
                        MovieChooserDialog dialogMovieChooser = new MovieChooserDialog(movie,
                                smartScrapeList.size() > 1 ? true : false);
                        if (!dialogMovieChooser.showDialog()) {
                            break;
                        }
                    }
                }
            });
        } catch (Exception e) {
            LOGGER.error("SmartScrape crashed " + e.getMessage());
        }
    }

    if (MovieModuleManager.MOVIE_SETTINGS.getSyncTrakt()) {
        TmmTask task = new SyncTraktTvTask(moviesToScrape, null);
        TmmTaskManager.getInstance().addUnnamedTask(task);
    }

    LOGGER.info("Done scraping movies)");
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Starts a thread and does a "ping" on our tracking server, sending the event (and the random UUID + some env vars).<br>
 * use "startup" / "shutdown" for tracking sessions
 * //from  w w  w  . j ava2s.  c  om
 * @param event
 *          The event for the GET request
 */
public static void trackEvent(final String event) {
    // should we track the event?
    Path disable = Paths.get("tmm.uuid.disable");
    if (Globals.settings.isEnableAnalytics() && !Files.exists(disable)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.currentThread().setName("trackEventThread");
                    Path uuidFile = Paths.get("tmm.uuid");

                    if (!Files.exists(uuidFile)) {
                        writeStringToFile(uuidFile, UUID.randomUUID().toString());
                    }

                    if (Files.exists(uuidFile)) {
                        String uuid = readFileToString(uuidFile);
                        System.setProperty("tmm.uuid", uuid);

                        String session = "";
                        if ("startup".equals(event)) {
                            session = "&sc=start";
                        } else if ("shutdown".equals(event)) {
                            session = "&sc=end";
                        }

                        // https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
                        // @formatter:off
                        String ga = "v=1" + "&tid=UA-35564534-5" + "&cid=" + uuid + "&an=tinyMediaManager"
                                + "&av=" + ReleaseInfo.getVersionForReporting() // project version OR svn/nightly/prerel string
                                + "&t=event" + "&ec=" + event + "&ea=" + event + "&aip=1" + "&je=1" + session
                                + "&ul=" + getEncProp("user.language") + "-" + getEncProp("user.country") // use real system language
                                + "&vp=" + TmmWindowSaver.getInstance().getInteger("mainWindowW") + "x"
                                + TmmWindowSaver.getInstance().getInteger("mainWindowH") + "&cd1="
                                + getEncProp("os.name") + "&cd2=" + getEncProp("os.arch") + "&cd3="
                                + getEncProp("java.specification.version") // short; eg 1.7
                                + "&cd4=" + ReleaseInfo.getVersion() // TMM version eg 2.5.5
                                + "&cd5=" + (Globals.isDonator() ? "1" : "0") + "&z="
                                + System.currentTimeMillis();
                        if (!GraphicsEnvironment.isHeadless()) {
                            ga += "&sr=" + java.awt.Toolkit.getDefaultToolkit().getScreenSize().width + "x"
                                    + java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;
                        }
                        // @formatter:on
                        Url url = new Url("https://ssl.google-analytics.com/collect?" + ga);

                        InputStream in = url.getInputStream();
                        if (in != null) {
                            try {
                                in.close();
                            } catch (Exception ignored) {
                            }
                        }
                    }
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    LOGGER.warn("could not ping our update server...");
                }
            }
        }).start();
    }
}