Introduce formatting methods for SourceException 16/33016/2
authorRobert Varga <robert.varga@pantheon.sk>
Mon, 4 Jan 2016 23:46:14 +0000 (00:46 +0100)
committerGerrit Code Review <gerrit@opendaylight.org>
Wed, 20 Jan 2016 15:17:29 +0000 (15:17 +0000)
- throwIf() is similar to Preconditions.checkArgument(), but checks the
  inverse condition
- throwIfNull() is similar to Preconditions.checkNotNull()
- new constructors with string formatting
- fix {Invalid,Missing}SubstatementException not having a version

Change-Id: I95d15fb6a591f77b0be17d9ca50f51d3636c80ed
Signed-off-by: Robert Varga <robert.varga@pantheon.sk>
(cherry picked from commit c652590993b1e4660d5d557868665dbfa634ed27)

35 files changed:
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/YinStatementParserImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/spi/SubstatementValidator.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/spi/meta/InferenceException.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/spi/meta/InvalidSubstatementException.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/spi/meta/MissingSubstatementException.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/spi/source/SourceException.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/SourceSpecificContext.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/AugmentStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/AugmentUtils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/BaseStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/BelongsToStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/GroupingUtils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/ImportStatementDefinition.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/IncludeStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/ModuleStatementSupport.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/RevisionDateStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/RevisionStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/SubmoduleStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/TypeStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/TypeUtils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/TypedefStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/UsesStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/Utils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/AbstractEffectiveDocumentedDataNodeContainer.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/EffectiveStmtUtils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/ImportEffectiveStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/LeafEffectiveStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/LeafListEffectiveStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/ListEffectiveStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/type/BinaryTypeEffectiveStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/type/BitsSpecificationEffectiveStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/type/EnumSpecificationEffectiveStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/type/IntegerTypeEffectiveStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/type/StringTypeEffectiveStatementImpl.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/retest/YangParserNegativeTest.java

