1
2
3
4
5
6
7
8
9
10
11 package org.mule.util;
12
13 import org.mule.api.registry.ServiceType;
14 import org.mule.config.ExceptionHelper;
15 import org.mule.transport.service.TransportFactory;
16
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.util.Properties;
20
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23
24
25
26
27 public class SpiUtils
28 {
29 private static final Log logger = LogFactory.getLog(SpiUtils.class);
30
31 public static final String SERVICE_ROOT = "META-INF/services/";
32
33
34 public static Properties findServiceDescriptor(ServiceType type, String name)
35 {
36 if (type.equals(ServiceType.TRANSPORT))
37 {
38
39 Properties tsd = findServiceDescriptor(type.getPath(), name, TransportFactory.class, false);
40
41 if (tsd == null)
42 {
43
44 tsd = findServiceDescriptor(type.getPath(), name, TransportFactory.class);
45 }
46
47 return tsd;
48 }
49 else if (type.equals(ServiceType.EXCEPTION))
50 {
51 return findServiceDescriptor(type.getPath(), name, ExceptionHelper.class);
52 }
53 else
54 {
55 logger.warn("Attempt to lookup unrecognized service type: " + type);
56 return null;
57 }
58
59 }
60
61 public static Properties findServiceDescriptor(String path, String name, Class currentClass)
62 {
63 return findServiceDescriptor(path, name, currentClass, true);
64 }
65
66
67
68
69 public static Properties findServiceDescriptor(String path, String name, Class currentClass, boolean fallbackToNonPreferred)
70 {
71
72
73
74 String preferredName = null;
75 String preferredPath = null;
76
77 if (!name.endsWith(".properties"))
78 {
79 name += ".properties";
80
81 preferredName = "preferred-" + name;
82 }
83
84 if (path.startsWith("/"))
85 {
86 path = path.substring(1);
87 }
88 if (!path.endsWith("/"))
89 {
90 path += "/";
91 }
92 if (path.startsWith(SERVICE_ROOT))
93 {
94 path += name;
95 }
96 else
97 {
98 preferredPath = SERVICE_ROOT + path + preferredName;
99 path = SERVICE_ROOT + path + name;
100 }
101 try
102 {
103
104 InputStream is = IOUtils.getResourceAsStream(preferredPath, currentClass, false, false);
105
106
107 if (is == null && fallbackToNonPreferred)
108 {
109 is = IOUtils.getResourceAsStream(path, currentClass, false, false);
110 }
111
112 if (is != null)
113 {
114 Properties props = new Properties();
115 try
116 {
117 props.load(is);
118 return props;
119 }
120 catch (IOException e)
121 {
122 logger.warn("Descriptor found but unable to load properties for service " + name);
123 return null;
124 }
125 }
126 else
127 {
128 return null;
129 }
130 }
131 catch (IOException e)
132 {
133 return null;
134 }
135 }
136 }