org.brocalc.domain.RangeConstraintMapUtil.java Source code

Java tutorial

Introduction

Here is the source code for org.brocalc.domain.RangeConstraintMapUtil.java

Source

/*******************************************************************************
 * Copyright (c) 2013 51zero Ltd.
 *
 * This file is part of the Brokerage Calculation Library (brocalc).
 *
 * brocalc is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * brocalc is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even he implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with brocalc.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package org.brocalc.domain;

import java.util.Map;

import com.google.common.collect.MapConstraint;
import com.google.common.collect.MapConstraints;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;

public class RangeConstraintMapUtil {

    public static class RangeOverlapException extends RuntimeException {
        public RangeOverlapException(String reason) {
            super(reason);
        }

        private static final long serialVersionUID = -7582000153162937271L;
    }

    public static <T extends Comparable<?>> Map<Range<T>, BrokerageScheduleComponent> createRangeConstrainedMap(
            final String rangeName) {
        final Map<Range<T>, BrokerageScheduleComponent> baseMap = Maps.newHashMap();
        Map<Range<T>, BrokerageScheduleComponent> constrainedMap = MapConstraints.constrainedMap(baseMap,
                new MapConstraint<Range<T>, BrokerageScheduleComponent>() {

                    @Override
                    public void checkKeyValue(Range<T> newKey,
                            BrokerageScheduleComponent brokerageScheduleComponent) {
                        baseMap.keySet();
                        for (Range<T> existingKey : baseMap.keySet()) {
                            if (existingKey.isConnected(newKey) && !existingKey.intersection(newKey).isEmpty()) {
                                throw new RangeOverlapException(
                                        rangeName + " " + newKey + " overlaps with " + existingKey);
                            }
                        }
                    }
                });
        return constrainedMap;
    }

}