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