]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.core/src/main/java/org/argeo/slc/spring/SpringUtils.java
Make assert SlcExecution cover underlying steps
[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.BeanUtils;
12 import org.springframework.beans.factory.BeanFactoryUtils;
13 import org.springframework.beans.factory.ListableBeanFactory;
14 import org.springframework.core.io.DefaultResourceLoader;
15 import org.springframework.core.io.Resource;
16
17 public class SpringUtils {
18 private final static Log log = LogFactory.getLog(SpringUtils.class);
19
20 public static <T> T loadSingleFromContext(ListableBeanFactory context,
21 Class<T> clss) {
22 // Map<String, T> beans = context.getBeansOfType(clss);
23 Map<String, T> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
24 context, clss, false, false);
25 if (beans.size() == 1) {
26 return beans.values().iterator().next();
27 } else if (beans.size() > 1) {
28 if (log.isDebugEnabled()) {
29 log
30 .debug(("Found more that on bean for type " + clss
31 + ": " + beans.keySet()));
32 }
33 return null;
34 } else {
35 return null;
36 }
37 }
38
39 public static Resource getParent(Resource res) {
40 try {
41 if (res.getURL().getPath().equals("/"))
42 return null;
43
44 String urlStr = res.getURL().toString();
45 if (urlStr.charAt(urlStr.length() - 1) == '/')
46 urlStr = urlStr.substring(0, urlStr.length() - 2);
47
48 String parentUrlStr = urlStr.substring(0, urlStr.lastIndexOf('/')) + '/';
49 URI uri = new URI(parentUrlStr).normalize();
50 return new DefaultResourceLoader(Thread.currentThread()
51 .getContextClassLoader()).getResource(uri.toString());
52 } catch (Exception e) {
53 throw new SlcException("Cannot get parent for resource " + res, e);
54 }
55 }
56
57 public static String extractRelativePath(Resource ancestor, Resource child) {
58 try {
59
60 return ancestor.getURI().relativize(child.getURI()).normalize()
61 .toString();
62 } catch (IOException e) {
63 throw new SlcException("Cannot extract relative path of " + child
64 + " based on " + ancestor, e);
65 }
66 }
67
68 private SpringUtils() {
69
70 }
71 }