]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.core/src/main/java/org/argeo/slc/spring/SpringUtils.java
git-svn-id: https://svn.argeo.org/slc/trunk@1286 4cfe0d0a-d680-48aa-b62c-e0a02a3f76cc
[gpl/argeo-slc.git] / org.argeo.slc.core / src / main / java / org / argeo / slc / spring / SpringUtils.java
1 package org.argeo.slc.spring;
2
3 import java.io.IOException;
4 import java.net.URI;
5 import java.net.URL;
6 import java.util.Map;
7
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
10 import org.argeo.slc.core.SlcException;
11 import org.springframework.beans.factory.ListableBeanFactory;
12 import org.springframework.core.io.DefaultResourceLoader;
13 import org.springframework.core.io.Resource;
14
15 public class SpringUtils {
16 private final static Log log = LogFactory.getLog(SpringUtils.class);
17
18 public static <T> T loadSingleFromContext(ListableBeanFactory context,
19 Class<T> clss) {
20 Map<String, T> beans = context.getBeansOfType(clss);
21 if (beans.size() == 1) {
22 return beans.values().iterator().next();
23 } else {
24 return null;
25 }
26 }
27
28 public static Resource getParent(Resource res) {
29 try {
30 if (res.getURL().getPath().equals("/"))
31 return null;
32
33 String urlStr = res.getURL().toString();
34 if (urlStr.charAt(urlStr.length() - 1) == '/')
35 urlStr = urlStr.substring(0, urlStr.length() - 2);
36
37 String parentUrlStr = urlStr.substring(0, urlStr.lastIndexOf('/')) + '/';
38 URI uri = new URI(parentUrlStr).normalize();
39 return new DefaultResourceLoader(Thread.currentThread()
40 .getContextClassLoader()).getResource(uri.toString());
41 } catch (Exception e) {
42 throw new SlcException("Cannot get parent for resource " + res, e);
43 }
44 }
45
46 public static String extractRelativePath(Resource ancestor, Resource child) {
47 try {
48
49 return ancestor.getURI().relativize(child.getURI()).normalize()
50 .toString();
51 } catch (IOException e) {
52 throw new SlcException("Cannot extract relative path of " + child
53 + " based on " + ancestor, e);
54 }
55 }
56
57 private SpringUtils() {
58
59 }
60 }