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.filter;
018
019import java.util.ArrayList;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Map;
023
024import org.apache.logging.log4j.Level;
025import org.apache.logging.log4j.Marker;
026import org.apache.logging.log4j.core.Filter;
027import org.apache.logging.log4j.core.LogEvent;
028import org.apache.logging.log4j.core.Logger;
029import org.apache.logging.log4j.core.config.Node;
030import org.apache.logging.log4j.core.config.plugins.Plugin;
031import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
032import org.apache.logging.log4j.core.config.plugins.PluginElement;
033import org.apache.logging.log4j.core.config.plugins.PluginFactory;
034import org.apache.logging.log4j.core.util.KeyValuePair;
035import org.apache.logging.log4j.message.Message;
036import org.apache.logging.log4j.message.StructuredDataMessage;
037import org.apache.logging.log4j.util.IndexedReadOnlyStringMap;
038import org.apache.logging.log4j.util.PerformanceSensitive;
039import org.apache.logging.log4j.util.StringBuilders;
040
041/**
042 * Filter based on data in a StructuredDataMessage.
043 */
044@Plugin(name = "StructuredDataFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
045@PerformanceSensitive("allocation")
046public final class StructuredDataFilter extends MapFilter {
047
048    private static final int MAX_BUFFER_SIZE = 2048;
049    private static ThreadLocal<StringBuilder> threadLocalStringBuilder = new ThreadLocal<>();
050
051    private StructuredDataFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch,
052                                 final Result onMismatch) {
053        super(map, oper, onMatch, onMismatch);
054    }
055
056    @Override
057    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
058                         final Throwable t) {
059        if (msg instanceof StructuredDataMessage) {
060            return filter((StructuredDataMessage) msg);
061        }
062        return Result.NEUTRAL;
063    }
064
065    @Override
066    public Result filter(final LogEvent event) {
067        final Message msg = event.getMessage();
068        if (msg instanceof StructuredDataMessage) {
069            return filter((StructuredDataMessage) msg);
070        }
071        return super.filter(event);
072    }
073
074    protected Result filter(final StructuredDataMessage message) {
075        boolean match = false;
076        final IndexedReadOnlyStringMap map = getStringMap();
077        for (int i = 0; i < map.size(); i++) {
078            final StringBuilder toMatch = getValue(message, map.getKeyAt(i));
079            if (toMatch != null) {
080                match = listContainsValue((List<String>) map.getValueAt(i), toMatch);
081            } else {
082                match = false;
083            }
084            if ((!isAnd() && match) || (isAnd() && !match)) {
085                break;
086            }
087        }
088        return match ? onMatch : onMismatch;
089    }
090
091    private StringBuilder getValue(final StructuredDataMessage data, final String key) {
092        final StringBuilder sb = getStringBuilder();
093        if (key.equalsIgnoreCase("id")) {
094            data.getId().formatTo(sb);
095            return sb;
096        } else if (key.equalsIgnoreCase("id.name")) {
097            return appendOrNull(data.getId().getName(), sb);
098        } else if (key.equalsIgnoreCase("type")) {
099            return appendOrNull(data.getType(), sb);
100        } else if (key.equalsIgnoreCase("message")) {
101            data.formatTo(sb);
102            return sb;
103        } else {
104            return appendOrNull(data.get(key), sb);
105        }
106    }
107
108    private StringBuilder getStringBuilder() {
109        StringBuilder result = threadLocalStringBuilder.get();
110        if (result == null) {
111            result = new StringBuilder();
112            threadLocalStringBuilder.set(result);
113        }
114        StringBuilders.trimToMaxSize(result, MAX_BUFFER_SIZE);
115        result.setLength(0);
116        return result;
117    }
118
119    private StringBuilder appendOrNull(final String value, final StringBuilder sb) {
120        if (value == null) {
121            return null;
122        }
123        sb.append(value);
124        return sb;
125    }
126
127    private boolean listContainsValue(final List<String> candidates, final StringBuilder toMatch) {
128        if (toMatch == null) {
129            for (int i = 0; i < candidates.size(); i++) {
130                final String candidate = candidates.get(i);
131                if (candidate == null) {
132                    return true;
133                }
134            }
135        } else {
136            for (int i = 0; i < candidates.size(); i++) {
137                final String candidate = candidates.get(i);
138                if (candidate == null) {
139                    return false;
140                }
141                if (StringBuilders.equals(candidate, 0, candidate.length(), toMatch, 0, toMatch.length())) {
142                    return true;
143                }
144            }
145        }
146        return false;
147    }
148
149    /**
150     * Creates the StructuredDataFilter.
151     * @param pairs Key and value pairs.
152     * @param oper The operator to perform. If not "or" the operation will be an "and".
153     * @param match The action to perform on a match.
154     * @param mismatch The action to perform on a mismatch.
155     * @return The StructuredDataFilter.
156     */
157    // TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
158    @PluginFactory
159    public static StructuredDataFilter createFilter(
160            @PluginElement("Pairs") final KeyValuePair[] pairs,
161            @PluginAttribute("operator") final String oper,
162            @PluginAttribute("onMatch") final Result match,
163            @PluginAttribute("onMismatch") final Result mismatch) {
164        if (pairs == null || pairs.length == 0) {
165            LOGGER.error("keys and values must be specified for the StructuredDataFilter");
166            return null;
167        }
168        final Map<String, List<String>> map = new HashMap<>();
169        for (final KeyValuePair pair : pairs) {
170            final String key = pair.getKey();
171            if (key == null) {
172                LOGGER.error("A null key is not valid in MapFilter");
173                continue;
174            }
175            final String value = pair.getValue();
176            if (value == null) {
177                LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
178                continue;
179            }
180            List<String> list = map.get(pair.getKey());
181            if (list != null) {
182                list.add(value);
183            } else {
184                list = new ArrayList<>();
185                list.add(value);
186                map.put(pair.getKey(), list);
187            }
188        }
189        if (map.isEmpty()) {
190            LOGGER.error("StructuredDataFilter is not configured with any valid key value pairs");
191            return null;
192        }
193        final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
194        return new StructuredDataFilter(map, isAnd, match, mismatch);
195    }
196}