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