View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  
20  package org.eclipse.jetty.spring;
21  
22  import java.net.URL;
23  import java.nio.charset.StandardCharsets;
24  import java.util.Arrays;
25  import java.util.Map;
26  import java.util.ServiceLoader;
27  
28  import org.eclipse.jetty.util.log.Log;
29  import org.eclipse.jetty.util.log.Logger;
30  import org.eclipse.jetty.xml.ConfigurationProcessor;
31  import org.eclipse.jetty.xml.ConfigurationProcessorFactory;
32  import org.eclipse.jetty.xml.XmlConfiguration;
33  import org.eclipse.jetty.xml.XmlParser;
34  import org.springframework.beans.BeanWrapper;
35  import org.springframework.beans.PropertyValues;
36  import org.springframework.beans.factory.config.BeanDefinition;
37  import org.springframework.beans.factory.support.DefaultListableBeanFactory;
38  import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
39  import org.springframework.core.io.ByteArrayResource;
40  import org.springframework.core.io.Resource;
41  import org.springframework.core.io.UrlResource;
42  
43  /**
44   * Spring ConfigurationProcessor
45   * <p>
46   * A {@link ConfigurationProcessor} that uses a spring XML file to emulate the {@link XmlConfiguration} format.
47   * <p>
48   * {@link XmlConfiguration} expects a primary object that is either passed in to a call to {@link #configure(Object)}
49   * or that is constructed by a call to {@link #configure()}. This processor looks for a bean definition
50   * with an id, name or alias of "Main" as uses that as the primary bean.
51   * <p>
52   * The objects mapped by {@link XmlConfiguration#getIdMap()} are set as singletons before any configuration calls
53   * and if the spring configuration file contains a definition for the singleton id, the the singleton is updated
54   * with a call to {@link DefaultListableBeanFactory#configureBean(Object, String)}.
55   * <p>
56   * The property map obtained via {@link XmlConfiguration#getProperties()} is set as a singleton called "properties"
57   * and values can be accessed by somewhat verbose
58   * usage of {@link org.springframework.beans.factory.config.MethodInvokingFactoryBean}.
59   * <p>
60   * This processor is returned by the {@link SpringConfigurationProcessorFactory} for any XML document whos first
61   * element is "beans". The factory is discovered by a {@link ServiceLoader} for {@link ConfigurationProcessorFactory}.
62   */
63  public class SpringConfigurationProcessor implements ConfigurationProcessor
64  {
65      private static final Logger LOG = Log.getLogger(SpringConfigurationProcessor.class);
66  
67      private XmlConfiguration _configuration;
68      private DefaultListableBeanFactory _beanFactory;
69      private String _main;
70  
71      @Override
72      public void init(URL url, XmlParser.Node config, XmlConfiguration configuration)
73      {
74          try
75          {
76              _configuration = configuration;
77  
78              Resource resource = url != null
79                      ? new UrlResource(url)
80                      : new ByteArrayResource(("" +
81                      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
82                      "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\">" +
83                      config).getBytes(StandardCharsets.UTF_8));
84  
85              _beanFactory = new DefaultListableBeanFactory()
86              {
87                  @Override
88                  protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs)
89                  {
90                      _configuration.initializeDefaults(bw.getWrappedInstance());
91                      super.applyPropertyValues(beanName, mbd, bw, pvs);
92                  }
93              };
94  
95              new XmlBeanDefinitionReader(_beanFactory).loadBeanDefinitions(resource);
96          }
97          catch (Exception e)
98          {
99              throw new RuntimeException(e);
100         }
101     }
102 
103     @Override
104     public Object configure(Object obj) throws Exception
105     {
106         doConfigure();
107         return _beanFactory.configureBean(obj, _main);
108     }
109 
110     /**
111      * Return a configured bean.  If a bean has the id or alias of "Main", then it is returned, otherwise the first bean in the file is returned.
112      *
113      * @see org.eclipse.jetty.xml.ConfigurationProcessor#configure()
114      */
115     @Override
116     public Object configure() throws Exception
117     {
118         doConfigure();
119         return _beanFactory.getBean(_main);
120     }
121 
122     private void doConfigure()
123     {
124         _beanFactory.registerSingleton("properties", _configuration.getProperties());
125 
126         // Look for the main bean;
127         for (String bean : _beanFactory.getBeanDefinitionNames())
128         {
129             LOG.debug("{} - {}", bean, Arrays.asList(_beanFactory.getAliases(bean)));
130             String[] aliases = _beanFactory.getAliases(bean);
131             if ("Main".equals(bean) || aliases != null && Arrays.asList(aliases).contains("Main"))
132             {
133                 _main = bean;
134                 break;
135             }
136         }
137         if (_main == null)
138             _main = _beanFactory.getBeanDefinitionNames()[0];
139 
140         // Register id beans as singletons
141         Map<String, Object> idMap = _configuration.getIdMap();
142         LOG.debug("idMap {}", idMap);
143         for (String id : idMap.keySet())
144         {
145             LOG.debug("register {}", id);
146             _beanFactory.registerSingleton(id, idMap.get(id));
147         }
148 
149         // Apply configuration to existing singletons
150         for (String id : idMap.keySet())
151         {
152             if (_beanFactory.containsBeanDefinition(id))
153             {
154                 LOG.debug("reconfigure {}", id);
155                 _beanFactory.configureBean(idMap.get(id), id);
156             }
157         }
158 
159         // Extract id's for next time.
160         for (String id : _beanFactory.getSingletonNames())
161             idMap.put(id, _beanFactory.getBean(id));
162     }
163 }