View Javadoc
1   /**
2    * This file Copyright (c) 2015-2017 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.HashSet;
42  import java.util.LinkedHashMap;
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, ?> source;
56      private Map<String, ?> decorator;
57      private String overlayPath;
58  
59      public static ConfigurationMapOverlay of(Map<String, ?> source) {
60          ConfigurationMapOverlay configMapMerger = new ConfigurationMapOverlay();
61          configMapMerger.source = source;
62          return configMapMerger;
63      }
64  
65      public ConfigurationMapOverlay by(Map<String, ?> 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 Map<String, Object> doOverlay(Map<String, ?> source, String currentTraversedPath) {
88          Map<String, Object> result = new LinkedHashMap<>();
89          for (final String key : source.keySet()) {
90              final 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                  final Map<String, 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             result = mergeMaps(result, decorator);
103         } else {
104             // Now check if maybe we need to simply add the decorator data under the remaining path which is completely missing from the parent
105 
106             // Make sure that so far we were going the right direction
107             if (overlayPath.startsWith("/".equals(currentTraversedPath) ? "/" : currentTraversedPath + "/")) {
108 
109                 // Resolve the part we did not cover yet
110                 String notCoveredOverlayPath = removeStart(overlayPath, currentTraversedPath);
111 
112                 // strip the leading slash if any
113                 notCoveredOverlayPath = stripStart(notCoveredOverlayPath, "/");
114 
115                 // extract the next possible hop
116                 final String nextNotCoveredLocation = notCoveredOverlayPath.contains("/") ? substringBefore(notCoveredOverlayPath, "/") : notCoveredOverlayPath;
117 
118                 // If the next hop is missing from the source - create the config path and
119                 if (!source.containsKey(nextNotCoveredLocation)) {
120                     addWithoutMerging(result, decorator, notCoveredOverlayPath);
121                 }
122             }
123         }
124 
125         return result;
126     }
127 
128     private void addWithoutMerging(Map source, Map decorator, String pathToAdd) {
129         // First - create the layered maps for the missing path
130         Map<String, Object> configMap;
131         if (pathToAdd.contains("/")) {
132             configMap = new LinkedHashMap<>();
133             // Figure out all the missing path fragments and create the map layers in a reversed order:
134             // e.g. we want to put the decorator data under path /foo/bar/baz which does not exist. For that
135             // we create an empty map and put the decorator data in it with the key 'baz'. Then we create another map
136             // and put the first map in it under key 'bar' and so on. The result is the layered configuration map
137             // corresponding to the path that was initially missing from the source (/foo/bar/baz in our case).
138             final List<String> fragmentsToCreate = Lists.reverse(Arrays.asList(substringAfter(pathToAdd, "/").split("/")));
139             for (final String pathFragment : fragmentsToCreate) {
140                 if (configMap.isEmpty()) {
141                     configMap.put(pathFragment, decorator);
142                 } else {
143                     Map<String, Object> wrappingMap = new LinkedHashMap<>();
144                     wrappingMap.put(pathFragment, configMap);
145                     configMap = wrappingMap;
146                 }
147             }
148         } else {
149             configMap = decorator;
150         }
151 
152         final String key = substringBefore(pathToAdd, "/");
153         //noinspection unchecked
154         source.put(key, configMap);
155     }
156 
157     private Map<String, Object> mergeMaps(Map<String, ?> original, Map<String, ?> decorator) {
158         final Map<String, Object> result = new LinkedHashMap<>();
159 
160         final Set<String> resultingKeys;
161         final Set<String> originalKeys = original.keySet();
162         final Set<String> decoratingKeys = decorator.keySet();
163 
164         if (decorator instanceof OverridingMap) {
165             // if the map contains the override instruction - use only the decorator keys
166             resultingKeys = new HashSet<>(decoratingKeys);
167         } else {
168             // otherwise - combine the decorator keys with the original keys
169             resultingKeys = Sets.union(originalKeys, decorator.keySet());
170         }
171 
172         resultingKeys.forEach(key -> result.put(key, mergeValues(original.get(key), decorator.get(key))));
173 
174         return result;
175     }
176 
177     private Object mergeValues(Object source, Object decoration) {
178         if (source == null) {
179             return decoration;
180         }
181 
182         if (decoration == null) {
183             return source;
184         }
185 
186         if (!(source instanceof Collection) && !(source instanceof Map)) {
187             // 'Simple value' case - decoration wins
188             return decoration;
189         } else {
190             // Map/collection have to be overlayed
191             final Map<String, Object> sourceValueMap = ToMap.toMap(source);
192             final Map<String, Object> decorationMap = ToMap.toMap(decoration);
193             return mergeMaps(sourceValueMap, decorationMap);
194         }
195     }
196 
197     /**
198      * Map structure wrapper which merely indicates to the {@link ConfigurationMapOverlay}
199      * that whenever the overlaying map is instance of this class, it should completely overwrite the
200      * data coming from the source map.
201      *
202      * @param <K> key type
203      * @param <V> value type
204      */
205     public final static class OverridingMap<K, V> extends AbstractMap<K, V> {
206 
207         private final Map<K, V> wrappedMap;
208 
209         public OverridingMap(Map<K, V> wrappedMap) {
210             this.wrappedMap = wrappedMap;
211         }
212 
213         @Override
214         public Set<Entry<K, V>> entrySet() {
215             return this.wrappedMap.entrySet();
216         }
217     }
218 
219 }