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;
} 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;
*/
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);
+ }
+
}
// 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);
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,
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
}
@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
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;
}
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);
}
}
@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);
}
}
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);
}
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);
}
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()));
}
/**
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()));
}
/**
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();
}
*/
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) {
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();
}
@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);
}
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;
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());
}
}
}
&& 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());
}
}
}
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);
@Override public Deviation.Deviate parseArgumentValue(
StmtContext<?, ?, ?> ctx, String value) throws SourceException {
- return Utils.parseDeviateFromString(value);
+ return Utils.parseDeviateFromString(ctx, value);
}
@Override public DeviateStatement createDeclared(
}
@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);
}
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);
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),
-/**
+/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
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);
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);
// 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;
}
@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);
}
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);
@Override
public List<LengthConstraint> parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
- return TypeUtils.parseLengthListFromString(value);
+ return TypeUtils.parseLengthListFromString(ctx, value);
}
@Override
@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);
}
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()));
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);
*/
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;
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);
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);
}
}
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);
@Override
public List<RangeConstraint> parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
- return TypeUtils.parseRangeListFromString(value);
+ return TypeUtils.parseRangeListFromString(ctx, value);
}
@Override
@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);
}
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)
.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);
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();
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;
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();
}
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();
}
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();
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;
// 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));
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();
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));
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);
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;
// 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<>();
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)
.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) {
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 {
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;
-/**
+/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
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
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());
}
}
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
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);
-/**
+/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
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;
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'"));
}
}
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'"));
}
}
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'"));
}
}
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);
}
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.
*/
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() {
-
- }
}
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;
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;
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);
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);
}
+/*
+ * 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;
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 {
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) {
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) {
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");
}
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."));
}
}
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);
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);
} 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]}"));
}
}
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'."));
}
}
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");
}
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");
}
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));
}
}
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));
}
}
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));
}
}
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));
}
}
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"));
}
}
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"));
}
}
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"));
}
}
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));
}
}
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);
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);
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);
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());
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();
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();
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"));
}
}
}
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;
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"));
}
}
}
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;
@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());