Search in sources :

Example 41 with HeadlessException

use of java.awt.HeadlessException in project jdk8u_jdk by JetBrains.

the class RasterPrinterJob method printDialog.

/**
     * Presents the user a dialog for changing properties of the
     * print job interactively.
     * The services browsable here are determined by the type of
     * service currently installed.
     * If the application installed a StreamPrintService on this
     * PrinterJob, only the available StreamPrintService (factories) are
     * browsable.
     *
     * @param attributes to store changed properties.
     * @return false if the user cancels the dialog and true otherwise.
     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
     * returns true.
     * @see java.awt.GraphicsEnvironment#isHeadless
     */
public boolean printDialog(final PrintRequestAttributeSet attributes) throws HeadlessException {
    if (GraphicsEnvironment.isHeadless()) {
        throw new HeadlessException();
    }
    DialogTypeSelection dlg = (DialogTypeSelection) attributes.get(DialogTypeSelection.class);
    // Check for native, note that default dialog is COMMON.
    if (dlg == DialogTypeSelection.NATIVE) {
        this.attributes = attributes;
        try {
            debug_println("calling setAttributes in printDialog");
            setAttributes(attributes);
        } catch (PrinterException e) {
        }
        setParentWindowID(attributes);
        boolean ret = printDialog();
        clearParentWindowID();
        this.attributes = attributes;
        return ret;
    }
    /* A security check has already been performed in the
         * java.awt.print.printerJob.getPrinterJob method.
         * So by the time we get here, it is OK for the current thread
         * to print either to a file (from a Dialog we control!) or
         * to a chosen printer.
         *
         * We raise privilege when we put up the dialog, to avoid
         * the "warning applet window" banner.
         */
    final GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
    PrintService service = (PrintService) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {

        public Object run() {
            PrintService service = getPrintService();
            if (service == null) {
                ServiceDialog.showNoPrintService(gc);
                return null;
            }
            return service;
        }
    });
    if (service == null) {
        return false;
    }
    PrintService[] services;
    StreamPrintServiceFactory[] spsFactories = null;
    if (service instanceof StreamPrintService) {
        spsFactories = lookupStreamPrintServices(null);
        services = new StreamPrintService[spsFactories.length];
        for (int i = 0; i < spsFactories.length; i++) {
            services[i] = spsFactories[i].getPrintService(null);
        }
    } else {
        services = (PrintService[]) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {

            public Object run() {
                PrintService[] services = PrinterJob.lookupPrintServices();
                return services;
            }
        });
        if ((services == null) || (services.length == 0)) {
            /*
                 * No services but default PrintService exists?
                 * Create services using defaultService.
                 */
            services = new PrintService[1];
            services[0] = service;
        }
    }
    Rectangle bounds = gc.getBounds();
    int x = bounds.x + bounds.width / 3;
    int y = bounds.y + bounds.height / 3;
    PrintService newService;
    // temporarily add an attribute pointing back to this job.
    PrinterJobWrapper jobWrapper = new PrinterJobWrapper(this);
    attributes.add(jobWrapper);
    try {
        newService = ServiceUI.printDialog(gc, x, y, services, service, DocFlavor.SERVICE_FORMATTED.PAGEABLE, attributes);
    } catch (IllegalArgumentException iae) {
        newService = ServiceUI.printDialog(gc, x, y, services, services[0], DocFlavor.SERVICE_FORMATTED.PAGEABLE, attributes);
    }
    attributes.remove(PrinterJobWrapper.class);
    if (newService == null) {
        return false;
    }
    if (!service.equals(newService)) {
        try {
            setPrintService(newService);
        } catch (PrinterException e) {
            /*
                 * The only time it would throw an exception is when
                 * newService is no longer available but we should still
                 * select this printer.
                 */
            myService = newService;
        }
    }
    return true;
}
Also used : HeadlessException(java.awt.HeadlessException) Rectangle(java.awt.Rectangle) PrinterException(java.awt.print.PrinterException) StreamPrintService(javax.print.StreamPrintService) DialogTypeSelection(javax.print.attribute.standard.DialogTypeSelection) GraphicsConfiguration(java.awt.GraphicsConfiguration) PrintService(javax.print.PrintService) StreamPrintService(javax.print.StreamPrintService) StreamPrintServiceFactory(javax.print.StreamPrintServiceFactory)

Example 42 with HeadlessException

use of java.awt.HeadlessException in project jdk8u_jdk by JetBrains.

the class RasterPrinterJob method pageDialog.

/**
     * return a PageFormat corresponding to the updated attributes,
     * or null if the user cancelled the dialog.
     */
