View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.config.json;
18  
19  import java.io.ByteArrayInputStream;
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.util.ArrayList;
24  import java.util.Arrays;
25  import java.util.Iterator;
26  import java.util.List;
27  import java.util.Map;
28  
29  import org.apache.logging.log4j.core.config.AbstractConfiguration;
30  import org.apache.logging.log4j.core.config.Configuration;
31  import org.apache.logging.log4j.core.config.ConfigurationSource;
32  import org.apache.logging.log4j.core.config.FileConfigurationMonitor;
33  import org.apache.logging.log4j.core.config.Node;
34  import org.apache.logging.log4j.core.config.Reconfigurable;
35  import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
36  import org.apache.logging.log4j.core.config.plugins.util.PluginType;
37  import org.apache.logging.log4j.core.config.plugins.util.ResolverUtil;
38  import org.apache.logging.log4j.core.config.status.StatusConfiguration;
39  import org.apache.logging.log4j.core.util.Patterns;
40  
41  import com.fasterxml.jackson.core.JsonParser;
42  import com.fasterxml.jackson.databind.JsonNode;
43  import com.fasterxml.jackson.databind.ObjectMapper;
44  
45  /**
46   * Creates a Node hierarchy from a JSON file.
47   */
48  public class JsonConfiguration extends AbstractConfiguration implements Reconfigurable {
49  
50      private static final String[] VERBOSE_CLASSES = new String[] { ResolverUtil.class.getName() };
51      private final List<Status> status = new ArrayList<Status>();
52      private JsonNode root;
53  
54      public JsonConfiguration(final ConfigurationSource configSource) {
55          super(configSource);
56          final File configFile = configSource.getFile();
57          byte[] buffer;
58          try {
59              final InputStream configStream = configSource.getInputStream();
60              try {
61                  buffer = toByteArray(configStream);
62              } finally {
63                  configStream.close();
64              }
65              final InputStream is = new ByteArrayInputStream(buffer);
66              root = getObjectMapper().readTree(is);
67              if (root.size() == 1) {
68                  for (final JsonNode node : root) {
69                      root = node;
70                  }
71              }
72              processAttributes(rootNode, root);
73              final StatusConfiguration statusConfig = new StatusConfiguration().withVerboseClasses(VERBOSE_CLASSES)
74                      .withStatus(getDefaultStatus());
75              for (final Map.Entry<String, String> entry : rootNode.getAttributes().entrySet()) {
76                  final String key = entry.getKey();
77                  final String value = getStrSubstitutor().replace(entry.getValue());
78                  // TODO: this duplicates a lot of the XmlConfiguration constructor
79                  if ("status".equalsIgnoreCase(key)) {
80                      statusConfig.withStatus(value);
81                  } else if ("dest".equalsIgnoreCase(key)) {
82                      statusConfig.withDestination(value);
83                  } else if ("shutdownHook".equalsIgnoreCase(key)) {
84                      isShutdownHookEnabled = !"disable".equalsIgnoreCase(value);
85                  } else if ("verbose".equalsIgnoreCase(entry.getKey())) {
86                      statusConfig.withVerbosity(value);
87                  } else if ("packages".equalsIgnoreCase(key)) {
88                      PluginManager.addPackages(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR)));
89                  } else if ("name".equalsIgnoreCase(key)) {
90                      setName(value);
91                  } else if ("monitorInterval".equalsIgnoreCase(key)) {
92                      final int interval = Integer.parseInt(value);
93                      if (interval > 0 && configFile != null) {
94                          monitor = new FileConfigurationMonitor(this, configFile, listeners, interval);
95                      }
96                  } else if ("advertiser".equalsIgnoreCase(key)) {
97                      createAdvertiser(value, configSource, buffer, "application/json");
98                  }
99              }
100             statusConfig.initialize();
101             if (getName() == null) {
102                 setName(configSource.getLocation());
103             }
104         } catch (final Exception ex) {
105             LOGGER.error("Error parsing {}", configSource.getLocation(), ex);
106         }
107     }
108 
109     protected ObjectMapper getObjectMapper() {
110         return new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true);
111     }
112 
113     @Override
114     public void setup() {
115         final Iterator<Map.Entry<String, JsonNode>> iter = root.fields();
116         final List<Node> children = rootNode.getChildren();
117         while (iter.hasNext()) {
118             final Map.Entry<String, JsonNode> entry = iter.next();
119             final JsonNode n = entry.getValue();
120             if (n.isObject()) {
121                 LOGGER.debug("Processing node for object {}", entry.getKey());
122                 children.add(constructNode(entry.getKey(), rootNode, n));
123             } else if (n.isArray()) {
124                 LOGGER.error("Arrays are not supported at the root configuration.");
125             }
126         }
127         LOGGER.debug("Completed parsing configuration");
128         if (status.size() > 0) {
129             for (final Status s : status) {
130                 LOGGER.error("Error processing element " + s.name + ": " + s.errorType);
131             }
132         }
133     }
134 
135     @Override
136     public Configuration reconfigure() {
137         try {
138             final ConfigurationSource source = getConfigurationSource().resetInputStream();
139             if (source == null) {
140                 return null;
141             }
142             return new JsonConfiguration(source);
143         } catch (final IOException ex) {
144             LOGGER.error("Cannot locate file {}", getConfigurationSource(), ex);
145         }
146         return null;
147     }
148 
149     private Node constructNode(final String name, final Node parent, final JsonNode jsonNode) {
150         final PluginType<?> type = pluginManager.getPluginType(name);
151         final Node node = new Node(parent, name, type);
152         processAttributes(node, jsonNode);
153         final Iterator<Map.Entry<String, JsonNode>> iter = jsonNode.fields();
154         final List<Node> children = node.getChildren();
155         while (iter.hasNext()) {
156             final Map.Entry<String, JsonNode> entry = iter.next();
157             final JsonNode n = entry.getValue();
158             if (n.isArray() || n.isObject()) {
159                 if (type == null) {
160                     status.add(new Status(name, n, ErrorType.CLASS_NOT_FOUND));
161                 }
162                 if (n.isArray()) {
163                     LOGGER.debug("Processing node for array {}", entry.getKey());
164                     for (int i = 0; i < n.size(); ++i) {
165                         final String pluginType = getType(n.get(i), entry.getKey());
166                         final PluginType<?> entryType = pluginManager.getPluginType(pluginType);
167                         final Node item = new Node(node, entry.getKey(), entryType);
168                         processAttributes(item, n.get(i));
169                         if (pluginType.equals(entry.getKey())) {
170                             LOGGER.debug("Processing {}[{}]", entry.getKey(), i);
171                         } else {
172                             LOGGER.debug("Processing {} {}[{}]", pluginType, entry.getKey(), i);
173                         }
174                         final Iterator<Map.Entry<String, JsonNode>> itemIter = n.get(i).fields();
175                         final List<Node> itemChildren = item.getChildren();
176                         while (itemIter.hasNext()) {
177                             final Map.Entry<String, JsonNode> itemEntry = itemIter.next();
178                             if (itemEntry.getValue().isObject()) {
179                                 LOGGER.debug("Processing node for object {}", itemEntry.getKey());
180                                 itemChildren.add(constructNode(itemEntry.getKey(), item, itemEntry.getValue()));
181                             } else if (itemEntry.getValue().isArray()) {
182                                 final JsonNode array = itemEntry.getValue();
183                                 final String entryName = itemEntry.getKey();
184                                 LOGGER.debug("Processing array for object {}", entryName);
185                                 for (int j = 0; j < array.size(); ++j) {
186                                     itemChildren.add(constructNode(entryName, item, array.get(j)));
187                                 }
188                             }
189 
190                         }
191                         children.add(item);
192                     }
193                 } else {
194                     LOGGER.debug("Processing node for object {}", entry.getKey());
195                     children.add(constructNode(entry.getKey(), node, n));
196                 }
197             } else {
198                 LOGGER.debug("Node {} is of type {}", entry.getKey(), n.getNodeType());
199             }
200         }
201 
202         String t;
203         if (type == null) {
204             t = "null";
205         } else {
206             t = type.getElementName() + ':' + type.getPluginClass();
207         }
208 
209         final String p = node.getParent() == null ? "null" : node.getParent().getName() == null ? "root" : node
210                 .getParent().getName();
211         LOGGER.debug("Returning {} with parent {} of type {}", node.getName(), p, t);
212         return node;
213     }
214 
215     private String getType(final JsonNode node, final String name) {
216         final Iterator<Map.Entry<String, JsonNode>> iter = node.fields();
217         while (iter.hasNext()) {
218             final Map.Entry<String, JsonNode> entry = iter.next();
219             if (entry.getKey().equalsIgnoreCase("type")) {
220                 final JsonNode n = entry.getValue();
221                 if (n.isValueNode()) {
222                     return n.asText();
223                 }
224             }
225         }
226         return name;
227     }
228 
229     private void processAttributes(final Node parent, final JsonNode node) {
230         final Map<String, String> attrs = parent.getAttributes();
231         final Iterator<Map.Entry<String, JsonNode>> iter = node.fields();
232         while (iter.hasNext()) {
233             final Map.Entry<String, JsonNode> entry = iter.next();
234             if (!entry.getKey().equalsIgnoreCase("type")) {
235                 final JsonNode n = entry.getValue();
236                 if (n.isValueNode()) {
237                     attrs.put(entry.getKey(), n.asText());
238                 }
239             }
240         }
241     }
242 
243     @Override
244     public String toString() {
245         return getClass().getSimpleName() + "[location=" + getConfigurationSource() + "]";
246     }
247 
248     /**
249      * The error that occurred.
250      */
251     private enum ErrorType {
252         CLASS_NOT_FOUND
253     }
254 
255     /**
256      * Status for recording errors.
257      */
258     private static class Status {
259         private final JsonNode node;
260         private final String name;
261         private final ErrorType errorType;
262 
263         public Status(final String name, final JsonNode node, final ErrorType errorType) {
264             this.name = name;
265             this.node = node;
266             this.errorType = errorType;
267         }
268     }
269 }