From 87ba9096e70eb7b65a2c304ef6e98798788eaed6 Mon Sep 17 00:00:00 2001 From: Robert Varga Date: Tue, 1 Jul 2014 18:18:44 +0200 Subject: [PATCH] BUG-868: remove InstanceIdentifier.getPath() users getPath() has been deprecated. Remove the easily call sites to getPathArguments(). Change-Id: I2058627301404e28b58851c27d8d8117f48a7b9d Signed-off-by: Robert Varga --- .../InventoryAndReadAdapter.java | 50 ++-- .../impl/util/compat/DataNormalizerTest.java | 5 +- .../sal/dom/broker/impl/DataReaderRouter.java | 6 +- .../impl/SchemaAwareDataStoreAdapter.java | 13 +- .../sal/dom/broker/util/YangSchemaUtils.java | 8 +- .../sal/dom/store/impl/tree/ListenerTree.java | 26 +- .../netconf/sal/NetconfDeviceDataReader.java | 2 +- ...etconfDeviceTwoPhaseCommitTransaction.java | 9 +- .../util/NetconfMessageTransformUtil.java | 64 ++--- .../sal/restconf/impl/ControllerContext.java | 34 +-- .../sal/restconf/impl/RestconfImpl.java | 237 +++++++++--------- .../streams/listeners/ListenerAdapter.java | 80 +++--- .../sal/restconf/impl/test/URITest.java | 11 +- .../doc/mountpoints/MountPointSwagger.java | 41 ++- 14 files changed, 313 insertions(+), 273 deletions(-) diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java index 5959d23366..e2c1386775 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java @@ -7,9 +7,12 @@ */ package org.opendaylight.controller.sal.compatibility; +import com.google.common.collect.Iterables; + import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -733,26 +736,45 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI } private boolean isKnownNodeConnector(final InstanceIdentifier nodeConnectorIdentifier) { - final List path = nodeConnectorIdentifier.getPath(); - if (path.size() >= 3) { - final PathArgument nodePath = path.get(1); - final PathArgument nodeConnectorPath = path.get(2); - final List nodeConnectors = nodeToNodeConnectorsMap.get(nodePath); - if (nodeConnectors != null) { - return nodeConnectors.contains(nodeConnectorPath); - } + final Iterator it = nodeConnectorIdentifier.getPathArguments().iterator(); + + if (!it.hasNext()) { + return false; } - return false; + it.next(); + + if (!it.hasNext()) { + return false; + } + final PathArgument nodePath = it.next(); + + if (!it.hasNext()) { + return false; + } + final PathArgument nodeConnectorPath = it.next(); + + final List nodeConnectors = nodeToNodeConnectorsMap.get(nodePath); + return nodeConnectors == null ? false : + nodeConnectors.contains(nodeConnectorPath); } private boolean recordNodeConnector(final InstanceIdentifier nodeConnectorIdentifier) { - final List path = nodeConnectorIdentifier.getPath(); - if (path.size() < 3) { + final Iterator it = nodeConnectorIdentifier.getPathArguments().iterator(); + + if (!it.hasNext()) { return false; } + it.next(); - final PathArgument nodePath = path.get(1); - final PathArgument nodeConnectorPath = path.get(2); + if (!it.hasNext()) { + return false; + } + final PathArgument nodePath = it.next(); + + if (!it.hasNext()) { + return false; + } + final PathArgument nodeConnectorPath = it.next(); synchronized (this) { List nodeConnectors = this.nodeToNodeConnectorsMap.get(nodePath); @@ -766,6 +788,6 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI } private List removeNodeConnectors(final InstanceIdentifier nodeIdentifier) { - return this.nodeToNodeConnectorsMap.remove(nodeIdentifier.getPath().get(1)); + return this.nodeToNodeConnectorsMap.remove(Iterables.get(nodeIdentifier.getPathArguments(), 1)); } } diff --git a/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java b/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java index 1b3ff305bc..dcb90a83ba 100644 --- a/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java +++ b/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java @@ -14,6 +14,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; @@ -149,10 +150,10 @@ public class DataNormalizerTest { private void verifyNormalizedInstanceIdentifier(final InstanceIdentifier actual, final Object... expPath) { assertNotNull("Actual InstanceIdentifier is null", actual); - assertEquals("InstanceIdentifier path length", expPath.length, actual.getPath().size()); + assertEquals("InstanceIdentifier path length", expPath.length, Iterables.size(actual.getPathArguments())); for (int i = 0; i < expPath.length; i++) { - PathArgument actualArg = actual.getPath().get(i); + PathArgument actualArg = Iterables.get(actual.getPathArguments(), i); if (expPath[i] instanceof Object[]) { // NodeIdentifierWithPredicates Object[] exp = (Object[]) expPath[i]; assertEquals("Actual path arg " + (i + 1) + " class", NodeIdentifierWithPredicates.class, diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java index ba9b2b7f55..4b5b86d0da 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java @@ -9,6 +9,8 @@ package org.opendaylight.controller.sal.dom.broker.impl; import static com.google.common.base.Preconditions.checkState; +import com.google.common.collect.Iterables; + import java.net.URI; import java.util.ArrayList; import java.util.Arrays; @@ -32,8 +34,6 @@ import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.Iterables; - public class DataReaderRouter extends AbstractDataReadRouter { private final static Logger LOG = LoggerFactory @@ -46,7 +46,7 @@ AbstractDataReadRouter { @Override protected CompositeNodeTOImpl merge(final InstanceIdentifier path, final Iterable data) { - PathArgument pathArgument = Iterables.getLast(path.getPath(), null); + PathArgument pathArgument = Iterables.getLast(path.getPathArguments(), null); boolean empty = true; QName name = (pathArgument == null ? null : pathArgument.getNodeType()); final ArrayList> nodes = new ArrayList>(); diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java index 1a572d157d..3cd7ed5e13 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java @@ -9,6 +9,11 @@ package org.opendaylight.controller.sal.dom.broker.impl; import static com.google.common.base.Preconditions.checkState; +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; + import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; @@ -40,10 +45,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableSet; - public class SchemaAwareDataStoreAdapter extends AbstractLockableDelegator implements // DataStore, // SchemaContextListener, // @@ -235,7 +236,7 @@ AutoCloseable { public CompositeNode readConfigurationData(final InstanceIdentifier path) { getDelegateReadLock().lock(); try { - if (path.getPath().isEmpty()) { + if (Iterables.isEmpty(path.getPathArguments())) { return null; } QName qname = null; @@ -278,7 +279,7 @@ AutoCloseable { public CompositeNode readOperationalData(final InstanceIdentifier path) { getDelegateReadLock().lock(); try { - if (path.getPath().isEmpty()) { + if (Iterables.isEmpty(path.getPathArguments())) { return null; } QName qname = null; diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java index 306cd34a69..29392dc7b3 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java @@ -10,6 +10,9 @@ package org.opendaylight.controller.sal.dom.broker.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; +import com.google.common.base.Function; +import com.google.common.collect.FluentIterable; + import java.util.Iterator; import java.util.List; import java.util.Set; @@ -34,9 +37,6 @@ import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; import org.opendaylight.yangtools.yang.model.api.UsesNode; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; - public final class YangSchemaUtils { private static final Function QNAME_FROM_PATH_ARGUMENT = new Function(){ @@ -57,7 +57,7 @@ public final class YangSchemaUtils { public static DataSchemaNode getSchemaNode(final SchemaContext schema,final InstanceIdentifier path) { checkArgument(schema != null,"YANG Schema must not be null."); checkArgument(path != null,"Path must not be null."); - return getSchemaNode(schema, FluentIterable.from(path.getPath()).transform(QNAME_FROM_PATH_ARGUMENT)); + return getSchemaNode(schema, FluentIterable.from(path.getPathArguments()).transform(QNAME_FROM_PATH_ARGUMENT)); } public static DataSchemaNode getSchemaNode(final SchemaContext schema,final Iterable path) { diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java b/opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java index e6221f6920..9d04a1b6ed 100644 --- a/opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java +++ b/opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java @@ -9,6 +9,19 @@ package org.opendaylight.controller.md.sal.dom.store.impl.tree; import com.google.common.base.Optional; import com.google.common.base.Preconditions; + +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import javax.annotation.concurrent.GuardedBy; + import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener; import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration; @@ -21,17 +34,6 @@ import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.concurrent.GuardedBy; -import java.lang.ref.Reference; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - /** * A set of listeners organized as a tree by node to which they listen. This class * allows for efficient lookup of listeners when we walk the DataTreeCandidate. @@ -70,7 +72,7 @@ public final class ListenerTree { try { Node walkNode = rootNode; - for (final PathArgument arg : path.getPath()) { + for (final PathArgument arg : path.getPathArguments()) { walkNode = walkNode.ensureChild(arg); } diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java index 2909baccdb..3535c96c80 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java @@ -74,7 +74,7 @@ public final class NetconfDeviceDataReader implements DataReader findNode(final CompositeNode node, final InstanceIdentifier identifier) { Node current = node; - for (final InstanceIdentifier.PathArgument arg : identifier.getPath()) { + for (final InstanceIdentifier.PathArgument arg : identifier.getPathArguments()) { if (current instanceof SimpleNode) { return null; } else if (current instanceof CompositeNode) { diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java index 1a3b108f8b..1737b8234a 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java @@ -21,13 +21,16 @@ import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessag import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.common.collect.Lists; + import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutionException; + import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction; import org.opendaylight.controller.md.sal.common.api.data.DataModification; import org.opendaylight.controller.sal.common.util.RpcErrors; @@ -108,7 +111,7 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact } } - private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, Optional defaultOperation) { + private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, final Optional defaultOperation) { final CompositeNodeBuilder ret = ImmutableCompositeNode.builder(); // Target @@ -133,8 +136,8 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact } private CompositeNode createEditConfigStructure(final InstanceIdentifier dataPath, final Optional operation, - final Optional lastChildOverride) { - Preconditions.checkArgument(dataPath.getPath().isEmpty() == false, "Instance identifier with empty path %s", dataPath); + final Optional lastChildOverride) { + Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath); List reversedPath = Lists.reverse(dataPath.getPath()); diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java index ee6daa1e3d..0ea3d6a35a 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java @@ -7,6 +7,14 @@ */ package org.opendaylight.controller.sal.connect.netconf.util; +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + import java.net.URI; import java.util.ArrayList; import java.util.Collections; @@ -36,13 +44,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.w3c.dom.Document; import org.w3c.dom.Element; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - public class NetconfMessageTransformUtil { private NetconfMessageTransformUtil() { @@ -76,7 +77,7 @@ public class NetconfMessageTransformUtil { public static Node toFilterStructure(final InstanceIdentifier identifier) { Node previous = null; - if (identifier.getPath().isEmpty()) { + if (Iterables.isEmpty(identifier.getPathArguments())) { return null; } @@ -103,15 +104,15 @@ public class NetconfMessageTransformUtil { } public static void checkValidReply(final NetconfMessage input, final NetconfMessage output) - throws NetconfDocumentedException { + throws NetconfDocumentedException { final String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id"); final String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id"); if(inputMsgId.equals(outputMsgId) == false) { Map errorInfo = ImmutableMap.builder() - .put( "actual-message-id", outputMsgId ) - .put( "expected-message-id", inputMsgId ) - .build(); + .put( "actual-message-id", outputMsgId ) + .put( "expected-message-id", inputMsgId ) + .build(); throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"", null, NetconfDocumentedException.ErrorType.protocol, @@ -126,7 +127,7 @@ public class NetconfMessageTransformUtil { } } - public static RpcError toRpcError( NetconfDocumentedException ex ) + public static RpcError toRpcError( final NetconfDocumentedException ex ) { StringBuilder infoBuilder = new StringBuilder(); Map errorInfo = ex.getErrorInfo(); @@ -134,44 +135,45 @@ public class NetconfMessageTransformUtil { { for( Entry e: errorInfo.entrySet() ) { infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() ) - .append( "' ); + .append( "' ); } } return RpcErrors.getRpcError( null, ex.getErrorTag().getTagValue(), infoBuilder.toString(), - toRpcErrorSeverity( ex.getErrorSeverity() ), ex.getLocalizedMessage(), - toRpcErrorType( ex.getErrorType() ), ex.getCause() ); + toRpcErrorSeverity( ex.getErrorSeverity() ), ex.getLocalizedMessage(), + toRpcErrorType( ex.getErrorType() ), ex.getCause() ); } - private static ErrorSeverity toRpcErrorSeverity( NetconfDocumentedException.ErrorSeverity severity ) { + private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) { switch( severity ) { - case warning: - return RpcError.ErrorSeverity.WARNING; - default: - return RpcError.ErrorSeverity.ERROR; + case warning: + return RpcError.ErrorSeverity.WARNING; + default: + return RpcError.ErrorSeverity.ERROR; } } - private static RpcError.ErrorType toRpcErrorType( NetconfDocumentedException.ErrorType type ) + private static RpcError.ErrorType toRpcErrorType( final NetconfDocumentedException.ErrorType type ) { switch( type ) { - case protocol: - return RpcError.ErrorType.PROTOCOL; - case rpc: - return RpcError.ErrorType.RPC; - case transport: - return RpcError.ErrorType.TRANSPORT; - default: - return RpcError.ErrorType.APPLICATION; + case protocol: + return RpcError.ErrorType.PROTOCOL; + case rpc: + return RpcError.ErrorType.RPC; + case transport: + return RpcError.ErrorType.TRANSPORT; + default: + return RpcError.ErrorType.APPLICATION; } } public static CompositeNode flattenInput(final CompositeNode node) { final QName inputQName = QName.create(node.getNodeType(), "input"); final CompositeNode input = node.getFirstCompositeByName(inputQName); - if (input == null) + if (input == null) { return node; + } if (input instanceof CompositeNode) { final List> nodes = ImmutableList.> builder() // diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java index 6330c0a479..7a16105056 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java @@ -7,6 +7,19 @@ */ package org.opendaylight.controller.sal.restconf.impl; +import com.google.common.base.Function; +import com.google.common.base.Objects; +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.common.base.Predicate; +import com.google.common.base.Splitter; +import com.google.common.base.Strings; +import com.google.common.collect.BiMap; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; @@ -55,19 +68,6 @@ import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import com.google.common.collect.BiMap; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - public class ControllerContext implements SchemaContextListener { private final static Logger LOG = LoggerFactory.getLogger( ControllerContext.class ); @@ -256,7 +256,7 @@ public class ControllerContext implements SchemaContextListener { public DataNodeContainer getDataNodeContainerFor( final InstanceIdentifier path ) { this.checkPreconditions(); - final List elements = path.getPath(); + final Iterable elements = path.getPathArguments(); PathArgument head = elements.iterator().next(); final QName startQName = head.getNodeType(); final Module initialModule = globalSchema.findModuleByNamespaceAndRevision( @@ -277,7 +277,7 @@ public class ControllerContext implements SchemaContextListener { public String toFullRestconfIdentifier( final InstanceIdentifier path ) { this.checkPreconditions(); - final List elements = path.getPath(); + final Iterable elements = path.getPathArguments(); final StringBuilder builder = new StringBuilder(); PathArgument head = elements.iterator().next(); final QName startQName = head.getNodeType(); @@ -805,8 +805,8 @@ public class ControllerContext implements SchemaContextListener { public boolean isInstantiatedDataSchema( final DataSchemaNode node ) { return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode || - node instanceof ContainerSchemaNode || node instanceof ListSchemaNode || - node instanceof AnyXmlSchemaNode; + node instanceof ContainerSchemaNode || node instanceof ListSchemaNode || + node instanceof AnyXmlSchemaNode; } private void addKeyValue( final HashMap map, final DataSchemaNode node, diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java index 4716a02be2..5a16c04aed 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java @@ -15,6 +15,7 @@ import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; + import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -27,10 +28,12 @@ import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.concurrent.Future; + import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; + import org.apache.commons.lang3.StringUtils; import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.sal.core.api.mount.MountInstance; @@ -112,7 +115,7 @@ public class RestconfImpl implements RestconfService { final List> modulesAsData = new ArrayList>(); final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); Set allModules = this.controllerContext.getAllModules(); for (final Module module : allModules) { @@ -121,7 +124,7 @@ public class RestconfImpl implements RestconfService { } final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); QName qName = modulesSchemaNode.getQName(); final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData); return new StructuredData(modulesNode, modulesSchemaNode, null); @@ -134,13 +137,13 @@ public class RestconfImpl implements RestconfService { final List> streamsAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE); for (final String streamName : availableStreams) { streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode)); } final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); QName qName = streamsSchemaNode.getQName(); final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData); return new StructuredData(streamsNode, streamsSchemaNode, null); @@ -152,27 +155,27 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); modules = this.controllerContext.getAllModules(mountPoint); } else { throw new RestconfDocumentedException( "URI has bad format. If modules behind mount point should be showed, URI has to end with " + - ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } final List> modulesAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); for (final Module module : modules) { modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode)); } final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); QName qName = modulesSchemaNode.getQName(); final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData); return new StructuredData(modulesNode, modulesSchemaNode, mountPoint); @@ -185,7 +188,7 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision); } @@ -196,13 +199,13 @@ public class RestconfImpl implements RestconfService { if (module == null) { throw new RestconfDocumentedException( "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '" + - moduleNameAndRevision.getRevision() + "' was not found.", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + moduleNameAndRevision.getRevision() + "' was not found.", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); } Module restconfModule = this.getRestconfModule(); final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode); return new StructuredData(moduleNode, moduleSchemaNode, mountPoint); } @@ -219,36 +222,36 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); modules = this.controllerContext.getAllModules(mountPoint); } else { throw new RestconfDocumentedException( "URI has bad format. If operations behind mount point should be showed, URI has to end with " + - ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } return this.operationsFromModulesToStructuredData(modules, mountPoint); } private StructuredData operationsFromModulesToStructuredData(final Set modules, - final MountInstance mountPoint) { + final MountInstance mountPoint) { final List> operationsAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); QName qName = operationsSchemaNode.getQName(); SchemaPath path = operationsSchemaNode.getPath(); ContainerSchemaNodeBuilder containerSchemaNodeBuilder = - new ContainerSchemaNodeBuilder(Draft02.RestConfModule.NAME, 0, qName, path); + new ContainerSchemaNodeBuilder(Draft02.RestConfModule.NAME, 0, qName, path); final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder; for (final Module module : modules) { Set rpcs = module.getRpcs(); for (final RpcDefinition rpc : rpcs) { QName rpcQName = rpc.getQName(); SimpleNode immutableSimpleNode = - NodeFactory.createImmutableSimpleNode(rpcQName, null, null); + NodeFactory.createImmutableSimpleNode(rpcQName, null, null); operationsAsData.add(immutableSimpleNode); String name = module.getName(); @@ -264,7 +267,7 @@ public class RestconfImpl implements RestconfService { } final CompositeNode operationsNode = - NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData); + NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData); ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build(); return new StructuredData(operationsNode, schemaNode, mountPoint); } @@ -316,34 +319,34 @@ public class RestconfImpl implements RestconfService { final List> streamNodeValues = new ArrayList>(); List instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) streamSchemaNode), - "name"); + "name"); final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(nameSchemaNode.getQName(), null, - streamName)); + streamName)); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) streamSchemaNode), "description"); + ((DataNodeContainer) streamSchemaNode), "description"); final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(descriptionSchemaNode.getQName(), null, - "DESCRIPTION_PLACEHOLDER")); + "DESCRIPTION_PLACEHOLDER")); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) streamSchemaNode), "replay-support"); + ((DataNodeContainer) streamSchemaNode), "replay-support"); final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null, - Boolean.valueOf(true))); + Boolean.valueOf(true))); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time"); + ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time"); final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(), - null, "")); + null, "")); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) streamSchemaNode), "events"); + ((DataNodeContainer) streamSchemaNode), "events"); final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(eventsSchemaNode.getQName(), - null, "")); + null, "")); return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues); } @@ -351,30 +354,30 @@ public class RestconfImpl implements RestconfService { private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) { final List> moduleNodeValues = new ArrayList>(); List instanceDataChildrenByName = - this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name"); + this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name"); final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(nameSchemaNode.getQName(), - null, module.getName())); + null, module.getName())); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) moduleSchemaNode), "revision"); + ((DataNodeContainer) moduleSchemaNode), "revision"); final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); Date _revision = module.getRevision(); moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(revisionSchemaNode.getQName(), null, - REVISION_FORMAT.format(_revision))); + REVISION_FORMAT.format(_revision))); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) moduleSchemaNode), "namespace"); + ((DataNodeContainer) moduleSchemaNode), "namespace"); final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(namespaceSchemaNode.getQName(), null, - module.getNamespace().toString())); + module.getNamespace().toString())); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) moduleSchemaNode), "feature"); + ((DataNodeContainer) moduleSchemaNode), "feature"); final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); for (final FeatureDefinition feature : module.getFeatures()) { moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(featureSchemaNode.getQName(), null, - feature.getQName().getLocalName())); + feature.getQName().getLocalName())); } return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues); @@ -391,7 +394,7 @@ public class RestconfImpl implements RestconfService { QName rpcName = rpc.getRpcDefinition().getQName(); URI rpcNamespace = rpcName.getNamespace(); if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE) && - Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) { + Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) { return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition()); } @@ -400,33 +403,33 @@ public class RestconfImpl implements RestconfService { return callRpc(rpc, payload); } - private void validateInput(DataSchemaNode inputSchema, CompositeNode payload) { + private void validateInput(final DataSchemaNode inputSchema, final CompositeNode payload) { if( inputSchema != null && payload == null ) { //expected a non null payload throw new RestconfDocumentedException( "Input is required.", - ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE ); + ErrorType.PROTOCOL, + ErrorTag.MALFORMED_MESSAGE ); } else if( inputSchema == null && payload != null ) { //did not expect any input throw new RestconfDocumentedException( "No input expected.", - ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE ); + ErrorType.PROTOCOL, + ErrorTag.MALFORMED_MESSAGE ); } //else //{ - //TODO: Validate "mandatory" and "config" values here??? Or should those be + //TODO: Validate "mandatory" and "config" values here??? Or should those be // validate in a more central location inside MD-SAL core. //} } private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, - final RpcDefinition rpc) { + final RpcDefinition rpc) { final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null); final SimpleNode pathNode = value == null ? null : - value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") ); + value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") ); final Object pathValue = pathNode == null ? null : pathNode.getValue(); if (!(pathValue instanceof InstanceIdentifier)) { @@ -437,7 +440,7 @@ public class RestconfImpl implements RestconfService { final InstanceIdentifier pathIdentifier = ((InstanceIdentifier) pathValue); String streamName = null; - if (!Iterables.isEmpty(pathIdentifier.getPath())) { + if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) { String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier); streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier); } @@ -449,12 +452,12 @@ public class RestconfImpl implements RestconfService { } final SimpleNode streamNameNode = NodeFactory.createImmutableSimpleNode( - QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName); + QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName); final List> output = new ArrayList>(); output.add(streamNameNode); final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode( - rpc.getOutput().getQName(), null, output, null, null); + rpc.getOutput().getQName(), null, output, null, null); if (!Notificator.existListenerFor(pathIdentifier)) { Notificator.createListener(pathIdentifier, streamName); @@ -547,14 +550,14 @@ public class RestconfImpl implements RestconfService { return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null); } - private void checkRpcSuccessAndThrowException(RpcResult rpcResult) { + private void checkRpcSuccessAndThrowException(final RpcResult rpcResult) { if (rpcResult.isSuccessful() == false) { Collection rpcErrors = rpcResult.getErrors(); if( rpcErrors == null || rpcErrors.isEmpty() ) { throw new RestconfDocumentedException( - "The operation was not successful and there were no RPC errors returned", - ErrorType.RPC, ErrorTag.OPERATION_FAILED ); + "The operation was not successful and there were no RPC errors returned", + ErrorType.RPC, ErrorTag.OPERATION_FAILED ); } List errorList = Lists.newArrayList(); @@ -567,7 +570,7 @@ public class RestconfImpl implements RestconfService { } @Override - public StructuredData readConfigurationData(final String identifier, UriInfo info) { + public StructuredData readConfigurationData(final String identifier, final UriInfo info) { final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier); CompositeNode data = null; MountInstance mountPoint = iiWithData.getMountPoint(); @@ -583,7 +586,7 @@ public class RestconfImpl implements RestconfService { } @SuppressWarnings("unchecked") - private > T pruneDataAtDepth( T node, Integer depth ) { + private > T pruneDataAtDepth( final T node, final Integer depth ) { if( depth == null ) { return node; } @@ -603,7 +606,7 @@ public class RestconfImpl implements RestconfService { } } - private Integer parseDepthParameter( UriInfo info ) { + private Integer parseDepthParameter( final UriInfo info ) { String param = info.getQueryParameters( false ).getFirst( "depth" ); if( Strings.isNullOrEmpty( param ) || "unbounded".equals( param ) ) { return null; @@ -628,7 +631,7 @@ public class RestconfImpl implements RestconfService { } @Override - public StructuredData readOperationalData(final String identifier, UriInfo info) { + public StructuredData readOperationalData(final String identifier, final UriInfo info) { final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier); CompositeNode data = null; MountInstance mountPoint = iiWithData.getMountPoint(); @@ -656,7 +659,7 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { status = broker.commitConfigurationDataPutBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value).get(); + mountPoint, iiWithData.getInstanceIdentifier(), value).get(); } else { status = broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), value).get(); } @@ -665,8 +668,9 @@ public class RestconfImpl implements RestconfService { throw new RestconfDocumentedException( "Error updating data", e ); } - if( status.getResult() == TransactionStatus.COMMITED ) + if( status.getResult() == TransactionStatus.COMMITED ) { return Response.status(Status.OK).build(); + } return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } @@ -682,14 +686,14 @@ public class RestconfImpl implements RestconfService { URI payloadNS = this.namespace(payload); if (payloadNS == null) { throw new RestconfDocumentedException( - "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); + "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); } InstanceIdWithSchemaNode iiWithData = null; CompositeNode value = null; if (this.representsMountPointRootData(payload)) { - // payload represents mount point data and URI represents path to the mount point + // payload represents mount point data and URI represents path to the mount point if (this.endsWithMountPoint(identifier)) { throw new RestconfDocumentedException( @@ -705,7 +709,7 @@ public class RestconfImpl implements RestconfService { } else { final InstanceIdWithSchemaNode incompleteInstIdWithData = - this.controllerContext.toInstanceIdentifier(identifier); + this.controllerContext.toInstanceIdentifier(identifier); final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode(); MountInstance mountPoint = incompleteInstIdWithData.getMountPoint(); final Module module = this.findModule(mountPoint, payload); @@ -717,7 +721,7 @@ public class RestconfImpl implements RestconfService { String payloadName = this.getName(payload); final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace( - parentSchema, payloadName, module.getNamespace()); + parentSchema, payloadName, module.getNamespace()); value = this.normalizeNode(payload, schemaNode, mountPoint); iiWithData = this.addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode); @@ -728,13 +732,13 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { Future> future = - broker.commitConfigurationDataPostBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value); + broker.commitConfigurationDataPostBehindMountPoint( + mountPoint, iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } else { Future> future = - broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); + broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } } @@ -746,8 +750,9 @@ public class RestconfImpl implements RestconfService { return Response.status(Status.ACCEPTED).build(); } - if( status.getResult() == TransactionStatus.COMMITED ) + if( status.getResult() == TransactionStatus.COMMITED ) { return Response.status(Status.NO_CONTENT).build(); + } return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } @@ -763,8 +768,8 @@ public class RestconfImpl implements RestconfService { URI payloadNS = this.namespace(payload); if (payloadNS == null) { throw new RestconfDocumentedException( - "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); + "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); } final Module module = this.findModule(null, payload); @@ -776,7 +781,7 @@ public class RestconfImpl implements RestconfService { String payloadName = this.getName(payload); final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace( - module, payloadName, module.getNamespace()); + module, payloadName, module.getNamespace()); final CompositeNode value = this.normalizeNode(payload, schemaNode, null); final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode); RpcResult status = null; @@ -785,13 +790,13 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { Future> future = - broker.commitConfigurationDataPostBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value); + broker.commitConfigurationDataPostBehindMountPoint( + mountPoint, iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } else { Future> future = - broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); + broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } } @@ -803,8 +808,9 @@ public class RestconfImpl implements RestconfService { return Response.status(Status.ACCEPTED).build(); } - if( status.getResult() == TransactionStatus.COMMITED ) + if( status.getResult() == TransactionStatus.COMMITED ) { return Response.status(Status.NO_CONTENT).build(); + } return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } @@ -818,7 +824,7 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { status = broker.commitConfigurationDataDeleteBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier()).get(); + mountPoint, iiWithData.getInstanceIdentifier()).get(); } else { status = broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get(); @@ -828,8 +834,9 @@ public class RestconfImpl implements RestconfService { throw new RestconfDocumentedException( "Error creating data", e ); } - if( status.getResult() == TransactionStatus.COMMITED ) + if( status.getResult() == TransactionStatus.COMMITED ) { return Response.status(Status.OK).build(); + } return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } @@ -898,8 +905,8 @@ public class RestconfImpl implements RestconfService { } private InstanceIdWithSchemaNode addLastIdentifierFromData( - final InstanceIdWithSchemaNode identifierWithSchemaNode, - final CompositeNode data, final DataSchemaNode schemaOfData) { + final InstanceIdWithSchemaNode identifierWithSchemaNode, + final CompositeNode data, final DataSchemaNode schemaOfData) { InstanceIdentifier instanceIdentifier = null; if (identifierWithSchemaNode != null) { instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier(); @@ -932,7 +939,7 @@ public class RestconfImpl implements RestconfService { } private HashMap resolveKeysFromData(final ListSchemaNode listNode, - final CompositeNode dataNode) { + final CompositeNode dataNode) { final HashMap keyValues = new HashMap(); List _keyDefinition = listNode.getKeyDefinition(); for (final QName key : _keyDefinition) { @@ -963,7 +970,7 @@ public class RestconfImpl implements RestconfService { private boolean endsWithMountPoint(final String identifier) { return identifier.endsWith(ControllerContext.MOUNT) || - identifier.endsWith(ControllerContext.MOUNT + "/"); + identifier.endsWith(ControllerContext.MOUNT + "/"); } private boolean representsMountPointRootData(final CompositeNode data) { @@ -983,7 +990,7 @@ public class RestconfImpl implements RestconfService { } private CompositeNode normalizeNode(final CompositeNode node, final DataSchemaNode schema, - final MountInstance mountPoint) { + final MountInstance mountPoint) { if (schema == null) { QName nodeType = node == null ? null : node.getNodeType(); String localName = nodeType == null ? null : nodeType.getLocalName(); @@ -1007,7 +1014,7 @@ public class RestconfImpl implements RestconfService { } catch (IllegalArgumentException e) { throw new RestconfDocumentedException( - e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } } @@ -1018,8 +1025,8 @@ public class RestconfImpl implements RestconfService { } private void normalizeNode(final NodeWrapper nodeBuilder, - final DataSchemaNode schema, final QName previousAugment, - final MountInstance mountPoint) { + final DataSchemaNode schema, final QName previousAugment, + final MountInstance mountPoint) { if (schema == null) { throw new RestconfDocumentedException( "Data has bad format.\n\"" + nodeBuilder.getLocalName() + @@ -1036,19 +1043,19 @@ public class RestconfImpl implements RestconfService { if (nodeBuilder.getQname() == null) { throw new RestconfDocumentedException( "Data has bad format.\nIf data is in XML format then namespace for \"" + - nodeBuilder.getLocalName() + - "\" should be \"" + schema.getQName().getNamespace() + "\".\n" + - "If data is in JSON format then module name for \"" + nodeBuilder.getLocalName() + - "\" should be corresponding to namespace \"" + - schema.getQName().getNamespace() + "\".", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + nodeBuilder.getLocalName() + + "\" should be \"" + schema.getQName().getNamespace() + "\".\n" + + "If data is in JSON format then module name for \"" + nodeBuilder.getLocalName() + + "\" should be corresponding to namespace \"" + + schema.getQName().getNamespace() + "\".", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } } if ( nodeBuilder instanceof CompositeNodeWrapper ) { if( schema instanceof DataNodeContainer ) { normalizeCompositeNode( (CompositeNodeWrapper)nodeBuilder, (DataNodeContainer)schema, - mountPoint, currentAugment ); + mountPoint, currentAugment ); } else if( schema instanceof AnyXmlSchemaNode ) { normalizeAnyXmlNode( (CompositeNodeWrapper)nodeBuilder, (AnyXmlSchemaNode)schema ); @@ -1062,7 +1069,7 @@ public class RestconfImpl implements RestconfService { } } - private void normalizeAnyXmlNode( CompositeNodeWrapper compositeNode, AnyXmlSchemaNode schema ) { + private void normalizeAnyXmlNode( final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema ) { List> children = compositeNode.getValues(); for( NodeWrapper child : children ) { child.setNamespace( schema.getQName().getNamespace() ); @@ -1072,7 +1079,7 @@ public class RestconfImpl implements RestconfService { } } - private void normalizeEmptyNode( EmptyNodeWrapper emptyNodeBuilder, DataSchemaNode schema ) { + private void normalizeEmptyNode( final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema ) { if ((schema instanceof LeafSchemaNode)) { emptyNodeBuilder.setComposite(false); } @@ -1084,8 +1091,8 @@ public class RestconfImpl implements RestconfService { } } - private void normalizeSimpleNode( SimpleNodeWrapper simpleNode, DataSchemaNode schema, - MountInstance mountPoint ) { + private void normalizeSimpleNode( final SimpleNodeWrapper simpleNode, final DataSchemaNode schema, + final MountInstance mountPoint ) { final Object value = simpleNode.getValue(); Object inputValue = value; TypeDefinition typeDefinition = this.typeDefinition(schema); @@ -1106,28 +1113,28 @@ public class RestconfImpl implements RestconfService { simpleNode.setValue(outputValue); } - private void normalizeCompositeNode( CompositeNodeWrapper compositeNodeBuilder, - DataNodeContainer schema, MountInstance mountPoint, - QName currentAugment ) { + private void normalizeCompositeNode( final CompositeNodeWrapper compositeNodeBuilder, + final DataNodeContainer schema, final MountInstance mountPoint, + final QName currentAugment ) { final List> children = compositeNodeBuilder.getValues(); for (final NodeWrapper child : children) { final List potentialSchemaNodes = this.controllerContext.findInstanceDataChildrenByName( - schema, child.getLocalName()); + schema, child.getLocalName()); if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) { StringBuilder builder = new StringBuilder(); for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) { builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()) - .append("\n"); + .append("\n"); } throw new RestconfDocumentedException( - "Node \"" + child.getLocalName() + - "\" is added as augment from more than one module. " + - "Therefore node must have namespace (XML format) or module name (JSON format)." + - "\nThe node is added as augment from modules with namespaces:\n" + builder, - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + "Node \"" + child.getLocalName() + + "\" is added as augment from more than one module. " + + "Therefore node must have namespace (XML format) or module name (JSON format)." + + "\nThe node is added as augment from modules with namespaces:\n" + builder, + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } boolean rightNodeSchemaFound = false; @@ -1144,8 +1151,8 @@ public class RestconfImpl implements RestconfService { if (!rightNodeSchemaFound) { throw new RestconfDocumentedException( - "Schema node \"" + child.getLocalName() + "\" was not found in module.", - ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT ); + "Schema node \"" + child.getLocalName() + "\" was not found in module.", + ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT ); } } @@ -1162,24 +1169,24 @@ public class RestconfImpl implements RestconfService { if (!foundKey) { throw new RestconfDocumentedException( - "Missing key in URI \"" + listKey.getLocalName() + - "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + "Missing key in URI \"" + listKey.getLocalName() + + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } } } } private QName normalizeNodeName(final NodeWrapper nodeBuilder, - final DataSchemaNode schema, final QName previousAugment, - final MountInstance mountPoint) { + final DataSchemaNode schema, final QName previousAugment, + final MountInstance mountPoint) { QName validQName = schema.getQName(); QName currentAugment = previousAugment; if (schema.isAugmenting()) { currentAugment = schema.getQName(); } else if (previousAugment != null && - !Objects.equal( schema.getQName().getNamespace(), previousAugment.getNamespace())) { + !Objects.equal( schema.getQName().getNamespace(), previousAugment.getNamespace())) { validQName = QName.create(currentAugment, schema.getQName().getLocalName()); } @@ -1192,8 +1199,8 @@ public class RestconfImpl implements RestconfService { } if (nodeBuilder.getNamespace() == null || - Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace()) || - Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*|| + Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace()) || + Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*|| Note: this check is wrong - can never be true as it compares a URI with a String not sure what the intention is so commented out... Objects.equal(nodeBuilder.getNamespace(), MOUNT_POINT_MODULE_NAME)*/ ) { diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java index 6282f37602..e1c163bc48 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java @@ -7,6 +7,11 @@ */ package org.opendaylight.controller.sal.streams.listeners; +import com.google.common.base.Preconditions; +import com.google.common.eventbus.AsyncEventBus; +import com.google.common.eventbus.EventBus; +import com.google.common.eventbus.Subscribe; + import io.netty.channel.Channel; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.internal.ConcurrentSet; @@ -53,11 +58,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import com.google.common.base.Preconditions; -import com.google.common.eventbus.AsyncEventBus; -import com.google.common.eventbus.EventBus; -import com.google.common.eventbus.Subscribe; - /** * {@link ListenerAdapter} is responsible to track events, which occurred by * changing data in data source. @@ -86,10 +86,10 @@ public class ListenerAdapter implements DataChangeListener { * @param streamName * The name of the stream. */ - ListenerAdapter(InstanceIdentifier path, String streamName) { + ListenerAdapter(final InstanceIdentifier path, final String streamName) { Preconditions.checkNotNull(path); Preconditions - .checkArgument(streamName != null && !streamName.isEmpty()); + .checkArgument(streamName != null && !streamName.isEmpty()); this.path = path; this.streamName = streamName; eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor()); @@ -99,7 +99,7 @@ public class ListenerAdapter implements DataChangeListener { @Override public void onDataChanged( - DataChangeEvent change) { + final DataChangeEvent change) { if (!change.getCreatedConfigurationData().isEmpty() || !change.getCreatedOperationalData().isEmpty() || !change.getUpdatedConfigurationData().isEmpty() @@ -118,7 +118,7 @@ public class ListenerAdapter implements DataChangeListener { */ private final class EventBusChangeRecorder { @Subscribe - public void recordCustomerChange(Event event) { + public void recordCustomerChange(final Event event) { if (event.getType() == EventType.REGISTER) { Channel subscriber = event.getSubscriber(); if (!subscribers.contains(subscriber)) { @@ -127,7 +127,7 @@ public class ListenerAdapter implements DataChangeListener { } else if (event.getType() == EventType.DEREGISTER) { subscribers.remove(event.getSubscriber()); Notificator - .removeListenerIfNoSubscriberExists(ListenerAdapter.this); + .removeListenerIfNoSubscriberExists(ListenerAdapter.this); } else if (event.getType() == EventType.NOTIFY) { for (Channel subscriber : subscribers) { if (subscriber.isActive()) { @@ -161,7 +161,7 @@ public class ListenerAdapter implements DataChangeListener { * @param type * EventType */ - public Event(EventType type) { + public Event(final EventType type) { this.type = type; } @@ -180,7 +180,7 @@ public class ListenerAdapter implements DataChangeListener { * @param subscriber * Channel */ - public void setSubscriber(Channel subscriber) { + public void setSubscriber(final Channel subscriber) { this.subscriber = subscriber; } @@ -199,7 +199,7 @@ public class ListenerAdapter implements DataChangeListener { * @param String * data. */ - public void setData(String data) { + public void setData(final String data) { this.data = data; } @@ -228,7 +228,7 @@ public class ListenerAdapter implements DataChangeListener { * @return Data in printable form. */ private String prepareXmlFrom( - DataChangeEvent change) { + final DataChangeEvent change) { Document doc = createDocument(); Element notificationElement = doc.createElementNS( "urn:ietf:params:xml:ns:netconf:notification:1.0", @@ -251,7 +251,7 @@ public class ListenerAdapter implements DataChangeListener { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer - .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); @@ -275,7 +275,7 @@ public class ListenerAdapter implements DataChangeListener { * Date * @return Data specified by RFC3339. */ - private String toRFC3339(Date d) { + private String toRFC3339(final Date d) { return rfc3339.format(d).replaceAll("(\\d\\d)(\\d\\d)$", "$1:$2"); } @@ -306,9 +306,9 @@ public class ListenerAdapter implements DataChangeListener { * @param change * {@link DataChangeEvent} */ - private void addValuesToDataChangedNotificationEventElement(Document doc, - Element dataChangedNotificationEventElement, - DataChangeEvent change) { + private void addValuesToDataChangedNotificationEventElement(final Document doc, + final Element dataChangedNotificationEventElement, + final DataChangeEvent change) { addValuesFromDataToElement(doc, change.getCreatedConfigurationData(), dataChangedNotificationEventElement, Store.CONFIG, Operation.CREATED); @@ -348,9 +348,9 @@ public class ListenerAdapter implements DataChangeListener { * @param operation * {@link Operation} */ - private void addValuesFromDataToElement(Document doc, - Set data, Element element, Store store, - Operation operation) { + private void addValuesFromDataToElement(final Document doc, + final Set data, final Element element, final Store store, + final Operation operation) { if (data == null || data.isEmpty()) { return; } @@ -375,9 +375,9 @@ public class ListenerAdapter implements DataChangeListener { * @param operation * {@link Operation} */ - private void addValuesFromDataToElement(Document doc, - Map data, Element element, - Store store, Operation operation) { + private void addValuesFromDataToElement(final Document doc, + final Map data, final Element element, + final Store store, final Operation operation) { if (data == null || data.isEmpty()) { return; } @@ -403,9 +403,9 @@ public class ListenerAdapter implements DataChangeListener { * {@link Operation} * @return {@link Node} node represented by changed event element. */ - private Node createDataChangeEventElement(Document doc, - InstanceIdentifier path, CompositeNode data, Store store, - Operation operation) { + private Node createDataChangeEventElement(final Document doc, + final InstanceIdentifier path, final CompositeNode data, final Store store, + final Operation operation) { Element dataChangeEventElement = doc.createElement("data-change-event"); Element pathElement = doc.createElement("path"); @@ -440,7 +440,7 @@ public class ListenerAdapter implements DataChangeListener { * {@link CompositeNode} * @return Data in XML format. */ - private Node translateToXml(InstanceIdentifier path, CompositeNode data) { + private Node translateToXml(final InstanceIdentifier path, final CompositeNode data) { DataNodeContainer schemaNode = ControllerContext.getInstance() .getDataNodeContainerFor(path); if (schemaNode == null) { @@ -468,13 +468,13 @@ public class ListenerAdapter implements DataChangeListener { * @param element * {@link Element} */ - private void addPathAsValueToElement(InstanceIdentifier path, - Element element) { + private void addPathAsValueToElement(final InstanceIdentifier path, + final Element element) { // Map< key = namespace, value = prefix> Map prefixes = new HashMap<>(); InstanceIdentifier instanceIdentifier = path; StringBuilder textContent = new StringBuilder(); - for (PathArgument pathArgument : instanceIdentifier.getPath()) { + for (PathArgument pathArgument : instanceIdentifier.getPathArguments()) { textContent.append("/"); writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes); @@ -514,8 +514,8 @@ public class ListenerAdapter implements DataChangeListener { * @param prefixes * Map of namespaces and prefixes. */ - private static void writeIdentifierWithNamespacePrefix(Element element, - StringBuilder textContent, QName qName, Map prefixes) { + private static void writeIdentifierWithNamespacePrefix(final Element element, + final StringBuilder textContent, final QName qName, final Map prefixes) { String namespace = qName.getNamespace().toString(); String prefix = prefixes.get(namespace); if (prefix == null) { @@ -541,7 +541,7 @@ public class ListenerAdapter implements DataChangeListener { * Collection of prefixes. * @return New prefix which consists of four random characters . */ - private static String generateNewPrefix(Collection prefixes) { + private static String generateNewPrefix(final Collection prefixes) { StringBuilder result = null; Random random = new Random(); do { @@ -571,7 +571,7 @@ public class ListenerAdapter implements DataChangeListener { * ListenerRegistration */ public void setRegistration( - ListenerRegistration registration) { + final ListenerRegistration registration) { this.registration = registration; } @@ -611,7 +611,7 @@ public class ListenerAdapter implements DataChangeListener { * @param subscriber * Channel */ - public void addSubscriber(Channel subscriber) { + public void addSubscriber(final Channel subscriber) { if (!subscriber.isActive()) { logger.debug("Channel is not active between websocket server and subscriber {}" + subscriber.remoteAddress()); @@ -627,7 +627,7 @@ public class ListenerAdapter implements DataChangeListener { * * @param subscriber */ - public void removeSubscriber(Channel subscriber) { + public void removeSubscriber(final Channel subscriber) { logger.debug("Subscriber {} is removed.", subscriber.remoteAddress()); Event event = new Event(EventType.DEREGISTER); event.setSubscriber(subscriber); @@ -652,7 +652,7 @@ public class ListenerAdapter implements DataChangeListener { private final String value; - private Store(String value) { + private Store(final String value) { this.value = value; } } @@ -666,7 +666,7 @@ public class ListenerAdapter implements DataChangeListener { private final String value; - private Operation(String value) { + private Operation(final String value) { this.value = value; } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java index 33d4b325be..efdb7b240c 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java @@ -14,6 +14,8 @@ import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.common.collect.Iterables; + import java.io.FileNotFoundException; import java.util.Set; @@ -131,7 +133,7 @@ public class URITest { initMountService(true); InstanceIdWithSchemaNode instanceIdentifier = controllerContext .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/"); - assertEquals(true, instanceIdentifier.getInstanceIdentifier().getPath().isEmpty()); + assertTrue(Iterables.isEmpty(instanceIdentifier.getInstanceIdentifier().getPathArguments())); } @Test @@ -152,7 +154,7 @@ public class URITest { .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class"); } - public void initMountService(boolean withSchema) { + public void initMountService(final boolean withSchema) { MountService mountService = mock(MountService.class); controllerContext.setMountService(mountService); BrokerFacade brokerFacade = mock(BrokerFacade.class); @@ -163,10 +165,11 @@ public class URITest { Set modules2 = TestUtils.loadModulesFrom("/test-config-data/yang2"); SchemaContext schemaContext2 = TestUtils.loadSchemaContext(modules2); MountInstance mountInstance = mock(MountInstance.class); - if (withSchema) + if (withSchema) { when(mountInstance.getSchemaContext()).thenReturn(schemaContext2); - else + } else { when(mountInstance.getSchemaContext()).thenReturn(null); + } when(mountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance); } } diff --git a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java index b996bf1234..fcabb088f4 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java +++ b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java @@ -46,7 +46,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount private final Map instanceIdToLongId = new TreeMap<>( new Comparator() { @Override - public int compare(InstanceIdentifier o1, InstanceIdentifier o2) { + public int compare(final InstanceIdentifier o1, final InstanceIdentifier o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); @@ -71,12 +71,12 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return urlToId; } - public void setGlobalSchema(SchemaService globalSchema) { + public void setGlobalSchema(final SchemaService globalSchema) { this.globalSchema = globalSchema; } - private String findModuleName(InstanceIdentifier id, SchemaContext context) { - PathArgument rootQName = id.getPath().get(0); + private String findModuleName(final InstanceIdentifier id, final SchemaContext context) { + PathArgument rootQName = id.getPathArguments().iterator().next(); for (Module mod : context.getModules()) { if (mod.getDataChildByName(rootQName.getNodeType()) != null) { return mod.getName(); @@ -85,40 +85,39 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return null; } - private String generateUrlPrefixFromInstanceID(InstanceIdentifier key, String moduleName) { - List path = key.getPath(); + private String generateUrlPrefixFromInstanceID(final InstanceIdentifier key, final String moduleName) { StringBuilder builder = new StringBuilder(); if (moduleName != null) { builder.append(moduleName); - builder.append(":"); + builder.append(':'); } boolean first = true; - for (PathArgument arg : path) { + for (PathArgument arg : key.getPathArguments()) { String name = arg.getNodeType().getLocalName(); if (first) { first = false; } else { - builder.append("/"); + builder.append('/'); } builder.append(name); if (arg instanceof InstanceIdentifier.NodeIdentifierWithPredicates) { NodeIdentifierWithPredicates nodeId = (NodeIdentifierWithPredicates) arg; for (Entry entry : nodeId.getKeyValues().entrySet()) { - builder.append("/").append(entry.getValue()); + builder.append('/').append(entry.getValue()); } } } - return builder.append("/").toString(); + return builder.append('/').toString(); } - private String getYangMountUrl(InstanceIdentifier key) { + private String getYangMountUrl(final InstanceIdentifier key) { String modName = findModuleName(key, globalSchema.getGlobalContext()); return generateUrlPrefixFromInstanceID(key, modName) + "yang-ext:mount/"; } - public ResourceList getResourceList(UriInfo uriInfo, Long id) { + public ResourceList getResourceList(final UriInfo uriInfo, final Long id) { InstanceIdentifier iid = getInstanceId(id); if (iid == null) { return null; // indicating not found. @@ -139,7 +138,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return list; } - private InstanceIdentifier getInstanceId(Long id) { + private InstanceIdentifier getInstanceId(final Long id) { InstanceIdentifier instanceId; synchronized (lock) { instanceId = longIdToInstanceId.get(id); @@ -147,7 +146,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return instanceId; } - private SchemaContext getSchemaContext(InstanceIdentifier id) { + private SchemaContext getSchemaContext(final InstanceIdentifier id) { if (id == null) { return null; @@ -165,7 +164,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return context; } - public ApiDeclaration getMountPointApi(UriInfo uriInfo, Long id, String module, String revision) { + public ApiDeclaration getMountPointApi(final UriInfo uriInfo, final Long id, final String module, final String revision) { InstanceIdentifier iid = getInstanceId(id); SchemaContext context = getSchemaContext(iid); String urlPrefix = getYangMountUrl(iid); @@ -179,7 +178,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return super.getApiDeclaration(module, revision, uriInfo, context, urlPrefix); } - private ApiDeclaration generateDataStoreApiDoc(UriInfo uriInfo, String context) { + private ApiDeclaration generateDataStoreApiDoc(final UriInfo uriInfo, final String context) { ApiDeclaration declaration = super.createApiDeclaration(createBasePathFromUriInfo(uriInfo)); List apis = new LinkedList<>(); @@ -194,7 +193,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount } - private Api createGetApi(String datastore, String note, String context) { + private Api createGetApi(final String datastore, final String note, final String context) { Operation getConfig = new Operation(); getConfig.setMethod("GET"); getConfig.setNickname("GET " + datastore); @@ -207,12 +206,12 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return api; } - public void setMountService(MountProvisionService mountService) { + public void setMountService(final MountProvisionService mountService) { this.mountService = mountService; } @Override - public void onMountPointCreated(InstanceIdentifier path) { + public void onMountPointCreated(final InstanceIdentifier path) { synchronized (lock) { Long idLong = idKey.incrementAndGet(); instanceIdToLongId.put(path, idLong); @@ -221,7 +220,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount } @Override - public void onMountPointRemoved(InstanceIdentifier path) { + public void onMountPointRemoved(final InstanceIdentifier path) { synchronized (lock) { Long id = instanceIdToLongId.remove(path); longIdToInstanceId.remove(id); -- 2.36.6