View Javadoc
1   /**
2    * This file Copyright (c) 2015-2018 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.AbstractMap;
39  import java.util.Arrays;
40  import java.util.Collection;
41  import java.util.LinkedHashMap;
42  import java.util.LinkedHashSet;
43  import java.util.List;
44  import java.util.Map;
45  import java.util.Set;
46  
47  import com.google.common.collect.Lists;
48  import com.google.common.collect.Sets;
49  
50  /**
51   * Overlays a map-represented configuration data (map of maps) with another similarly-structured map at a certain path.
52   */
53  public class ConfigurationMapOverlay {
54  
55      private Map<String, Object> source;
56      private Map<String, Object> decorator;
57      private String overlayPath;
58  
59      public static ConfigurationMapOverlay of(Map<String, Object> source) {
60          ConfigurationMapOverlay configMapMerger = new ConfigurationMapOverlay();
61          configMapMerger.source = source;
62          return configMapMerger;
63      }
64  
65      public ConfigurationMapOverlay by(Map<String, Object> decorator) {
66          this.decorator = decorator;
67          return this;
68      }
69  
70      public ConfigurationMapOverlay at(String path) {
71          this.overlayPath = path;
72          return this;
73      }
74  
75      public Map<String, Object> overlay() {
76          return doOverlay(source, "/");
77      }
78  
79      /**
80       * Recursively goes over the {@code source} map and tracks the current traversed path. If the
81       * current traversed path matches the {@link #overlayPath overlay path} - the {@link #decorator overlay map}
82       * is merged directly into the current source sub-map (or sub-collection).
83       *
84       * @param source map structure being overlayed
85       * @param currentTraversedPath currently processed part of the {@code source}
86       */
87      private <K> Map<K, Object> doOverlay(Map<K, Object> source, String currentTraversedPath) {
88          Map<K, Object> result = new LinkedHashMap<>();
89          for (K key : source.keySet()) {
90              Object value = source.get(key);
91              // If not a map or collection - nothing to do, simply put the value into resulting map
92              if (!(value instanceof Collection) && !(value instanceof Map)) {
93                  result.put(key, value);
94              } else {
95                  // If value is a map or collection - try to recursively overlay it
96                  Map<Object, Object> map = ToMap.toMap(value);
97                  result.put(key, doOverlay(map, String.format("%s/%s", stripEnd(currentTraversedPath, "/"), key)));
98              }
99          }
100 
101         if (overlayPath.equals(currentTraversedPath)) {
102             // cannot overcome the lousy cast below, this is because decorator data may occur at a point where we no longer guarantee keys to be strings
103             result = mergeMaps((Map) result, decorator);
104         } else {
105             // Now check if maybe we need to simply add the decorator data under the remaining path which is completely missing from the parent
106 
107             // Make sure that so far we were going the right direction
108             if (overlayPath.startsWith("/".equals(currentTraversedPath) ? "/" : currentTraversedPath + "/")) {
109 
110                 // Resolve the part we did not cover yet
111                 String notCoveredOverlayPath = removeStart(overlayPath, currentTraversedPath);
112 
113                 // strip the leading slash if any
114                 notCoveredOverlayPath = stripStart(notCoveredOverlayPath, "/");
115 
116                 // extract the next possible hop
117                 final String nextNotCoveredLocation = notCoveredOverlayPath.contains("/") ? substringBefore(notCoveredOverlayPath, "/") : notCoveredOverlayPath;
118 
119                 // If the next hop is missing from the source - create the config path and
120                 if (!source.containsKey(nextNotCoveredLocation)) {
121                     addWithoutMerging(result, decorator, notCoveredOverlayPath);
122                 }
123             }
124         }
125 
126         return result;
127     }
128 
129     private void addWithoutMerging(Map source, Map decorator, String pathToAdd) {
130         // First - create the layered maps for the missing path
131         Map<String, Object> configMap;
132         if (pathToAdd.contains("/")) {
133             configMap = new LinkedHashMap<>();
134             // Figure out all the missing path fragments and create the map layers in a reversed order:
135             // e.g. we want to put the decorator data under path /foo/bar/baz which does not exist. For that
136             // we create an empty map and put the decorator data in it with the key 'baz'. Then we create another map
137             // and put the first map in it under key 'bar' and so on. The result is the layered configuration map
138             // corresponding to the path that was initially missing from the source (/foo/bar/baz in our case).
139             final List<String> fragmentsToCreate = Lists.reverse(Arrays.asList(substringAfter(pathToAdd, "/").split("/")));
140             for (final String pathFragment : fragmentsToCreate) {
141                 if (configMap.isEmpty()) {
142                     configMap.put(pathFragment, decorator);
143                 } else {
144                     Map<String, Object> wrappingMap = new LinkedHashMap<>();
145                     wrappingMap.put(pathFragment, configMap);
146                     configMap = wrappingMap;
147                 }
148             }
149         } else {
150             configMap = decorator;
151         }
152 
153         final String key = substringBefore(pathToAdd, "/");
154         //noinspection unchecked
155         source.put(key, configMap);
156     }
157 
158     private <K> Map<K, Object> mergeMaps(Map<K, Object> original, Map<K, Object> decorator) {
159         final Map<K, Object> result = new LinkedHashMap<>();
160 
161         final Set<K> resultingKeys;
162         final Set<K> originalKeys = original.keySet();
163         final Set<K> decoratingKeys = decorator.keySet();
164 
165         if (decorator instanceof OverridingMap) {
166             // if the map contains the override instruction - use only the decorator keys
167             resultingKeys = new LinkedHashSet<>(decoratingKeys);
168         } else {
169             // otherwise - combine the decorator keys with the original keys
170             resultingKeys = Sets.union(originalKeys, decorator.keySet());
171         }
172 
173         resultingKeys.forEach(key -> result.put(key, mergeValues(original.get(key), decorator.get(key))));
174 
175         return result;
176     }
177 
178     private Object mergeValues(Object source, Object decoration) {
179         if (source == null) {
180             return decoration;
181         }
182 
183         if (decoration == null) {
184             return source;
185         }
186 
187         if (!(source instanceof Collection) && !(source instanceof Map)) {
188             // 'Simple value' case - decoration wins
189             return decoration;
190         } else {
191             // Map/collection have to be overlayed
192             final Map<Object, Object> sourceValueMap = ToMap.toMap(source);
193             final Map<Object, Object> decorationMap = ToMap.toMap(decoration);
194             return mergeMaps(sourceValueMap, decorationMap);
195         }
196     }
197 
198     /**
199      * Map structure wrapper which merely indicates to the {@link ConfigurationMapOverlay}
200      * that whenever the overlaying map is instance of this class, it should completely overwrite the
201      * data coming from the source map.
202      *
203      * @param <K> key type
204      * @param <V> value type
205      */
206     public final static class OverridingMap<K, V> extends AbstractMap<K, V> {
207 
208         private final Map<K, V> wrappedMap;
209 
210         public OverridingMap(Map<K, V> wrappedMap) {
211             this.wrappedMap = wrappedMap;
212         }
213 
214         @Override
215         public Set<Entry<K, V>> entrySet() {
216             return this.wrappedMap.entrySet();
217         }
218     }
219 
220 }