All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mockserver.matchers.MapMatcher Maven / Gradle / Ivy

There is a newer version: 5.15.0
Show newest version
package org.mockserver.matchers;

import com.google.common.collect.Multimap;
import org.mockserver.model.KeyToMultiValue;
import org.mockserver.model.ModelObject;

import java.util.List;
import java.util.regex.PatternSyntaxException;

/**
 * @author jamesdbloom
 */
public class MapMatcher extends ModelObject implements Matcher> {
    private final Multimap multimap;

    public MapMatcher(Multimap multimap) {
        this.multimap = multimap;
    }

    public boolean matches(List values) {
        boolean result = false;

        if (containsAll(KeyToMultiValue.toMultiMap(values), this.multimap)) {
            result = true;
        } else {
            logger.trace("Map [{}] is not a subset of [{}]", this.multimap, KeyToMultiValue.toMultiMap(values));
        }

        return result;
    }

    private boolean containsAll(Multimap superset, Multimap subset) {
        for (String key : subset.keySet()) {
            for (String value : subset.get(key)) {
                boolean regexMatches = false;
                if (!superset.containsKey(key)) {
                    return false;
                } else { // key does exist
                    for (String supersetValue : superset.get(key)) {
                        try {
                            if (supersetValue.matches(value)) {
                                regexMatches = true;
                            }
                        } catch (PatternSyntaxException pse) {
                            logger.error("Error while matching regex [" +  value + "] for string [" + supersetValue + "] " + pse.getMessage());
                        }
                    }
                    if (!regexMatches) {
                        return false;
                    }
                }
                if (!regexMatches && !superset.containsEntry(key, value)) {
                    return false;
                }
            }
        }
        return true;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy