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