Solved

Security exception on ImageIcon.getImage()

Posted on 2007-04-03
6
680 Views
Last Modified: 2012-06-21
Hi,

I'm writing an applet which uses images downloaded from google images. Generally this works fine but in some cases when the image isn't available i get a security exception which is not caught by the following code:
BufferedImage bufferedImage = null;
    try{
            //convert string to url as Imageicon gets url address.
            URL url = new URL(imageLink);
            //ensures that all pixels have been loaded before returning
            Image img = new ImageIcon(url).getImage();
            bufferedImage = getBufferedImageFromImage(img);
       } catch(Exception e) {
            e.printStackTrace();
       }
       return bufferedImage;
      
The error stack generated is:
Uncaught error fetching image:
java.lang.SecurityException
      at java.lang.SecurityManager.checkPermission(Unknown Source)
      at java.lang.SecurityManager.checkConnect(Unknown Source)
      at sun.awt.image.URLImageSource.checkSecurity(Unknown Source)
      at sun.awt.image.ImageRepresentation.imageComplete(Unknown Source)
      at sun.awt.image.InputStreamImageSource.errorConsumer(Unknown Source)
at sun.awt.image.InputStreamImageSource.setDecoder(Unknown Source)
      at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
      at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
      at sun.awt.image.ImageFetcher.run(Unknown Source)

Any comments would be appreciated.
Sophe
0
Comment
Question by:sophe
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 24

Expert Comment

by:sciuriware
ID: 18844877
Do you have access to that image file?
Generally you only have access to the server.

;JOOP!
0
 

Author Comment

by:sophe
ID: 18844973
sorry i don't understand your question.
it is simply using a url to a file found via google images.
here is an example url that causes this problem: http://6a.typepad.com/images/missing.gif 

sophe
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 18848670
Copy that image to your project and access it as local resource.
In general a random file is not accessible by a JAVA client because of security restrictions.
You can't access files local to the client without access being granted, the same for
files on some random system, otherwise the former situation could be 'circumvented'.
So, copy the image to the directory of one of your class files and load it as in this snippet:

   /**
    * Safely get the path to a resource file via Class info.
    * <p>If the file is missing, assuming that the resource was an image file,<BR>
    * the packaged <b>MISSING.gif</b> icon is substituted,
    * using the class info <b>packageClass</b> retrieved elsewhere.</p>
    * @param  classinfo   a Class loaded from the root of relative pathname.
    * @param  filename    the relative pathname to the resource file.
    * @return             an URL to the resulting resource.
    */
   private static URL findResource(Class classInfo, String filename)
   {
   URL resourceURL;

      if(classInfo == null)
      {
         fatal("BAD CLASS INFO");
      }

      if((resourceURL = classInfo.getResource(filename)) == null)
      {
         error("RESOURCE FILE '" + filename + "' MISSING.");
         if((resourceURL
            = packageClass.getResource("res/MISSING.gif")) == null)
         {
            fatal("SUBSTITUTE IMAGE 'MISSING' NOT FOUND.");
         }
      }
      return(resourceURL);
   }


// And deploying this in my program elsewhere (assume JFrame mainFrame;   ):

   /**
    * Set the default icon on the program main JFrame.
    * <p>Can be used to reset the icon after calls with an argument.<BR>
    * The default icon should be <b>res/<program>.gif</b>.</p>
    */
   public static void setMainFrameIcon( )
   {
      mainFrame.setIconImage
      (
         Toolkit.getDefaultToolkit().getImage(findResource(this.getClass( ), "res/Application.gif"))
      );
   }

;JOOP!
0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

Author Comment

by:sophe
ID: 18849340
The url is found dynamically by searching google images for a keyword entered by the user. This is done with the following code:
/**
*@param keyword is the object  to be searched in google
*/
public String makeURLCon (String keyword) {
    String source= null;
    try{
         //search Google images for the keyword
         URL url = new    
                URL("http://images.google.co.uk/images?svnum=10&hl=en&q="+keyword+"&btnG=Search");
                  
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            //Sets the general request property
            connection.setRequestProperty("User-agent","Mozilla/4.0");
            InputStream inputStrm = connection.getInputStream();
            source = readSource(inputStrm);
                  
      }catch (Exception e) {
            e.printStackTrace();
      }
      return source;
}

Generally if the applet sees the image can't be downloaded it moves on to the next url in the source. But this doesn't happen when a SecurityException is thrown for some reason.

So this means that i can't save each image manually.
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 18849627
If you are sure about that, simply catch it and go on searching:

    try
    {
// convert string to url as Imageicon gets url address.
            URL url = new URL(imageLink);
// ensures that all pixels have been loaded before returning
            Image img = new ImageIcon(url).getImage();
            bufferedImage = getBufferedImageFromImage(img);
    }
    catch(Exception e) { /* IGNORE EXCEPTION */ }

    return bufferedImage;

// See the corrected code, and heed my style.

;JOOP!
0
 
LVL 24

Accepted Solution

by:
sciuriware earned 250 total points
ID: 18849637
Additional remark:  the code that calls this must check that if null is returned
the decision must be made to retry or not!

And, on second thoughts,  it is better to replace the line:
                  catch(Exception e) { /* IGNORE EXCEPTION */ }
by:
                  catch(SecurityException e) { /* IGNORE EXCEPTION */ }

;JOOP!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
how to see all occupied ports on windows 10 laptop 15 84
hibernate example using maven 12 82
collection output issue 9 66
restrict decimal places for double datatype 10 34
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question