]> git.argeo.org Git - lgpl/argeo-commons.git/blob - StyleSheetResourceLoader.java
a7e3b6e846ef6a93e85114aae26ee62f316205f8
[lgpl/argeo-commons.git] / StyleSheetResourceLoader.java
1 package org.argeo.cms.util;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.net.URL;
8 import java.util.LinkedHashMap;
9 import java.util.Map;
10
11 import org.apache.commons.io.IOUtils;
12 import org.argeo.cms.CmsException;
13 import org.eclipse.rap.rwt.service.ResourceLoader;
14 import org.osgi.framework.Bundle;
15 import org.osgi.framework.BundleContext;
16
17 /** {@link ResourceLoader} caching stylesheets. */
18 public class StyleSheetResourceLoader implements ResourceLoader {
19 private final BundleContext bundleContext;
20
21 private Map<String, StyleSheet> stylesheets = new LinkedHashMap<String, StyleSheet>();
22
23 public StyleSheetResourceLoader(BundleContext bundleContext) {
24 this.bundleContext = bundleContext;
25 }
26
27 @Override
28 public InputStream getResourceAsStream(String resourceName)
29 throws IOException {
30 if (!stylesheets.containsKey(resourceName)) {
31 // TODO deal with other bundles
32 Bundle bundle = bundleContext.getBundle();
33 // String location =
34 // bundle.getLocation().substring("initial@reference:".length());
35 // if (location.startsWith("file:")) {
36 // Path path = null;
37 // try {
38 // path = Paths.get(new URI(location));
39 // } catch (URISyntaxException e) {
40 // e.printStackTrace();
41 // }
42 // if (path != null) {
43 // Path resourcePath = path.resolve(resourceName);
44 // if (Files.exists(resourcePath))
45 // return Files.newInputStream(resourcePath);
46 // }
47 // }
48 URL res = bundle.getResource(resourceName);
49 if (res == null)
50 throw new CmsException("Resource " + resourceName
51 + " not found in bundle " + bundle.getSymbolicName());
52 ByteArrayOutputStream out = new ByteArrayOutputStream();
53 IOUtils.copy(res.openStream(), out);
54 stylesheets.put(resourceName, new StyleSheet(out.toByteArray()));
55 }
56 return new ByteArrayInputStream(stylesheets.get(resourceName).getData());
57 // return res.openStream();
58 }
59
60 private class StyleSheet {
61 private byte[] data;
62
63 public StyleSheet(byte[] data) {
64 super();
65 this.data = data;
66 }
67
68 public byte[] getData() {
69 return data;
70 }
71
72 }
73 }