001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.config.json;
018
019import com.fasterxml.jackson.core.JsonParser;
020import com.fasterxml.jackson.databind.JsonNode;
021import com.fasterxml.jackson.databind.ObjectMapper;
022import org.apache.logging.log4j.core.config.AbstractConfiguration;
023import org.apache.logging.log4j.core.config.Configuration;
024import org.apache.logging.log4j.core.config.ConfigurationSource;
025import org.apache.logging.log4j.core.config.FileConfigurationMonitor;
026import org.apache.logging.log4j.core.config.Node;
027import org.apache.logging.log4j.core.config.Reconfigurable;
028import org.apache.logging.log4j.core.config.plugins.util.PluginType;
029import org.apache.logging.log4j.core.config.plugins.util.ResolverUtil;
030import org.apache.logging.log4j.core.config.status.StatusConfiguration;
031import org.apache.logging.log4j.core.util.Patterns;
032
033import java.io.ByteArrayInputStream;
034import java.io.File;
035import java.io.IOException;
036import java.io.InputStream;
037import java.util.ArrayList;
038import java.util.Arrays;
039import java.util.Iterator;
040import java.util.List;
041import java.util.Map;
042
043/**
044 * Creates a Node hierarchy from a JSON file.
045 */
046public class JsonConfiguration extends AbstractConfiguration implements Reconfigurable {
047
048    private static final long serialVersionUID = 1L;
049    private static final String[] VERBOSE_CLASSES = new String[] { ResolverUtil.class.getName() };
050    private final List<Status> status = new ArrayList<>();
051    private JsonNode root;
052
053    public JsonConfiguration(final ConfigurationSource configSource) {
054        super(configSource);
055        final File configFile = configSource.getFile();
056        byte[] buffer;
057        try {
058            try (final InputStream configStream = configSource.getInputStream()) {
059                buffer = toByteArray(configStream);
060            }
061            final InputStream is = new ByteArrayInputStream(buffer);
062            root = getObjectMapper().readTree(is);
063            if (root.size() == 1) {
064                for (final JsonNode node : root) {
065                    root = node;
066                }
067            }
068            processAttributes(rootNode, root);
069            final StatusConfiguration statusConfig = new StatusConfiguration().withVerboseClasses(VERBOSE_CLASSES)
070                    .withStatus(getDefaultStatus());
071            for (final Map.Entry<String, String> entry : rootNode.getAttributes().entrySet()) {
072                final String key = entry.getKey();
073                final String value = getStrSubstitutor().replace(entry.getValue());
074                // TODO: this duplicates a lot of the XmlConfiguration constructor
075                if ("status".equalsIgnoreCase(key)) {
076                    statusConfig.withStatus(value);
077                } else if ("dest".equalsIgnoreCase(key)) {
078                    statusConfig.withDestination(value);
079                } else if ("shutdownHook".equalsIgnoreCase(key)) {
080                    isShutdownHookEnabled = !"disable".equalsIgnoreCase(value);
081                } else if ("verbose".equalsIgnoreCase(entry.getKey())) {
082                    statusConfig.withVerbosity(value);
083                } else if ("packages".equalsIgnoreCase(key)) {
084                    pluginPackages.addAll(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR)));
085                } else if ("name".equalsIgnoreCase(key)) {
086                    setName(value);
087                } else if ("monitorInterval".equalsIgnoreCase(key)) {
088                    final int intervalSeconds = Integer.parseInt(value);
089                    if (intervalSeconds > 0 && configFile != null) {
090                        monitor = new FileConfigurationMonitor(this, configFile, listeners, intervalSeconds);
091                    }
092                } else if ("advertiser".equalsIgnoreCase(key)) {
093                    createAdvertiser(value, configSource, buffer, "application/json");
094                }
095            }
096            statusConfig.initialize();
097            if (getName() == null) {
098                setName(configSource.getLocation());
099            }
100        } catch (final Exception ex) {
101            LOGGER.error("Error parsing {}", configSource.getLocation(), ex);
102        }
103    }
104
105    protected ObjectMapper getObjectMapper() {
106        return new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true);
107    }
108
109    @Override
110    public void setup() {
111        final Iterator<Map.Entry<String, JsonNode>> iter = root.fields();
112        final List<Node> children = rootNode.getChildren();
113        while (iter.hasNext()) {
114            final Map.Entry<String, JsonNode> entry = iter.next();
115            final JsonNode n = entry.getValue();
116            if (n.isObject()) {
117                LOGGER.debug("Processing node for object {}", entry.getKey());
118                children.add(constructNode(entry.getKey(), rootNode, n));
119            } else if (n.isArray()) {
120                LOGGER.error("Arrays are not supported at the root configuration.");
121            }
122        }
123        LOGGER.debug("Completed parsing configuration");
124        if (status.size() > 0) {
125            for (final Status s : status) {
126                LOGGER.error("Error processing element " + s.name + ": " + s.errorType);
127            }
128        }
129    }
130
131    @Override
132    public Configuration reconfigure() {
133        try {
134            final ConfigurationSource source = getConfigurationSource().resetInputStream();
135            if (source == null) {
136                return null;
137            }
138            return new JsonConfiguration(source);
139        } catch (final IOException ex) {
140            LOGGER.error("Cannot locate file {}", getConfigurationSource(), ex);
141        }
142        return null;
143    }
144
145    private Node constructNode(final String name, final Node parent, final JsonNode jsonNode) {
146        final PluginType<?> type = pluginManager.getPluginType(name);
147        final Node node = new Node(parent, name, type);
148        processAttributes(node, jsonNode);
149        final Iterator<Map.Entry<String, JsonNode>> iter = jsonNode.fields();
150        final List<Node> children = node.getChildren();
151        while (iter.hasNext()) {
152            final Map.Entry<String, JsonNode> entry = iter.next();
153            final JsonNode n = entry.getValue();
154            if (n.isArray() || n.isObject()) {
155                if (type == null) {
156                    status.add(new Status(name, n, ErrorType.CLASS_NOT_FOUND));
157                }
158                if (n.isArray()) {
159                    LOGGER.debug("Processing node for array {}", entry.getKey());
160                    for (int i = 0; i < n.size(); ++i) {
161                        final String pluginType = getType(n.get(i), entry.getKey());
162                        final PluginType<?> entryType = pluginManager.getPluginType(pluginType);
163                        final Node item = new Node(node, entry.getKey(), entryType);
164                        processAttributes(item, n.get(i));
165                        if (pluginType.equals(entry.getKey())) {
166                            LOGGER.debug("Processing {}[{}]", entry.getKey(), i);
167                        } else {
168                            LOGGER.debug("Processing {} {}[{}]", pluginType, entry.getKey(), i);
169                        }
170                        final Iterator<Map.Entry<String, JsonNode>> itemIter = n.get(i).fields();
171                        final List<Node> itemChildren = item.getChildren();
172                        while (itemIter.hasNext()) {
173                            final Map.Entry<String, JsonNode> itemEntry = itemIter.next();
174                            if (itemEntry.getValue().isObject()) {
175                                LOGGER.debug("Processing node for object {}", itemEntry.getKey());
176                                itemChildren.add(constructNode(itemEntry.getKey(), item, itemEntry.getValue()));
177                            } else if (itemEntry.getValue().isArray()) {
178                                final JsonNode array = itemEntry.getValue();
179                                final String entryName = itemEntry.getKey();
180                                LOGGER.debug("Processing array for object {}", entryName);
181                                for (int j = 0; j < array.size(); ++j) {
182                                    itemChildren.add(constructNode(entryName, item, array.get(j)));
183                                }
184                            }
185
186                        }
187                        children.add(item);
188                    }
189                } else {
190                    LOGGER.debug("Processing node for object {}", entry.getKey());
191                    children.add(constructNode(entry.getKey(), node, n));
192                }
193            } else {
194                LOGGER.debug("Node {} is of type {}", entry.getKey(), n.getNodeType());
195            }
196        }
197
198        String t;
199        if (type == null) {
200            t = "null";
201        } else {
202            t = type.getElementName() + ':' + type.getPluginClass();
203        }
204
205        final String p = node.getParent() == null ? "null" : node.getParent().getName() == null ? "root" : node
206                .getParent().getName();
207        LOGGER.debug("Returning {} with parent {} of type {}", node.getName(), p, t);
208        return node;
209    }
210
211    private String getType(final JsonNode node, final String name) {
212        final Iterator<Map.Entry<String, JsonNode>> iter = node.fields();
213        while (iter.hasNext()) {
214            final Map.Entry<String, JsonNode> entry = iter.next();
215            if (entry.getKey().equalsIgnoreCase("type")) {
216                final JsonNode n = entry.getValue();
217                if (n.isValueNode()) {
218                    return n.asText();
219                }
220            }
221        }
222        return name;
223    }
224
225    private void processAttributes(final Node parent, final JsonNode node) {
226        final Map<String, String> attrs = parent.getAttributes();
227        final Iterator<Map.Entry<String, JsonNode>> iter = node.fields();
228        while (iter.hasNext()) {
229            final Map.Entry<String, JsonNode> entry = iter.next();
230            if (!entry.getKey().equalsIgnoreCase("type")) {
231                final JsonNode n = entry.getValue();
232                if (n.isValueNode()) {
233                    attrs.put(entry.getKey(), n.asText());
234                }
235            }
236        }
237    }
238
239    @Override
240    public String toString() {
241        return getClass().getSimpleName() + "[location=" + getConfigurationSource() + "]";
242    }
243
244    /**
245     * The error that occurred.
246     */
247    private enum ErrorType {
248        CLASS_NOT_FOUND
249    }
250
251    /**
252     * Status for recording errors.
253     */
254    private static class Status {
255        private final JsonNode node;
256        private final String name;
257        private final ErrorType errorType;
258
259        public Status(final String name, final JsonNode node, final ErrorType errorType) {
260            this.name = name;
261            this.node = node;
262            this.errorType = errorType;
263        }
264
265        @Override
266        public String toString() {
267            return "Status [name=" + name + ", errorType=" + errorType + ", node=" + node + "]";
268        }
269    }
270}