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;
023import java.util.Objects;
024
025import org.apache.logging.log4j.Level;
026import org.apache.logging.log4j.Marker;
027import org.apache.logging.log4j.core.Filter;
028import org.apache.logging.log4j.core.LogEvent;
029import org.apache.logging.log4j.core.Logger;
030import org.apache.logging.log4j.core.config.Node;
031import org.apache.logging.log4j.core.config.plugins.Plugin;
032import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
033import org.apache.logging.log4j.core.config.plugins.PluginElement;
034import org.apache.logging.log4j.core.config.plugins.PluginFactory;
035import org.apache.logging.log4j.core.util.KeyValuePair;
036import org.apache.logging.log4j.message.MapMessage;
037import org.apache.logging.log4j.message.Message;
038import org.apache.logging.log4j.util.ReadOnlyStringMap;
039
040/**
041 * A Filter that operates on a Map.
042 */
043@Plugin(name = "MapFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
044public class MapFilter extends AbstractFilter {
045
046    private final Map<String, List<String>> map;
047
048    private final boolean isAnd;
049
050    protected MapFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch,
051                        final Result onMismatch) {
052        super(onMatch, onMismatch);
053        Objects.requireNonNull(map, "map cannot be null");
054        this.isAnd = oper;
055        this.map = map;
056    }
057
058    @Override
059    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
060                         final Throwable t) {
061        if (msg instanceof MapMessage) {
062            return filter(((MapMessage) msg).getData()) ? onMatch : onMismatch;
063        }
064        return Result.NEUTRAL;
065    }
066
067    @Override
068    public Result filter(final LogEvent event) {
069        final Message msg = event.getMessage();
070        if (msg instanceof MapMessage) {
071            return filter(((MapMessage) msg).getData()) ? onMatch : onMismatch;
072        }
073        return Result.NEUTRAL;
074    }
075
076    protected boolean filter(final Map<String, String> data) {
077        boolean match = false;
078        for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
079            final String toMatch = data.get(entry.getKey());
080            match = toMatch != null && entry.getValue().contains(toMatch);
081            if ((!isAnd && match) || (isAnd && !match)) {
082                break;
083            }
084        }
085        return match;
086    }
087
088    protected boolean filter(final ReadOnlyStringMap data) {
089        boolean match = false;
090        for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
091            final String toMatch = data.getValue(entry.getKey());
092            match = toMatch != null && entry.getValue().contains(toMatch);
093            if ((!isAnd && match) || (isAnd && !match)) {
094                break;
095            }
096        }
097        return match;
098    }
099
100    @Override
101    public String toString() {
102        final StringBuilder sb = new StringBuilder();
103        sb.append("isAnd=").append(isAnd);
104        if (map.size() > 0) {
105            sb.append(", {");
106            boolean first = true;
107            for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
108                if (!first) {
109                    sb.append(", ");
110                }
111                first = false;
112                final List<String> list = entry.getValue();
113                final String value = list.size() > 1 ? list.get(0) : list.toString();
114                sb.append(entry.getKey()).append('=').append(value);
115            }
116            sb.append('}');
117        }
118        return sb.toString();
119    }
120
121    protected boolean isAnd() {
122        return isAnd;
123    }
124
125    protected Map<String, List<String>> getMap() {
126        return map;
127    }
128
129    @PluginFactory
130    public static MapFilter createFilter(
131            @PluginElement("Pairs") final KeyValuePair[] pairs,
132            @PluginAttribute("operator") final String oper,
133            @PluginAttribute("onMatch") final Result match,
134            @PluginAttribute("onMismatch") final Result mismatch) {
135        if (pairs == null || pairs.length == 0) {
136            LOGGER.error("keys and values must be specified for the MapFilter");
137            return null;
138        }
139        final Map<String, List<String>> map = new HashMap<>();
140        for (final KeyValuePair pair : pairs) {
141            final String key = pair.getKey();
142            if (key == null) {
143                LOGGER.error("A null key is not valid in MapFilter");
144                continue;
145            }
146            final String value = pair.getValue();
147            if (value == null) {
148                LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
149                continue;
150            }
151            List<String> list = map.get(pair.getKey());
152            if (list != null) {
153                list.add(value);
154            } else {
155                list = new ArrayList<>();
156                list.add(value);
157                map.put(pair.getKey(), list);
158            }
159        }
160        if (map.isEmpty()) {
161            LOGGER.error("MapFilter is not configured with any valid key value pairs");
162            return null;
163        }
164        final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
165        return new MapFilter(map, isAnd, match, mismatch);
166    }
167}