Bug 4540: Yang parser exceptions should follow consistent path 68/32868/1
authorIgor Foltin <ifoltin@cisco.com>
Wed, 9 Dec 2015 14:27:20 +0000 (15:27 +0100)
committerRobert Varga <nite@hq.sk>
Sat, 16 Jan 2016 11:17:26 +0000 (11:17 +0000)
Replaced FileInputStream with NamedFileInputStream
in order to provide source path.

Replaced several standard Java exceptions with
yang-parser-impl exceptions where appropriate.

Added StatementSourceReference object into error messages.

Code refactoring based on codestyle rules.

Change-Id: I7e0c80d1d1c4644fa8c61a420ba0055ae84d2398
Signed-off-by: Igor Foltin <ifoltin@cisco.com>
(cherry picked from commit afc9771f12441ce707dac07ad282fbbd4022bfb2)

32 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/source/SourceException.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/NamespaceStorageSupport.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/reactor/StatementContextBase.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/StatementContextWriter.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/DeviateStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/FractionDigitsStatementImpl.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/KeyStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/LengthStatementImpl.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/PositionStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/RangeStatementImpl.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/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/Utils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/ValueStatementImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/rfc6020/effective/ChoiceEffectiveStatementImpl.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/ListEffectiveStatementImpl.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/retest/ListKeysTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/retest/ParsingExtensionValueTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/retest/TestUtils.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/retest/YangParserIdentityTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/retest/YangParserNegativeTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/retest/YangParserWithContextTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/test/Bug4410Test.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/test/Bug4933Test.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/stmt/test/SubstatementValidatorTest.java

index 5113e68dfd81c052a97589f545111b527dbd9e23..4ce9bce6499a333fbb6538e611dd97dcff9f342b 100644 (file)
@@ -25,6 +25,7 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
 import org.opendaylight.yangtools.yang.parser.spi.source.DeclarationInTextSource;
 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
+import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
 import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
@@ -155,8 +156,8 @@ public class YinStatementParserImpl {
             } else {
                 //if statement not found through all phases, throw exception
                 if (writer.getPhase().equals(ModelProcessingPhase.FULL_DECLARATION)) {
-                    throw new IllegalArgumentException(identifier.getLocalName() + " is not a YIN " +
-                            "statement or use of extension. Source: " + ref);
+                    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;
index aafaabf146054977eae4bc515460db29e6b91f03..cddfe2df13be8543b121a2a927e5e6aca6636718 100644 (file)
@@ -17,25 +17,29 @@ import javax.annotation.Nonnull;
  */
 public class SourceException extends RuntimeException {
 
-    /**
-     *
-     */
     private static final long serialVersionUID = 1L;
 
     private final StatementSourceReference sourceRef;
 
     public SourceException(@Nonnull String message,@Nonnull StatementSourceReference source) {
-        super(Preconditions.checkNotNull(message));
-        sourceRef = Preconditions.checkNotNull(source);
+        super(createMessage(message, source));
+        sourceRef = source;
     }
 
     public SourceException(@Nonnull String message,@Nonnull StatementSourceReference source, Throwable cause) {
-        super(Preconditions.checkNotNull(message),cause);
-        sourceRef = Preconditions.checkNotNull(source);
+        super(createMessage(message, source), cause);
+        sourceRef = source;
     }
 
     public @Nonnull StatementSourceReference getSourceReference() {
         return sourceRef;
     }
 
+    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);
+    }
+
 }
index 0f9b948496fb372be3ca2e3e2852738e98b34fde..63db5d1c7010c8abe6fdd8028bc9bb3b40d29350 100644 (file)
@@ -38,8 +38,6 @@ abstract class NamespaceStorageSupport implements NamespaceStorageNode {
         // NOOP
     }
 
-    //<K,V,N extends IdentifierNamespace<K, V>> V
-    //public final <K, VT, V extends VT ,N extends IdentifierNamespace<K, V>> VT getFromNamespace(Class<N> type, K key)
     public final <K,V, KT extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(final Class<N> type, final KT key)
             throws NamespaceNotAvailableException {
         return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this,key);
index 64351b8818efafe5e5ba4ea85b4c9c2261ecd774..fb23468d8d3aa2a44b9735b1230ce4ee7b1e28b7 100644 (file)
@@ -94,14 +94,15 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         return currentContext.getStatementDefinition(name);
     }
 
