2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl;
11 import com.google.common.collect.Iterables;
12 import com.google.common.collect.Ordering;
13 import com.google.common.collect.Range;
14 import org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl.util.EPTemplateUtil;
15 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ep.provider.model.rev160302.sxp.ep.mapper.EndpointPolicyTemplateBySgt;
16 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ep.provider.rev160722.SgtGeneratorConfig;
17 import org.opendaylight.yang.gen.v1.urn.opendaylight.sxp.database.rev160308.Sgt;
19 import java.util.Optional;
22 * Purpose: generate {@link Sgt} value on demand
24 public class SgtGeneratorImpl {
25 private final Ordering<Sgt> sgtOrdering;
26 private Optional<Range<Integer>> sgtRange = Optional.empty();
28 public SgtGeneratorImpl(final SgtGeneratorConfig sgtGenerator) {
29 if (sgtGenerator != null) {
30 sgtRange = Optional.of(
31 Range.closed(sgtGenerator.getSgtLow().getValue(), sgtGenerator.getSgtHigh().getValue()));
33 sgtOrdering = EPTemplateUtil.createSgtOrdering();
37 * @param templateCache source of used sgt items
38 * @return next free sgt
40 public java.util.Optional<Sgt> generateNextSgt(SimpleCachedDao<Sgt, EndpointPolicyTemplateBySgt> templateCache) {
41 return sgtRange.flatMap(range ->
42 findTopUsedSgt(templateCache.keySet())
43 .map(topUsedSgt -> incrementSafely(range, topUsedSgt))
47 private Optional<Sgt> findTopUsedSgt(final Iterable<Sgt> sgts) {
48 return java.util.Optional.ofNullable(sgts)
49 .filter(sgtBag -> !Iterables.isEmpty(sgtBag))
50 .map(sgtOrdering::max);
53 private Sgt incrementSafely(final Range<Integer> range, final Sgt topUsedSgt) {
54 final Sgt applicableSgt;
56 final int nextMax = topUsedSgt.getValue() + 1;
57 if (range.contains(nextMax)) {
58 applicableSgt = new Sgt(nextMax);
59 } else if (nextMax < range.lowerEndpoint()) {
60 applicableSgt = new Sgt(range.lowerEndpoint());