View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.internal.config;
21  
22  import org.apache.myfaces.tobago.context.ThemeImpl;
23  import org.apache.myfaces.tobago.sanitizer.IgnoringSanitizer;
24  import org.apache.myfaces.tobago.sanitizer.JsoupSanitizer;
25  import org.apache.myfaces.tobago.sanitizer.Sanitizer;
26  import org.slf4j.Logger;
27  import org.slf4j.LoggerFactory;
28  
29  import java.util.ArrayList;
30  import java.util.Collections;
31  import java.util.Comparator;
32  import java.util.List;
33  import java.util.Map;
34  import java.util.Properties;
35  
36  public class TobagoConfigSorter implements Comparator<TobagoConfigFragment> {
37  
38    private static final Logger LOG = LoggerFactory.getLogger(TobagoConfigSorter.class);
39  
40    private List<TobagoConfigFragment> list;
41    private List<Pair> pairs;
42  
43    public TobagoConfigSorter(final List<TobagoConfigFragment> list) {
44      this.list = list;
45    }
46  
47    public void sort() {
48  
49      createRelevantPairs();
50  
51      makeTransitive();
52  
53      ensureIrreflexive();
54  
55      ensureAntiSymmetric();
56  
57      sort0();
58  
59      if (LOG.isInfoEnabled()) {
60        LOG.info("Order of the Tobago config files:");
61        for (final TobagoConfigFragment fragment : list) {
62          String name = fragment.getName();
63          if (name == null) {
64            name = "<unnamed>";
65          } else {
66            name = "'" + name + "'";
67          }
68          LOG.info("name=" + name + " url='" + fragment.getUrl() + "'");
69        }
70      }
71    }
72  
73    public TobagoConfigImpl merge() {
74  
75      final TobagoConfigImpl result = new TobagoConfigImpl();
76  
77      // default sanitizer
78      String sanitizerClass = JsoupSanitizer.class.getName();
79      Properties sanitizerProperties = new Properties();
80      sanitizerProperties.setProperty("whitelist", "relaxed");
81  
82      for (final TobagoConfigFragment fragment : list) {
83        // default theme
84        final String defaultTheme = fragment.getDefaultThemeName();
85        if (defaultTheme != null) {
86          result.setDefaultThemeName(defaultTheme);
87        }
88  
89        // supported themes
90        for (final String supported : fragment.getSupportedThemeNames()) {
91          result.addSupportedThemeName(supported);
92        }
93  
94        // resource dirs
95        for (final String dir : fragment.getResourceDirs()) {
96          result.addResourceDir(dir);
97        }
98  
99        // renderers config
100       if (fragment.getRenderersConfig() != null) {
101         if (result.getRenderersConfig() instanceof RenderersConfigImpl) {
102           ((RenderersConfigImpl) result.getRenderersConfig()).merge(fragment.getRenderersConfig(), false);
103         } else if (result.getRenderersConfig() == null) {
104           result.setRenderersConfig(fragment.getRenderersConfig());
105         }
106       }
107 
108       // session secret
109       if (fragment.getCreateSessionSecret() != null) {
110         result.setCreateSessionSecret(fragment.getCreateSessionSecret());
111       }
112       if (fragment.getCheckSessionSecret() != null) {
113         result.setCheckSessionSecret(fragment.getCheckSessionSecret());
114       }
115 
116       if (fragment.getPreventFrameAttacks() != null) {
117         result.setPreventFrameAttacks(fragment.getPreventFrameAttacks());
118       }
119 
120       if (fragment.getContentSecurityPolicy() != null) {
121         result.getContentSecurityPolicy().merge(fragment.getContentSecurityPolicy());
122       }
123 
124       if (fragment.getSetNosniffHeader() != null) {
125         result.setSetNosniffHeader(fragment.getSetNosniffHeader());
126       }
127 
128       if (fragment.getSanitizerClass() != null) {
129         sanitizerClass = fragment.getSanitizerClass();
130         sanitizerProperties = fragment.getSanitizerProperties();
131       }
132 
133       // theme definition
134       result.toString();
135       for (ThemeImpl theme : fragment.getThemeDefinitions()) {
136         result.addAvailableTheme(theme);
137       }
138 
139       // url
140       // todo???
141 
142       final Map<String, String> mimeTypes = result.getMimeTypes();
143       for (final Map.Entry<String, String> entry : fragment.getMimeTypes().entrySet()) {
144         mimeTypes.put(entry.getKey(), entry.getValue());
145       }
146 
147     }
148 
149     resolveThemes(result, result.getAvailableThemes());
150 
151     if (sanitizerClass != null) {
152       try {
153         final Class<? extends Sanitizer> aClass = Class.forName(sanitizerClass).asSubclass(Sanitizer.class);
154         final Sanitizer sanitizer = aClass.newInstance();
155         sanitizer.setProperties(sanitizerProperties);
156         result.setSanitizer(sanitizer);
157       } catch (Throwable e) {
158         LOG.error("Can't create sanitizer: '" + sanitizerClass + "'", e);
159         result.setSanitizer(new IgnoringSanitizer());
160       }
161     }
162 
163     return result;
164   }
165 
166   protected void makeTransitive() {
167     // make the half order transitive: a < b && b < c => a < c
168     boolean growing = true;
169     while (growing) {
170       growing = false;
171       for (int i = 0; i < pairs.size(); i++) {
172         for (int j = 0; j < pairs.size(); j++) {
173           if (pairs.get(i).getHigher() == pairs.get(j).getLower()
174               && !isInRelation(pairs.get(i).getLower(), pairs.get(j).getHigher())) {
175             pairs.add(new Pair(pairs.get(i).getLower(), pairs.get(j).getHigher()));
176             growing = true;
177           }
178         }
179       }
180     }
181   }
182 
183   protected void ensureIrreflexive() {
184     for (final Pair a : pairs) {
185         if (a.getLower() == a.getHigher()) {
186           final StringBuilder buffer = new StringBuilder();
187           buffer.append("Ordering problem. There are conflicting order rules. Not irreflexive. '");
188           buffer.append(a.getLower());
189           buffer.append("' < '");
190           buffer.append(a.getHigher());
191           buffer.append("'!\nThe reason may be a cycle.\n");
192           buffer.append("Complete list of rules: \n");
193           for (final Pair pair : pairs) {
194             buffer.append("'");
195             buffer.append(pair.getLower());
196             buffer.append("' < '");
197             buffer.append(pair.getHigher());
198             buffer.append("'\n");
199 
200           }
201           throw new RuntimeException(buffer.toString());
202         }
203       }
204   }
205 
206   protected void ensureAntiSymmetric() {
207     for (final Pair a : pairs) {
208       for (final Pair b : pairs) {
209         if (a.getLower() == b.getHigher() && a.getHigher() == b.getLower()) {
210           final StringBuilder buffer = new StringBuilder();
211           buffer.append("Ordering problem. There are conflicting order rules. Not antisymmetric. '");
212           buffer.append(a.getLower());
213           buffer.append("' < '");
214           buffer.append(a.getHigher());
215           buffer.append("'" + "'");
216           buffer.append(a.getLower());
217           buffer.append("' > '");
218           buffer.append(a.getHigher());
219           buffer.append("'!\nThe reason may be a cycle.\n");
220           buffer.append("Complete list of rules: \n");
221           for (final Pair pair : pairs) {
222             buffer.append("'");
223             buffer.append(pair.getLower());
224             buffer.append("' < '");
225             buffer.append(pair.getHigher());
226             buffer.append("'\n");
227 
228           }
229           throw new RuntimeException(buffer.toString());
230         }
231       }
232     }
233   }
234 
235   @Override
236   public int compare(final TobagoConfigFragment a, final TobagoConfigFragment b) {
237     if (isInRelation(a, b)) {
238       return -1;
239     }
240     if (isInRelation(b, a)) {
241       return 1;
242     }
243     return 0;
244   }
245 
246   protected void createRelevantPairs() {
247 
248     pairs = new ArrayList<Pair>();
249 
250     // collecting all relations, which are relevant for us. We don't need "before" and "after" of unknown names.
251     for (final TobagoConfigFragment tobagoConfig : list) {
252       for (final String befores : tobagoConfig.getBefore()) {
253         final TobagoConfigFragment before = findByName(befores);
254         if (before != null) {
255           pairs.add(new Pair(tobagoConfig, before));
256         }
257       }
258       for (final String afters : tobagoConfig.getAfter()) {
259         final TobagoConfigFragment after = findByName(afters);
260         if (after != null) {
261           pairs.add(new Pair(after, tobagoConfig));
262         }
263       }
264     }
265   }
266 
267   protected void sort0() {
268     Collections.sort(list, this);
269   }
270 
271   private boolean isInRelation(final TobagoConfigFragment lower, final TobagoConfigFragment higher) {
272     for (final Pair p : pairs) {
273       if (p.getLower() == lower && p.getHigher() == higher) {
274         return true;
275       }
276     }
277     return false;
278   }
279 
280   private TobagoConfigFragment findByName(final String name) {
281     for (final TobagoConfigFragment tobagoConfig : list) {
282       if (name.equals(tobagoConfig.getName())) {
283         return tobagoConfig;
284       }
285     }
286     return null;
287   }
288 
289   private void resolveThemes(TobagoConfigImpl tobagoConfig, Map<String, ThemeImpl> map) {
290     for (final ThemeImpl theme : map.values()) {
291       final String fallbackName = theme.getFallbackName();
292       final ThemeImpl fallback = map.get(fallbackName);
293       theme.setFallback(fallback);
294     }
295     for (final ThemeImpl theme : map.values()) {
296       theme.resolveFallbacks();
297     }
298     for (final ThemeImpl theme : map.values()) {
299       theme.resolveRendererConfig(tobagoConfig.getRenderersConfig());
300     }
301     for (final ThemeImpl theme : map.values()) {
302       theme.resolveResources();
303     }
304     for (final ThemeImpl theme : map.values()) {
305       theme.init();
306     }
307   }
308 
309   protected List<Pair> getPairs() {
310     return pairs;
311   }
312 
313   private static class Pair {
314 
315     private final TobagoConfigFragment lower;
316     private final TobagoConfigFragment higher;
317 
318     private Pair(final TobagoConfigFragment lower, final TobagoConfigFragment higher) {
319       this.lower = lower;
320       this.higher = higher;
321     }
322 
323     public TobagoConfigFragment getLower() {
324       return lower;
325     }
326 
327     public TobagoConfigFragment getHigher() {
328       return higher;
329     }
330 
331     @Override
332     public String toString() {
333       return lower + "<" + higher;
334     }
335   }
336 
337 }