private static final Logger LOG = LoggerFactory.getLogger(YinStatementParserImpl.class);
+ private final List<String> toBeSkipped = new ArrayList<>();
+ private final String sourceName;
private StatementWriter writer;
private QNameToStatementDefinition stmtDef;
private PrefixToModule prefixes;
- private final String sourceName;
private String uriStr;
private boolean isType = false;
private boolean action = true;
private boolean yinElement = false;
- private List<String> toBeSkipped = new ArrayList<>();
- public YinStatementParserImpl(String sourceName) {
+ public YinStatementParserImpl(final String sourceName) {
this.sourceName = Preconditions.checkNotNull(sourceName);
}
* created.
* When done, start walking through YIN source
*
- *
* @param writer - instance of StatementWriter to emit declared statements
* @param stmtDef - map of valid statement definitions for linkage phase
*
*/
- public void setAttributes(StatementWriter writer, QNameToStatementDefinition stmtDef) {
+ public void setAttributes(final StatementWriter writer, final QNameToStatementDefinition stmtDef) {
this.writer = writer;
this.stmtDef = stmtDef;
}
/**
- *
* This method is supposed to be called in any phase but linkage, when YinStatementParserImpl instance has already
* been created.
* When done, start walking through YIN source
* @param prefixes - map of valid prefixes for any phase but linkage
*
*/
- public void setAttributes(StatementWriter writer, QNameToStatementDefinition stmtDef, PrefixToModule prefixes) {
+ public void setAttributes(final StatementWriter writer, final QNameToStatementDefinition stmtDef, final PrefixToModule prefixes) {
this.writer = writer;
this.stmtDef = stmtDef;
this.prefixes = prefixes;
}
/**
- *
* This method executes parsing YIN source and emitting declared statements via attached StatementWriter
*
* @param inputReader - instance of XMlStreamReader, allows forward, read-only access to XML.
- *
*/
- public void walk(XMLStreamReader inputReader) {
+ public void walk(final XMLStreamReader inputReader) {
try {
while (inputReader.hasNext()) {
inputReader.next();
}
}
- private void startStatement(QName identifier, StatementSourceReference ref) {
+ private void startStatement(final QName identifier, final StatementSourceReference ref) {
writer.startStatement(identifier, ref);
}
- private void argumentValue(XMLStreamReader inputReader, StatementSourceReference ref, QName identifier, boolean
+ private void argumentValue(final XMLStreamReader inputReader, final StatementSourceReference ref, final QName identifier, final boolean
yinElement) {
if (yinElement) {
writeTextOnlyElement(inputReader, ref);
}
}
- private void endStatement(StatementSourceReference ref) {
+ private void endStatement(final StatementSourceReference ref) {
writer.endStatement(ref);
}
- private void enterStatement(XMLStreamReader inputReader) throws URISyntaxException {
+ private void enterStatement(final XMLStreamReader inputReader) throws URISyntaxException {
final StatementSourceReference ref = DeclarationInTextSource.atPosition(sourceName, inputReader
.getLocation().getLineNumber(), inputReader.getLocation().getColumnNumber());
uriStr = inputReader.getNamespaceURI();
}
} else {
//if statement not found through all phases, throw exception
- if (writer.getPhase().equals(ModelProcessingPhase.FULL_DECLARATION)) {
- throw new SourceException(String.format("%s is not a YIN statement or use of extension.",
- identifier.getLocalName()), ref);
- } else {
- //otherwise skip it (statement not to be read yet)
- action = false;
- toBeSkipped.add(getElementFullName(inputReader));
- }
+ SourceException.throwIf(writer.getPhase().equals(ModelProcessingPhase.FULL_DECLARATION), ref,
+ "%s is not a YIN statement or use of extension.", identifier.getLocalName());
+
+ //otherwise skip it (statement not to be read yet)
+ action = false;
+ toBeSkipped.add(getElementFullName(inputReader));
}
if (isType) {
}
}
- private void exitStatement(XMLStreamReader inputReader) throws URISyntaxException {
+ private void exitStatement(final XMLStreamReader inputReader) throws URISyntaxException {
final String statementName = getElementFullName(inputReader);
final QName identifier = new QName(new URI(inputReader.getNamespaceURI()), statementName);
final StatementSourceReference ref = DeclarationInTextSource.atPosition(sourceName, inputReader
}
}
- private void writeTextOnlyElement(XMLStreamReader inputReader, StatementSourceReference ref) {
+ private void writeTextOnlyElement(final XMLStreamReader inputReader, final StatementSourceReference ref) {
try {
writer.argumentValue(inputReader.getElementText(), ref);
} catch (XMLStreamException e) {
}
}
- private void writeNormalizedAttributeValue(XMLStreamReader inputReader, QName
- identifier, StatementSourceReference ref) {
+ private void writeNormalizedAttributeValue(final XMLStreamReader inputReader, final QName
+ identifier, final StatementSourceReference ref) {
final String attributeValue = getAttributeValue(inputReader, identifier, stmtDef);
- if (attributeValue != null)
+ if (attributeValue != null) {
writer.argumentValue(attributeValue, ref);
+ }
}
- private void writeTypeStmtAndArg(XMLStreamReader inputReader, QName identifier, StatementSourceReference ref) {
+ private void writeTypeStmtAndArg(final XMLStreamReader inputReader, final QName identifier, final StatementSourceReference ref) {
String argument = getAttributeValue(inputReader, identifier, stmtDef);
if (TypeUtils.isYangTypeBodyStmtString(argument)) {
startStatement(new QName(YangConstants.RFC6020_YIN_NAMESPACE, argument), ref);
isType = false;
}
- private static String getElementFullName(XMLStreamReader inputReader) {
+ private static String getElementFullName(final XMLStreamReader inputReader) {
if (!inputReader.getPrefix().isEmpty()) {
return inputReader.getPrefix() + ":" + inputReader.getLocalName();
} else {
}
}
- private static boolean isStatementWithArgument(QName identifier, QNameToStatementDefinition stmtDef) {
+ private static boolean isStatementWithArgument(final QName identifier, final QNameToStatementDefinition stmtDef) {
if (stmtDef != null && stmtDef.get(Utils.trimPrefix(identifier)) == null) {
return false;
- } else if (((StatementSupport) stmtDef.get(Utils.trimPrefix(identifier)))
- .getPublicView().getArgumentName() == null) {
+ } else if (((StatementSupport<?, ?, ?>) stmtDef.get(Utils.trimPrefix(identifier))).getPublicView().getArgumentName() == null) {
return false;
}
return true;
}
- private static boolean isStatementWithYinElement(QName identifier, QNameToStatementDefinition stmtDef) {
+ private static boolean isStatementWithYinElement(final QName identifier, final QNameToStatementDefinition stmtDef) {
final StatementDefinition statementDefinition = stmtDef.get(Utils.trimPrefix(identifier));
- if (statementDefinition != null) {
- return ((Rfc6020Mapping) ((StatementSupport) statementDefinition).getPublicView()).isArgumentYinElement();
- } else {
+ if (statementDefinition == null) {
return false;
}
+
+ return ((Rfc6020Mapping) ((StatementSupport<?, ?, ?>) statementDefinition).getPublicView()).isArgumentYinElement();
}
- private static String getAttributeValue(XMLStreamReader inputReader, QName identifier, QNameToStatementDefinition
+ private static String getAttributeValue(final XMLStreamReader inputReader, final QName identifier, final QNameToStatementDefinition
stmtDef) {
String namespace = null;
- return inputReader.getAttributeValue(namespace, (((StatementSupport) stmtDef.get(Utils.trimPrefix(identifier)))
+ return inputReader.getAttributeValue(namespace, (((StatementSupport<?, ?, ?>) stmtDef.get(Utils.trimPrefix(identifier)))
.getPublicView()).getArgumentName().getLocalName());
}
}
\ No newline at end of file
package org.opendaylight.yangtools.yang.parser.spi;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
-import java.util.ArrayList;
-import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
+import java.util.Map.Entry;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.parser.spi.meta.InvalidSubstatementException;
import org.opendaylight.yangtools.yang.parser.spi.meta.MissingSubstatementException;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
-import org.opendaylight.yangtools.yang.parser.util.YangParseException;
public final class SubstatementValidator {
+ public final static int MAX = Integer.MAX_VALUE;
private final Map<StatementDefinition, Cardinality> cardinalityMap;
private final StatementDefinition currentStatement;
private final SpecialCase specialCase;
- public final static int MAX = Integer.MAX_VALUE;
- private SubstatementValidator(Builder builder, SpecialCase specialCase) {
+ private SubstatementValidator(final Builder builder, final SpecialCase specialCase) {
this.cardinalityMap = builder.cardinalityMap.build();
this.currentStatement = builder.currentStatement;
this.specialCase = specialCase;
}
- public static Builder builder(StatementDefinition currentStatement) {
+ public static Builder builder(final StatementDefinition currentStatement) {
return new Builder(currentStatement);
}
private final ImmutableMap.Builder<StatementDefinition, Cardinality> cardinalityMap = ImmutableMap.builder();
private final StatementDefinition currentStatement;
- private Builder(StatementDefinition currentStatement) {
+ private Builder(final StatementDefinition currentStatement) {
this.currentStatement = currentStatement;
}
- public Builder add(StatementDefinition d, int min, int max) {
+ public Builder add(final StatementDefinition d, final int min, final int max) {
this.cardinalityMap.put(d, new Cardinality(min, max));
return this;
}
return new SubstatementValidator(this, SpecialCase.NULL);
}
- public SubstatementValidator build(SpecialCase specialCase) {
+ public SubstatementValidator build(final SpecialCase specialCase) {
return new SubstatementValidator(this, specialCase);
}
}
public void validate(final StmtContext<?, ?, ?> ctx) throws InvalidSubstatementException,
MissingSubstatementException {
- final Map<StatementDefinition, Integer> stmtDefMap = new HashMap<>();
- final Map<StatementDefinition, Integer> validatedMap = new HashMap<>();
- final Collection<StatementContextBase<?, ?, ?>> substatementsInit = new ArrayList<>();
- substatementsInit.addAll(ctx.declaredSubstatements());
- substatementsInit.addAll(ctx.effectiveSubstatements());
+ final Iterable<StatementContextBase<?, ?, ?>> substatementsInit = Iterables.concat(
+ ctx.declaredSubstatements(), ctx.effectiveSubstatements());
+ final Map<StatementDefinition, Integer> stmtDefMap = new HashMap<>();
for (StatementContextBase<?, ?, ?> stmtCtx : substatementsInit) {
final StatementDefinition definition = stmtCtx.getPublicDefinition();
if (!stmtDefMap.containsKey(definition)) {
}
if (stmtDefMap.isEmpty() && specialCase == SpecialCase.NOTNULL) {
- throw new InvalidSubstatementException(String.format("%s must contain atleast 1 element. Error in module "
- + "%s (%s)", currentStatement, ctx.getRoot().getStatementArgument(),
- ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
- ctx.getStatementSourceReference());
+ throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
+ "%s must contain atleast 1 element. Error in module %s (%s)", currentStatement,
+ ctx.getRoot().getStatementArgument(),
+ ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
}
- for (Map.Entry entry : stmtDefMap.entrySet()) {
+ final Map<StatementDefinition, Integer> validatedMap = new HashMap<>();
+ for (Entry<?, ?> entry : stmtDefMap.entrySet()) {
final StatementDefinition key = (StatementDefinition) entry.getKey();
if (!cardinalityMap.containsKey(key)) {
if (ctx.getFromNamespace(ExtensionNamespace.class, key.getStatementName()) != null) {
continue;
}
- throw new InvalidSubstatementException(String.format("%s is not valid for %s. Error in module %s (%s)",
- key, currentStatement, ctx.getRoot().getStatementArgument(),
- ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
- ctx.getStatementSourceReference());
+ throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
+ "%s is not valid for %s. Error in module %s (%s)", key, currentStatement,
+ ctx.getRoot().getStatementArgument(),
+ ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
}
if (cardinalityMap.get(key).getMin() > (Integer) entry.getValue()) {
- throw new InvalidSubstatementException(String.format("Minimal count of %s for %s is %s, detected %s. "
- + "Error in module %s (%s)", key, currentStatement, cardinalityMap.get(key).getMin(),
- entry.getValue(), ctx.getRoot().getStatementArgument(),
- ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
- ctx.getStatementSourceReference());
+ throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
+ "Minimal count of %s for %s is %s, detected %s. Error in module %s (%s)", key, currentStatement,
+ cardinalityMap.get(key).getMin(), entry.getValue(), ctx.getRoot().getStatementArgument(),
+ ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
}
if (cardinalityMap.get(key).getMax() < (Integer) entry.getValue()) {
- throw new InvalidSubstatementException(String.format("Maximal count of %s for %s is %s, detected %s. "
- + "Error in module %s (%s)", key, currentStatement, cardinalityMap.get(key).getMax(),
- entry.getValue(), ctx.getRoot().getStatementArgument(),
- ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
- ctx.getStatementSourceReference());
+ throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
+ "Maximal count of %s for %s is %s, detected %s. Error in module %s (%s)", key, currentStatement,
+ cardinalityMap.get(key).getMax(), entry.getValue(), ctx.getRoot().getStatementArgument(),
+ ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
}
validatedMap.put(key, 1);
}
final MapDifference<StatementDefinition, Object> diff = Maps.difference(validatedMap, cardinalityMap);
-
- for (Map.Entry entry : diff.entriesOnlyOnRight().entrySet()) {
+ for (Entry<?, ?> entry : diff.entriesOnlyOnRight().entrySet()) {
final int min = ((Cardinality) entry.getValue()).getMin();
if (min > 0) {
- throw new MissingSubstatementException(String.format("%s is missing %s. Minimal count is %s. Error in"
- + " module %s (%s)", currentStatement, entry.getKey(), min, ctx.getRoot()
- .getStatementArgument(), ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot())),
- ctx.getStatementSourceReference());
+ throw new MissingSubstatementException(ctx.getStatementSourceReference(),
+ "%s is missing %s. Minimal count is %s. Error in module %s (%s)", currentStatement, entry.getKey(),
+ min, ctx.getRoot().getStatementArgument(),
+ ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
}
}
}
private final int min;
private final int max;
- private Cardinality(int min, int max) throws YangParseException {
- if (min > max) {
- throw new IllegalArgumentException("Min can not be greater than max!");
- }
- if (min < 0) {
- throw new IllegalArgumentException("Min can not be les than 0!");
- }
+ private Cardinality(final int min, final int max) {
+ Preconditions.checkArgument(min >= 0, "Min %s cannot be less than 0!");
+ Preconditions.checkArgument(min <= max, "Min %s can not be greater than max %s!", min, max);
this.min = min;
this.max = max;
}
import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
/**
- *
* Thrown when there was inference error
- *
*/
public class InferenceException extends SourceException {
-
-
private static final long serialVersionUID = 1L;
- public InferenceException(@Nonnull String message, @Nonnull StatementSourceReference source, Throwable cause) {
+ public InferenceException(@Nonnull final String message, @Nonnull final StatementSourceReference source,
+ final Throwable cause) {
super(message, source, cause);
}
- public InferenceException(@Nonnull String message, @Nonnull StatementSourceReference source) {
+ public InferenceException(@Nonnull final String message, @Nonnull final StatementSourceReference source) {
super(message, source);
}
+ public InferenceException(@Nonnull final StatementSourceReference source, @Nonnull final String format,
+ final Object... args) {
+ this(String.format(format, args), source);
+ }
+
+ /**
+ * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
+ * this method does nothing.
+ *
+ * @param expression Expression to be evaluated
+ * @param source Statement source reference
+ * @param format Format string, according to {@link String#format(String, Object...)}.
+ * @param args Format string arguments, according to {@link String#format(String, Object...)}
+ * @throws InferenceException if the expression evaluates to true.
+ */
+ public static void throwIf(final boolean expression, @Nonnull final StatementSourceReference source,
+ @Nonnull final String format, final Object... args) {
+ if (expression) {
+ throw new InferenceException(source, format, args);
+ }
+ }
}
public class InvalidSubstatementException extends SourceException {
private static final long serialVersionUID = 1L;
- public InvalidSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source, final Throwable cause) {
+ public InvalidSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source,
+ final Throwable cause) {
super(message, source, cause);
}
public InvalidSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source) {
super(message, source);
}
+
+ public InvalidSubstatementException(@Nonnull final StatementSourceReference source, @Nonnull final String format,
+ final Object... args) {
+ this(String.format(format, args), source);
+ }
}
super(message, source);
}
- public MissingSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source, final Throwable cause) {
+ public MissingSubstatementException(@Nonnull final String message, @Nonnull final StatementSourceReference source,
+ final Throwable cause) {
super(message, source, cause);
}
+
+ public MissingSubstatementException(@Nonnull final StatementSourceReference source, @Nonnull final String format,
+ final Object... args) {
+ this(String.format(format, args), source);
+ }
}
import javax.annotation.Nonnull;
/**
- *
* Thrown to indicate error in YANG model source.
- *
*/
public class SourceException extends RuntimeException {
-
private static final long serialVersionUID = 1L;
private final StatementSourceReference sourceRef;
- public SourceException(@Nonnull String message,@Nonnull StatementSourceReference source) {
+ /**
+ * Create a new instance with the specified message and source. The message will be appended with
+ * the source reference.
+ *
+ * @param message Context message
+ * @param source Statement source
+ */
+ public SourceException(@Nonnull final String message, @Nonnull final StatementSourceReference source) {
super(createMessage(message, source));
sourceRef = source;
}
- public SourceException(@Nonnull String message,@Nonnull StatementSourceReference source, Throwable cause) {
+ /**
+ * Create a new instance with the specified message and source. The message will be appended with
+ * the source reference.
+ *
+ * @param message Context message
+ * @param source Statement source
+ * @param cause Underlying cause of this exception
+ */
+ public SourceException(@Nonnull final String message, @Nonnull final StatementSourceReference source,
+ final Throwable cause) {
super(createMessage(message, source), cause);
sourceRef = source;
}
+ /**
+ * Create a new instance with the specified source and a formatted message. The message will be appended with
+ * the source reference.
+ *
+ * @param source Statement source
+ * @param format Format string, according to {@link String#format(String, Object...)}.
+ * @param args Format string arguments, according to {@link String#format(String, Object...)}
+ */
+ public SourceException(@Nonnull final StatementSourceReference source, @Nonnull final String format,
+ final Object... args) {
+ this(String.format(format, args), source);
+ }
+
+ /**
+ * Create a new instance with the specified source and a formatted message. The message will be appended with
+ * the source reference.
+ *
+ * @param source Statement source
+ * @param cause Underlying cause of this exception
+ * @param format Format string, according to {@link String#format(String, Object...)}.
+ * @param args Format string arguments, according to {@link String#format(String, Object...)}
+ */
+ public SourceException(@Nonnull final StatementSourceReference source, final Throwable cause,
+ @Nonnull final String format, final Object... args) {
+ this(String.format(format, args), source, cause);
+ }
+
+ /**
+ * Return the reference to the source which caused this exception.
+ *
+ * @return Source reference
+ */
public @Nonnull StatementSourceReference getSourceReference() {
return sourceRef;
}
+ /**
+ * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
+ * this method does nothing.
+ *
+ * @param expression Expression to be evaluated
+ * @param source Statement source reference
+ * @param format Format string, according to {@link String#format(String, Object...)}.
+ * @param args Format string arguments, according to {@link String#format(String, Object...)}
+ * @throws SourceException if the expression evaluates to true.
+ */
+ public static void throwIf(final boolean expression, @Nonnull final StatementSourceReference source,
+ @Nonnull final String format, final Object... args) {
+ if (expression) {
+ throw new SourceException(source, format, args);
+ }
+ }
+
+ /**
+ * Throw an instance of this exception if an object is null. If the object is non-null, it will
+ * be returned as the result of this method.
+ *
+ * @param obj Object reference to be checked
+ * @param source Statement source reference
+ * @param format Format string, according to {@link String#format(String, Object...)}.
+ * @param args Format string arguments, according to {@link String#format(String, Object...)}
+ * @return Object if it is not null
+ * @throws SourceException if object is null
+ */
+ @Nonnull public static <T> T throwIfNull(final T obj, @Nonnull final StatementSourceReference source,
+ @Nonnull final String format, final Object... args) {
+ throwIf(obj == null, source, format, args);
+ return obj;
+ }
+
private static String createMessage(@Nonnull final String message, @Nonnull final StatementSourceReference source) {
Preconditions.checkNotNull(message);
Preconditions.checkNotNull(source);
- return String.format("%s\nStatement source at %s", message, source);
+ return message + " [at " + source + ']';
}
-
}
if (def == null) {
// unknown-stmts (from import, include or local-scope)
if (qNameToStmtDefMap.get(name) != null) {
- final StatementContextBase<?, ?, ?> extension =
- (StatementContextBase<?, ?, ?>) currentContext.getAllFromNamespace(ExtensionNamespace.class).get(name);
- if (extension != null) {
- final QName arg = (QName) extension.getStatementArgument();
- final QName qName = current.getFromNamespace(QNameCacheNamespace.class,
- QName.create(arg, extension.getIdentifier().getArgument()));
-
- def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
- getNewStatementDefinition(qName)));
- } else {
- throw new SourceException("Extension not found: " + name,
- current.getStatementSourceReference());
- }
+ final StatementContextBase<?, ?, ?> extension =
+ (StatementContextBase<?, ?, ?>) currentContext.getAllFromNamespace(ExtensionNamespace.class).get(name);
+
+ SourceException.throwIfNull(extension, current.getStatementSourceReference(), "Extension %s not found",
+ name);
+
+ final QName arg = (QName) extension.getStatementArgument();
+ final QName qName = current.getFromNamespace(QNameCacheNamespace.class,
+ QName.create(arg, extension.getIdentifier().getArgument()));
+
+ def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
+ getNewStatementDefinition(qName)));
} else {
// type-body-stmts
def = resolveTypeBodyStmts(name.getLocalName());
}
- }
- else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
+ } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
QName qName = Utils.qNameFromArgument(current, name.getLocalName());
- def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition
- (getNewStatementDefinition(qName)));
+ def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
+ getNewStatementDefinition(qName)));
}
Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
return new ContextBuilder(def, ref) {
@Override
- public StatementContextBase build() throws SourceException {
+ public StatementContextBase build() {
if (root == null) {
root = new RootStatementContext(this, SourceSpecificContext.this);
} else {
private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
-
- Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
boolean hasProgressed = false;
+
+ final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
while (modifier.hasNext()) {
if (modifier.next().tryApply()) {
modifier.remove();
.class);
final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
(BelongsToPrefixToModuleIdentifier.class);
- if (belongsToPrefixes != null)
+ if (belongsToPrefixes != null) {
allPrefixes.putAll(belongsToPrefixes);
+ }
for (Entry<String, ModuleIdentifier> stringModuleIdentifierEntry : allPrefixes.entrySet()) {
final QNameModule namespace = getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class,
- stringModuleIdentifierEntry.getValue());
+ stringModuleIdentifierEntry.getValue());
prefixToModuleMap.put(stringModuleIdentifierEntry.getKey(), namespace);
}
return prefixToModuleMap;
// regular YANG statements added
ImmutableMap<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(
inProgressPhase).getDefinitions();
- for (Map.Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
+ for (Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
qNameToStmtDefMap.put(entry.getKey(), entry.getValue());
}
// extensions added
if (inProgressPhase.equals(ModelProcessingPhase.FULL_DECLARATION)) {
- Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions = currentContext
- .getAllFromNamespace(ExtensionNamespace.class);
+ Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions =
+ currentContext.getAllFromNamespace(ExtensionNamespace.class);
if (extensions != null) {
- for (Map.Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension : extensions
- .entrySet()) {
- qNameToStmtDefMap
- .put((extension.getKey()),
- (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension
- .getValue()).definition()
- .getFactory());
+ for (Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension :
+ extensions.entrySet()) {
+ qNameToStmtDefMap.put((extension.getKey()),
+ (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension.getValue()).definition()
+ .getFactory());
}
}
}
return;
}
- final ModelActionBuilder augmentAction = augmentNode
- .newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
- final ModelActionBuilder.Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>>> sourceCtxPrereq = augmentAction
- .requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
- final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target = augmentAction.mutatesEffectiveCtx(getSearchRoot(augmentNode), SchemaNodeIdentifierBuildNamespace.class, augmentNode.getStatementArgument());
+ final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(
+ ModelProcessingPhase.EFFECTIVE_MODEL);
+ final ModelActionBuilder.Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>>> sourceCtxPrereq =
+ augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
+ final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target =
+ augmentAction.mutatesEffectiveCtx(getSearchRoot(augmentNode), SchemaNodeIdentifierBuildNamespace.class, augmentNode.getStatementArgument());
augmentAction.apply(new ModelActionBuilder.InferenceAction() {
@Override
- public void apply() throws InferenceException {
+ public void apply() {
final StatementContextBase<?, ?, ?> augmentTargetCtx = (StatementContextBase<?, ?, ?>) target.get();
-
if (!AugmentUtils.isSupportedAugmentTarget(augmentTargetCtx) || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
augmentNode.setIsSupportedToBuildEffective(false);
return;
}
+
+ // FIXME: this is a workaround for models which augment a node which is added via an extension
+ // which we do not handle. This needs to be reworked in terms of unknown schema nodes.
final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
try {
- AugmentUtils.copyFromSourceToTarget(augmentSourceCtx,
- augmentTargetCtx);
- augmentTargetCtx
- .addEffectiveSubstatement(augmentSourceCtx);
+ AugmentUtils.copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
+ augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
updateAugmentOrder(augmentSourceCtx);
} catch (SourceException e) {
- LOG.warn(e.getMessage(), e);
+ LOG.warn("Failed to add augmentation %s defined at {}",
+ augmentSourceCtx.getStatementSourceReference(), e);
}
-
}
- private void updateAugmentOrder(
- final StatementContextBase<?, ?, ?> augmentSourceCtx) {
- Integer currentOrder = augmentSourceCtx
- .getFromNamespace(StmtOrderingNamespace.class,
- Rfc6020Mapping.AUGMENT);
+ private void updateAugmentOrder(final StatementContextBase<?, ?, ?> augmentSourceCtx) {
+ Integer currentOrder = augmentSourceCtx.getFromNamespace(StmtOrderingNamespace.class,
+ Rfc6020Mapping.AUGMENT);
if (currentOrder == null) {
currentOrder = 1;
} else {
currentOrder++;
}
+
augmentSourceCtx.setOrder(currentOrder);
- augmentSourceCtx.addToNs(StmtOrderingNamespace.class,
- Rfc6020Mapping.AUGMENT, currentOrder);
+ augmentSourceCtx.addToNs(StmtOrderingNamespace.class, Rfc6020Mapping.AUGMENT, currentOrder);
}
@Override
- public void prerequisiteFailed(
- final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed)
- throws InferenceException {
- throw new InferenceException("Augment target not found: "
- + augmentNode.getStatementArgument(), augmentNode
- .getStatementSourceReference());
+ public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) {
+ throw new InferenceException(augmentNode.getStatementSourceReference(),
+ "Augment target '%s' not found", augmentNode.getStatementArgument());
}
});
}
private static Mutable<?, ?, ?> getSearchRoot(final Mutable<?, ?, ?> augmentContext) {
Mutable<?, ?, ?> parent = augmentContext.getParentContext();
// Augment is in uses - we need to augment instantiated nodes in parent.
- if(Rfc6020Mapping.USES.equals(parent.getPublicDefinition())) {
+ if (Rfc6020Mapping.USES.equals(parent.getPublicDefinition())) {
return parent.getParentContext();
}
return parent;
.addAll(sourceCtx.declaredSubstatements()).addAll(sourceCtx.effectiveSubstatements()).build();
for (final StatementContextBase<?, ?, ?> sourceSubStatement : sourceSubStatements) {
- if (sourceSubStatement.getPublicDefinition().getDeclaredRepresentationClass()
- .equals(MandatoryStatement.class)) {
- throw new InferenceException(
- String.format(
- "An augment cannot add node '%s' because it is mandatory and in module different from target",
- sourceCtx.rawStatementArgument()), sourceCtx.getStatementSourceReference());
- }
+ InferenceException.throwIf(MandatoryStatement.class.equals(
+ sourceSubStatement.getPublicDefinition().getDeclaredRepresentationClass()),
+ sourceCtx.getStatementSourceReference(),
+ "An augment cannot add node '%s' because it is mandatory and in module different from target",
+ sourceCtx.rawStatementArgument());
}
}
boolean qNamesEqual = sourceIsDataNode && targetIsDataNode
&& Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
- if (qNamesEqual) {
- throw new InferenceException(String.format(
- "An augment cannot add node named '%s' because this name is already used in target",
- sourceCtx.rawStatementArgument()), sourceCtx.getStatementSourceReference());
- }
+ InferenceException.throwIf(qNamesEqual, sourceCtx.getStatementSourceReference(),
+ "An augment cannot add node named '%s' because this name is already used in target",
+ sourceCtx.rawStatementArgument());
}
}
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.BaseEffectiveStatementImpl;
public class BaseStatementImpl extends AbstractDeclaredStatement<QName> implements BaseStatement {
- private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
- .BASE)
- .build();
+ private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+ SubstatementValidator.builder(Rfc6020Mapping.BASE).build();
protected BaseStatementImpl(final StmtContext<QName, BaseStatement, ?> context) {
super(context);
if (StmtContextUtils.producesDeclared(baseParentCtx, IdentityStatement.class)) {
final QName baseIdentityQName = baseStmtCtx.getStatementArgument();
- ModelActionBuilder baseIdentityAction = baseStmtCtx.newInferenceAction(ModelProcessingPhase.STATEMENT_DEFINITION);
- final Prerequisite<StmtContext<?, ?, ?>> requiresPrereq = baseIdentityAction.requiresCtx(baseStmtCtx, IdentityNamespace.class, baseIdentityQName, ModelProcessingPhase.STATEMENT_DEFINITION);
- final Prerequisite<StmtContext.Mutable<?, ?, ?>> mutatesPrereq = baseIdentityAction.mutatesCtx
- (baseParentCtx, ModelProcessingPhase.STATEMENT_DEFINITION);
+ final ModelActionBuilder baseIdentityAction = baseStmtCtx.newInferenceAction(
+ ModelProcessingPhase.STATEMENT_DEFINITION);
+ final Prerequisite<StmtContext<?, ?, ?>> requiresPrereq = baseIdentityAction.requiresCtx(baseStmtCtx,
+ IdentityNamespace.class, baseIdentityQName, ModelProcessingPhase.STATEMENT_DEFINITION);
+ final Prerequisite<StmtContext.Mutable<?, ?, ?>> mutatesPrereq = baseIdentityAction.mutatesCtx(
+ baseParentCtx, ModelProcessingPhase.STATEMENT_DEFINITION);
baseIdentityAction.apply(new InferenceAction() {
@Override
- public void apply() throws InferenceException {
+ public void apply() {
List<StmtContext<?, ?, ?>> derivedIdentities =
baseStmtCtx.getFromNamespace(DerivedIdentitiesNamespace.class, baseStmtCtx.getStatementArgument());
if (derivedIdentities == null) {
@Override
public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
- throw new InferenceException(
- "Unable to resolve identity " + baseParentCtx.getStatementArgument() + " and base identity "
- + baseStmtCtx.getStatementArgument(), baseStmtCtx.getStatementSourceReference());
+ throw new InferenceException(baseStmtCtx.getStatementSourceReference(),
+ "Unable to resolve identity %s and base identity %s",
+ baseParentCtx.getStatementArgument(), baseStmtCtx.getStatementArgument());
}
});
}
}
@Override
- public void onFullDefinitionDeclared(Mutable<QName, BaseStatement,
- EffectiveStatement<QName, BaseStatement>> stmt) throws SourceException {
+ public void onFullDefinitionDeclared(
+ final Mutable<QName, BaseStatement, EffectiveStatement<QName, BaseStatement>> stmt) {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
}
import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNamespaceForBelongsTo;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.BelongsEffectiveToStatementImpl;
public class BelongsToStatementImpl extends AbstractDeclaredStatement<String>
implements BelongsToStatement {
- private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
- .BELONGS_TO)
- .add(Rfc6020Mapping.PREFIX, 1, 1)
- .build();
+ private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+ SubstatementValidator.builder(Rfc6020Mapping.BELONGS_TO).add(Rfc6020Mapping.PREFIX, 1, 1).build();
- protected BelongsToStatementImpl(
- final StmtContext<String, BelongsToStatement, ?> context) {
+ protected BelongsToStatementImpl(final StmtContext<String, BelongsToStatement, ?> context) {
super(context);
}
}
@Override
- public void onLinkageDeclared(final StmtContext.Mutable<String, BelongsToStatement, EffectiveStatement<String, BelongsToStatement>> belongsToCtx) throws SourceException {
+ public void onLinkageDeclared(
+ final StmtContext.Mutable<String, BelongsToStatement, EffectiveStatement<String, BelongsToStatement>> belongsToCtx) {
ModelActionBuilder belongsToAction = belongsToCtx.newInferenceAction(ModelProcessingPhase.SOURCE_LINKAGE);
final ModuleIdentifier belongsToModuleIdentifier = getModuleIdentifier(belongsToCtx);
- final ModelActionBuilder.Prerequisite<StmtContext<?, ?, ?>> belongsToPrereq = belongsToAction.requiresCtx(belongsToCtx, ModuleNamespaceForBelongsTo.class, belongsToModuleIdentifier.getName(), ModelProcessingPhase.SOURCE_LINKAGE);
+ final ModelActionBuilder.Prerequisite<StmtContext<?, ?, ?>> belongsToPrereq = belongsToAction.requiresCtx(
+ belongsToCtx, ModuleNamespaceForBelongsTo.class, belongsToModuleIdentifier.getName(),
+ ModelProcessingPhase.SOURCE_LINKAGE);
belongsToAction.apply(new InferenceAction() {
-
@Override
- public void apply() throws InferenceException {
+ public void apply() {
StmtContext<?, ?, ?> belongsToModuleCtx = belongsToPrereq.get();
- belongsToCtx.addToNs(BelongsToModuleContext.class, belongsToModuleIdentifier,
- belongsToModuleCtx);
- belongsToCtx.addToNs(BelongsToPrefixToModuleIdentifier.class, StmtContextUtils
- .findFirstDeclaredSubstatement(belongsToCtx, PrefixStatement.class).getStatementArgument
- (), belongsToModuleIdentifier);
+ belongsToCtx.addToNs(BelongsToModuleContext.class, belongsToModuleIdentifier, belongsToModuleCtx);
+ belongsToCtx.addToNs(BelongsToPrefixToModuleIdentifier.class,
+ StmtContextUtils.findFirstDeclaredSubstatement(belongsToCtx, PrefixStatement.class)
+ .getStatementArgument(), belongsToModuleIdentifier);
}
@Override
- public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) throws InferenceException {
+ public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) {
if (failed.contains(belongsToPrereq)) {
- throw new InferenceException("Module from belongs-to was not found: " + belongsToCtx.getStatementArgument(), belongsToCtx
- .getStatementSourceReference());
+ throw new InferenceException(belongsToCtx.getStatementSourceReference(),
+ "Module '%s' from belongs-to was not found", belongsToCtx.getStatementArgument());
}
}
});
}
- private static ModuleIdentifier getModuleIdentifier(final StmtContext.Mutable<String, BelongsToStatement, EffectiveStatement<String, BelongsToStatement>> belongsToCtx) {
+ private static ModuleIdentifier getModuleIdentifier(
+ final StmtContext.Mutable<String, BelongsToStatement, EffectiveStatement<String, BelongsToStatement>> belongsToCtx) {
String moduleName = belongsToCtx.getStatementArgument();
- return new ModuleIdentifierImpl(moduleName, Optional.<URI> absent(), Optional.of(SimpleDateFormatUtil.DEFAULT_BELONGS_TO_DATE));
+ return new ModuleIdentifierImpl(moduleName, Optional.<URI> absent(),
+ Optional.of(SimpleDateFormatUtil.DEFAULT_BELONGS_TO_DATE));
}
@Override
- public void onFullDefinitionDeclared(StmtContext.Mutable<String, BelongsToStatement,
- EffectiveStatement<String, BelongsToStatement>> stmt) throws SourceException {
+ public void onFullDefinitionDeclared(final StmtContext.Mutable<String, BelongsToStatement,
+ EffectiveStatement<String, BelongsToStatement>> stmt) {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
}
StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
StatementDefinition refineTargetNodeDef = refineTargetNodeCtx.getPublicDefinition();
- if (!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx)) {
- throw new SourceException("Error in module '"
- + refineSubstatementCtx.getRoot().getStatementArgument()
- + "' in the refine of uses '"
- + refineSubstatementCtx.getParentContext().getStatementArgument()
- + "': can not perform refine of '" + refineSubstatementCtx.getPublicDefinition()
- + "' for the target '" + refineTargetNodeCtx.getPublicDefinition() + "'.",
- refineSubstatementCtx.getStatementSourceReference());
- }
+ SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
+ refineSubstatementCtx.getStatementSourceReference(),
+ "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
+ refineSubstatementCtx.getRoot().getStatementArgument(),
+ refineSubstatementCtx.getParentContext().getStatementArgument(),
+ refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx.getPublicDefinition());
if (isAllowedToAddByRefine(refineSubstatementDef)) {
refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.SOURCE_LINKAGE;
import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-
import com.google.common.base.Optional;
import java.net.URI;
import java.util.Collection;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.ImportEffectiveStatementImpl;
public class ImportStatementDefinition
extends AbstractStatementSupport<String, ImportStatement, EffectiveStatement<String, ImportStatement>> {
- private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
- .IMPORT)
- .add(Rfc6020Mapping.PREFIX, 1, 1)
- .add(Rfc6020Mapping.REVISION_DATE, 0, 1)
- .build();
+ private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+ SubstatementValidator.builder(Rfc6020Mapping.IMPORT)
+ .add(Rfc6020Mapping.PREFIX, 1, 1).add(Rfc6020Mapping.REVISION_DATE, 0, 1).build();
public ImportStatementDefinition() {
super(Rfc6020Mapping.IMPORT);
}
@Override
- public ImportStatement createDeclared(
- final StmtContext<String, ImportStatement, ?> ctx) {
+ public ImportStatement createDeclared(final StmtContext<String, ImportStatement, ?> ctx) {
return new ImportStatementImpl(ctx);
}
}
@Override
- public void onFullDefinitionDeclared(Mutable<String, ImportStatement,
- EffectiveStatement<String, ImportStatement>> stmt) throws SourceException {
+ public void onFullDefinitionDeclared(
+ final Mutable<String, ImportStatement, EffectiveStatement<String, ImportStatement>> stmt) {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
}
importAction.apply(new InferenceAction() {
@Override
- public void apply() throws InferenceException {
+ public void apply() {
StmtContext<?, ?, ?> importedModule = null;
ModuleIdentifier importedModuleIdentifier = null;
if (impIdentifier.getRevision() == SimpleDateFormatUtil.DEFAULT_DATE_IMP) {
- Entry<ModuleIdentifier, StmtContext<?, ModuleStatement, EffectiveStatement<String, ModuleStatement>>> recentModuleEntry = findRecentModule(
- impIdentifier, stmt.getAllFromNamespace(ModuleNamespace.class));
+ Entry<ModuleIdentifier, StmtContext<?, ModuleStatement, EffectiveStatement<String, ModuleStatement>>> recentModuleEntry =
+ findRecentModule(impIdentifier, stmt.getAllFromNamespace(ModuleNamespace.class));
if (recentModuleEntry != null) {
importedModuleIdentifier = recentModuleEntry.getKey();
importedModule = recentModuleEntry.getValue();
Entry<ModuleIdentifier, StmtContext<?, ModuleStatement, EffectiveStatement<String, ModuleStatement>>> recentModuleEntry = null;
for (Entry<ModuleIdentifier, StmtContext<?, ModuleStatement, EffectiveStatement<String, ModuleStatement>>> moduleEntry : allModules.entrySet()) {
- if (moduleEntry.getKey().getName().equals(impIdentifier.getName())
- && moduleEntry.getKey().getRevision().compareTo(recentModuleIdentifier.getRevision()) > 0) {
- recentModuleIdentifier = moduleEntry.getKey();
+ final ModuleIdentifier id = moduleEntry.getKey();
+
+ if (id.getName().equals(impIdentifier.getName())
+ && id.getRevision().compareTo(recentModuleIdentifier.getRevision()) > 0) {
+ recentModuleIdentifier = id;
recentModuleEntry = moduleEntry;
}
}
@Override
public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
if (failed.contains(imported)) {
- throw new InferenceException(String.format("Imported module [%s] was not found.", impIdentifier),
- stmt.getStatementSourceReference());
+ throw new InferenceException(stmt.getStatementSourceReference(),
+ "Imported module [%s] was not found.", impIdentifier);
}
}
});
import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.SOURCE_LINKAGE;
import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-
import com.google.common.base.Optional;
import java.net.URI;
import java.util.Collection;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.IncludeEffectiveStatementImpl;
public class IncludeStatementImpl extends AbstractDeclaredStatement<String> implements IncludeStatement {
- private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
- .INCLUDE)
- .add(Rfc6020Mapping.REVISION_DATE, 0, 1)
- .build();
+ private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(
+ Rfc6020Mapping.INCLUDE).add(Rfc6020Mapping.REVISION_DATE, 0, 1).build();
- protected IncludeStatementImpl(StmtContext<String, IncludeStatement, ?> context) {
+ protected IncludeStatementImpl(final StmtContext<String, IncludeStatement, ?> context) {
super(context);
}
}
@Override
- public String parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
+ public String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
return value;
}
@Override
- public IncludeStatement createDeclared(StmtContext<String, IncludeStatement, ?> ctx) {
+ public IncludeStatement createDeclared(final StmtContext<String, IncludeStatement, ?> ctx) {
return new IncludeStatementImpl(ctx);
}
@Override
public EffectiveStatement<String, IncludeStatement> createEffective(
- StmtContext<String, IncludeStatement, EffectiveStatement<String, IncludeStatement>> ctx) {
+ final StmtContext<String, IncludeStatement, EffectiveStatement<String, IncludeStatement>> ctx) {
return new IncludeEffectiveStatementImpl(ctx);
}
@Override
public void onLinkageDeclared(
- final Mutable<String, IncludeStatement, EffectiveStatement<String, IncludeStatement>> stmt)
- throws SourceException {
+ final Mutable<String, IncludeStatement, EffectiveStatement<String, IncludeStatement>> stmt) {
final ModuleIdentifier includeSubmoduleIdentifier = getIncludeSubmoduleIdentifier(stmt);
ModelActionBuilder includeAction = stmt.newInferenceAction(SOURCE_LINKAGE);
SubmoduleNamespace.class, includeSubmoduleIdentifier, SOURCE_LINKAGE);
includeAction.apply(new InferenceAction() {
-
@Override
- public void apply() throws InferenceException {
+ public void apply() {
StmtContext<?, ?, ?> includedSubModuleContext = requiresCtxPrerequisite.get();
stmt.addToNs(IncludedModuleContext.class, includeSubmoduleIdentifier,
}
@Override
- public void prerequisiteFailed(Collection<? extends Prerequisite<?>> failed) throws InferenceException {
- if (failed.contains(requiresCtxPrerequisite)) {
- throw new InferenceException("Included submodule was not found: "+stmt.getStatementArgument(), stmt
- .getStatementSourceReference());
- }
+ public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
+ InferenceException.throwIf(failed.contains(requiresCtxPrerequisite),
+ stmt.getStatementSourceReference(),
+ "Included submodule '%s' was not found: ", stmt.getStatementArgument());
}
});
}
- private static ModuleIdentifier getIncludeSubmoduleIdentifier(Mutable<String, IncludeStatement, ?> stmt) {
+ private static ModuleIdentifier getIncludeSubmoduleIdentifier(final Mutable<String, IncludeStatement, ?> stmt) {
String subModuleName = stmt.getStatementArgument();
}
@Override
- public void onFullDefinitionDeclared(Mutable<String, IncludeStatement,
+ public void onFullDefinitionDeclared(final Mutable<String, IncludeStatement,
EffectiveStatement<String, IncludeStatement>> stmt) throws SourceException {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
import static org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator.MAX;
import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-
import com.google.common.base.Optional;
import java.net.URI;
import java.util.Date;
}
@Override
- public String parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
+ public String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
return value;
}
@Override
- public ModuleStatement createDeclared(StmtContext<String, ModuleStatement, ?> ctx) {
+ public ModuleStatement createDeclared(final StmtContext<String, ModuleStatement, ?> ctx) {
return new ModuleStatementImpl(ctx);
}
@Override
public EffectiveStatement<String, ModuleStatement> createEffective(
- StmtContext<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> ctx) {
+ final StmtContext<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> ctx) {
return new ModuleEffectiveStatementImpl(ctx);
}
@Override
- public void onLinkageDeclared(Mutable<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> stmt)
- throws SourceException {
+ public void onLinkageDeclared(final Mutable<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> stmt) {
Optional<URI> moduleNs = Optional.fromNullable(firstAttributeOf(stmt.declaredSubstatements(),
NamespaceStatement.class));
- if (!moduleNs.isPresent()) {
- throw new SourceException(String.format("Namespace of the module [%s] is missing",
- stmt.getStatementArgument()), stmt.getStatementSourceReference());
- }
+ SourceException.throwIf(!moduleNs.isPresent(), stmt.getStatementSourceReference(),
+ "Namespace of the module [%s] is missing", stmt.getStatementArgument());
Optional<Date> revisionDate = Optional.fromNullable(Utils.getLatestRevision(stmt.declaredSubstatements()));
if (!revisionDate.isPresent()) {
stmt.addContext(ModuleNamespaceForBelongsTo.class, moduleIdentifier.getName(), stmt);
stmt.addContext(NamespaceToModule.class, qNameModule, stmt);
- String modulePrefix = firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class);
- if (modulePrefix == null) {
- throw new SourceException(String.format("Prefix of the module [%s] is missing",
- stmt.getStatementArgument()), stmt.getStatementSourceReference());
- }
+ final String modulePrefix = firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class);
+ SourceException.throwIfNull(modulePrefix, stmt.getStatementSourceReference(),
+ "Prefix of the module [%s] is missing", stmt.getStatementArgument());
stmt.addToNs(PrefixToModule.class, modulePrefix, qNameModule);
stmt.addToNs(ModuleNameToModuleQName.class, stmt.getStatementArgument(), qNameModule);
stmt.addToNs(ModuleCtxToModuleQName.class, stmt, qNameModule);
stmt.addToNs(ModuleQNameToModuleName.class, qNameModule, stmt.getStatementArgument());
stmt.addToNs(ModuleIdentifierToModuleQName.class, moduleIdentifier, qNameModule);
-
stmt.addToNs(ImpPrefixToModuleIdentifier.class, modulePrefix, moduleIdentifier);
}
@Override
- public void onFullDefinitionDeclared(Mutable<String, ModuleStatement,
+ public void onFullDefinitionDeclared(final Mutable<String, ModuleStatement,
EffectiveStatement<String, ModuleStatement>> stmt) throws SourceException {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.RevisionDateEffectiveStatementImpl;
-public class RevisionDateStatementImpl extends
- AbstractDeclaredStatement<Date> implements RevisionDateStatement {
- private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
- .REVISION_DATE)
- .build();
+public class RevisionDateStatementImpl extends AbstractDeclaredStatement<Date> implements RevisionDateStatement {
+ private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+ SubstatementValidator.builder(Rfc6020Mapping.REVISION_DATE).build();
- protected RevisionDateStatementImpl(
- StmtContext<Date, RevisionDateStatement, ?> context) {
+ protected RevisionDateStatementImpl(final StmtContext<Date, RevisionDateStatement, ?> context) {
super(context);
}
}
@Override
- public Date parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) throws SourceException {
- Date revision;
+ public Date parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) throws SourceException {
try {
- revision = SimpleDateFormatUtil.getRevisionFormat()
- .parse(value);
+ return SimpleDateFormatUtil.getRevisionFormat().parse(value);
} catch (ParseException e) {
- throw new SourceException(String.format("Revision value %s is not in required format yyyy-MM-dd",
- value), ctx.getStatementSourceReference(), e);
+ throw new SourceException(ctx.getStatementSourceReference(), e,
+ "Revision value %s is not in required format yyyy-MM-dd", value);
}
-
- return revision;
}
@Override
- public RevisionDateStatement createDeclared(
- StmtContext<Date, RevisionDateStatement, ?> ctx) {
+ public RevisionDateStatement createDeclared(final StmtContext<Date, RevisionDateStatement, ?> ctx) {
return new RevisionDateStatementImpl(ctx);
}
@Override
public EffectiveStatement<Date, RevisionDateStatement> createEffective(
- StmtContext<Date, RevisionDateStatement, EffectiveStatement<Date, RevisionDateStatement>> ctx) {
+ final StmtContext<Date, RevisionDateStatement, EffectiveStatement<Date, RevisionDateStatement>> ctx) {
return new RevisionDateEffectiveStatementImpl(ctx);
}
@Override
- public void onFullDefinitionDeclared(StmtContext.Mutable<Date, RevisionDateStatement,
- EffectiveStatement<Date, RevisionDateStatement>> stmt) throws SourceException {
+ public void onFullDefinitionDeclared(
+ final StmtContext.Mutable<Date, RevisionDateStatement, EffectiveStatement<Date, RevisionDateStatement>> stmt) {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
}
public Date getDate() {
return argument();
}
-
}
public class RevisionStatementImpl extends AbstractDeclaredStatement<Date>
implements RevisionStatement {
- private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
- .REVISION)
- .add(Rfc6020Mapping.DESCRIPTION, 0, 1)
- .add(Rfc6020Mapping.REFERENCE, 0, 1)
- .build();
+ private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(
+ Rfc6020Mapping.REVISION)
+ .add(Rfc6020Mapping.DESCRIPTION, 0, 1).add(Rfc6020Mapping.REFERENCE, 0, 1).build();
- protected RevisionStatementImpl(
- StmtContext<Date, RevisionStatement, ?> context) {
+ protected RevisionStatementImpl(final StmtContext<Date, RevisionStatement, ?> context) {
super(context);
}
}
@Override
- public Date parseArgumentValue(StmtContext<?, ?, ?> ctx, String value)
- throws SourceException {
- Date revision;
+ public Date parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
try {
- revision = SimpleDateFormatUtil.getRevisionFormat()
- .parse(value);
+ return SimpleDateFormatUtil.getRevisionFormat().parse(value);
} catch (ParseException e) {
- throw new SourceException(String.format("Revision value %s is not in required format yyyy-MM-dd",
- value), ctx.getStatementSourceReference(), e);
+ throw new SourceException(ctx.getStatementSourceReference(), e,
+ "Revision value %s is not in required format yyyy-MM-dd", value);
}
-
- return revision;
}
@Override
- public RevisionStatement createDeclared(
- StmtContext<Date, RevisionStatement, ?> ctx) {
+ public RevisionStatement createDeclared(final StmtContext<Date, RevisionStatement, ?> ctx) {
return new RevisionStatementImpl(ctx);
}
@Override
public EffectiveStatement<Date, RevisionStatement> createEffective(
- StmtContext<Date, RevisionStatement, EffectiveStatement<Date, RevisionStatement>> ctx) {
+ final StmtContext<Date, RevisionStatement, EffectiveStatement<Date, RevisionStatement>> ctx) {
return new RevisionEffectiveStatementImpl(ctx);
}
@Override
- public void onFullDefinitionDeclared(StmtContext.Mutable<Date, RevisionStatement,
- EffectiveStatement<Date, RevisionStatement>> stmt) throws SourceException {
+ public void onFullDefinitionDeclared(
+ final StmtContext.Mutable<Date, RevisionStatement, EffectiveStatement<Date, RevisionStatement>> stmt) {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
}
import static org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator.MAX;
import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.findFirstDeclaredSubstatement;
import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-
import com.google.common.base.Optional;
import java.net.URI;
import java.util.Date;
.add(Rfc6020Mapping.USES, 0, MAX)
.add(Rfc6020Mapping.YANG_VERSION, 0, 1)
.build();
+ private static final Optional<Date> DEFAULT_REVISION = Optional.of(SimpleDateFormatUtil.DEFAULT_DATE_REV);
- protected SubmoduleStatementImpl(StmtContext<String, SubmoduleStatement, ?> context) {
+ protected SubmoduleStatementImpl(final StmtContext<String, SubmoduleStatement, ?> context) {
super(context);
}
}
@Override
- public String parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) {
+ public String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
return value;
}
@Override
public SubmoduleStatement createDeclared(
- StmtContext<String, SubmoduleStatement, ?> ctx) {
+ final StmtContext<String, SubmoduleStatement, ?> ctx) {
return new SubmoduleStatementImpl(ctx);
}
@Override
public EffectiveStatement<String, SubmoduleStatement> createEffective(
- StmtContext<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> ctx) {
+ final StmtContext<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> ctx) {
return new SubmoduleEffectiveStatementImpl(ctx);
}
@Override
public void onLinkageDeclared(
- Mutable<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> stmt)
+ final Mutable<String, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>> stmt)
throws SourceException {
- Optional<Date> revisionDate = Optional.fromNullable(Utils.getLatestRevision(stmt.declaredSubstatements()));
- if (!revisionDate.isPresent()) {
- revisionDate = Optional.of(SimpleDateFormatUtil.DEFAULT_DATE_REV);
- }
+ final Optional<Date> revisionDate = Optional.fromNullable(
+ Utils.getLatestRevision(stmt.declaredSubstatements())).or(DEFAULT_REVISION);
- ModuleIdentifier submoduleIdentifier = new ModuleIdentifierImpl(
- stmt.getStatementArgument(), Optional.<URI> absent(),
- revisionDate);
+ ModuleIdentifier submoduleIdentifier = new ModuleIdentifierImpl(stmt.getStatementArgument(),
+ Optional.<URI> absent(), revisionDate);
stmt.addContext(SubmoduleNamespace.class, submoduleIdentifier, stmt);
stmt.declaredSubstatements(), BelongsToStatement.class);
StmtContext<?, ?, ?> prefixSubStmtCtx = findFirstDeclaredSubstatement(
stmt, 0, BelongsToStatement.class, PrefixStatement.class);
-
- if (prefixSubStmtCtx == null) {
- throw new SourceException(String.format("Prefix of belongsTo statement is missing in submodule [%s]",
- stmt.getStatementArgument()), stmt.getStatementSourceReference());
- }
+ SourceException.throwIfNull(prefixSubStmtCtx, stmt.getStatementSourceReference(),
+ "Prefix of belongsTo statement is missing in submodule [%s]", stmt.getStatementArgument());
String prefix = (String) prefixSubStmtCtx.getStatementArgument();
- stmt.addToNs(BelongsToPrefixToModuleName.class, prefix,
- belongsToModuleName);
+ stmt.addToNs(BelongsToPrefixToModuleName.class, prefix, belongsToModuleName);
}
@Override
- public void onFullDefinitionDeclared(Mutable<String, SubmoduleStatement,
+ public void onFullDefinitionDeclared(final Mutable<String, SubmoduleStatement,
EffectiveStatement<String, SubmoduleStatement>> stmt) throws SourceException {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
import static org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator.MAX;
-
import com.google.common.base.Verify;
import java.util.Collection;
import javax.annotation.Nonnull;
final QName qname = Utils.qNameFromArgument(ctx, ctx.getStatementArgument());
final StmtContext<?, TypedefStatement, TypedefEffectiveStatement> typedef =
ctx.getFromNamespace(TypeNamespace.class, qname);
- if (typedef == null) {
- throw new SourceException("Type '" + qname + "' not found", ctx.getStatementSourceReference());
- }
+ SourceException.throwIfNull(typedef, ctx.getStatementSourceReference(), "Type '%s' not found", qname);
final TypedefEffectiveStatement effectiveTypedef = typedef.buildEffective();
Verify.verify(effectiveTypedef instanceof TypeDefEffectiveStatementImpl);
@Override
public void onFullDefinitionDeclared(
- final Mutable<String, TypeStatement, EffectiveStatement<String, TypeStatement>> stmt)
- throws SourceException {
+ final Mutable<String, TypeStatement, EffectiveStatement<String, TypeStatement>> stmt){
SUBSTATEMENT_VALIDATOR.validate(stmt);
// if it is yang built-in type, no prerequisite is needed, so simply return
* Otherwise perform no operation.
*/
typeAction.apply(new InferenceAction() {
-
@Override
public void apply() {
// Intentional NOOP
}
@Override
- public void prerequisiteFailed(Collection<? extends Prerequisite<?>> failed) {
- if (failed.contains(typePrereq)) {
- throw new InferenceException(String.format("Type [%s] was not found.", typeQName), stmt
- .getStatementSourceReference());
- }
+ public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
+ InferenceException.throwIf(failed.contains(typePrereq), stmt.getStatementSourceReference(),
+ "Type [%s] was not found.", typeQName);
}
});
}
max = parseDecimalConstraintValue(ctx, boundaries.next());
// if min larger than max then error
- if (compareNumbers(min, max) == 1) {
- throw new InferenceException(String.format(
- "Range constraint %s has descending order of boundaries; should be ascending",
- singleRange), ctx.getStatementSourceReference());
- }
- if (boundaries.hasNext()) {
- throw new SourceException(String.format("Wrong number of boundaries in range constraint %s",
- singleRange), ctx.getStatementSourceReference());
- }
+ InferenceException.throwIf(compareNumbers(min, max) == 1, ctx.getStatementSourceReference(),
+ "Range constraint %s has descending order of boundaries; should be ascending", singleRange);
+
+ SourceException.throwIf(boundaries.hasNext(), ctx.getStatementSourceReference(),
+ "Wrong number of boundaries in range constraint %s", singleRange);
} else {
max = min;
}
// some of intervals overlapping
if (rangeConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(rangeConstraints).getMax()) != 1) {
- throw new InferenceException(String.format("Some of the ranges in %s are not disjoint",
- rangeArgument), ctx.getStatementSourceReference());
+ throw new InferenceException(ctx.getStatementSourceReference(),
+ "Some of the ranges in %s are not disjoint", rangeArgument);
}
rangeConstraints.add(new RangeConstraintEffectiveImpl(min, max, description, reference));
// some of intervals overlapping
if (rangeConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(rangeConstraints).getMax()) != 1) {
- throw new InferenceException(String.format("Some of the length ranges in %s are not disjoint",
- rangeArgument), ctx.getStatementSourceReference());
+ throw new InferenceException(ctx.getStatementSourceReference(),
+ "Some of the length ranges in %s are not disjoint", rangeArgument);
}
rangeConstraints.add(new LengthConstraintEffectiveImpl(min, max, description, reference));
import org.opendaylight.yangtools.yang.model.api.stmt.ReferenceStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.StatusStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.TypeStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.TypedefStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.UnitsStatement;
import org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator;
.add(Rfc6020Mapping.UNITS, 0, 1)
.build();
- protected TypedefStatementImpl(StmtContext<QName, TypedefStatement, ?> context) {
+ protected TypedefStatementImpl(final StmtContext<QName, TypedefStatement, ?> context) {
super(context);
}
}
@Override
- public QName parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) throws SourceException {
+ public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
return Utils.qNameFromArgument(ctx, value);
}
@Override
- public TypedefStatement createDeclared(StmtContext<QName, TypedefStatement, ?> ctx) {
+ public TypedefStatement createDeclared(final StmtContext<QName, TypedefStatement, ?> ctx) {
return new TypedefStatementImpl(ctx);
}
@Override
public EffectiveStatement<QName, TypedefStatement> createEffective(
- StmtContext<QName, TypedefStatement, EffectiveStatement<QName, TypedefStatement>> ctx) {
+ final StmtContext<QName, TypedefStatement, EffectiveStatement<QName, TypedefStatement>> ctx) {
return new TypeDefEffectiveStatementImpl(ctx);
}
@Override
public void onStatementDefinitionDeclared(
- StmtContext.Mutable<QName, TypedefStatement, EffectiveStatement<QName, TypedefStatement>> stmt)
- throws SourceException {
+ final StmtContext.Mutable<QName, TypedefStatement, EffectiveStatement<QName, TypedefStatement>> stmt) {
if (stmt != null && stmt.getParentContext() != null) {
- if (stmt.getParentContext().getFromNamespace(TypeNamespace.class, stmt.getStatementArgument()) != null) {
- throw new SourceException(String.format("Duplicate name for typedef %s",
- stmt.getStatementArgument()), stmt.getStatementSourceReference());
- }
+ final StmtContext<?, TypedefStatement, TypedefEffectiveStatement> existing =
+ stmt.getParentContext().getFromNamespace(TypeNamespace.class, stmt.getStatementArgument());
+ SourceException.throwIf(existing != null, stmt.getStatementSourceReference(),
+ "Duplicate name for typedef %s", stmt.getStatementArgument());
stmt.getParentContext().addContext(TypeNamespace.class, stmt.getStatementArgument(), stmt);
}
}
@Override
- public void onFullDefinitionDeclared(StmtContext.Mutable<QName, TypedefStatement,
+ public void onFullDefinitionDeclared(final StmtContext.Mutable<QName, TypedefStatement,
EffectiveStatement<QName, TypedefStatement>> stmt) throws SourceException {
super.onFullDefinitionDeclared(stmt);
SUBSTATEMENT_VALIDATOR.validate(stmt);
package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
import static org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator.MAX;
-
import java.util.Collection;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
throws SourceException {
SUBSTATEMENT_VALIDATOR.validate(usesNode);
- if(StmtContextUtils.isInExtensionBody(usesNode)) {
+ if (StmtContextUtils.isInExtensionBody(usesNode)) {
return;
}
usesAction.apply(new InferenceAction() {
@Override
- public void apply() throws InferenceException {
+ public void apply() {
StatementContextBase<?, ?, ?> targetNodeStmtCtx = (StatementContextBase<?, ?, ?>) targetNodePre.get();
StatementContextBase<?, ?, ?> sourceGrpStmtCtx = (StatementContextBase<?, ?, ?>) sourceGroupingPre.get();
}
@Override
- public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) throws InferenceException {
- if (failed.contains(sourceGroupingPre)) {
- throw new InferenceException("Grouping " + groupingName + " was not resolved.", usesNode
- .getStatementSourceReference());
- }
+ public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
+ InferenceException.throwIf(failed.contains(sourceGroupingPre),
+ usesNode.getStatementSourceReference(), "Grouping '%s' was not resolved.", groupingName);
throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference());
}
});
// to detect if key contains duplicates
if ((new HashSet<>(keyTokens)).size() < keyTokens.size()) {
// FIXME: report all duplicate keys
- throw new SourceException(String.format("Duplicate value in list key: %s", value),
- ctx.getStatementSourceReference());
+ throw new SourceException(ctx.getStatementSourceReference(), "Duplicate value in list key: %s", value);
}
Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof DataSchemaNode) {
- DataSchemaNode dataSchemaNode = (DataSchemaNode) effectiveStatement;
+ final DataSchemaNode dataSchemaNode = (DataSchemaNode) effectiveStatement;
if (!mutableChildNodes.containsKey(dataSchemaNode.getQName())) {
- mutableChildNodes.put(dataSchemaNode.getQName(),
- dataSchemaNode);
+ mutableChildNodes.put(dataSchemaNode.getQName(), dataSchemaNode);
mutablePublicChildNodes.add(dataSchemaNode);
} else {
throw EffectiveStmtUtils.createNameCollisionSourceException(ctx, effectiveStatement);
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-public final class EffectiveStmtUtils {
+final class EffectiveStmtUtils {
private EffectiveStmtUtils() {
throw new UnsupportedOperationException("Utility class");
}
- public static SourceException createNameCollisionSourceException(final StmtContext<?, ?, ?> ctx,
+ static SourceException createNameCollisionSourceException(final StmtContext<?, ?, ?> ctx,
final EffectiveStatement<?, ?> effectiveStatement) {
- return new SourceException("Error in module '"
- + ctx.getRoot().getStatementArgument()
- + "': can not add '"
- + effectiveStatement.argument()
- + "'. Node name collision: '"
- + effectiveStatement.argument()
- + "' already declared.",
- ctx.getStatementSourceReference());
+ return new SourceException(ctx.getStatementSourceReference(),
+ "Error in module '%s': cannot add '%s'. Node name collision: '%s' already declared.",
+ ctx.getRoot().getStatementArgument(),
+ effectiveStatement.argument(),
+ effectiveStatement.argument());
}
-
}
this.revision = (revisionDateStmt == null) ? SimpleDateFormatUtil.DEFAULT_DATE_IMP : revisionDateStmt.argument();
PrefixEffectiveStatementImpl prefixStmt = firstEffective(PrefixEffectiveStatementImpl.class);
- if (prefixStmt != null ) {
+ if (prefixStmt != null) {
this.prefix = prefixStmt.argument();
} else {
throw new MissingSubstatementException("Prefix is mandatory substatement of import statement",
super(ctx);
this.original = ctx.getOriginalCtx() == null ? null : (LeafSchemaNode) ctx.getOriginalCtx().buildEffective();
- final TypeEffectiveStatement<?> typeStmt = firstSubstatementOfType(TypeEffectiveStatement.class);
- if (typeStmt == null) {
- throw new SourceException("Leaf is missing a 'type' statement", ctx.getStatementSourceReference());
- }
+ final TypeEffectiveStatement<?> typeStmt = SourceException.throwIfNull(
+ firstSubstatementOfType(TypeEffectiveStatement.class), ctx.getStatementSourceReference(),
+ "Leaf is missing a 'type' statement");
String dflt = null;
String units = null;
this.original = ctx.getOriginalCtx() == null ? null : (LeafListSchemaNode) ctx.getOriginalCtx()
.buildEffective();
- final TypeEffectiveStatement<?> typeStmt = firstSubstatementOfType(TypeEffectiveStatement.class);
- if (typeStmt == null) {
- throw new SourceException("Leaf-list is missing a 'type' statement", ctx.getStatementSourceReference());
- }
+ final TypeEffectiveStatement<?> typeStmt = SourceException.throwIfNull(
+ firstSubstatementOfType(TypeEffectiveStatement.class), ctx.getStatementSourceReference(),
+ "Leaf-list is missing a 'type' statement");
final ConcreteTypeBuilder<?> builder = ConcreteTypes.concreteTypeBuilder(typeStmt.getTypeDefinition(),
ctx.getSchemaPath().get());
final QName keyQName = key.getLastComponent();
if (!possibleLeafQNamesForKey.contains(keyQName)) {
- throw new InferenceException(String.format("Key '%s' misses node '%s' in list '%s'",
- keyEffectiveSubstatement.getDeclared().rawArgument(), keyQName.getLocalName(),
- ctx.getStatementArgument()), ctx.getStatementSourceReference());
+ throw new InferenceException(ctx.getStatementSourceReference(),
+ "Key '%s' misses node '%s' in list '%s'", keyEffectiveSubstatement.getDeclared().rawArgument(),
+ keyQName.getLocalName(), ctx.getStatementArgument());
}
keyDefinitionInit.add(keyQName);
typeDefinition = builder.build();
} catch (InvalidLengthConstraintException e) {
final LengthConstraint c = e.getOffendingConstraint();
- throw new SourceException(String.format("Invalid length constraint: <%s, %s>", c.getMin(), c.getMax()),
- ctx.getStatementSourceReference(), e);
+ throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid length constraint: <%s, %s>",
+ c.getMin(), c.getMax());
}
}
} else if (highestPosition != 4294967295L) {
newPos = highestPosition + 1;
} else {
- throw new SourceException("Bit " + b + " must have a position statement",
- ctx.getStatementSourceReference());
+ throw new SourceException(ctx.getStatementSourceReference(),
+ "Bit %s must have a position statement", b);
}
b = new BitImpl(newPos, b.getQName(), b.getPath(), b.getDescription(), b.getReference(),
b.getStatus(), b.getUnknownSchemaNodes());
}
- if (b.getPosition() < 0L || b.getPosition() > 4294967295L) {
- throw new SourceException("Bit " + b + " has illegal position", ctx.getStatementSourceReference());
- }
+ SourceException.throwIf(b.getPosition() < 0L && b.getPosition() > 4294967295L,
+ ctx.getStatementSourceReference(), "Bit %s has illegal position", b);
if (highestPosition == null || highestPosition < b.getPosition()) {
highestPosition = b.getPosition();
} else if (highestValue != 2147483647) {
newValue = highestValue + 1;
} else {
- throw new SourceException("Enum " + p + " must have a value statement",
- ctx.getStatementSourceReference());
+ throw new SourceException(ctx.getStatementSourceReference(),
+ "Enum '%s' must have a value statement", p);
}
p = new EnumPairImpl(p.getName(), newValue, p.getPath(), p.getDescription(), p.getReference(),
typeDefinition = builder.build();
} catch (InvalidRangeConstraintException e) {
final RangeConstraint c = e.getOffendingConstraint();
- throw new SourceException(String.format("Invalid range constraint: <%s, %s>", c.getMin(), c.getMax()),
- ctx.getStatementSourceReference(), e);
+ throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid range constraint: <%s, %s>",
+ c.getMin(), c.getMax());
}
}
typeDefinition = builder.build();
} catch (InvalidLengthConstraintException e) {
final LengthConstraint c = e.getOffendingConstraint();
- throw new SourceException(String.format("Invalid length constraint: <%s, %s>", c.getMin(), c.getMax()),
- ctx.getStatementSourceReference(), e);
+ throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid length constraint: <%s, %s>",
+ c.getMin(), c.getMax());
}
}
} catch (SomeModifiersUnresolvedException e) {
final Throwable rootCause = Throwables.getRootCause(e);
assertTrue(rootCause instanceof InferenceException);
- assertTrue(rootCause.getMessage().startsWith("Augment target not found: Absolute{path=[(urn:simple" +
- ".container.demo?revision=1970-01-01)unknown]}"));
+ assertTrue(rootCause.getMessage().startsWith(
+ "Augment target 'Absolute{path=[(urn:simple.container.demo?revision=1970-01-01)unknown]}' not found"));
}
}
fail("SourceException should be thrown");
}
} catch (SourceException e) {
- String expected = "Error in module 'container': can not add '(urn:simple.container" +
+ String expected = "Error in module 'container': cannot add '(urn:simple.container" +
".demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container" +
".demo?revision=1970-01-01)foo' already declared.";
assertTrue(e.getMessage().contains(expected));
fail("SourceException should be thrown");
}
} catch (SourceException e) {
- String expected = "Error in module 'container-list': can not add '(urn:simple.container" +
+ String expected = "Error in module 'container-list': cannot add '(urn:simple.container" +
".demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container" +
".demo?revision=1970-01-01)foo' already declared.";
assertTrue(e.getMessage().contains(expected));
fail("SourceException should be thrown");
}
} catch (SourceException e) {
- String expected = "Error in module 'container-leaf': can not add '(urn:simple.container" +
+ String expected = "Error in module 'container-leaf': cannot add '(urn:simple.container" +
".demo?revision=1970-01-01)foo'. Node name collision: '(urn:simple.container" +
".demo?revision=1970-01-01)foo' already declared.";
assertTrue(e.getMessage().contains(expected));
fail("SourceException should be thrown");
}
} catch (SourceException e) {
- String expected = "Error in module 'typedef': can not add '(urn:simple.container" +
+ String expected = "Error in module 'typedef': cannot add '(urn:simple.container" +
".demo?revision=1970-01-01)int-ext'. Node name collision: '(urn:simple.container" +
".demo?revision=1970-01-01)int-ext' already declared.";
assertTrue(e.getMessage().startsWith(expected));