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