Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-5040674

Headless exceptions using j2sdk1.4.2_xx on windows and unix

XMLWordPrintable

    • beta
    • x86
    • windows_xp

        again");
                 ex1.printStackTrace();
                 return null;
             }
             return pictureName;
         }
        }

        class ImageTest extends JComponent
        {
        /**
        *
        */
        public ImageTest()
        {
        super();
        // TODO Auto-generated constructor stub
        }
        /* (non-Javadoc)
        * @see java.awt.Component#paint(java.awt.Graphics)
        */
        public void paint(Graphics g)
        {
        // TODO Auto-generated method stub
        g.setColor(java.awt.Color.yellow);
        g.fillRect(0, 0, getWidth(), getHeight());
        super.paint(g);
        }
        }

        I received this feedback from Sun:

        "It seems like a bug in JDK. VoltileImages are not supported in headless mode since they require support from the native graphics system that is not available. Swing uses volatileImages unconditionally during painting, and probably should first check if it is supported in the current graphics mode. I am not sure the usage demonstrated in the test program is declared to be supported in headless mode, but it seems reasonable to file a bug and we'll investigate."



        ======================================================================


        Name: rv122619 Date: 04/30/2004

        We are witnessing problems when running our headless Junit tests at 1.4.2 and 1.5. At 1.4.1 there are no issues. It appears to be related to the VolatileImageBuffer. This appears to now be used by the Jcomponent paint() method when there are lightweight children to be drawn. The following code shows the problem when run with the option -Djava.awt.headless. This works in all flavors of 1.4.1 and no flavors of 1.4.2 onward. Note the commented out code that will allow the code to run.

        import java.awt.BorderLayout;
        import java.awt.Graphics;
        import java.awt.GraphicsEnvironment;
        import java.awt.image.BufferedImage;
        import java.io.FileOutputStream;
        import java.io.OutputStream;

        import javax.swing.JComponent;
        import javax.swing.JPanel;
        import javax.swing.SwingUtilities;

        import com.sun.image.codec.jpeg.JPEGCodec;
        import com.sun.image.codec.jpeg.JPEGEncodeParam;
        import com.sun.image.codec.jpeg.JPEGImageEncoder;




        public class nonJunitBIPGraph_blc0018u
        {

         

          /**
           * Main method needed to make a self runnable class
           *
           * @param args This is required for main method
           */
          public static void main(String[] args) {
          
           System.out.println("headless: "+GraphicsEnvironment.isHeadless());

            internalTest();
            System.out.println("Done");
            System.exit(0);
          }
          
          // uncomment the following to allow the test to succeed
        // static
        // {
        // System.setProperty("swing.volatileImageBufferEnabled", "false");
        // }
          
          public static void internalTest()
          {
           System.out.println("Running InternalTest");
           JPanel p = new JPanel();
           p.setLayout(new BorderLayout());
           ImageTest a = new ImageTest();
           p.add(a);
           p.setSize(100,100);

           TestImageEncoders.saveAsImage( p, ".\\internalTest.png");

          }
        }

        /**
        * This class is for image encoding.
        *
        * @param name
        */
        class TestImageEncoders {
         /**
          * JPEG format
          * @param name */
        // static final public int JPEG = 0;
        // static final public int GRF = 1;
        // static final public int PNG = 2;
         static final public String JPEG = "jpg";
         static final public String GRF = "grf";
         static final public String PNG = "png";
         static public String globalImageType = "";
         
         // Image save sizes
         static final private int saveSizeX=600;
         static final private int saveSizeY=450;
         static final private int ganttSaveSizeX=1000;
         static final private int ganttSaveSizeY=650;
         
         static private displayImage tempImage = null;
         
         static private String testCaseDescription = "";
         // forcedHeadless is used to force me to go through the headless SaveImage code even
         // though the system has a head(java.awt.headless=false). The VDE has encountered problems
         // here.
         static boolean displayImageBeforeSaving = false;
        //
        // public static boolean imageEncoderFinished = false;
         /**
          * @param name */
         
         /** Creates a new instance of ImageEncoders */
         public TestImageEncoders() {
         }
         
         static public synchronized void setTestMethodName(String testName) {
             testCaseDescription = testName;
         }

        // static public synchronized void setImageType(String imageType) {
        // globalImageType = imageType;
        // }

        // static public synchronized String getImageType() {
        // return globalImageType;
        // }
         
         static public boolean showImageBeforeSaving() {
             return (displayImageBeforeSaving = Boolean.getBoolean("displayImageBeforeSaving"));
         }
         
         static public String getNewOutputFileImageType() {
             try {
                 return ((System.getProperty("saveOutputImageFileTypeAs")).toLowerCase().trim());
             } catch (Exception e) {
                 return null;
             }
         }
             
         /** Creates a new instance of ImageEncoders */
         private TestImageEncoders(final JComponent component, final String imageFileName, String imageType) {
             try {
                 tempImage = null;
                 SwingUtilities.invokeAndWait(new R(component, imageFileName, imageType));
                 if ((tempImage != null) && (showImageBeforeSaving())) {
                     tempImage.dispose();
                 }
             }
             catch (Exception e) {
                 try {
                      paintAndSave(component, imageFileName, imageType);
                 } catch (Exception ee) {
                     e.printStackTrace();
                     ee.printStackTrace();
                 }
             }
         }
         
         // A class for managing the image creation and painting of a component.
         static private class R implements Runnable {
             private JComponent component;
             private String imageFileName;
             private String imageType;
             
             public R(JComponent component, String imageFileName, String imageType) {
                 this.component=component;
                 this.imageFileName=imageFileName;
                 this.imageType=imageType;
             }
             
             public void run() {
                 paintAndSave(component, imageFileName, imageType);
             }
         }
         
         static private BufferedImage createImage(JComponent component) {
             component.addNotify();
             int sizeX, sizeY;
             
             sizeX=saveSizeX;
             sizeY=saveSizeY;
             component.setBounds(0, 0, sizeX, sizeY);
             BufferedImage image=new BufferedImage(sizeX, sizeY, BufferedImage.TYPE_INT_RGB);
             return image;
         }
         
         static private void paintAndSave(JComponent component, String imageFileName, String imageType) {
             BufferedImage bimage=createImage(component);
             component.validate();
             component.paint(bimage.getGraphics());
             
             if (showImageBeforeSaving()) {
                 if (GraphicsEnvironment.isHeadless()) {
                     System.out.println(" ");
                     System.out.println("NOTE: YOU ARE ATTEMPTING TO DISPLAY IMAGE(S) IN AN HEADLESS ENVIRONMENT.");
                     System.out.println("NOTE: YOU ARE GOING TO RECEIVE EXCEPTIONS.");
                     System.out.println(" ");
                 }
                 tempImage = new displayImage(component, bimage);
             }
               
         // I had to add this once I began saving png type images. Because of a QATrack limitation I have to save
         // my png images in a .grf file type(i.e. ttt.grf). This works ok for QAtrack but it does not work on a
         // local machine. Therefore I have to rename the file(i.e. from ttt.grf too ttt.png) so I can diff and
         // display it.
             if ((globalImageType != null) && (globalImageType != "")) {
                 if (imageFileName.trim().toLowerCase().endsWith(PNG)) {
                     imageFileName = imageFileName.replaceAll(("." + PNG), globalImageType);
                 }
                 else if (imageFileName.trim().toLowerCase().endsWith(GRF)) {
                     imageFileName = imageFileName.replaceAll(("." + GRF), globalImageType);
                 }
                 else if (imageFileName.trim().toLowerCase().endsWith(JPEG)) {
                     imageFileName = imageFileName.replaceAll(("." + JPEG), globalImageType);
                 }
             }
             if (imageType == PNG) {
                 try {
                     // Png Encoder
                     OutputStream os = new FileOutputStream(imageFileName);
                     javax.imageio.ImageIO.setUseCache(false);
                     javax.imageio.ImageIO.write(bimage, "png", new java.io.BufferedOutputStream(os));
                 } catch (Exception e) {
                     System.out.println("Exception occured when encoding and saving the PNG output image.");
                     e.printStackTrace();
                 }
             }
             else {
                 try {
                     OutputStream os = new FileOutputStream(imageFileName);
                     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                     JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
                     param.setQuality(1.0f, true);
                     encoder.encode(bimage, param);
                     os.close();
                 }
                 catch (Exception e) {
                     System.out.println("Exception occured when encoding and saving image.");
                     e.printStackTrace();
                 }
             }
         }
             
         static private class displayImage extends javax.swing.JDialog {
             BufferedImage bimage = null;
             JComponent component = null;
             int sizeX=0, sizeY=0;
                  
             public displayImage() {
             }
             
             public displayImage(JComponent component, BufferedImage bimage) {
                 this.bimage=bimage;
                 this.component=component;
                 sizeX=saveSizeX;
                 sizeY=saveSizeY;
                 component.validate();
                 component.paintAll(bimage.getGraphics());
                 setDefaultCloseOperation(javax.swing.JDialog.DISPOSE_ON_CLOSE);
                 setVisible(true);
                 setBounds(0, 0, sizeX, sizeY);
             }
                  
             public void paint(java.awt.Graphics g) {
                 g.drawImage(bimage, 0, 0, null);
                 super.paint(g);
             }
         }
         
         
         static public synchronized void saveAsImage(String testCaseDescrp, final JComponent comp, String pictureName) {
             setTestMethodName(testCaseDescrp);
             saveAsImage(comp, pictureName);
         }
         

         
         static public synchronized void saveAsImage(final JComponent comp, String myTitle, String pictureName) {
             saveAsImage("Unknown testcase name", comp, pictureName);
         }
         
                
         
         /**
          * Save the picture in the component to an image file named pictureName
          * with given image file type.
          *
          * @param comp
          * @param pictureName
          * @param imageType
          */
         static public void saveAsImage(final JComponent comp, String pictureName) {
             String imageType = "";
             pictureName = filenameErrorChecker(pictureName);
             if ((pictureName == null) || (pictureName).equals("")) {
                 return;
             }
             
             if (pictureName.trim().toLowerCase().endsWith(GRF)) {
                 imageType = GRF;
             }
             else if (pictureName.trim().toLowerCase().endsWith(JPEG)) {
                 imageType = JPEG;
             }
             else if (pictureName.trim().toLowerCase().endsWith(PNG)) {
                 imageType = PNG;
             }

             String tempOutputFileImageType = getNewOutputFileImageType();
             if ((tempOutputFileImageType != null) && (tempOutputFileImageType != "")) {
                 if ((!pictureName.trim().toLowerCase().endsWith(GRF)) &&
                     (!pictureName.trim().toLowerCase().endsWith(PNG)) &&
                     (!pictureName.trim().toLowerCase().endsWith(JPEG))) {
                         pictureName = pictureName.trim() + "." + tempOutputFileImageType;
                 }
                 globalImageType = "." + tempOutputFileImageType;
                 String tempImageFileName = pictureName;
                 if (tempImageFileName.trim().toLowerCase().endsWith(PNG)) {
                     tempImageFileName = tempImageFileName.replaceAll(("." + PNG), globalImageType);
                 }
                 else if (tempImageFileName.trim().toLowerCase().endsWith(GRF)) {
                     tempImageFileName = tempImageFileName.replaceAll(("." + GRF), globalImageType);
                 }
                 else if (tempImageFileName.trim().toLowerCase().endsWith(JPEG)) {
                     tempImageFileName = tempImageFileName.replaceAll(("." + JPEG), globalImageType);
                 }
                 System.out.println(" Saving " + tempOutputFileImageType.toUpperCase() + " Image... " + tempImageFileName + " ---> testCaseName:" + testCaseDescription);
             }
             else {
                 if ((!pictureName.trim().toLowerCase().endsWith(GRF)) &&
                     (!pictureName.trim().toLowerCase().endsWith(PNG)) &&
                     (!pictureName.trim().toLowerCase().endsWith(JPEG))) {
                         pictureName = pictureName.trim() + ".png"; //Default
                 }
                 if (imageType == JPEG) {
                     System.out.println(" Saving JPEG Image... " + pictureName + " ---> testCaseName:" + testCaseDescription);
                 }
                 else if (imageType == GRF) {
                     System.out.println(" Saving GRF Image... " + pictureName + " ---> testCaseName:" + testCaseDescription);
                 }
                 else if (imageType == PNG) {
                     System.out.println(" Saving PNG Image... " + pictureName + " ---> testCaseName:" + testCaseDescription);
                 }
             }
             new TestImageEncoders(comp, pictureName, imageType);
         }
         
         static public String filenameErrorChecker(String pictureName) {
             try {
                 try {
                     if ((pictureName.trim().equals(""))
                     || (pictureName.trim().equals(" "))
                     || (pictureName.trim() == null)) {
                         System.out.println("1 - Either the directory's path or the picture's filename(\"" + pictureName + "\") is invalid please try again");
                         return null;
                     }
                 }
                 catch (Exception ex1) {
                     System.out.println("2 - Either the directory's path or the picture's filename(\"" + pictureName + "\") is invalid please try again");
                     return null;
                 }
                 //If the pictureName has too many slashes(i.e. \\) then replace them with single slashes(i.e. \).
                 //Note: I 1st convert all the slashes to the forward slash("/") because replaceAll throws
                 //exceptions when processing backward slashes("\").
                 pictureName = pictureName.replace('\\', '/');
                 
                 //Now, replace any double slashes("//") with single slashes("/"), then replace the
                 //forward slashes("/") with the backward slashes("\").
                 while (pictureName.indexOf("//") >= 0) {
                     pictureName = pictureName.replaceAll("//", "/");
                 }
                 pictureName = pictureName.replace('/', '\\');
                 // System.out.println((System.getProperty("os.name")).toString().toLowerCase());
                 if (((System.getProperty("os.name")).toString().toLowerCase()).indexOf("windows") >= 0) {
                     //Windows OS
                     //When the pictures are on a server, make sure the path is ok(i.e. "\\dvt4\sss.gif" NOT "\dvt4\sss.gif")
                     if (pictureName.trim().startsWith("\\")) {
                         if (pictureName.trim().startsWith("\\\\")) {
                             //Do nothing the path is ok(i.e. \\dvt4\sss.gif)
                         }
                         else {
                             // Let's fix the path: Change the current path from "\dvt4\sss.gif" too "\\dvt4\sss.gif"
                             pictureName = "\\" + pictureName.trim();
                         }
                     }
                 }
                 else {
                     //NON-Windows OS
                     pictureName = pictureName.replace('\\', '/');
                 }
             }
             catch (Exception ex) {
                 //Let processing continue
             }
             try {
                 java.io.File tt = new java.io.File(pictureName);
                 if ((new java.io.File(tt.getParent())).exists()) {
                     //Do Nothing
                 }
                 else {
                     new java.io.File(tt.getParent()).mkdirs();
                     if (!(new java.io.File(tt.getParent())).exists()) {
                         System.out.println(
                         "3 - Either the directory's path or the picture's filename(\""
                         + pictureName
                         + "\") is invalid please try again");
                         return null;
                     }
                 }
             }
             catch (Exception ex1) {
                 System.out.println(
                 "4 - Either the directory's path or the picture's filename(\""
                 + pictureName
                 + "\") is invalid please try

              svioletsunw Scott Violet (Inactive)
              rverabel Raghu Verabelli (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              0 Start watching this issue

                Created:
                Updated:
                Resolved:
                Imported:
                Indexed: