-
Notifications
You must be signed in to change notification settings - Fork 55
/
ConfigurationListener.java
executable file
·635 lines (505 loc) · 24.8 KB
/
ConfigurationListener.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/*
* Copyright (c) 2014, 2024 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.hk2.configuration.internal;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import jakarta.annotation.PostConstruct;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import org.glassfish.hk2.api.ActiveDescriptor;
import org.glassfish.hk2.api.DescriptorVisibility;
import org.glassfish.hk2.api.DynamicConfiguration;
import org.glassfish.hk2.api.DynamicConfigurationListener;
import org.glassfish.hk2.api.DynamicConfigurationService;
import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.Visibility;
import org.glassfish.hk2.configuration.api.ConfiguredBy;
import org.glassfish.hk2.configuration.api.PostDynamicChange;
import org.glassfish.hk2.configuration.api.PreDynamicChange;
import org.glassfish.hk2.configuration.hub.api.BeanDatabase;
import org.glassfish.hk2.configuration.hub.api.BeanDatabaseUpdateListener;
import org.glassfish.hk2.configuration.hub.api.Change;
import org.glassfish.hk2.configuration.hub.api.Hub;
import org.glassfish.hk2.configuration.hub.api.Instance;
import org.glassfish.hk2.configuration.hub.api.Type;
import org.glassfish.hk2.utilities.BuilderHelper;
import org.glassfish.hk2.utilities.reflection.ClassReflectionHelper;
import org.glassfish.hk2.utilities.reflection.MethodWrapper;
import org.glassfish.hk2.utilities.reflection.ReflectionHelper;
import org.glassfish.hk2.utilities.reflection.internal.ClassReflectionHelperImpl;
/**
* @author jwells
*
*/
@Singleton
@Visibility(DescriptorVisibility.LOCAL)
public class ConfigurationListener implements BeanDatabaseUpdateListener {
@Inject
private Hub hub;
@Inject
private ServiceLocator locator;
@Inject
private DynamicConfigurationService configurationService;
@Inject
private ConfiguredByInjectionResolver injectionResolver;
@Inject
private ConfiguredByContext context;
private final ConcurrentHashMap<String, ModificationInformation> typeInformation =
new ConcurrentHashMap<String, ModificationInformation>();
private final ReentrantLock progenitorLock = new ReentrantLock();
private HashSet<ActiveDescriptor<?>> allProgenitors =
new HashSet<ActiveDescriptor<?>>();
@PostConstruct
private void postConstruct() {
initialize(hub.getCurrentDatabase());
}
private ActiveDescriptor<?> addInstanceDescriptor(DynamicConfiguration config, ActiveDescriptor<?> parent, String name, String type, Object bean, Object metadata) {
DelegatingNamedActiveDescriptor addMe = new DelegatingNamedActiveDescriptor(parent, name);
ActiveDescriptor<?> systemDescriptor = config.addActiveDescriptor(addMe);
injectionResolver.addBean(systemDescriptor, bean, type, metadata);
return systemDescriptor;
}
private boolean invokePreMethod(Object target,
List<PropertyChangeEvent> changes,
String typeName) {
ModificationInformation modInfo = typeInformation.get(typeName);
if (modInfo == null) {
return true;
}
Method preMethod = modInfo.getPreDynamicChangeMethod(target.getClass());
if (preMethod == null) {
return true;
}
Class<?> params[] = preMethod.getParameterTypes();
Object result = null;
if (params.length <= 0) {
try {
result = ReflectionHelper.invoke(target, preMethod, new Object[0], true);
}
catch (Throwable th) {
return true;
}
}
else if (params.length == 1) {
if (!List.class.isAssignableFrom(params[0])) return true;
Object pValues[] = new Object[1];
pValues[0] = Collections.unmodifiableList(changes);
try {
result = ReflectionHelper.invoke(target, preMethod, pValues, true);
}
catch (Throwable th) {
return true;
}
}
else {
return true;
}
if (result == null || !(result instanceof Boolean)) {
return true;
}
Boolean b = (Boolean) result;
return b;
}
private void invokePostMethod(Object target,
List<PropertyChangeEvent> changes,
String typeName) {
ModificationInformation modInfo = typeInformation.get(typeName);
if (modInfo == null) return;
Method postMethod = modInfo.getPostDynamicChangeMethod(target.getClass());
if (postMethod == null) return;
Class<?> params[] = postMethod.getParameterTypes();
if (params.length <= 0) {
try {
ReflectionHelper.invoke(target, postMethod, new Object[0], true);
}
catch (Throwable th) {
return;
}
}
else if (params.length == 1) {
if (!List.class.isAssignableFrom(params[0])) return;
Object pValues[] = new Object[1];
pValues[0] = Collections.unmodifiableList(changes);
try {
ReflectionHelper.invoke(target, postMethod, pValues, true);
}
catch (Throwable th) {
return;
}
}
}
private void modifyInstanceDescriptor(ActiveDescriptor<?> parent,
String name,
Object bean,
Object metadata,
String typeName,
List<PropertyChangeEvent> changes
) {
BeanInfo modifiedInfo = injectionResolver.addBean(parent, bean, typeName, metadata);
Object target = context.findOnly(parent);
if (target == null) {
// race lost
return;
}
boolean moveForward = invokePreMethod(target, changes, typeName);
if (!moveForward) {
// User told us to NOT move forward
return;
}
HashMap<String, PropertyChangeEvent> changedProperties = new HashMap<String, PropertyChangeEvent>();
for (PropertyChangeEvent pce : changes) {
changedProperties.put(pce.getPropertyName(), pce);
if (target instanceof PropertyChangeListener) {
PropertyChangeListener listener = (PropertyChangeListener) target;
try {
listener.propertyChange(pce);
}
catch (Throwable th) {
// TODO: What to do about errors?
}
}
}
HashMap<Method, Object[]> dynamicMethods = new HashMap<Method, Object[]>();
HashSet<Method> notDynamicMethods = new HashSet<Method>();
for (Injectee injectee : parent.getInjectees()) {
AnnotatedElement ae = injectee.getParent();
if (ae == null) continue;
if (ae instanceof Field) {
String propName = BeanUtilities.getParameterNameFromField((Field) ae, true);
if (propName == null) continue;
PropertyChangeEvent pce = changedProperties.get(propName);
if (pce != null) {
try {
ReflectionHelper.setField((Field) ae, target, pce.getNewValue());
}
catch (Throwable th) {
// TODO: How to handle exceptions
}
}
continue;
}
if (ae instanceof Method) {
Method method = (Method) ae;
if (notDynamicMethods.contains(method)) continue;
if (!BeanUtilities.hasDynamicParameter(method)) {
notDynamicMethods.add(method);
continue;
}
Object params[] = dynamicMethods.get(method);
if (params == null) {
params = new Object[method.getParameterTypes().length];
dynamicMethods.put(method, params);
}
String propName = BeanUtilities.getParameterNameFromMethod(method, injectee.getPosition());
if (propName == null) {
ActiveDescriptor<?> paramDescriptor = locator.getInjecteeDescriptor(injectee);
if (paramDescriptor == null) {
params[injectee.getPosition()] = null;
}
else {
params[injectee.getPosition()] = locator.getServiceHandle(paramDescriptor).getService();
}
}
else {
PropertyChangeEvent pce = changedProperties.get(propName);
if (pce != null) {
params[injectee.getPosition()] = pce.getNewValue();
}
else {
params[injectee.getPosition()] = BeanUtilities.getBeanPropertyValue(injectee.getRequiredType(), propName, modifiedInfo);
}
}
}
}
for(Map.Entry<Method, Object[]> entries : dynamicMethods.entrySet()) {
try {
ReflectionHelper.invoke(target, entries.getKey(), entries.getValue(), true);
}
catch (Throwable e) {
// How to handle errors?
}
}
invokePostMethod(target, changes, typeName);
return;
}
private void initialize(BeanDatabase database) {
Set<Type> allTypes = database.getAllTypes();
LinkedList<ActiveDescriptor<?>> added = new LinkedList<ActiveDescriptor<?>>();
DynamicConfiguration config = configurationService.createDynamicConfiguration();
for (Type type : allTypes) {
String typeName = type.getName();
typeInformation.put(typeName, new ModificationInformation());
List<ActiveDescriptor<?>> typeDescriptors = locator.getDescriptors(new NoNameTypeFilter(locator, typeName, null));
for (ActiveDescriptor<?> typeDescriptor : typeDescriptors) {
// These match the type, so now we have to add one per instance
Map<String, Instance> typeInstances = type.getInstances();
for (Map.Entry<String, Instance> entry : typeInstances.entrySet()) {
added.add(addInstanceDescriptor(config, typeDescriptor, entry.getKey(), typeName, entry.getValue().getBean(),
entry.getValue().getMetadata()));
}
}
}
List<ActiveDescriptor<?>> progenitors = locator.getDescriptors(new NoNameTypeFilter(locator, null, null));
progenitorLock.lock();
try {
allProgenitors.addAll(progenitors);
} finally {
progenitorLock.unlock();
}
config.addActiveDescriptor(DescriptorListener.class);
// Add all instances
config.commit();
// Create demand for all the ones we just added
for (ActiveDescriptor<?> descriptor : added) {
if (!isEager(descriptor)) continue;
ServiceHandle<?> handle = locator.getServiceHandle(descriptor);
handle.getService(); // TODO: how to handle errors?
}
}
private static boolean isEager(ActiveDescriptor<?> descriptor) {
Class<?> implClass = descriptor.getImplementationClass();
if (implClass == null) return false;
ConfiguredBy configuredBy = implClass.getAnnotation(ConfiguredBy.class);
if (configuredBy == null) return false;
return ConfiguredBy.CreationPolicy.EAGER.equals(configuredBy.creationPolicy());
}
private String getTypeFromConfiguredBy(ActiveDescriptor<?> descriptor) {
if (!descriptor.isReified()) {
descriptor = locator.reifyDescriptor(descriptor);
}
Class<?> implClass = descriptor.getImplementationClass();
ConfiguredBy configuredBy = implClass.getAnnotation(ConfiguredBy.class);
if (configuredBy == null) {
throw new AssertionError("May only give this method ConfiguredBy descriptors");
}
return configuredBy.value();
}
/* (non-Javadoc)
* @see org.glassfish.hk2.configuration.hub.api.BeanDatabaseUpdateListener#databaseHasChanged(org.glassfish.hk2.configuration.hub.api.BeanDatabase, java.util.List)
*/
@Override
public void commitDatabaseChange(
BeanDatabase reference,
BeanDatabase newDatabase,
Object commitMessage,
List<Change> changes) {
LinkedList<ActiveDescriptor<?>> added = new LinkedList<ActiveDescriptor<?>>();
LinkedList<ActiveDescriptor<?>> removed = new LinkedList<ActiveDescriptor<?>>();
DynamicConfiguration config = configurationService.createDynamicConfiguration();
for (Change change : changes) {
if (Change.ChangeCategory.ADD_INSTANCE.equals(change.getChangeCategory())) {
String typeName = change.getChangeType().getName();
if (!typeInformation.containsKey(typeName)) {
typeInformation.put(typeName, new ModificationInformation());
}
String addedInstanceKey = change.getInstanceKey();
Object addedInstanceBean = change.getInstanceValue().getBean();
Object addedInstanceMetadata = change.getInstanceValue().getMetadata();
List<ActiveDescriptor<?>> typeDescriptors = locator.getDescriptors(new NoNameTypeFilter(locator, change.getChangeType().getName(), null));
for (ActiveDescriptor<?> typeDescriptor : typeDescriptors) {
// These match the type, so now we have to add one per instance
added.add(addInstanceDescriptor(config, typeDescriptor, addedInstanceKey, typeName, addedInstanceBean, addedInstanceMetadata));
}
}
else if (Change.ChangeCategory.MODIFY_INSTANCE.equals(change.getChangeCategory())) {
String modifiedInstanceKey = change.getInstanceKey();
Instance instance = change.getInstanceValue();
Object modifiedInstanceBean = (instance != null) ? instance.getBean() : null;
Object modifiedMetadata = (instance != null) ? instance.getMetadata() : null;
List<ActiveDescriptor<?>> typeDescriptors = locator.getDescriptors(
new NoNameTypeFilter(locator, change.getChangeType().getName(), modifiedInstanceKey));
for (ActiveDescriptor<?> typeDescriptor : typeDescriptors) {
modifyInstanceDescriptor(typeDescriptor,
modifiedInstanceKey,
modifiedInstanceBean,
modifiedMetadata,
change.getChangeType().getName(),
change.getModifiedProperties());
}
}
else if (Change.ChangeCategory.REMOVE_TYPE.equals(change.getChangeCategory())) {
String typeName = change.getChangeType().getName();
ModificationInformation cache = typeInformation.remove(typeName);
if (cache != null) {
cache.dispose();
}
}
else if (Change.ChangeCategory.REMOVE_INSTANCE.equals(change.getChangeCategory())) {
String removedInstanceKey = change.getInstanceKey();
List<ActiveDescriptor<?>> removeDescriptors = locator.getDescriptors(new NoNameTypeFilter(locator, change.getChangeType().getName(), removedInstanceKey));
for (ActiveDescriptor<?> removeDescriptor : removeDescriptors) {
config.addUnbindFilter(BuilderHelper.createSpecificDescriptorFilter(removeDescriptor));
injectionResolver.removeBean(removeDescriptor);
removed.add(removeDescriptor);
}
}
}
// Add all instances
if (!added.isEmpty() || !removed.isEmpty()) {
config.commit();
// Create demand for all the ones we just added
for (ActiveDescriptor<?> descriptor : added) {
if (!isEager(descriptor)) continue;
ServiceHandle<?> handle = locator.getServiceHandle(descriptor);
handle.getService(); // TODO: how to handle errors?
}
// Destroy the ones we just removed
for (ActiveDescriptor<?> descriptor : removed) {
ServiceHandle<?> handle = locator.getServiceHandle(descriptor);
handle.destroy();
}
}
}
private static class ModificationInformation {
private final ClassReflectionHelper helper = new ClassReflectionHelperImpl();
private final HashMap<Class<?>, Method> preMethods =
new HashMap<Class<?>, Method>();
private final HashMap<Class<?>, Method> postMethods =
new HashMap<Class<?>, Method>();
private Method getPreDynamicChangeMethod(Class<?> rawClass) {
if (preMethods.containsKey(rawClass)) {
return preMethods.get(rawClass);
}
Method preModificationMethod = getSpecialMethod(rawClass, PreDynamicChange.class);
preMethods.put(rawClass, preModificationMethod);
return preModificationMethod;
}
private Method getPostDynamicChangeMethod(Class<?> rawClass) {
if (postMethods.containsKey(rawClass)) {
return postMethods.get(rawClass);
}
Method postModificationMethod = getSpecialMethod(rawClass, PostDynamicChange.class);
postMethods.put(rawClass, postModificationMethod);
return postModificationMethod;
}
private Method getSpecialMethod(Class<?> rawClass, Class<? extends Annotation> anno) {
Set<MethodWrapper> wrappers = helper.getAllMethods(rawClass);
for (MethodWrapper wrapper : wrappers) {
Method candidate = wrapper.getMethod();
if (candidate.getAnnotation(anno) != null) {
return candidate;
}
}
return null;
}
private void dispose() {
helper.dispose();
preMethods.clear();
postMethods.clear();
}
}
private void calculateProgenitorAddsAndRemoves() {
List<ActiveDescriptor<?>> progenitors;
BeanDatabase database = hub.getCurrentDatabase();
final DynamicConfiguration config = configurationService.createDynamicConfiguration();
final LinkedList<ActiveDescriptor<?>> addedList = new LinkedList<ActiveDescriptor<?>>();
final LinkedList<ActiveDescriptor<?>> removedList = new LinkedList<ActiveDescriptor<?>>();
progenitorLock.lock();
try {
HashSet<ActiveDescriptor<?>> removed = new HashSet<ActiveDescriptor<?>>(allProgenitors);
progenitors = locator.getDescriptors(new NoNameTypeFilter(locator, null, null));
allProgenitors = new HashSet<ActiveDescriptor<?>>(progenitors);
HashSet<ActiveDescriptor<?>> added = new HashSet<ActiveDescriptor<?>>(allProgenitors);
added.removeAll(removed);
removed.removeAll(progenitors);
// Now added contains all of the added progenitors,
// and removed contains all of the removed progenitors
for (ActiveDescriptor<?> addMe : added) {
String typeName = getTypeFromConfiguredBy(addMe);
typeInformation.putIfAbsent(typeName, new ModificationInformation());
Type type = database.getType(typeName);
if (type != null) {
for (Map.Entry<String, Instance> instance : type.getInstances().entrySet()) {
String addedInstanceKey = instance.getKey();
Object addedInstanceBean = instance.getValue().getBean();
Object addedInstanceMetadata = instance.getValue().getMetadata();
addedList.add(addInstanceDescriptor(config, addMe, addedInstanceKey, typeName, addedInstanceBean, addedInstanceMetadata));
}
}
}
} finally {
progenitorLock.unlock();
}
if (!addedList.isEmpty() || !removedList.isEmpty()) {
config.commit();
new Thread(new Runnable() {
@Override
public void run() {
// Create demand for all the ones we just added
for (ActiveDescriptor<?> descriptor : addedList) {
if (!isEager(descriptor)) continue;
ServiceHandle<?> handle = locator.getServiceHandle(descriptor);
handle.getService(); // TODO: how to handle errors?
}
// Destroy the ones we just removed
for (ActiveDescriptor<?> descriptor : removedList) {
ServiceHandle<?> handle = locator.getServiceHandle(descriptor);
handle.destroy();
}
}
}).start();
}
}
@Singleton
private static class DescriptorListener implements DynamicConfigurationListener {
@Inject
private ConfigurationListener parent;
/* (non-Javadoc)
* @see org.glassfish.hk2.api.DynamicConfigurationListener#configurationChanged()
*/
@Override
public void configurationChanged() {
parent.calculateProgenitorAddsAndRemoves();
}
}
/* (non-Javadoc)
* @see org.glassfish.hk2.configuration.hub.api.BeanDatabaseUpdateListener#prepareDatabaseChange(org.glassfish.hk2.configuration.hub.api.BeanDatabase, org.glassfish.hk2.configuration.hub.api.BeanDatabase, java.lang.Object, java.util.List)
*/
@Override
public void prepareDatabaseChange(BeanDatabase currentDatabase,
BeanDatabase proposedDatabase, Object commitMessage,
List<Change> changes) {
// Do nothing
}
/* (non-Javadoc)
* @see org.glassfish.hk2.configuration.hub.api.BeanDatabaseUpdateListener#rollbackDatabaseChange(org.glassfish.hk2.configuration.hub.api.BeanDatabase, org.glassfish.hk2.configuration.hub.api.BeanDatabase, java.lang.Object, java.util.List)
*/
@Override
public void rollbackDatabaseChange(BeanDatabase currentDatabase,
BeanDatabase proposedDatabase, Object commitMessage,
List<Change> changes) {
// Do nothing
}
@Override
public String toString() {
return "ConfigurationListener(" + System.identityHashCode(this) + ")";
}
}