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