View Javadoc
1   package org.argeo.cms.ui.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  
16  /** {@link ResourceLoader} caching stylesheets. */
17  public class StyleSheetResourceLoader implements ResourceLoader {
18  	private Bundle themeBundle;
19  	private Map<String, StyleSheet> stylesheets = new LinkedHashMap<String, StyleSheet>();
20  
21  	public StyleSheetResourceLoader(Bundle themeBundle) {
22  		this.themeBundle = themeBundle;
23  	}
24  
25  	@Override
26  	public InputStream getResourceAsStream(String resourceName) throws IOException {
27  		if (!stylesheets.containsKey(resourceName)) {
28  			// TODO deal with other bundles
29  			// Bundle bundle = bundleContext.getBundle();
30  			// String location =
31  			// bundle.getLocation().substring("initial@reference:".length());
32  			// if (location.startsWith("file:")) {
33  			// Path path = null;
34  			// try {
35  			// path = Paths.get(new URI(location));
36  			// } catch (URISyntaxException e) {
37  			// e.printStackTrace();
38  			// }
39  			// if (path != null) {
40  			// Path resourcePath = path.resolve(resourceName);
41  			// if (Files.exists(resourcePath))
42  			// return Files.newInputStream(resourcePath);
43  			// }
44  			// }
45  
46  			URL res = themeBundle.getEntry(resourceName);
47  			if (res == null)
48  				throw new CmsException(
49  						"Entry " + resourceName + " not found in bundle " + themeBundle.getSymbolicName());
50  			ByteArrayOutputStream out = new ByteArrayOutputStream();
51  			IOUtils.copy(res.openStream(), out);
52  			stylesheets.put(resourceName, new StyleSheet(out.toByteArray()));
53  		}
54  		return new ByteArrayInputStream(stylesheets.get(resourceName).getData());
55  		// return res.openStream();
56  	}
57  
58  	private class StyleSheet {
59  		private byte[] data;
60  
61  		public StyleSheet(byte[] data) {
62  			super();
63  			this.data = data;
64  		}
65  
66  		public byte[] getData() {
67  			return data;
68  		}
69  
70  	}
71  }