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