2 * Copyright (c) 2015 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
8 package org.opendaylight.yangtools.sal.java.api.generator;
10 import com.google.common.base.Preconditions;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
17 abstract class AbstractPrimitiveRangeGenerator<T extends Number & Comparable<T>> extends AbstractRangeGenerator<T> {
18 private static final Logger LOG = LoggerFactory.getLogger(AbstractPrimitiveRangeGenerator.class);
19 private final T minValue;
20 private final T maxValue;
22 protected AbstractPrimitiveRangeGenerator(final Class<T> typeClass, final T minValue, final T maxValue) {
24 this.minValue = Preconditions.checkNotNull(minValue);
25 this.maxValue = Preconditions.checkNotNull(maxValue);
28 private boolean needsMaximumEnforcement(final T maxToEnforce) {
29 return maxValue.compareTo(maxToEnforce) > 0;
32 private boolean needsMinimumEnforcement(final T minToEnforce) {
33 return minValue.compareTo(minToEnforce) < 0;
36 private final Collection<String> createConditionals(final Collection<RangeConstraint> restrictions) {
37 final Collection<String> ret = new ArrayList<>(restrictions.size());
39 for (RangeConstraint r : restrictions) {
40 final T min = getValue(r.getMin());
41 final boolean needMin = needsMinimumEnforcement(min);
43 final T max = getValue(r.getMax());
44 final boolean needMax = needsMaximumEnforcement(max);
46 if (!needMin && !needMax) {
47 LOG.debug("Type {} indicates [{}, {}] does not require enforcement", getTypeName(), min, max);
51 final StringBuilder sb = new StringBuilder();
53 sb.append("value >= ").append(format(min));
59 sb.append("value <= ").append(format(max));
62 ret.add(sb.toString());
69 protected final String generateRangeCheckerImplementation(final String checkerName, final Collection<RangeConstraint> restrictions) {
70 final StringBuilder sb = new StringBuilder();
71 final Collection<String> conditionals = createConditionals(restrictions);
73 sb.append("private static void ").append(checkerName).append("(final ").append(getTypeName()).append(" value) {\n");
75 if (!conditionals.isEmpty()) {
76 for (String c : conditionals) {
77 sb.append(" if (").append(c).append(") {\n");
78 sb.append(" return;\n");
82 sb.append(" throw new IllegalArgumentException(String.format(\"Invalid value %s does not match any required ranges\", value));\n");