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 java.util.ArrayList;
23  import java.util.Collections;
24  import java.util.List;
25  
26  public class ContentSecurityPolicy {
27  
28    private Mode mode;
29    private List<String> directiveList;
30  
31    private boolean unmodifiable = false;
32  
33    private void checkLocked() throws IllegalStateException {
34      if (unmodifiable) {
35        throw new RuntimeException("The configuration must not be changed after initialization!");
36      }
37    }
38  
39    /**
40     * Lock the configuration, so it cannot be modified any more.
41     */
42    public void lock() {
43      unmodifiable = true;
44      directiveList = Collections.unmodifiableList(directiveList);
45    }
46  
47    public ContentSecurityPolicy(final String mode) {
48      this.mode = Mode.parse(mode);
49      this.directiveList = new ArrayList<String>();
50    }
51  
52    public void merge(final ContentSecurityPolicy other) {
53      checkLocked();
54      directiveList.addAll(other.directiveList);
55      mode = other.mode;
56    }
57  
58    public List<String> getDirectiveList() {
59      return directiveList;
60    }
61  
62    public Mode getMode() {
63      return mode;
64    }
65  
66    public static enum Mode {
67      ON("on"),
68      OFF("off"),
69      REPORT_ONLY("report-only");
70  
71      private final String value;
72  
73      private Mode(final String value) {
74        this.value = value;
75      }
76  
77      public String getValue() {
78        return value;
79      }
80  
81      public static Mode parse(final String string) {
82        if (ON.value.equals(string)) {
83          return ON;
84        } else if (OFF.value.equals(string)) {
85          return OFF;
86        } else if (REPORT_ONLY.value.equals(string)) {
87          return REPORT_ONLY;
88        } else {
89          throw new IllegalArgumentException("Found: " + string);
90        }
91      }
92    }
93  
94  }