/
FSClassLoaderProvider.java
362 lines (324 loc) · 12.2 KB
/
FSClassLoaderProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.commons.fsclassloader.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.sling.commons.classloader.ClassLoaderWriter;
import org.apache.sling.commons.classloader.ClassLoaderWriterListener;
import org.apache.sling.commons.classloader.DynamicClassLoaderManager;
import org.apache.sling.commons.fsclassloader.FSClassLoaderMBean;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ServiceScope;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>FSClassLoaderProvider</code> is a dynamic class loader provider
* which uses the file system to store and read class files from.
*
*/
@Component(service = ClassLoaderWriter.class, scope = ServiceScope.BUNDLE,
configurationPid = FSClassLoaderProvider.SHARED_CONFIGURATION_PID,
property = {
Constants.SERVICE_RANKING + ":Integer=100"
})
@Designate(ocd = FSClassLoaderComponentConfig.class)
public class FSClassLoaderProvider implements ClassLoaderWriter {
public static final String SHARED_CONFIGURATION_PID = "org.apache.sling.commons.fsclassloader.impl.FSClassLoaderProvider";
private static final String LISTENER_FILTER = "(" + Constants.OBJECTCLASS + "="
+ ClassLoaderWriterListener.class.getName() + ")";
/** File root */
private File root;
/** File root URL */
private URL rootURL;
/** Current class loader */
private FSDynamicClassLoader loader;
private static ServiceListener classLoaderWriterServiceListener;
private Map<Long, ServiceReference<ClassLoaderWriterListener>> classLoaderWriterListeners = new HashMap<Long, ServiceReference<ClassLoaderWriterListener>>();
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Reference(service = DynamicClassLoaderManager.class)
private ServiceReference<DynamicClassLoaderManager> dynamicClassLoaderManager;
/** The bundle asking for this service instance */
private Bundle callerBundle;
private static ServiceRegistration<?> mbeanRegistration;
/**
* Activate this component. Create the root directory.
*
* @param componentContext
* @throws MalformedURLException
* @throws InvalidSyntaxException
* @throws MalformedObjectNameException
*/
@Activate
protected void activate(final ComponentContext componentContext, final FSClassLoaderComponentConfig config)
throws MalformedURLException, InvalidSyntaxException, MalformedObjectNameException {
// get the file root
this.root = CacheLocationUtils.getRootDir(componentContext.getBundleContext(), config);
this.root.mkdirs();
this.rootURL = this.root.toURI().toURL();
this.callerBundle = componentContext.getUsingBundle();
classLoaderWriterListeners.clear();
if (classLoaderWriterServiceListener != null) {
componentContext.getBundleContext().removeServiceListener(classLoaderWriterServiceListener);
classLoaderWriterServiceListener = null;
}
classLoaderWriterServiceListener = new ServiceListener() {
@Override
public void serviceChanged(ServiceEvent event) {
ServiceReference<ClassLoaderWriterListener> reference = (ServiceReference<ClassLoaderWriterListener>) event
.getServiceReference();
if (event.getType() == ServiceEvent.MODIFIED || event.getType() == ServiceEvent.REGISTERED) {
classLoaderWriterListeners.put(getId(reference), reference);
} else {
classLoaderWriterListeners.remove(getId(reference));
}
}
private Long getId(ServiceReference<ClassLoaderWriterListener> reference) {
return (Long)reference.getProperty(Constants.SERVICE_ID);
}
};
componentContext.getBundleContext().addServiceListener(classLoaderWriterServiceListener, LISTENER_FILTER);
// handle the MBean Installation
if (mbeanRegistration != null) {
mbeanRegistration.unregister();
mbeanRegistration = null;
}
Hashtable<String, String> jmxProps = new Hashtable<String, String>();
jmxProps.put("type", "ClassLoader");
jmxProps.put("name", "FSClassLoader");
final Hashtable<String, Object> mbeanProps = new Hashtable<String, Object>();
mbeanProps.put(Constants.SERVICE_DESCRIPTION, "Apache Sling FSClassLoader Controller Service");
mbeanProps.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
mbeanProps.put("jmx.objectname", new ObjectName("org.apache.sling.classloader", jmxProps));
mbeanRegistration = componentContext.getBundleContext().registerService(FSClassLoaderMBean.class.getName(),
new FSClassLoaderMBeanImpl(this, this.root), mbeanProps);
}
/**
* Deactivate this component. Create the root directory.
*/
@Deactivate
protected void deactivate(ComponentContext componentContext) {
this.root = null;
this.rootURL = null;
this.destroyClassLoader();
if (classLoaderWriterServiceListener != null) {
componentContext.getBundleContext().removeServiceListener(classLoaderWriterServiceListener);
}
if (mbeanRegistration != null) {
mbeanRegistration.unregister();
mbeanRegistration = null;
}
}
private void destroyClassLoader() {
final ClassLoader rcl = this.loader;
if (rcl != null) {
this.loader = null;
final ServiceReference<DynamicClassLoaderManager> localDynamicClassLoaderManager = this.dynamicClassLoaderManager;
final Bundle localCallerBundle = this.callerBundle;
if (localDynamicClassLoaderManager != null && localCallerBundle != null) {
try {
localCallerBundle.getBundleContext().ungetService(localDynamicClassLoaderManager);
} catch (Exception ex) {
// Ignore, this is a best effort - likely the calling bundle has been stopped already
}
}
}
}
/**
* @see org.apache.sling.commons.classloader.ClassLoaderWriter#getClassLoader()
*/
@Override
public ClassLoader getClassLoader() {
synchronized (this) {
if (loader == null || !loader.isLive()) {
this.destroyClassLoader();
// get the dynamic class loader for the bundle using this
// class loader writer
final DynamicClassLoaderManager dclm = this.callerBundle.getBundleContext()
.getService(this.dynamicClassLoaderManager);
loader = new FSDynamicClassLoader(new URL[] { this.rootURL }, dclm.getDynamicClassLoader());
}
return this.loader;
}
}
private void checkClassLoader(final String filePath) {
if (filePath.endsWith(".class")) {
// remove store directory and .class
final String path = filePath.substring(this.root.getAbsolutePath().length() + 1, filePath.length() - 6);
// convert to a class name
final String className = path.replace(File.separatorChar, '.');
synchronized (this) {
final FSDynamicClassLoader currentLoader = this.loader;
if (currentLoader != null) {
currentLoader.check(className);
}
}
}
}
// ---------- SCR Integration ----------------------------------------------
private boolean deleteRecursive(final File f, final List<String> names) {
if (f.isDirectory()) {
for (final File c : f.listFiles()) {
if (!deleteRecursive(c, names)) {
return false;
}
}
}
names.add(f.getAbsolutePath());
return f.delete();
}
/**
* @see org.apache.sling.commons.classloader.ClassLoaderWriter#delete(java.lang.String)
*/
@Override
public boolean delete(final String name) {
final String path = cleanPath(name);
final File file = new File(path);
if (file.exists()) {
final List<String> names = new ArrayList<String>();
final boolean result = deleteRecursive(file, names);
logger.debug("Deleted {} : {}", name, result);
if (result) {
for (final String n : names) {
this.checkClassLoader(n);
}
for (ServiceReference<ClassLoaderWriterListener> reference : classLoaderWriterListeners.values()) {
if (reference != null) {
ClassLoaderWriterListener listener = callerBundle.getBundleContext().getService(reference);
if (listener != null) {
listener.onClassLoaderClear(name);
} else {
logger.warn("Found ClassLoaderWriterListener Service reference with no service bound");
}
}
}
}
return result;
}
// file does not exist so we return false
return false;
}
/**
* @see org.apache.sling.commons.classloader.ClassLoaderWriter#getOutputStream(java.lang.String)
*/
@Override
public OutputStream getOutputStream(final String name) {
logger.debug("Get stream for {}", name);
final String path = cleanPath(name);
final File file = new File(path);
final File parentDir = file.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
try {
if (file.exists()) {
this.checkClassLoader(path);
}
return new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* @see org.apache.sling.commons.classloader.ClassLoaderWriter#rename(java.lang.String,
* java.lang.String)
*/
@Override
public boolean rename(final String oldName, final String newName) {
logger.debug("Rename {} to {}", oldName, newName);
final String oldPath = cleanPath(oldName);
final String newPath = cleanPath(newName);
final File old = new File(oldPath);
final boolean result = old.renameTo(new File(newPath));
if (result) {
this.checkClassLoader(oldPath);
this.checkClassLoader(newPath);
}
return result;
}
/**
* Clean the path by converting slashes to the correct format and prefixing
* the root directory.
*
* @param path
* The path
* @return The file path
*/
private String cleanPath(String path) {
// replace backslash by slash
path = path.replace('\\', '/');
// cut off trailing slash
while (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
if (File.separatorChar != '/') {
path = path.replace('/', File.separatorChar);
}
return this.root.getAbsolutePath() + path;
}
/**
* @see org.apache.sling.commons.classloader.ClassLoaderWriter#getInputStream(java.lang.String)
*/
@Override
public InputStream getInputStream(final String name) throws IOException {
logger.debug("Get input stream of {}", name);
final String path = cleanPath(name);
final File file = new File(path);
return new FileInputStream(file);
}
/**
* @see org.apache.sling.commons.classloader.ClassLoaderWriter#getLastModified(java.lang.String)
*/
@Override
public long getLastModified(final String name) {
logger.debug("Get last modified of {}", name);
final String path = cleanPath(name);
final File file = new File(path);
if (file.exists()) {
return file.lastModified();
}
// fallback to "non-existant" in case of problems
return -1;
}
}