View Javadoc
1   /**
2    * This file Copyright (c) 2015 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.config.maputil;
35  
36  import static org.apache.commons.lang3.StringUtils.*;
37  
38  import java.util.Arrays;
39  import java.util.Collection;
40  import java.util.List;
41  import java.util.Map;
42  
43  import com.google.common.collect.Lists;
44  import com.google.common.collect.Maps;
45  import com.google.common.collect.Sets;
46  
47  /**
48   * Overlays a map-represented configuration data (map of maps) with another similarly-structured map at a certain path.
49   */
50  public class ConfigurationMapOverlay {
51  
52      private Map<String, ?> source;
53      private Map<String, ?> decorator;
54      private String overlayPath;
55  
56      public static ConfigurationMapOverlay of(Map<String, ?> source) {
57          ConfigurationMapOverlay configMapMerger = new ConfigurationMapOverlay();
58          configMapMerger.source = source;
59          return configMapMerger;
60      }
61  
62      public ConfigurationMapOverlay by(Map<String,?> decorator) {
63          this.decorator = decorator;
64          return this;
65      }
66  
67      public ConfigurationMapOverlay at(String path) {
68          this.overlayPath = path;
69          return this;
70      }
71  
72      public Map<String, Object> overlay() {
73          return doOverlay(source, "/");
74      }
75  
76      /**
77       * Recursively goes over the {@code source} map and tracks the current traversed path. If the
78       * current traversed path matches the {@link #overlayPath overlay path} - the {@link #decorator overlay map}
79       * is merged directly into the current source sub-map (or sub-collection).
80       *
81       * @param source map structure being overlayed
82       * @param currentTraversedPath currently processed part of the {@code source}
83       */
84      private Map<String, Object> doOverlay(Map<String, ?> source, String currentTraversedPath) {
85          Map<String, Object> result = Maps.newLinkedHashMap();
86          for (final String key : source.keySet()) {
87              final Object value = source.get(key);
88              // If not a map or collection - nothing to do, simply put the value into resulting map
89              if (!(value instanceof Collection) && !(value instanceof Map)) {
90                  result.put(key, value);
91              } else {
92                  // If value is a map or collection - try to recursively overlay it
93                  final Map<String, Object> map = ToMap.toMap(value);
94                  result.put(key, doOverlay(map, String.format("%s/%s", stripEnd(currentTraversedPath, "/"), key)));
95              }
96          }
97  
98          if (overlayPath.equals(currentTraversedPath)) {
99              result = mergeMaps(result, decorator);
100         } else {
101             // Now check if maybe we need to simply add the decorator data under the remaining path which is completely missing from the parent
102 
103             // Make sure that so far we were going the right direction
104             if (overlayPath.startsWith(currentTraversedPath)) {
105 
106                 // Resolve the part we did not cover yet
107                 String notCoveredOverlayPath = removeStart(overlayPath, currentTraversedPath);
108 
109                 // strip the leading slash if any
110                 notCoveredOverlayPath = stripStart(notCoveredOverlayPath, "/");
111 
112                 // extract the next possible hop
113                 final String nextNotCoveredLocation = notCoveredOverlayPath.contains("/") ? substringBefore(notCoveredOverlayPath, "/") : notCoveredOverlayPath;
114 
115                 // If the next hop is missing from the source - create the config path and
116                 if (!source.containsKey(nextNotCoveredLocation)) {
117                     addWithoutMerging(result, decorator, notCoveredOverlayPath);
118                 }
119             }
120         }
121 
122         return result;
123     }
124 
125     private void addWithoutMerging(Map source, Map decorator, String pathToAdd) {
126         // First - create the layered maps for the missing path
127         Map<String, Object> configMap;
128         if (pathToAdd.contains("/")) {
129             configMap = Maps.newLinkedHashMap();
130             // Figure out all the missing path fragments and create the map layers in a reversed order:
131             // e.g. we want to put the decorator data under path /foo/bar/baz which does not exist. For that
132             // we create an empty map and put the decorator data in it with the key 'baz'. Then we create another map
133             // and put the first map in it under key 'bar' and so on. The result is the layered configuration map
134             // corresponding to the path that was initially missing from the source (/foo/bar/baz in our case).
135             final List<String> fragmentsToCreate = Lists.reverse(Arrays.asList(substringAfter(pathToAdd, "/").split("/")));
136             for (final String pathFragment : fragmentsToCreate) {
137                 if (configMap.isEmpty()) {
138                     configMap.put(pathFragment, decorator);
139                 } else {
140                     Map<String, Object> wrappingMap = Maps.newLinkedHashMap();
141                     wrappingMap.put(pathFragment, configMap);
142                     configMap = wrappingMap;
143                 }
144             }
145         } else {
146             configMap = decorator;
147         }
148 
149         final String key = substringBefore(pathToAdd, "/");
150         //noinspection unchecked
151         source.put(key, configMap);
152     }
153 
154     private Map<String, Object> mergeMaps(Map<String, ?> original, Map<String, ?> decorator) {
155         final Map<String, Object> result = Maps.newLinkedHashMap();
156         for (final String key  : Sets.union(original.keySet(), decorator.keySet())) {
157             result.put(key, mergeValues(original.get(key), decorator.get(key)));
158         }
159         return result;
160     }
161 
162     private Object mergeValues(Object source, Object decoration) {
163         if (source == null) {
164             return decoration;
165         }
166 
167         if (decoration == null) {
168             return source;
169         }
170 
171         if (!(source instanceof Collection) && !(source instanceof Map)) {
172             // 'Simple value' case - decoration wins
173             return decoration;
174         } else {
175             // Map/collection have to be overlayed
176             final Map<String, Object> sourceValueMap = ToMap.toMap(source);
177             final Map<String, Object> decorationMap = ToMap.toMap(decoration);
178             return mergeMaps(sourceValueMap, decorationMap);
179         }
180     }
181 }