index 4ce9bce6499a333fbb6538e611dd97dcff9f342b..5128185a229fd704e0b54494d29617d3c7958a0e 100644 (file)
@@ -37,17 +37,17 @@ public class YinStatementParserImpl {
 
     private static final Logger LOG = LoggerFactory.getLogger(YinStatementParserImpl.class);
 
+    private final List<String> toBeSkipped = new ArrayList<>();
+    private final String sourceName;
     private StatementWriter writer;
     private QNameToStatementDefinition stmtDef;
     private PrefixToModule prefixes;
-    private final String sourceName;
     private String uriStr;
     private boolean isType = false;
     private boolean action = true;
     private boolean yinElement = false;
-    private List<String> toBeSkipped = new ArrayList<>();
 
-    public YinStatementParserImpl(String sourceName) {
+    public YinStatementParserImpl(final String sourceName) {
         this.sourceName = Preconditions.checkNotNull(sourceName);
     }
 
@@ -57,18 +57,16 @@ public class YinStatementParserImpl {
      * created.
      * When done, start walking through YIN source
      *
-     *
      * @param writer - instance of StatementWriter to emit declared statements
      * @param stmtDef - map of valid statement definitions for linkage phase
      *
      */
-    public void setAttributes(StatementWriter writer, QNameToStatementDefinition stmtDef) {
+    public void setAttributes(final StatementWriter writer, final QNameToStatementDefinition stmtDef) {
         this.writer = writer;
         this.stmtDef = stmtDef;
     }
 
     /**
-     *
      * This method is supposed to be called in any phase but linkage, when YinStatementParserImpl instance has already
      * been created.
      * When done, start walking through YIN source
@@ -78,20 +76,18 @@ public class YinStatementParserImpl {
      * @param prefixes - map of valid prefixes for any phase but linkage
      *
      */
-    public void setAttributes(StatementWriter writer, QNameToStatementDefinition stmtDef, PrefixToModule prefixes) {
+    public void setAttributes(final StatementWriter writer, final QNameToStatementDefinition stmtDef, final PrefixToModule prefixes) {
         this.writer = writer;
         this.stmtDef = stmtDef;
         this.prefixes = prefixes;
     }
 
     /**
-     *
      * This method executes parsing YIN source and emitting declared statements via attached StatementWriter
      *
      * @param inputReader - instance of XMlStreamReader, allows forward, read-only access to XML.
-     *
      */
-    public void walk(XMLStreamReader inputReader) {
+    public void walk(final XMLStreamReader inputReader) {
         try {
             while (inputReader.hasNext()) {
                 inputReader.next();
@@ -110,11 +106,11 @@ public class YinStatementParserImpl {
         }
     }
 
-    private void startStatement(QName identifier, StatementSourceReference ref) {
+    private void startStatement(final QName identifier, final StatementSourceReference ref) {
         writer.startStatement(identifier, ref);
     }
 
-    private void argumentValue(XMLStreamReader inputReader, StatementSourceReference ref, QName identifier, boolean
+    private void argumentValue(final XMLStreamReader inputReader, final StatementSourceReference ref, final QName identifier, final boolean
             yinElement) {
         if (yinElement) {
             writeTextOnlyElement(inputReader, ref);
@@ -123,11 +119,11 @@ public class YinStatementParserImpl {
         }
     }
 
-    private void endStatement(StatementSourceReference ref) {
+    private void endStatement(final StatementSourceReference ref) {
         writer.endStatement(ref);
     }
 
-    private void enterStatement(XMLStreamReader inputReader) throws URISyntaxException {
+    private void enterStatement(final XMLStreamReader inputReader) throws URISyntaxException {
         final StatementSourceReference ref = DeclarationInTextSource.atPosition(sourceName, inputReader
                 .getLocation().getLineNumber(), inputReader.getLocation().getColumnNumber());
         uriStr = inputReader.getNamespaceURI();
@@ -155,14 +151,12 @@ public class YinStatementParserImpl {
                 }
             } else {
                 //if statement not found through all phases, throw exception
-                if (writer.getPhase().equals(ModelProcessingPhase.FULL_DECLARATION)) {
-                    throw new SourceException(String.format("%s is not a YIN statement or use of extension.",
-                            identifier.getLocalName()), ref);
-                } else {
-                    //otherwise skip it (statement not to be read yet)
-                    action = false;
-                    toBeSkipped.add(getElementFullName(inputReader));
-                }
+                SourceException.throwIf(writer.getPhase().equals(ModelProcessingPhase.FULL_DECLARATION), ref,
+                    "%s is not a YIN statement or use of extension.", identifier.getLocalName());
+
+                //otherwise skip it (statement not to be read yet)
+                action = false;
+                toBeSkipped.add(getElementFullName(inputReader));
             }
 
             if (isType) {
@@ -175,7 +169,7 @@ public class YinStatementParserImpl {
         }
     }
 
-    private void exitStatement(XMLStreamReader inputReader) throws URISyntaxException {
+    private void exitStatement(final XMLStreamReader inputReader) throws URISyntaxException {
         final String statementName = getElementFullName(inputReader);
         final QName identifier = new QName(new URI(inputReader.getNamespaceURI()), statementName);
         final StatementSourceReference ref = DeclarationInTextSource.atPosition(sourceName, inputReader
@@ -196,7 +190,7 @@ public class YinStatementParserImpl {
         }
     }
 
-    private void writeTextOnlyElement(XMLStreamReader inputReader, StatementSourceReference ref) {
+    private void writeTextOnlyElement(final XMLStreamReader inputReader, final StatementSourceReference ref) {
         try {
             writer.argumentValue(inputReader.getElementText(), ref);
         } catch (XMLStreamException e) {
@@ -204,14 +198,15 @@ public class YinStatementParserImpl {
         }
     }
 
-    private void writeNormalizedAttributeValue(XMLStreamReader inputReader, QName
-            identifier, StatementSourceReference ref) {
+    private void writeNormalizedAttributeValue(final XMLStreamReader inputReader, final QName
+            identifier, final StatementSourceReference ref) {
         final String attributeValue = getAttributeValue(inputReader, identifier, stmtDef);
-        if (attributeValue != null)
+        if (attributeValue != null) {
             writer.argumentValue(attributeValue, ref);
+        }
     }
 
-    private void writeTypeStmtAndArg(XMLStreamReader inputReader, QName identifier, StatementSourceReference ref) {
+    private void writeTypeStmtAndArg(final XMLStreamReader inputReader, final QName identifier, final StatementSourceReference ref) {
         String argument = getAttributeValue(inputReader, identifier, stmtDef);
         if (TypeUtils.isYangTypeBodyStmtString(argument)) {
             startStatement(new QName(YangConstants.RFC6020_YIN_NAMESPACE, argument), ref);
@@ -223,7 +218,7 @@ public class YinStatementParserImpl {
         isType = false;
     }
 
-    private static String getElementFullName(XMLStreamReader inputReader) {
+    private static String getElementFullName(final XMLStreamReader inputReader) {
         if (!inputReader.getPrefix().isEmpty()) {
             return inputReader.getPrefix() + ":" + inputReader.getLocalName();
         } else {
@@ -231,29 +226,28 @@ public class YinStatementParserImpl {
         }
     }
 
-    private static boolean isStatementWithArgument(QName identifier, QNameToStatementDefinition stmtDef) {
+    private static boolean isStatementWithArgument(final QName identifier, final QNameToStatementDefinition stmtDef) {
         if (stmtDef != null && stmtDef.get(Utils.trimPrefix(identifier)) == null) {
             return false;
-        } else if (((StatementSupport) stmtDef.get(Utils.trimPrefix(identifier)))
-                .getPublicView().getArgumentName() == null) {
+        } else if (((StatementSupport<?, ?, ?>) stmtDef.get(Utils.trimPrefix(identifier))).getPublicView().getArgumentName() == null) {
             return false;
         }
         return true;
     }
 
-    private static boolean isStatementWithYinElement(QName identifier, QNameToStatementDefinition stmtDef) {
+    private static boolean isStatementWithYinElement(final QName identifier, final QNameToStatementDefinition stmtDef) {
         final StatementDefinition statementDefinition = stmtDef.get(Utils.trimPrefix(identifier));
-        if (statementDefinition != null) {
-            return ((Rfc6020Mapping) ((StatementSupport) statementDefinition).getPublicView()).isArgumentYinElement();
-        } else {
+        if (statementDefinition == null) {
             return false;
         }
+
+        return ((Rfc6020Mapping) ((StatementSupport<?, ?, ?>) statementDefinition).getPublicView()).isArgumentYinElement();
     }
 
-    private static String getAttributeValue(XMLStreamReader inputReader, QName identifier, QNameToStatementDefinition
+    private static String getAttributeValue(final XMLStreamReader inputReader, final QName identifier, final QNameToStatementDefinition
             stmtDef) {
         String namespace = null;
-        return inputReader.getAttributeValue(namespace, (((StatementSupport) stmtDef.get(Utils.trimPrefix(identifier)))
+        return inputReader.getAttributeValue(namespace, (((StatementSupport<?, ?, ?>) stmtDef.get(Utils.trimPrefix(identifier)))
                 .getPublicView()).getArgumentName().getLocalName());
     }
 }
\ No newline at end of file
index 362fd04547b535ee2533c3ebc7fc51ea169e73c5..761b60c1f2ff2477bf3642f242e47dce9e229f6c 100644 (file)
@@ -8,34 +8,34 @@
 
 package org.opendaylight.yangtools.yang.parser.spi;
 
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
 import com.google.common.collect.MapDifference;
 import com.google.common.collect.Maps;
-import java.util.ArrayList;
-import java.util.Collection;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Map.Entry;
 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
 import org.opendaylight.yangtools.yang.parser.spi.meta.InvalidSubstatementException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.MissingSubstatementException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
-import org.opendaylight.yangtools.yang.parser.util.YangParseException;
 
 public final class SubstatementValidator {
+    public final static int MAX = Integer.MAX_VALUE;
     private final Map<StatementDefinition, Cardinality> cardinalityMap;
     private final StatementDefinition currentStatement;
     private final SpecialCase specialCase;
-    public final static int MAX = Integer.MAX_VALUE;
 
-    private SubstatementValidator(Builder builder, SpecialCase specialCase) {
+    private SubstatementValidator(final Builder builder, final SpecialCase specialCase) {
         this.cardinalityMap = builder.cardinalityMap.build();
         this.currentStatement = builder.currentStatement;
         this.specialCase = specialCase;
     }
 
-    public static Builder builder(StatementDefinition currentStatement) {
+    public static Builder builder(final StatementDefinition currentStatement) {
         return new Builder(currentStatement);
     }
 
@@ -43,11 +43,11 @@ public final class SubstatementValidator {
         private final ImmutableMap.Builder<StatementDefinition, Cardinality> cardinalityMap = ImmutableMap.builder();
         private final StatementDefinition currentStatement;
 
-        private Builder(StatementDefinition currentStatement) {
+        private Builder(final StatementDefinition currentStatement) {
             this.currentStatement = currentStatement;
         }
 
-        public Builder add(StatementDefinition d, int min, int max) {
+        public Builder add(final StatementDefinition d, final int min, final int max) {
             this.cardinalityMap.put(d, new Cardinality(min, max));
             return this;
         }
@@ -56,19 +56,17 @@ public final class SubstatementValidator {
             return new SubstatementValidator(this, SpecialCase.NULL);
         }
 
-        public SubstatementValidator build(SpecialCase specialCase) {
+        public SubstatementValidator build(final SpecialCase specialCase) {
             return new SubstatementValidator(this, specialCase);
         }
     }
 
     public void validate(final StmtContext<?, ?, ?> ctx) throws InvalidSubstatementException,
             MissingSubstatementException {
-        final Map<StatementDefinition, Integer> stmtDefMap = new HashMap<>();
-        final Map<StatementDefinition, Integer> validatedMap = new HashMap<>();
-        final Collection<StatementContextBase<?, ?, ?>> substatementsInit = new ArrayList<>();
-        substatementsInit.addAll(ctx.declaredSubstatements());
-        substatementsInit.addAll(ctx.effectiveSubstatements());
+        final Iterable<StatementContextBase<?, ?, ?>> substatementsInit = Iterables.concat(
+            ctx.declaredSubstatements(), ctx.effectiveSubstatements());
 
+        final Map<StatementDefinition, Integer> stmtDefMap = new HashMap<>();
         for (StatementContextBase<?, ?, ?> stmtCtx : substatementsInit) {
             final StatementDefinition definition = stmtCtx.getPublicDefinition();
             if (!stmtDefMap.containsKey(definition)) {
@@ -79,49 +77,47 @@ public final class SubstatementValidator {
         }
 
         if (stmtDefMap.isEmpty() && specialCase == SpecialCase.NOTNULL) {
-            throw new InvalidSubstatementException(String.format("%s must contain atleast 1 element. Error in module "
-                    + "%s (%s)", currentStatement, ctx.getRoot().getStatementArgument(),
-                    ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
-                    ctx.getStatementSourceReference());
+            throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
+                "%s must contain atleast 1 element. Error in module %s (%s)", currentStatement,
+                ctx.getRoot().getStatementArgument(),
+                ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
         }
 
-        for (Map.Entry entry : stmtDefMap.entrySet()) {
+        final Map<StatementDefinition, Integer> validatedMap = new HashMap<>();
+        for (Entry<?, ?> entry : stmtDefMap.entrySet()) {
             final StatementDefinition key = (StatementDefinition) entry.getKey();
             if (!cardinalityMap.containsKey(key)) {
                 if (ctx.getFromNamespace(ExtensionNamespace.class, key.getStatementName()) != null) {
                     continue;
                 }
-                throw new InvalidSubstatementException(String.format("%s is not valid for %s. Error in module %s (%s)",
-                        key, currentStatement, ctx.getRoot().getStatementArgument(),
-                        ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
-                        ctx.getStatementSourceReference());
+                throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
+                    "%s is not valid for %s. Error in module %s (%s)", key, currentStatement,
+                    ctx.getRoot().getStatementArgument(),
+                    ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
             }
             if (cardinalityMap.get(key).getMin() > (Integer) entry.getValue()) {
-                throw new InvalidSubstatementException(String.format("Minimal count of %s for %s is %s, detected %s. "
-                        + "Error in module %s (%s)", key, currentStatement, cardinalityMap.get(key).getMin(),
-                        entry.getValue(), ctx.getRoot().getStatementArgument(),
-                        ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
-                        ctx.getStatementSourceReference());
+                throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
+                    "Minimal count of %s for %s is %s, detected %s. Error in module %s (%s)", key, currentStatement,
+                    cardinalityMap.get(key).getMin(), entry.getValue(), ctx.getRoot().getStatementArgument(),
+                    ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
             }
             if (cardinalityMap.get(key).getMax() < (Integer) entry.getValue()) {
-                throw new InvalidSubstatementException(String.format("Maximal count of %s for %s is %s, detected %s. "
-                        + "Error in module %s (%s)", key, currentStatement, cardinalityMap.get(key).getMax(),
-                        entry.getValue(), ctx.getRoot().getStatementArgument(),
-                        ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
-                        ctx.getStatementSourceReference());
+                throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
+                    "Maximal count of %s for %s is %s, detected %s. Error in module %s (%s)", key, currentStatement,
+                    cardinalityMap.get(key).getMax(), entry.getValue(), ctx.getRoot().getStatementArgument(),
+                    ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
             }
             validatedMap.put(key, 1);
         }
 
         final MapDifference<StatementDefinition, Object> diff = Maps.difference(validatedMap, cardinalityMap);
-
-        for (Map.Entry entry : diff.entriesOnlyOnRight().entrySet()) {
+        for (Entry<?, ?> entry : diff.entriesOnlyOnRight().entrySet()) {
             final int min = ((Cardinality) entry.getValue()).getMin();
             if (min > 0) {
-                throw new MissingSubstatementException(String.format("%s is missing %s. Minimal count is %s. Error in"
-                        + "  module %s (%s)", currentStatement, entry.getKey(), min, ctx.getRoot()
-                        .getStatementArgument(), ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
-                        ctx.getStatementSourceReference());
+                throw new MissingSubstatementException(ctx.getStatementSourceReference(),
+                    "%s is missing %s. Minimal count is %s. Error in module %s (%s)", currentStatement, entry.getKey(),
+                    min, ctx.getRoot().getStatementArgument(),
+                    ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
             }
         }
     }
@@ -130,13 +126,9 @@ public final class SubstatementValidator {
         private final int min;
         private final int max;
 
-        private Cardinality(int min, int max) throws YangParseException {
-            if (min > max) {
-                throw new IllegalArgumentException("Min can not be greater than max!");
-            }
-            if (min < 0) {
-                throw new IllegalArgumentException("Min can not be les than 0!");
-            }
+        private Cardinality(final int min, final int max) {
+            Preconditions.checkArgument(min >= 0, "Min %s cannot be less than 0!");
+            Preconditions.checkArgument(min <= max, "Min %s can not be greater than max %s!", min, max);
             this.min = min;
             this.max = max;
         }
index 8e5cce13cea4b74bae56deb7af1ad534e7ac1b5d..c1cb981ed75c4f0b866f021478da1ca38eaccd9d 100644 (file)
@@ -12,21 +12,39 @@ import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
 
 /**
- *
  * Thrown when there was inference error
- *
  */
 public class InferenceException extends SourceException {
-
-
     private static final long serialVersionUID = 1L;
 
-    public InferenceException(@Nonnull String message, @Nonnull StatementSourceReference source, Throwable cause) {
+    public InferenceException(@Nonnull final String message, @Nonnull final StatementSourceReference source,
+            final Throwable cause) {
         super(message, source, cause);
     }
 
-    public InferenceException(@Nonnull String message, @Nonnull StatementSourceReference source) {
+    public InferenceException(@Nonnull final String message, @Nonnull final StatementSourceReference source) {
         super(message, source);
     }
 
+    public InferenceException(@Nonnull final StatementSourceReference source, @Nonnull final String format,
+            final Object... args) {
+        this(String.format(format, args), source);
+    }
+
+    /**
+     * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
+     * this method does nothing.
+     *
+     * @param expression Expression to be evaluated
+     * @param source Statement source reference
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     * @throws InferenceException if the expression evaluates to true.
+     */
+    public static void throwIf(final boolean expression, @Nonnull final StatementSourceReference source,
+            @Nonnull final String format, final Object... args) {
+        if (expression) {
+            throw new InferenceException(source, format, args);
+        }
+    }
 }
index c8678eca20e7e23489b846f8109225fff0bd2416..3412ee7175233ee63f2695b5d0ba1869702122ef 100644 (file)
@@ -17,11 +17,17 @@ import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReferenc
 public class InvalidSubstatementException extends SourceException {
     private static final long serialVersionUID = 1L;
 
-    public InvalidSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source, final Throwable cause) {
+    public InvalidSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source,
+            final Throwable cause) {
         super(message, source, cause);
     }
 
     public InvalidSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source) {
         super(message, source);
     }
+
+    public InvalidSubstatementException(@Nonnull final StatementSourceReference source, @Nonnull final String format,
+            final Object... args) {
+        this(String.format(format, args), source);
+    }
 }
index 44978aa56cf0dc2cd1be2c92dee9b5aeefe323ff..d2570dbed771952e82ec106cdf2e2196631eff87 100644 (file)
@@ -21,7 +21,13 @@ public class MissingSubstatementException extends SourceException {
         super(message, source);
     }
 
-    public MissingSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source, final Throwable cause) {
+    public MissingSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source,
+            final Throwable cause) {
         super(message, source, cause);
     }
+
+    public MissingSubstatementException(@Nonnull final StatementSourceReference source, @Nonnull final String format,
+            final Object... args) {
+        this(String.format(format, args), source);
+    }
 }
index cddfe2df13be8543b121a2a927e5e6aca6636718..a31e549d63c85c894ef297d9ff4e4add7943f982 100644 (file)
@@ -11,35 +11,113 @@ import com.google.common.base.Preconditions;
 import javax.annotation.Nonnull;
 
 /**
- *
  * Thrown to indicate error in YANG model source.
- *
  */
 public class SourceException extends RuntimeException {
-
     private static final long serialVersionUID = 1L;
 
     private final StatementSourceReference sourceRef;
 
-    public SourceException(@Nonnull String message,@Nonnull StatementSourceReference source) {
+    /**
+     * Create a new instance with the specified message and source. The message will be appended with
+     * the source reference.
+     *
+     * @param message Context message
+     * @param source Statement source
+     */
+    public SourceException(@Nonnull final String message, @Nonnull final StatementSourceReference source) {
         super(createMessage(message, source));
         sourceRef = source;
     }
 
-    public SourceException(@Nonnull String message,@Nonnull StatementSourceReference source, Throwable cause) {
+    /**
+     * Create a new instance with the specified message and source. The message will be appended with
+     * the source reference.
+     *
+     * @param message Context message
+     * @param source Statement source
+     * @param cause Underlying cause of this exception
+     */
+    public SourceException(@Nonnull final String message, @Nonnull final StatementSourceReference source,
+            final Throwable cause) {
         super(createMessage(message, source), cause);
         sourceRef = source;
     }
 
+    /**
+     * Create a new instance with the specified source and a formatted message. The message will be appended with
+     * the source reference.
+     *
+     * @param source Statement source
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     */
+    public SourceException(@Nonnull final StatementSourceReference source, @Nonnull final String format,
+            final Object... args) {
+        this(String.format(format, args), source);
+    }
+
+    /**
+     * Create a new instance with the specified source and a formatted message. The message will be appended with
+     * the source reference.
+     *
+     * @param source Statement source
+     * @param cause Underlying cause of this exception
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     */
+    public SourceException(@Nonnull final StatementSourceReference source, final Throwable cause,
+            @Nonnull final String format, final Object... args) {
+        this(String.format(format, args), source, cause);
+    }
+
+    /**
+     * Return the reference to the source which caused this exception.
+     *
+     * @return Source reference
+     */
     public @Nonnull StatementSourceReference getSourceReference() {
         return sourceRef;
     }
 
+    /**
+     * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
+     * this method does nothing.
+     *
+     * @param expression Expression to be evaluated
+     * @param source Statement source reference
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     * @throws SourceException if the expression evaluates to true.
+     */
+    public static void throwIf(final boolean expression, @Nonnull final StatementSourceReference source,
+            @Nonnull final String format, final Object... args) {
+        if (expression) {
+            throw new SourceException(source, format, args);
+        }
+    }
+
+    /**
+     * Throw an instance of this exception if an object is null. If the object is non-null, it will
+     * be returned as the result of this method.
+     *
+     * @param obj Object reference to be checked
+     * @param source Statement source reference
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     * @return Object if it is not null
+     * @throws SourceException if object is null
+     */
+    @Nonnull public static <T> T throwIfNull(final T obj, @Nonnull final StatementSourceReference source,
+            @Nonnull final String format, final Object... args) {
+        throwIf(obj == null, source, format, args);
+        return obj;
+    }
+
     private static String createMessage(@Nonnull final String message, @Nonnull final StatementSourceReference source) {
         Preconditions.checkNotNull(message);
         Preconditions.checkNotNull(source);
 
-        return String.format("%s\nStatement source at %s", message, source);
+        return message + " [at " + source + ']';
     }
-
 }
index fb23468d8d3aa2a44b9735b1230ce4ee7b1e28b7..792864eb0fea341b06d61ebd3d7c13dceb689b41 100644 (file)
@@ -101,29 +101,27 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         if (def == null) {
             // unknown-stmts (from import, include or local-scope)
             if (qNameToStmtDefMap.get(name) != null) {
-                    final StatementContextBase<?, ?, ?> extension =
-                            (StatementContextBase<?, ?, ?>) currentContext.getAllFromNamespace(ExtensionNamespace.class).get(name);
-                if (extension != null) {
-                    final QName arg = (QName) extension.getStatementArgument();
-                    final QName qName = current.getFromNamespace(QNameCacheNamespace.class,
-                            QName.create(arg, extension.getIdentifier().getArgument()));
-
-                    def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
-                            getNewStatementDefinition(qName)));
-                } else {
-                        throw new SourceException("Extension not found: " + name,
-                                current.getStatementSourceReference());
-                }
+                final StatementContextBase<?, ?, ?> extension =
+                        (StatementContextBase<?, ?, ?>) currentContext.getAllFromNamespace(ExtensionNamespace.class).get(name);
+
+                SourceException.throwIfNull(extension, current.getStatementSourceReference(), "Extension %s not found",
+                    name);
+
+                final QName arg = (QName) extension.getStatementArgument();
+                final QName qName = current.getFromNamespace(QNameCacheNamespace.class,
+                    QName.create(arg, extension.getIdentifier().getArgument()));
+
+                def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
+                    getNewStatementDefinition(qName)));
             } else {
                 // type-body-stmts
                 def = resolveTypeBodyStmts(name.getLocalName());
             }
-        }
-        else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
+        } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
             QName qName = Utils.qNameFromArgument(current, name.getLocalName());
 
-            def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition
-                    (getNewStatementDefinition(qName)));
+            def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
+                getNewStatementDefinition(qName)));
         }
 
         Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
@@ -144,7 +142,7 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         return new ContextBuilder(def, ref) {
 
             @Override
-            public StatementContextBase build() throws SourceException {
+            public StatementContextBase build() {
                 if (root == null) {
                     root = new RootStatementContext(this, SourceSpecificContext.this);
                 } else {
@@ -259,9 +257,9 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
 
 
     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
-
-        Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
         boolean hasProgressed = false;
+
+        final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
         while (modifier.hasNext()) {
             if (modifier.next().tryApply()) {
                 modifier.remove();
@@ -352,12 +350,13 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
                 .class);
         final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
                 (BelongsToPrefixToModuleIdentifier.class);
-        if (belongsToPrefixes != null)
+        if (belongsToPrefixes != null) {
             allPrefixes.putAll(belongsToPrefixes);
+        }
 
         for (Entry<String, ModuleIdentifier> stringModuleIdentifierEntry : allPrefixes.entrySet()) {
             final QNameModule namespace = getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class,
-                    stringModuleIdentifierEntry.getValue());
+                stringModuleIdentifierEntry.getValue());
             prefixToModuleMap.put(stringModuleIdentifierEntry.getKey(), namespace);
         }
         return prefixToModuleMap;
@@ -367,22 +366,20 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         // regular YANG statements added
         ImmutableMap<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(
                 inProgressPhase).getDefinitions();
-        for (Map.Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
+        for (Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
             qNameToStmtDefMap.put(entry.getKey(), entry.getValue());
         }
 
         // extensions added
         if (inProgressPhase.equals(ModelProcessingPhase.FULL_DECLARATION)) {
-            Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions = currentContext
-                    .getAllFromNamespace(ExtensionNamespace.class);
+            Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions =
+                    currentContext.getAllFromNamespace(ExtensionNamespace.class);
             if (extensions != null) {
-                for (Map.Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension : extensions
-                        .entrySet()) {
-                    qNameToStmtDefMap
-                              .put((extension.getKey()),
-                                    (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension
-                                            .getValue()).definition()
-                                            .getFactory());
+                for (Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension :
+                    extensions.entrySet()) {
+                    qNameToStmtDefMap.put((extension.getKey()),
+                        (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension.getValue()).definition()
+                        .getFactory());
                 }
             }
         }
index 731f21791fb475218ac65f99f1665f396d0793e3..6a2d471f1ccad4f49e7d93c9a938b0065097b23f 100644 (file)
@@ -97,56 +97,52 @@ public class AugmentStatementImpl extends AbstractDeclaredStatement<SchemaNodeId
                 return;
             }
 
-            final ModelActionBuilder augmentAction = augmentNode
-                    .newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
-            final ModelActionBuilder.Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>>> sourceCtxPrereq = augmentAction
-                    .requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
-            final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target = augmentAction.mutatesEffectiveCtx(getSearchRoot(augmentNode), SchemaNodeIdentifierBuildNamespace.class, augmentNode.getStatementArgument());
+            final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(
+                ModelProcessingPhase.EFFECTIVE_MODEL);
+            final ModelActionBuilder.Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>>> sourceCtxPrereq =
+                    augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
+            final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target =
+                    augmentAction.mutatesEffectiveCtx(getSearchRoot(augmentNode), SchemaNodeIdentifierBuildNamespace.class, augmentNode.getStatementArgument());
             augmentAction.apply(new ModelActionBuilder.InferenceAction() {
 
                 @Override
-                public void apply() throws InferenceException {
+                public void apply() {
                     final StatementContextBase<?, ?, ?> augmentTargetCtx = (StatementContextBase<?, ?, ?>) target.get();
-
                     if (!AugmentUtils.isSupportedAugmentTarget(augmentTargetCtx) || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
                         augmentNode.setIsSupportedToBuildEffective(false);
                         return;
                     }
+
+                    // FIXME: this is a workaround for models which augment a node which is added via an extension
+                    //        which we do not handle. This needs to be reworked in terms of unknown schema nodes.
                     final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
                     try {
-                        AugmentUtils.copyFromSourceToTarget(augmentSourceCtx,
-                                augmentTargetCtx);
-                        augmentTargetCtx
-                                .addEffectiveSubstatement(augmentSourceCtx);
+                        AugmentUtils.copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
+                        augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
                         updateAugmentOrder(augmentSourceCtx);
                     } catch (SourceException e) {
-                        LOG.warn(e.getMessage(), e);
+                        LOG.warn("Failed to add augmentation %s defined at {}",
+                            augmentSourceCtx.getStatementSourceReference(), e);
                     }
-
                 }
 
-                private void updateAugmentOrder(
-                        final StatementContextBase<?, ?, ?> augmentSourceCtx) {
-                    Integer currentOrder = augmentSourceCtx
-                            .getFromNamespace(StmtOrderingNamespace.class,
-                                    Rfc6020Mapping.AUGMENT);
+                private void updateAugmentOrder(final StatementContextBase<?, ?, ?> augmentSourceCtx) {
+                    Integer currentOrder = augmentSourceCtx.getFromNamespace(StmtOrderingNamespace.class,
+                        Rfc6020Mapping.AUGMENT);
                     if (currentOrder == null) {
                         currentOrder = 1;
                     } else {
                         currentOrder++;
                     }
+
                     augmentSourceCtx.setOrder(currentOrder);
-                    augmentSourceCtx.addToNs(StmtOrderingNamespace.class,
-                            Rfc6020Mapping.AUGMENT, currentOrder);
+                    augmentSourceCtx.addToNs(StmtOrderingNamespace.class, Rfc6020Mapping.AUGMENT, currentOrder);
                 }
 
                 @Override
-                public void prerequisiteFailed(
-                        final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed)
-                        throws InferenceException {
-                    throw new InferenceException("Augment target not found: "
-                            + augmentNode.getStatementArgument(), augmentNode
-                            .getStatementSourceReference());
+                public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) {
+                    throw new InferenceException(augmentNode.getStatementSourceReference(),
+                        "Augment target '%s' not found", augmentNode.getStatementArgument());
                 }
             });
         }
@@ -154,7 +150,7 @@ public class AugmentStatementImpl extends AbstractDeclaredStatement<SchemaNodeId
         private static Mutable<?, ?, ?> getSearchRoot(final Mutable<?, ?, ?> augmentContext) {
             Mutable<?, ?, ?> parent = augmentContext.getParentContext();
             // Augment is in uses - we need to augment instantiated nodes in parent.
-            if(Rfc6020Mapping.USES.equals(parent.getPublicDefinition())) {
+            if (Rfc6020Mapping.USES.equals(parent.getPublicDefinition())) {
                 return parent.getParentContext();
             }
             return parent;
index c873ddbfbc6d6bace69312c57c7a08b571a86428..c835eb24febd2d5f787dbd73294de9bcb6732515 100644 (file)
@@ -96,13 +96,11 @@ public final class AugmentUtils {
                     .addAll(sourceCtx.declaredSubstatements()).addAll(sourceCtx.effectiveSubstatements()).build();
 
             for (final StatementContextBase<?, ?, ?> sourceSubStatement : sourceSubStatements) {
-                if (sourceSubStatement.getPublicDefinition().getDeclaredRepresentationClass()
-                        .equals(MandatoryStatement.class)) {
-                    throw new InferenceException(
-                            String.format(
-                                    "An augment cannot add node '%s' because it is mandatory and in module different from target",
-                                    sourceCtx.rawStatementArgument()), sourceCtx.getStatementSourceReference());
-                }
+                InferenceException.throwIf(MandatoryStatement.class.equals(
+                    sourceSubStatement.getPublicDefinition().getDeclaredRepresentationClass()),
+                    sourceCtx.getStatementSourceReference(),
+                    "An augment cannot add node '%s' because it is mandatory and in module different from target",
+                    sourceCtx.rawStatementArgument());
             }
         }
 
@@ -115,11 +113,9 @@ public final class AugmentUtils {
             boolean qNamesEqual = sourceIsDataNode && targetIsDataNode
                     && Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
 
-            if (qNamesEqual) {
-                throw new InferenceException(String.format(
-                        "An augment cannot add node named '%s' because this name is already used in target",
-                        sourceCtx.rawStatementArgument()), sourceCtx.getStatementSourceReference());
-            }
+            InferenceException.throwIf(qNamesEqual, sourceCtx.getStatementSourceReference(),
+                "An augment cannot add node named '%s' because this name is already used in target",
+                sourceCtx.rawStatementArgument());
         }
     }
 
index a14a557c244d3b009c1b2445b261f8d0a92cd76a..9fdf95ae95c8a27d336a06bf2afafa5cb9557744 100644 (file)
@@ -28,13 +28,11 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.BaseEffectiveStatementImpl;
 
 public class BaseStatementImpl extends AbstractDeclaredStatement<QName> implements BaseStatement {
-    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
-            .BASE)
-            .build();
+    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+            SubstatementValidator.builder(Rfc6020Mapping.BASE).build();
 
     protected BaseStatementImpl(final StmtContext<QName, BaseStatement, ?> context) {
         super(context);
@@ -70,14 +68,16 @@ public class BaseStatementImpl extends AbstractDeclaredStatement<QName> implemen
             if (StmtContextUtils.producesDeclared(baseParentCtx, IdentityStatement.class)) {
 
                 final QName baseIdentityQName = baseStmtCtx.getStatementArgument();
-                ModelActionBuilder baseIdentityAction = baseStmtCtx.newInferenceAction(ModelProcessingPhase.STATEMENT_DEFINITION);
-                final Prerequisite<StmtContext<?, ?, ?>> requiresPrereq = baseIdentityAction.requiresCtx(baseStmtCtx, IdentityNamespace.class, baseIdentityQName, ModelProcessingPhase.STATEMENT_DEFINITION);
-                final Prerequisite<StmtContext.Mutable<?, ?, ?>> mutatesPrereq = baseIdentityAction.mutatesCtx
-                        (baseParentCtx, ModelProcessingPhase.STATEMENT_DEFINITION);
+                final ModelActionBuilder baseIdentityAction = baseStmtCtx.newInferenceAction(
+                    ModelProcessingPhase.STATEMENT_DEFINITION);
+                final Prerequisite<StmtContext<?, ?, ?>> requiresPrereq = baseIdentityAction.requiresCtx(baseStmtCtx,
+                    IdentityNamespace.class, baseIdentityQName, ModelProcessingPhase.STATEMENT_DEFINITION);
+                final Prerequisite<StmtContext.Mutable<?, ?, ?>> mutatesPrereq = baseIdentityAction.mutatesCtx(
+                    baseParentCtx, ModelProcessingPhase.STATEMENT_DEFINITION);
 
                 baseIdentityAction.apply(new InferenceAction() {
                     @Override
-                    public void apply() throws InferenceException {
+                    public void apply() {
                         List<StmtContext<?, ?, ?>> derivedIdentities =
                                 baseStmtCtx.getFromNamespace(DerivedIdentitiesNamespace.class, baseStmtCtx.getStatementArgument());
                         if (derivedIdentities == null) {
@@ -89,17 +89,17 @@ public class BaseStatementImpl extends AbstractDeclaredStatement<QName> implemen
 
                     @Override
                     public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
-                        throw new InferenceException(
-                            "Unable to resolve identity " + baseParentCtx.getStatementArgument() + " and base identity "
-                        + baseStmtCtx.getStatementArgument(), baseStmtCtx.getStatementSourceReference());
+                        throw new InferenceException(baseStmtCtx.getStatementSourceReference(),
+                            "Unable to resolve identity %s and base identity %s",
+                            baseParentCtx.getStatementArgument(), baseStmtCtx.getStatementArgument());
                     }
                 });
             }
         }
 
         @Override
-        public void onFullDefinitionDeclared(Mutable<QName, BaseStatement,
-                EffectiveStatement<QName, BaseStatement>> stmt) throws SourceException {
+        public void onFullDefinitionDeclared(
+                final Mutable<QName, BaseStatement, EffectiveStatement<QName, BaseStatement>> stmt) {
             super.onFullDefinitionDeclared(stmt);
             SUBSTATEMENT_VALIDATOR.validate(stmt);
         }
index dd8c76b3a00ab59b7c3f569c583097f83b8cb622..0b5cb9a0952d9fccb43109d75edf5c2a6707a8f0 100644 (file)
@@ -29,18 +29,14 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNamespaceForBelongsTo;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.BelongsEffectiveToStatementImpl;
 
 public class BelongsToStatementImpl extends AbstractDeclaredStatement<String>
         implements BelongsToStatement {
-    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
-            .BELONGS_TO)
-            .add(Rfc6020Mapping.PREFIX, 1, 1)
-            .build();
+    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+            SubstatementValidator.builder(Rfc6020Mapping.BELONGS_TO).add(Rfc6020Mapping.PREFIX, 1, 1).build();
 
-    protected BelongsToStatementImpl(
-            final StmtContext<String, BelongsToStatement, ?> context) {
+    protected BelongsToStatementImpl(final StmtContext<String, BelongsToStatement, ?> context) {
         super(context);
     }
 
@@ -70,43 +66,46 @@ public class BelongsToStatementImpl extends AbstractDeclaredStatement<String>
         }
 
         @Override
-        public void onLinkageDeclared(final StmtContext.Mutable<String, BelongsToStatement, EffectiveStatement<String, BelongsToStatement>> belongsToCtx) throws SourceException {
+        public void onLinkageDeclared(
+                final StmtContext.Mutable<String, BelongsToStatement, EffectiveStatement<String, BelongsToStatement>> belongsToCtx) {
             ModelActionBuilder belongsToAction = belongsToCtx.newInferenceAction(ModelProcessingPhase.SOURCE_LINKAGE);
 
             final ModuleIdentifier belongsToModuleIdentifier = getModuleIdentifier(belongsToCtx);
-            final ModelActionBuilder.Prerequisite<StmtContext<?, ?, ?>> belongsToPrereq = belongsToAction.requiresCtx(belongsToCtx, ModuleNamespaceForBelongsTo.class, belongsToModuleIdentifier.getName(), ModelProcessingPhase.SOURCE_LINKAGE);
+            final ModelActionBuilder.Prerequisite<StmtContext<?, ?, ?>> belongsToPrereq = belongsToAction.requiresCtx(
+                belongsToCtx, ModuleNamespaceForBelongsTo.class, belongsToModuleIdentifier.getName(),
+                ModelProcessingPhase.SOURCE_LINKAGE);
 
             belongsToAction.apply(new InferenceAction() {
-
                 @Override
-                public void apply() throws InferenceException {
+                public void apply() {
                     StmtContext<?, ?, ?> belongsToModuleCtx = belongsToPrereq.get();
 
-                    belongsToCtx.addToNs(BelongsToModuleContext.class, belongsToModuleIdentifier,
-                            belongsToModuleCtx);
-                    belongsToCtx.addToNs(BelongsToPrefixToModuleIdentifier.class, StmtContextUtils
-                            .findFirstDeclaredSubstatement(belongsToCtx, PrefixStatement.class).getStatementArgument
-                                    (), belongsToModuleIdentifier);
+                    belongsToCtx.addToNs(BelongsToModuleContext.class, belongsToModuleIdentifier, belongsToModuleCtx);
+                    belongsToCtx.addToNs(BelongsToPrefixToModuleIdentifier.class,
+                        StmtContextUtils.findFirstDeclaredSubstatement(belongsToCtx, PrefixStatement.class)
+                        .getStatementArgument(), belongsToModuleIdentifier);
                 }
 
                 @Override
-                public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) throws InferenceException {
+                public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) {
                     if (failed.contains(belongsToPrereq)) {
-                        throw new InferenceException("Module from belongs-to was not found: " + belongsToCtx.getStatementArgument(), belongsToCtx
-                                .getStatementSourceReference());
+                        throw new InferenceException(belongsToCtx.getStatementSourceReference(),
+                            "Module '%s' from belongs-to was not found", belongsToCtx.getStatementArgument());
                     }
                 }
             });
         }
 
-        private static ModuleIdentifier getModuleIdentifier(final StmtContext.Mutable<String, BelongsToStatement, EffectiveStatement<String, BelongsToStatement>> belongsToCtx) {
+        private static ModuleIdentifier getModuleIdentifier(
+                final StmtContext.Mutable<String, BelongsToStatement, EffectiveStatement<String, BelongsToStatement>> belongsToCtx) {
             String moduleName = belongsToCtx.getStatementArgument();
-            return new ModuleIdentifierImpl(moduleName, Optional.<URI> absent(), Optional.of(SimpleDateFormatUtil.DEFAULT_BELONGS_TO_DATE));
+            return new ModuleIdentifierImpl(moduleName, Optional.<URI> absent(),
+                Optional.of(SimpleDateFormatUtil.DEFAULT_BELONGS_TO_DATE));
         }
 
         @Override
-        public void onFullDefinitionDeclared(StmtContext.Mutable<String, BelongsToStatement,
-                EffectiveStatement<String, BelongsToStatement>> stmt) throws SourceException {
+        public void onFullDefinitionDeclared(final StmtContext.Mutable<String, BelongsToStatement,
+                EffectiveStatement<String, BelongsToStatement>> stmt) {
             super.onFullDefinitionDeclared(stmt);
             SUBSTATEMENT_VALIDATOR.validate(stmt);
         }
index e28a1c6bb90d65c0fe337d665cc5b83bd1fdb250..7f92ae4a7414928805b306c23105ccbfb396b443 100644 (file)
@@ -179,15 +179,12 @@ public final class GroupingUtils {
         StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
         StatementDefinition refineTargetNodeDef = refineTargetNodeCtx.getPublicDefinition();
 
-        if (!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx)) {
-            throw new SourceException("Error in module '"
-                    + refineSubstatementCtx.getRoot().getStatementArgument()
-                    + "' in the refine of uses '"
-                    + refineSubstatementCtx.getParentContext().getStatementArgument()
-                    + "': can not perform refine of '" + refineSubstatementCtx.getPublicDefinition()
-                    + "' for the target '" + refineTargetNodeCtx.getPublicDefinition() + "'.",
-                    refineSubstatementCtx.getStatementSourceReference());
-        }
+        SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
+            refineSubstatementCtx.getStatementSourceReference(),
+            "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
+                    refineSubstatementCtx.getRoot().getStatementArgument(),
+                    refineSubstatementCtx.getParentContext().getStatementArgument(),
+                    refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx.getPublicDefinition());
 
         if (isAllowedToAddByRefine(refineSubstatementDef)) {
             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
index 5832cf68f31c797f29ec1f869416cdaf1960971e..6bf310158fc9a866697310dada0ce70bca48d082 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 
 import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.SOURCE_LINKAGE;
 import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-
 import com.google.common.base.Optional;
 import java.net.URI;
 import java.util.Collection;
@@ -36,16 +35,13 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prereq
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.ImportEffectiveStatementImpl;
 
 public class ImportStatementDefinition
         extends AbstractStatementSupport<String, ImportStatement, EffectiveStatement<String, ImportStatement>> {
-    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
-            .IMPORT)
-            .add(Rfc6020Mapping.PREFIX, 1, 1)
-            .add(Rfc6020Mapping.REVISION_DATE, 0, 1)
-            .build();
+    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+            SubstatementValidator.builder(Rfc6020Mapping.IMPORT)
+            .add(Rfc6020Mapping.PREFIX, 1, 1).add(Rfc6020Mapping.REVISION_DATE, 0, 1).build();
 
     public ImportStatementDefinition() {
         super(Rfc6020Mapping.IMPORT);
@@ -57,8 +53,7 @@ public class ImportStatementDefinition
     }
 
     @Override
-    public ImportStatement createDeclared(
-            final StmtContext<String, ImportStatement, ?> ctx) {
+    public ImportStatement createDeclared(final StmtContext<String, ImportStatement, ?> ctx) {
         return new ImportStatementImpl(ctx);
     }
 
@@ -69,8 +64,8 @@ public class ImportStatementDefinition
     }
 
     @Override
-    public void onFullDefinitionDeclared(Mutable<String, ImportStatement,
-            EffectiveStatement<String, ImportStatement>> stmt) throws SourceException {
+    public void onFullDefinitionDeclared(
+            final Mutable<String, ImportStatement, EffectiveStatement<String, ImportStatement>> stmt) {
         super.onFullDefinitionDeclared(stmt);
         SUBSTATEMENT_VALIDATOR.validate(stmt);
     }
@@ -86,12 +81,12 @@ public class ImportStatementDefinition
 
         importAction.apply(new InferenceAction() {
             @Override
-            public void apply() throws InferenceException {
+            public void apply() {
                 StmtContext<?, ?, ?> importedModule = null;
                 ModuleIdentifier importedModuleIdentifier = null;
                 if (impIdentifier.getRevision() == SimpleDateFormatUtil.DEFAULT_DATE_IMP) {
-                    Entry<ModuleIdentifier, StmtContext<?, ModuleStatement, EffectiveStatement<String, ModuleStatement>>> recentModuleEntry = findRecentModule(
-                            impIdentifier, stmt.getAllFromNamespace(ModuleNamespace.class));
+                    Entry<ModuleIdentifier, StmtContext<?, ModuleStatement, EffectiveStatement<String, ModuleStatement>>> recentModuleEntry =
+                            findRecentModule(impIdentifier, stmt.getAllFromNamespace(ModuleNamespace.class));
                     if (recentModuleEntry != null) {
                         importedModuleIdentifier = recentModuleEntry.getKey();
                         importedModule = recentModuleEntry.getValue();
@@ -119,9 +114,11 @@ public class ImportStatementDefinition
                 Entry<ModuleIdentifier, StmtContext<?, ModuleStatement, EffectiveStatement<String, ModuleStatement>>> recentModuleEntry = null;
 
                 for (Entry<ModuleIdentifier, StmtContext<?, ModuleStatement, EffectiveStatement<String, ModuleStatement>>> moduleEntry : allModules.entrySet()) {
-                    if (moduleEntry.getKey().getName().equals(impIdentifier.getName())
-                            && moduleEntry.getKey().getRevision().compareTo(recentModuleIdentifier.getRevision()) > 0) {
-                        recentModuleIdentifier = moduleEntry.getKey();
+                    final ModuleIdentifier id = moduleEntry.getKey();
+
+                    if (id.getName().equals(impIdentifier.getName())
+                            && id.getRevision().compareTo(recentModuleIdentifier.getRevision()) > 0) {
+                        recentModuleIdentifier = id;
                         recentModuleEntry = moduleEntry;
                     }
                 }
@@ -132,8 +129,8 @@ public class ImportStatementDefinition
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed)  {
                 if (failed.contains(imported)) {
-                    throw new InferenceException(String.format("Imported module [%s] was not found.", impIdentifier),
-                        stmt.getStatementSourceReference());
+                    throw new InferenceException(stmt.getStatementSourceReference(),
+                        "Imported module [%s] was not found.", impIdentifier);
                 }
             }
         });
index d5869d6cf95288a229659fa99e865ec802323d29..872426cf3529aca09d110c5d091652a140e35054 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 
 import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.SOURCE_LINKAGE;
 import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-
 import com.google.common.base.Optional;
 import java.net.URI;
 import java.util.Collection;
@@ -37,12 +36,10 @@ import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.IncludeEffectiveStatementImpl;
 
 public class IncludeStatementImpl extends AbstractDeclaredStatement<String> implements IncludeStatement {
-    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
-            .INCLUDE)
-            .add(Rfc6020Mapping.REVISION_DATE, 0, 1)
-            .build();
+    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(
+        Rfc6020Mapping.INCLUDE).add(Rfc6020Mapping.REVISION_DATE, 0, 1).build();
 
-    protected IncludeStatementImpl(StmtContext<String, IncludeStatement, ?> context) {
+    protected IncludeStatementImpl(final StmtContext<String, IncludeStatement, ?> context) {
         super(context);
     }
 
@@ -54,25 +51,24 @@ public class IncludeStatementImpl extends AbstractDeclaredStatement<String> impl
         }
 
         @Override
-        public String parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
+        public String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
             return value;
         }
 
         @Override
-        public IncludeStatement createDeclared(StmtContext<String, IncludeStatement, ?> ctx) {
+        public IncludeStatement createDeclared(final StmtContext<String, IncludeStatement, ?> ctx) {
             return new IncludeStatementImpl(ctx);
         }
 
         @Override
         public EffectiveStatement<String, IncludeStatement> createEffective(
-                StmtContext<String, IncludeStatement, EffectiveStatement<String, IncludeStatement>> ctx) {
+                final StmtContext<String, IncludeStatement, EffectiveStatement<String, IncludeStatement>> ctx) {
             return new IncludeEffectiveStatementImpl(ctx);
         }
 
         @Override
         public void onLinkageDeclared(
-                final Mutable<String, IncludeStatement, EffectiveStatement<String, IncludeStatement>> stmt)
-                throws SourceException {
+                final Mutable<String, IncludeStatement, EffectiveStatement<String, IncludeStatement>> stmt) {
             final ModuleIdentifier includeSubmoduleIdentifier = getIncludeSubmoduleIdentifier(stmt);
 
             ModelActionBuilder includeAction = stmt.newInferenceAction(SOURCE_LINKAGE);
@@ -80,9 +76,8 @@ public class IncludeStatementImpl extends AbstractDeclaredStatement<String> impl
                     SubmoduleNamespace.class, includeSubmoduleIdentifier, SOURCE_LINKAGE);
 
             includeAction.apply(new InferenceAction() {
-
                 @Override
-                public void apply() throws InferenceException {
+                public void apply() {
                     StmtContext<?, ?, ?> includedSubModuleContext = requiresCtxPrerequisite.get();
 
                     stmt.addToNs(IncludedModuleContext.class, includeSubmoduleIdentifier,
@@ -92,16 +87,15 @@ public class IncludeStatementImpl extends AbstractDeclaredStatement<String> impl
                 }
 
                 @Override
-                public void prerequisiteFailed(Collection<? extends Prerequisite<?>> failed) throws InferenceException {
-                    if (failed.contains(requiresCtxPrerequisite)) {
-                        throw new InferenceException("Included submodule was not found: "+stmt.getStatementArgument(), stmt
-                                .getStatementSourceReference());
-                    }
+                public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
+                    InferenceException.throwIf(failed.contains(requiresCtxPrerequisite),
+                        stmt.getStatementSourceReference(),
+                        "Included submodule '%s' was not found: ", stmt.getStatementArgument());
                 }
             });
         }
 
-        private static ModuleIdentifier getIncludeSubmoduleIdentifier(Mutable<String, IncludeStatement, ?> stmt) {
+        private static ModuleIdentifier getIncludeSubmoduleIdentifier(final Mutable<String, IncludeStatement, ?> stmt) {
 
             String subModuleName = stmt.getStatementArgument();
 
@@ -114,7 +108,7 @@ public class IncludeStatementImpl extends AbstractDeclaredStatement<String> impl
         }
 
         @Override
-        public void onFullDefinitionDeclared(Mutable<String, IncludeStatement,
+        public void onFullDefinitionDeclared(final Mutable<String, IncludeStatement,
                 EffectiveStatement<String, IncludeStatement>> stmt) throws SourceException {
             super.onFullDefinitionDeclared(stmt);
             SUBSTATEMENT_VALIDATOR.validate(stmt);
index ea6d565b895288b891582df87ec952ac5d7e319f..f66e2b96c067e68fa269307dc0a41ca4d6f78c1d 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 
 import static org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator.MAX;
 import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-
 import com.google.common.base.Optional;
 import java.net.URI;
 import java.util.Date;
@@ -75,31 +74,28 @@ public class ModuleStatementSupport extends
     }
 
     @Override
-    public String parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
+    public String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
         return value;
     }
 
     @Override
-    public ModuleStatement createDeclared(StmtContext<String, ModuleStatement, ?> ctx) {
+    public ModuleStatement createDeclared(final StmtContext<String, ModuleStatement, ?> ctx) {
         return new ModuleStatementImpl(ctx);
     }
 
     @Override
     public EffectiveStatement<String, ModuleStatement> createEffective(
-            StmtContext<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> ctx) {
+            final StmtContext<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> ctx) {
         return new ModuleEffectiveStatementImpl(ctx);
     }
 
     @Override
-    public void onLinkageDeclared(Mutable<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> stmt)
-            throws SourceException {
+    public void onLinkageDeclared(final Mutable<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> stmt) {
 
         Optional<URI> moduleNs = Optional.fromNullable(firstAttributeOf(stmt.declaredSubstatements(),
                 NamespaceStatement.class));
-        if (!moduleNs.isPresent()) {
-            throw new SourceException(String.format("Namespace of the module [%s] is missing",
-                    stmt.getStatementArgument()), stmt.getStatementSourceReference());
-        }
+        SourceException.throwIf(!moduleNs.isPresent(), stmt.getStatementSourceReference(),
+            "Namespace of the module [%s] is missing", stmt.getStatementArgument());
 
         Optional<Date> revisionDate = Optional.fromNullable(Utils.getLatestRevision(stmt.declaredSubstatements()));
         if (!revisionDate.isPresent()) {
@@ -114,23 +110,20 @@ public class ModuleStatementSupport extends
         stmt.addContext(ModuleNamespaceForBelongsTo.class, moduleIdentifier.getName(), stmt);
         stmt.addContext(NamespaceToModule.class, qNameModule, stmt);
 
-        String modulePrefix = firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class);
-        if (modulePrefix == null) {
-            throw new SourceException(String.format("Prefix of the module [%s] is missing",
-                    stmt.getStatementArgument()), stmt.getStatementSourceReference());
-        }
+        final String modulePrefix = firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class);
+        SourceException.throwIfNull(modulePrefix, stmt.getStatementSourceReference(),
+            "Prefix of the module [%s] is missing", stmt.getStatementArgument());
 
         stmt.addToNs(PrefixToModule.class, modulePrefix, qNameModule);
         stmt.addToNs(ModuleNameToModuleQName.class, stmt.getStatementArgument(), qNameModule);
         stmt.addToNs(ModuleCtxToModuleQName.class, stmt, qNameModule);
         stmt.addToNs(ModuleQNameToModuleName.class, qNameModule, stmt.getStatementArgument());
         stmt.addToNs(ModuleIdentifierToModuleQName.class, moduleIdentifier, qNameModule);
-
         stmt.addToNs(ImpPrefixToModuleIdentifier.class, modulePrefix, moduleIdentifier);
     }
 
     @Override
-    public void onFullDefinitionDeclared(Mutable<String, ModuleStatement,
+    public void onFullDefinitionDeclared(final Mutable<String, ModuleStatement,
             EffectiveStatement<String, ModuleStatement>> stmt) throws SourceException {
         super.onFullDefinitionDeclared(stmt);
         SUBSTATEMENT_VALIDATOR.validate(stmt);
index 0e6ef322fb9d7a97273e253cc542d510aa5119f7..28d4ee82b0ae51c4bbd923e4338907f29dd01d6e 100644 (file)
@@ -20,14 +20,11 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.RevisionDateEffectiveStatementImpl;
 
-public class RevisionDateStatementImpl extends
-        AbstractDeclaredStatement<Date> implements RevisionDateStatement {
-    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
-            .REVISION_DATE)
-            .build();
+public class RevisionDateStatementImpl extends AbstractDeclaredStatement<Date> implements RevisionDateStatement {
+    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+            SubstatementValidator.builder(Rfc6020Mapping.REVISION_DATE).build();
 
-    protected RevisionDateStatementImpl(
-            StmtContext<Date, RevisionDateStatement, ?> context) {
+    protected RevisionDateStatementImpl(final StmtContext<Date, RevisionDateStatement, ?> context) {
         super(context);
     }
 
@@ -40,34 +37,29 @@ public class RevisionDateStatementImpl extends
         }
 
         @Override
-        public Date parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) throws SourceException {
-            Date revision;
+        public Date parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) throws SourceException {
             try {
-                revision = SimpleDateFormatUtil.getRevisionFormat()
-                        .parse(value);
+                return SimpleDateFormatUtil.getRevisionFormat().parse(value);
             } catch (ParseException e) {
-                throw new SourceException(String.format("Revision value %s is not in required format yyyy-MM-dd",
-                        value), ctx.getStatementSourceReference(), e);
+                throw new SourceException(ctx.getStatementSourceReference(), e,
+                    "Revision value %s is not in required format yyyy-MM-dd", value);
             }
-
-            return revision;
         }
 
         @Override
-        public RevisionDateStatement createDeclared(
-                StmtContext<Date, RevisionDateStatement, ?> ctx) {
+        public RevisionDateStatement createDeclared(final StmtContext<Date, RevisionDateStatement, ?> ctx) {
             return new RevisionDateStatementImpl(ctx);
         }
 
         @Override
         public EffectiveStatement<Date, RevisionDateStatement> createEffective(
-                StmtContext<Date, RevisionDateStatement, EffectiveStatement<Date, RevisionDateStatement>> ctx) {
+                final StmtContext<Date, RevisionDateStatement, EffectiveStatement<Date, RevisionDateStatement>> ctx) {
             return new RevisionDateEffectiveStatementImpl(ctx);
         }
 
         @Override
-        public void onFullDefinitionDeclared(StmtContext.Mutable<Date, RevisionDateStatement,
-                EffectiveStatement<Date, RevisionDateStatement>> stmt) throws SourceException {
+        public void onFullDefinitionDeclared(
+                final StmtContext.Mutable<Date, RevisionDateStatement, EffectiveStatement<Date, RevisionDateStatement>> stmt) {
             super.onFullDefinitionDeclared(stmt);
             SUBSTATEMENT_VALIDATOR.validate(stmt);
         }
@@ -77,5 +69,4 @@ public class RevisionDateStatementImpl extends
     public Date getDate() {
         return argument();
     }
-
 }
index 16ef33e27b3c4e35f0a65aeffee0e851b63ecccd..5ac76435214e14a0495d203eaa7ea7f1d053f772 100644 (file)
@@ -25,14 +25,11 @@ import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.RevisionEff
 
 public class RevisionStatementImpl extends AbstractDeclaredStatement<Date>
         implements RevisionStatement {
-    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
-            .REVISION)
-            .add(Rfc6020Mapping.DESCRIPTION, 0, 1)
-            .add(Rfc6020Mapping.REFERENCE, 0, 1)
-            .build();
+    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(
+        Rfc6020Mapping.REVISION)
+            .add(Rfc6020Mapping.DESCRIPTION, 0, 1).add(Rfc6020Mapping.REFERENCE, 0, 1).build();
 
-    protected RevisionStatementImpl(
-            StmtContext<Date, RevisionStatement, ?> context) {
+    protected RevisionStatementImpl(final StmtContext<Date, RevisionStatement, ?> context) {
         super(context);
     }
 
@@ -45,35 +42,29 @@ public class RevisionStatementImpl extends AbstractDeclaredStatement<Date>
         }
 
         @Override
-        public Date parseArgumentValue(StmtContext<?, ?, ?> ctx, String value)
-                throws SourceException {
-            Date revision;
+        public Date parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
             try {
-                revision = SimpleDateFormatUtil.getRevisionFormat()
-                        .parse(value);
+                return SimpleDateFormatUtil.getRevisionFormat().parse(value);
             } catch (ParseException e) {
-                throw new SourceException(String.format("Revision value %s is not in required format yyyy-MM-dd",
-                        value), ctx.getStatementSourceReference(), e);
+                throw new SourceException(ctx.getStatementSourceReference(), e,
+                    "Revision value %s is not in required format yyyy-MM-dd", value);
             }
-
-            return revision;
         }
 
         @Override
-        public RevisionStatement createDeclared(
-                StmtContext<Date, RevisionStatement, ?> ctx) {
+        public RevisionStatement createDeclared(final StmtContext<Date, RevisionStatement, ?> ctx) {
             return new RevisionStatementImpl(ctx);
         }
 
         @Override
         public EffectiveStatement<Date, RevisionStatement> createEffective(
-                StmtContext<Date, RevisionStatement, EffectiveStatement<Date, RevisionStatement>> ctx) {
+                final StmtContext<Date, RevisionStatement, EffectiveStatement<Date, RevisionStatement>> ctx) {
             return new RevisionEffectiveStatementImpl(ctx);
         }
 
         @Override
-        public void onFullDefinitionDeclared(StmtContext.Mutable<Date, RevisionStatement,
-                EffectiveStatement<Date, RevisionStatement>> stmt) throws SourceException {
+        public void onFullDefinitionDeclared(
+                final StmtContext.Mutable<Date, RevisionStatement, EffectiveStatement<Date, RevisionStatement>> stmt) {
             super.onFullDefinitionDeclared(stmt);
             SUBSTATEMENT_VALIDATOR.validate(stmt);
         }
index 41c0a5343d448faf0b6ab2a50a6e43b1c3d05494..5516f9debce27c0a5b574611ea1ea7730e6faa91 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 import static org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator.MAX;
 import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.findFirstDeclaredSubstatement;
 import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-
 import com.google.common.base.Optional;
 import java.net.URI;
 import java.util.Date;
@@ -61,8 +60,9 @@ public class SubmoduleStatementImpl extends AbstractRootStatement<SubmoduleState
             .add(Rfc6020Mapping.USES, 0, MAX)
             .add(Rfc6020Mapping.YANG_VERSION, 0, 1)
             .build();
+    private static final Optional<Date> DEFAULT_REVISION = Optional.of(SimpleDateFormatUtil.DEFAULT_DATE_REV);
 
-    protected SubmoduleStatementImpl(StmtContext<String, SubmoduleStatement, ?> context) {
+    protected SubmoduleStatementImpl(final StmtContext<String, SubmoduleStatement, ?> context) {
         super(context);
     }
 
@@ -74,35 +74,32 @@ public class SubmoduleStatementImpl extends AbstractRootStatement<SubmoduleState
         }
 
         @Override
-        public String parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
+        public String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
             return value;
         }
 
         @Override
         public SubmoduleStatement createDeclared(
-                StmtContext<String, SubmoduleStatement, ?> ctx) {
+                final StmtContext<String, SubmoduleStatement, ?> ctx) {
             return new SubmoduleStatementImpl(ctx);
         }
 
         @Override
         public EffectiveStatement<String, SubmoduleStatement> createEffective(
-                StmtContext<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> ctx) {
+                final StmtContext<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> ctx) {
             return new SubmoduleEffectiveStatementImpl(ctx);
         }
 
         @Override
         public void onLinkageDeclared(
-                Mutable<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> stmt)
+                final Mutable<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> stmt)
                 throws SourceException {
 
-            Optional<Date> revisionDate = Optional.fromNullable(Utils.getLatestRevision(stmt.declaredSubstatements()));
-            if (!revisionDate.isPresent()) {
-                revisionDate = Optional.of(SimpleDateFormatUtil.DEFAULT_DATE_REV);
-            }
+            final Optional<Date> revisionDate = Optional.fromNullable(
+                Utils.getLatestRevision(stmt.declaredSubstatements())).or(DEFAULT_REVISION);
 
-            ModuleIdentifier submoduleIdentifier = new ModuleIdentifierImpl(
-                    stmt.getStatementArgument(), Optional.<URI> absent(),
-                    revisionDate);
+            ModuleIdentifier submoduleIdentifier = new ModuleIdentifierImpl(stmt.getStatementArgument(),
+                Optional.<URI> absent(), revisionDate);
 
             stmt.addContext(SubmoduleNamespace.class, submoduleIdentifier, stmt);
 
@@ -110,20 +107,16 @@ public class SubmoduleStatementImpl extends AbstractRootStatement<SubmoduleState
                     stmt.declaredSubstatements(), BelongsToStatement.class);
             StmtContext<?, ?, ?> prefixSubStmtCtx = findFirstDeclaredSubstatement(
                     stmt, 0, BelongsToStatement.class, PrefixStatement.class);
-
-            if (prefixSubStmtCtx == null) {
-                throw new SourceException(String.format("Prefix of belongsTo statement is missing in submodule [%s]",
-                        stmt.getStatementArgument()), stmt.getStatementSourceReference());
-            }
+            SourceException.throwIfNull(prefixSubStmtCtx, stmt.getStatementSourceReference(),
+                "Prefix of belongsTo statement is missing in submodule [%s]", stmt.getStatementArgument());
 
             String prefix = (String) prefixSubStmtCtx.getStatementArgument();
 
-            stmt.addToNs(BelongsToPrefixToModuleName.class, prefix,
-                    belongsToModuleName);
+            stmt.addToNs(BelongsToPrefixToModuleName.class, prefix, belongsToModuleName);
         }
 
         @Override
-        public void onFullDefinitionDeclared(Mutable<String, SubmoduleStatement,
+        public void onFullDefinitionDeclared(final Mutable<String, SubmoduleStatement,
                 EffectiveStatement<String, SubmoduleStatement>> stmt) throws SourceException {
             super.onFullDefinitionDeclared(stmt);
             SUBSTATEMENT_VALIDATOR.validate(stmt);
index de9ea479bb9a98a884baf9253534996e8f1396fa..8253d60d37ddfc9374ca53b9cc9132c0104e38e9 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 
 import static org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator.MAX;
-
 import com.google.common.base.Verify;
 import java.util.Collection;
 import javax.annotation.Nonnull;
@@ -151,9 +150,7 @@ public class TypeStatementImpl extends AbstractDeclaredStatement<String>
                 final QName qname = Utils.qNameFromArgument(ctx, ctx.getStatementArgument());
                 final StmtContext<?, TypedefStatement, TypedefEffectiveStatement> typedef =
                         ctx.getFromNamespace(TypeNamespace.class, qname);
-                if (typedef == null) {
-                    throw new SourceException("Type '" + qname + "' not found", ctx.getStatementSourceReference());
-                }
+                SourceException.throwIfNull(typedef, ctx.getStatementSourceReference(), "Type '%s' not found", qname);
 
                 final TypedefEffectiveStatement effectiveTypedef = typedef.buildEffective();
                 Verify.verify(effectiveTypedef instanceof TypeDefEffectiveStatementImpl);
@@ -199,8 +196,7 @@ public class TypeStatementImpl extends AbstractDeclaredStatement<String>
 
         @Override
         public void onFullDefinitionDeclared(
-                final Mutable<String, TypeStatement, EffectiveStatement<String, TypeStatement>> stmt)
-                throws SourceException {
+                final Mutable<String, TypeStatement, EffectiveStatement<String, TypeStatement>> stmt){
             SUBSTATEMENT_VALIDATOR.validate(stmt);
 
             // if it is yang built-in type, no prerequisite is needed, so simply return
@@ -219,18 +215,15 @@ public class TypeStatementImpl extends AbstractDeclaredStatement<String>
              * Otherwise perform no operation.
              */
             typeAction.apply(new InferenceAction() {
-
                 @Override
                 public void apply() {
                     // Intentional NOOP
                 }
 
                 @Override
-                public void prerequisiteFailed(Collection<? extends Prerequisite<?>> failed) {
-                    if (failed.contains(typePrereq)) {
-                        throw new InferenceException(String.format("Type [%s] was not found.", typeQName), stmt
-                                .getStatementSourceReference());
-                    }
+                public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
+                    InferenceException.throwIf(failed.contains(typePrereq), stmt.getStatementSourceReference(),
+                        "Type [%s] was not found.", typeQName);
                 }
             });
         }
index 3aee37027267ebd1a1e1c8f3e7db7d3bb1b1d355..cd579073d68808a41ac0fed62a7f096efd65fd0e 100644 (file)
@@ -135,23 +135,19 @@ public final class TypeUtils {
                 max = parseDecimalConstraintValue(ctx, boundaries.next());
 
                 // if min larger than max then error
-                if (compareNumbers(min, max) == 1) {
-                    throw new InferenceException(String.format(
-                            "Range constraint %s has descending order of boundaries; should be ascending",
-                            singleRange), ctx.getStatementSourceReference());
-                }
-                if (boundaries.hasNext()) {
-                    throw new SourceException(String.format("Wrong number of boundaries in range constraint %s",
-                            singleRange), ctx.getStatementSourceReference());
-                }
+                InferenceException.throwIf(compareNumbers(min, max) == 1, ctx.getStatementSourceReference(),
+                        "Range constraint %s has descending order of boundaries; should be ascending", singleRange);
+
+                SourceException.throwIf(boundaries.hasNext(), ctx.getStatementSourceReference(),
+                    "Wrong number of boundaries in range constraint %s", singleRange);
             } else {
                 max = min;
             }
 
             // some of intervals overlapping
             if (rangeConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(rangeConstraints).getMax()) != 1) {
-                throw new InferenceException(String.format("Some of the ranges in %s are not disjoint",
-                        rangeArgument), ctx.getStatementSourceReference());
+                throw new InferenceException(ctx.getStatementSourceReference(),
+                    "Some of the ranges in %s are not disjoint", rangeArgument);
             }
 
             rangeConstraints.add(new RangeConstraintEffectiveImpl(min, max, description, reference));
@@ -188,8 +184,8 @@ public final class TypeUtils {
 
             // some of intervals overlapping
             if (rangeConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(rangeConstraints).getMax()) != 1) {
-                throw new InferenceException(String.format("Some of the length ranges in %s are not disjoint",
-                        rangeArgument), ctx.getStatementSourceReference());
+                throw new InferenceException(ctx.getStatementSourceReference(),
+                    "Some of the length ranges in %s are not disjoint", rangeArgument);
             }
 
             rangeConstraints.add(new LengthConstraintEffectiveImpl(min, max, description, reference));
index 9d3fb3ef1ad936c0e8084c85d8860238852689d3..b96a2708e40be500f94fddbe9c7591e573333cf1 100644 (file)
@@ -15,6 +15,7 @@ import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.ReferenceStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.StatusStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.TypeStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.UnitsStatement;
 import org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator;
@@ -36,7 +37,7 @@ public class TypedefStatementImpl extends AbstractDeclaredStatement<QName> imple
             .add(Rfc6020Mapping.UNITS, 0, 1)
             .build();
 
-    protected TypedefStatementImpl(StmtContext<QName, TypedefStatement, ?> context) {
+    protected TypedefStatementImpl(final StmtContext<QName, TypedefStatement, ?> context) {
         super(context);
     }
 
@@ -48,37 +49,36 @@ public class TypedefStatementImpl extends AbstractDeclaredStatement<QName> imple
         }
 
         @Override
-        public QName parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) throws SourceException {
+        public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
             return Utils.qNameFromArgument(ctx, value);
         }
 
         @Override
-        public TypedefStatement createDeclared(StmtContext<QName, TypedefStatement, ?> ctx) {
+        public TypedefStatement createDeclared(final StmtContext<QName, TypedefStatement, ?> ctx) {
             return new TypedefStatementImpl(ctx);
         }
 
         @Override
         public EffectiveStatement<QName, TypedefStatement> createEffective(
-                StmtContext<QName, TypedefStatement, EffectiveStatement<QName, TypedefStatement>> ctx) {
+                final StmtContext<QName, TypedefStatement, EffectiveStatement<QName, TypedefStatement>> ctx) {
             return new TypeDefEffectiveStatementImpl(ctx);
         }
 
         @Override
         public void onStatementDefinitionDeclared(
-                StmtContext.Mutable<QName, TypedefStatement, EffectiveStatement<QName, TypedefStatement>> stmt)
-                throws SourceException {
+                final StmtContext.Mutable<QName, TypedefStatement, EffectiveStatement<QName, TypedefStatement>> stmt) {
             if (stmt != null && stmt.getParentContext() != null) {
-                if (stmt.getParentContext().getFromNamespace(TypeNamespace.class, stmt.getStatementArgument()) != null) {
-                    throw new SourceException(String.format("Duplicate name for typedef %s",
-                            stmt.getStatementArgument()), stmt.getStatementSourceReference());
-                }
+                final StmtContext<?, TypedefStatement, TypedefEffectiveStatement> existing =
+                        stmt.getParentContext().getFromNamespace(TypeNamespace.class, stmt.getStatementArgument());
+                SourceException.throwIf(existing != null, stmt.getStatementSourceReference(),
+                        "Duplicate name for typedef %s", stmt.getStatementArgument());
 
                 stmt.getParentContext().addContext(TypeNamespace.class, stmt.getStatementArgument(), stmt);
             }
         }
 
         @Override
-        public void onFullDefinitionDeclared(StmtContext.Mutable<QName, TypedefStatement,
+        public void onFullDefinitionDeclared(final StmtContext.Mutable<QName, TypedefStatement,
                 EffectiveStatement<QName, TypedefStatement>> stmt) throws SourceException {
             super.onFullDefinitionDeclared(stmt);
             SUBSTATEMENT_VALIDATOR.validate(stmt);
index 154467fb19d47c9361436a684b1276225c3f53c6..a5872bd614f440a02497893ed86210e1cd7359f7 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 
 import static org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator.MAX;
-
 import java.util.Collection;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
@@ -75,7 +74,7 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
                 throws SourceException {
             SUBSTATEMENT_VALIDATOR.validate(usesNode);
 
-            if(StmtContextUtils.isInExtensionBody(usesNode)) {
+            if (StmtContextUtils.isInExtensionBody(usesNode)) {
                 return;
             }
 
@@ -90,7 +89,7 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
             usesAction.apply(new InferenceAction() {
 
                 @Override
-                public void apply() throws InferenceException {
+                public void apply() {
                     StatementContextBase<?, ?, ?> targetNodeStmtCtx = (StatementContextBase<?, ?, ?>) targetNodePre.get();
                     StatementContextBase<?, ?, ?> sourceGrpStmtCtx = (StatementContextBase<?, ?, ?>) sourceGroupingPre.get();
 
@@ -104,11 +103,9 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
                 }
 
                 @Override
-                public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) throws InferenceException {
-                    if (failed.contains(sourceGroupingPre)) {
-                        throw new InferenceException("Grouping " + groupingName + " was not resolved.", usesNode
-                                .getStatementSourceReference());
-                    }
+                public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
+                    InferenceException.throwIf(failed.contains(sourceGroupingPre),
+                        usesNode.getStatementSourceReference(), "Grouping '%s' was not resolved.", groupingName);
                     throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference());
                 }
             });
index a19e00df1cdee1b2fb1249e1dabd196c484929bd..3123445b478574bee0f9ac12a10eed0f48218abf 100644 (file)
@@ -107,8 +107,7 @@ public final class Utils {
         // to detect if key contains duplicates
         if ((new HashSet<>(keyTokens)).size() < keyTokens.size()) {
             // FIXME: report all duplicate keys
-            throw new SourceException(String.format("Duplicate value in list key: %s", value),
-                    ctx.getStatementSourceReference());
+            throw new SourceException(ctx.getStatementSourceReference(), "Duplicate value in list key: %s", value);
         }
 
         Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
index 04415543bb3072fa0c314464352ec9e59e519e0b..de640644cd12bd69efca2c3df6e8b17f41d9a3b4 100644 (file)
@@ -49,10 +49,9 @@ abstract class AbstractEffectiveDocumentedDataNodeContainer<A, D extends Declare
 
         for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
             if (effectiveStatement instanceof DataSchemaNode) {
-                DataSchemaNode dataSchemaNode = (DataSchemaNode) effectiveStatement;
+                final DataSchemaNode dataSchemaNode = (DataSchemaNode) effectiveStatement;
                 if (!mutableChildNodes.containsKey(dataSchemaNode.getQName())) {
-                    mutableChildNodes.put(dataSchemaNode.getQName(),
-                            dataSchemaNode);
+                    mutableChildNodes.put(dataSchemaNode.getQName(), dataSchemaNode);
                     mutablePublicChildNodes.add(dataSchemaNode);
                 } else {
                     throw EffectiveStmtUtils.createNameCollisionSourceException(ctx, effectiveStatement);
index 854b857dfeaa9cf9558827469a18573b691b0a00..63c5b10da14e7c349b9c0cab5fecbfd51eec2ade 100644 (file)
@@ -12,22 +12,18 @@ import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 
-public final class EffectiveStmtUtils {
+final class EffectiveStmtUtils {
 
     private EffectiveStmtUtils() {
         throw new UnsupportedOperationException("Utility class");
     }
 
-    public static SourceException createNameCollisionSourceException(final StmtContext<?, ?, ?> ctx,
+    static SourceException createNameCollisionSourceException(final StmtContext<?, ?, ?> ctx,
             final EffectiveStatement<?, ?> effectiveStatement) {
-        return new SourceException("Error in module '"
-                + ctx.getRoot().getStatementArgument()
-                + "': can not add '"
-                + effectiveStatement.argument()
-                + "'. Node name collision: '"
-                + effectiveStatement.argument()
-                + "' already declared.",
-                ctx.getStatementSourceReference());
+        return new SourceException(ctx.getStatementSourceReference(),
+            "Error in module '%s': cannot add '%s'. Node name collision: '%s' already declared.",
+            ctx.getRoot().getStatementArgument(),
+            effectiveStatement.argument(),
+            effectiveStatement.argument());
     }
-
 }
index 03fde57ee243baae7c91f5b6d64f0483fbb23fdf..d9f6fb6b2ca9141ca630b97267520513b5532712 100644 (file)
@@ -31,7 +31,7 @@ public class ImportEffectiveStatementImpl extends DeclaredEffectiveStatementBase
         this.revision = (revisionDateStmt == null) ? SimpleDateFormatUtil.DEFAULT_DATE_IMP : revisionDateStmt.argument();
 
         PrefixEffectiveStatementImpl prefixStmt = firstEffective(PrefixEffectiveStatementImpl.class);
-        if (prefixStmt != null ) {
+        if (prefixStmt != null) {
             this.prefix = prefixStmt.argument();
         } else {
             throw new MissingSubstatementException("Prefix is mandatory substatement of import statement",
index 70d80394699d89810ef8465ad303bd5cd33b12ea..113a5d49e909a1eefd30f37b5124300de1e3698e 100644 (file)
@@ -32,10 +32,9 @@ public final class LeafEffectiveStatementImpl extends AbstractEffectiveDataSchem
         super(ctx);
         this.original = ctx.getOriginalCtx() == null ? null : (LeafSchemaNode) ctx.getOriginalCtx().buildEffective();
 
-        final TypeEffectiveStatement<?> typeStmt = firstSubstatementOfType(TypeEffectiveStatement.class);
-        if (typeStmt == null) {
-            throw new SourceException("Leaf is missing a 'type' statement", ctx.getStatementSourceReference());
-        }
+        final TypeEffectiveStatement<?> typeStmt = SourceException.throwIfNull(
+                firstSubstatementOfType(TypeEffectiveStatement.class), ctx.getStatementSourceReference(),
+                "Leaf is missing a 'type' statement");
 
         String dflt = null;
         String units = null;
index 6d9a5f6f42d90801b7c2ac84f1f680372a2aa15b..7f391833ba950243e26fb55e3454299ed2a8c672 100644 (file)
@@ -35,10 +35,9 @@ public final class LeafListEffectiveStatementImpl extends AbstractEffectiveDataS
         this.original = ctx.getOriginalCtx() == null ? null : (LeafListSchemaNode) ctx.getOriginalCtx()
                 .buildEffective();
 
-        final TypeEffectiveStatement<?> typeStmt = firstSubstatementOfType(TypeEffectiveStatement.class);
-        if (typeStmt == null) {
-            throw new SourceException("Leaf-list is missing a 'type' statement", ctx.getStatementSourceReference());
-        }
+        final TypeEffectiveStatement<?> typeStmt = SourceException.throwIfNull(
+            firstSubstatementOfType(TypeEffectiveStatement.class), ctx.getStatementSourceReference(),
+            "Leaf-list is missing a 'type' statement");
 
         final ConcreteTypeBuilder<?> builder = ConcreteTypes.concreteTypeBuilder(typeStmt.getTypeDefinition(),
             ctx.getSchemaPath().get());
index cb6166415ae98803c26f1ac579a8de732a393a59..7dc2c2361e7a082e9e0c12905807cb4fa9cc8e3a 100644 (file)
@@ -64,9 +64,9 @@ public final class ListEffectiveStatementImpl extends AbstractEffectiveSimpleDat
                 final QName keyQName = key.getLastComponent();
 
                 if (!possibleLeafQNamesForKey.contains(keyQName)) {
-                    throw new InferenceException(String.format("Key '%s' misses node '%s' in list '%s'",
-                            keyEffectiveSubstatement.getDeclared().rawArgument(), keyQName.getLocalName(),
-                            ctx.getStatementArgument()), ctx.getStatementSourceReference());
+                    throw new InferenceException(ctx.getStatementSourceReference(),
+                        "Key '%s' misses node '%s' in list '%s'", keyEffectiveSubstatement.getDeclared().rawArgument(),
+                        keyQName.getLocalName(), ctx.getStatementArgument());
                 }
 
                 keyDefinitionInit.add(keyQName);
index 3c528f7a90d3513b6345dbcb36f2c08ba50f3d58..62b37a3af580e5547f9cec0df7453b56f89ed715 100644 (file)
@@ -47,8 +47,8 @@ public final class BinaryTypeEffectiveStatementImpl extends DeclaredEffectiveSta
             typeDefinition = builder.build();
         } catch (InvalidLengthConstraintException e) {
             final LengthConstraint c = e.getOffendingConstraint();
-            throw new SourceException(String.format("Invalid length constraint: <%s, %s>", c.getMin(), c.getMax()),
-                ctx.getStatementSourceReference(), e);
+            throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid length constraint: <%s, %s>",
+                c.getMin(), c.getMax());
         }
     }
 
index 05374ce27c7d4ff9137b37556e733063d18ff06c..b688f18f46d00c8fb0d6933940b1eba63d358ecf 100644 (file)
@@ -41,17 +41,16 @@ public final class BitsSpecificationEffectiveStatementImpl extends
                     } else if (highestPosition != 4294967295L) {
                         newPos = highestPosition + 1;
                     } else {
-                        throw new SourceException("Bit " + b + " must have a position statement",
-                            ctx.getStatementSourceReference());
+                        throw new SourceException(ctx.getStatementSourceReference(),
+                            "Bit %s must have a position statement", b);
                     }
 
                     b = new BitImpl(newPos, b.getQName(), b.getPath(), b.getDescription(), b.getReference(),
                         b.getStatus(), b.getUnknownSchemaNodes());
                 }
 
-                if (b.getPosition() < 0L || b.getPosition() > 4294967295L) {
-                    throw new SourceException("Bit " + b + " has illegal position", ctx.getStatementSourceReference());
-                }
+                SourceException.throwIf(b.getPosition() < 0L && b.getPosition() > 4294967295L,
+                        ctx.getStatementSourceReference(), "Bit %s has illegal position", b);
 
                 if (highestPosition == null || highestPosition < b.getPosition()) {
                     highestPosition = b.getPosition();
index 66fc7d0d9577ba7829c8a4caa228ef97ec48d833..96dae96a9bbd3c2f39cba09e3c520a8cce9b060c 100644 (file)
@@ -42,8 +42,8 @@ public final class EnumSpecificationEffectiveStatementImpl extends
                     } else if (highestValue != 2147483647) {
                         newValue = highestValue + 1;
                     } else {
-                        throw new SourceException("Enum " + p + " must have a value statement",
-                            ctx.getStatementSourceReference());
+                        throw new SourceException(ctx.getStatementSourceReference(),
+                            "Enum '%s' must have a value statement", p);
                     }
 
                     p = new EnumPairImpl(p.getName(), newValue, p.getPath(), p.getDescription(), p.getReference(),
index 5576360b65edce817bf908e8f8549c54918e1243..856e30cb90f3310e52c387ce6e1cee27e4001155 100644 (file)
@@ -48,8 +48,8 @@ public final class IntegerTypeEffectiveStatementImpl extends
             typeDefinition = builder.build();
         } catch (InvalidRangeConstraintException e) {
             final RangeConstraint c = e.getOffendingConstraint();
-            throw new SourceException(String.format("Invalid range constraint: <%s, %s>", c.getMin(), c.getMax()),
-                ctx.getStatementSourceReference(), e);
+            throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid range constraint: <%s, %s>",
+                c.getMin(), c.getMax());
         }
     }
 
index 895f14dde10fea858d67803a130aafa202c1b3b6..edbc8dce353d6825ed441dd204eb1f542b2c04db 100644 (file)
@@ -59,8 +59,8 @@ public final class StringTypeEffectiveStatementImpl extends DeclaredEffectiveSta
             typeDefinition = builder.build();
         } catch (InvalidLengthConstraintException e) {
             final LengthConstraint c = e.getOffendingConstraint();
-            throw new SourceException(String.format("Invalid length constraint: <%s, %s>", c.getMin(), c.getMax()),
-                ctx.getStatementSourceReference(), e);
+            throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid length constraint: <%s, %s>",
+                c.getMin(), c.getMax());
         }
     }
 
index 80ed386a63fe91b6517d075aa61672a1aa18d743..cd6e6f5ff5443b3ff75440146cfc8812da1fc510 100644 (file)
@@ -96,8 +96,8 @@ public class YangParserNegativeTest {
         } catch (SomeModifiersUnresolvedException e) {
             final Throwable rootCause = Throwables.getRootCause(e);
             assertTrue(rootCause instanceof InferenceException);
-            assertTrue(rootCause.getMessage().startsWith("Augment target not found: Absolute{path=[(urn:simple" +
-                            ".container.demo?revision=1970-01-01)unknown]}"));
+            assertTrue(rootCause.getMessage().startsWith(
+                "Augment target 'Absolute{path=[(urn:simple.container.demo?revision=1970-01-01)unknown]}' not found"));
         }
     }
 
@@ -151,7 +151,7 @@ public class YangParserNegativeTest {
                 fail("SourceException should be thrown");
             }
         } catch (SourceException e) {
-            String expected = "Error in module 'container': can not add '(urn:simple.container" +
+            String expected = "Error in module 'container': cannot add '(urn:simple.container" +
                     ".demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container" +
                     ".demo?revision=1970-01-01)foo' already declared.";
             assertTrue(e.getMessage().contains(expected));
@@ -167,7 +167,7 @@ public class YangParserNegativeTest {
                 fail("SourceException should be thrown");
             }
         } catch (SourceException e) {
-            String expected = "Error in module 'container-list': can not add '(urn:simple.container" +
+            String expected = "Error in module 'container-list': cannot add '(urn:simple.container" +
                     ".demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container" +
                     ".demo?revision=1970-01-01)foo' already declared.";
             assertTrue(e.getMessage().contains(expected));
@@ -183,7 +183,7 @@ public class YangParserNegativeTest {
                 fail("SourceException should be thrown");
             }
         } catch (SourceException e) {
-            String expected = "Error in module 'container-leaf': can not add '(urn:simple.container" +
+            String expected = "Error in module 'container-leaf': cannot add '(urn:simple.container" +
                     ".demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container" +
                     ".demo?revision=1970-01-01)foo' already declared.";
             assertTrue(e.getMessage().contains(expected));
@@ -199,7 +199,7 @@ public class YangParserNegativeTest {
                 fail("SourceException should be thrown");
             }
         } catch (SourceException e) {
-            String expected = "Error in module 'typedef': can not add '(urn:simple.container" +
+            String expected = "Error in module 'typedef': cannot add '(urn:simple.container" +
                     ".demo?revision=1970-01-01)int-ext'. Node name collision: '(urn:simple.container" +
                     ".demo?revision=1970-01-01)int-ext' already declared.";
             assertTrue(e.getMessage().startsWith(expected));