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.Map;
035    
036    /**
037     * A Filter that operates on a Map.
038     */
039    @Plugin(name = "MapFilter", type = "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(@PluginElement("pairs") final KeyValuePair[] pairs,
120                                             @PluginAttr("operator") final String oper,
121                                             @PluginAttr("onmatch") final String match,
122                                             @PluginAttr("onmismatch") final String mismatch) {
123            if (pairs == null || pairs.length == 0) {
124                LOGGER.error("keys and values must be specified for the MapFilter");
125                return null;
126            }
127            final Map<String, List<String>> map = new HashMap<String, List<String>>();
128            for (final KeyValuePair pair : pairs) {
129                final String key = pair.getKey();
130                if (key == null) {
131                    LOGGER.error("A null key is not valid in MapFilter");
132                    continue;
133                }
134                final String value = pair.getValue();
135                if (value == null) {
136                    LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
137                    continue;
138                }
139                List<String> list = map.get(pair.getKey());
140                if (list != null) {
141                    list.add(value);
142                } else {
143                    list = new ArrayList<String>();
144                    list.add(value);
145                    map.put(pair.getKey(), list);
146                }
147            }
148            if (map.size() == 0) {
149                LOGGER.error("MapFilter is not configured with any valid key value pairs");
150                return null;
151            }
152            final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
153            final Result onMatch = Result.toResult(match);
154            final Result onMismatch = Result.toResult(mismatch);
155            return new MapFilter(map, isAnd, onMatch, onMismatch);
156        }
157    }