-    ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name, final StatementSourceReference ref) {
+    ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name,
+                                                final StatementSourceReference ref) {
         StatementDefinitionContext<?, ?, ?> def = getDefinition(name);
 
         if (def == null) {
-            //unknown-stmts (from import, include or local-scope)
+            // unknown-stmts (from import, include or local-scope)
             if (qNameToStmtDefMap.get(name) != null) {
-                final StatementContextBase<?, ?, ?> extension = (StatementContextBase<?, ?, ?>) currentContext
-                        .getAllFromNamespace(ExtensionNamespace.class).get(name);
+                    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,
@@ -110,7 +111,8 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
                     def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
                             getNewStatementDefinition(qName)));
                 } else {
-                    throw new IllegalArgumentException("Not found unknown statement: " + name);
+                        throw new SourceException("Extension not found: " + name,
+                                current.getStatementSourceReference());
                 }
             } else {
                 // type-body-stmts
@@ -137,7 +139,8 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     @SuppressWarnings({"rawtypes", "unchecked"})
-    private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def, final StatementSourceReference ref) {
+    private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def,
+                                                       final StatementSourceReference ref) {
         return new ContextBuilder(def, ref) {
 
             @Override
@@ -145,7 +148,8 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
                 if (root == null) {
                     root = new RootStatementContext(this, SourceSpecificContext.this);
                 } else {
-                    Preconditions.checkState(root.getIdentifier().equals(createIdentifier()), "Root statement was already defined as %s.", root.getIdentifier());
+                    Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
+                            "Root statement was already defined as %s.", root.getIdentifier());
                 }
                 root.resetLists();
                 return root;
@@ -167,14 +171,16 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     void startPhase(final ModelProcessingPhase phase) {
-        @Nullable ModelProcessingPhase previousPhase = phase.getPreviousPhase();
+        @Nullable
+        ModelProcessingPhase previousPhase = phase.getPreviousPhase();
         Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
         Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
         inProgressPhase = phase;
     }
 
     @Override
-    public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key, final V value) {
+    public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
+           final V value) {
         if (ImportedNamespaceContext.class.isAssignableFrom(type)) {
             importedNamespaces.add((NamespaceStorageNode) value);
         }
@@ -221,7 +227,8 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     @Override
-    public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(final Class<N> type) {
+    public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
+            final Class<N> type) {
         return currentContext.getNamespaceBehaviour(type);
     }
 
@@ -357,14 +364,14 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     private QNameToStatementDefinition stmtDef() {
-        //regular YANG statements added
+        // regular YANG statements added
         ImmutableMap<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(
                 inProgressPhase).getDefinitions();
         for (Map.Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
             qNameToStmtDefMap.put(entry.getKey(), entry.getValue());
         }
 
-        //extensions added
+        // extensions added
         if (inProgressPhase.equals(ModelProcessingPhase.FULL_DECLARATION)) {
             Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions = currentContext
                     .getAllFromNamespace(ExtensionNamespace.class);
index 59a22343e13743e8d9531faf92dea4059bc94adb..92b2d0bd37c8461dbf6c3ec1412688fe2ed2e9be 100644 (file)
@@ -167,12 +167,13 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     }
 
     StatementContextBase(final StatementContextBase<A, D, E> original) {
-        this.definition = Preconditions
-                .checkNotNull(original.definition, "Statement context definition cannot be null");
-        this.identifier = Preconditions
-                .checkNotNull(original.identifier, "Statement context identifier cannot be null");
+        this.definition = Preconditions.checkNotNull(original.definition,
+                "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
+        this.identifier = Preconditions.checkNotNull(original.identifier,
+                "Statement context identifier cannot be null copying from: %s", original.getStatementSourceReference());
         this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
-                "Statement context statementDeclSource cannot be null");
+                "Statement context statementDeclSource cannot be null copying from: %s",
+                original.getStatementSourceReference());
         this.completedPhase = null;
         this.copyHistory.add(TypeOfCopy.ORIGINAL);
     }
@@ -274,10 +275,10 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
-                "Effective statement cannot be added in declared phase");
+                "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
 
         effective.add(Preconditions.checkNotNull(substatement,
-                "StatementContextBase effective substatement cannot be null"));
+                "StatementContextBase effective substatement cannot be null at: %s", getStatementSourceReference()));
     }
 
     /**
@@ -294,10 +295,10 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
 
         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
-                "Declared statement cannot be added in effective phase");
+                "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
 
         declared.add(Preconditions.checkNotNull(substatement,
-                "StatementContextBase declared substatement cannot be null"));
+                "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
     }
 
     /**
@@ -382,7 +383,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
 
         final SourceSpecificContext sourceContext = getRoot().getSourceContext();
         Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
-                "Declared statements list cannot be cleared in effective phase");
+                "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
 
         declared.clear();
     }
@@ -518,8 +519,10 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      */
     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) throws SourceException {
 
-        Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null");
-        Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null");
+        Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
+                getStatementSourceReference());
+        Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
+                getStatementSourceReference());
 
         ModelProcessingPhase finishedPhase = completedPhase;
         while (finishedPhase != null) {
@@ -542,7 +545,8 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
         ModelProcessingPhase finishedPhase = completedPhase;
         while (finishedPhase != null) {
             if (phase.equals(finishedPhase)) {
-                throw new IllegalStateException("Mutation registered after phase was completed.");
+                throw new IllegalStateException("Mutation registered after phase was completed at: "  +
+                        getStatementSourceReference());
             }
             finishedPhase = finishedPhase.getPreviousPhase();
         }
index 7ad0bae9a76afd4b154c840aba398dd373e7eafe..3f8684e7dba8d52e1bae475b7017188681cd5e33 100644 (file)
@@ -36,7 +36,7 @@ class StatementContextWriter implements StatementWriter {
 
     @Override
     public void argumentValue(String value, StatementSourceReference ref) {
-        Preconditions.checkState(current != null, "Could not set two arguments for one statement.");
+        Preconditions.checkState(current != null, "Could not set two arguments for one statement: %s", ref);
         current.setArgument(value, ref);
     }
 
index bea54a8217a2c50d510ee20b45419dab65e62583..c873ddbfbc6d6bace69312c57c7a08b571a86428 100644 (file)
@@ -18,6 +18,7 @@ import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
+import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.TypeOfCopy;
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
@@ -97,10 +98,10 @@ public final class AugmentUtils {
             for (final StatementContextBase<?, ?, ?> sourceSubStatement : sourceSubStatements) {
                 if (sourceSubStatement.getPublicDefinition().getDeclaredRepresentationClass()
                         .equals(MandatoryStatement.class)) {
-                    throw new IllegalArgumentException(
+                    throw new InferenceException(
                             String.format(
                                     "An augment cannot add node '%s' because it is mandatory and in module different from target",
-                                    sourceCtx.rawStatementArgument()));
+                                    sourceCtx.rawStatementArgument()), sourceCtx.getStatementSourceReference());
                 }
             }
         }
@@ -115,9 +116,9 @@ public final class AugmentUtils {
                     && Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
 
             if (qNamesEqual) {
-                throw new IllegalStateException(String.format(
+                throw new InferenceException(String.format(
                         "An augment cannot add node named '%s' because this name is already used in target",
-                        sourceCtx.rawStatementArgument()));
+                        sourceCtx.rawStatementArgument()), sourceCtx.getStatementSourceReference());
             }
         }
     }
index 6d04cbdad1bb1ecec9a271b5a89ab8f843d4b428..0e0886f729ee2bb3aaa9d92d24607cf8c1926227 100644 (file)
@@ -40,7 +40,8 @@ public class DeviateStatementImpl extends AbstractDeclaredStatement<Deviation.De
         super(context);
     }
 
