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