0

I need to retrieve the url of used ressources in my vaadin 7 web application, in my case the ressource is an image which can be located in VAADIN/themes/themename/img folder or it can be founded in a jar file.

So the method i want to write has this signature :

   /**
    * Returns the URL for an image described with its name
    */ 
     public String getURL(String image) {
      ...
     }
Amira
  • 3,184
  • 13
  • 60
  • 95

1 Answers1

0

May be slow because of the jars.
You should fill a list previously with the file types that you want.

public String getURL(String image) {
    String realPath = VaadinServlet.getCurrent().getServletContext().getRealPath("/");
    List<String> list = new ArrayList<String>();
    search(image, new File(realPath), realPath, "", list);
    if (list.isEmpty()) {
        return null; // or error message
    }
    VaadinServletRequest r = (VaadinServletRequest) VaadinService.getCurrentRequest();
    return r.getScheme() + "://" + r.getServerName() + ":" + r.getServerPort()
            + r.getContextPath() + list.get(0); // or return all
}

private void search(String image, File file, String fullPath, String relPath, List<String> list) {
    if (file.isDirectory()) {
        for (String subFile : file.list()) {
            String newFullPath = fullPath + "/" + subFile;
            search(image, new File(newFullPath), newFullPath, relPath + "/" + subFile, list);
        }
    } else {
        if (image.equals(file.getName())) {
            list.add(relPath);
        }
        if (file.getName().endsWith(".jar")) {
            ZipInputStream zis = null;
            try {
                zis = new ZipInputStream(new FileInputStream(fullPath));
                ZipEntry entry = null;
                while ((entry = zis.getNextEntry()) != null) {
                    String name = entry.getName();
                    if (name.equals(image) || name.endsWith("/" + image)) {
                        list.add("/" + name);
                    }
                }
            } catch (Exception e) {
                // error handling
            } finally {
                IOUtils.closeQuietly(zis);
            }
        }
    }
}
Krayo
  • 2,492
  • 4
  • 27
  • 45