Organize Imports for Checkstyle compliance.
Checkstyle compliance: line length.
Checkstyle compliance: various types of small changes.
Checkstyle compliant Exception handling.
Checkstyle final clean up & enforcement.
Add the fail on violation flag into the pom.xml .
Change-Id: Ib50c1754c97932714d4eb19b7e34a818af8a1a77
Signed-off-by: matus.kubica <matus.kubica@pantheon.tech>
Signed-off-by: Ivan Hrasko <ivan.hrasko@pantheon.tech>
<artifactId>yang-data-codec-xml</artifactId>
</dependency>
</dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
</project>
return currentContext.get();
}
- public CurrentSchemaContext(final SchemaService schemaService, final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProvider) {
+ public CurrentSchemaContext(final SchemaService schemaService,
+ final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProvider) {
this.rootSchemaSourceProvider = rootSchemaSourceProvider;
schemaContextListenerListenerRegistration = schemaService.registerSchemaContextListener(this);
}
public void onGlobalContextUpdated(final SchemaContext schemaContext) {
currentContext.set(schemaContext);
// FIXME is notifying all the listeners from this callback wise ?
- final Set<Capability> addedCaps = MdsalNetconfOperationServiceFactory.transformCapabilities(currentContext.get(), rootSchemaSourceProvider);
+ final Set<Capability> addedCaps = MdsalNetconfOperationServiceFactory.transformCapabilities(
+ currentContext.get(), rootSchemaSourceProvider);
for (final CapabilityListener listener : listeners1) {
listener.onCapabilitiesChanged(addedCaps, Collections.emptySet());
}
}
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- listener.onCapabilitiesChanged(MdsalNetconfOperationServiceFactory.transformCapabilities(currentContext.get(), rootSchemaSourceProvider), Collections.<Capability>emptySet());
+ listener.onCapabilitiesChanged(MdsalNetconfOperationServiceFactory.transformCapabilities(currentContext.get(),
+ rootSchemaSourceProvider), Collections.emptySet());
listeners1.add(listener);
return () -> listeners1.remove(listener);
}
private final OperationProvider operationProvider;
- public MdsalNetconfOperationService(final CurrentSchemaContext schemaContext, final String netconfSessionIdForReporting,
+ public MdsalNetconfOperationService(final CurrentSchemaContext schemaContext,
+ final String netconfSessionIdForReporting,
final DOMDataBroker dataBroker, final DOMRpcService rpcService) {
- this.operationProvider = new OperationProvider(netconfSessionIdForReporting, schemaContext, dataBroker, rpcService);
+ this.operationProvider = new OperationProvider(netconfSessionIdForReporting, schemaContext, dataBroker,
+ rpcService);
}
@Override
private final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProviderDependency;
private final NetconfOperationServiceFactoryListener netconfOperationServiceFactoryListener;
- public MdsalNetconfOperationServiceFactory(final SchemaService schemaService,
- final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProviderDependency,
- final NetconfOperationServiceFactoryListener netconfOperationServiceFactoryListener,
- final DOMDataBroker dataBroker,
- final DOMRpcService rpcService) {
+ public MdsalNetconfOperationServiceFactory(
+ final SchemaService schemaService,
+ final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProviderDependency,
+ final NetconfOperationServiceFactoryListener netconfOperationServiceFactoryListener,
+ final DOMDataBroker dataBroker,
+ final DOMRpcService rpcService) {
this.dataBroker = dataBroker;
this.rpcService = rpcService;
this.rootSchemaSourceProviderDependency = rootSchemaSourceProviderDependency;
- this.currentSchemaContext = new CurrentSchemaContext(Preconditions.checkNotNull(schemaService), rootSchemaSourceProviderDependency);
+ this.currentSchemaContext = new CurrentSchemaContext(Preconditions.checkNotNull(schemaService),
+ rootSchemaSourceProviderDependency);
this.netconfOperationServiceFactoryListener = netconfOperationServiceFactoryListener;
this.netconfOperationServiceFactoryListener.onAddNetconfOperationServiceFactory(this);
}
@Override
public MdsalNetconfOperationService createService(final String netconfSessionIdForReporting) {
Preconditions.checkState(dataBroker != null, "MD-SAL provider not yet initialized");
- return new MdsalNetconfOperationService(currentSchemaContext, netconfSessionIdForReporting, dataBroker, rpcService);
+ return new MdsalNetconfOperationService(currentSchemaContext, netconfSessionIdForReporting, dataBroker,
+ rpcService);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void close() {
try {
if (netconfOperationServiceFactoryListener != null) {
netconfOperationServiceFactoryListener.onRemoveNetconfOperationServiceFactory(this);
}
- } catch(Exception e) {
+ } catch (Exception e) {
LOG.error("Failed to close resources correctly - ignore", e);
}
}
return transformCapabilities(currentSchemaContext.getCurrentContext(), rootSchemaSourceProviderDependency);
}
- static Set<Capability> transformCapabilities(final SchemaContext currentContext, final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProviderDependency) {
+ static Set<Capability> transformCapabilities(
+ final SchemaContext currentContext,
+ final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProviderDependency) {
final Set<Capability> capabilities = new HashSet<>();
// Added by netconf-impl by default
-// capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
+ // capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
final Set<Module> modules = currentContext.getModules();
for (final Module module : modules) {
Optional<YangModuleCapability> cap = moduleToCapability(module, rootSchemaSourceProviderDependency);
- if(cap.isPresent()) {
+ if (cap.isPresent()) {
capabilities.add(cap.get());
}
for (final Module submodule : module.getSubmodules()) {
cap = moduleToCapability(submodule, rootSchemaSourceProviderDependency);
- if(cap.isPresent()) {
+ if (cap.isPresent()) {
capabilities.add(cap.get());
}
}
InputStream sourceStream = null;
String source;
try {
- sourceStream = rootSchemaSourceProviderDependency.getSource(moduleSourceIdentifier).checkedGet().openStream();
+ sourceStream = rootSchemaSourceProviderDependency.getSource(moduleSourceIdentifier).checkedGet()
+ .openStream();
source = CharStreams.toString(new InputStreamReader(sourceStream, StandardCharsets.UTF_8));
} catch (IOException | SchemaSourceException e) {
LOG.warn("Ignoring source for module {}. Unable to read content", moduleSourceIdentifier, e);
LOG.warn("Error closing yang source stream {}. Ignoring", moduleSourceIdentifier, e);
}
- if(source !=null) {
+ if (source != null) {
return Optional.of(new YangModuleCapability(module, source));
} else {
LOG.warn("Missing source for module {}. This module will not be available from netconf server",
private final DOMRpcService rpcService;
private final TransactionProvider transactionProvider;
- public OperationProvider(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
- final DOMDataBroker dataBroker, final DOMRpcService rpcService) {
+ OperationProvider(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
+ final DOMDataBroker dataBroker, final DOMRpcService rpcService) {
this.netconfSessionIdForReporting = netconfSessionIdForReporting;
this.schemaContext = schemaContext;
this.dataBroker = dataBroker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TransactionProvider implements AutoCloseable{
+public class TransactionProvider implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(TransactionProvider.class);
private final String netconfSessionIdForReporting;
- private static final String NO_TRANSACTION_FOUND_FOR_SESSION = "No candidateTransaction found for session ";
-
+ private static final String NO_TRANSACTION_FOUND_FOR_SESSION = "No candidateTransaction found for session ";
public TransactionProvider(final DOMDataBroker dataBroker, final String netconfSessionIdForReporting) {
this.dataBroker = dataBroker;
} catch (final TransactionCommitFailedException e) {
LOG.debug("Transaction {} failed on", candidateTransaction, e);
final String cause = e.getCause() != null ? (" Cause: " + e.getCause().getMessage()) : "";
- throw new DocumentedException("Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting +
- cause,
+ throw new DocumentedException(
+ "Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting + cause,
ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
} finally {
allOpenReadWriteTransactions.remove(candidateTransaction);
LOG.debug("Aborting current candidateTransaction");
final Optional<DOMDataReadWriteTransaction> otx = getCandidateTransaction();
if (!otx.isPresent()) {
- LOG.warn("discard-changes triggerd on an empty transaction for session: {}", netconfSessionIdForReporting );
+ LOG.warn("discard-changes triggerd on an empty transaction for session: {}", netconfSessionIdForReporting);
return;
}
candidateTransaction.cancel();
public synchronized void abortRunningTransaction(final DOMDataReadWriteTransaction tx) {
LOG.debug("Aborting current running Transaction");
- Preconditions.checkState(runningTransaction != null, NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
+ Preconditions.checkState(runningTransaction != null,
+ NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
tx.cancel();
allOpenReadWriteTransactions.remove(tx);
}
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
boolean commitStatus = transactionProvider.commitTransaction();
LOG.trace("Commit completed successfully {}", commitStatus);
private final ModifyAction action;
private final List<PathArgument> path;
- public DataTreeChange(final NormalizedNode<?, ?> changeRoot, final ModifyAction action, final ArrayList<PathArgument> path) {
+ public DataTreeChange(final NormalizedNode<?, ?> changeRoot, final ModifyAction action,
+ final ArrayList<PathArgument> path) {
this.changeRoot = changeRoot;
this.action = action;
this.path = Lists.reverse(path);
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
try {
transactionProvider.abortTransaction();
} catch (final IllegalStateException e) {
LOG.warn("Abort failed ", e);
final Map<String, String> errorInfo = new HashMap<>();
- errorInfo
- .put(ErrorTag.OPERATION_FAILED.name(),
- "Operation failed. Use 'get-config' or 'edit-config' before triggering 'discard-changes' operation");
+ errorInfo.put(ErrorTag.OPERATION_FAILED.name(),
+ "Operation failed. Use 'get-config' or 'edit-config' before triggering "
+ + OPERATION_NAME + " operation");
throw new DocumentedException(e.getMessage(), e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
ErrorSeverity.ERROR, errorInfo);
}
final YangInstanceIdentifier path = YangInstanceIdentifier.create(change.getPath());
final NormalizedNode<?, ?> changeData = change.getChangeRoot();
switch (change.getAction()) {
- case NONE:
- return;
- case MERGE:
- mergeParentMap(rwtx, path, changeData);
- rwtx.merge(LogicalDatastoreType.CONFIGURATION, path, changeData);
- break;
- case CREATE:
- try {
- final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
- if (readResult.isPresent()) {
- throw new DocumentedException("Data already exists, cannot execute CREATE operation",
- ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
+ case NONE:
+ return;
+ case MERGE:
+ mergeParentMap(rwtx, path, changeData);
+ rwtx.merge(LogicalDatastoreType.CONFIGURATION, path, changeData);
+ break;
+ case CREATE:
+ try {
+ final Optional<NormalizedNode<?, ?>> readResult =
+ rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
+ if (readResult.isPresent()) {
+ throw new DocumentedException("Data already exists, cannot execute CREATE operation",
+ ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
+ }
+ mergeParentMap(rwtx, path, changeData);
+ rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
+ } catch (final ReadFailedException e) {
+ LOG.warn("Read from datastore failed when trying to read data for create operation", change, e);
}
+ break;
+ case REPLACE:
mergeParentMap(rwtx, path, changeData);
rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
- } catch (final ReadFailedException e) {
- LOG.warn("Read from datastore failed when trying to read data for create operation", change, e);
- }
- break;
- case REPLACE:
- mergeParentMap(rwtx, path, changeData);
- rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
- break;
- case DELETE:
- try {
- final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
- if (!readResult.isPresent()) {
- throw new DocumentedException("Data is missing, cannot execute DELETE operation",
- ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
+ break;
+ case DELETE:
+ try {
+ final Optional<NormalizedNode<?, ?>> readResult =
+ rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
+ if (!readResult.isPresent()) {
+ throw new DocumentedException("Data is missing, cannot execute DELETE operation",
+ ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
+ }
+ rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
+ } catch (final ReadFailedException e) {
+ LOG.warn("Read from datastore failed when trying to read data for delete operation", change, e);
}
+ break;
+ case REMOVE:
rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
- } catch (final ReadFailedException e) {
- LOG.warn("Read from datastore failed when trying to read data for delete operation", change, e);
- }
- break;
- case REMOVE:
- rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
- break;
- default:
- LOG.warn("Unknown/not implemented operation, not executing");
+ break;
+ default:
+ LOG.warn("Unknown/not implemented operation, not executing");
}
}
final YangInstanceIdentifier mapNodeYid = path.getParent();
//merge empty map
final MapNode mixinNode = Builders.mapBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(mapNodeYid.getLastPathArgument().getNodeType()))
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(mapNodeYid.getLastPathArgument().getNodeType()))
.build();
rwtx.merge(LogicalDatastoreType.CONFIGURATION, mapNodeYid, mixinNode);
}
private NormalizedNode<?, ?> parseIntoNormalizedNode(final DataSchemaNode schemaNode, final XmlElement element,
final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider) {
if (schemaNode instanceof ContainerSchemaNode) {
- return DomToNormalizedNodeParserFactory
- .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
+ return DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(),
+ schemaContext.getCurrentContext(), editOperationStrategyProvider)
.getContainerNodeParser()
.parse(Collections.singletonList(element.getDomElement()), (ContainerSchemaNode) schemaNode);
} else if (schemaNode instanceof ListSchemaNode) {
- return DomToNormalizedNodeParserFactory
- .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
+ return DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(),
+ schemaContext.getCurrentContext(), editOperationStrategyProvider)
.getMapNodeParser()
.parse(Collections.singletonList(element.getDomElement()), (ListSchemaNode) schemaNode);
} else {
try {
// returns module with newest revision since findModuleByNamespace returns a set of modules and we only
// need the newest one
- final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null);
+ final Module module =
+ schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null);
if (module == null) {
// no module is present with this namespace
throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace,
if (schemaNode != null) {
dataSchemaNode = Optional.of(schemaNode);
} else {
- throw new DocumentedException("Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
+ throw new DocumentedException(
+ "Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
ErrorType.APPLICATION,
ErrorTag.UNKNOWN_NAMESPACE,
ErrorSeverity.ERROR);
throw new DocumentedException("Multiple target elements", ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE,
ErrorSeverity.ERROR);
} else {
- final XmlElement targetChildNode = XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement();
+ final XmlElement targetChildNode =
+ XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement();
return Datastore.valueOf(targetChildNode.getName());
}
}
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.EditConfigInput;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
class EditOperationStrategyProvider extends DomToNormalizedNodeParserFactory.BuildingStrategyProvider {
- private static final QName OPERATION_ATTRIBUTE = QName.create(EditConfigInput.QNAME.getNamespace(), null, XmlNetconfConstants.OPERATION_ATTR_KEY);
+ private static final QName OPERATION_ATTRIBUTE = QName.create(EditConfigInput.QNAME.getNamespace(), null,
+ XmlNetconfConstants.OPERATION_ATTR_KEY);
private final DataTreeChangeTracker changeTracker;
- public EditOperationStrategyProvider(final DataTreeChangeTracker changeTracker) {
+ EditOperationStrategyProvider(final DataTreeChangeTracker changeTracker) {
this.changeTracker = changeTracker;
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, LeafNode<?>> forLeaf() {
+ protected ExtensibleParser.BuildingStrategy<NodeIdentifier, LeafNode<?>> forLeaf() {
return new NetconfOperationLeafStrategy(changeTracker);
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, ContainerNode> forContainer() {
+ protected ExtensibleParser.BuildingStrategy<NodeIdentifier, ContainerNode> forContainer() {
return new NetconfOperationContainerStrategy<>(changeTracker);
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, MapNode> forMap() {
+ protected ExtensibleParser.BuildingStrategy<NodeIdentifier, MapNode> forMap() {
return new NetconfOperationCollectionStrategy<>(changeTracker);
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<?>> forLeafSetEntry() {
+ protected ExtensibleParser.BuildingStrategy<NodeWithValue, LeafSetEntryNode<?>> forLeafSetEntry() {
return new NetconfOperationLeafSetEntryStrategy(changeTracker);
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> forMapEntry() {
+ protected ExtensibleParser.BuildingStrategy<NodeIdentifierWithPredicates, MapEntryNode> forMapEntry() {
return new NetconfOperationContainerStrategy<>(changeTracker);
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, OrderedMapNode> forOrderedList() {
+ protected ExtensibleParser.BuildingStrategy<NodeIdentifier, OrderedMapNode> forOrderedList() {
return new NetconfOperationCollectionStrategy<>(changeTracker);
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, UnkeyedListEntryNode> forUnkeyedListEntry() {
+ protected ExtensibleParser.BuildingStrategy<NodeIdentifier, UnkeyedListEntryNode> forUnkeyedListEntry() {
return new NetconfOperationContainerStrategy<>(changeTracker);
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, UnkeyedListNode> forUnkeyedList() {
+ protected ExtensibleParser.BuildingStrategy<NodeIdentifier, UnkeyedListNode> forUnkeyedList() {
return new NetconfOperationCollectionStrategy<>(changeTracker);
}
@Override
- protected ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> forChoice() {
+ protected ExtensibleParser.BuildingStrategy<NodeIdentifier, ChoiceNode> forChoice() {
return new NetconfOperationContainerStrategy<>(changeTracker);
}
@Override
- public ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.AugmentationIdentifier, AugmentationNode> forAugmentation() {
+ public ExtensibleParser.BuildingStrategy<AugmentationIdentifier, AugmentationNode> forAugmentation() {
return new NetconfOperationContainerStrategy<>(changeTracker);
}
- private static class NetconfOperationCollectionStrategy<N extends NormalizedNode<YangInstanceIdentifier.NodeIdentifier, ?>> implements ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, N> {
+ private static class NetconfOperationCollectionStrategy<N extends NormalizedNode<NodeIdentifier, ?>>
+ implements ExtensibleParser.BuildingStrategy<NodeIdentifier, N> {
private final DataTreeChangeTracker changeTracker;
- public NetconfOperationCollectionStrategy(final DataTreeChangeTracker changeTracker) {
+ NetconfOperationCollectionStrategy(final DataTreeChangeTracker changeTracker) {
this.changeTracker = changeTracker;
}
@Nullable
@Override
- public N build(final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ?, N> builder) {
+ public N build(final NormalizedNodeBuilder<NodeIdentifier, ?, N> builder) {
changeTracker.popPath();
return builder.build();
}
@Override
- public void prepareAttributes(final Map<QName, String> attributes, final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ?, N> containerBuilder) {
+ public void prepareAttributes(
+ final Map<QName, String> attributes,
+ final NormalizedNodeBuilder<NodeIdentifier, ?, N> containerBuilder) {
changeTracker.pushPath(containerBuilder.build().getIdentifier());
}
}
- public static final class NetconfOperationLeafStrategy implements ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeIdentifier, LeafNode<?>> {
+ public static final class NetconfOperationLeafStrategy
+ implements ExtensibleParser.BuildingStrategy<NodeIdentifier, LeafNode<?>> {
private final DataTreeChangeTracker dataTreeChangeTracker;
- public NetconfOperationLeafStrategy(final DataTreeChangeTracker dataTreeChangeTracker) {
+ NetconfOperationLeafStrategy(final DataTreeChangeTracker dataTreeChangeTracker) {
this.dataTreeChangeTracker = dataTreeChangeTracker;
}
@Nullable
@Override
- public LeafNode<?> build(final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ?, LeafNode<?>> builder) {
+ public LeafNode<?> build(
+ final NormalizedNodeBuilder<NodeIdentifier, ?, LeafNode<?>> builder) {
LeafNode<?> node = builder.build();
String operation = (String) node.getAttributeValue(OPERATION_ATTRIBUTE);
if (operation == null) {
return node;
}
- if(builder instanceof AttributesBuilder<?>) {
+ if (builder instanceof AttributesBuilder<?>) {
((AttributesBuilder<?>) builder).withAttributes(Collections.<QName, String>emptyMap());
}
node = builder.build();
ModifyAction action = ModifyAction.fromXmlValue(operation);
- if (dataTreeChangeTracker.getDeleteOperationTracker() > 0 || dataTreeChangeTracker.getRemoveOperationTracker() > 0) {
+ if (dataTreeChangeTracker.getDeleteOperationTracker() > 0
+ || dataTreeChangeTracker .getRemoveOperationTracker() > 0) {
return node;
} else {
if (!action.equals(dataTreeChangeTracker.peekAction())) {
dataTreeChangeTracker.pushPath(node.getIdentifier());
- dataTreeChangeTracker.addDataTreeChange(new DataTreeChangeTracker.DataTreeChange(node, action, new ArrayList<>(dataTreeChangeTracker.getCurrentPath())));
+ dataTreeChangeTracker.addDataTreeChange(new DataTreeChangeTracker.DataTreeChange(node, action,
+ new ArrayList<>(dataTreeChangeTracker.getCurrentPath())));
dataTreeChangeTracker.popPath();
return null;
} else {
}
@Override
- public void prepareAttributes(final Map<QName, String> attributes, final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ?, LeafNode<?>> containerBuilder) {
+ public void prepareAttributes(
+ final Map<QName, String> attributes,
+ final NormalizedNodeBuilder<NodeIdentifier, ?, LeafNode<?>> containerBuilder) {
// Noop
}
}
- public static final class NetconfOperationLeafSetEntryStrategy implements ExtensibleParser.BuildingStrategy<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<?>> {
+ public static final class NetconfOperationLeafSetEntryStrategy
+ implements ExtensibleParser.BuildingStrategy<NodeWithValue, LeafSetEntryNode<?>> {
private final DataTreeChangeTracker dataTreeChangeTracker;
- public NetconfOperationLeafSetEntryStrategy(final DataTreeChangeTracker dataTreeChangeTracker) {
+ NetconfOperationLeafSetEntryStrategy(final DataTreeChangeTracker dataTreeChangeTracker) {
this.dataTreeChangeTracker = dataTreeChangeTracker;
}
@Nullable
@Override
- public LeafSetEntryNode<?> build(final NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, ?, LeafSetEntryNode<?>> builder) {
+ public LeafSetEntryNode<?> build(final NormalizedNodeBuilder<NodeWithValue, ?, LeafSetEntryNode<?>> builder) {
LeafSetEntryNode<?> node = builder.build();
String operation = (String) node.getAttributeValue(OPERATION_ATTRIBUTE);
if (operation == null) {
node = builder.build();
ModifyAction action = ModifyAction.fromXmlValue(operation);
- if (dataTreeChangeTracker.getDeleteOperationTracker() > 0 || dataTreeChangeTracker.getRemoveOperationTracker() > 0) {
+ if (dataTreeChangeTracker.getDeleteOperationTracker() > 0
+ || dataTreeChangeTracker.getRemoveOperationTracker() > 0) {
return node;
} else {
if (!action.equals(dataTreeChangeTracker.peekAction())) {
dataTreeChangeTracker.pushPath(node.getIdentifier());
- dataTreeChangeTracker.addDataTreeChange(new DataTreeChangeTracker.DataTreeChange(node, action, new ArrayList<>(dataTreeChangeTracker.getCurrentPath())));
+ dataTreeChangeTracker.addDataTreeChange(new DataTreeChangeTracker.DataTreeChange(node, action,
+ new ArrayList<>(dataTreeChangeTracker.getCurrentPath())));
dataTreeChangeTracker.popPath();
return null;
} else {
}
@Override
- public void prepareAttributes(final Map<QName, String> attributes, final NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, ?, LeafSetEntryNode<?>> containerBuilder) {
-
+ public void prepareAttributes(
+ final Map<QName, String> attributes,
+ final NormalizedNodeBuilder<NodeWithValue, ?, LeafSetEntryNode<?>> containerBuilder) {
}
}
- public static final class NetconfOperationContainerStrategy<P extends YangInstanceIdentifier.PathArgument, N extends DataContainerNode<P>> implements ExtensibleParser.BuildingStrategy<P, N> {
+ public static final class NetconfOperationContainerStrategy<P extends PathArgument, N
+ extends DataContainerNode<P>> implements ExtensibleParser.BuildingStrategy<P, N> {
private final DataTreeChangeTracker dataTreeChangeTracker;
- public NetconfOperationContainerStrategy(final DataTreeChangeTracker dataTreeChangeTracker) {
+ NetconfOperationContainerStrategy(final DataTreeChangeTracker dataTreeChangeTracker) {
this.dataTreeChangeTracker = dataTreeChangeTracker;
}
final ModifyAction currentAction = dataTreeChangeTracker.popAction();
//if we know that we are going to delete a parent node just complete the entire subtree
- if (dataTreeChangeTracker.getDeleteOperationTracker() > 0 || dataTreeChangeTracker.getRemoveOperationTracker() > 0) {
+ if (dataTreeChangeTracker.getDeleteOperationTracker() > 0
+ || dataTreeChangeTracker.getRemoveOperationTracker() > 0) {
dataTreeChangeTracker.popPath();
return node;
} else {
//if parent and current actions dont match create a DataTreeChange and add it to the change list
//dont add a new child to the parent node
if (!currentAction.equals(dataTreeChangeTracker.peekAction())) {
- dataTreeChangeTracker.addDataTreeChange(new DataTreeChangeTracker.DataTreeChange(node, currentAction, new ArrayList<>(dataTreeChangeTracker.getCurrentPath())));
+ dataTreeChangeTracker.addDataTreeChange(new DataTreeChangeTracker.DataTreeChange(node,
+ currentAction, new ArrayList<>(dataTreeChangeTracker.getCurrentPath())));
dataTreeChangeTracker.popPath();
return null;
} else {
}
@Override
- public void prepareAttributes(final Map<QName, String> attributes, final NormalizedNodeBuilder<P, ?, N> containerBuilder) {
+ public void prepareAttributes(final Map<QName, String> attributes,
+ final NormalizedNodeBuilder<P, ?, N> containerBuilder) {
dataTreeChangeTracker.pushPath(containerBuilder.build().getIdentifier());
final String operation = attributes.get(OPERATION_ATTRIBUTE);
if (operation != null) {
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-// FIXME Duplicated code
-// netconf/netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/Lock.java
+/* FIXME Duplicated code
+ netconf/netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/
+ confignetconfconnector/operations/Lock.java
+ */
public class Lock extends AbstractSingletonNetconfOperation {
private static final Logger LOG = LoggerFactory.getLogger(Lock.class);
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
final Datastore targetDatastore = extractTargetParameter(operationElement);
if (targetDatastore == Datastore.candidate) {
LOG.debug("Locking candidate datastore on session: {}", getNetconfSessionIdForReporting());
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
- throw new DocumentedException("Unable to lock " + targetDatastore + " datastore", DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, DocumentedException.ErrorSeverity.ERROR);
+ throw new DocumentedException("Unable to lock " + targetDatastore + " datastore",
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED,
+ DocumentedException.ErrorSeverity.ERROR);
}
static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
private final DOMRpcService rpcService;
- public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final DOMRpcService rpcService) {
+ public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
+ final DOMRpcService rpcService) {
super(netconfSessionIdForReporting);
this.schemaContext = schemaContext;
this.rpcService = rpcService;
//this returns module with the newest revision if more then 1 module with same namespace is found
private Optional<Module> getModule(final URI namespaceURI) {
- return Optional.fromNullable(schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null));
+ return Optional.fromNullable(
+ schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null));
}
- private Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI, final String name) {
+ private Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
+ final String name) {
for (final RpcDefinition rpcDef : module.getRpcs()) {
if (rpcDef.getQName().getNamespace().equals(namespaceURI)
&& rpcDef.getQName().getLocalName().equals(name)) {
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
final String netconfOperationName = operationElement.getName();
final String netconfOperationNamespace;
final Optional<Module> moduleOptional = getModule(namespaceURI);
if (!moduleOptional.isPresent()) {
- throw new DocumentedException("Unable to find module in Schema Context with namespace and name : " +
- namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
+ throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
+ + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
}
- final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(), namespaceURI, netconfOperationName);
+ final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
+ namespaceURI, netconfOperationName);
if (!rpcDefinitionOptional.isPresent()) {
- throw new DocumentedException("Unable to find RpcDefinition with namespace and name : " + namespaceURI + " " + netconfOperationName,
+ throw new DocumentedException(
+ "Unable to find RpcDefinition with namespace and name : "
+ + namespaceURI + " " + netconfOperationName,
ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
}
try {
final DOMRpcResult result = rpcFuture.checkedGet();
if (result.getResult() == null) {
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK,
+ Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
}
return (Element) transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
} catch (final DOMRpcException e) {
final Map<String, Attr> attributes = requestElement.getAttributes();
final Element response = handle(document, operationElement, subsequentOperation);
- final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
+ Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
- if(XmlElement.fromDomElement(response).hasNamespace()) {
+ if (XmlElement.fromDomElement(response).hasNamespace()) {
rpcReply.appendChild(response);
} else {
final NodeList list = response.getChildNodes();
return document;
}
- private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data, final SchemaPath rpcOutputPath) {
+ private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
+ final SchemaPath rpcOutputPath) {
final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
}
}
- private void writeRootElement(final XMLStreamWriter xmlWriter, final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
+ private void writeRootElement(final XMLStreamWriter xmlWriter, final SchemaOrderedNormalizedNodeWriter nnWriter,
+ final ContainerNode data) {
try {
final Collection<DataContainerChild<?, ?>> value = (Collection) data.getValue();
nnWriter.write(value);
}
/**
- * Parses xml element rpc input into normalized node or null if rpc does not take any input
- * @param oElement rpc xml element
- * @param input input container schema node, or null if rpc does not take any input
+ * Parses xml element rpc input into normalized node or null if rpc does not take any input.
+ *
+ * @param element rpc xml element
+ * @param input input container schema node, or null if rpc does not take any input
* @return parsed rpc into normalized node, or null if input schema is null
*/
@Nullable
- private NormalizedNode<?, ?> rpcToNNode(final XmlElement oElement, @Nullable final ContainerSchemaNode input) {
+ private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input) {
return input.getChildNodes().isEmpty() ? null : DomToNormalizedNodeParserFactory
.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext())
.getContainerNodeParser()
- .parse(Collections.singletonList(oElement.getDomElement()), input);
+ .parse(Collections.singletonList(element.getDomElement()), input);
}
}
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-// FIXME Duplicated code
-// netconf/netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/UnLock.java
+/* FIXME Duplicated code
+ netconf/netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/
+ operations/UnLock.java
+*/
public class Unlock extends AbstractSingletonNetconfOperation {
private static final Logger LOG = LoggerFactory.getLogger(Unlock.class);
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
final Datastore targetDatastore = Lock.extractTargetParameter(operationElement);
if (targetDatastore == Datastore.candidate) {
LOG.debug("Unlocking candidate datastore on session: {}", getNetconfSessionIdForReporting());
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
- throw new DocumentedException("Unable to unlock " + targetDatastore + " datastore", DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, DocumentedException.ErrorSeverity.ERROR);
+ throw new DocumentedException("Unable to unlock " + targetDatastore + " datastore",
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED,
+ DocumentedException.ErrorSeverity.ERROR);
}
@Override
package org.opendaylight.netconf.mdsal.connector.ops.get;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.mdsal.connector.ops.Datastore;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public abstract class AbstractGet extends AbstractSingletonNetconfOperation {
+ private static final XMLOutputFactory XML_OUTPUT_FACTORY;
+ private static final YangInstanceIdentifier ROOT = YangInstanceIdentifier.EMPTY;
+ private static final String FILTER = "filter";
- private static final Logger LOG = LoggerFactory.getLogger(AbstractGet.class);
+ static {
+ XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
+ XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
+ }
- protected static final String FILTER = "filter";
- static final YangInstanceIdentifier ROOT = YangInstanceIdentifier.builder().build();
protected final CurrentSchemaContext schemaContext;
private final FilterContentValidator validator;
this.validator = new FilterContentValidator(schemaContext);
}
- private static final XMLOutputFactory XML_OUTPUT_FACTORY;
-
- static {
- XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
- XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
- }
-
- protected Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data, final YangInstanceIdentifier dataRoot) {
-
+ protected Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
+ final YangInstanceIdentifier dataRoot) {
final DOMResult result = new DOMResult(document.createElement(XmlNetconfConstants.DATA_KEY));
final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
return result.getNode();
}
-
private XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
try {
return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
}
}
- private static final Function<PathArgument, QName> PATH_ARG_TO_QNAME = new Function<YangInstanceIdentifier.PathArgument, QName>() {
- @Override
- public QName apply(final YangInstanceIdentifier.PathArgument input) {
- return input.getNodeType();
- }
- };
-
private SchemaPath getSchemaPath(final YangInstanceIdentifier dataRoot) {
- return SchemaPath.create(Iterables.transform(dataRoot.getPathArguments(), PATH_ARG_TO_QNAME), dataRoot.equals(ROOT));
+ return SchemaPath.create(
+ Iterables.transform(dataRoot.getPathArguments(), PathArgument::getNodeType), dataRoot.equals(ROOT));
}
- private void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter, final ContainerNode data) {
+ private void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
+ final ContainerNode data) {
try {
if (data.getNodeType().equals(SchemaContext.NAME)) {
for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
}
}
- protected Element serializeNodeWithParentStructure(final Document document, final YangInstanceIdentifier dataRoot, final NormalizedNode node) {
+ protected Element serializeNodeWithParentStructure(final Document document, final YangInstanceIdentifier dataRoot,
+ final NormalizedNode node) {
if (!dataRoot.equals(ROOT)) {
return (Element) transformNormalizedNode(document,
ImmutableNodes.fromInstanceId(schemaContext.getCurrentContext(), dataRoot, node),
ROOT);
}
- return (Element) transformNormalizedNode(document, node, ROOT);
+ return (Element) transformNormalizedNode(document, node, ROOT);
}
/**
+ * Obtain data root according to filter from operation element.
*
* @param operationElement operation element
- * @return if Filter is present and not empty returns Optional of the InstanceIdentifier to the read location in datastore.
- * empty filter returns Optional.absent() which should equal an empty <data/> container in the response.
- * if filter is not present we want to read the entire datastore - return ROOT.
- * @throws DocumentedException
+ * @return if filter is present and not empty returns Optional of the InstanceIdentifier to the read location
+ * in datastore. Empty filter returns Optional.absent() which should equal an empty <data/>
+ * container in the response. If filter is not present we want to read the entire datastore - return ROOT.
+ * @throws DocumentedException if not possible to get identifier from filter
*/
- protected Optional<YangInstanceIdentifier> getDataRootFromFilter(final XmlElement operationElement) throws DocumentedException {
+ protected Optional<YangInstanceIdentifier> getDataRootFromFilter(final XmlElement operationElement)
+ throws DocumentedException {
final Optional<XmlElement> filterElement = operationElement.getOnlyChildElementOptionally(FILTER);
if (filterElement.isPresent()) {
if (filterElement.get().getChildElements().size() == 0) {
}
@VisibleForTesting
- protected YangInstanceIdentifier getInstanceIdentifierFromFilter(final XmlElement filterElement) throws DocumentedException {
+ protected YangInstanceIdentifier getInstanceIdentifierFromFilter(final XmlElement filterElement)
+ throws DocumentedException {
if (filterElement.getChildElements().size() != 1) {
throw new DocumentedException("Multiple filter roots not supported yet",
}
protected static final class GetConfigExecution {
-
private final Optional<Datastore> datastore;
- public GetConfigExecution(final Optional<Datastore> datastore) {
- this.datastore = datastore;
- }
- public Optional<Datastore> getDatastore() {
- return datastore;
+ GetConfigExecution(final Optional<Datastore> datastore) {
+ this.datastore = datastore;
}
static GetConfigExecution fromXml(final XmlElement xml, final String operationName) throws DocumentedException {
try {
validateInputRpc(xml, operationName);
} catch (final DocumentedException e) {
- throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
+ throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e.getErrorType(), e.getErrorTag(),
+ e.getErrorSeverity(), e.getErrorInfo());
}
final Optional<Datastore> sourceDatastore;
try {
sourceDatastore = parseSource(xml);
} catch (final DocumentedException e) {
- throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
+ throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e.getErrorType(),
+ e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
}
return new GetConfigExecution(sourceDatastore);
final Optional<XmlElement> sourceElement = xml.getOnlyChildElementOptionally(XmlNetconfConstants.SOURCE_KEY,
XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- return sourceElement.isPresent() ?
- Optional.of(Datastore.valueOf(sourceElement.get().getOnlyChildElement().getName())) : Optional.<Datastore>absent();
+ return sourceElement.isPresent()
+ ? Optional.of(Datastore.valueOf(sourceElement.get().getOnlyChildElement().getName()))
+ : Optional.<Datastore>absent();
}
- private static void validateInputRpc(final XmlElement xml, final String operationName) throws DocumentedException {
+ private static void validateInputRpc(final XmlElement xml, final String operationName) throws
+ DocumentedException {
xml.checkName(operationName);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
+ public Optional<Datastore> getDatastore() {
+ return datastore;
+ }
+
}
}
private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
private final CurrentSchemaContext schemaContext;
- /**
- * @param schemaContext current schema context
- */
public FilterContentValidator(final CurrentSchemaContext schemaContext) {
this.schemaContext = schemaContext;
}
*
* @param filterContent filter content
* @return YangInstanceIdentifier
- * @throws DocumentedException if filter content is not valid
+ * @throws DocumentedException if filter content validation failed
*/
public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
try {
final URI namespace = new URI(filterContent.getNamespace());
final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null);
final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
- final FilterTree filterTree = validateNode(filterContent, schema, new FilterTree(schema.getQName(),
- Type.OTHER, schema));
+ final FilterTree filterTree = validateNode(
+ filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema));
return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
- } catch (final DocumentedException e) {
- throw e;
- } catch (final Exception e) {
+ } catch (final URISyntaxException e) {
+ throw new RuntimeException("Wrong namespace in element + " + filterContent.toString());
+ } catch (final ValidationException e) {
LOG.debug("Filter content isn't valid", e);
throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
DocumentedException.ErrorType.APPLICATION,
}
/**
- * Returns module's child data node of given name space and name
+ * Returns module's child data node of given name space and name.
*
* @param module module
* @param nameSpace name space
return childNode;
}
}
- throw new DocumentedException("Unable to find node with namespace: " + nameSpace + "in schema context: " +
- schemaContext.getCurrentContext().toString(),
+ throw new DocumentedException("Unable to find node with namespace: " + nameSpace
+ + "in schema context: " + schemaContext.getCurrentContext().toString(),
DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
DocumentedException.ErrorSeverity.ERROR);
}
final Map<QName, Object> keys = new HashMap<>();
final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
- for (final QName qName : keyDefinition) {
- final Optional<XmlElement> childElements = current.getOnlyChildElementOptionally(qName.getLocalName());
+ for (final QName qualifiedName : keyDefinition) {
+ final Optional<XmlElement> childElements =
+ current.getOnlyChildElementOptionally(qualifiedName.getLocalName());
if (!childElements.isPresent()) {
return Collections.emptyMap();
}
final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
if (keyValue.isPresent()) {
- final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qName);
+ final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qualifiedName);
if (listKey instanceof IdentityrefTypeDefinition) {
- keys.put(qName, keyValue.get());
+ keys.put(qualifiedName, keyValue.get());
} else {
if (listKey.getType() instanceof IdentityrefTypeDefinition) {
final Document document = filterContent.getDomElement().getOwnerDocument();
final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
- final XmlCodecFactory xmlCodecFactory = XmlCodecFactory.create(schemaContext.getCurrentContext());
+ final XmlCodecFactory xmlCodecFactory =
+ XmlCodecFactory.create(schemaContext.getCurrentContext());
final TypeAwareCodec identityrefTypeCodec = xmlCodecFactory.codecFor(listKey);
- final QName deserializedKey = (QName) identityrefTypeCodec.parseValue(nsContext, keyValue.get());
- keys.put(qName, deserializedKey);
+ final QName deserializedKey =
+ (QName) identityrefTypeCodec.parseValue(nsContext, keyValue.get());
+ keys.put(qualifiedName, deserializedKey);
} else {
final Object deserializedKey = TypeDefinitionAwareCodec.from(listKey.getType())
.deserialize(keyValue.get());
- keys.put(qName, deserializedKey);
+ keys.put(qualifiedName, deserializedKey);
}
}
}
return keys;
}
+ private enum Type {
+ LIST, CHOICE_CASE, OTHER
+ }
+
/**
* Class represents tree of QNames as they are present in the filter.
*/
}
}
- private enum Type {
- LIST, CHOICE_CASE, OTHER
- }
-
private static class ValidationException extends Exception {
- public ValidationException(final XmlElement parent, final XmlElement child) {
+ ValidationException(final XmlElement parent, final XmlElement child) {
super("Element " + child + " can't be child of " + parent);
}
}
private static final String OPERATION_NAME = "get";
private final TransactionProvider transactionProvider;
- public Get(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final TransactionProvider transactionProvider) {
+ public Get(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
+ final TransactionProvider transactionProvider) {
super(netconfSessionIdForReporting, schemaContext);
this.transactionProvider = transactionProvider;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
final Optional<YangInstanceIdentifier> dataRootOptional = getDataRootFromFilter(operationElement);
if (!dataRootOptional.isPresent()) {
final DOMDataReadWriteTransaction rwTx = getTransaction(Datastore.running);
try {
- final Optional<NormalizedNode<?, ?>> normalizedNodeOptional = rwTx.read(LogicalDatastoreType.OPERATIONAL, dataRoot).checkedGet();
+ final Optional<NormalizedNode<?, ?>> normalizedNodeOptional = rwTx.read(
+ LogicalDatastoreType.OPERATIONAL, dataRoot).checkedGet();
transactionProvider.abortRunningTransaction(rwTx);
if (!normalizedNodeOptional.isPresent()) {
} else if (datastore == Datastore.running) {
return transactionProvider.createRunningTransaction();
}
- throw new DocumentedException("Incorrect Datastore: ", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
+ throw new DocumentedException("Incorrect Datastore: ", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT,
+ ErrorSeverity.ERROR);
}
@Override
private static final String OPERATION_NAME = "get-config";
private final TransactionProvider transactionProvider;
- public GetConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final TransactionProvider transactionProvider) {
+ public GetConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
+ final TransactionProvider transactionProvider) {
super(netconfSessionIdForReporting, schemaContext);
this.transactionProvider = transactionProvider;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
GetConfigExecution getConfigExecution = null;
try {
getConfigExecution = GetConfigExecution.fromXml(operationElement, OPERATION_NAME);
final DOMDataReadWriteTransaction rwTx = getTransaction(getConfigExecution.getDatastore().get());
try {
- final Optional<NormalizedNode<?, ?>> normalizedNodeOptional = rwTx.read(LogicalDatastoreType.CONFIGURATION, dataRoot).checkedGet();
+ final Optional<NormalizedNode<?, ?>> normalizedNodeOptional = rwTx.read(
+ LogicalDatastoreType.CONFIGURATION, dataRoot).checkedGet();
if (getConfigExecution.getDatastore().get() == Datastore.running) {
transactionProvider.abortRunningTransaction(rwTx);
}
} else if (datastore == Datastore.running) {
return transactionProvider.createRunningTransaction();
}
- throw new DocumentedException("Incorrect Datastore: ", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
+ throw new DocumentedException("Incorrect Datastore: ", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT,
+ ErrorSeverity.ERROR);
}
@Override
final NodeList chields = node.getChildNodes();
for (int i = 0; i < chields.getLength(); i++) {
final Node chield = chields.item(i);
- if (chield.getNodeType() == Node.ELEMENT_NODE)
+ if (chield.getNodeType() == Node.ELEMENT_NODE) {
readNode(chield, false);
+ }
}
}
}
import com.google.common.io.ByteSource;
import com.google.common.util.concurrent.Futures;
-import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
-import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
public class NetconfMDSalMappingTest {
-
private static final Logger LOG = LoggerFactory.getLogger(NetconfMDSalMappingTest.class);
private static final String RPC_REPLY_ELEMENT = "rpc-reply";
private static final QName USERS = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "users");
private static final QName USER = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "user");
private static final QName MODULES = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "modules");
- private static final QName AUGMENTED_CONTAINER = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "augmented-container");
- private static final QName AUGMENTED_STRING_IN_CONT = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "identifier");
- private static final QName CHOICE_NODE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "choice-node");
- private static final QName AUGMENTED_CASE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "augmented-case");
- private static final QName CHOICE_WRAPPER = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "choice-wrapper");
- private static final QName INNER_CHOICE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "inner-choice");
- private static final QName INNER_CHOICE_TEXT = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "text");
+ private static final QName AUGMENTED_CONTAINER = QName.create("urn:opendaylight:mdsal:mapping:test",
+ "2015-02-26", "augmented-container");
+ private static final QName AUGMENTED_STRING_IN_CONT = QName.create("urn:opendaylight:mdsal:mapping:test",
+ "2015-02-26", "identifier");
+ private static final QName CHOICE_NODE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
+ "choice-node");
+ private static final QName AUGMENTED_CASE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
+ "augmented-case");
+ private static final QName CHOICE_WRAPPER = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
+ "choice-wrapper");
+ private static final QName INNER_CHOICE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
+ "inner-choice");
+ private static final QName INNER_CHOICE_TEXT = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
+ "text");
private static final YangInstanceIdentifier AUGMENTED_CONTAINER_IN_MODULES =
YangInstanceIdentifier.builder().node(TOP).node(MODULES).build();
-
- private static Document RPC_REPLY_OK = null;
-
- static {
- try {
- RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpc-reply_ok.xml");
- } catch (final Exception e) {
- LOG.debug("unable to load rpc reply ok.", e);
- RPC_REPLY_OK = XmlUtil.newDocument();
- }
- }
+ private static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
+ private static final Document RPC_REPLY_OK = NetconfMDSalMappingTest.getReplyOk();
private CurrentSchemaContext currentSchemaContext = null;
private SchemaContext schemaContext = null;
- private final String sessionIdForReporting = "netconf-test-session1";
-
private TransactionProvider transactionProvider = null;
@Mock
private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
+ @SuppressWarnings("illegalCatch")
+ private static Document getReplyOk() {
+ Document doc;
+ try {
+ doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpc-reply_ok.xml");
+ } catch (final Exception e) {
+ LOG.debug("unable to load rpc reply ok.", e);
+ doc = XmlUtil.newDocument();
+ }
+ return doc;
+ }
+
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
16, 16, "CommitFutures");
final ConcurrentDOMDataBroker cdb = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
- this.transactionProvider = new TransactionProvider(cdb, sessionIdForReporting);
+ this.transactionProvider = new TransactionProvider(cdb, SESSION_ID_FOR_REPORTING);
doAnswer(new Answer() {
@Override
}).when(sourceProvider).getSource(any(SourceIdentifier.class));
this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
-
}
@Test
@Test
public void testIncorrectGet() throws Exception {
-
try {
- executeOperation(new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider), "messages/mapping/bad_getConfig.xml");
+ executeOperation(new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider),
+ "messages/mapping/bad_getConfig.xml");
fail("Should have failed, this is an incorrect request");
} catch (final DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
}
try {
- executeOperation(new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider), "messages/mapping/bad_namespace_getConfig.xml");
+ executeOperation(new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider),
+ "messages/mapping/bad_namespace_getConfig.xml");
fail("Should have failed, this is an incorrect request");
} catch (final DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
assertTrue(e.getErrorType() == ErrorType.APPLICATION);
}
-
-
}
@Test
public void testEditRunning() throws Exception {
-
try {
edit("messages/mapping/editConfigs/editConfig_running.xml");
fail("Should have failed - edit config on running datastore is not supported");
assertTrue(e.getErrorTag() == ErrorTag.OPERATION_NOT_SUPPORTED);
assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
}
-
}
@Test
@Test
public void testCandidateTransaction() throws Exception {
-
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_n1.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
assertEmptyDatastore(getConfigRunning());
verifyResponse(discardChanges(), RPC_REPLY_OK);
assertEmptyDatastore(getConfigCandidate());
-
}
@Test
public void testEditWithCommit() throws Exception {
-
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_n1.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
verifyResponse(commit(), RPC_REPLY_OK);
- verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
+ verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
deleteDatastore();
-
}
@Test
verifyResponse(commit(), RPC_REPLY_OK);
final Document configRunning = getConfigRunning();
final String responseAsString = XmlUtil.toString(configRunning);
- verifyResponse(configRunning, XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_keys_1_control.xml"));
+ verifyResponse(configRunning, XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_keys_1_control.xml"));
final int key3 = responseAsString.indexOf("key3");
final int key1 = responseAsString.indexOf("key1");
@Test
public void testMultipleEditsWithMerge() throws Exception {
-
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_1.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_control_1.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_control_1.xml"));
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_single_1.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_control_2.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_control_2.xml"));
assertEmptyDatastore(getConfigRunning());
verifyResponse(commit(), RPC_REPLY_OK);
- verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_control_2.xml"));
+ verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_control_2.xml"));
deleteDatastore();
-
}
@Test
public void testMoreComplexEditConfigs() throws Exception {
-
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_1.xml"), RPC_REPLY_OK);
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_single_1.xml"), RPC_REPLY_OK);
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_2.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_after_more_complex_merge.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_after_more_complex_merge.xml"));
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_3.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_after_more_complex_merge_2.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_after_more_complex_merge_2.xml"));
verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_4_replace.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_after_replace.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_after_replace.xml"));
verifyResponse(commit(), RPC_REPLY_OK);
- verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_after_replace.xml"));
+ verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_after_replace.xml"));
verifyResponse(edit("messages/mapping/editConfigs/editConfig_replace_default.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_replace_default_control.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_replace_default_control.xml"));
verifyResponse(commit(), RPC_REPLY_OK);
- verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_replace_default_control.xml"));
+ verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_replace_default_control.xml"));
deleteDatastore();
-
}
@Test
public void testLock() throws Exception {
-
verifyResponse(lockCandidate(), RPC_REPLY_OK);
try {
assertTrue(e.getErrorType() == ErrorType.APPLICATION);
}
-
try {
lockWithoutTarget();
fail("Should have failed, target is missing");
@Test
public void testUnlock() throws Exception {
-
verifyResponse(unlockCandidate(), RPC_REPLY_OK);
try {
@Test
public void testEditWithCreate() throws Exception {
-
verifyResponse(edit("messages/mapping/editConfigs/editConfig_create.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_create_n1_control.xml"));
-
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfig_create_n1_control.xml"));
try {
edit("messages/mapping/editConfigs/editConfig_create.xml");
}
verifyResponse(discardChanges(), RPC_REPLY_OK);
-
}
@Test
public void testDeleteNonExisting() throws Exception {
-
assertEmptyDatastore(getConfigCandidate());
assertEmptyDatastore(getConfigRunning());
assertTrue(e.getErrorTag() == ErrorTag.DATA_MISSING);
assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
}
-
}
@Test
public void testEditMissingDefaultOperation() throws Exception {
-
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_missing_default-operation_1.xml"), RPC_REPLY_OK);
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_missing_default-operation_2.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_missing_default-operation_control.xml"));
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_missing_default-operation_1.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_missing_default-operation_2.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_missing_default-operation_control.xml"));
verifyResponse(commit(), RPC_REPLY_OK);
- verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_missing_default-operation_control.xml"));
+ verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_missing_default-operation_control.xml"));
deleteDatastore();
}
- public static void printDocument(final Document doc) throws IOException, TransformerException {
+ private static void printDocument(final Document doc) throws Exception {
final TransformerFactory tf = TransformerFactory.newInstance();
final Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
public void testEditConfigWithMultipleOperations() throws Exception {
deleteDatastore();
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_setup.xml"), RPC_REPLY_OK);
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_1.xml"), RPC_REPLY_OK);
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_setup.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_1.xml"),
+ RPC_REPLY_OK);
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_2.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_operations_2_control.xml"));
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_2.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_operations_2_control.xml"));
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_3_leaf_operations.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_operations_3_control.xml"));
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_3_leaf_operations.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_operations_3_control.xml"));
deleteDatastore();
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_setup.xml"), RPC_REPLY_OK);
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_default-replace.xml"), RPC_REPLY_OK);
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_setup.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_default-replace.xml"),
+ RPC_REPLY_OK);
try {
edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_create_existing.xml");
assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
}
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_delete_children_operations.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_delete_children_operations_control.xml"));
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_remove-non-existing.xml"), RPC_REPLY_OK);
-
+ verifyResponse(edit(
+ "messages/mapping/editConfigs/"
+ + "editConfig_merge_multiple_operations_4_delete_children_operations.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/"
+ + "editConfig_merge_multiple_operations_4_delete_children_operations_control.xml"));
+ verifyResponse(edit(
+ "messages/mapping/editConfigs/"
+ + "editConfig_merge_multiple_operations_4_remove-non-existing.xml"),
+ RPC_REPLY_OK);
try {
- edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_delete-non-existing.xml");
+ edit("messages/mapping/editConfigs/"
+ + "editConfig_merge_multiple_operations_4_delete-non-existing.xml");
fail();
} catch (final DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
}
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup-control.xml"));
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup-control.xml"));
// Test files have been modified. RFC6020 requires that at most once case inside a choice is present at any time
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup2.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup2-control.xml"));
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup2.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup2-control.xml"));
- verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_delete.xml"), RPC_REPLY_OK);
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_delete_children_operations_control.xml"));
+ verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_delete.xml"),
+ RPC_REPLY_OK);
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
+ "messages/mapping/editConfigs"
+ + "/editConfig_merge_multiple_operations_4_delete_children_operations_control.xml"));
deleteDatastore();
}
public void testReplaceMapEntry() throws Exception {
verifyResponse(edit("messages/mapping/editConfigs/edit-config-replace-map-entry.xml"), RPC_REPLY_OK);
verifyResponse(commit(), RPC_REPLY_OK);
- verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/get-config-map-entry.xml"));
+ verifyResponse(getConfigRunning(),
+ XmlFileLoader.xmlFileToDocument("messages/mapping/get-config-map-entry.xml"));
}
@Test
public void testMergeMapEntry() throws Exception {
verifyResponse(edit("messages/mapping/editConfigs/edit-config-merge-map-entry.xml"), RPC_REPLY_OK);
verifyResponse(commit(), RPC_REPLY_OK);
- verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/get-config-map-entry.xml"));
+ verifyResponse(getConfigRunning(),
+ XmlFileLoader.xmlFileToDocument("messages/mapping/get-config-map-entry.xml"));
}
@Test
public void testFiltering() throws Exception {
-
assertEmptyDatastore(getConfigCandidate());
assertEmptyDatastore(getConfigRunning());
verifyResponse(getWithFilter("messages/mapping/filters/get-empty-filter.xml"),
XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response.xml"));
- verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response.xml"));
+ verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response"
+ + ".xml"));
verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response.xml"));
verifyResponse(getConfigWithFilter("messages/mapping/filters/get-filter-users.xml"),
XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response.xml"));
verifyFilterIdentifier("messages/mapping/filters/get-filter-users.xml",
YangInstanceIdentifier.builder().node(TOP).node(USERS).build());
- final YangInstanceIdentifier ident = YangInstanceIdentifier.
- builder(AUGMENTED_CONTAINER_IN_MODULES).
- node(AUGMENTED_CONTAINER).
- node(AUGMENTED_STRING_IN_CONT).build();
+ final YangInstanceIdentifier ident = YangInstanceIdentifier
+ .builder(AUGMENTED_CONTAINER_IN_MODULES)
+ .node(AUGMENTED_CONTAINER)
+ .node(AUGMENTED_STRING_IN_CONT).build();
verifyFilterIdentifier("messages/mapping/filters/get-filter-augmented-string.xml", ident);
verifyFilterIdentifier("messages/mapping/filters/get-filter-augmented-case.xml",
verifyFilterIdentifier("messages/mapping/filters/get-filter-augmented-case-inner-choice.xml",
YangInstanceIdentifier.builder().node(TOP).node(CHOICE_NODE).node(CHOICE_WRAPPER).build());
verifyFilterIdentifier("messages/mapping/filters/get-filter-augmented-case-inner-case.xml",
- YangInstanceIdentifier.builder().node(TOP).node(CHOICE_NODE).node(CHOICE_WRAPPER).node(INNER_CHOICE).node(INNER_CHOICE_TEXT).build());
+ YangInstanceIdentifier.builder().node(TOP).node(CHOICE_NODE).node(CHOICE_WRAPPER).node(INNER_CHOICE)
+ .node(INNER_CHOICE_TEXT).build());
// verifyResponse(getConfigWithFilter("messages/mapping/filters/get-filter-augmented-string.xml"),
// XmlFileLoader.xmlFileToDocument("messages/mapping/filters/response-augmented-string.xml"));
}
- private void verifyFilterIdentifier(final String resource, final YangInstanceIdentifier identifier) throws Exception {
- final TestingGetConfig getConfig = new TestingGetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
+ private void verifyFilterIdentifier(final String resource, final YangInstanceIdentifier identifier)
+ throws Exception {
+ final TestingGetConfig getConfig = new TestingGetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext,
+ transactionProvider);
final Document request = XmlFileLoader.xmlFileToDocument(resource);
final YangInstanceIdentifier iid = getConfig.getInstanceIdentifierFromDocument(request);
assertEquals(identifier, iid);
}
- private class TestingGetConfig extends GetConfig{
- public TestingGetConfig(final String sessionId, final CurrentSchemaContext schemaContext, final TransactionProvider transactionProvider) {
+ private class TestingGetConfig extends GetConfig {
+ TestingGetConfig(final String sessionId, final CurrentSchemaContext schemaContext,
+ final TransactionProvider transactionProvider) {
super(sessionId, schemaContext, transactionProvider);
}
- public YangInstanceIdentifier getInstanceIdentifierFromDocument(final Document request) throws DocumentedException {
- final XmlElement filterElement = XmlElement.fromDomDocument(request).getOnlyChildElement(GET_CONFIG).getOnlyChildElement(FILTER_NODE);
+ YangInstanceIdentifier getInstanceIdentifierFromDocument(final Document request) throws DocumentedException {
+ final XmlElement filterElement = XmlElement.fromDomDocument(request).getOnlyChildElement(GET_CONFIG)
+ .getOnlyChildElement(FILTER_NODE);
return getInstanceIdentifierFromFilter(filterElement);
}
}
- private void deleteDatastore() throws Exception{
+ private void deleteDatastore() throws Exception {
verifyResponse(edit("messages/mapping/editConfigs/editConfig_delete-root.xml"), RPC_REPLY_OK);
assertEmptyDatastore(getConfigCandidate());
assertEmptyDatastore(getConfigRunning());
}
- private void verifyResponse(final Document response, final Document template) throws IOException, TransformerException {
+ private void verifyResponse(final Document response, final Document template) throws Exception {
final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
dd.overrideElementQualifier(new NetconfXmlUnitRecursiveQualifier());
}
private void assertEmptyDatastore(final Document response) {
-
final NodeList nodes = response.getChildNodes();
assertTrue(nodes.getLength() == 1);
final Node dataNode = replyNodes.item(0);
assertEquals(dataNode.getLocalName(), DATA_ELEMENT);
assertFalse(dataNode.hasChildNodes());
-
}
- private Document commit() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Commit commit = new Commit(sessionIdForReporting, transactionProvider);
+ private Document commit() throws Exception {
+ final Commit commit = new Commit(SESSION_ID_FOR_REPORTING, transactionProvider);
return executeOperation(commit, "messages/mapping/commit.xml");
}
- private Document discardChanges() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final DiscardChanges discardOp = new DiscardChanges(sessionIdForReporting, transactionProvider);
+ private Document discardChanges() throws Exception {
+ final DiscardChanges discardOp = new DiscardChanges(SESSION_ID_FOR_REPORTING, transactionProvider);
return executeOperation(discardOp, "messages/mapping/discardChanges.xml");
}
- private Document edit(final String resource) throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final EditConfig editConfig = new EditConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
+ private Document edit(final String resource) throws Exception {
+ final EditConfig editConfig = new EditConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext,
+ transactionProvider);
return executeOperation(editConfig, resource);
}
- private Document get() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Get get = new Get(sessionIdForReporting, currentSchemaContext, transactionProvider);
+ private Document get() throws Exception {
+ final Get get = new Get(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
return executeOperation(get, "messages/mapping/get.xml");
}
- private Document getWithFilter(final String resource) throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Get get = new Get(sessionIdForReporting, currentSchemaContext, transactionProvider);
+ private Document getWithFilter(final String resource) throws Exception {
+ final Get get = new Get(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
return executeOperation(get, resource);
}
- private Document getConfigRunning() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
+ private Document getConfigRunning() throws Exception {
+ final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
return executeOperation(getConfig, "messages/mapping/getConfig.xml");
}
- private Document getConfigCandidate() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
+ private Document getConfigCandidate() throws Exception {
+ final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
return executeOperation(getConfig, "messages/mapping/getConfig_candidate.xml");
}
- private Document getConfigWithFilter(final String resource) throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
+ private Document getConfigWithFilter(final String resource) throws Exception {
+ final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
return executeOperation(getConfig, resource);
}
- private Document lock() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Lock lock = new Lock(sessionIdForReporting);
+ private Document lock() throws Exception {
+ final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
return executeOperation(lock, "messages/mapping/lock.xml");
}
- private Document unlock() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Unlock unlock = new Unlock(sessionIdForReporting);
+ private Document unlock() throws Exception {
+ final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
return executeOperation(unlock, "messages/mapping/unlock.xml");
}
- private Document lockWithoutTarget() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Lock lock = new Lock(sessionIdForReporting);
+ private Document lockWithoutTarget() throws Exception {
+ final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
return executeOperation(lock, "messages/mapping/lock_notarget.xml");
}
- private Document unlockWithoutTarget() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Unlock unlock = new Unlock(sessionIdForReporting);
+ private Document unlockWithoutTarget() throws Exception {
+ final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
return executeOperation(unlock, "messages/mapping/unlock_notarget.xml");
}
- private Document lockCandidate() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Lock lock = new Lock(sessionIdForReporting);
+ private Document lockCandidate() throws Exception {
+ final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
return executeOperation(lock, "messages/mapping/lock_candidate.xml");
}
- private Document unlockCandidate() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
- final Unlock unlock = new Unlock(sessionIdForReporting);
+ private Document unlockCandidate() throws Exception {
+ final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
return executeOperation(unlock, "messages/mapping/unlock_candidate.xml");
}
- private Document executeOperation(final NetconfOperation op, final String filename) throws ParserConfigurationException, SAXException, IOException, DocumentedException {
+ private Document executeOperation(final NetconfOperation op, final String filename) throws Exception {
final Document request = XmlFileLoader.xmlFileToDocument(filename);
final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
- LOG.debug("Got response {}" , response);
+ LOG.debug("Got response {}", response);
return response;
}
private List<InputStream> getYangSchemas() {
- final List<String> schemaPaths = Arrays.asList("/META-INF/yang/config.yang", "/yang/mdsal-netconf-mapping-test.yang");
+ final List<String> schemaPaths = Arrays.asList("/META-INF/yang/config.yang",
+ "/yang/mdsal-netconf-mapping-test.yang");
final List<InputStream> schemas = new ArrayList<>();
for (final String schemaPath : schemaPaths) {
}
@Override
- public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
+ public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
+ final SchemaContextListener listener) {
listener.onGlobalContextUpdated(getGlobalContext());
return new ListenerRegistration<SchemaContextListener>() {
@Override
import com.google.common.io.ByteSource;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
-import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
-import javax.xml.transform.TransformerException;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.util.test.XmlFileLoader;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.w3c.dom.Document;
public class RuntimeRpcTest {
-
private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
+ private static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
+ private static final Document RPC_REPLY_OK = RuntimeRpcTest.getReplyOk();
- private final String sessionIdForReporting = "netconf-test-session1";
-
- private static Document RPC_REPLY_OK = null;
-
- static {
+ @SuppressWarnings("illegalCatch")
+ private static Document getReplyOk() {
+ Document doc;
try {
- RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
+ doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
} catch (final Exception e) {
LOG.debug("unable to load rpc reply ok.", e);
- RPC_REPLY_OK = XmlUtil.newDocument();
+ doc = XmlUtil.newDocument();
}
+ return doc;
}
private final DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
@Nonnull
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
- return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
+ @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
+ return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(null, Collections.emptyList()));
}
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
return null;
}
};
private final DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
@Nonnull
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
- return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
+ @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
+ return Futures.immediateFailedCheckedFuture(new DOMRpcException("rpc invocation not implemented yet") {
});
}
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
return null;
}
};
private final DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
@Nonnull
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
- final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
- final Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
- final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(), type.getLastComponent().getLocalName());
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
+ @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
+ final Collection<DataContainerChild<? extends PathArgument, ?>> children = (Collection) input.getValue();
+ final Module module = schemaContext.findModuleByNamespaceAndRevision(
+ type.getLastComponent().getNamespace(), null);
+ final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
+ module, module.getNamespace(), type.getLastComponent().getLocalName());
final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
final ContainerNode node = ImmutableContainerNodeBuilder.create()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
.withValue(children).build();
- return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(node));
+ return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(node));
}
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
return null;
}
};
private SchemaContext schemaContext = null;
private CurrentSchemaContext currentSchemaContext = null;
+
@Mock
private SchemaService schemaService;
@Mock
@Before
public void setUp() throws Exception {
-
initMocks(this);
doNothing().when(registration).close();
doReturn(listener).when(registration).getInstance();
doNothing().when(schemaService).removeModule(any(Module.class));
doReturn(schemaContext).when(schemaService).getGlobalContext();
doReturn(schemaContext).when(schemaService).getSessionContext();
- doAnswer(new Answer() {
- @Override
- public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
- ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
- return registration;
- }
+ doAnswer(invocationOnMock -> {
+ ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
+ return registration;
}).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
- doAnswer(new Answer() {
- @Override
- public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
- final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
- final YangTextSchemaSource yangTextSchemaSource =
- YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
- return Futures.immediateCheckedFuture(yangTextSchemaSource);
+ doAnswer(invocationOnMock -> {
+ final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
+ final YangTextSchemaSource yangTextSchemaSource =
+ YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
+ return Futures.immediateCheckedFuture(yangTextSchemaSource);
- }
}).when(sourceProvider).getSource(any(SourceIdentifier.class));
this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
@Test
public void testVoidOutputRpc() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
+ final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testSuccesfullNonVoidInvocation() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
+ final RuntimeRpc rpc = new RuntimeRpc(
+ SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testSuccesfullContainerInvocation() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
+ final RuntimeRpc rpc = new RuntimeRpc(
+ SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testFailedInvocation() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
+ final RuntimeRpc rpc = new RuntimeRpc(
+ SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceFailedInvocation);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testVoidInputOutputRpc() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
+ final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testBadNamespaceInRpc() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
+ final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
try {
}
}
- private void verifyResponse(final Document response, final Document template) throws IOException, TransformerException {
+ private void verifyResponse(final Document response, final Document template) throws Exception {
final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
//we care about order so response has to be identical
}
return null;
-
}
private List<InputStream> getYangSchemas() {
- final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
+ final List<String> schemaPaths = Collections.singletonList("/yang/mdsal-netconf-rpc-test.yang");
final List<InputStream> schemas = new ArrayList<>();
for (final String schemaPath : schemaPaths) {
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
import org.w3c.dom.Document;
public class Bug8084 {
- private static final QName base = QName.create("urn:dummy:mod-0", "2016-03-01", "mainroot");
+ private static final QName BASE = QName.create("urn:dummy:mod-0", "2016-03-01", "mainroot");
@Test
public void testValidateTypes() throws Exception {
final YangInstanceIdentifier actual = validator.validate(xmlElement);
final Map<QName, Object> inputs = new HashMap<>();
- inputs.put(QName.create(base, "id1"), "aaa");
- inputs.put(QName.create(base, "id2"), Byte.valueOf("-9"));
- inputs.put(QName.create(base, "id3"), Short.valueOf("-30000"));
- inputs.put(QName.create(base, "id4"), Integer.valueOf("-2000000000"));
- inputs.put(QName.create(base, "id5"), Long.valueOf("-2000000000000000"));
- inputs.put(QName.create(base, "id6"), Short.valueOf("9"));
- inputs.put(QName.create(base, "id7"), Integer.valueOf("30000"));
- inputs.put(QName.create(base, "id8"), Long.valueOf("2000000000"));
- inputs.put(QName.create(base, "id9"), BigInteger.valueOf(Long.valueOf("2000000000000000")));
- inputs.put(QName.create(base, "id10"), true);
- inputs.put(QName.create(base, "id11"), BigDecimal.valueOf(128.55));
- inputs.put(QName.create(base, "id12"), QName.create(base, "foo"));
- inputs.put(QName.create(base, "id13"), QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "foo"));
- final QName idActual = (QName) ((YangInstanceIdentifier.NodeIdentifierWithPredicates) actual.getLastPathArgument()).
- getKeyValues().get(QName.create(base, "id12"));
-
+ inputs.put(QName.create(BASE, "id1"), "aaa");
+ inputs.put(QName.create(BASE, "id2"), Byte.valueOf("-9"));
+ inputs.put(QName.create(BASE, "id3"), Short.valueOf("-30000"));
+ inputs.put(QName.create(BASE, "id4"), Integer.valueOf("-2000000000"));
+ inputs.put(QName.create(BASE, "id5"), Long.valueOf("-2000000000000000"));
+ inputs.put(QName.create(BASE, "id6"), Short.valueOf("9"));
+ inputs.put(QName.create(BASE, "id7"), Integer.valueOf("30000"));
+ inputs.put(QName.create(BASE, "id8"), Long.valueOf("2000000000"));
+ inputs.put(QName.create(BASE, "id9"), BigInteger.valueOf(Long.valueOf("2000000000000000")));
+ inputs.put(QName.create(BASE, "id10"), true);
+ inputs.put(QName.create(BASE, "id11"), BigDecimal.valueOf(128.55));
+ inputs.put(QName.create(BASE, "id12"), QName.create(BASE, "foo"));
+ inputs.put(
+ QName.create(BASE, "id13"),
+ QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "foo"));
+ final QName idActual = (QName) ((NodeIdentifierWithPredicates) actual.getLastPathArgument())
+ .getKeyValues().get(QName.create(BASE, "id12"));
final YangInstanceIdentifier expected = YangInstanceIdentifier.builder()
- .node(base)
- .node(QName.create(base, "multi-key-list2"))
- .nodeWithKey(QName.create(base, "multi-key-list2"), inputs)
+ .node(BASE)
+ .node(QName.create(BASE, "multi-key-list2"))
+ .nodeWithKey(QName.create(BASE, "multi-key-list2"), inputs)
.build();
- final QName idExpected = (QName) ((YangInstanceIdentifier.NodeIdentifierWithPredicates) expected.getLastPathArgument()).
- getKeyValues().get(QName.create(base, "id12"));
+ final QName idExpected = (QName) ((NodeIdentifierWithPredicates) expected.getLastPathArgument())
+ .getKeyValues().get(QName.create(BASE, "id12"));
assertEquals(idExpected, idActual);
assertEquals(expected, actual);
-
}
}
import static org.mockito.Mockito.mock;
import com.google.common.base.Preconditions;
-import java.io.IOException;
import java.io.InputStream;
-import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
@RunWith(value = Parameterized.class)
public class FilterContentValidatorTest {
private FilterContentValidator validator;
@Parameterized.Parameters
- public static Collection<Object[]> data() throws IOException, SAXException, URISyntaxException, InitializationError {
+ public static Collection<Object[]> data() throws Exception {
final List<Object[]> result = new ArrayList<>();
final Path path = Paths.get(FilterContentValidatorTest.class.getResource("/filter/expected.txt").toURI());
final List<String> expected = Files.readAllLines(path);
throw new InitializationError("Number of lines in results file must be same as test case count");
}
for (int i = 1; i <= TEST_CASE_COUNT; i++) {
- final Document document = XmlUtil.readXmlToDocument(FilterContentValidatorTest.class.getResourceAsStream("/filter/f" + i + ".xml"));
- result.add(new Object[]{document, expected.get(i-1)});
+ final Document document = XmlUtil.readXmlToDocument(FilterContentValidatorTest.class.getResourceAsStream(
+ "/filter/f" + i + ".xml"));
+ result.add(new Object[]{document, expected.get(i - 1)});
}
return result;
}
validator = new FilterContentValidator(currentContext);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Test
public void testValidate() throws Exception {
if (expected.startsWith("success")) {
return prev;
}
- private static QName createNodeQName(final QName prev, final String qNameString) {
- final QName qName = QName.create(qNameString);
+ private static QName createNodeQName(final QName prev, final String input) {
+ final QName qName = QName.create(input);
if (qName.getModule().getNamespace() != null) {
return qName;
} else {
- return QName.create(Preconditions.checkNotNull(prev), qNameString);
+ return QName.create(Preconditions.checkNotNull(prev), input);
}
}
}