public PageFormat pageDialog(final PrintRequestAttributeSet attributes) throws HeadlessException {
    if (GraphicsEnvironment.isHeadless()) {
        throw new HeadlessException();
    }
    DialogTypeSelection dlg = (DialogTypeSelection) attributes.get(DialogTypeSelection.class);
    // Check for native, note that default dialog is COMMON.
    if (dlg == DialogTypeSelection.NATIVE) {
        PrintService pservice = getPrintService();
        PageFormat pageFrmAttrib = attributeToPageFormat(pservice, attributes);
        setParentWindowID(attributes);
        PageFormat page = pageDialog(pageFrmAttrib);
        clearParentWindowID();
        // page object and as per spec, we should return null in that case.
        if (page == pageFrmAttrib) {
            return null;
        }
        updateAttributesWithPageFormat(pservice, page, attributes);
        return page;
    }
    final GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
    Rectangle bounds = gc.getBounds();
    int x = bounds.x + bounds.width / 3;
    int y = bounds.y + bounds.height / 3;
    PrintService service = (PrintService) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {

        public Object run() {
            PrintService service = getPrintService();
            if (service == null) {
                ServiceDialog.showNoPrintService(gc);
                return null;
            }
            return service;
        }
    });
    if (service == null) {
        return null;
    }
    if (onTop != null) {
        attributes.add(onTop);
    }
    ServiceDialog pageDialog = new ServiceDialog(gc, x, y, service, DocFlavor.SERVICE_FORMATTED.PAGEABLE, attributes, (Frame) null);
    pageDialog.show();
    if (pageDialog.getStatus() == ServiceDialog.APPROVE) {
        PrintRequestAttributeSet newas = pageDialog.getAttributes();
        Class amCategory = SunAlternateMedia.class;
        if (attributes.containsKey(amCategory) && !newas.containsKey(amCategory)) {
            attributes.remove(amCategory);
        }
        attributes.addAll(newas);
        return attributeToPageFormat(service, attributes);
    } else {
        return null;
    }
}
Also used : ServiceDialog(sun.print.ServiceDialog) HeadlessException(java.awt.HeadlessException) Rectangle(java.awt.Rectangle) DialogTypeSelection(javax.print.attribute.standard.DialogTypeSelection) PrintService(javax.print.PrintService) StreamPrintService(javax.print.StreamPrintService) GraphicsConfiguration(java.awt.GraphicsConfiguration) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) PageFormat(java.awt.print.PageFormat)

Example 43 with HeadlessException

use of java.awt.HeadlessException in project jmeter by apache.

the class MenuFactory method initializeMenus.

private static void initializeMenus() {
    try {
        List<String> guiClasses = ClassFinder.findClassesThatExtend(JMeterUtils.getSearchPaths(), new Class[] { JMeterGUIComponent.class, TestBean.class });
        Collections.sort(guiClasses);
        for (String name : guiClasses) {
            /*
                 * JMeterTreeNode and TestBeanGUI are special GUI classes, and
                 * aren't intended to be added to menus
                 *
                 * TODO: find a better way of checking this
                 */
            if (// $NON-NLS-1$
            name.endsWith("JMeterTreeNode") || name.endsWith("TestBeanGUI")) {
                // Don't try to instantiate these
                continue;
            }
            if (elementsToSkip.contains(name)) {
                // No point instantiating class
                log.info("Skipping {}", name);
                continue;
            }
            // Should the TestBean be hidden?
            boolean hideBean = false;
            JMeterGUIComponent item = null;
            try {
                Class<?> c = Class.forName(name);
                if (TestBean.class.isAssignableFrom(c)) {
                    TestBeanGUI tbgui = new TestBeanGUI(c);
                    hideBean = tbgui.isHidden() || (tbgui.isExpert() && !JMeterUtils.isExpertMode());
                    item = tbgui;
                } else {
                    item = (JMeterGUIComponent) c.newInstance();
                }
            } catch (NoClassDefFoundError e) {
                log.warn("Configuration error, probably corrupt or missing third party library(jar) ? Could not create class: {}. {}", name, e, e);
                continue;
            } catch (HeadlessException e) {
                // NOSONAR
                log.warn("Could not instantiate class: {}", name, e);
                continue;
            } catch (RuntimeException e) {
                throw e;
            } catch (Exception e) {
                // NOSONAR
                log.warn("Could not instantiate class: {}", name, e);
                continue;
            }
            if (hideBean || elementsToSkip.contains(item.getStaticLabel())) {
                log.info("Skipping {}", name);
                continue;
            } else {
                // Don't add it again
                elementsToSkip.add(name);
            }
            Collection<String> categories = item.getMenuCategories();
            if (categories == null) {
                log.debug("{} participates in no menus.", name);
                continue;
            }
            if (categories.contains(THREADS)) {
                threads.add(new MenuInfo(item, name));
            }
            if (categories.contains(FRAGMENTS)) {
                fragments.add(new MenuInfo(item, name));
            }
            if (categories.contains(TIMERS)) {
                timers.add(new MenuInfo(item, name));
            }
            if (categories.contains(POST_PROCESSORS)) {
                postProcessors.add(new MenuInfo(item, name));
            }
            if (categories.contains(PRE_PROCESSORS)) {
                preProcessors.add(new MenuInfo(item, name));
            }
            if (categories.contains(CONTROLLERS)) {
                controllers.add(new MenuInfo(item, name));
            }
            if (categories.contains(SAMPLERS)) {
                samplers.add(new MenuInfo(item, name));
            }
            if (categories.contains(NON_TEST_ELEMENTS)) {
                nonTestElements.add(new MenuInfo(item, name));
            }
            if (categories.contains(LISTENERS)) {
                listeners.add(new MenuInfo(item, name));
            }
            if (categories.contains(CONFIG_ELEMENTS)) {
                configElements.add(new MenuInfo(item, name));
            }
            if (categories.contains(ASSERTIONS)) {
                assertions.add(new MenuInfo(item, name));
            }
        }
    } catch (IOException e) {
        log.error("IO Exception while initializing menus.", e);
    }
}
Also used : HeadlessException(java.awt.HeadlessException) IOException(java.io.IOException) HeadlessException(java.awt.HeadlessException) IOException(java.io.IOException) TestBeanGUI(org.apache.jmeter.testbeans.gui.TestBeanGUI) JMeterGUIComponent(org.apache.jmeter.gui.JMeterGUIComponent)

