1 package com.atlassian.plugin.spring.scanner.test.dynamic;
2
3 import com.atlassian.event.api.EventPublisher;
4 import com.atlassian.plugin.Plugin;
5 import com.atlassian.plugin.PluginAccessor;
6 import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
7 import com.atlassian.plugin.spring.scanner.dynamic.contexts.DynamicContext;
8 import com.google.common.base.Joiner;
9 import org.osgi.framework.BundleContext;
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.context.ApplicationContext;
12 import org.springframework.context.ConfigurableApplicationContext;
13 import org.springframework.stereotype.Component;
14
15
16
17
18 @SuppressWarnings({"SpringJavaAutowiringInspection", "FieldCanBeLocal", "UnusedDeclaration"})
19 @Component
20 public class DynamicContextManager {
21 private static final Joiner INTERFACE_NAME_JOINER = Joiner.on(", ");
22
23 private final ApplicationContext parentContext;
24 private final BundleContext bundleContext;
25 private final DynamicContext.Installer dynamicContextInstaller;
26 private ConfigurableApplicationContext internalContext;
27
28 @Autowired
29 public DynamicContextManager(@ComponentImport EventPublisher eventPublisher, @ComponentImport PluginAccessor pluginAccessor, ApplicationContext parentContext, BundleContext bundleContext) {
30 this.parentContext = parentContext;
31 this.bundleContext = bundleContext;
32
33 final String pluginKey = "com.atlassian.plugin.atlassian-spring-scanner-maven-test";
34 Plugin plugin = pluginAccessor.getPlugin(pluginKey);
35 if (plugin == null) {
36 throw new IllegalStateException("Plugin with key '" + pluginKey + "' was not found");
37 }
38
39 dynamicContextInstaller = DynamicContext.installer(eventPublisher, bundleContext, plugin.getKey());
40 }
41
42 public Result bootstrapTheRestOfTheApplication() {
43 long then = System.currentTimeMillis();
44 if (internalContext == null) {
45 this.internalContext = dynamicContextInstaller.useContext(new String[]{"/dynamicProfile/dynamic-context-spring-scanner.xml"}, parentContext);
46
47 return new Result(true, then);
48 } else {
49 return new Result(false, then);
50 }
51 }
52
53 public Result shutdownNewContext() {
54 long then = System.currentTimeMillis();
55 if (internalContext != null) {
56 dynamicContextInstaller.closeAndUseContext(internalContext, internalContext.getParent());
57 internalContext = null;
58 return new Result(true, then);
59 }
60 return new Result(false, then);
61 }
62
63 public ConfigurableApplicationContext getInternalContext() {
64 return internalContext;
65 }
66
67 public static class Result {
68 boolean tookPlace;
69 long timeTaken;
70
71 Result(final boolean tookPlace, final long then) {
72 this.tookPlace = tookPlace;
73 this.timeTaken = System.currentTimeMillis() - then;
74 }
75
76 public boolean tookPlace() {
77 return tookPlace;
78 }
79
80 public long getTimeTaken() {
81 return timeTaken;
82 }
83 }
84 }