1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.openehealth.ipf.commons.spring.core.config;
17
18 import org.openehealth.ipf.commons.core.config.OrderedConfigurer;
19 import org.openehealth.ipf.commons.core.config.Registry;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.springframework.beans.factory.BeanInitializationException;
23 import org.springframework.context.ApplicationListener;
24 import org.springframework.context.event.ContextRefreshedEvent;
25
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
30
31
32
33
34
35
36
37 @SuppressWarnings({"rawtypes", "unchecked"})
38 public class SpringConfigurationPostProcessor implements
39 ApplicationListener<ContextRefreshedEvent> {
40
41 private static Logger LOG = LoggerFactory.getLogger(SpringConfigurationPostProcessor.class);
42
43 private boolean refreshed;
44 private boolean restartOnce = true;
45
46 private List<OrderedConfigurer> springConfigurers;
47
48 protected void configure(Registry registry) {
49 for (OrderedConfigurer sc : springConfigurers) {
50 Collection configurations = sc.lookup(registry);
51 if (configurations != null && configurations.size() > 0) {
52 for (Object configuration : configurations) {
53 LOG.debug("Configuring extension {}", configuration);
54 try {
55 sc.configure(configuration);
56 } catch (Exception e) {
57 throw new BeanInitializationException("Cannot initialize " + configuration, e);
58 }
59 }
60 }
61 }
62 }
63
64
65
66
67 public void setRestartOnce(boolean restartOnce) {
68 this.restartOnce = restartOnce;
69 }
70
71 public List<OrderedConfigurer> getSpringConfigurers() {
72 return springConfigurers;
73 }
74
75 public void setSpringConfigurers(List<OrderedConfigurer> springConfigurers) {
76 this.springConfigurers = springConfigurers;
77 Collections.sort(springConfigurers);
78 }
79
80 @Override
81 public void onApplicationEvent(ContextRefreshedEvent event) {
82 if (!refreshed || !restartOnce) {
83 SpringRegistry registry = new SpringRegistry();
84 registry.setBeanFactory(event.getApplicationContext());
85
86 if (getSpringConfigurers() == null) {
87 LOG.info("No extension beans configured, will look up registry for extension beans");
88 springConfigurers = new ArrayList(registry.beans(
89 OrderedConfigurer.class).values());
90 Collections.sort(springConfigurers);
91 }
92 LOG.info("Number of extension beans: " + springConfigurers.size());
93 configure(registry);
94 refreshed = true;
95
96 } else {
97 LOG.info("Spring context has already been initialized before");
98 }
99 }
100 }