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.collect.Range;
11 import java.util.Collection;
12 import javax.annotation.Nonnull;
13 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
16 * Abstract base for generators which require instantiation of boundary values
17 * to check. These are implemented by generating an array constant within the
18 * class, which contains {@link Range} instances, which hold pre-instantiated
21 * @param <T> type of the class
23 abstract class AbstractBigRangeGenerator<T extends Number & Comparable<T>> extends AbstractRangeGenerator<T> {
24 private static final String RANGE = Range.class.getName();
26 protected AbstractBigRangeGenerator(final Class<T> typeClass) {
30 private StringBuilder itemType() {
31 return new StringBuilder(RANGE).append('<').append(getTypeName()).append('>');
34 private StringBuilder arrayType() {
35 return new StringBuilder(itemType()).append("[]");
39 protected final String generateRangeCheckerImplementation(final String checkerName, @Nonnull final Collection<RangeConstraint> constraints) {
40 final String fieldName = checkerName.toUpperCase() + "_RANGES";
41 final StringBuilder sb = new StringBuilder();
43 // Field to hold the Range objects in an array
44 sb.append("private static final ").append(arrayType()).append(' ').append(fieldName).append(";\n");
46 // Static initializer block for the array
47 sb.append("static {\n");
48 sb.append(" @SuppressWarnings(\"unchecked\")\n");
49 sb.append(" final ").append(arrayType()).append(" a = (").append(arrayType())
50 .append(") java.lang.reflect.Array.newInstance(").append(RANGE).append(".class, ").append(constraints.size()).append(");\n");
53 for (RangeConstraint r : constraints) {
54 final String min = format(getValue(r.getMin()));
55 final String max = format(getValue(r.getMax()));
57 sb.append(" a[").append(i++).append("] = ").append(RANGE).append(".closed(").append(min).append(", ").append(max).append(");\n");
60 sb.append(" ").append(fieldName).append(" = a;\n");
63 // Static enforcement method
64 sb.append("private static void ").append(checkerName).append("(final ").append(getTypeName()).append(" value) {\n");
65 sb.append(" for (").append(itemType()).append(" r : ").append(fieldName).append(") {\n");
66 sb.append(" if (r.contains(value)) {\n");
67 sb.append(" return;\n");
70 sb.append(" throw new IllegalArgumentException(String.format(\"Invalid range: %s, expected: %s.\", value, java.util.Arrays.asList(").append(fieldName).append(")));\n");