Example 44 with HeadlessException

use of java.awt.HeadlessException in project jmeter by apache.

the class JMeterTest method getObjects.

public static Collection<Object> getObjects(Class<?> extendsClass) throws Exception {
    String exName = extendsClass.getName();
    Object myThis = "";
    Iterator<String> classes = ClassFinder.findClassesThatExtend(JMeterUtils.getSearchPaths(), new Class[] { extendsClass }).iterator();
    List<Object> objects = new LinkedList<>();
    String n = "";
    boolean caughtError = true;
    Throwable caught = null;
    try {
        while (classes.hasNext()) {
            n = classes.next();
            // TODO - improve this check
            if (n.endsWith("RemoteJMeterEngineImpl")) {
                // Don't try to instantiate remote server
                continue;
            }
            Class<?> c = null;
            try {
                c = Class.forName(n);
                try {
                    // Try with a parameter-less constructor first
                    objects.add(c.newInstance());
                } catch (InstantiationException e) {
                    caught = e;
                    try {
                        // Events often have this constructor
                        objects.add(c.getConstructor(new Class[] { Object.class }).newInstance(new Object[] { myThis }));
                    } catch (NoSuchMethodException f) {
                        // no luck. Ignore this class
                        if (!Enum.class.isAssignableFrom(c)) {
                            // ignore enums
                            System.out.println("o.a.j.junit.JMeterTest WARN: " + exName + ": NoSuchMethodException  " + n + ", missing empty Constructor or Constructor with Object parameter");
                        }
                    }
                }
            } catch (NoClassDefFoundError e) {
                // no luck. Ignore this class
                System.out.println("o.a.j.junit.JMeterTest WARN: " + exName + ": NoClassDefFoundError " + n + ":" + e.getMessage());
                e.printStackTrace(System.out);
            } catch (IllegalAccessException e) {
                caught = e;
                System.out.println("o.a.j.junit.JMeterTest WARN: " + exName + ": IllegalAccessException " + n + ":" + e.getMessage());
                e.printStackTrace(System.out);
            // We won't test restricted-access classes.
            } catch (HeadlessException | ExceptionInInitializerError e) {
                // EIIE can be caused by Headless
                caught = e;
                System.out.println("o.a.j.junit.JMeterTest Error creating " + n + " " + e.toString());
            } catch (Exception e) {
                caught = e;
                if (e instanceof RemoteException) {
                    // not thrown, so need to check here
                    System.out.println("o.a.j.junit.JMeterTest WARN: " + "Error creating " + n + " " + e.toString());
                } else {
                    throw new Exception("Error creating " + n, e);
                }
            }
        }
        caughtError = false;
    } finally {
        if (caughtError) {
            System.out.println("Last class=" + n);
            System.out.println("objects.size=" + objects.size());
            System.out.println("Last error=" + caught);
        }
    }
    if (objects.isEmpty()) {
        System.out.println("No classes found that extend " + exName + ". Check the following:");
        System.out.println("Search paths are:");
        String[] ss = JMeterUtils.getSearchPaths();
        for (String s : ss) {
            System.out.println(s);
        }
        if (!classPathShown) {
            // Only dump it once
            System.out.println("Class path is:");
            String cp = System.getProperty("java.class.path");
            String[] classPathElements = JOrphanUtils.split(cp, java.io.File.pathSeparator);
            for (String classPathElement : classPathElements) {
                System.out.println(classPathElement);
            }
            classPathShown = true;
        }
    }
    return objects;
}
Also used : HeadlessException(java.awt.HeadlessException) LinkedList(java.util.LinkedList) HeadlessException(java.awt.HeadlessException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RemoteException(java.rmi.RemoteException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) RemoteException(java.rmi.RemoteException)

Example 45 with HeadlessException

use of java.awt.HeadlessException in project JMRI by JMRI.

the class ReportContext method addScreenSize.

/**
     * Provide screen - size information. This is based on the
     * jmri.util.JmriJFrame calculation, but isn't refactored to there because
     * we also want diagnostic info
     */
public void addScreenSize() {
    try {
        // Find screen size. This throws null-pointer exceptions on
        // some Java installs, however, for unknown reasons, so be
        // prepared to fall back.
        JFrame dummy = new JFrame();
        try {
            Insets insets = dummy.getToolkit().getScreenInsets(dummy.getGraphicsConfiguration());
            Dimension screen = dummy.getToolkit().getScreenSize();
            addString("Screen size h:" + screen.height + ", w:" + screen.width + " Inset t:" + insets.top + ", b:" + insets.bottom + "; l:" + insets.left + ", r:" + insets.right);
        } catch (NoSuchMethodError ex) {
            Dimension screen = dummy.getToolkit().getScreenSize();
            addString("Screen size h:" + screen.height + ", w:" + screen.width + " (No Inset method available)");
        }
    } catch (HeadlessException ex) {
        // failed, fall back to standard method
        addString("(Cannot sense screen size due to " + ex.toString() + ")");
    }
    try {
        // Find screen resolution. Not expected to fail, but just in case....
        int dpi = Toolkit.getDefaultToolkit().getScreenResolution();
        addString("Screen resolution: " + dpi);
    } catch (HeadlessException ex) {
        addString("Screen resolution not available");
    }
    //Rectangle virtualBounds = new Rectangle();
    try {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        addString("Environment max bounds: " + ge.getMaximumWindowBounds());
        try {
            GraphicsDevice[] gs = ge.getScreenDevices();
            for (GraphicsDevice gd : gs) {
                GraphicsConfiguration[] gc = gd.getConfigurations();
                for (int i = 0; i < gc.length; i++) {
                    addString("bounds[" + i + "] = " + gc[i].getBounds());
                // virtualBounds = virtualBounds.union(gc[i].getBounds());
                }
                addString("Device: " + gd.getIDstring() + " bounds = " + gd.getDefaultConfiguration().getBounds() + " " + gd.getDefaultConfiguration().toString());
            }
        } catch (HeadlessException ex) {
            addString("Exception getting device bounds " + ex.getMessage());
        }
    } catch (HeadlessException ex) {
        addString("Exception getting max window bounds " + ex.getMessage());
    }
    // various Linux window managers
    try {
        Insets jmriInsets = JmriInsets.getInsets();
        addString("JmriInsets t:" + jmriInsets.top + ", b:" + jmriInsets.bottom + "; l:" + jmriInsets.left + ", r:" + jmriInsets.right);
    } catch (Exception ex) {
        addString("Exception getting JmriInsets" + ex.getMessage());
    }
}
Also used : Insets(java.awt.Insets) JmriInsets(jmri.util.JmriInsets) GraphicsDevice(java.awt.GraphicsDevice) HeadlessException(java.awt.HeadlessException) JFrame(javax.swing.JFrame) Dimension(java.awt.Dimension) GraphicsEnvironment(java.awt.GraphicsEnvironment) SocketException(java.net.SocketException) HeadlessException(java.awt.HeadlessException) GraphicsConfiguration(java.awt.GraphicsConfiguration)

Aggregations

HeadlessException (java.awt.HeadlessException)63 IOException (java.io.IOException)19 File (java.io.File)16 Point (java.awt.Point)8 GraphicsConfiguration (java.awt.GraphicsConfiguration)7 BufferedImage (java.awt.image.BufferedImage)7 Dimension (java.awt.Dimension)6 Rectangle (java.awt.Rectangle)6 ActionEvent (java.awt.event.ActionEvent)5 PrintService (javax.print.PrintService)5 StreamPrintService (javax.print.StreamPrintService)5 JFrame (javax.swing.JFrame)5 GraphicsDevice (java.awt.GraphicsDevice)4 GraphicsEnvironment (java.awt.GraphicsEnvironment)4 PrinterException (java.awt.print.PrinterException)4 DialogTypeSelection (javax.print.attribute.standard.DialogTypeSelection)4 ImageIcon (javax.swing.ImageIcon)4 JFileChooser (javax.swing.JFileChooser)4 Frame (java.awt.Frame)3 Graphics (java.awt.Graphics)3