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