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        // renderers config
95        if (fragment.getRenderersConfig() != null) {
96          if (result.getRenderersConfig() instanceof RenderersConfigImpl) {
97            ((RenderersConfigImpl) result.getRenderersConfig()).merge(fragment.getRenderersConfig(), false);
98          } else if (result.getRenderersConfig() == null) {
99            result.setRenderersConfig(fragment.getRenderersConfig());
100         }
101       }
102 
103       // session secret
104       if (fragment.getCreateSessionSecret() != null) {
105         result.setCreateSessionSecret(fragment.getCreateSessionSecret());
106       }
107       if (fragment.getCheckSessionSecret() != null) {
108         result.setCheckSessionSecret(fragment.getCheckSessionSecret());
109       }
110 
111       if (fragment.getPreventFrameAttacks() != null) {
112         result.setPreventFrameAttacks(fragment.getPreventFrameAttacks());
113       }
114 
115       if (fragment.getContentSecurityPolicy() != null) {
116         result.getContentSecurityPolicy().merge(fragment.getContentSecurityPolicy());
117       }
118 
119       if (fragment.getSecurityAnnotation() != null) {
120         result.setSecurityAnnotation(fragment.getSecurityAnnotation());
121       }
122 
123       if (fragment.getSetNosniffHeader() != null) {
124         result.setSetNosniffHeader(fragment.getSetNosniffHeader());
125       }
126 
127       if (fragment.getSanitizerClass() != null) {
128         sanitizerClass = fragment.getSanitizerClass();
129         sanitizerProperties = fragment.getSanitizerProperties();
130       }
131 
132       if (fragment.getDecodeLineFeed() != null) {
133         result.setDecodeLineFeed(fragment.getDecodeLineFeed());
134       }
135 
136       // theme definition
137       for (ThemeImpl theme : fragment.getThemeDefinitions()) {
138         result.addAvailableTheme(theme);
139       }
140 
141       // url
142       // todo???
143 
144       final Map<String, String> mimeTypes = result.getMimeTypes();
145       for (final Map.Entry<String, String> entry : fragment.getMimeTypes().entrySet()) {
146         mimeTypes.put(entry.getKey(), entry.getValue());
147       }
148 
149     }
150 
151     resolveThemes(result, result.getAvailableThemes());
152 
153     if (sanitizerClass != null) {
154       try {
155         final Class<? extends Sanitizer> aClass = Class.forName(sanitizerClass).asSubclass(Sanitizer.class);
156         final Sanitizer sanitizer = aClass.newInstance();
157         sanitizer.setProperties(sanitizerProperties);
158         result.setSanitizer(sanitizer);
159       } catch (Throwable e) {
160         LOG.error("Can't create sanitizer: '" + sanitizerClass + "'", e);
161         result.setSanitizer(new IgnoringSanitizer());
162       }
163     }
164 
165     return result;
166   }
167 
168   protected void makeTransitive() {
169     // make the half order transitive: a < b && b < c => a < c
170     boolean growing = true;
171     while (growing) {
172       growing = false;
173       for (int i = 0; i < pairs.size(); i++) {
174         for (int j = 0; j < pairs.size(); j++) {
175           if (pairs.get(i).getHigher() == pairs.get(j).getLower()
176               && !isInRelation(pairs.get(i).getLower(), pairs.get(j).getHigher())) {
177             pairs.add(new Pair(pairs.get(i).getLower(), pairs.get(j).getHigher()));
178             growing = true;
179           }
180         }
181       }
182     }
183   }
184 
185   protected void ensureIrreflexive() {
186     for (final Pair a : pairs) {
187         if (a.getLower() == a.getHigher()) {
188           final StringBuilder buffer = new StringBuilder();
189           buffer.append("Ordering problem. There are conflicting order rules. Not irreflexive. '");
190           buffer.append(a.getLower());
191           buffer.append("' < '");
192           buffer.append(a.getHigher());
193           buffer.append("'!\nThe reason may be a cycle.\n");
194           buffer.append("Complete list of rules: \n");
195           for (final Pair pair : pairs) {
196             buffer.append("'");
197             buffer.append(pair.getLower());
198             buffer.append("' < '");
199             buffer.append(pair.getHigher());
200             buffer.append("'\n");
201 
202           }
203           throw new RuntimeException(buffer.toString());
204         }
205       }
206   }
207 
208   protected void ensureAntiSymmetric() {
209     for (final Pair a : pairs) {
210       for (final Pair b : pairs) {
211         if (a.getLower() == b.getHigher() && a.getHigher() == b.getLower()) {
212           final StringBuilder buffer = new StringBuilder();
213           buffer.append("Ordering problem. There are conflicting order rules. Not antisymmetric. '");
214           buffer.append(a.getLower());
215           buffer.append("' < '");
216           buffer.append(a.getHigher());
217           buffer.append("'" + "'");
218           buffer.append(a.getLower());
219           buffer.append("' > '");
220           buffer.append(a.getHigher());
221           buffer.append("'!\nThe reason may be a cycle.\n");
222           buffer.append("Complete list of rules: \n");
223           for (final Pair pair : pairs) {
224             buffer.append("'");
225             buffer.append(pair.getLower());
226             buffer.append("' < '");
227             buffer.append(pair.getHigher());
228             buffer.append("'\n");
229 
230           }
231           throw new RuntimeException(buffer.toString());
232         }
233       }
234     }
235   }
236 
237   @Override
238   public int compare(final TobagoConfigFragment a, final TobagoConfigFragment b) {
239     if (isInRelation(a, b)) {
240       return -1;
241     }
242     if (isInRelation(b, a)) {
243       return 1;
244     }
245     return 0;
246   }
247 
248   protected void createRelevantPairs() {
249 
250     pairs = new ArrayList<Pair>();
251 
252     // collecting all relations, which are relevant for us. We don't need "before" and "after" of unknown names.
253     for (final TobagoConfigFragment tobagoConfig : list) {
254       for (final String befores : tobagoConfig.getBefore()) {
255         final TobagoConfigFragment before = findByName(befores);
256         if (before != null) {
257           pairs.add(new Pair(tobagoConfig, before));
258         }
259       }
260       for (final String afters : tobagoConfig.getAfter()) {
261         final TobagoConfigFragment after = findByName(afters);
262         if (after != null) {
263           pairs.add(new Pair(after, tobagoConfig));
264         }
265       }
266     }
267   }
268 
269   protected void sort0() {
270     Collections.sort(list, this);
271   }
272 
273   private boolean isInRelation(final TobagoConfigFragment lower, final TobagoConfigFragment higher) {
274     for (final Pair p : pairs) {
275       if (p.getLower() == lower && p.getHigher() == higher) {
276         return true;
277       }
278     }
279     return false;
280   }
281 
282   private TobagoConfigFragment findByName(final String name) {
283     for (final TobagoConfigFragment tobagoConfig : list) {
284       if (name.equals(tobagoConfig.getName())) {
285         return tobagoConfig;
286       }
287     }
288     return null;
289   }
290 
291   private void resolveThemes(TobagoConfigImpl tobagoConfig, Map<String, ThemeImpl> map) {
292     for (final ThemeImpl theme : map.values()) {
293       final String fallbackName = theme.getFallbackName();
294       final ThemeImpl fallback = map.get(fallbackName);
295       theme.setFallback(fallback);
296     }
297     for (final ThemeImpl theme : map.values()) {
298       theme.resolveFallbacks();
299     }
300     for (final ThemeImpl theme : map.values()) {
301       theme.resolveRendererConfig(tobagoConfig.getRenderersConfig());
302     }
303     for (final ThemeImpl theme : map.values()) {
304       theme.resolveResources();
305     }
306     for (final ThemeImpl theme : map.values()) {
307       theme.init();
308     }
309   }
310 
311   protected List<Pair> getPairs() {
312     return pairs;
313   }
314 
315   private static class Pair {
316 
317     private final TobagoConfigFragment lower;
318     private final TobagoConfigFragment higher;
319 
320     private Pair(final TobagoConfigFragment lower, final TobagoConfigFragment higher) {
321       this.lower = lower;
322       this.higher = higher;
323     }
324 
325     public TobagoConfigFragment getLower() {
326       return lower;
327     }
328 
329     public TobagoConfigFragment getHigher() {
330       return higher;
331     }
332 
333     @Override
334     public String toString() {
335       return lower + "<" + higher;
336     }
337   }
338 
339 }