-    public static class Definition extends AbstractStatementSupport<Deviation.Deviate,DeviateStatement,EffectiveStatement<Deviation.Deviate,DeviateStatement>> {
+    public static class Definition extends AbstractStatementSupport<Deviation.Deviate, DeviateStatement,
+            EffectiveStatement<Deviation.Deviate, DeviateStatement>> {
 
         public Definition() {
             super(Rfc6020Mapping.DEVIATE);
@@ -48,7 +49,7 @@ public class DeviateStatementImpl extends AbstractDeclaredStatement<Deviation.De
 
         @Override public Deviation.Deviate parseArgumentValue(
                 StmtContext<?, ?, ?> ctx, String value) throws SourceException {
-            return Utils.parseDeviateFromString(value);
+            return Utils.parseDeviateFromString(ctx, value);
         }
 
         @Override public DeviateStatement createDeclared(
@@ -57,7 +58,8 @@ public class DeviateStatementImpl extends AbstractDeclaredStatement<Deviation.De
         }
 
         @Override public EffectiveStatement<Deviation.Deviate, DeviateStatement> createEffective(
-                StmtContext<Deviation.Deviate, DeviateStatement, EffectiveStatement<Deviation.Deviate, DeviateStatement>> ctx) {
+                StmtContext<Deviation.Deviate, DeviateStatement, EffectiveStatement<Deviation.Deviate,
+                        DeviateStatement>> ctx) {
             return new DeviateEffectiveStatementImpl(ctx);
         }
 
index ab7413aa82869d87ed0fb73135830e9b8593afbe..1e415ec9b531c6173b167b3ec92034fb4591f855 100644 (file)
@@ -30,9 +30,8 @@ public class FractionDigitsStatementImpl extends AbstractDeclaredStatement<Integ
         super(context);
     }
 
-    public static class Definition
-            extends
-            AbstractStatementSupport<Integer, FractionDigitsStatement, EffectiveStatement<Integer, FractionDigitsStatement>> {
+    public static class Definition extends AbstractStatementSupport<Integer, FractionDigitsStatement,
+            EffectiveStatement<Integer, FractionDigitsStatement>> {
 
         public Definition() {
             super(Rfc6020Mapping.FRACTION_DIGITS);
@@ -46,8 +45,8 @@ public class FractionDigitsStatementImpl extends AbstractDeclaredStatement<Integ
             try {
                 fractionDigits = Integer.parseInt(value);
             } catch (NumberFormatException e) {
-                throw new IllegalArgumentException(String.format("%s is not valid fraction-digits integer argument",
-                        value), e);
+                throw new SourceException(String.format("%s is not valid fraction-digits integer argument",
+                        value), ctx.getStatementSourceReference(), e);
             }
 
             Preconditions.checkArgument(FRAC_DIGITS_ALLOWED.contains(fractionDigits),
index 328f8f243d359396db414b3ae2fdb09e7b3ccab7..e28a1c6bb90d65c0fe337d665cc5b83bd1fdb250 100644 (file)
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
@@ -152,12 +152,13 @@ public final class GroupingUtils {
 
         Object refineArgument = refineCtx.getStatementArgument();
         Preconditions.checkArgument(refineArgument instanceof SchemaNodeIdentifier,
-            "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier", refineArgument);
+            "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier. At %s", refineArgument,
+                refineCtx.getStatementSourceReference());
 
         SchemaNodeIdentifier refineTargetNodeIdentifier = (SchemaNodeIdentifier) refineArgument;
         StatementContextBase<?, ?, ?> refineTargetNodeCtx = Utils.findNode(usesParentCtx, refineTargetNodeIdentifier);
-        Preconditions.checkArgument(refineTargetNodeCtx != null, "Refine target node %s not found.",
-                refineTargetNodeIdentifier);
+        Preconditions.checkArgument(refineTargetNodeCtx != null, "Refine target node %s not found. At %s",
+                refineTargetNodeIdentifier, refineCtx.getStatementSourceReference());
 
         addOrReplaceNodes(refineCtx, refineTargetNodeCtx);
         refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
index 6bb9679a142a265afda926caee7b0b887c12fe76..1ff02358654a87be8e41fb688b7d64f8e8d8be3f 100644 (file)
@@ -35,7 +35,8 @@ public class KeyStatementImpl extends AbstractDeclaredStatement<Collection<Schem
 
     public static class Definition
             extends
-            AbstractStatementSupport<Collection<SchemaNodeIdentifier>, KeyStatement, EffectiveStatement<Collection<SchemaNodeIdentifier>, KeyStatement>> {
+            AbstractStatementSupport<Collection<SchemaNodeIdentifier>, KeyStatement,
+                    EffectiveStatement<Collection<SchemaNodeIdentifier>, KeyStatement>> {
 
         public Definition() {
             super(Rfc6020Mapping.KEY);
@@ -53,7 +54,8 @@ public class KeyStatementImpl extends AbstractDeclaredStatement<Collection<Schem
             // Throws NPE on nulls, retains first inserted value, cannot be modified
             final Collection<SchemaNodeIdentifier> ret = builder.build();
 
-            Preconditions.checkArgument(ret.size() == tokens, "Key argument '%s' contains duplicates", value);
+            Preconditions.checkArgument(ret.size() == tokens, "Key argument '%s' contains duplicates. At %s", value,
+                    ctx.getStatementSourceReference());
             return ret;
         }
 
@@ -64,7 +66,8 @@ public class KeyStatementImpl extends AbstractDeclaredStatement<Collection<Schem
 
         @Override
         public EffectiveStatement<Collection<SchemaNodeIdentifier>, KeyStatement> createEffective(
-                final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, EffectiveStatement<Collection<SchemaNodeIdentifier>, KeyStatement>> ctx) {
+                final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement,
+                        EffectiveStatement<Collection<SchemaNodeIdentifier>, KeyStatement>> ctx) {
             return new KeyEffectiveStatementImpl(ctx);
         }
 
index 24b8d6c02c5158b2f587238f5386615be905be7c..0df10da9592f32c9e6f911b85c1b128cc8487ed2 100644 (file)
@@ -36,9 +36,8 @@ public class LengthStatementImpl extends AbstractDeclaredStatement<List<LengthCo
         super(context);
     }
 
-    public static class Definition
-            extends
-            AbstractStatementSupport<List<LengthConstraint>, LengthStatement, EffectiveStatement<List<LengthConstraint>, LengthStatement>> {
+    public static class Definition extends AbstractStatementSupport<List<LengthConstraint>, LengthStatement,
+            EffectiveStatement<List<LengthConstraint>, LengthStatement>> {
 
         public Definition() {
             super(Rfc6020Mapping.LENGTH);
@@ -46,7 +45,7 @@ public class LengthStatementImpl extends AbstractDeclaredStatement<List<LengthCo
 
         @Override
         public List<LengthConstraint> parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
-            return TypeUtils.parseLengthListFromString(value);
+            return TypeUtils.parseLengthListFromString(ctx, value);
         }
 
         @Override
@@ -56,7 +55,8 @@ public class LengthStatementImpl extends AbstractDeclaredStatement<List<LengthCo
 
         @Override
         public EffectiveStatement<List<LengthConstraint>, LengthStatement> createEffective(
-                StmtContext<List<LengthConstraint>, LengthStatement, EffectiveStatement<List<LengthConstraint>, LengthStatement>> ctx) {
+                StmtContext<List<LengthConstraint>, LengthStatement, EffectiveStatement<List<LengthConstraint>,
+                        LengthStatement>> ctx) {
             return new LengthEffectiveStatementImpl(ctx);
         }
 
index a6e5f0c0bd711b652915b168bb4529db37111cd6..ea6d565b895288b891582df87ec952ac5d7e319f 100644 (file)
@@ -97,8 +97,8 @@ public class ModuleStatementSupport extends
         Optional<URI> moduleNs = Optional.fromNullable(firstAttributeOf(stmt.declaredSubstatements(),
                 NamespaceStatement.class));
         if (!moduleNs.isPresent()) {
-            throw new IllegalArgumentException("Namespace of the module [" + stmt.getStatementArgument()
-                    + "] is missing.");
+            throw new SourceException(String.format("Namespace of the module [%s] is missing",
+                    stmt.getStatementArgument()), stmt.getStatementSourceReference());
         }
 
         Optional<Date> revisionDate = Optional.fromNullable(Utils.getLatestRevision(stmt.declaredSubstatements()));
@@ -116,7 +116,8 @@ public class ModuleStatementSupport extends
 
         String modulePrefix = firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class);
         if (modulePrefix == null) {
-            throw new IllegalArgumentException("Prefix of the module [" + stmt.getStatementArgument() + "] is missing.");
+            throw new SourceException(String.format("Prefix of the module [%s] is missing",
+                    stmt.getStatementArgument()), stmt.getStatementSourceReference());
         }
 
         stmt.addToNs(PrefixToModule.class, modulePrefix, qNameModule);
index c0d47f52f691942e671b086053925c0a5b21ed41..474fbb04b4afdbcc6c7ed8bcea317b5dc7556ba4 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 
+import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.PositionStatement;
@@ -24,9 +25,8 @@ public class PositionStatementImpl extends AbstractDeclaredStatement<Long> imple
         super(context);
     }
 
-    public static class Definition
-            extends
-            AbstractStatementSupport<Long, PositionStatement, EffectiveStatement<Long, PositionStatement>> {
+    public static class Definition extends AbstractStatementSupport<Long, PositionStatement,
+            EffectiveStatement<Long, PositionStatement>> {
 
         public Definition() {
             super(Rfc6020Mapping.POSITION);
@@ -37,7 +37,8 @@ public class PositionStatementImpl extends AbstractDeclaredStatement<Long> imple
             try {
                 return Long.parseLong(value);
             } catch (NumberFormatException e) {
-                throw new IllegalArgumentException(String.format("Position value %s is not valid integer", value), e);
+                throw new SourceException(String.format("Bit position value %s is not valid integer", value),
+                        ctx.getStatementSourceReference(), e);
             }
         }
 
index 21b13682a28ab2f866af68245a5bc52120189947..7e1bf0ad6e82685fe8fd8cdf0e4a436e7bd22320 100644 (file)
@@ -42,9 +42,8 @@ public class RangeStatementImpl extends AbstractDeclaredStatement<List<RangeCons
         super(context);
     }
 
-    public static class Definition
-            extends
-            AbstractStatementSupport<List<RangeConstraint>, RangeStatement, EffectiveStatement<List<RangeConstraint>, RangeStatement>> {
+    public static class Definition extends AbstractStatementSupport<List<RangeConstraint>, RangeStatement,
+            EffectiveStatement<List<RangeConstraint>, RangeStatement>> {
 
         public Definition() {
             super(Rfc6020Mapping.RANGE);
@@ -52,7 +51,7 @@ public class RangeStatementImpl extends AbstractDeclaredStatement<List<RangeCons
 
         @Override
         public List<RangeConstraint> parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
-            return TypeUtils.parseRangeListFromString(value);
+            return TypeUtils.parseRangeListFromString(ctx, value);
         }
 
         @Override
@@ -62,7 +61,8 @@ public class RangeStatementImpl extends AbstractDeclaredStatement<List<RangeCons
 
         @Override
         public EffectiveStatement<List<RangeConstraint>, RangeStatement> createEffective(
-                StmtContext<List<RangeConstraint>, RangeStatement, EffectiveStatement<List<RangeConstraint>, RangeStatement>> ctx) {
+                StmtContext<List<RangeConstraint>, RangeStatement, EffectiveStatement<List<RangeConstraint>,
+                        RangeStatement>> ctx) {
             return new RangeEffectiveStatementImpl(ctx);
         }
 
index eab3ce3436afdb576261ff8be03290ae51dbf350..41c0a5343d448faf0b6ab2a50a6e43b1c3d05494 100644 (file)
@@ -32,8 +32,7 @@ import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModule
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.SubmoduleEffectiveStatementImpl;
 
-public class SubmoduleStatementImpl extends
-        AbstractRootStatement<SubmoduleStatement> implements SubmoduleStatement {
+public class SubmoduleStatementImpl extends AbstractRootStatement<SubmoduleStatement> implements SubmoduleStatement {
     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
             .SUBMODULE)
             .add(Rfc6020Mapping.ANYXML, 0, MAX)
@@ -63,14 +62,12 @@ public class SubmoduleStatementImpl extends
             .add(Rfc6020Mapping.YANG_VERSION, 0, 1)
             .build();
 
-    protected SubmoduleStatementImpl(
-            StmtContext<String, SubmoduleStatement, ?> context) {
+    protected SubmoduleStatementImpl(StmtContext<String, SubmoduleStatement, ?> context) {
         super(context);
     }
 
-    public static class Definition
-            extends
-            AbstractStatementSupport<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> {
+    public static class Definition extends AbstractStatementSupport<String, SubmoduleStatement,
+            EffectiveStatement<String, SubmoduleStatement>> {
 
         public Definition() {
             super(Rfc6020Mapping.SUBMODULE);
@@ -115,9 +112,8 @@ public class SubmoduleStatementImpl extends
                     stmt, 0, BelongsToStatement.class, PrefixStatement.class);
 
             if (prefixSubStmtCtx == null) {
-                throw new IllegalArgumentException(
-                        "Prefix of belongsTo statement is missing in submodule ["
-                                + stmt.getStatementArgument() + "].");
+                throw new SourceException(String.format("Prefix of belongsTo statement is missing in submodule [%s]",
+                        stmt.getStatementArgument()), stmt.getStatementSourceReference());
             }
 
             String prefix = (String) prefixSubStmtCtx.getStatementArgument();
index 9b9683d41c34d0cd828112daea6bc7b647c75b62..3aee37027267ebd1a1e1c8f3e7db7d3bb1b1d355 100644 (file)
@@ -23,8 +23,10 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 import org.opendaylight.yangtools.yang.model.util.UnresolvedNumber;
+import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
 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.type.LengthConstraintEffectiveImpl;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.type.RangeConstraintEffectiveImpl;
 
@@ -84,7 +86,7 @@ public final class TypeUtils {
         return new BigDecimal(num1.toString()).compareTo(new BigDecimal(num2.toString()));
     }
 
-    private static Number parseIntegerConstraintValue(final String value) {
+    private static Number parseIntegerConstraintValue(final StmtContext<?, ?, ?> ctx, final String value) {
         if ("max".equals(value)) {
             return UnresolvedNumber.max();
         }
@@ -95,11 +97,12 @@ public final class TypeUtils {
         try {
             return new BigInteger(value);
         } catch (NumberFormatException e) {
-            throw new IllegalArgumentException(String.format("Value %s is not a valid integer", value), e);
+            throw new SourceException(String.format("Value %s is not a valid integer", value),
+                    ctx.getStatementSourceReference(), e);
         }
     }
 
-    private static Number parseDecimalConstraintValue(final String value) {
+    private static Number parseDecimalConstraintValue(final StmtContext<?, ?, ?> ctx, final String value) {
         if ("max".equals(value)) {
             return UnresolvedNumber.max();
         }
@@ -110,11 +113,13 @@ public final class TypeUtils {
         try {
             return value.indexOf('.') != -1 ? new BigDecimal(value) : new BigInteger(value);
         } catch (NumberFormatException e) {
-            throw new IllegalArgumentException(String.format("Value %s is not a valid decimal number", value), e);
+            throw new SourceException(String.format("Value %s is not a valid decimal number", value),
+                    ctx.getStatementSourceReference(), e);
         }
     }
 
-    public static List<RangeConstraint> parseRangeListFromString(final String rangeArgument) {
+    public static List<RangeConstraint> parseRangeListFromString(final StmtContext<?, ?, ?> ctx,
+                                                                 final String rangeArgument) {
 
         Optional<String> description = Optional.absent();
         Optional<String> reference = Optional.absent();
@@ -123,19 +128,21 @@ public final class TypeUtils {
 
         for (final String singleRange : PIPE_SPLITTER.split(rangeArgument)) {
             final Iterator<String> boundaries = TWO_DOTS_SPLITTER.splitToList(singleRange).iterator();
-            final Number min = parseDecimalConstraintValue(boundaries.next());
+            final Number min = parseDecimalConstraintValue(ctx, boundaries.next());
 
             final Number max;
             if (boundaries.hasNext()) {
-                max = parseDecimalConstraintValue(boundaries.next());
+                max = parseDecimalConstraintValue(ctx, boundaries.next());
 
                 // if min larger than max then error
                 if (compareNumbers(min, max) == 1) {
-                    throw new IllegalArgumentException(String.format(
-                            "Range constraint %s has descending order of boundaries; should be ascending", singleRange));
+                    throw new InferenceException(String.format(
+                            "Range constraint %s has descending order of boundaries; should be ascending",
+                            singleRange), ctx.getStatementSourceReference());
                 }
                 if (boundaries.hasNext()) {
-                    throw new IllegalArgumentException("Wrong number of boundaries in range constraint " + singleRange);
+                    throw new SourceException(String.format("Wrong number of boundaries in range constraint %s",
+                            singleRange), ctx.getStatementSourceReference());
                 }
             } else {
                 max = min;
@@ -143,8 +150,8 @@ public final class TypeUtils {
 
             // some of intervals overlapping
             if (rangeConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(rangeConstraints).getMax()) != 1) {
-                throw new IllegalArgumentException(String.format("Some of the ranges in %s are not disjoint",
-                        rangeArgument));
+                throw new InferenceException(String.format("Some of the ranges in %s are not disjoint",
+                        rangeArgument), ctx.getStatementSourceReference());
             }
 
             rangeConstraints.add(new RangeConstraintEffectiveImpl(min, max, description, reference));
@@ -153,8 +160,8 @@ public final class TypeUtils {
         return rangeConstraints;
     }
 
-    public static List<LengthConstraint> parseLengthListFromString(final String rangeArgument) {
-
+    public static List<LengthConstraint> parseLengthListFromString(final StmtContext<?, ?, ?> ctx,
+            final String rangeArgument) {
         Optional<String> description = Optional.absent();
         Optional<String> reference = Optional.absent();
 
@@ -162,25 +169,27 @@ public final class TypeUtils {
 
         for (final String singleRange : PIPE_SPLITTER.split(rangeArgument)) {
             final Iterator<String> boundaries = TWO_DOTS_SPLITTER.splitToList(singleRange).iterator();
-            final Number min = parseIntegerConstraintValue(boundaries.next());
+            final Number min = parseIntegerConstraintValue(ctx, boundaries.next());
 
             final Number max;
             if (boundaries.hasNext()) {
-                max = parseIntegerConstraintValue(boundaries.next());
+                max = parseIntegerConstraintValue(ctx, boundaries.next());
 
                 // if min larger than max then error
                 Preconditions.checkArgument(compareNumbers(min, max) != 1,
-                        "Length constraint %s has descending order of boundaries; should be ascending", singleRange);
-                Preconditions.checkArgument(!boundaries.hasNext(), "Wrong number of boundaries in length constraint %s",
-                        singleRange);
+                        "Length constraint %s has descending order of boundaries; should be ascending. Statement source at %s",
+                        singleRange, ctx.getStatementSourceReference());
+                Preconditions.checkArgument(!boundaries.hasNext(),
+                        "Wrong number of boundaries in length constraint %s. Statement source at %s", singleRange,
+                        ctx.getStatementSourceReference());
             } else {
                 max = min;
             }
 
             // some of intervals overlapping
             if (rangeConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(rangeConstraints).getMax()) != 1) {
-                throw new IllegalArgumentException(String.format("Some of the length ranges in %s are not disjoint",
-                        rangeArgument));
+                throw new InferenceException(String.format("Some of the length ranges in %s are not disjoint",
+                        rangeArgument), ctx.getStatementSourceReference());
             }
 
             rangeConstraints.add(new LengthConstraintEffectiveImpl(min, max, description, reference));
index 3c06831867649a2fc8d00b0bcc082c9581f9b817..9d3fb3ef1ad936c0e8084c85d8860238852689d3 100644 (file)
@@ -69,8 +69,8 @@ public class TypedefStatementImpl extends AbstractDeclaredStatement<QName> imple
                 throws SourceException {
             if (stmt != null && stmt.getParentContext() != null) {
                 if (stmt.getParentContext().getFromNamespace(TypeNamespace.class, stmt.getStatementArgument()) != null) {
-                    throw new IllegalArgumentException(String.format("Duplicate name for typedef %s",
-                            stmt.getStatementArgument()));
+                    throw new SourceException(String.format("Duplicate name for typedef %s",
+                            stmt.getStatementArgument()), stmt.getStatementSourceReference());
                 }
 
                 stmt.getParentContext().addContext(TypeNamespace.class, stmt.getStatementArgument(), stmt);
index 03996c932904314dd31dc1631547c4f09d5f1c74..f0e6abf83509fc69c87570c2883522714b7a8bb6 100644 (file)
@@ -55,6 +55,7 @@ import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModul
 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
+import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -102,7 +103,8 @@ public final class Utils {
         // to detect if key contains duplicates
         if ((new HashSet<>(keyTokens)).size() < keyTokens.size()) {
             // FIXME: report all duplicate keys
-            throw new IllegalArgumentException();
+            throw new SourceException(String.format("Duplicate value in list key: %s", value),
+                    ctx.getStatementSourceReference());
         }
 
         Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
@@ -253,8 +255,9 @@ public final class Utils {
             break;
         }
 
-        Preconditions.checkArgument(qNameModule != null, "Error in module '%s': can not resolve QNameModule for '%s'.",
-                ctx.getRoot().rawStatementArgument(), value);
+        Preconditions.checkArgument(qNameModule != null,
+                "Error in module '%s': can not resolve QNameModule for '%s'. Statement source at %s",
+                ctx.getRoot().rawStatementArgument(), value, ctx.getStatementSourceReference());
         final QNameModule resultQNameModule;
         if (qNameModule.getRevision() == null) {
             resultQNameModule = QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV)
@@ -313,9 +316,10 @@ public final class Utils {
                 .isAssignableFrom(UnknownStatementImpl.class);
     }
 
-    public static Deviation.Deviate parseDeviateFromString(final String deviateKeyword) {
+    public static Deviation.Deviate parseDeviateFromString(final StmtContext<?, ?, ?> ctx, final String deviateKeyword) {
         return Preconditions.checkNotNull(KEYWORD_TO_DEVIATE_MAP.get(deviateKeyword),
-                "String '%s' is not valid deviate argument", deviateKeyword);
+                "String '%s' is not valid deviate argument. Statement source at %s", deviateKeyword,
+                ctx.getStatementSourceReference());
     }
 
     public static Status parseStatus(final String value) {
index f9fbff197af52d12bd03622cf36cdbce5cc86a6b..6f78b55963c722ae673cab195acddfb862b79401 100644 (file)
@@ -14,6 +14,7 @@ import org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator;
 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
 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.ValueEffectiveStatementImpl;
 
 public class ValueStatementImpl extends AbstractDeclaredStatement<Integer> implements ValueStatement {
@@ -38,10 +39,9 @@ public class ValueStatementImpl extends AbstractDeclaredStatement<Integer> imple
             try {
                 valueNum = Integer.parseInt(value);
             } catch (NumberFormatException e) {
-                throw new IllegalArgumentException(
-                        String.format(
-                                "%s is not valid value statement integer argument in a range of -2147483648..2147483647",
-                                value), e);
+                throw new SourceException(String.format(
+                        "%s is not valid value statement integer argument in a range of -2147483648..2147483647", value),
+                        ctx.getStatementSourceReference(), e);
             }
 
             return valueNum;
index 82435f3c4f613288a985f422c4ee40b6743086c8..03fde57ee243baae7c91f5b6d64f0483fbb23fdf 100644 (file)
@@ -12,6 +12,7 @@ import java.util.Objects;
 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
 import org.opendaylight.yangtools.yang.model.api.stmt.ImportStatement;
+import org.opendaylight.yangtools.yang.parser.spi.meta.MissingSubstatementException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 
 public class ImportEffectiveStatementImpl extends DeclaredEffectiveStatementBase<String, ImportStatement> implements
@@ -33,7 +34,8 @@ public class ImportEffectiveStatementImpl extends DeclaredEffectiveStatementBase
         if (prefixStmt != null ) {
             this.prefix = prefixStmt.argument();
         } else {
-            throw new IllegalStateException("Prefix is mandatory substatement of import statement");
+            throw new MissingSubstatementException("Prefix is mandatory substatement of import statement",
+                    ctx.getStatementSourceReference());
         }
     }
 
index 8ac81815b82e35c192b609860e866efe30c67d88..cb6166415ae98803c26f1ac579a8de732a393a59 100644 (file)
@@ -22,6 +22,7 @@ import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.ListStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
+import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 
 public final class ListEffectiveStatementImpl extends AbstractEffectiveSimpleDataNodeContainer<ListStatement> implements
@@ -63,9 +64,9 @@ public final class ListEffectiveStatementImpl extends AbstractEffectiveSimpleDat
                 final QName keyQName = key.getLastComponent();
 
                 if (!possibleLeafQNamesForKey.contains(keyQName)) {
-                    throw new IllegalArgumentException(String.format("Key '%s' misses node '%s' in list '%s', file %s",
+                    throw new InferenceException(String.format("Key '%s' misses node '%s' in list '%s'",
                             keyEffectiveSubstatement.getDeclared().rawArgument(), keyQName.getLocalName(),
-                            ctx.getStatementArgument(), ctx.getStatementSourceReference()));
+                            ctx.getStatementArgument()), ctx.getStatementSourceReference());
                 }
 
                 keyDefinitionInit.add(keyQName);
index 7cdbb128a74ca6f52a7ffb0661d69dc6cb57bd41..9183fae91503ac95e3af1139c41ebc00f7f147f2 100644 (file)
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
@@ -15,6 +15,7 @@ import java.io.IOException;
 import java.net.URISyntaxException;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
+import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
@@ -49,7 +50,7 @@ public class ListKeysTest {
             reactor.buildEffective();
             fail("effective build should fail due to list instead of leaf referenced in list key");
         } catch (Exception e) {
-            assertEquals(IllegalArgumentException.class, e.getClass());
+            assertEquals(InferenceException.class, e.getClass());
             assertTrue(e.getMessage().startsWith("Key 'test1_key1 test1_key2' misses node 'test1_key2'"));
         }
     }
@@ -67,7 +68,7 @@ public class ListKeysTest {
             reactor.buildEffective();
             fail("effective build should fail due to missing leaf referenced in list key");
         } catch (Exception e) {
-            assertEquals(IllegalArgumentException.class, e.getClass());
+            assertEquals(InferenceException.class, e.getClass());
             assertTrue(e.getMessage().startsWith("Key 'test1_key1 test1_key2' misses node 'test1_key2'"));
         }
     }
@@ -85,7 +86,7 @@ public class ListKeysTest {
             reactor.buildEffective();
             fail("effective build should fail due to list instead of leaf in grouping referenced in list key");
         } catch (Exception e) {
-            assertEquals(IllegalArgumentException.class, e.getClass());
+            assertEquals(InferenceException.class, e.getClass());
             assertTrue(e.getMessage().startsWith("Key 'grp_list' misses node 'grp_list'"));
         }
     }
@@ -101,14 +102,16 @@ public class ListKeysTest {
 
         try {
             reactor.buildEffective();
-            fail("effective build should fail due to list instead of leaf in grouping augmented to list referenced in list key");
+            fail("effective build should fail due to list instead of leaf in grouping augmented to list referenced " +
+                    "in list key");
         } catch (Exception e) {
-            assertEquals(IllegalArgumentException.class, e.getClass());
+            assertEquals(InferenceException.class, e.getClass());
             assertTrue(e.getMessage().startsWith("Key 'grp_leaf' misses node 'grp_leaf'"));
         }
     }
 
-    private static void addSources(final CrossSourceStatementReactor.BuildAction reactor, final YangStatementSourceImpl... sources) {
+    private static void addSources(final CrossSourceStatementReactor.BuildAction reactor,
+                                   final YangStatementSourceImpl... sources) {
         for (YangStatementSourceImpl source : sources) {
             reactor.addSource(source);
         }
index f2db310aa41c33829ac8b76f6337ea9d61c82d1d..5ecd311caaa91ce2088467f35a04c19b3b932cde 100644 (file)
@@ -10,12 +10,7 @@ package org.opendaylight.yangtools.yang.stmt.retest;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Set;
-import org.junit.Before;
 import org.junit.Test;
-import org.opendaylight.yangtools.yang.model.api.Module;
 
 /**
  * Test for testing of extensions and their arguments.
@@ -24,23 +19,13 @@ import org.opendaylight.yangtools.yang.model.api.Module;
  */
 public class ParsingExtensionValueTest {
 
-    private Set<Module> modules;
-
-    @Before
-    public void init() throws Exception {
-        //TODO: change test or create new module in order to respect new statement parser validations
-        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
-
+    @Test
+    public void extensionTest() throws Exception {
         try {
-            modules = TestUtils.loadModules(getClass().getResource("/extensions").toURI());
+            TestUtils.loadModules(getClass().getResource("/extensions").toURI());
         } catch (Exception e) {
             assertEquals(IllegalArgumentException.class, e.getClass());
             assertTrue(e.getMessage().startsWith("ext:id is not a YANG statement or use of extension"));
         }
     }
-
-    @Test
-    public void parsingExtensionArgsTest() {
-
-    }
 }
index 13b9aba8127a335d44e55039e8cfbb8e517dc1af..50af9ba031315e4a8ab4a472e4e6eda8a62889cc 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.yangtools.yang.stmt.retest;
 
 import static org.junit.Assert.assertEquals;
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.InputStream;
 import java.net.URI;
@@ -42,6 +41,7 @@ import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YinStatementSourceImpl;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
+import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
 import org.opendaylight.yangtools.yang.stmt.test.StmtTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -268,8 +268,7 @@ public final class TestUtils {
         StatementStreamSource[] sources = new StatementStreamSource[files.length];
 
         for (int i = 0; i < files.length; i++) {
-            sources[i] = new YangStatementSourceImpl(new FileInputStream(
-                    files[i]));
+            sources[i] = new YangStatementSourceImpl(new NamedFileInputStream(files[i], files[i].getPath()));
         }
 
         return parseYangSources(sources);
@@ -302,8 +301,8 @@ public final class TestUtils {
         return parseYangSources(testSourcesFile);
     }
 
-    private static void addYinSources(final CrossSourceStatementReactor.BuildAction reactor, final YinStatementSourceImpl...
-            sources) {
+    private static void addYinSources(final CrossSourceStatementReactor.BuildAction reactor,
+                                      final YinStatementSourceImpl... sources) {
         for (YinStatementSourceImpl source : sources) {
             reactor.addSource(source);
         }
index 5021e89e921f23d85df08d14e6ce36c65deb1c85..662022dbabc22114e2e20f5783daa83043067825 100644 (file)
@@ -1,9 +1,16 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
 package org.opendaylight.yangtools.yang.stmt.retest;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotEquals;
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.InputStream;
 import java.net.URISyntaxException;
@@ -13,6 +20,7 @@ import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
+import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
 import org.opendaylight.yangtools.yang.stmt.test.StmtTestUtils;
 
 public class YangParserIdentityTest {
@@ -22,7 +30,7 @@ public class YangParserIdentityTest {
     public void testParsingIdentityTestModule() throws URISyntaxException,
             ReactorException, FileNotFoundException {
         File yang = new File(getClass().getResource("/identity/identitytest.yang").toURI());
-        InputStream stream = new FileInputStream(yang);
+        InputStream stream = new NamedFileInputStream(yang, yang.getPath());
         try {
             TestUtils.loadModule(stream);
         } catch (SomeModifiersUnresolvedException e) {
@@ -36,7 +44,7 @@ public class YangParserIdentityTest {
     public void testParsingPrefixIdentityTestModule() throws URISyntaxException,
             ReactorException, FileNotFoundException {
         File yang = new File(getClass().getResource("/identity/prefixidentitytest.yang").toURI());
-        InputStream stream = new FileInputStream(yang);
+        InputStream stream = new NamedFileInputStream(yang, yang.getPath());
         try {
             TestUtils.loadModule(stream);
         } catch (SomeModifiersUnresolvedException e) {
index aa214a1c99eb8536af75ab5fcf54cdbf9a1c6987..80ed386a63fe91b6517d075aa61672a1aa18d743 100644 (file)
@@ -11,27 +11,46 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import com.google.common.base.Throwables;
+import java.io.ByteArrayOutputStream;
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.InputStream;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import org.junit.After;
+import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
+import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
 
 public class YangParserNegativeTest {
 
+    private final PrintStream stdout = System.out;
+    private final ByteArrayOutputStream output = new ByteArrayOutputStream();
+    private String testLog;
+
+    @Before
+    public void setUp() throws UnsupportedEncodingException {
+        System.setOut(new PrintStream(output, true, "UTF-8"));
+    }
+
+    @After
+    public void cleanUp() {
+        System.setOut(stdout);
+    }
+
     @Test
     public void testInvalidImport() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/testfile1.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
                 fail("SomeModifiersUnresolvedException should be thrown");
             }
@@ -39,7 +58,7 @@ public class YangParserNegativeTest {
             Throwable rootCause = Throwables.getRootCause(e);
             assertTrue(rootCause instanceof InferenceException);
             assertTrue(rootCause.getMessage().startsWith("Imported module"));
-            assertTrue(rootCause.getMessage().endsWith("was not found."));
+            assertTrue(rootCause.getMessage().contains("was not found."));
         }
     }
 
@@ -47,9 +66,9 @@ public class YangParserNegativeTest {
     public void testTypeNotFound() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/testfile2.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
-                fail("IllegalArgumentException should be thrown");
+                fail("InferenceException should be thrown");
             }
         } catch (SomeModifiersUnresolvedException e) {
             Throwable rootCause = Throwables.getRootCause(e);
@@ -65,9 +84,9 @@ public class YangParserNegativeTest {
         File yang2 = new File(getClass().getResource("/negative-scenario/testfile3.yang").toURI());
         try {
             final List<InputStream> streams = new ArrayList<>(2);
-            try (InputStream testFile0 = new FileInputStream(yang1)) {
+            try (InputStream testFile0 = new NamedFileInputStream(yang1, yang1.getPath())) {
                 streams.add(testFile0);
-                try (InputStream testFile3 = new FileInputStream(yang2)) {
+                try (InputStream testFile3 = new NamedFileInputStream(yang2, yang2.getPath())) {
                     streams.add(testFile3);
                     assertEquals("Expected loaded files count is 2", 2, streams.size());
                     TestUtils.loadModules(streams);
@@ -77,9 +96,8 @@ public class YangParserNegativeTest {
         } catch (SomeModifiersUnresolvedException e) {
             final Throwable rootCause = Throwables.getRootCause(e);
             assertTrue(rootCause instanceof InferenceException);
-            assertEquals(
-                    "Augment target not found: Absolute{path=[(urn:simple.container.demo?revision=1970-01-01)unknown]}",
-                    rootCause.getMessage());
+            assertTrue(rootCause.getMessage().startsWith("Augment target not found: Absolute{path=[(urn:simple" +
+                            ".container.demo?revision=1970-01-01)unknown]}"));
         }
     }
 
@@ -87,15 +105,14 @@ public class YangParserNegativeTest {
     public void testInvalidRefine() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/testfile4.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
                 fail("SourceException should be thrown");
             }
         } catch (SourceException e) {
-            assertTrue(e
-                    .getMessage()
-                    .contains(
-                            "Error in module 'test4' in the refine of uses 'Relative{path=[(urn:simple.container.demo?revision=1970-01-01)node]}': can not perform refine of 'PRESENCE' for the target 'LEAF_LIST'."));
+            assertTrue(e.getMessage().contains("Error in module 'test4' in the refine of uses 'Relative{path=[" +
+                    "(urn:simple.container.demo?revision=1970-01-01)node]}': can not perform refine of 'PRESENCE' for" +
+                    " the target 'LEAF_LIST'."));
         }
     }
 
@@ -103,7 +120,7 @@ public class YangParserNegativeTest {
     public void testInvalidLength() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/testfile5.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
                 fail("YangParseException should be thrown");
             }
@@ -116,7 +133,7 @@ public class YangParserNegativeTest {
     public void testInvalidRange() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/testfile6.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
                 fail("Exception should be thrown");
             }
@@ -129,13 +146,15 @@ public class YangParserNegativeTest {
     public void testDuplicateContainer() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/duplicity/container.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
                 fail("SourceException should be thrown");
             }
         } catch (SourceException e) {
-            String expected = "Error in module 'container': can not add '(urn:simple.container.demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container.demo?revision=1970-01-01)foo' already declared.";
-            assertEquals(expected, e.getMessage());
+            String expected = "Error in module 'container': can not 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));
         }
     }
 
@@ -143,13 +162,15 @@ public class YangParserNegativeTest {
     public void testDuplicateContainerList() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/duplicity/container-list.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
                 fail("SourceException should be thrown");
             }
         } catch (SourceException e) {
-            String expected = "Error in module 'container-list': can not add '(urn:simple.container.demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container.demo?revision=1970-01-01)foo' already declared.";
-            assertEquals(expected, e.getMessage());
+            String expected = "Error in module 'container-list': can not 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));
         }
     }
 
@@ -157,13 +178,15 @@ public class YangParserNegativeTest {
     public void testDuplicateContainerLeaf() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/duplicity/container-leaf.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
                 fail("SourceException should be thrown");
             }
         } catch (SourceException e) {
-            String expected = "Error in module 'container-leaf': can not add '(urn:simple.container.demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container.demo?revision=1970-01-01)foo' already declared.";
-            assertEquals(expected, e.getMessage());
+            String expected = "Error in module 'container-leaf': can not 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));
         }
     }
 
@@ -171,13 +194,15 @@ public class YangParserNegativeTest {
     public void testDuplicateTypedef() throws Exception {
         File yang = new File(getClass().getResource("/negative-scenario/duplicity/typedef.yang").toURI());
         try {
-            try (InputStream stream = new FileInputStream(yang)) {
+            try (InputStream stream = new NamedFileInputStream(yang, yang.getPath())) {
                 TestUtils.loadModule(stream);
-                fail("IllegalArgumentException should be thrown");
+                fail("SourceException should be thrown");
             }
-        } catch (IllegalArgumentException e) {
-            String expected = "Duplicate name for typedef (urn:simple.container.demo?revision=1970-01-01)int-ext";
-            assertEquals(expected, e.getMessage());
+        } catch (SourceException e) {
+            String expected = "Error in module 'typedef': can not 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));
         }
     }
 
@@ -185,14 +210,11 @@ public class YangParserNegativeTest {
     public void testDuplicityInAugmentTarget1() throws Exception {
         File yang1 = new File(getClass().getResource("/negative-scenario/duplicity/augment0.yang").toURI());
         File yang2 = new File(getClass().getResource("/negative-scenario/duplicity/augment1.yang").toURI());
-        try {
-            try (InputStream stream1 = new FileInputStream(yang1); InputStream stream2 = new FileInputStream(yang2)) {
-                TestUtils.loadModules(Arrays.asList(stream1, stream2));
-                fail("IllegalStateException should be thrown");
-            }
-        } catch (IllegalStateException e) {
-            assertEquals(e.getMessage(),
-                    "An augment cannot add node named 'id' because this name is already used in target");
+        try (InputStream stream1 = new NamedFileInputStream(yang1, yang1.getPath());
+            InputStream stream2 = new NamedFileInputStream(yang2, yang2.getPath())) {
+            TestUtils.loadModules(Arrays.asList(stream1, stream2));
+            testLog = output.toString();
+            assertTrue(testLog.contains("An augment cannot add node named 'id' because this name is already used in target"));
         }
     }
 
@@ -200,14 +222,11 @@ public class YangParserNegativeTest {
     public void testDuplicityInAugmentTarget2() throws Exception {
         File yang1 = new File(getClass().getResource("/negative-scenario/duplicity/augment0.yang").toURI());
         File yang2 = new File(getClass().getResource("/negative-scenario/duplicity/augment2.yang").toURI());
-        try {
-            try (InputStream stream1 = new FileInputStream(yang1); InputStream stream2 = new FileInputStream(yang2)) {
-                TestUtils.loadModules(Arrays.asList(stream1, stream2));
-                fail("IllegalStateException should be thrown");
-            }
-        } catch (IllegalStateException e) {
-            assertEquals(e.getMessage(),
-                    "An augment cannot add node named 'delta' because this name is already used in target");
+        try (InputStream stream1 = new NamedFileInputStream(yang1, yang1.getPath());
+             InputStream stream2 = new NamedFileInputStream(yang2, yang2.getPath())) {
+            TestUtils.loadModules(Arrays.asList(stream1, stream2));
+            testLog = output.toString();
+            assertTrue(testLog.contains("An augment cannot add node named 'delta' because this name is already used in target"));
         }
     }
 
@@ -215,14 +234,12 @@ public class YangParserNegativeTest {
     public void testMandatoryInAugment() throws Exception {
         File yang1 = new File(getClass().getResource("/negative-scenario/testfile8.yang").toURI());
         File yang2 = new File(getClass().getResource("/negative-scenario/testfile7.yang").toURI());
-        try {
-            try (InputStream stream1 = new FileInputStream(yang1); InputStream stream2 = new FileInputStream(yang2)) {
-                TestUtils.loadModules(Arrays.asList(stream1, stream2));
-                fail("IllegalArgumentException should be thrown");
-            }
-        } catch (IllegalArgumentException e) {
-            String expected = "An augment cannot add node 'linkleaf' because it is mandatory and in module different from target";
-            assertEquals(expected, e.getMessage());
+        try (InputStream stream1 = new NamedFileInputStream(yang1, yang1.getPath());
+             InputStream stream2 = new NamedFileInputStream(yang2, yang2.getPath())) {
+            TestUtils.loadModules(Arrays.asList(stream1, stream2));
+            testLog = output.toString();
+            assertTrue(testLog.contains(
+                    "An augment cannot add node 'linkleaf' because it is mandatory and in module different from target"));
         }
     }
 
@@ -258,12 +275,13 @@ public class YangParserNegativeTest {
     public void testInvalidListKeyDefinition() throws Exception {
         File yang1 = new File(getClass().getResource("/negative-scenario/invalid-list-key-def.yang").toURI());
         try {
-            try (InputStream stream1 = new FileInputStream(yang1)) {
+            try (InputStream stream1 = new NamedFileInputStream(yang1, yang1.getPath())) {
                 TestUtils.loadModule(stream1);
-                fail("IllegalArgumentException should be thrown");
+                fail("InferenceException should be thrown");
             }
-        } catch (IllegalArgumentException e) {
-            String expected = "Key 'rib-id' misses node 'rib-id' in list '(invalid:list:key:def?revision=1970-01-01)application-map'";
+        } catch (InferenceException e) {
+            String expected = "Key 'rib-id' misses node 'rib-id' in list '(invalid:list:key:def?revision=1970-01-01)" +
+                    "application-map'";
             assertTrue(e.getMessage().startsWith(expected));
         }
     }
index 9b299b996983821510649537568dad2648d93aef..8918a5adbbb1fa2254b8458ade6c6b3616817dec 100644 (file)
@@ -94,21 +94,6 @@ public class YangParserWithContextTest {
                 SimpleDateFormatUtil.getRevisionFormat().parse("2013-06-18"));
         assertNotNull(module);
 
-//        String resource = "/ietf/ietf-inet-types@2010-09-24.yang";
-//        InputStream stream = new FileInputStream(new File(getClass()
-//                .getResource(resource).toURI()));
-//        SchemaContext context = parser.resolveSchemaContext(TestUtils
-//                .loadModules(Lists.newArrayList(stream)));
-//        stream.close();
-//
-//        resource = "/context-test/test1.yang";
-//        InputStream stream2 = new FileInputStream(new File(getClass()
-//                .getResource(resource).toURI()));
-//        Module module = TestUtils.loadModuleWithContext("test1", stream2,
-//                context);
-//        stream2.close();
-//        assertNotNull(module);
-
         LeafSchemaNode leaf = (LeafSchemaNode) module.getDataChildByName("id");
 
         assertTrue(leaf.getType() instanceof UnsignedIntegerTypeDefinition);
@@ -144,19 +129,6 @@ public class YangParserWithContextTest {
         StmtTestUtils.addSources(reactor, BAZ, FOO, BAR, SUBFOO, test2);
         SchemaContext context = reactor.buildEffective();
 
-        // Module testModule;
-        // try (InputStream stream = new FileInputStream(new
-        // File(getClass().getResource("/context-test/test2.yang")
-        // .toURI()))) {
-        // testModule = TestUtils.loadModuleWithContext("test2", stream,
-        // context);
-        // }
-        // assertNotNull(testModule);
-
-        // suffix _u = added by uses
-        // suffix _g = defined in grouping from context
-
-        // get grouping
         Module testModule = context.findModuleByName("test2",
                 SimpleDateFormatUtil.getRevisionFormat().parse("2013-06-18"));
         assertNotNull(testModule);
@@ -271,14 +243,6 @@ public class YangParserWithContextTest {
         StmtTestUtils.addSources(reactor, BAZ, FOO, BAR, SUBFOO, test2);
         SchemaContext context = reactor.buildEffective();
 
-        // Module module;
-        // try (InputStream stream = new FileInputStream(new
-        // File(getClass().getResource("/context-test/test2.yang")
-        // .toURI()))) {
-        // module = TestUtils.loadModuleWithContext("test2", stream, context);
-        // }
-        // assertNotNull(module);
-
         Module module = context.findModuleByName("test2",
                 SimpleDateFormatUtil.getRevisionFormat().parse("2013-06-18"));
         assertNotNull(module);
@@ -375,20 +339,6 @@ public class YangParserWithContextTest {
                 SimpleDateFormatUtil.getRevisionFormat().parse("2013-06-18"));
         assertNotNull(module);
 
-//        SchemaContext context;
-//        File yangFile = new File(getClass().getResource(
-//                "/types/custom-types-test@2012-4-4.yang").toURI());
-//        File dependenciesDir = new File(getClass().getResource("/ietf").toURI());
-//        YangContextParser parser = new YangParserImpl();
-//        context = parser.parseFile(yangFile, dependenciesDir);
-//
-//        Module module;
-//        try (InputStream stream = new FileInputStream(new File(getClass()
-//                .getResource("/context-test/test3.yang").toURI()))) {
-//            module = TestUtils.loadModuleWithContext("test3", stream, context);
-//        }
-//        assertNotNull(module);
-
         Set<IdentitySchemaNode> identities = module.getIdentities();
         assertEquals(1, identities.size());
 
@@ -429,19 +379,6 @@ public class YangParserWithContextTest {
                 SimpleDateFormatUtil.getRevisionFormat().parse("2013-06-18"));
         assertNotNull(module);
 
-//        SchemaContext context;
-//        File yangFile = new File(getClass().getResource(
-//                "/types/custom-types-test@2012-4-4.yang").toURI());
-//        File dependenciesDir = new File(getClass().getResource("/ietf").toURI());
-//        YangContextParser parser = new YangParserImpl();
-//        context = parser.parseFile(yangFile, dependenciesDir);
-//
-//        Module module;
-//        try (InputStream stream = new FileInputStream(new File(getClass()
-//                .getResource("/context-test/test3.yang").toURI()))) {
-//            module = TestUtils.loadModuleWithContext("test3", stream, context);
-//        }
-
         ContainerSchemaNode network = (ContainerSchemaNode) module
                 .getDataChildByName("network");
         List<UnknownSchemaNode> unknownNodes = network.getUnknownSchemaNodes();
@@ -522,29 +459,6 @@ public class YangParserWithContextTest {
                 SimpleDateFormatUtil.getRevisionFormat().parse("2013-02-27"));
         assertNotNull(testModule);
 
-        // load first module
-//        SchemaContext context;
-//        String resource = "/model/bar.yang";
-//
-//        try (InputStream stream = new FileInputStream(new File(getClass()
-//                .getResource(resource).toURI()))) {
-//            context = parser.resolveSchemaContext(TestUtils.loadModules(Lists
-//                    .newArrayList(stream)));
-//        }
-
-        // load another modules and parse them against already existing context
-//        Set<Module> modules;
-//        try (InputStream stream = new FileInputStream(new File(getClass()
-//                .getResource("/context-test/deviation-test.yang").toURI()))) {
-//            List<InputStream> input = Lists.newArrayList(stream);
-//            modules = TestUtils.loadModulesWithContext(input, context);
-//        }
-//        assertNotNull(modules);
-
-        // test deviation
-        //Module testModule = TestUtils.findModule(modules, "deviation-test");
-
-
         Set<Deviation> deviations = testModule.getDeviations();
         assertEquals(1, deviations.size());
         Deviation dev = deviations.iterator().next();
index af221998a1348545d0602eea65374b343509478a..f8a939bf01a861726810e8fcdf171b897ed0dfbe 100644 (file)
@@ -31,7 +31,7 @@ public class Bug4410Test {
             assertTrue(rootCause instanceof InferenceException);
             final String message = rootCause.getMessage();
             assertTrue(message.startsWith("Type [(foo?revision=1970-01-01)"));
-            assertTrue(message.endsWith("was not found."));
+            assertTrue(message.contains("was not found"));
         }
     }
 }
index c9b71a07cbce388755116da0370977b9da4a6b07..14ba17be33d0909ad988dfaa758ad69e665fe9d6 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.yangtools.yang.stmt.test;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.io.FileNotFoundException;
@@ -38,7 +39,7 @@ public class Bug4933Test {
             StmtTestUtils.parseYangSources("/bugs/bug4933/incorrect");
             fail("NullPointerException should be thrown.");
         } catch (NullPointerException e) {
-            assertEquals("String 'not_supported' is not valid deviate argument", e.getMessage());
+            assertTrue(e.getMessage().startsWith("String 'not_supported' is not valid deviate argument. Statement source at"));
         }
     }
 }
index 294ceb9b7f0a55795b51d7f6985e4383bce3e04c..f4fe296a26ef73c6bcddef7b07013ce0d8518076 100644 (file)
@@ -22,6 +22,7 @@ import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
 import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.parser.spi.meta.MissingSubstatementException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
 import org.opendaylight.yangtools.yang.stmt.retest.TestUtils;
 
@@ -68,7 +69,7 @@ public class SubstatementValidatorTest {
 
     @Test
     public void missingElementException() throws URISyntaxException, ReactorException {
-        expectedEx.expect(IllegalStateException.class);
+        expectedEx.expect(MissingSubstatementException.class);
 
         Set<Module> modules = TestUtils.loadModules(getClass().getResource
                 ("/substatement-validator/missing-element").toURI());