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

org.simpleflatmapper.map.context.KeyAndPredicate Maven / Gradle / Ivy

Go to download

Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.

There is a newer version: 9.0.2
Show newest version
package org.simpleflatmapper.map.context;

import org.simpleflatmapper.util.Predicate;

public class KeyAndPredicate implements Predicate {
    public final K key;
    public final Predicate predicate;

    public KeyAndPredicate(K key, Predicate predicate) {
        this.key = key;
        this.predicate = predicate;
    }

    @Override
    public boolean test(S s) {
        return predicate == null ? true : predicate.test(s);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        KeyAndPredicate that = (KeyAndPredicate) o;

        if (!key.equals(that.key)) return false;
        return predicate != null ? predicate.equals(that.predicate) : that.predicate == null;
    }

    @Override
    public int hashCode() {
        int result = key.hashCode();
        result = 31 * result + (predicate != null ? predicate.hashCode() : 0);
        return result;
    }

    public KeyAndPredicate mergeWith(KeyAndPredicate keyAndPredicate) {
        if (!this.key.equals(keyAndPredicate.key)) throw new IllegalArgumentException();
        
        if (this.predicate == null || keyAndPredicate.predicate == null) { // null is equivalent to true
            return this;
        }
        
        if (this.predicate.equals(keyAndPredicate.predicate)) {
            return this;
        }
        
        return new KeyAndPredicate(key, new OrPredicate(predicate, keyAndPredicate.predicate));
    }

    private static class OrPredicate implements Predicate {
        private final Predicate p1;
        private final Predicate p2;

        private OrPredicate(Predicate p1, Predicate p2) {
            this.p1 = p1;
            this.p2 = p2;
        }

        @Override
        public boolean test(S s) {
            return p1.test(s) || p2.test(s);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            OrPredicate that = (OrPredicate) o;

            if (p1 != null ? !p1.equals(that.p1) : that.p1 != null) return false;
            return p2 != null ? p2.equals(that.p2) : that.p2 == null;
        }

        @Override
        public int hashCode() {
            int result = p1 != null ? p1.hashCode() : 0;
            result = 31 * result + (p2 != null ? p2.hashCode() : 0);
            return result;
        }
    }
}