1

I need to render an html document that can have images stored both internally and externally. To render I use a library that will load these images by their urls (as referenced in the html).

What I'm doing is:

  1. for external images I use http:// urls normally.

  2. for images in the classpath I use a "classpath://" protocol in the url so I can redirect to it when the library is trying to load.

To do as in 2. I extend java.net.URLStreamHandler like follows:

public class ClasspathUrlHandler extends URLStreamHandler
{
    @Override
    protected URLConnection openConnection(URL relativeUrl) throws IOException
    {
        ClassLoader classLoader = getClass().getClassLoader();
        URL absoluteUrl = classLoader.getResource(relativeUrl.getPath());
        return absoluteUrl.openConnection();
    }
}

My problem now is that some images are stored as blob in the database and I can only access them as byte arrays. I can't get an absolute url to them like in the classpath case.

Is there a way I can create a URLConnection object based on a byte[]?

Note: I want URLConnection because that's what openConnection() in URLStreamHandler returns, like in the example.

Victor Basso
  • 5,556
  • 5
  • 42
  • 60
  • you can try writing that byte array to a file (probably temp file) and create a url to that file. just take care that these files get deleted too. –  May 16 '14 at 17:30
  • 1
    Is it 100% imperative you need a URLConnection. I'm guessing that for the rendering you need to open a stream (InputStream) from the URLConnection. If its not too much work it might be clearner to return InputStream from the classes, which would support URLConnection, Classpath Resource, Database Call, File etc without needing to override the URLConnection object – Ryan S May 16 '14 at 17:37
  • I agree with you. The whole point of java.io is to deal with multiple of sources like this (so it makes sanse to use InputStream as you say). I'm tied to the URLConnection because that's the way I found to intercept the loading within this library. I suspect I have to find another way around it. – Victor Basso May 16 '14 at 19:45

0 Answers0