Как получить местоположение Image Ressource на сервере

Мне нужно получить URL-адрес используемых ресурсов в моем веб-приложении vaadin 7, в моем случае ресурс представляет собой изображение, которое может быть расположено в папке VAADIN/themes/themename/img или может быть основано в файле jar.

Итак, метод, который я хочу написать, имеет эту подпись:

   /**
    * Returns the URL for an image described with its name
    */ 
     public String getURL(String image) {
      ...
     }

person Amira    schedule 06.01.2014    source источник


Ответы (1)


Может быть медленным из-за банок.
Вам следует предварительно заполнить список нужными типами файлов.

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);
            }
        }
    }
}
person Krayo    schedule 15.09.2014