From: Tony Tkacik Date: Sun, 3 Aug 2014 18:17:46 +0000 (+0000) Subject: Merge "Bug 1392: Change ReadTransaction#read to return CheckedFuture" X-Git-Tag: release/helium~356 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=commitdiff_plain;h=dcbf09a50b0f7fb437386f0433bd4464db1193de;hp=10948fbda7e6d997525cce5b4929a1e426045c52;p=controller.git Merge "Bug 1392: Change ReadTransaction#read to return CheckedFuture" --- diff --git a/.gitignore b/.gitignore index f8cf74f826..9144cda4cc 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,5 @@ out/ maven-eclipse.xml .DS_STORE .metadata +opendaylight/md-sal/sal-distributed-datastore/journal + diff --git a/features/nsf/src/main/resources/features.xml b/features/nsf/src/main/resources/features.xml index fb61f33fb3..130d72e01a 100644 --- a/features/nsf/src/main/resources/features.xml +++ b/features/nsf/src/main/resources/features.xml @@ -34,12 +34,14 @@ mvn:org.opendaylight.controller/forwardingrulesmanager.implementation/${forwardingrulesmanager.implementation.version} mvn:org.opendaylight.controller/topologymanager/${topologymanager.version} + mvn:org.opendaylight.controller/topologymanager.shell/${topologymanager.shell.version} mvn:org.opendaylight.controller/networkconfig.neutron/${networkconfig.neutron.version} mvn:org.opendaylight.controller/networkconfig.neutron.implementation/${networkconfig.neutron.implementation.version} mvn:org.opendaylight.controller/hosttracker/${hosttracker.api.version} mvn:org.opendaylight.controller/hosttracker.implementation/${hosttracker.implementation.version} + mvn:org.opendaylight.controller/hosttracker.shell/${hosttracker.shell.version} mvn:org.opendaylight.controller/forwarding.staticrouting @@ -70,4 +72,4 @@ mvn:org.opendaylight.controller/topology.northbound/${topology.northbound.version} mvn:org.opendaylight.controller/usermanager.northbound/${usermanager.northbound.version} - \ No newline at end of file + diff --git a/itests/base-features-it/pom.xml b/itests/base-features-it/pom.xml new file mode 100644 index 0000000000..8f73779009 --- /dev/null +++ b/itests/base-features-it/pom.xml @@ -0,0 +1,90 @@ + + 4.0.0 + + org.opendaylight.controller + itests-controller + 1.4.2-SNAPSHOT + ../pom.xml + + base-features-it + base-features-it + jar + + + org.opendaylight.controller + base-features + ${project.version} + features + xml + + + org.slf4j + slf4j-api + + + + org.ops4j.pax.exam + pax-exam-container-karaf + ${pax.exam.version} + test + + + org.ops4j.pax.exam + pax-exam-junit4 + test + + + org.ops4j.pax.exam + pax-exam + ${pax.exam.version} + test + + + org.ops4j.pax.url + pax-url-aether + test + + + javax.inject + javax.inject + 1 + test + + + org.apache.karaf.features + org.apache.karaf.features.core + ${karaf.version} + test + + + org.osgi + org.osgi.core + test + + + junit + junit + test + + + + + + + + + + + diff --git a/itests/base-features-it/src/test/java/org/opendaylight/controller/base/BaseFeatureTest.java b/itests/base-features-it/src/test/java/org/opendaylight/controller/base/BaseFeatureTest.java new file mode 100644 index 0000000000..0d38940346 --- /dev/null +++ b/itests/base-features-it/src/test/java/org/opendaylight/controller/base/BaseFeatureTest.java @@ -0,0 +1,74 @@ +package org.opendaylight.controller.base; + +import static org.ops4j.pax.exam.CoreOptions.maven; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.logLevel; + +import java.io.File; +import java.net.URI; +import java.util.EnumSet; + +import javax.inject.Inject; + +import junit.framework.Assert; + +import org.apache.karaf.features.Feature; +import org.apache.karaf.features.FeaturesService; +import org.apache.karaf.features.Repository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.ops4j.pax.exam.Configuration; +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.junit.PaxExam; +import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel; + + +@RunWith(PaxExam.class) +public class BaseFeatureTest { + @Inject + private FeaturesService featuresService; + @Configuration + public Option[] config() { + return new Option[] { + // Provision and launch a container based on a distribution of Karaf (Apache ServiceMix). + karafDistributionConfiguration() + .frameworkUrl( + maven() + .groupId("org.opendaylight.controller") + .artifactId("distribution.opendaylight-karaf") + .type("tar.gz") + .version("1.4.2-SNAPSHOT")) + .name("OpenDaylight") + .unpackDirectory(new File("target/pax")) + .useDeployFolder(false), + // It is really nice if the container sticks around after the test so you can check the contents + // of the data directory when things go wrong. + keepRuntimeFolder(), + // Don't bother with local console output as it just ends up cluttering the logs + configureConsole().ignoreLocalConsole(), + // Force the log level to INFO so we have more details during the test. It defaults to WARN. + logLevel(LogLevel.WARN), + // Remember that the test executes in another process. If you want to debug it, you need + // to tell Pax Exam to launch that process with debugging enabled. Launching the test class itself with + // debugging enabled (for example in Eclipse) will not get you the desired results. + //debugConfiguration("5000", true), + }; + } + + @Test + public void testAllFeatures() throws Exception { + featuresService.addRepository(new URI("mvn:org.opendaylight.controller/base-features/1.4.2-SNAPSHOT/xml/features")); + Repository repoUnderTest = featuresService.getRepository("base-1.4.2-SNAPSHOT"); + Assert.assertNotNull(repoUnderTest); + Feature[] featuresUnderTest = repoUnderTest.getFeatures(); + for(int i=0; i< featuresUnderTest.length; i++) + { + Feature feature = featuresUnderTest[i]; + featuresService.installFeature(feature,EnumSet.of(FeaturesService.Option.Verbose)); + System.out.println("Testing Feature:"+feature.getName()); + Assert.assertTrue(featuresService.isInstalled(feature)); + } + } +} \ No newline at end of file diff --git a/itests/pom.xml b/itests/pom.xml new file mode 100644 index 0000000000..19836a2ad6 --- /dev/null +++ b/itests/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + + org.opendaylight.controller + commons.opendaylight + 1.4.2-SNAPSHOT + ../opendaylight/commons/opendaylight + + itests-controller + pom + + 3.0 + + + base-features-it + + diff --git a/opendaylight/commons/opendaylight/pom.xml b/opendaylight/commons/opendaylight/pom.xml index cddff45191..5ce5840da8 100644 --- a/opendaylight/commons/opendaylight/pom.xml +++ b/opendaylight/commons/opendaylight/pom.xml @@ -95,6 +95,7 @@ 0.5.2-SNAPSHOT 0.5.2-SNAPSHOT 0.4.2-SNAPSHOT + 1.0.0-SNAPSHOT 0.4.2-SNAPSHOT 0.4.2-SNAPSHOT 0.0.2-SNAPSHOT @@ -133,6 +134,7 @@ 1.4.2-SNAPSHOT 2013.08.27.4-SNAPSHOT 0.0.2-SNAPSHOT + 4.0.0 1.1.6 1.1.6 1.0-alpha-2 @@ -179,6 +181,7 @@ 0.4.2-SNAPSHOT 0.4.2-SNAPSHOT 0.4.2-SNAPSHOT + 1.0.0-SNAPSHOT 0.4.2-SNAPSHOT 1.2.0 1.2.2 @@ -1597,6 +1600,11 @@ util ${yangtools.version} + + org.opendaylight.yangtools + yang-data-composite-node + ${yangtools.version} + diff --git a/opendaylight/distribution/opendaylight/pom.xml b/opendaylight/distribution/opendaylight/pom.xml index 4d0770f8cb..7c3289adb5 100644 --- a/opendaylight/distribution/opendaylight/pom.xml +++ b/opendaylight/distribution/opendaylight/pom.xml @@ -1234,6 +1234,10 @@ org.opendaylight.yangtools yang-parser-impl + + org.opendaylight.yangtools + yang-data-composite-node + org.opendaylight.yangtools.model diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java b/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java new file mode 100644 index 0000000000..5d11be4826 --- /dev/null +++ b/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java @@ -0,0 +1,9 @@ +package org.opendaylight.controller.hosttracker; + +import java.util.List; + +public interface IHostTrackerShell{ + + public List dumpPendingArpReqList(); + public List dumpFailedArpReqList(); +} \ No newline at end of file diff --git a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java b/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java index 825b2453aa..7e527712b1 100644 --- a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java +++ b/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java @@ -16,6 +16,7 @@ import java.util.Set; import org.apache.felix.dm.Component; import org.opendaylight.controller.clustering.services.ICacheUpdateAware; import org.opendaylight.controller.clustering.services.IClusterContainerServices; +import org.opendaylight.controller.hosttracker.IHostTrackerShell; import org.opendaylight.controller.hosttracker.IfHostListener; import org.opendaylight.controller.hosttracker.IfIptoHost; import org.opendaylight.controller.hosttracker.IfNewHostNotify; @@ -78,6 +79,7 @@ public class Activator extends ComponentActivatorAbstractBase { IInventoryListener.class.getName(), IfIptoHost.class.getName(), IfHostListener.class.getName(), + IHostTrackerShell.class.getName(), ITopologyManagerAware.class.getName(), ICacheUpdateAware.class.getName() }, props); diff --git a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java b/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java index ce49b599e1..f728b35bbf 100644 --- a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java +++ b/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java @@ -39,6 +39,7 @@ import org.opendaylight.controller.clustering.services.IClusterContainerServices import org.opendaylight.controller.clustering.services.IClusterServices; import org.opendaylight.controller.hosttracker.HostIdFactory; import org.opendaylight.controller.hosttracker.IHostId; +import org.opendaylight.controller.hosttracker.IHostTrackerShell; import org.opendaylight.controller.hosttracker.IPHostId; import org.opendaylight.controller.hosttracker.IPMacHostId; import org.opendaylight.controller.hosttracker.IfHostListener; @@ -100,7 +101,7 @@ import org.slf4j.LoggerFactory; * */ -public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAware, IInventoryListener, +public class HostTracker implements IfIptoHost, IfHostListener, IHostTrackerShell, ISwitchManagerAware, IInventoryListener, ITopologyManagerAware, ICacheUpdateAware, CommandProvider { static final String ACTIVE_HOST_CACHE = "hosttracker.ActiveHosts"; static final String INACTIVE_HOST_CACHE = "hosttracker.InactiveHosts"; @@ -1618,4 +1619,24 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw IHostId id = HostIdFactory.create(addr, null); return getHostNetworkHierarchy(id); } + + @Override + public List dumpPendingArpReqList() { + ARPPending arphost; + List arpReq = new ArrayList(); + for (Entry entry : ARPPendingList.entrySet()) { + arpReq.add(entry.getValue().getHostId().toString()); + } + return arpReq; + } + + @Override + public List dumpFailedArpReqList() { + ARPPending arphost; + List arpReq = new ArrayList(); + for (Entry entry : failedARPReqList.entrySet()) { + arpReq.add(entry.getValue().getHostId().toString()); + } + return arpReq; + } } diff --git a/opendaylight/hosttracker/shell/pom.xml b/opendaylight/hosttracker/shell/pom.xml new file mode 100644 index 0000000000..3f73303180 --- /dev/null +++ b/opendaylight/hosttracker/shell/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + org.opendaylight.controller + commons.opendaylight + 1.4.2-SNAPSHOT + ../../commons/opendaylight + + hosttracker.shell + ${hosttracker.shell.version} + bundle + + + junit + junit + + + org.apache.karaf.shell + org.apache.karaf.shell.console + 3.0.0 + + + org.mockito + mockito-all + + + org.opendaylight.controller + hosttracker.implementation + ${hosttracker.implementation.version} + + + + + + + org.apache.felix + maven-bundle-plugin + ${bundle.plugin.version} + + + org.apache.felix.service.command, + org.apache.karaf.shell.commands, + org.apache.karaf.shell.console, + * + + + + + + + diff --git a/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java b/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java new file mode 100644 index 0000000000..ec9971f3c8 --- /dev/null +++ b/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java @@ -0,0 +1,28 @@ +package org.opendaylight.controller.hosttracker.shell; +/** +* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. +* +* This program and the accompanying materials are made available under the +* terms of the Eclipse Public License v1.0 which accompanies this distribution, +* and is available at http://www.eclipse.org/legal/epl-v10.html +*/ + +import org.apache.felix.gogo.commands.Command; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.opendaylight.controller.hosttracker.IHostTrackerShell; + +@Command(scope = "hosttracker", name = "dumpFailedARPReqList", description="Display the dump failed ARPReqList") +public class DumpFailedARPReqList extends OsgiCommandSupport{ + + private IHostTrackerShell hostTracker; + + @Override + protected Object doExecute() throws Exception { + System.out.print(hostTracker.dumpFailedArpReqList()); + return null; + } + + public void setHostTracker(IHostTrackerShell hostTracker){ + this.hostTracker = hostTracker; + } +} diff --git a/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java b/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java new file mode 100644 index 0000000000..7f52a55bd1 --- /dev/null +++ b/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java @@ -0,0 +1,28 @@ +package org.opendaylight.controller.hosttracker.shell; +/** +* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. +* +* This program and the accompanying materials are made available under the +* terms of the Eclipse Public License v1.0 which accompanies this distribution, +* and is available at http://www.eclipse.org/legal/epl-v10.html +*/ + +import org.apache.felix.gogo.commands.Command; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.opendaylight.controller.hosttracker.IHostTrackerShell; + +@Command(scope = "hosttracker", name = "dumpPendingARPReqList", description="Display the dump pending ARPReqList") +public class DumpPendingARPReqList extends OsgiCommandSupport{ + + private IHostTrackerShell hostTracker; + + @Override + protected Object doExecute() throws Exception { + System.out.print(hostTracker.dumpPendingArpReqList()); + return null; + } + + public void setHostTracker(IHostTrackerShell hostTracker){ + this.hostTracker = hostTracker; + } +} \ No newline at end of file diff --git a/opendaylight/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 0000000000..ba79b5d8c5 --- /dev/null +++ b/opendaylight/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/opendaylight/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java b/opendaylight/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java new file mode 100644 index 0000000000..a0a5a2e610 --- /dev/null +++ b/opendaylight/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java @@ -0,0 +1,47 @@ +package org.opendaylight.controller.hosttracker.shell; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import org.opendaylight.controller.hosttracker.IHostTrackerShell; + +public class HostTrackerShellTest { + + private final long COMMAND_TIMEOUT = 1000; + private IHostTrackerShell hostTracker; + + @Test + public void testDumpPendingARPReqList() throws Exception { + DumpPendingARPReqList dumpPendTest = new DumpPendingARPReqList(); + hostTracker = mock(IHostTrackerShell.class); + List failedList = new ArrayList(Arrays.asList("a", "b", "c")); + when(hostTracker.dumpPendingArpReqList()).thenReturn(failedList); + dumpPendTest.setHostTracker(hostTracker); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + System.setOut(new PrintStream(baos)); + dumpPendTest.doExecute(); + //Assert.assertTrue(true); + Assert.assertEquals("[a, b, c]", baos.toString()); + } + + @Test + public void testDumpFailedARPReqList() throws Exception { + DumpFailedARPReqList dumpFailTest = new DumpFailedARPReqList(); + hostTracker = mock(IHostTrackerShell.class); + List failedList = new ArrayList(Arrays.asList("a", "b", "c")); + when(hostTracker.dumpFailedArpReqList()).thenReturn(failedList); + dumpFailTest.setHostTracker(hostTracker); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + System.setOut(new PrintStream(baos)); + dumpFailTest.doExecute(); + //Assert.assertTrue(true); + Assert.assertEquals("[a, b, c]", baos.toString()); + } +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java index 641ec0582c..aa100df9d0 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java @@ -11,10 +11,12 @@ package org.opendaylight.controller.cluster.example; import akka.actor.ActorRef; import akka.actor.Props; import akka.japi.Creator; +import com.google.common.base.Optional; import org.opendaylight.controller.cluster.example.messages.KeyValue; import org.opendaylight.controller.cluster.example.messages.KeyValueSaved; import org.opendaylight.controller.cluster.example.messages.PrintRole; import org.opendaylight.controller.cluster.example.messages.PrintState; +import org.opendaylight.controller.cluster.raft.ConfigParams; import org.opendaylight.controller.cluster.raft.RaftActor; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; @@ -31,15 +33,17 @@ public class ExampleActor extends RaftActor { private long persistIdentifier = 1; - public ExampleActor(String id, Map peerAddresses) { - super(id, peerAddresses); + public ExampleActor(String id, Map peerAddresses, + Optional configParams) { + super(id, peerAddresses, configParams); } - public static Props props(final String id, final Map peerAddresses){ + public static Props props(final String id, final Map peerAddresses, + final Optional configParams){ return Props.create(new Creator(){ @Override public ExampleActor create() throws Exception { - return new ExampleActor(id, peerAddresses); + return new ExampleActor(id, peerAddresses, configParams); } }); } @@ -56,10 +60,12 @@ public class ExampleActor extends RaftActor { } } else if (message instanceof PrintState) { - LOG.debug("State of the node:"+getId() + " has = "+state.size() + " entries"); + LOG.debug("State of the node:{} has entries={}, {}", + getId(), state.size(), getReplicatedLogState()); } else if (message instanceof PrintRole) { - LOG.debug(getId() + " = " + getRaftState()); + LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),getPeers()); + } else { super.onReceiveCommand(message); } @@ -83,6 +89,7 @@ public class ExampleActor extends RaftActor { @Override protected void applySnapshot(Object snapshot) { state.clear(); state.putAll((HashMap) snapshot); + LOG.debug("Snapshot applied to state :" + ((HashMap) snapshot).size()); } @Override public void onReceiveRecover(Object message) { diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleConfigParamsImpl.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleConfigParamsImpl.java new file mode 100644 index 0000000000..d11377dbcb --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleConfigParamsImpl.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.example; + +import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl; + +/** + * Implementation of ConfigParams for Example + */ +public class ExampleConfigParamsImpl extends DefaultConfigParamsImpl { + @Override + public long getSnapshotBatchCount() { + return 50; + } +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/Main.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/Main.java index a148ed4009..0e5d643a64 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/Main.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/Main.java @@ -11,7 +11,9 @@ package org.opendaylight.controller.cluster.example; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; +import com.google.common.base.Optional; import org.opendaylight.controller.cluster.example.messages.KeyValue; +import org.opendaylight.controller.cluster.raft.ConfigParams; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -34,15 +36,15 @@ public class Main { public static void main(String[] args) throws Exception{ ActorRef example1Actor = actorSystem.actorOf(ExampleActor.props("example-1", - withoutPeer("example-1")), "example-1"); + withoutPeer("example-1"), Optional.absent()), "example-1"); ActorRef example2Actor = actorSystem.actorOf(ExampleActor.props("example-2", - withoutPeer("example-2")), "example-2"); + withoutPeer("example-2"), Optional.absent()), "example-2"); ActorRef example3Actor = actorSystem.actorOf(ExampleActor.props("example-3", - withoutPeer("example-3")), "example-3"); + withoutPeer("example-3"), Optional.absent()), "example-3"); List examples = Arrays.asList(example1Actor, example2Actor, example3Actor); @@ -74,7 +76,8 @@ public class Main { String actorName = "example-" + i; examples.add(i - 1, actorSystem.actorOf(ExampleActor.props(actorName, - withoutPeer(actorName)), actorName)); + withoutPeer(actorName), Optional.absent()), + actorName)); System.out.println("Created actor : " + actorName); continue; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java index c2d0b3a6b7..fd6e192bf0 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java @@ -2,8 +2,10 @@ package org.opendaylight.controller.cluster.example; import akka.actor.ActorRef; import akka.actor.ActorSystem; +import com.google.common.base.Optional; import org.opendaylight.controller.cluster.example.messages.PrintRole; import org.opendaylight.controller.cluster.example.messages.PrintState; +import org.opendaylight.controller.cluster.raft.ConfigParams; import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer; import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer; @@ -11,14 +13,13 @@ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; -import java.util.Random; import java.util.concurrent.ConcurrentHashMap; /** * This is a test driver for testing akka-raft implementation * Its uses ExampleActors and threads to push content(key-vals) to these actors * Each ExampleActor can have one or more ClientActors. Each ClientActor spawns - * a thread and starts push logs to the actor its assignged to. + * a thread and starts push logs to the actor its assigned to. */ public class TestDriver { @@ -26,7 +27,9 @@ public class TestDriver { private static Map allPeers = new HashMap<>(); private static Map clientActorRefs = new HashMap(); private static Map actorRefs = new HashMap(); - private static LogGenerator logGenerator = new LogGenerator();; + private static LogGenerator logGenerator = new LogGenerator(); + private int nameCounter = 0; + private static ConfigParams configParams = new ExampleConfigParamsImpl(); /** * Create nodes, add clients and start logging. @@ -35,6 +38,7 @@ public class TestDriver { * createNodes:{num} * addNodes:{num} * stopNode:{nodeName} + * reinstateNode:{nodeName} * addClients:{num} * addClientsToNode:{nodeName, num} * startLogging @@ -83,6 +87,10 @@ public class TestDriver { String[] arr = command.split(":"); td.stopNode(arr[1]); + } else if (command.startsWith("reinstateNode")) { + String[] arr = command.split(":"); + td.reinstateNode(arr[1]); + } else if (command.startsWith("startLogging")) { td.startAllLogging(); @@ -106,15 +114,19 @@ public class TestDriver { } } + public static ActorRef createExampleActor(String name) { + return actorSystem.actorOf(ExampleActor.props(name, withoutPeer(name), + Optional.of(configParams)), name); + } + public void createNodes(int num) { for (int i=0; i < num; i++) { - int rand = getUnusedRandom(num); - allPeers.put("example-"+rand, "akka://default/user/example-"+rand); + nameCounter = nameCounter + 1; + allPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter); } for (String s : allPeers.keySet()) { - ActorRef exampleActor = actorSystem.actorOf( - ExampleActor.props(s, withoutPeer(s)), s); + ActorRef exampleActor = createExampleActor(s); actorRefs.put(s, exampleActor); System.out.println("Created node:"+s); @@ -125,15 +137,14 @@ public class TestDriver { public void addNodes(int num) { Map newPeers = new HashMap<>(); for (int i=0; i < num; i++) { - int rand = getUnusedRandom(num); - newPeers.put("example-"+rand, "akka://default/user/example-"+rand); - allPeers.put("example-"+rand, "akka://default/user/example-"+rand); + nameCounter = nameCounter + 1; + newPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter); + allPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter); } Map newActorRefs = new HashMap(num); for (Map.Entry entry : newPeers.entrySet()) { - ActorRef exampleActor = actorSystem.actorOf( - ExampleActor.props(entry.getKey(), withoutPeer(entry.getKey())), entry.getKey()); + ActorRef exampleActor = createExampleActor(entry.getKey()); newActorRefs.put(entry.getKey(), exampleActor); //now also add these new nodes as peers from the previous nodes @@ -165,7 +176,7 @@ public class TestDriver { public void addClientsToNode(String actorName, int num) { ActorRef actorRef = actorRefs.get(actorName); for (int i=0; i < num; i++) { - String clientName = "client-" + i + "-" + actorRef; + String clientName = "client-" + i + "-" + actorName; clientActorRefs.put(clientName, actorSystem.actorOf(ClientActor.props(actorRef), clientName)); System.out.println("Added client-node:" + clientName); @@ -174,11 +185,13 @@ public class TestDriver { public void stopNode(String actorName) { ActorRef actorRef = actorRefs.get(actorName); - String clientName = "client-"+actorName; - if(clientActorRefs.containsKey(clientName)) { - actorSystem.stop(clientActorRefs.get(clientName)); - clientActorRefs.remove(clientName); + + for (Map.Entry entry : clientActorRefs.entrySet()) { + if (entry.getKey().endsWith(actorName)) { + actorSystem.stop(entry.getValue()); + } } + actorSystem.stop(actorRef); actorRefs.remove(actorName); @@ -187,7 +200,21 @@ public class TestDriver { } allPeers.remove(actorName); + } + public void reinstateNode(String actorName) { + String address = "akka://default/user/"+actorName; + allPeers.put(actorName, address); + + ActorRef exampleActor = createExampleActor(actorName); + + for (ActorRef actor : actorRefs.values()) { + actor.tell(new AddRaftPeer(actorName, address), null); + } + + actorRefs.put(actorName, exampleActor); + + addClientsToNode(actorName, 1); } public void startAllLogging() { @@ -232,14 +259,6 @@ public class TestDriver { return null; } - private int getUnusedRandom(int num) { - int rand = -1; - do { - rand = (new Random()).nextInt(num * num); - } while (allPeers.keySet().contains("example-"+rand)); - - return rand; - } private static Map withoutPeer(String peerId) { Map without = new ConcurrentHashMap<>(allPeers); diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImpl.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImpl.java new file mode 100644 index 0000000000..24bfa3de21 --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImpl.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.raft; + +import java.util.ArrayList; +import java.util.List; + +/** + * Abstract class handling the mapping of + * logical LogEntry Index and the physical list index. + */ +public abstract class AbstractReplicatedLogImpl implements ReplicatedLog { + + protected final List journal; + protected final Object snapshot; + protected long snapshotIndex = -1; + protected long snapshotTerm = -1; + + public AbstractReplicatedLogImpl(Object state, long snapshotIndex, + long snapshotTerm, List unAppliedEntries) { + this.snapshot = state; + this.snapshotIndex = snapshotIndex; + this.snapshotTerm = snapshotTerm; + this.journal = new ArrayList<>(unAppliedEntries); + } + + + public AbstractReplicatedLogImpl() { + this.snapshot = null; + this.journal = new ArrayList<>(); + } + + protected int adjustedIndex(long logEntryIndex) { + if(snapshotIndex < 0){ + return (int) logEntryIndex; + } + return (int) (logEntryIndex - (snapshotIndex + 1)); + } + + @Override + public ReplicatedLogEntry get(long logEntryIndex) { + int adjustedIndex = adjustedIndex(logEntryIndex); + + if (adjustedIndex < 0 || adjustedIndex >= journal.size()) { + // physical index should be less than list size and >= 0 + return null; + } + + return journal.get(adjustedIndex); + } + + @Override + public ReplicatedLogEntry last() { + if (journal.isEmpty()) { + return null; + } + // get the last entry directly from the physical index + return journal.get(journal.size() - 1); + } + + @Override + public long lastIndex() { + if (journal.isEmpty()) { + // it can happen that after snapshot, all the entries of the + // journal are trimmed till lastApplied, so lastIndex = snapshotIndex + return snapshotIndex; + } + return last().getIndex(); + } + + @Override + public long lastTerm() { + if (journal.isEmpty()) { + // it can happen that after snapshot, all the entries of the + // journal are trimmed till lastApplied, so lastTerm = snapshotTerm + return snapshotTerm; + } + return last().getTerm(); + } + + @Override + public void removeFrom(long logEntryIndex) { + int adjustedIndex = adjustedIndex(logEntryIndex); + if (adjustedIndex < 0 || adjustedIndex >= journal.size()) { + // physical index should be less than list size and >= 0 + return; + } + journal.subList(adjustedIndex , journal.size()).clear(); + } + + @Override + public void append(ReplicatedLogEntry replicatedLogEntry) { + journal.add(replicatedLogEntry); + } + + @Override + public List getFrom(long logEntryIndex) { + int adjustedIndex = adjustedIndex(logEntryIndex); + int size = journal.size(); + List entries = new ArrayList<>(100); + if (adjustedIndex >= 0 && adjustedIndex < size) { + // physical index should be less than list size and >= 0 + entries.addAll(journal.subList(adjustedIndex, size)); + } + return entries; + } + + @Override + public long size() { + return journal.size(); + } + + @Override + public boolean isPresent(long logEntryIndex) { + if (logEntryIndex > lastIndex()) { + // if the request logical index is less than the last present in the list + return false; + } + int adjustedIndex = adjustedIndex(logEntryIndex); + return (adjustedIndex >= 0); + } + + @Override + public boolean isInSnapshot(long logEntryIndex) { + return logEntryIndex <= snapshotIndex; + } + + @Override + public Object getSnapshot() { + return snapshot; + } + + @Override + public long getSnapshotIndex() { + return snapshotIndex; + } + + @Override + public long getSnapshotTerm() { + return snapshotTerm; + } + + @Override + public abstract void appendAndPersist(ReplicatedLogEntry replicatedLogEntry); + + @Override + public abstract void removeFromAndPersist(long index); +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ConfigParams.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ConfigParams.java new file mode 100644 index 0000000000..4c6434aec4 --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ConfigParams.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.raft; + +import scala.concurrent.duration.FiniteDuration; + +/** + * Configuration Parameter interface for configuring the Raft consensus system + *

+ * Any component using this implementation might want to provide an implementation of + * this interface to configure + * + * A default implementation will be used if none is provided. + * + * @author Kamal Rameshan + */ +public interface ConfigParams { + /** + * The minimum number of entries to be present in the in-memory Raft log + * for a snapshot to be taken + * + * @return long + */ + public long getSnapshotBatchCount(); + + /** + * The interval at which a heart beat message will be sent to the remote + * RaftActor + * + * @return FiniteDuration + */ + public FiniteDuration getHeartBeatInterval(); + + /** + * The interval in which a new election would get triggered if no leader is found + * + * Normally its set to atleast twice the heart beat interval + * + * @return FiniteDuration + */ + public FiniteDuration getElectionTimeOutInterval(); + + /** + * The maximum election time variance. The election is scheduled using both + * the Election Timeout and Variance + * + * @return int + */ + public int getElectionTimeVariance(); +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/DefaultConfigParamsImpl.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/DefaultConfigParamsImpl.java new file mode 100644 index 0000000000..c633337226 --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/DefaultConfigParamsImpl.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.raft; + +import scala.concurrent.duration.FiniteDuration; + +import java.util.concurrent.TimeUnit; + +/** + * Default implementation of the ConfigParams + * + * If no implementation is provided for ConfigParams, then this will be used. + */ +public class DefaultConfigParamsImpl implements ConfigParams { + + private static final int SNAPSHOT_BATCH_COUNT = 100000; + + /** + * The maximum election time variance + */ + private static final int ELECTION_TIME_MAX_VARIANCE = 100; + + + /** + * The interval at which a heart beat message will be sent to the remote + * RaftActor + *

+ * Since this is set to 100 milliseconds the Election timeout should be + * at least 200 milliseconds + */ + protected static final FiniteDuration HEART_BEAT_INTERVAL = + new FiniteDuration(100, TimeUnit.MILLISECONDS); + + + @Override + public long getSnapshotBatchCount() { + return SNAPSHOT_BATCH_COUNT; + } + + @Override + public FiniteDuration getHeartBeatInterval() { + return HEART_BEAT_INTERVAL; + } + + + @Override + public FiniteDuration getElectionTimeOutInterval() { + // returns 2 times the heart beat interval + return HEART_BEAT_INTERVAL.$times(2); + } + + @Override + public int getElectionTimeVariance() { + return ELECTION_TIME_MAX_VARIANCE; + } +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java index b8e9653bc5..70b85b4627 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java @@ -22,6 +22,7 @@ import akka.persistence.UntypedPersistentActor; import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot; import org.opendaylight.controller.cluster.raft.base.messages.ApplyState; import org.opendaylight.controller.cluster.raft.base.messages.Replicate; +import com.google.common.base.Optional; import org.opendaylight.controller.cluster.raft.behaviors.Candidate; import org.opendaylight.controller.cluster.raft.behaviors.Follower; import org.opendaylight.controller.cluster.raft.behaviors.Leader; @@ -33,7 +34,6 @@ import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; import java.io.Serializable; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -100,14 +100,22 @@ public abstract class RaftActor extends UntypedPersistentActor { public RaftActor(String id, Map peerAddresses) { + this(id, peerAddresses, Optional.absent()); + } + + public RaftActor(String id, Map peerAddresses, + Optional configParams) { + context = new RaftActorContextImpl(this.getSelf(), - this.getContext(), - id, new ElectionTermImpl(), - -1, -1, replicatedLog, peerAddresses, LOG); + this.getContext(), id, new ElectionTermImpl(), + -1, -1, replicatedLog, peerAddresses, + (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()), + LOG); } @Override public void onReceiveRecover(Object message) { if (message instanceof SnapshotOffer) { + LOG.debug("SnapshotOffer called.."); SnapshotOffer offer = (SnapshotOffer) message; Snapshot snapshot = (Snapshot) offer.snapshot(); @@ -116,6 +124,13 @@ public abstract class RaftActor extends UntypedPersistentActor { // when we need to install it on a peer replicatedLog = new ReplicatedLogImpl(snapshot); + context.setReplicatedLog(replicatedLog); + + LOG.debug("Applied snapshot to replicatedLog. " + + "snapshotIndex={}, snapshotTerm={}, journal-size={}", + replicatedLog.snapshotIndex, replicatedLog.snapshotTerm, + replicatedLog.size()); + // Apply the snapshot to the actors state applySnapshot(snapshot.getState()); @@ -127,7 +142,11 @@ public abstract class RaftActor extends UntypedPersistentActor { context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), ((UpdateElectionTerm) message).getVotedFor()); } else if (message instanceof RecoveryCompleted) { LOG.debug( - "Last index in log : " + replicatedLog.lastIndex()); + "RecoveryCompleted - Switching actor to Follower - " + + "Last index in log:{}, snapshotIndex={}, snapshotTerm={}, " + + "journal-size={}", + replicatedLog.lastIndex(), replicatedLog.snapshotIndex, + replicatedLog.snapshotTerm, replicatedLog.size()); currentBehavior = switchBehavior(RaftState.Follower); } } @@ -191,6 +210,15 @@ public abstract class RaftActor extends UntypedPersistentActor { } } + public java.util.Set getPeers() { + return context.getPeerAddresses().keySet(); + } + + protected String getReplicatedLogState() { + return "snapshotIndex=" + context.getReplicatedLog().getSnapshotIndex() + + ", snapshotTerm=" + context.getReplicatedLog().getSnapshotTerm() + + ", im-mem journal size=" + context.getReplicatedLog().size(); + } /** @@ -343,85 +371,33 @@ public abstract class RaftActor extends UntypedPersistentActor { } private void trimPersistentData(long sequenceNumber) { - // Trim snapshots + // Trim akka snapshots // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied // For now guessing that it is ANDed. deleteSnapshots(new SnapshotSelectionCriteria( - sequenceNumber - 100000, 43200000)); + sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000)); - // Trim journal + // Trim akka journal deleteMessages(sequenceNumber); } - private class ReplicatedLogImpl implements ReplicatedLog { - private final List journal; - private final Object snapshot; - private long snapshotIndex = -1; - private long snapshotTerm = -1; + private class ReplicatedLogImpl extends AbstractReplicatedLogImpl { public ReplicatedLogImpl(Snapshot snapshot) { - this.snapshot = snapshot.getState(); - this.snapshotIndex = snapshot.getLastAppliedIndex(); - this.snapshotTerm = snapshot.getLastAppliedTerm(); - - this.journal = new ArrayList<>(snapshot.getUnAppliedEntries()); + super(snapshot.getState(), + snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(), + snapshot.getUnAppliedEntries()); } public ReplicatedLogImpl() { - this.snapshot = null; - this.journal = new ArrayList<>(); + super(); } - @Override public ReplicatedLogEntry get(long index) { - int adjustedIndex = adjustedIndex(index); + @Override public void removeFromAndPersist(long logEntryIndex) { + int adjustedIndex = adjustedIndex(logEntryIndex); - if (adjustedIndex < 0 || adjustedIndex >= journal.size()) { - return null; - } - - return journal.get(adjustedIndex); - } - - @Override public ReplicatedLogEntry last() { - if (journal.size() == 0) { - return null; - } - return get(journal.size() - 1); - } - - @Override public long lastIndex() { - if (journal.size() == 0) { - return -1; - } - - return last().getIndex(); - } - - @Override public long lastTerm() { - if (journal.size() == 0) { - return -1; - } - - return last().getTerm(); - } - - - @Override public void removeFrom(long index) { - int adjustedIndex = adjustedIndex(index); - - if (adjustedIndex < 0 || adjustedIndex >= journal.size()) { - return; - } - - journal.subList(adjustedIndex , journal.size()).clear(); - } - - - @Override public void removeFromAndPersist(long index) { - int adjustedIndex = adjustedIndex(index); - - if (adjustedIndex < 0 || adjustedIndex >= journal.size()) { + if (adjustedIndex < 0) { return; } @@ -435,29 +411,6 @@ public abstract class RaftActor extends UntypedPersistentActor { //FIXME : Doing nothing for now } }); - - - } - - @Override public void append( - final ReplicatedLogEntry replicatedLogEntry) { - journal.add(replicatedLogEntry); - } - - @Override public List getFrom(long index) { - int adjustedIndex = adjustedIndex(index); - - List entries = new ArrayList<>(100); - if (adjustedIndex < 0 || adjustedIndex >= journal.size()) { - return entries; - } - - - for (int i = adjustedIndex; - i < journal.size(); i++) { - entries.add(journal.get(i)); - } - return entries; } @Override public void appendAndPersist( @@ -482,20 +435,42 @@ public abstract class RaftActor extends UntypedPersistentActor { new Procedure() { public void apply(ReplicatedLogEntry evt) throws Exception { // FIXME : Tentatively create a snapshot every hundred thousand entries. To be tuned. - if (size() > 100000) { - ReplicatedLogEntry lastAppliedEntry = - get(context.getLastApplied()); + if (journal.size() > context.getConfigParams().getSnapshotBatchCount()) { + LOG.info("Initiating Snapshot Capture.."); long lastAppliedIndex = -1; long lastAppliedTerm = -1; + + ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied()); if (lastAppliedEntry != null) { lastAppliedIndex = lastAppliedEntry.getIndex(); lastAppliedTerm = lastAppliedEntry.getTerm(); } - saveSnapshot(Snapshot.create(createSnapshot(), + LOG.debug("Snapshot Capture logSize: {}", journal.size()); + LOG.debug("Snapshot Capture lastApplied:{} ", context.getLastApplied()); + LOG.debug("Snapshot Capture lastAppliedIndex:{}", lastAppliedIndex); + LOG.debug("Snapshot Capture lastAppliedTerm:{}", lastAppliedTerm); + + // create a snapshot object from the state provided and save it + // when snapshot is saved async, SaveSnapshotSuccess is raised. + Snapshot sn = Snapshot.create(createSnapshot(), getFrom(context.getLastApplied() + 1), lastIndex(), lastTerm(), lastAppliedIndex, - lastAppliedTerm)); + lastAppliedTerm); + saveSnapshot(sn); + + LOG.info("Persisting of snapshot done:{}", sn.getLogMessage()); + + //be greedy and remove entries from in-mem journal which are in the snapshot + // and update snapshotIndex and snapshotTerm without waiting for the success, + // TODO: damage-recovery to be done on failure + journal.subList(0, (int) (lastAppliedIndex - snapshotIndex)).clear(); + snapshotIndex = lastAppliedIndex; + snapshotTerm = lastAppliedTerm; + + LOG.info("Removed in-memory snapshotted entries, " + + "adjusted snaphsotIndex:{}" + + "and term:{}", snapshotIndex, lastAppliedTerm); } // Send message for replication if (clientActor != null) { @@ -509,46 +484,8 @@ public abstract class RaftActor extends UntypedPersistentActor { ); } - @Override public long size() { - return journal.size() + snapshotIndex + 1; - } - - @Override public boolean isPresent(long index) { - int adjustedIndex = adjustedIndex(index); - - if (adjustedIndex < 0 || adjustedIndex >= journal.size()) { - return false; - } - return true; - } - - @Override public boolean isInSnapshot(long index) { - return index <= snapshotIndex; - } - - @Override public Object getSnapshot() { - return snapshot; - } - - @Override public long getSnapshotIndex() { - return snapshotIndex; - } - - @Override public long getSnapshotTerm() { - return snapshotTerm; - } - - private int adjustedIndex(long index) { - if(snapshotIndex < 0){ - return (int) index; - } - return (int) (index - snapshotIndex); - } } - - - private static class DeleteEntries implements Serializable { private final int fromIndex; @@ -609,6 +546,17 @@ public abstract class RaftActor extends UntypedPersistentActor { public long getLastAppliedTerm() { return lastAppliedTerm; } + + public String getLogMessage() { + StringBuilder sb = new StringBuilder(); + return sb.append("Snapshot={") + .append("lastTerm:" + this.getLastTerm() + ", ") + .append("LastAppliedIndex:" + this.getLastAppliedIndex() + ", ") + .append("LastAppliedTerm:" + this.getLastAppliedTerm() + ", ") + .append("UnAppliedEntries size:" + this.getUnAppliedEntries().size() + "}") + .toString(); + + } } private class ElectionTermImpl implements ElectionTerm { diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContext.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContext.java index ae9431a43a..0eb4b73779 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContext.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContext.java @@ -85,6 +85,12 @@ public interface RaftActorContext { */ void setLastApplied(long lastApplied); + /** + * + * @param replicatedLog + */ + public void setReplicatedLog(ReplicatedLog replicatedLog); + /** * @return A representation of the log */ @@ -155,4 +161,9 @@ public interface RaftActorContext { * @param peerAddress */ void setPeerAddress(String peerId, String peerAddress); + + /** + * @return ConfigParams + */ + public ConfigParams getConfigParams(); } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContextImpl.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContextImpl.java index 833c8a9e8a..25da37105c 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContextImpl.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContextImpl.java @@ -19,7 +19,7 @@ import java.util.Map; import static com.google.common.base.Preconditions.checkState; -public class RaftActorContextImpl implements RaftActorContext{ +public class RaftActorContextImpl implements RaftActorContext { private final ActorRef actor; @@ -33,16 +33,20 @@ public class RaftActorContextImpl implements RaftActorContext{ private long lastApplied; - private final ReplicatedLog replicatedLog; + private ReplicatedLog replicatedLog; private final Map peerAddresses; private final LoggingAdapter LOG; + private final ConfigParams configParams; + public RaftActorContextImpl(ActorRef actor, UntypedActorContext context, String id, ElectionTerm termInformation, long commitIndex, - long lastApplied, ReplicatedLog replicatedLog, Map peerAddresses, LoggingAdapter logger) { + long lastApplied, ReplicatedLog replicatedLog, + Map peerAddresses, ConfigParams configParams, + LoggingAdapter logger) { this.actor = actor; this.context = context; this.id = id; @@ -51,6 +55,7 @@ public class RaftActorContextImpl implements RaftActorContext{ this.lastApplied = lastApplied; this.replicatedLog = replicatedLog; this.peerAddresses = peerAddresses; + this.configParams = configParams; this.LOG = logger; } @@ -90,6 +95,10 @@ public class RaftActorContextImpl implements RaftActorContext{ this.lastApplied = lastApplied; } + @Override public void setReplicatedLog(ReplicatedLog replicatedLog) { + this.replicatedLog = replicatedLog; + } + @Override public ReplicatedLog getReplicatedLog() { return replicatedLog; } @@ -110,6 +119,10 @@ public class RaftActorContextImpl implements RaftActorContext{ return peerAddresses.get(peerId); } + @Override public ConfigParams getConfigParams() { + return configParams; + } + @Override public void addToPeers(String name, String address) { peerAddresses.put(name, address); } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java index f7281bb8e3..0a553b40fd 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java @@ -43,27 +43,6 @@ public abstract class AbstractRaftActorBehavior implements RaftActorBehavior { */ protected final RaftActorContext context; - /** - * The maximum election time variance - */ - private static final int ELECTION_TIME_MAX_VARIANCE = 100; - - /** - * The interval at which a heart beat message will be sent to the remote - * RaftActor - *

- * Since this is set to 100 milliseconds the Election timeout should be - * at least 200 milliseconds - */ - protected static final FiniteDuration HEART_BEAT_INTERVAL = - new FiniteDuration(100, TimeUnit.MILLISECONDS); - - /** - * The interval in which a new election would get triggered if no leader is found - */ - private static final long ELECTION_TIME_INTERVAL = - HEART_BEAT_INTERVAL.toMillis() * 2; - /** * */ @@ -208,9 +187,9 @@ public abstract class AbstractRaftActorBehavior implements RaftActorBehavior { * @return */ protected FiniteDuration electionDuration() { - long variance = new Random().nextInt(ELECTION_TIME_MAX_VARIANCE); - return new FiniteDuration(ELECTION_TIME_INTERVAL + variance, - TimeUnit.MILLISECONDS); + long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance()); + return context.getConfigParams().getElectionTimeOutInterval().$plus( + new FiniteDuration(variance, TimeUnit.MILLISECONDS)); } /** diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Follower.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Follower.java index db62dfc2ac..c8cd41dfa1 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Follower.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Follower.java @@ -126,15 +126,10 @@ public class Follower extends AbstractRaftActorBehavior { int addEntriesFrom = 0; if (context.getReplicatedLog().size() > 0) { - // Find the entry up until which the one that is not in the - // follower's log - for (int i = 0; - i < appendEntries.getEntries() - .size(); i++, addEntriesFrom++) { - ReplicatedLogEntry matchEntry = - appendEntries.getEntries().get(i); - ReplicatedLogEntry newEntry = context.getReplicatedLog() - .get(matchEntry.getIndex()); + // Find the entry up until which the one that is not in the follower's log + for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) { + ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i); + ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex()); if (newEntry == null) { //newEntry not found in the log diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java index 53e47c2f84..2a44e8b7a5 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java @@ -112,8 +112,8 @@ public class Leader extends AbstractRaftActorBehavior { scheduleHeartBeat(new FiniteDuration(0, TimeUnit.SECONDS)); scheduleInstallSnapshotCheck( - new FiniteDuration(HEART_BEAT_INTERVAL.length() * 1000, - HEART_BEAT_INTERVAL.unit()) + new FiniteDuration(context.getConfigParams().getHeartBeatInterval().length() * 1000, + context.getConfigParams().getHeartBeatInterval().unit()) ); } @@ -241,7 +241,7 @@ public class Leader extends AbstractRaftActorBehavior { (InstallSnapshotReply) message); } } finally { - scheduleHeartBeat(HEART_BEAT_INTERVAL); + scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval()); } return super.handleMessage(sender, message); diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImplTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImplTest.java new file mode 100644 index 0000000000..ae8e525233 --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImplTest.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.raft; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload; +import static org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockReplicatedLogEntry; +/** +* +*/ +public class AbstractReplicatedLogImplTest { + + private MockAbstractReplicatedLogImpl replicatedLogImpl; + + @Before + public void setUp() { + replicatedLogImpl = new MockAbstractReplicatedLogImpl(); + } + + @After + public void tearDown() { + replicatedLogImpl.journal.clear(); + replicatedLogImpl.setSnapshotIndex(-1); + replicatedLogImpl.setSnapshotTerm(-1); + replicatedLogImpl = null; + } + + @Test + public void testIndexOperations() { + // create a set of initial entries in the in-memory log + replicatedLogImpl.append(new MockReplicatedLogEntry(1, 0, new MockPayload("A"))); + replicatedLogImpl.append(new MockReplicatedLogEntry(1, 1, new MockPayload("B"))); + replicatedLogImpl.append(new MockReplicatedLogEntry(1, 2, new MockPayload("C"))); + replicatedLogImpl.append(new MockReplicatedLogEntry(2, 3, new MockPayload("D"))); + + // check if the values returned are correct, with snapshotIndex = -1 + assertEquals("B", replicatedLogImpl.get(1).getData().toString()); + assertEquals("D", replicatedLogImpl.last().getData().toString()); + assertEquals(3, replicatedLogImpl.lastIndex()); + assertEquals(2, replicatedLogImpl.lastTerm()); + assertEquals(2, replicatedLogImpl.getFrom(2).size()); + assertEquals(4, replicatedLogImpl.size()); + assertTrue(replicatedLogImpl.isPresent(2)); + assertFalse(replicatedLogImpl.isPresent(4)); + assertFalse(replicatedLogImpl.isInSnapshot(2)); + + // now create a snapshot of 3 entries, with 1 unapplied entry left in the log + // It removes the entries which have made it to snapshot + // and updates the snapshot index and term + Map state = takeSnapshot(3); + + // check the values after the snapshot. + // each index value passed in the test is the logical index (log entry index) + // which gets mapped to the list's physical index + assertEquals("D", replicatedLogImpl.get(3).getData().toString()); + assertEquals("D", replicatedLogImpl.last().getData().toString()); + assertNull(replicatedLogImpl.get(1)); + assertEquals(3, replicatedLogImpl.lastIndex()); + assertEquals(2, replicatedLogImpl.lastTerm()); + assertEquals(0, replicatedLogImpl.getFrom(2).size()); + assertEquals(1, replicatedLogImpl.size()); + assertFalse(replicatedLogImpl.isPresent(2)); + assertTrue(replicatedLogImpl.isPresent(3)); + assertFalse(replicatedLogImpl.isPresent(4)); + assertTrue(replicatedLogImpl.isInSnapshot(2)); + + // append few more entries + replicatedLogImpl.append(new MockReplicatedLogEntry(2, 4, new MockPayload("E"))); + replicatedLogImpl.append(new MockReplicatedLogEntry(2, 5, new MockPayload("F"))); + replicatedLogImpl.append(new MockReplicatedLogEntry(3, 6, new MockPayload("G"))); + replicatedLogImpl.append(new MockReplicatedLogEntry(3, 7, new MockPayload("H"))); + + // check their values as well + assertEquals(5, replicatedLogImpl.size()); + assertEquals("D", replicatedLogImpl.get(3).getData().toString()); + assertEquals("E", replicatedLogImpl.get(4).getData().toString()); + assertEquals("H", replicatedLogImpl.last().getData().toString()); + assertEquals(3, replicatedLogImpl.lastTerm()); + assertEquals(7, replicatedLogImpl.lastIndex()); + assertTrue(replicatedLogImpl.isPresent(7)); + assertFalse(replicatedLogImpl.isInSnapshot(7)); + assertEquals(1, replicatedLogImpl.getFrom(7).size()); + assertEquals(2, replicatedLogImpl.getFrom(6).size()); + + // take a second snapshot with 5 entries with 0 unapplied entries left in the log + state = takeSnapshot(5); + + assertEquals(0, replicatedLogImpl.size()); + assertNull(replicatedLogImpl.last()); + assertNull(replicatedLogImpl.get(7)); + assertNull(replicatedLogImpl.get(1)); + assertFalse(replicatedLogImpl.isPresent(7)); + assertTrue(replicatedLogImpl.isInSnapshot(7)); + assertEquals(0, replicatedLogImpl.getFrom(7).size()); + assertEquals(0, replicatedLogImpl.getFrom(6).size()); + + } + + // create a snapshot for test + public Map takeSnapshot(int numEntries) { + Map map = new HashMap(numEntries); + List entries = replicatedLogImpl.getEntriesTill(numEntries); + for (ReplicatedLogEntry entry : entries) { + map.put(entry.getIndex(), entry.getData().toString()); + } + + int term = (int) replicatedLogImpl.lastTerm(); + int lastIndex = (int) entries.get(entries.size() - 1).getIndex(); + entries.clear(); + replicatedLogImpl.setSnapshotTerm(term); + replicatedLogImpl.setSnapshotIndex(lastIndex); + + return map; + + } + class MockAbstractReplicatedLogImpl extends AbstractReplicatedLogImpl { + @Override + public void appendAndPersist(ReplicatedLogEntry replicatedLogEntry) { + } + + @Override + public void removeFromAndPersist(long index) { + } + + public void setSnapshotIndex(long snapshotIndex) { + this.snapshotIndex = snapshotIndex; + } + + public void setSnapshotTerm(long snapshotTerm) { + this.snapshotTerm = snapshotTerm; + } + + public List getEntriesTill(int index) { + return journal.subList(0, index); + } + } +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java index 2e200cba27..aa50fa7442 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java @@ -177,7 +177,10 @@ public class MockRaftActorContext implements RaftActorContext { this.peerAddresses = peerAddresses; } - + @Override + public ConfigParams getConfigParams() { + return new DefaultConfigParamsImpl(); + } public static class SimpleReplicatedLog implements ReplicatedLog { private final List log = new ArrayList<>(); diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/README-FIRST b/opendaylight/md-sal/sal-protocolbuffer-encoding/README-FIRST index d0be2cbcbb..4791979c17 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/README-FIRST +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/README-FIRST @@ -24,5 +24,9 @@ machine 6. !!!WARNING!!! - never edit the generated sources files of protocol buffer -7. !!!NOTE!!! if you are planning to add new .proto file option java_package should begin with +7. !!!IMPORTANT!!! if you are planning to add new .proto file option java_package should begin with org.opendaylight.controller.protobuff.messages to properly exclude from sonar. + +8. !!!IMPORTANT!!! for any new .proto file added you need to create corresponding version-compatibility-serialized-data + serialized test file under test/resources and a test case for one message in your .proto file. + Please follow the instruction in readme.txt in that folder diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeToNormalizedNodeBuilder.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeToNormalizedNodeBuilder.java index ce120809d7..03d632b61f 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeToNormalizedNodeBuilder.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeToNormalizedNodeBuilder.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node; import com.google.common.base.Preconditions; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeValueCodec.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeValueCodec.java index 7b6f5c46d2..14ca75b9f3 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeValueCodec.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeValueCodec.java @@ -1,9 +1,11 @@ /* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * */ package org.opendaylight.controller.cluster.datastore.node; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java index fc4b3954c5..17bdb36e56 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node; import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToProtocolBufferNode.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToProtocolBufferNode.java index fb15312665..68d3c590e0 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToProtocolBufferNode.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToProtocolBufferNode.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node; import com.google.common.base.Preconditions; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java index a34307f6b4..e2c4c35893 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.common.QName; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java index 175e242a11..ea3986f4a0 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java index 9edec1e230..1b9c70867d 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.common.QName; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java index 4bfcf391dd..6d3a26ad77 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.common.QName; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java index b2ec5644d4..2d434fffcf 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java index e82a23d37f..31e6521a28 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import com.google.common.base.Preconditions; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java index 4ccc7076ff..0083b00403 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import com.google.common.base.Preconditions; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java index 7735a12a8b..d370eb2deb 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java index 69b00bef92..9e85ccb9ab 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java index ba81836ea8..cf5174319d 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; public class PathUtils { diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java index 8dba0563bd..002b9ff82e 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.common.QName; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java index d9a067b573..90f5cf3396 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.util; import com.google.common.base.Preconditions; @@ -44,13 +54,6 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the terms of the Eclipse - * Public License v1.0 which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ /* * * EncoderDecoderUtil helps in wrapping the NormalizedNode into a SimpleNormalizedNode diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java index 5b459e7e7c..55cb341086 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.util; import org.opendaylight.controller.cluster.datastore.node.utils.NodeIdentifierFactory; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/mdsal/CompositeModificationPayload.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/mdsal/CompositeModificationPayload.java index 87b246bd7e..99f4751875 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/mdsal/CompositeModificationPayload.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/mdsal/CompositeModificationPayload.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: CompositeModificationPayload.proto diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java index ac0701a6d8..49cb1ead9c 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: Cohort.proto @@ -652,7 +662,7 @@ public final class ThreePhaseCommitCohortMessages { public final boolean isInitialized() { if (!hasCanCommit()) { - + return false; } return true; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java index 81e5b462cc..f88b66bcd3 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: Common.proto @@ -179,7 +189,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -195,7 +205,7 @@ public final class NormalizedNodeMessages { getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; @@ -222,7 +232,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -238,7 +248,7 @@ public final class NormalizedNodeMessages { getValueBytes() { java.lang.Object ref = value_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; @@ -265,7 +275,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -281,7 +291,7 @@ public final class NormalizedNodeMessages { getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); type_ = b; @@ -541,7 +551,7 @@ public final class NormalizedNodeMessages { public final boolean isInitialized() { if (!hasName()) { - + return false; } return true; @@ -595,7 +605,7 @@ public final class NormalizedNodeMessages { getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; @@ -669,7 +679,7 @@ public final class NormalizedNodeMessages { getValueBytes() { java.lang.Object ref = value_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; @@ -743,7 +753,7 @@ public final class NormalizedNodeMessages { getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); type_ = b; @@ -930,7 +940,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -946,7 +956,7 @@ public final class NormalizedNodeMessages { getValueBytes() { java.lang.Object ref = value_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; @@ -1168,7 +1178,7 @@ public final class NormalizedNodeMessages { public final boolean isInitialized() { if (!hasValue()) { - + return false; } return true; @@ -1222,7 +1232,7 @@ public final class NormalizedNodeMessages { getValueBytes() { java.lang.Object ref = value_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; @@ -1341,7 +1351,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4; */ - java.util.List + java.util.List getAttributesList(); /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4; @@ -1354,7 +1364,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4; */ - java.util.List + java.util.List getAttributesOrBuilderList(); /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4; @@ -1504,7 +1514,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -1520,7 +1530,7 @@ public final class NormalizedNodeMessages { getValueBytes() { java.lang.Object ref = value_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; @@ -1555,7 +1565,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -1575,7 +1585,7 @@ public final class NormalizedNodeMessages { getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); type_ = b; @@ -1619,7 +1629,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4; */ - public java.util.List + public java.util.List getAttributesOrBuilderList() { return attributes_; } @@ -1948,7 +1958,7 @@ public final class NormalizedNodeMessages { attributesBuilder_ = null; attributes_ = other.attributes_; bitField0_ = (bitField0_ & ~0x00000008); - attributesBuilder_ = + attributesBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getAttributesFieldBuilder() : null; } else { @@ -1962,18 +1972,18 @@ public final class NormalizedNodeMessages { public final boolean isInitialized() { if (!hasValue()) { - + return false; } if (hasNodeType()) { if (!getNodeType().isInitialized()) { - + return false; } } for (int i = 0; i < getAttributesCount(); i++) { if (!getAttributes(i).isInitialized()) { - + return false; } } @@ -2028,7 +2038,7 @@ public final class NormalizedNodeMessages { getValueBytes() { java.lang.Object ref = value_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; @@ -2114,7 +2124,7 @@ public final class NormalizedNodeMessages { getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); type_ = b; @@ -2275,7 +2285,7 @@ public final class NormalizedNodeMessages { * optional .org.opendaylight.controller.mdsal.QName nodeType = 3; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder> getNodeTypeFieldBuilder() { if (nodeTypeBuilder_ == null) { nodeTypeBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -2483,7 +2493,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4; */ - public java.util.List + public java.util.List getAttributesOrBuilderList() { if (attributesBuilder_ != null) { return attributesBuilder_.getMessageOrBuilderList(); @@ -2509,12 +2519,12 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4; */ - public java.util.List + public java.util.List getAttributesBuilderList() { return getAttributesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> getAttributesFieldBuilder() { if (attributesBuilder_ == null) { attributesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< @@ -2546,7 +2556,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1; */ - java.util.List + java.util.List getArgumentsList(); /** * repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1; @@ -2559,7 +2569,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1; */ - java.util.List + java.util.List getArgumentsOrBuilderList(); /** * repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1; @@ -2680,7 +2690,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1; */ - public java.util.List + public java.util.List getArgumentsOrBuilderList() { return arguments_; } @@ -2933,7 +2943,7 @@ public final class NormalizedNodeMessages { argumentsBuilder_ = null; arguments_ = other.arguments_; bitField0_ = (bitField0_ & ~0x00000001); - argumentsBuilder_ = + argumentsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getArgumentsFieldBuilder() : null; } else { @@ -2948,7 +2958,7 @@ public final class NormalizedNodeMessages { public final boolean isInitialized() { for (int i = 0; i < getArgumentsCount(); i++) { if (!getArguments(i).isInitialized()) { - + return false; } } @@ -3169,7 +3179,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1; */ - public java.util.List + public java.util.List getArgumentsOrBuilderList() { if (argumentsBuilder_ != null) { return argumentsBuilder_.getMessageOrBuilderList(); @@ -3195,12 +3205,12 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1; */ - public java.util.List + public java.util.List getArgumentsBuilderList() { return getArgumentsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder> getArgumentsFieldBuilder() { if (argumentsBuilder_ == null) { argumentsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< @@ -3262,7 +3272,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3; */ - java.util.List + java.util.List getAttributesList(); /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3; @@ -3275,7 +3285,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3; */ - java.util.List + java.util.List getAttributesOrBuilderList(); /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3; @@ -3287,7 +3297,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Node child = 4; */ - java.util.List + java.util.List getChildList(); /** * repeated .org.opendaylight.controller.mdsal.Node child = 4; @@ -3300,7 +3310,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Node child = 4; */ - java.util.List + java.util.List getChildOrBuilderList(); /** * repeated .org.opendaylight.controller.mdsal.Node child = 4; @@ -3546,7 +3556,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -3562,7 +3572,7 @@ public final class NormalizedNodeMessages { getPathBytes() { java.lang.Object ref = path_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); path_ = b; @@ -3589,7 +3599,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -3605,7 +3615,7 @@ public final class NormalizedNodeMessages { getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); type_ = b; @@ -3627,7 +3637,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3; */ - public java.util.List + public java.util.List getAttributesOrBuilderList() { return attributes_; } @@ -3663,7 +3673,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Node child = 4; */ - public java.util.List + public java.util.List getChildOrBuilderList() { return child_; } @@ -3704,7 +3714,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -3720,7 +3730,7 @@ public final class NormalizedNodeMessages { getValueBytes() { java.lang.Object ref = value_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; @@ -3747,7 +3757,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -3763,7 +3773,7 @@ public final class NormalizedNodeMessages { getValueTypeBytes() { java.lang.Object ref = valueType_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); valueType_ = b; @@ -4202,7 +4212,7 @@ public final class NormalizedNodeMessages { attributesBuilder_ = null; attributes_ = other.attributes_; bitField0_ = (bitField0_ & ~0x00000004); - attributesBuilder_ = + attributesBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getAttributesFieldBuilder() : null; } else { @@ -4228,7 +4238,7 @@ public final class NormalizedNodeMessages { childBuilder_ = null; child_ = other.child_; bitField0_ = (bitField0_ & ~0x00000008); - childBuilder_ = + childBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getChildFieldBuilder() : null; } else { @@ -4266,19 +4276,19 @@ public final class NormalizedNodeMessages { public final boolean isInitialized() { for (int i = 0; i < getAttributesCount(); i++) { if (!getAttributes(i).isInitialized()) { - + return false; } } for (int i = 0; i < getChildCount(); i++) { if (!getChild(i).isInitialized()) { - + return false; } } if (hasInstanceIdentifierValue()) { if (!getInstanceIdentifierValue().isInitialized()) { - + return false; } } @@ -4333,7 +4343,7 @@ public final class NormalizedNodeMessages { getPathBytes() { java.lang.Object ref = path_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); path_ = b; @@ -4407,7 +4417,7 @@ public final class NormalizedNodeMessages { getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); type_ = b; @@ -4647,7 +4657,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3; */ - public java.util.List + public java.util.List getAttributesOrBuilderList() { if (attributesBuilder_ != null) { return attributesBuilder_.getMessageOrBuilderList(); @@ -4673,12 +4683,12 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3; */ - public java.util.List + public java.util.List getAttributesBuilderList() { return getAttributesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> getAttributesFieldBuilder() { if (attributesBuilder_ == null) { attributesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< @@ -4887,7 +4897,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Node child = 4; */ - public java.util.List + public java.util.List getChildOrBuilderList() { if (childBuilder_ != null) { return childBuilder_.getMessageOrBuilderList(); @@ -4913,12 +4923,12 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.Node child = 4; */ - public java.util.List + public java.util.List getChildBuilderList() { return getChildFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getChildFieldBuilder() { if (childBuilder_ == null) { childBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< @@ -4961,7 +4971,7 @@ public final class NormalizedNodeMessages { getValueBytes() { java.lang.Object ref = value_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; @@ -5035,7 +5045,7 @@ public final class NormalizedNodeMessages { getValueTypeBytes() { java.lang.Object ref = valueType_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); valueType_ = b; @@ -5277,7 +5287,7 @@ public final class NormalizedNodeMessages { * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 8; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getInstanceIdentifierValueFieldBuilder() { if (instanceIdentifierValueBuilder_ == null) { instanceIdentifierValueBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -5459,7 +5469,7 @@ public final class NormalizedNodeMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -5475,7 +5485,7 @@ public final class NormalizedNodeMessages { getParentPathBytes() { java.lang.Object ref = parentPath_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); parentPath_ = b; @@ -5751,12 +5761,12 @@ public final class NormalizedNodeMessages { public final boolean isInitialized() { if (!hasParentPath()) { - + return false; } if (hasNormalizedNode()) { if (!getNormalizedNode().isInitialized()) { - + return false; } } @@ -5811,7 +5821,7 @@ public final class NormalizedNodeMessages { getParentPathBytes() { java.lang.Object ref = parentPath_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); parentPath_ = b; @@ -5960,7 +5970,7 @@ public final class NormalizedNodeMessages { * optional .org.opendaylight.controller.mdsal.Node normalizedNode = 2; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getNormalizedNodeFieldBuilder() { if (normalizedNodeBuilder_ == null) { normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -6431,16 +6441,16 @@ public final class NormalizedNodeMessages { public final boolean isInitialized() { if (!hasInstanceIdentifierPath()) { - + return false; } if (!getInstanceIdentifierPath().isInitialized()) { - + return false; } if (hasNormalizedNode()) { if (!getNormalizedNode().isInitialized()) { - + return false; } } @@ -6570,7 +6580,7 @@ public final class NormalizedNodeMessages { * required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPath = 1; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getInstanceIdentifierPathFieldBuilder() { if (instanceIdentifierPathBuilder_ == null) { instanceIdentifierPathBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -6687,7 +6697,7 @@ public final class NormalizedNodeMessages { * optional .org.opendaylight.controller.mdsal.Node normalizedNode = 2; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getNormalizedNodeFieldBuilder() { if (normalizedNodeBuilder_ == null) { normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -6718,7 +6728,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1; */ - java.util.List + java.util.List getMapEntriesList(); /** * repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1; @@ -6731,7 +6741,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1; */ - java.util.List + java.util.List getMapEntriesOrBuilderList(); /** * repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1; @@ -6852,7 +6862,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1; */ - public java.util.List + public java.util.List getMapEntriesOrBuilderList() { return mapEntries_; } @@ -7105,7 +7115,7 @@ public final class NormalizedNodeMessages { mapEntriesBuilder_ = null; mapEntries_ = other.mapEntries_; bitField0_ = (bitField0_ & ~0x00000001); - mapEntriesBuilder_ = + mapEntriesBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getMapEntriesFieldBuilder() : null; } else { @@ -7120,7 +7130,7 @@ public final class NormalizedNodeMessages { public final boolean isInitialized() { for (int i = 0; i < getMapEntriesCount(); i++) { if (!getMapEntries(i).isInitialized()) { - + return false; } } @@ -7341,7 +7351,7 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1; */ - public java.util.List + public java.util.List getMapEntriesOrBuilderList() { if (mapEntriesBuilder_ != null) { return mapEntriesBuilder_.getMessageOrBuilderList(); @@ -7367,12 +7377,12 @@ public final class NormalizedNodeMessages { /** * repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1; */ - public java.util.List + public java.util.List getMapEntriesBuilderList() { return getMapEntriesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder> getMapEntriesFieldBuilder() { if (mapEntriesBuilder_ == null) { mapEntriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/SimpleNormalizedNodeMessage.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/SimpleNormalizedNodeMessage.java index 29e54571d3..7cee40df7a 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/SimpleNormalizedNodeMessage.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/SimpleNormalizedNodeMessage.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: SimpleNormalizedNode.proto @@ -159,7 +169,7 @@ public final class SimpleNormalizedNodeMessage { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -175,7 +185,7 @@ public final class SimpleNormalizedNodeMessage { getNodeIdentifierBytes() { java.lang.Object ref = nodeIdentifier_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); nodeIdentifier_ = b; @@ -202,7 +212,7 @@ public final class SimpleNormalizedNodeMessage { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -218,7 +228,7 @@ public final class SimpleNormalizedNodeMessage { getXmlStringBytes() { java.lang.Object ref = xmlString_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); xmlString_ = b; @@ -463,11 +473,11 @@ public final class SimpleNormalizedNodeMessage { public final boolean isInitialized() { if (!hasNodeIdentifier()) { - + return false; } if (!hasXmlString()) { - + return false; } return true; @@ -521,7 +531,7 @@ public final class SimpleNormalizedNodeMessage { getNodeIdentifierBytes() { java.lang.Object ref = nodeIdentifier_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); nodeIdentifier_ = b; @@ -595,7 +605,7 @@ public final class SimpleNormalizedNodeMessage { getXmlStringBytes() { java.lang.Object ref = xmlString_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); xmlString_ = b; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessages.java index 2018834768..1a98112073 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessages.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessages.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: DataChangeListener.proto @@ -85,7 +95,7 @@ public final class DataChangeListenerMessages { /** * repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6; */ - java.util.List + java.util.List getRemovedPathsList(); /** * repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6; @@ -98,7 +108,7 @@ public final class DataChangeListenerMessages { /** * repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6; */ - java.util.List + java.util.List getRemovedPathsOrBuilderList(); /** * repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6; @@ -395,7 +405,7 @@ public final class DataChangeListenerMessages { /** * repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6; */ - public java.util.List + public java.util.List getRemovedPathsOrBuilderList() { return removedPaths_; } @@ -810,7 +820,7 @@ public final class DataChangeListenerMessages { removedPathsBuilder_ = null; removedPaths_ = other.removedPaths_; bitField0_ = (bitField0_ & ~0x00000020); - removedPathsBuilder_ = + removedPathsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRemovedPathsFieldBuilder() : null; } else { @@ -825,37 +835,37 @@ public final class DataChangeListenerMessages { public final boolean isInitialized() { if (hasOriginalSubTree()) { if (!getOriginalSubTree().isInitialized()) { - + return false; } } if (hasUpdatedSubTree()) { if (!getUpdatedSubTree().isInitialized()) { - + return false; } } if (hasOriginalData()) { if (!getOriginalData().isInitialized()) { - + return false; } } if (hasUpdatedData()) { if (!getUpdatedData().isInitialized()) { - + return false; } } if (hasCreatedData()) { if (!getCreatedData().isInitialized()) { - + return false; } } for (int i = 0; i < getRemovedPathsCount(); i++) { if (!getRemovedPaths(i).isInitialized()) { - + return false; } } @@ -985,7 +995,7 @@ public final class DataChangeListenerMessages { * optional .org.opendaylight.controller.mdsal.Node originalSubTree = 1; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getOriginalSubTreeFieldBuilder() { if (originalSubTreeBuilder_ == null) { originalSubTreeBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -1102,7 +1112,7 @@ public final class DataChangeListenerMessages { * optional .org.opendaylight.controller.mdsal.Node updatedSubTree = 2; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getUpdatedSubTreeFieldBuilder() { if (updatedSubTreeBuilder_ == null) { updatedSubTreeBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -1219,7 +1229,7 @@ public final class DataChangeListenerMessages { * optional .org.opendaylight.controller.mdsal.NodeMap originalData = 3; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> getOriginalDataFieldBuilder() { if (originalDataBuilder_ == null) { originalDataBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -1336,7 +1346,7 @@ public final class DataChangeListenerMessages { * optional .org.opendaylight.controller.mdsal.NodeMap updatedData = 4; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> getUpdatedDataFieldBuilder() { if (updatedDataBuilder_ == null) { updatedDataBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -1453,7 +1463,7 @@ public final class DataChangeListenerMessages { * optional .org.opendaylight.controller.mdsal.NodeMap createdData = 5; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> getCreatedDataFieldBuilder() { if (createdDataBuilder_ == null) { createdDataBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -1661,7 +1671,7 @@ public final class DataChangeListenerMessages { /** * repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6; */ - public java.util.List + public java.util.List getRemovedPathsOrBuilderList() { if (removedPathsBuilder_ != null) { return removedPathsBuilder_.getMessageOrBuilderList(); @@ -1687,12 +1697,12 @@ public final class DataChangeListenerMessages { /** * repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6; */ - public java.util.List + public java.util.List getRemovedPathsBuilderList() { return getRemovedPathsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getRemovedPathsFieldBuilder() { if (removedPathsBuilder_ == null) { removedPathsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessages.java index eaa90012db..088630aa32 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessages.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessages.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: Persistent.proto @@ -193,7 +203,7 @@ public final class PersistentMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -209,7 +219,7 @@ public final class PersistentMessages { getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); type_ = b; @@ -541,20 +551,20 @@ public final class PersistentMessages { public final boolean isInitialized() { if (!hasType()) { - + return false; } if (!hasPath()) { - + return false; } if (!getPath().isInitialized()) { - + return false; } if (hasData()) { if (!getData().isInitialized()) { - + return false; } } @@ -609,7 +619,7 @@ public final class PersistentMessages { getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); type_ = b; @@ -758,7 +768,7 @@ public final class PersistentMessages { * required .org.opendaylight.controller.mdsal.InstanceIdentifier path = 2; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getPathFieldBuilder() { if (pathBuilder_ == null) { pathBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -875,7 +885,7 @@ public final class PersistentMessages { * optional .org.opendaylight.controller.mdsal.Node data = 3; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getDataFieldBuilder() { if (dataBuilder_ == null) { dataBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -906,7 +916,7 @@ public final class PersistentMessages { /** * repeated .org.opendaylight.controller.mdsal.Modification modification = 1; */ - java.util.List + java.util.List getModificationList(); /** * repeated .org.opendaylight.controller.mdsal.Modification modification = 1; @@ -919,7 +929,7 @@ public final class PersistentMessages { /** * repeated .org.opendaylight.controller.mdsal.Modification modification = 1; */ - java.util.List + java.util.List getModificationOrBuilderList(); /** * repeated .org.opendaylight.controller.mdsal.Modification modification = 1; @@ -1040,7 +1050,7 @@ public final class PersistentMessages { /** * repeated .org.opendaylight.controller.mdsal.Modification modification = 1; */ - public java.util.List + public java.util.List getModificationOrBuilderList() { return modification_; } @@ -1293,7 +1303,7 @@ public final class PersistentMessages { modificationBuilder_ = null; modification_ = other.modification_; bitField0_ = (bitField0_ & ~0x00000001); - modificationBuilder_ = + modificationBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getModificationFieldBuilder() : null; } else { @@ -1308,7 +1318,7 @@ public final class PersistentMessages { public final boolean isInitialized() { for (int i = 0; i < getModificationCount(); i++) { if (!getModification(i).isInitialized()) { - + return false; } } @@ -1529,7 +1539,7 @@ public final class PersistentMessages { /** * repeated .org.opendaylight.controller.mdsal.Modification modification = 1; */ - public java.util.List + public java.util.List getModificationOrBuilderList() { if (modificationBuilder_ != null) { return modificationBuilder_.getMessageOrBuilderList(); @@ -1555,12 +1565,12 @@ public final class PersistentMessages { /** * repeated .org.opendaylight.controller.mdsal.Modification modification = 1; */ - public java.util.List + public java.util.List getModificationBuilderList() { return getModificationFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder> + org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder> getModificationFieldBuilder() { if (modificationBuilder_ == null) { modificationBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessages.java index e06dd0d429..0f439d8c7c 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessages.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessages.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: ListenerRegistration.proto @@ -837,7 +847,7 @@ public final class ListenerRegistrationMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -853,7 +863,7 @@ public final class ListenerRegistrationMessages { getDataChangeListenerActorPathBytes() { java.lang.Object ref = dataChangeListenerActorPath_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); dataChangeListenerActorPath_ = b; @@ -1146,19 +1156,19 @@ public final class ListenerRegistrationMessages { public final boolean isInitialized() { if (!hasInstanceIdentifierPath()) { - + return false; } if (!hasDataChangeListenerActorPath()) { - + return false; } if (!hasDataChangeScope()) { - + return false; } if (!getInstanceIdentifierPath().isInitialized()) { - + return false; } return true; @@ -1287,7 +1297,7 @@ public final class ListenerRegistrationMessages { * required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPath = 1; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getInstanceIdentifierPathFieldBuilder() { if (instanceIdentifierPathBuilder_ == null) { instanceIdentifierPathBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -1329,7 +1339,7 @@ public final class ListenerRegistrationMessages { getDataChangeListenerActorPathBytes() { java.lang.Object ref = dataChangeListenerActorPath_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); dataChangeListenerActorPath_ = b; @@ -1556,7 +1566,7 @@ public final class ListenerRegistrationMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -1572,7 +1582,7 @@ public final class ListenerRegistrationMessages { getListenerRegistrationPathBytes() { java.lang.Object ref = listenerRegistrationPath_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); listenerRegistrationPath_ = b; @@ -1801,7 +1811,7 @@ public final class ListenerRegistrationMessages { public final boolean isInitialized() { if (!hasListenerRegistrationPath()) { - + return false; } return true; @@ -1855,7 +1865,7 @@ public final class ListenerRegistrationMessages { getListenerRegistrationPathBytes() { java.lang.Object ref = listenerRegistrationPath_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); listenerRegistrationPath_ = b; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessages.java index 7c2a47e1b0..7141863591 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessages.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessages.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: ShardManager.proto @@ -139,7 +149,7 @@ public final class ShardManagerMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -155,7 +165,7 @@ public final class ShardManagerMessages { getShardNameBytes() { java.lang.Object ref = shardName_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); shardName_ = b; @@ -377,7 +387,7 @@ public final class ShardManagerMessages { public final boolean isInitialized() { if (!hasShardName()) { - + return false; } return true; @@ -431,7 +441,7 @@ public final class ShardManagerMessages { getShardNameBytes() { java.lang.Object ref = shardName_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); shardName_ = b; @@ -618,7 +628,7 @@ public final class ShardManagerMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -634,7 +644,7 @@ public final class ShardManagerMessages { getPrimaryPathBytes() { java.lang.Object ref = primaryPath_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); primaryPath_ = b; @@ -856,7 +866,7 @@ public final class ShardManagerMessages { public final boolean isInitialized() { if (!hasPrimaryPath()) { - + return false; } return true; @@ -910,7 +920,7 @@ public final class ShardManagerMessages { getPrimaryPathBytes() { java.lang.Object ref = primaryPath_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); primaryPath_ = b; @@ -1097,7 +1107,7 @@ public final class ShardManagerMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -1113,7 +1123,7 @@ public final class ShardManagerMessages { getShardNameBytes() { java.lang.Object ref = shardName_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); shardName_ = b; @@ -1335,7 +1345,7 @@ public final class ShardManagerMessages { public final boolean isInitialized() { if (!hasShardName()) { - + return false; } return true; @@ -1389,7 +1399,7 @@ public final class ShardManagerMessages { getShardNameBytes() { java.lang.Object ref = shardName_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); shardName_ = b; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessages.java index 3f354ba40e..68bf325336 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessages.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessages.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: ShardTransactionChain.proto @@ -1066,7 +1076,7 @@ public final class ShardTransactionChainMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -1082,7 +1092,7 @@ public final class ShardTransactionChainMessages { getTransactionChainPathBytes() { java.lang.Object ref = transactionChainPath_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionChainPath_ = b; @@ -1304,7 +1314,7 @@ public final class ShardTransactionChainMessages { public final boolean isInitialized() { if (!hasTransactionChainPath()) { - + return false; } return true; @@ -1358,7 +1368,7 @@ public final class ShardTransactionChainMessages { getTransactionChainPathBytes() { java.lang.Object ref = transactionChainPath_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionChainPath_ = b; diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java index ee2c70423e..52411f322b 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + // Generated by the protocol buffer compiler. DO NOT EDIT! // source: ShardTransaction.proto @@ -757,7 +767,7 @@ public final class ShardTransactionMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -773,7 +783,7 @@ public final class ShardTransactionMessages { getTransactionIdBytes() { java.lang.Object ref = transactionId_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionId_ = b; @@ -995,7 +1005,7 @@ public final class ShardTransactionMessages { public final boolean isInitialized() { if (!hasTransactionId()) { - + return false; } return true; @@ -1049,7 +1059,7 @@ public final class ShardTransactionMessages { getTransactionIdBytes() { java.lang.Object ref = transactionId_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionId_ = b; @@ -1256,7 +1266,7 @@ public final class ShardTransactionMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -1272,7 +1282,7 @@ public final class ShardTransactionMessages { getTransactionActorPathBytes() { java.lang.Object ref = transactionActorPath_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionActorPath_ = b; @@ -1299,7 +1309,7 @@ public final class ShardTransactionMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -1315,7 +1325,7 @@ public final class ShardTransactionMessages { getTransactionIdBytes() { java.lang.Object ref = transactionId_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionId_ = b; @@ -1560,11 +1570,11 @@ public final class ShardTransactionMessages { public final boolean isInitialized() { if (!hasTransactionActorPath()) { - + return false; } if (!hasTransactionId()) { - + return false; } return true; @@ -1618,7 +1628,7 @@ public final class ShardTransactionMessages { getTransactionActorPathBytes() { java.lang.Object ref = transactionActorPath_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionActorPath_ = b; @@ -1692,7 +1702,7 @@ public final class ShardTransactionMessages { getTransactionIdBytes() { java.lang.Object ref = transactionId_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); transactionId_ = b; @@ -2188,7 +2198,7 @@ public final class ShardTransactionMessages { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -2204,7 +2214,7 @@ public final class ShardTransactionMessages { getActorPathBytes() { java.lang.Object ref = actorPath_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); actorPath_ = b; @@ -2426,7 +2436,7 @@ public final class ShardTransactionMessages { public final boolean isInitialized() { if (!hasActorPath()) { - + return false; } return true; @@ -2480,7 +2490,7 @@ public final class ShardTransactionMessages { getActorPathBytes() { java.lang.Object ref = actorPath_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); actorPath_ = b; @@ -2902,11 +2912,11 @@ public final class ShardTransactionMessages { public final boolean isInitialized() { if (!hasInstanceIdentifierPathArguments()) { - + return false; } if (!getInstanceIdentifierPathArguments().isInitialized()) { - + return false; } return true; @@ -3035,7 +3045,7 @@ public final class ShardTransactionMessages { * required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getInstanceIdentifierPathArgumentsFieldBuilder() { if (instanceIdentifierPathArgumentsBuilder_ == null) { instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -3734,11 +3744,11 @@ public final class ShardTransactionMessages { public final boolean isInitialized() { if (!hasInstanceIdentifierPathArguments()) { - + return false; } if (!getInstanceIdentifierPathArguments().isInitialized()) { - + return false; } return true; @@ -3867,7 +3877,7 @@ public final class ShardTransactionMessages { * required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getInstanceIdentifierPathArgumentsFieldBuilder() { if (instanceIdentifierPathArgumentsBuilder_ == null) { instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -4256,7 +4266,7 @@ public final class ShardTransactionMessages { public final boolean isInitialized() { if (hasNormalizedNode()) { if (!getNormalizedNode().isInitialized()) { - + return false; } } @@ -4386,7 +4396,7 @@ public final class ShardTransactionMessages { * optional .org.opendaylight.controller.mdsal.Node normalizedNode = 1; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getNormalizedNodeFieldBuilder() { if (normalizedNodeBuilder_ == null) { normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -4859,19 +4869,19 @@ public final class ShardTransactionMessages { public final boolean isInitialized() { if (!hasInstanceIdentifierPathArguments()) { - + return false; } if (!hasNormalizedNode()) { - + return false; } if (!getInstanceIdentifierPathArguments().isInitialized()) { - + return false; } if (!getNormalizedNode().isInitialized()) { - + return false; } return true; @@ -5000,7 +5010,7 @@ public final class ShardTransactionMessages { * required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getInstanceIdentifierPathArgumentsFieldBuilder() { if (instanceIdentifierPathArgumentsBuilder_ == null) { instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -5117,7 +5127,7 @@ public final class ShardTransactionMessages { * required .org.opendaylight.controller.mdsal.Node normalizedNode = 2; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getNormalizedNodeFieldBuilder() { if (normalizedNodeBuilder_ == null) { normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -5899,19 +5909,19 @@ public final class ShardTransactionMessages { public final boolean isInitialized() { if (!hasInstanceIdentifierPathArguments()) { - + return false; } if (!hasNormalizedNode()) { - + return false; } if (!getInstanceIdentifierPathArguments().isInitialized()) { - + return false; } if (!getNormalizedNode().isInitialized()) { - + return false; } return true; @@ -6040,7 +6050,7 @@ public final class ShardTransactionMessages { * required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> getInstanceIdentifierPathArgumentsFieldBuilder() { if (instanceIdentifierPathArgumentsBuilder_ == null) { instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder< @@ -6157,7 +6167,7 @@ public final class ShardTransactionMessages { * required .org.opendaylight.controller.mdsal.Node normalizedNode = 2; */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> getNormalizedNodeFieldBuilder() { if (normalizedNodeBuilder_ == null) { normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder< diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java index 4ccbc97f35..1b85d46fc6 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java @@ -1,9 +1,11 @@ /* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * */ package org.opendaylight.controller.cluster.datastore.node; @@ -15,9 +17,9 @@ import org.opendaylight.controller.cluster.datastore.node.utils.NodeIdentifierFa import org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeGetter; import org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeNavigator; import org.opendaylight.controller.cluster.datastore.util.TestModel; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Container; import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -32,127 +34,147 @@ public class NormalizedNodeToNodeCodecTest { - private SchemaContext schemaContext; + private SchemaContext schemaContext; - @Before - public void setUp(){ - schemaContext = TestModel.createTestContext(); - assertNotNull("Schema context must not be null.", schemaContext); - } + @Before + public void setUp() { + schemaContext = TestModel.createTestContext(); + assertNotNull("Schema context must not be null.", schemaContext); + } - private YangInstanceIdentifier instanceIdentifierFromString(String s){ + private YangInstanceIdentifier instanceIdentifierFromString(String s) { - String[] ids = s.split("/"); + String[] ids = s.split("/"); - List pathArguments = new ArrayList<>(); - for(String nodeId : ids){ - if(!"".equals(nodeId)) { - pathArguments.add(NodeIdentifierFactory.getArgument(nodeId)); - } - } - final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.create(pathArguments); - return instanceIdentifier; + List pathArguments = new ArrayList<>(); + for (String nodeId : ids) { + if (!"".equals(nodeId)) { + pathArguments.add(NodeIdentifierFactory.getArgument(nodeId)); + } } + final YangInstanceIdentifier instanceIdentifier = + YangInstanceIdentifier.create(pathArguments); + return instanceIdentifier; + } - @Test - public void testNormalizeNodeAttributesToProtoBuffNode(){ - final NormalizedNode documentOne = TestModel.createTestContainer(); - String id = "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" + - "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list" + - "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=2}]" + - "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id"; + @Test + public void testNormalizeNodeAttributesToProtoBuffNode() { + final NormalizedNode documentOne = TestModel.createTestContainer(); + String id = + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" + + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list" + + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=2}]" + + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id"; - NormalizedNodeGetter normalizedNodeGetter = new NormalizedNodeGetter(id); - new NormalizedNodeNavigator(normalizedNodeGetter).navigate( - YangInstanceIdentifier.builder().build().toString(), documentOne); + NormalizedNodeGetter normalizedNodeGetter = new NormalizedNodeGetter(id); + new NormalizedNodeNavigator(normalizedNodeGetter).navigate( + YangInstanceIdentifier.builder().build().toString(), documentOne); - // Validate the value of id can be retrieved from the normalized node - NormalizedNode output = normalizedNodeGetter.getOutput(); - assertNotNull(output); + // Validate the value of id can be retrieved from the normalized node + NormalizedNode output = normalizedNodeGetter.getOutput(); + assertNotNull(output); - NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(schemaContext); - Container container = codec.encode(instanceIdentifierFromString(id),output); + NormalizedNodeToNodeCodec codec = + new NormalizedNodeToNodeCodec(schemaContext); + Container container = + codec.encode(instanceIdentifierFromString(id), output); - assertNotNull(container); - assertEquals(id, container.getParentPath()+"/"+container.getNormalizedNode().getPath()) ; + assertNotNull(container); + assertEquals(id, container.getParentPath() + "/" + + container.getNormalizedNode().getPath()); - // Decode the normalized node from the ProtocolBuffer form - //first get the node representation of normalized node - final Node node = container.getNormalizedNode(); + // Decode the normalized node from the ProtocolBuffer form + // first get the node representation of normalized node + final Node node = container.getNormalizedNode(); - NormalizedNode normalizedNode = codec.decode(instanceIdentifierFromString(id),node); + NormalizedNode normalizedNode = + codec.decode(instanceIdentifierFromString(id), node); - assertEquals(normalizedNode.getValue().toString(),output.getValue().toString()); - } + assertEquals(normalizedNode.getValue().toString(), output.getValue() + .toString()); + } - @Test - public void testThatANormalizedNodeToProtoBuffNodeEncodeDecode() throws Exception { - final NormalizedNode documentOne = TestModel.createTestContainer(); + @Test + public void testThatANormalizedNodeToProtoBuffNodeEncodeDecode() + throws Exception { + final NormalizedNode documentOne = TestModel.createTestContainer(); - final NormalizedNodeToNodeCodec normalizedNodeToNodeCodec = new NormalizedNodeToNodeCodec(schemaContext); + final NormalizedNodeToNodeCodec normalizedNodeToNodeCodec = + new NormalizedNodeToNodeCodec(schemaContext); - Container container = normalizedNodeToNodeCodec.encode(YangInstanceIdentifier.builder().build(), documentOne); + Container container = + normalizedNodeToNodeCodec.encode(YangInstanceIdentifier.builder() + .build(), documentOne); - final NormalizedNode decode = normalizedNodeToNodeCodec.decode(instanceIdentifierFromString("/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"),container.getNormalizedNode()); - assertNotNull(decode != null); + final NormalizedNode decode = + normalizedNodeToNodeCodec + .decode( + instanceIdentifierFromString("/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"), + container.getNormalizedNode()); + assertNotNull(decode != null); - //let us ensure that the return decode normalized node encode returns same container - Container containerResult = normalizedNodeToNodeCodec.encode(YangInstanceIdentifier.builder().build(), decode); + // let us ensure that the return decode normalized node encode returns same container + Container containerResult = + normalizedNodeToNodeCodec.encode(YangInstanceIdentifier.builder() + .build(), decode); - assertEquals(container.getParentPath(),containerResult.getParentPath()); - assertEquals(container.getNormalizedNode().getChildCount(),container.getNormalizedNode().getChildCount()); + assertEquals(container.getParentPath(), containerResult.getParentPath()); + assertEquals(container.getNormalizedNode().getChildCount(), container + .getNormalizedNode().getChildCount()); - Assert.assertEquals(containerResult.getNormalizedNode().getChildCount(),container.getNormalizedNode().getChildCount()); + Assert.assertEquals(containerResult.getNormalizedNode().getChildCount(), + container.getNormalizedNode().getChildCount()); - //check first level children are proper - ListchildrenResult = containerResult.getNormalizedNode().getChildList(); - ListchildrenOriginal = container.getNormalizedNode().getChildList(); + // check first level children are proper + List childrenResult = + containerResult.getNormalizedNode().getChildList(); + List childrenOriginal = container.getNormalizedNode().getChildList(); - System.out.println("-------------------------------------------------"); + System.out.println("-------------------------------------------------"); - System.out.println(childrenOriginal.toString()); + System.out.println(childrenOriginal.toString()); - System.out.println("-------------------------------------------------"); + System.out.println("-------------------------------------------------"); - System.out.println(childrenResult.toString()); + System.out.println(childrenResult.toString()); - boolean bFound; - for(Node resultChild: childrenResult){ - bFound = false; - for(Node originalChild:childrenOriginal){ - if(originalChild.getPath().equals(resultChild.getPath()) - && resultChild.getType().equals(resultChild.getType())){ - bFound=true; - break; - } - } - Assert.assertTrue(bFound); + boolean bFound; + for (Node resultChild : childrenResult) { + bFound = false; + for (Node originalChild : childrenOriginal) { + if (originalChild.getPath().equals(resultChild.getPath()) + && resultChild.getType().equals(resultChild.getType())) { + bFound = true; + break; } - + } + Assert.assertTrue(bFound); } - @Test - public void addAugmentations(){ - String stringId = "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" + - "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list" + - "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=1}]"; + } - YangInstanceIdentifier identifier = instanceIdentifierFromString(stringId); + @Test + public void addAugmentations() { + String stringId = + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" + + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list" + + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=1}]"; - MapEntryNode uno = TestModel.createAugmentedListEntry(1, "Uno"); + YangInstanceIdentifier identifier = instanceIdentifierFromString(stringId); - NormalizedNodeToNodeCodec codec = - new NormalizedNodeToNodeCodec(schemaContext); + MapEntryNode uno = TestModel.createAugmentedListEntry(1, "Uno"); - Container encode = codec - .encode(identifier, uno); + NormalizedNodeToNodeCodec codec = + new NormalizedNodeToNodeCodec(schemaContext); - System.out.println(encode.getNormalizedNode()); + Container encode = codec.encode(identifier, uno); - codec.decode(identifier, encode.getNormalizedNode()); - } + System.out.println(encode.getNormalizedNode()); + + codec.decode(identifier, encode.getNormalizedNode()); + } } diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java index 4b0bde83e0..4da7d8c483 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.node.utils; import junit.framework.Assert; @@ -6,15 +16,16 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class NodeIdentifierFactoryTest { - @Test - public void validateAugmentationIdentifier(){ - YangInstanceIdentifier.PathArgument argument = NodeIdentifierFactory - .getArgument( - "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}"); + @Test + public void validateAugmentationIdentifier() { + YangInstanceIdentifier.PathArgument argument = + NodeIdentifierFactory + .getArgument("AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}"); - Assert.assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier); + Assert + .assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier); - } + } } diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java index bb246fb1e4..136748e341 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.util; import org.junit.Assert; @@ -13,129 +23,139 @@ import java.util.List; public class InstanceIdentifierUtilsTest { - private static QName TEST_QNAME = QName.create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"); - private static QName NODE_WITH_VALUE_QNAME = QName.create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)value"); - private static QName NODE_WITH_PREDICATES_QNAME = QName.create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)pred"); - private static QName NAME_QNAME = QName.create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)name"); + private static QName TEST_QNAME = + QName + .create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"); + private static QName NODE_WITH_VALUE_QNAME = + QName + .create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)value"); + private static QName NODE_WITH_PREDICATES_QNAME = + QName + .create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)pred"); + private static QName NAME_QNAME = + QName + .create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)name"); - @Test - public void testSerializationOfNodeIdentifier(){ - YangInstanceIdentifier.PathArgument p1 = - new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME); + @Test + public void testSerializationOfNodeIdentifier() { + YangInstanceIdentifier.PathArgument p1 = + new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME); - List arguments = new ArrayList<>(); + List arguments = new ArrayList<>(); - arguments.add(p1); + arguments.add(p1); - YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments); + YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments); - NormalizedNodeMessages.InstanceIdentifier instanceIdentifier = - InstanceIdentifierUtils.toSerializable(expected); + NormalizedNodeMessages.InstanceIdentifier instanceIdentifier = + InstanceIdentifierUtils.toSerializable(expected); - YangInstanceIdentifier actual = - InstanceIdentifierUtils.fromSerializable(instanceIdentifier); + YangInstanceIdentifier actual = + InstanceIdentifierUtils.fromSerializable(instanceIdentifier); - Assert.assertEquals(expected.getLastPathArgument(), - actual.getLastPathArgument()); + Assert.assertEquals(expected.getLastPathArgument(), + actual.getLastPathArgument()); - } + } - @Test - public void testSerializationOfNodeWithValue(){ + @Test + public void testSerializationOfNodeWithValue() { - withValue((short) 1); - withValue((long) 2); - withValue(3); - withValue(true); + withValue((short) 1); + withValue((long) 2); + withValue(3); + withValue(true); - } + } - private void withValue(Object value){ - YangInstanceIdentifier.PathArgument p1 = - new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME); + private void withValue(Object value) { + YangInstanceIdentifier.PathArgument p1 = + new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME); - YangInstanceIdentifier.PathArgument p2 = - new YangInstanceIdentifier.NodeWithValue(NODE_WITH_VALUE_QNAME, value); + YangInstanceIdentifier.PathArgument p2 = + new YangInstanceIdentifier.NodeWithValue(NODE_WITH_VALUE_QNAME, value); - List arguments = new ArrayList<>(); + List arguments = new ArrayList<>(); - arguments.add(p1); - arguments.add(p2); + arguments.add(p1); + arguments.add(p2); - YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments); + YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments); - NormalizedNodeMessages.InstanceIdentifier instanceIdentifier = - InstanceIdentifierUtils.toSerializable(expected); + NormalizedNodeMessages.InstanceIdentifier instanceIdentifier = + InstanceIdentifierUtils.toSerializable(expected); - YangInstanceIdentifier actual = - InstanceIdentifierUtils.fromSerializable(instanceIdentifier); + YangInstanceIdentifier actual = + InstanceIdentifierUtils.fromSerializable(instanceIdentifier); - Assert.assertEquals(expected.getLastPathArgument(), - actual.getLastPathArgument()); - } + Assert.assertEquals(expected.getLastPathArgument(), + actual.getLastPathArgument()); + } - @Test - public void testSerializationOfNodeIdentifierWithPredicates(){ + @Test + public void testSerializationOfNodeIdentifierWithPredicates() { - withPredicates((short) 1); - withPredicates((long) 2); - withPredicates(3); - withPredicates(true); + withPredicates((short) 1); + withPredicates((long) 2); + withPredicates(3); + withPredicates(true); - } + } - private void withPredicates(Object value){ - YangInstanceIdentifier.PathArgument p1 = - new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME); + private void withPredicates(Object value) { + YangInstanceIdentifier.PathArgument p1 = + new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME); - YangInstanceIdentifier.PathArgument p2 = - new YangInstanceIdentifier.NodeIdentifierWithPredicates(NODE_WITH_PREDICATES_QNAME, NAME_QNAME, value); + YangInstanceIdentifier.PathArgument p2 = + new YangInstanceIdentifier.NodeIdentifierWithPredicates( + NODE_WITH_PREDICATES_QNAME, NAME_QNAME, value); - List arguments = new ArrayList<>(); + List arguments = new ArrayList<>(); - arguments.add(p1); - arguments.add(p2); + arguments.add(p1); + arguments.add(p2); - YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments); + YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments); - NormalizedNodeMessages.InstanceIdentifier instanceIdentifier = - InstanceIdentifierUtils.toSerializable(expected); + NormalizedNodeMessages.InstanceIdentifier instanceIdentifier = + InstanceIdentifierUtils.toSerializable(expected); - YangInstanceIdentifier actual = - InstanceIdentifierUtils.fromSerializable(instanceIdentifier); + YangInstanceIdentifier actual = + InstanceIdentifierUtils.fromSerializable(instanceIdentifier); - Assert.assertEquals(expected.getLastPathArgument(), - actual.getLastPathArgument()); - } + Assert.assertEquals(expected.getLastPathArgument(), + actual.getLastPathArgument()); + } - @Test - public void testAugmentationIdentifier(){ - YangInstanceIdentifier.PathArgument p1 = - new YangInstanceIdentifier.AugmentationIdentifier(new HashSet(Arrays.asList(TEST_QNAME))); + @Test + public void testAugmentationIdentifier() { + YangInstanceIdentifier.PathArgument p1 = + new YangInstanceIdentifier.AugmentationIdentifier(new HashSet( + Arrays.asList(TEST_QNAME))); - List arguments = new ArrayList<>(); + List arguments = new ArrayList<>(); - arguments.add(p1); + arguments.add(p1); - YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments); + YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments); - NormalizedNodeMessages.InstanceIdentifier instanceIdentifier = - InstanceIdentifierUtils.toSerializable(expected); + NormalizedNodeMessages.InstanceIdentifier instanceIdentifier = + InstanceIdentifierUtils.toSerializable(expected); - YangInstanceIdentifier actual = - InstanceIdentifierUtils.fromSerializable(instanceIdentifier); + YangInstanceIdentifier actual = + InstanceIdentifierUtils.fromSerializable(instanceIdentifier); - Assert.assertEquals(expected.getLastPathArgument(), - actual.getLastPathArgument()); + Assert.assertEquals(expected.getLastPathArgument(), + actual.getLastPathArgument()); - } + } } diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java index fb28704952..853b3e264b 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java @@ -1,9 +1,11 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * - * This program and the accompanying materials are made available under the terms of the Eclipse - * Public License v1.0 which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * */ package org.opendaylight.controller.cluster.datastore.util; @@ -71,8 +73,8 @@ import java.util.Set; /** - * Two of the testcases in the yangtools/yang-data-impl are leveraged (with modification) to - * create the serialization of NormalizedNode using the ProtocolBuffer + * Two of the testcases in the yangtools/yang-data-impl are leveraged (with modification) to create + * the serialization of NormalizedNode using the ProtocolBuffer * * @syedbahm * @@ -80,403 +82,402 @@ import java.util.Set; public class NormalizedNodeXmlConverterTest { - private static final Logger logger = LoggerFactory - .getLogger(NormalizedNodeXmlConverterTest.class); - public static final String NAMESPACE = - "urn:opendaylight:params:xml:ns:yang:controller:test"; - private static Date revision; - private ContainerNode expectedNode; - private ContainerSchemaNode containerNode; - private String xmlPath; - - static { - try { - revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13"); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - public static DataSchemaNode getSchemaNode(final SchemaContext context, - final String moduleName, final String childNodeName) { - for (Module module : context.getModules()) { - if (module.getName().equals(moduleName)) { - DataSchemaNode found = - findChildNode(module.getChildNodes(), childNodeName); - Preconditions.checkState(found != null, "Unable to find %s", - childNodeName); - return found; - } - } - throw new IllegalStateException("Unable to find child node " - + childNodeName); + private static final Logger logger = LoggerFactory + .getLogger(NormalizedNodeXmlConverterTest.class); + public static final String NAMESPACE = + "urn:opendaylight:params:xml:ns:yang:controller:test"; + private static Date revision; + private ContainerNode expectedNode; + private ContainerSchemaNode containerNode; + private String xmlPath; + + static { + try { + revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13"); + } catch (ParseException e) { + throw new RuntimeException(e); } - - static DataSchemaNode findChildNode(final Collection children, final String name) { - List containers = Lists.newArrayList(); - - for (DataSchemaNode dataSchemaNode : children) { - if (dataSchemaNode.getQName().getLocalName().equals(name)) { - return dataSchemaNode; - } - if (dataSchemaNode instanceof DataNodeContainer) { - containers.add((DataNodeContainer) dataSchemaNode); - } else if (dataSchemaNode instanceof ChoiceNode) { - containers.addAll(((ChoiceNode) dataSchemaNode).getCases()); - } - } - - for (DataNodeContainer container : containers) { - DataSchemaNode retVal = findChildNode(container.getChildNodes(), name); - if (retVal != null) { - return retVal; - } - } - - return null; + } + + public static DataSchemaNode getSchemaNode(final SchemaContext context, + final String moduleName, final String childNodeName) { + for (Module module : context.getModules()) { + if (module.getName().equals(moduleName)) { + DataSchemaNode found = + findChildNode(module.getChildNodes(), childNodeName); + Preconditions.checkState(found != null, "Unable to find %s", + childNodeName); + return found; + } } - - public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier( - final String localName) { - return new YangInstanceIdentifier.NodeIdentifier(QName.create( - URI.create(NAMESPACE), revision, localName)); + throw new IllegalStateException("Unable to find child node " + + childNodeName); + } + + static DataSchemaNode findChildNode( + final Collection children, final String name) { + List containers = Lists.newArrayList(); + + for (DataSchemaNode dataSchemaNode : children) { + if (dataSchemaNode.getQName().getLocalName().equals(name)) { + return dataSchemaNode; + } + if (dataSchemaNode instanceof DataNodeContainer) { + containers.add((DataNodeContainer) dataSchemaNode); + } else if (dataSchemaNode instanceof ChoiceNode) { + containers.addAll(((ChoiceNode) dataSchemaNode).getCases()); + } } - public static YangInstanceIdentifier.AugmentationIdentifier getAugmentIdentifier( - final String... childNames) { - Set qn = Sets.newHashSet(); - - for (String childName : childNames) { - qn.add(getNodeIdentifier(childName).getNodeType()); - } - - return new YangInstanceIdentifier.AugmentationIdentifier(qn); + for (DataNodeContainer container : containers) { + DataSchemaNode retVal = findChildNode(container.getChildNodes(), name); + if (retVal != null) { + return retVal; + } } + return null; + } - public static ContainerNode augmentChoiceExpectedNode() { - - DataContainerNodeBuilder b = - Builders.containerBuilder(); - b.withNodeIdentifier(getNodeIdentifier("container")); - - b.withChild(Builders - .choiceBuilder() - .withNodeIdentifier(getNodeIdentifier("ch2")) - .withChild( - Builders.leafBuilder() - .withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2") - .build()) - .withChild( - Builders - .choiceBuilder() - .withNodeIdentifier(getNodeIdentifier("c2DeepChoice")) - .withChild( - Builders - .leafBuilder() - .withNodeIdentifier( - getNodeIdentifier("c2DeepChoiceCase1Leaf2")) - .withValue("2").build()).build()).build()); - - b.withChild(Builders - .choiceBuilder() - .withNodeIdentifier(getNodeIdentifier("ch3")) - .withChild( - Builders.leafBuilder() - .withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3") - .build()).build()); - - b.withChild(Builders - .augmentationBuilder() - .withNodeIdentifier(getAugmentIdentifier("augLeaf")) - .withChild( - Builders.leafBuilder() - .withNodeIdentifier(getNodeIdentifier("augLeaf")) - .withValue("augment").build()).build()); - - b.withChild(Builders - .augmentationBuilder() - .withNodeIdentifier(getAugmentIdentifier("ch")) - .withChild( - Builders - .choiceBuilder() - .withNodeIdentifier(getNodeIdentifier("ch")) - .withChild( - Builders.leafBuilder() - .withNodeIdentifier(getNodeIdentifier("c1Leaf")) - .withValue("1").build()) - .withChild( - Builders - .augmentationBuilder() - .withNodeIdentifier( - getAugmentIdentifier("c1Leaf_AnotherAugment", - "deepChoice")) - .withChild( - Builders - .leafBuilder() - .withNodeIdentifier( - getNodeIdentifier("c1Leaf_AnotherAugment")) - .withValue("1").build()) - .withChild( - Builders - .choiceBuilder() - .withNodeIdentifier( - getNodeIdentifier("deepChoice")) - .withChild( - Builders - .leafBuilder() - .withNodeIdentifier( - getNodeIdentifier("deepLeafc1")) - .withValue("1").build()).build()) - .build()).build()).build()); - - return b.build(); - } - + public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier( + final String localName) { + return new YangInstanceIdentifier.NodeIdentifier(QName.create( + URI.create(NAMESPACE), revision, localName)); + } + public static YangInstanceIdentifier.AugmentationIdentifier getAugmentIdentifier( + final String... childNames) { + Set qn = Sets.newHashSet(); - public void init(final String yangPath, final String xmlPath, final ContainerNode expectedNode) - throws Exception { - SchemaContext schema = parseTestSchema(yangPath); - this.xmlPath = xmlPath; - this.containerNode = - (ContainerSchemaNode) getSchemaNode(schema, "test", "container"); - this.expectedNode = expectedNode; + for (String childName : childNames) { + qn.add(getNodeIdentifier(childName).getNodeType()); } - SchemaContext parseTestSchema(final String yangPath) throws Exception { - - YangParserImpl yangParserImpl = new YangParserImpl(); - InputStream stream = - NormalizedNodeXmlConverterTest.class.getResourceAsStream(yangPath); - ArrayList al = new ArrayList(); - al.add(stream); - Set modules = yangParserImpl.parseYangModelsFromStreams(al); - return yangParserImpl.resolveSchemaContext(modules); - + return new YangInstanceIdentifier.AugmentationIdentifier(qn); + } + + + public static ContainerNode augmentChoiceExpectedNode() { + + DataContainerNodeBuilder b = + Builders.containerBuilder(); + b.withNodeIdentifier(getNodeIdentifier("container")); + + b.withChild(Builders + .choiceBuilder() + .withNodeIdentifier(getNodeIdentifier("ch2")) + .withChild( + Builders.leafBuilder() + .withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2") + .build()) + .withChild( + Builders + .choiceBuilder() + .withNodeIdentifier(getNodeIdentifier("c2DeepChoice")) + .withChild( + Builders + .leafBuilder() + .withNodeIdentifier( + getNodeIdentifier("c2DeepChoiceCase1Leaf2")) + .withValue("2").build()).build()).build()); + + b.withChild(Builders + .choiceBuilder() + .withNodeIdentifier(getNodeIdentifier("ch3")) + .withChild( + Builders.leafBuilder() + .withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3") + .build()).build()); + + b.withChild(Builders + .augmentationBuilder() + .withNodeIdentifier(getAugmentIdentifier("augLeaf")) + .withChild( + Builders.leafBuilder() + .withNodeIdentifier(getNodeIdentifier("augLeaf")) + .withValue("augment").build()).build()); + + b.withChild(Builders + .augmentationBuilder() + .withNodeIdentifier(getAugmentIdentifier("ch")) + .withChild( + Builders + .choiceBuilder() + .withNodeIdentifier(getNodeIdentifier("ch")) + .withChild( + Builders.leafBuilder() + .withNodeIdentifier(getNodeIdentifier("c1Leaf")) + .withValue("1").build()) + .withChild( + Builders + .augmentationBuilder() + .withNodeIdentifier( + getAugmentIdentifier("c1Leaf_AnotherAugment", + "deepChoice")) + .withChild( + Builders + .leafBuilder() + .withNodeIdentifier( + getNodeIdentifier("c1Leaf_AnotherAugment")) + .withValue("1").build()) + .withChild( + Builders + .choiceBuilder() + .withNodeIdentifier( + getNodeIdentifier("deepChoice")) + .withChild( + Builders + .leafBuilder() + .withNodeIdentifier( + getNodeIdentifier("deepLeafc1")) + .withValue("1").build()).build()) + .build()).build()).build()); + + return b.build(); + } + + + + public void init(final String yangPath, final String xmlPath, + final ContainerNode expectedNode) throws Exception { + SchemaContext schema = parseTestSchema(yangPath); + this.xmlPath = xmlPath; + this.containerNode = + (ContainerSchemaNode) getSchemaNode(schema, "test", "container"); + this.expectedNode = expectedNode; + } + + SchemaContext parseTestSchema(final String yangPath) throws Exception { + + YangParserImpl yangParserImpl = new YangParserImpl(); + InputStream stream = + NormalizedNodeXmlConverterTest.class.getResourceAsStream(yangPath); + ArrayList al = new ArrayList(); + al.add(stream); + Set modules = yangParserImpl.parseYangModelsFromStreams(al); + return yangParserImpl.resolveSchemaContext(modules); + + } + + + @Test + public void testConversionWithAugmentChoice() throws Exception { + init("/augment_choice.yang", "/augment_choice.xml", + augmentChoiceExpectedNode()); + Document doc = loadDocument(xmlPath); + + ContainerNode built = + DomToNormalizedNodeParserFactory + .getInstance(DomUtils.defaultValueCodecProvider()) + .getContainerNodeParser() + .parse(Collections.singletonList(doc.getDocumentElement()), + containerNode); + + if (expectedNode != null) { + junit.framework.Assert.assertEquals(expectedNode, built); } + logger.info("{}", built); - @Test - public void testConversionWithAugmentChoice() throws Exception { - init("/augment_choice.yang", "/augment_choice.xml", - augmentChoiceExpectedNode()); - Document doc = loadDocument(xmlPath); + Iterable els = + DomFromNormalizedNodeSerializerFactory + .getInstance(XmlDocumentUtils.getDocument(), + DomUtils.defaultValueCodecProvider()) + .getContainerNodeSerializer().serialize(containerNode, built); - ContainerNode built = - DomToNormalizedNodeParserFactory - .getInstance(DomUtils.defaultValueCodecProvider()) - .getContainerNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - containerNode); + Element el = els.iterator().next(); - if (expectedNode != null) { - junit.framework.Assert.assertEquals(expectedNode, built); - } + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.setIgnoreComments(true); - logger.info("{}", built); + System.out.println(toString(doc.getDocumentElement())); + System.out.println(toString(el)); - Iterable els = - DomFromNormalizedNodeSerializerFactory - .getInstance(XmlDocumentUtils.getDocument(), - DomUtils.defaultValueCodecProvider()) - .getContainerNodeSerializer().serialize(containerNode, built); + new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), + XMLUnit.buildTestDocument(toString(el))).similar(); + } - Element el = els.iterator().next(); + private static ContainerNode listLeafListWithAttributes() { + DataContainerNodeBuilder b = + Builders.containerBuilder(); + b.withNodeIdentifier(getNodeIdentifier("container")); - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); + CollectionNodeBuilder listBuilder = + Builders.mapBuilder().withNodeIdentifier(getNodeIdentifier("list")); - System.out.println(toString(doc.getDocumentElement())); - System.out.println(toString(el)); + Map predicates = Maps.newHashMap(); + predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L); - new Diff( - XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), - XMLUnit.buildTestDocument(toString(el))).similar(); - } + DataContainerNodeBuilder list1Builder = + Builders.mapEntryBuilder().withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifierWithPredicates( + getNodeIdentifier("list").getNodeType(), predicates)); + NormalizedNodeBuilder> uint32InListBuilder = + Builders.leafBuilder().withNodeIdentifier( + getNodeIdentifier("uint32InList")); - private static ContainerNode listLeafListWithAttributes() { - DataContainerNodeBuilder b = - Builders.containerBuilder(); - b.withNodeIdentifier(getNodeIdentifier("container")); + list1Builder.withChild(uint32InListBuilder.withValue(3L).build()); - CollectionNodeBuilder listBuilder = - Builders.mapBuilder().withNodeIdentifier(getNodeIdentifier("list")); + listBuilder.withChild(list1Builder.build()); + b.withChild(listBuilder.build()); - Map predicates = Maps.newHashMap(); - predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L); + NormalizedNodeBuilder> booleanBuilder = + Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean")); + booleanBuilder.withValue(false); + b.withChild(booleanBuilder.build()); - DataContainerNodeBuilder list1Builder = - Builders.mapEntryBuilder().withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifierWithPredicates( - getNodeIdentifier("list").getNodeType(), predicates)); - NormalizedNodeBuilder> uint32InListBuilder = - Builders.leafBuilder().withNodeIdentifier( - getNodeIdentifier("uint32InList")); + ListNodeBuilder> leafListBuilder = + Builders.leafSetBuilder().withNodeIdentifier( + getNodeIdentifier("leafList")); - list1Builder.withChild(uint32InListBuilder.withValue(3L).build()); + NormalizedNodeBuilder> leafList1Builder = + Builders.leafSetEntryBuilder().withNodeIdentifier( + new YangInstanceIdentifier.NodeWithValue(getNodeIdentifier( + "leafList").getNodeType(), "a")); - listBuilder.withChild(list1Builder.build()); - b.withChild(listBuilder.build()); + leafList1Builder.withValue("a"); - NormalizedNodeBuilder> booleanBuilder = - Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean")); - booleanBuilder.withValue(false); - b.withChild(booleanBuilder.build()); + leafListBuilder.withChild(leafList1Builder.build()); + b.withChild(leafListBuilder.build()); - ListNodeBuilder> leafListBuilder = - Builders.leafSetBuilder().withNodeIdentifier( - getNodeIdentifier("leafList")); + return b.build(); + } - NormalizedNodeBuilder> leafList1Builder = - Builders.leafSetEntryBuilder().withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue(getNodeIdentifier("leafList") - .getNodeType(), "a")); - leafList1Builder.withValue("a"); + @Test + public void testConversionWithAttributes() throws Exception { + init("/test.yang", "/simple_xml_with_attributes.xml", + listLeafListWithAttributes()); + Document doc = loadDocument(xmlPath); - leafListBuilder.withChild(leafList1Builder.build()); - b.withChild(leafListBuilder.build()); + ContainerNode built = + DomToNormalizedNodeParserFactory + .getInstance(DomUtils.defaultValueCodecProvider()) + .getContainerNodeParser() + .parse(Collections.singletonList(doc.getDocumentElement()), + containerNode); - return b.build(); + if (expectedNode != null) { + junit.framework.Assert.assertEquals(expectedNode, built); } + logger.info("{}", built); - @Test - public void testConversionWithAttributes() throws Exception { - init("/test.yang", "/simple_xml_with_attributes.xml", - listLeafListWithAttributes()); - Document doc = loadDocument(xmlPath); + Iterable els = + DomFromNormalizedNodeSerializerFactory + .getInstance(XmlDocumentUtils.getDocument(), + DomUtils.defaultValueCodecProvider()) + .getContainerNodeSerializer().serialize(containerNode, built); - ContainerNode built = - DomToNormalizedNodeParserFactory - .getInstance(DomUtils.defaultValueCodecProvider()) - .getContainerNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - containerNode); + Element el = els.iterator().next(); - if (expectedNode != null) { - junit.framework.Assert.assertEquals(expectedNode, built); - } + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.setIgnoreComments(true); - logger.info("{}", built); + System.out.println(toString(doc.getDocumentElement())); + System.out.println(toString(el)); - Iterable els = - DomFromNormalizedNodeSerializerFactory - .getInstance(XmlDocumentUtils.getDocument(), - DomUtils.defaultValueCodecProvider()) - .getContainerNodeSerializer().serialize(containerNode, built); + new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), + XMLUnit.buildTestDocument(toString(el))).similar(); + } - Element el = els.iterator().next(); - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); + private Document loadDocument(final String xmlPath) throws Exception { + InputStream resourceAsStream = + NormalizedNodeXmlConverterTest.class.getResourceAsStream(xmlPath); - System.out.println(toString(doc.getDocumentElement())); - System.out.println(toString(el)); + Document currentConfigElement = readXmlToDocument(resourceAsStream); + Preconditions.checkNotNull(currentConfigElement); + return currentConfigElement; + } - new Diff( - XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), - XMLUnit.buildTestDocument(toString(el))).similar(); - } + private static final DocumentBuilderFactory BUILDERFACTORY; + static { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + factory.setCoalescing(true); + factory.setIgnoringElementContentWhitespace(true); + factory.setIgnoringComments(true); + BUILDERFACTORY = factory; + } - private Document loadDocument(final String xmlPath) throws Exception { - InputStream resourceAsStream = - NormalizedNodeXmlConverterTest.class.getResourceAsStream(xmlPath); - - Document currentConfigElement = readXmlToDocument(resourceAsStream); - Preconditions.checkNotNull(currentConfigElement); - return currentConfigElement; - } - - private static final DocumentBuilderFactory BUILDERFACTORY; - - static { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - factory.setCoalescing(true); - factory.setIgnoringElementContentWhitespace(true); - factory.setIgnoringComments(true); - BUILDERFACTORY = factory; + private Document readXmlToDocument(final InputStream xmlContent) + throws IOException, SAXException { + DocumentBuilder dBuilder; + try { + dBuilder = BUILDERFACTORY.newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw new RuntimeException("Failed to parse XML document", e); } - - private Document readXmlToDocument(final InputStream xmlContent) - throws IOException, SAXException { - DocumentBuilder dBuilder; - try { - dBuilder = BUILDERFACTORY.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw new RuntimeException("Failed to parse XML document", e); - } - Document doc = dBuilder.parse(xmlContent); - - doc.getDocumentElement().normalize(); - return doc; - } - - public static String toString(final Element xml) { - try { - Transformer transformer = - TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - StreamResult result = new StreamResult(new StringWriter()); - DOMSource source = new DOMSource(xml); - transformer.transform(source, result); - - return result.getWriter().toString(); - } catch (IllegalArgumentException | TransformerFactoryConfigurationError - | TransformerException e) { - throw new RuntimeException("Unable to serialize xml element " + xml, e); - } + Document doc = dBuilder.parse(xmlContent); + + doc.getDocumentElement().normalize(); + return doc; + } + + public static String toString(final Element xml) { + try { + Transformer transformer = + TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + + StreamResult result = new StreamResult(new StringWriter()); + DOMSource source = new DOMSource(xml); + transformer.transform(source, result); + + return result.getWriter().toString(); + } catch (IllegalArgumentException | TransformerFactoryConfigurationError + | TransformerException e) { + throw new RuntimeException("Unable to serialize xml element " + xml, e); } + } - @Test - public void testConversionToNormalizedXml() throws Exception { - SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml = - EncoderDecoderUtil.encode(parseTestSchema("/augment_choice.yang"), - augmentChoiceExpectedNode()); - Document expectedDoc = loadDocument("/augment_choice.xml"); - Document convertedDoc = - EncoderDecoderUtil.factory.newDocumentBuilder().parse( - new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8"))); - System.out.println(toString(convertedDoc.getDocumentElement())); - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); - new Diff(XMLUnit.buildControlDocument(toString(expectedDoc - .getDocumentElement())), - XMLUnit.buildTestDocument(toString(convertedDoc - .getDocumentElement()))).similar(); - System.out.println(toString(expectedDoc.getDocumentElement())); - - } - - - @Test - public void testConversionFromXmlToNormalizedNode() throws Exception { - SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml = - EncoderDecoderUtil.encode(parseTestSchema("/test.yang"), - listLeafListWithAttributes()); - Document expectedDoc = loadDocument("/simple_xml_with_attributes.xml"); - Document convertedDoc = - EncoderDecoderUtil.factory.newDocumentBuilder().parse( - new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8"))); - System.out.println(toString(convertedDoc.getDocumentElement())); - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); - new Diff(XMLUnit.buildControlDocument(toString(expectedDoc - .getDocumentElement())), - XMLUnit.buildTestDocument(toString(convertedDoc - .getDocumentElement()))).similar(); - System.out.println(toString(expectedDoc.getDocumentElement())); - - // now we will try to convert xml back to normalize node. - ContainerNode cn = - (ContainerNode) EncoderDecoderUtil.decode( - parseTestSchema("/test.yang"), nnXml); - junit.framework.Assert.assertEquals(listLeafListWithAttributes(), cn); - - } + @Test + public void testConversionToNormalizedXml() throws Exception { + SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml = + EncoderDecoderUtil.encode(parseTestSchema("/augment_choice.yang"), + augmentChoiceExpectedNode()); + Document expectedDoc = loadDocument("/augment_choice.xml"); + Document convertedDoc = + EncoderDecoderUtil.factory.newDocumentBuilder().parse( + new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8"))); + System.out.println(toString(convertedDoc.getDocumentElement())); + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.setIgnoreComments(true); + new Diff(XMLUnit.buildControlDocument(toString(expectedDoc + .getDocumentElement())), + XMLUnit.buildTestDocument(toString(convertedDoc.getDocumentElement()))) + .similar(); + System.out.println(toString(expectedDoc.getDocumentElement())); + + } + + + @Test + public void testConversionFromXmlToNormalizedNode() throws Exception { + SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml = + EncoderDecoderUtil.encode(parseTestSchema("/test.yang"), + listLeafListWithAttributes()); + Document expectedDoc = loadDocument("/simple_xml_with_attributes.xml"); + Document convertedDoc = + EncoderDecoderUtil.factory.newDocumentBuilder().parse( + new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8"))); + System.out.println(toString(convertedDoc.getDocumentElement())); + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.setIgnoreComments(true); + new Diff(XMLUnit.buildControlDocument(toString(expectedDoc + .getDocumentElement())), + XMLUnit.buildTestDocument(toString(convertedDoc.getDocumentElement()))) + .similar(); + System.out.println(toString(expectedDoc.getDocumentElement())); + + // now we will try to convert xml back to normalize node. + ContainerNode cn = + (ContainerNode) EncoderDecoderUtil.decode( + parseTestSchema("/test.yang"), nnXml); + junit.framework.Assert.assertEquals(listLeafListWithAttributes(), cn); + + } } diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java index bef4057aa2..3eeb06f93c 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java @@ -1,3 +1,13 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.cluster.datastore.util; import org.opendaylight.yangtools.yang.common.QName; @@ -34,453 +44,427 @@ import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.ma public class TestModel { - public static final QName TEST_QNAME = QName.create( - "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", - "2014-03-13", "test"); - - public static final QName AUG_NAME_QNAME = QName.create( - "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug", - "2014-03-13", "name"); - - public static final QName AUG_CONT_QNAME = QName.create( - "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug", - "2014-03-13", "cont"); - - - public static final QName DESC_QNAME = QName.create(TEST_QNAME, "desc"); - public static final QName POINTER_QNAME = - QName.create(TEST_QNAME, "pointer"); - public static final QName SOME_REF_QNAME = - QName.create(TEST_QNAME, "some-ref"); - public static final QName MYIDENTITY_QNAME = - QName.create(TEST_QNAME, "myidentity"); - public static final QName SWITCH_FEATURES_QNAME = - QName.create(TEST_QNAME, "switch-features"); - - public static final QName AUGMENTED_LIST_QNAME = - QName.create(TEST_QNAME, "augmented-list"); - - public static final QName OUTER_LIST_QNAME = QName.create(TEST_QNAME, - "outer-list"); - public static final QName INNER_LIST_QNAME = QName.create(TEST_QNAME, - "inner-list"); - public static final QName OUTER_CHOICE_QNAME = QName.create(TEST_QNAME, - "outer-choice"); - public static final QName ID_QNAME = QName.create(TEST_QNAME, "id"); - public static final QName NAME_QNAME = QName.create(TEST_QNAME, "name"); - public static final QName VALUE_QNAME = QName.create(TEST_QNAME, "value"); - private static final String DATASTORE_TEST_YANG = - "/odl-datastore-test.yang"; - private static final String DATASTORE_AUG_YANG = - "/odl-datastore-augmentation.yang"; - private static final String DATASTORE_TEST_NOTIFICATION_YANG = - "/odl-datastore-test-notification.yang"; - - - public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier - .of(TEST_QNAME); - public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier - .builder(TEST_PATH).node(DESC_QNAME).build(); - public static final YangInstanceIdentifier OUTER_LIST_PATH = YangInstanceIdentifier - .builder(TEST_PATH).node(OUTER_LIST_QNAME).build(); - public static final QName TWO_QNAME = QName.create(TEST_QNAME, "two"); - public static final QName THREE_QNAME = QName.create(TEST_QNAME, "three"); - - private static final Integer ONE_ID = 1; - private static final Integer TWO_ID = 2; - private static final String TWO_ONE_NAME = "one"; - private static final String TWO_TWO_NAME = "two"; - private static final String DESC = "Hello there"; - - // Family specific constants - public static final QName FAMILY_QNAME = - QName - .create( - "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test", - "2014-04-17", "family"); - public static final QName CHILDREN_QNAME = QName.create(FAMILY_QNAME, - "children"); - public static final QName GRAND_CHILDREN_QNAME = QName.create(FAMILY_QNAME, - "grand-children"); - public static final QName CHILD_NUMBER_QNAME = QName.create(FAMILY_QNAME, - "child-number"); - public static final QName CHILD_NAME_QNAME = QName.create(FAMILY_QNAME, - "child-name"); - public static final QName GRAND_CHILD_NUMBER_QNAME = QName.create( - FAMILY_QNAME, "grand-child-number"); - public static final QName GRAND_CHILD_NAME_QNAME = - QName.create(FAMILY_QNAME, - "grand-child-name"); - - public static final YangInstanceIdentifier FAMILY_PATH = YangInstanceIdentifier - .of(FAMILY_QNAME); - public static final YangInstanceIdentifier FAMILY_DESC_PATH = YangInstanceIdentifier - .builder(FAMILY_PATH).node(DESC_QNAME).build(); - public static final YangInstanceIdentifier CHILDREN_PATH = YangInstanceIdentifier - .builder(FAMILY_PATH).node(CHILDREN_QNAME).build(); - - private static final Integer FIRST_CHILD_ID = 1; - private static final Integer SECOND_CHILD_ID = 2; - - private static final String FIRST_CHILD_NAME = "first child"; - private static final String SECOND_CHILD_NAME = "second child"; - - private static final Integer FIRST_GRAND_CHILD_ID = 1; - private static final Integer SECOND_GRAND_CHILD_ID = 2; - - private static final String FIRST_GRAND_CHILD_NAME = "first grand child"; - private static final String SECOND_GRAND_CHILD_NAME = "second grand child"; - - // first child - private static final YangInstanceIdentifier CHILDREN_1_PATH = YangInstanceIdentifier - .builder(CHILDREN_PATH) - .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID) // - .build(); - private static final YangInstanceIdentifier CHILDREN_1_NAME_PATH = - YangInstanceIdentifier.builder(CHILDREN_PATH) - .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, FIRST_CHILD_NAME) // - .build(); + public static final QName TEST_QNAME = QName.create( + "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", + "2014-03-13", "test"); + + public static final QName AUG_NAME_QNAME = QName.create( + "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug", + "2014-03-13", "name"); + + public static final QName AUG_CONT_QNAME = QName.create( + "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug", + "2014-03-13", "cont"); + + + public static final QName DESC_QNAME = QName.create(TEST_QNAME, "desc"); + public static final QName POINTER_QNAME = QName.create(TEST_QNAME, "pointer"); + public static final QName SOME_REF_QNAME = QName.create(TEST_QNAME, + "some-ref"); + public static final QName MYIDENTITY_QNAME = QName.create(TEST_QNAME, + "myidentity"); + public static final QName SWITCH_FEATURES_QNAME = QName.create(TEST_QNAME, + "switch-features"); + + public static final QName AUGMENTED_LIST_QNAME = QName.create(TEST_QNAME, + "augmented-list"); + + public static final QName OUTER_LIST_QNAME = QName.create(TEST_QNAME, + "outer-list"); + public static final QName INNER_LIST_QNAME = QName.create(TEST_QNAME, + "inner-list"); + public static final QName OUTER_CHOICE_QNAME = QName.create(TEST_QNAME, + "outer-choice"); + public static final QName ID_QNAME = QName.create(TEST_QNAME, "id"); + public static final QName NAME_QNAME = QName.create(TEST_QNAME, "name"); + public static final QName VALUE_QNAME = QName.create(TEST_QNAME, "value"); + private static final String DATASTORE_TEST_YANG = "/odl-datastore-test.yang"; + private static final String DATASTORE_AUG_YANG = + "/odl-datastore-augmentation.yang"; + private static final String DATASTORE_TEST_NOTIFICATION_YANG = + "/odl-datastore-test-notification.yang"; + + + public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier + .of(TEST_QNAME); + public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier + .builder(TEST_PATH).node(DESC_QNAME).build(); + public static final YangInstanceIdentifier OUTER_LIST_PATH = + YangInstanceIdentifier.builder(TEST_PATH).node(OUTER_LIST_QNAME).build(); + public static final QName TWO_QNAME = QName.create(TEST_QNAME, "two"); + public static final QName THREE_QNAME = QName.create(TEST_QNAME, "three"); + + private static final Integer ONE_ID = 1; + private static final Integer TWO_ID = 2; + private static final String TWO_ONE_NAME = "one"; + private static final String TWO_TWO_NAME = "two"; + private static final String DESC = "Hello there"; + + // Family specific constants + public static final QName FAMILY_QNAME = + QName + .create( + "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test", + "2014-04-17", "family"); + public static final QName CHILDREN_QNAME = QName.create(FAMILY_QNAME, + "children"); + public static final QName GRAND_CHILDREN_QNAME = QName.create(FAMILY_QNAME, + "grand-children"); + public static final QName CHILD_NUMBER_QNAME = QName.create(FAMILY_QNAME, + "child-number"); + public static final QName CHILD_NAME_QNAME = QName.create(FAMILY_QNAME, + "child-name"); + public static final QName GRAND_CHILD_NUMBER_QNAME = QName.create( + FAMILY_QNAME, "grand-child-number"); + public static final QName GRAND_CHILD_NAME_QNAME = QName.create(FAMILY_QNAME, + "grand-child-name"); + + public static final YangInstanceIdentifier FAMILY_PATH = + YangInstanceIdentifier.of(FAMILY_QNAME); + public static final YangInstanceIdentifier FAMILY_DESC_PATH = + YangInstanceIdentifier.builder(FAMILY_PATH).node(DESC_QNAME).build(); + public static final YangInstanceIdentifier CHILDREN_PATH = + YangInstanceIdentifier.builder(FAMILY_PATH).node(CHILDREN_QNAME).build(); + + private static final Integer FIRST_CHILD_ID = 1; + private static final Integer SECOND_CHILD_ID = 2; + + private static final String FIRST_CHILD_NAME = "first child"; + private static final String SECOND_CHILD_NAME = "second child"; + + private static final Integer FIRST_GRAND_CHILD_ID = 1; + private static final Integer SECOND_GRAND_CHILD_ID = 2; + + private static final String FIRST_GRAND_CHILD_NAME = "first grand child"; + private static final String SECOND_GRAND_CHILD_NAME = "second grand child"; + + // first child + private static final YangInstanceIdentifier CHILDREN_1_PATH = + YangInstanceIdentifier.builder(CHILDREN_PATH) + .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID) // + .build(); + private static final YangInstanceIdentifier CHILDREN_1_NAME_PATH = + YangInstanceIdentifier.builder(CHILDREN_PATH) + .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, FIRST_CHILD_NAME) // + .build(); + + private static final YangInstanceIdentifier CHILDREN_2_PATH = + YangInstanceIdentifier.builder(CHILDREN_PATH) + .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID) // + .build(); + private static final YangInstanceIdentifier CHILDREN_2_NAME_PATH = + YangInstanceIdentifier.builder(CHILDREN_PATH) + .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, SECOND_CHILD_NAME) // + .build(); + + + private static final YangInstanceIdentifier GRAND_CHILD_1_PATH = + YangInstanceIdentifier + .builder(CHILDREN_1_PATH) + .node(GRAND_CHILDREN_QNAME) + // + .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, + FIRST_GRAND_CHILD_ID) // + .build(); + + private static final YangInstanceIdentifier GRAND_CHILD_1_NAME_PATH = + YangInstanceIdentifier + .builder(CHILDREN_1_PATH) + .node(GRAND_CHILDREN_QNAME) + // + .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME, + FIRST_GRAND_CHILD_NAME) // + .build(); + + private static final YangInstanceIdentifier GRAND_CHILD_2_PATH = + YangInstanceIdentifier + .builder(CHILDREN_2_PATH) + .node(GRAND_CHILDREN_QNAME) + // + .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, + SECOND_GRAND_CHILD_ID) // + .build(); + + private static final YangInstanceIdentifier GRAND_CHILD_2_NAME_PATH = + YangInstanceIdentifier + .builder(CHILDREN_2_PATH) + .node(GRAND_CHILDREN_QNAME) + // + .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME, + SECOND_GRAND_CHILD_NAME) // + .build(); + + private static final YangInstanceIdentifier DESC_PATH_ID = + YangInstanceIdentifier.builder(DESC_PATH).build(); + private static final YangInstanceIdentifier OUTER_LIST_1_PATH = + YangInstanceIdentifier.builder(OUTER_LIST_PATH) + .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) // + .build(); + + private static final YangInstanceIdentifier OUTER_LIST_2_PATH = + YangInstanceIdentifier.builder(OUTER_LIST_PATH) + .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) // + .build(); + + private static final YangInstanceIdentifier TWO_TWO_PATH = + YangInstanceIdentifier.builder(OUTER_LIST_2_PATH).node(INNER_LIST_QNAME) // + .nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) // + .build(); + + private static final YangInstanceIdentifier TWO_TWO_VALUE_PATH = + YangInstanceIdentifier.builder(TWO_TWO_PATH).node(VALUE_QNAME) // + .build(); + + private static final MapEntryNode BAR_NODE = mapEntryBuilder( + OUTER_LIST_QNAME, ID_QNAME, TWO_ID) // + .withChild(mapNodeBuilder(INNER_LIST_QNAME) // + .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) // + .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) // + .build()) // + .build(); + + public static final InputStream getDatastoreTestInputStream() { + return getInputStream(DATASTORE_TEST_YANG); + } + + public static final InputStream getDatastoreAugInputStream() { + return getInputStream(DATASTORE_AUG_YANG); + } + + public static final InputStream getDatastoreTestNotificationInputStream() { + return getInputStream(DATASTORE_TEST_NOTIFICATION_YANG); + } + + private static InputStream getInputStream(final String resourceName) { + return TestModel.class.getResourceAsStream(resourceName); + } + + public static SchemaContext createTestContext() { + List inputStreams = new ArrayList<>(); + inputStreams.add(getDatastoreTestInputStream()); + inputStreams.add(getDatastoreAugInputStream()); + inputStreams.add(getDatastoreTestNotificationInputStream()); + + YangParserImpl parser = new YangParserImpl(); + Set modules = parser.parseYangModelsFromStreams(inputStreams); + return parser.resolveSchemaContext(modules); + } + + /** + * Returns a test document + *

+ * + *

+   * test
+   *     outer-list
+   *          id 1
+   *     outer-list
+   *          id 2
+   *          inner-list
+   *                  name "one"
+   *          inner-list
+   *                  name "two"
+   *
+   * 
+ * + * @return + */ + public static NormalizedNode createDocumentOne( + SchemaContext schemaContext) { + return ImmutableContainerNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(schemaContext.getQName())) + .withChild(createTestContainer()).build(); + + } + + public static ContainerNode createTestContainer() { + + + // Create a list of shoes + // This is to test leaf list entry + final LeafSetEntryNode nike = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "shoe"), "nike")).withValue("nike").build(); + + final LeafSetEntryNode puma = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "shoe"), "puma")).withValue("puma").build(); - private static final YangInstanceIdentifier CHILDREN_2_PATH = YangInstanceIdentifier - .builder(CHILDREN_PATH) - .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID) // - .build(); - private static final YangInstanceIdentifier CHILDREN_2_NAME_PATH = - YangInstanceIdentifier.builder(CHILDREN_PATH) - .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, SECOND_CHILD_NAME) // + final LeafSetNode shoes = + ImmutableLeafSetNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(QName.create( + TEST_QNAME, "shoe"))).withChild(nike).withChild(puma) .build(); - private static final YangInstanceIdentifier GRAND_CHILD_1_PATH = - YangInstanceIdentifier.builder(CHILDREN_1_PATH) - .node(GRAND_CHILDREN_QNAME) - // - .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, - FIRST_GRAND_CHILD_ID) // - .build(); + // Test a leaf-list where each entry contains an identity + final LeafSetEntryNode cap1 = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "capability"), DESC_QNAME)) + .withValue(DESC_QNAME).build(); - private static final YangInstanceIdentifier GRAND_CHILD_1_NAME_PATH = - YangInstanceIdentifier.builder(CHILDREN_1_PATH) - .node(GRAND_CHILDREN_QNAME) - // - .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME, - FIRST_GRAND_CHILD_NAME) // - .build(); + final LeafSetNode capabilities = + ImmutableLeafSetNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(QName.create( + TEST_QNAME, "capability"))).withChild(cap1).build(); - private static final YangInstanceIdentifier GRAND_CHILD_2_PATH = - YangInstanceIdentifier.builder(CHILDREN_2_PATH) - .node(GRAND_CHILDREN_QNAME) - // - .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, - SECOND_GRAND_CHILD_ID) // - .build(); + ContainerNode switchFeatures = + ImmutableContainerNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(SWITCH_FEATURES_QNAME)) + .withChild(capabilities).build(); - private static final YangInstanceIdentifier GRAND_CHILD_2_NAME_PATH = - YangInstanceIdentifier.builder(CHILDREN_2_PATH) - .node(GRAND_CHILDREN_QNAME) - // - .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME, - SECOND_GRAND_CHILD_NAME) // + // Create a leaf list with numbers + final LeafSetEntryNode five = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + (new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "number"), 5))).withValue(5).build(); + final LeafSetEntryNode fifteen = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + (new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "number"), 15))).withValue(15).build(); + final LeafSetNode numbers = + ImmutableLeafSetNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(QName.create( + TEST_QNAME, "number"))).withChild(five).withChild(fifteen) .build(); - private static final YangInstanceIdentifier DESC_PATH_ID = YangInstanceIdentifier - .builder(DESC_PATH).build(); - private static final YangInstanceIdentifier OUTER_LIST_1_PATH = - YangInstanceIdentifier.builder(OUTER_LIST_PATH) - .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) // - .build(); - private static final YangInstanceIdentifier OUTER_LIST_2_PATH = - YangInstanceIdentifier.builder(OUTER_LIST_PATH) - .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) // - .build(); + // Create augmentations + MapEntryNode mapEntry = createAugmentedListEntry(1, "First Test"); - private static final YangInstanceIdentifier TWO_TWO_PATH = YangInstanceIdentifier - .builder(OUTER_LIST_2_PATH).node(INNER_LIST_QNAME) // - .nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) // - .build(); - private static final YangInstanceIdentifier TWO_TWO_VALUE_PATH = - YangInstanceIdentifier.builder(TWO_TWO_PATH).node(VALUE_QNAME) // - .build(); + // Create the document + return ImmutableContainerNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)) + .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC)) + .withChild(ImmutableNodes.leafNode(POINTER_QNAME, "pointer")) + .withChild( + ImmutableNodes.leafNode(SOME_REF_QNAME, YangInstanceIdentifier + .builder().build())) + .withChild(ImmutableNodes.leafNode(MYIDENTITY_QNAME, DESC_QNAME)) - private static final MapEntryNode BAR_NODE = mapEntryBuilder( - OUTER_LIST_QNAME, ID_QNAME, TWO_ID) // - .withChild(mapNodeBuilder(INNER_LIST_QNAME) // - .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) // - .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) // - .build()) // - .build(); - - public static final InputStream getDatastoreTestInputStream() { - return getInputStream(DATASTORE_TEST_YANG); - } - - public static final InputStream getDatastoreAugInputStream() { - return getInputStream(DATASTORE_AUG_YANG); - } - - public static final InputStream getDatastoreTestNotificationInputStream() { - return getInputStream(DATASTORE_TEST_NOTIFICATION_YANG); - } - - private static InputStream getInputStream(final String resourceName) { - return TestModel.class.getResourceAsStream(resourceName); - } - - public static SchemaContext createTestContext() { - List inputStreams = new ArrayList<>(); - inputStreams.add(getDatastoreTestInputStream()); - inputStreams.add(getDatastoreAugInputStream()); - inputStreams.add(getDatastoreTestNotificationInputStream()); - - YangParserImpl parser = new YangParserImpl(); - Set modules = parser.parseYangModelsFromStreams(inputStreams); - return parser.resolveSchemaContext(modules); - } - - /** - * Returns a test document - *

- *

-     * test
-     *     outer-list
-     *          id 1
-     *     outer-list
-     *          id 2
-     *          inner-list
-     *                  name "one"
-     *          inner-list
-     *                  name "two"
-     *
-     * 
- * - * @return - */ - public static NormalizedNode createDocumentOne( - SchemaContext schemaContext) { - return ImmutableContainerNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(schemaContext.getQName())) - .withChild(createTestContainer()).build(); - - } - - public static ContainerNode createTestContainer() { - - - // Create a list of shoes - // This is to test leaf list entry - final LeafSetEntryNode nike = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue( - QName.create(TEST_QNAME, - "shoe"), "nike") - ).withValue("nike").build(); - - final LeafSetEntryNode puma = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue( - QName.create(TEST_QNAME, - "shoe"), "puma") - ).withValue("puma").build(); - - final LeafSetNode shoes = - ImmutableLeafSetNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier( - QName.create(TEST_QNAME, - "shoe")) - ).withChild(nike).withChild(puma).build(); - - - // Test a leaf-list where each entry contains an identity - final LeafSetEntryNode cap1 = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue( - QName.create(TEST_QNAME, - "capability"), DESC_QNAME) - ).withValue(DESC_QNAME).build(); - - final LeafSetNode capabilities = - ImmutableLeafSetNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier( - QName.create(TEST_QNAME, - "capability")) - ).withChild(cap1).build(); - - ContainerNode switchFeatures = ImmutableContainerNodeBuilder - .create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier( - SWITCH_FEATURES_QNAME)) - .withChild(capabilities) - .build(); + // .withChild(augmentationNode) + .withChild(shoes) + .withChild(numbers) + .withChild(switchFeatures) + .withChild( + mapNodeBuilder(AUGMENTED_LIST_QNAME).withChild(mapEntry).build()) + .withChild( + mapNodeBuilder(OUTER_LIST_QNAME) + .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID)) + .withChild(BAR_NODE).build()).build(); + + } - // Create a leaf list with numbers - final LeafSetEntryNode five = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - (new YangInstanceIdentifier.NodeWithValue( - QName.create(TEST_QNAME, - "number"), 5)) - ).withValue(5).build(); - final LeafSetEntryNode fifteen = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - (new YangInstanceIdentifier.NodeWithValue( - QName.create(TEST_QNAME, - "number"), 15)) - ).withValue(15).build(); - final LeafSetNode numbers = - ImmutableLeafSetNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier( - QName.create(TEST_QNAME, - "number")) - ).withChild(five).withChild(fifteen).build(); - - - // Create augmentations - MapEntryNode mapEntry = createAugmentedListEntry(1, "First Test"); - - - // Create the document - return ImmutableContainerNodeBuilder + public static MapEntryNode createAugmentedListEntry(int id, String name) { + + Set childAugmentations = new HashSet<>(); + childAugmentations.add(AUG_CONT_QNAME); + + ContainerNode augCont = + ImmutableContainerNodeBuilder .create() .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)) - .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC)) - .withChild(ImmutableNodes.leafNode(POINTER_QNAME, "pointer")) - .withChild(ImmutableNodes.leafNode(SOME_REF_QNAME, - YangInstanceIdentifier.builder().build())) - .withChild(ImmutableNodes.leafNode(MYIDENTITY_QNAME, DESC_QNAME)) - - //.withChild(augmentationNode) - .withChild(shoes) - .withChild(numbers) - .withChild(switchFeatures) - .withChild(mapNodeBuilder(AUGMENTED_LIST_QNAME).withChild(mapEntry).build()) - .withChild( - mapNodeBuilder(OUTER_LIST_QNAME) - .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID)) - .withChild(BAR_NODE).build() - ).build(); - - } - - public static MapEntryNode createAugmentedListEntry(int id, String name) { - - Set childAugmentations = new HashSet<>(); - childAugmentations.add(AUG_CONT_QNAME); - - ContainerNode augCont = ImmutableContainerNodeBuilder - .create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(AUG_CONT_QNAME)) - .withChild(ImmutableNodes.leafNode(AUG_NAME_QNAME, name)) - .build(); + new YangInstanceIdentifier.NodeIdentifier(AUG_CONT_QNAME)) + .withChild(ImmutableNodes.leafNode(AUG_NAME_QNAME, name)).build(); - final YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier = - new YangInstanceIdentifier.AugmentationIdentifier(childAugmentations); + final YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier = + new YangInstanceIdentifier.AugmentationIdentifier(childAugmentations); - final AugmentationNode augmentationNode = - Builders.augmentationBuilder() - .withNodeIdentifier(augmentationIdentifier) - .withChild(augCont) - .build(); + final AugmentationNode augmentationNode = + Builders.augmentationBuilder() + .withNodeIdentifier(augmentationIdentifier).withChild(augCont) + .build(); - return ImmutableMapEntryNodeBuilder.create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifierWithPredicates( - AUGMENTED_LIST_QNAME, ID_QNAME, id)) - .withChild(ImmutableNodes.leafNode(ID_QNAME, id)) - .withChild(augmentationNode).build(); - } - - - public static ContainerNode createFamily() { - final DataContainerNodeAttrBuilder - familyContainerBuilder = - ImmutableContainerNodeBuilder.create().withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(FAMILY_QNAME)); - - final CollectionNodeBuilder childrenBuilder = - mapNodeBuilder(CHILDREN_QNAME); - - final DataContainerNodeBuilder - firstChildBuilder = - mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID); - final DataContainerNodeBuilder - secondChildBuilder = - mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, - SECOND_CHILD_ID); - - final DataContainerNodeBuilder - firstGrandChildBuilder = - mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, - FIRST_GRAND_CHILD_ID); - final DataContainerNodeBuilder - secondGrandChildBuilder = - mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, - SECOND_GRAND_CHILD_ID); - - firstGrandChildBuilder - .withChild( - ImmutableNodes.leafNode(GRAND_CHILD_NUMBER_QNAME, - FIRST_GRAND_CHILD_ID) - ).withChild( + return ImmutableMapEntryNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifierWithPredicates( + AUGMENTED_LIST_QNAME, ID_QNAME, id)) + .withChild(ImmutableNodes.leafNode(ID_QNAME, id)) + .withChild(augmentationNode).build(); + } + + + public static ContainerNode createFamily() { + final DataContainerNodeAttrBuilder familyContainerBuilder = + ImmutableContainerNodeBuilder.create().withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(FAMILY_QNAME)); + + final CollectionNodeBuilder childrenBuilder = + mapNodeBuilder(CHILDREN_QNAME); + + final DataContainerNodeBuilder firstChildBuilder = + mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID); + final DataContainerNodeBuilder secondChildBuilder = + mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID); + + final DataContainerNodeBuilder firstGrandChildBuilder = + mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, + FIRST_GRAND_CHILD_ID); + final DataContainerNodeBuilder secondGrandChildBuilder = + mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, + SECOND_GRAND_CHILD_ID); + + firstGrandChildBuilder + .withChild( + ImmutableNodes.leafNode(GRAND_CHILD_NUMBER_QNAME, + FIRST_GRAND_CHILD_ID)).withChild( ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME, - FIRST_GRAND_CHILD_NAME) - ); - - secondGrandChildBuilder.withChild( - ImmutableNodes - .leafNode(GRAND_CHILD_NUMBER_QNAME, SECOND_GRAND_CHILD_ID) - ) - .withChild( - ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME, - SECOND_GRAND_CHILD_NAME) - ); - - firstChildBuilder - .withChild( - ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, FIRST_CHILD_ID)) - .withChild( - ImmutableNodes.leafNode(CHILD_NAME_QNAME, FIRST_CHILD_NAME)) - .withChild( - mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild( - firstGrandChildBuilder.build()).build() - ); - - - secondChildBuilder - .withChild( - ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, SECOND_CHILD_ID)) - .withChild( - ImmutableNodes.leafNode(CHILD_NAME_QNAME, SECOND_CHILD_NAME)) - .withChild( - mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild( - firstGrandChildBuilder.build()).build() - ); - - childrenBuilder.withChild(firstChildBuilder.build()); - childrenBuilder.withChild(secondChildBuilder.build()); - - return familyContainerBuilder.withChild(childrenBuilder.build()) - .build(); - } + FIRST_GRAND_CHILD_NAME)); + + secondGrandChildBuilder.withChild( + ImmutableNodes + .leafNode(GRAND_CHILD_NUMBER_QNAME, SECOND_GRAND_CHILD_ID)) + .withChild( + ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME, + SECOND_GRAND_CHILD_NAME)); + + firstChildBuilder + .withChild(ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, FIRST_CHILD_ID)) + .withChild(ImmutableNodes.leafNode(CHILD_NAME_QNAME, FIRST_CHILD_NAME)) + .withChild( + mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild( + firstGrandChildBuilder.build()).build()); + + + secondChildBuilder + .withChild(ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, SECOND_CHILD_ID)) + .withChild(ImmutableNodes.leafNode(CHILD_NAME_QNAME, SECOND_CHILD_NAME)) + .withChild( + mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild( + firstGrandChildBuilder.build()).build()); + + childrenBuilder.withChild(firstChildBuilder.build()); + childrenBuilder.withChild(secondChildBuilder.build()); + + return familyContainerBuilder.withChild(childrenBuilder.build()).build(); + } } diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java new file mode 100644 index 0000000000..c6c4afd505 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java @@ -0,0 +1,77 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.protobuff.messages; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; + +/** + * @author: syedbahm Date: 7/31/14 + */ +public abstract class AbstractMessagesTest { + public final String VERSION_COMPATIBILTY_TEST_DATA_PATH = "." + + File.separator + "src" + File.separator + "test" + File.separator + + "resources" + File.separator + "version-compatibility-serialized-data"; + private File file; + private File testDataFile; + + protected AbstractMessagesTest() { + init(); + } + + protected void init() { + file = new File(getTestFileName()); + testDataFile = + new File(VERSION_COMPATIBILTY_TEST_DATA_PATH + File.separator + + getTestFileName() + "Data"); + } + + + + abstract public void verifySerialization() throws Exception; + + + protected void writeToFile( + com.google.protobuf.GeneratedMessage.Builder builder) throws Exception { + + FileOutputStream output = new FileOutputStream(file); + builder.build().writeTo(output); + output.close();; + + } + + protected com.google.protobuf.GeneratedMessage readFromFile( + com.google.protobuf.Parser parser) throws Exception { + com.google.protobuf.GeneratedMessage message = + (com.google.protobuf.GeneratedMessage) parser + .parseFrom(new FileInputStream(file)); + + /*Note: we will delete only the test file -- comment below if you want to capture the + version-compatibility-serialized-data test data file.The file will be generated at root of the + sal-protocolbuffer-encoding + and you need to move it to test/resources/version-compatbility-serialized-data folder renaming the file to include suffix "Data" + */ + file.delete(); + return message; + } + + protected com.google.protobuf.GeneratedMessage readFromTestDataFile( + com.google.protobuf.Parser parser) throws Exception { + return (com.google.protobuf.GeneratedMessage) parser + .parseFrom(new FileInputStream(testDataFile)); + } + + + public abstract String getTestFileName(); + + +} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/ShardManagerMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/ShardManagerMessagesTest.java deleted file mode 100644 index b0758da9d1..0000000000 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/ShardManagerMessagesTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.opendaylight.controller.protobuff.messages; - -/** - * This test case is present to ensure that if others have used proper version of protocol buffer. - * - * If a different version of protocol buffer is used then it would generate different java sources - * and would result in breaking of this test case. - * - * @author: syedbahm Date: 6/20/14 - * - */ - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; - -public class ShardManagerMessagesTest { - - @Test - public void verifySerialization() throws Exception { - ShardManagerMessages.FindPrimary.Builder builder = - ShardManagerMessages.FindPrimary.newBuilder(); - builder.setShardName("Inventory"); - File testFile = new File("./test"); - FileOutputStream output = new FileOutputStream(testFile); - builder.build().writeTo(output); - output.close(); - - // Here we will read the same and check we got back what we had saved - ShardManagerMessages.FindPrimary findPrimary = - ShardManagerMessages.FindPrimary - .parseFrom(new FileInputStream(testFile)); - Assert.assertEquals("Inventory", findPrimary.getShardName()); - - testFile.delete(); - - } -} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessagesTest.java new file mode 100644 index 0000000000..a01ccb88c7 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessagesTest.java @@ -0,0 +1,68 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.protobuff.messages.cohort3pc; + +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; + +/** + * This test case is present to ensure that if others have used proper version of protocol buffer + * for the cohort.proto messages + * + * If a different version of protocol buffer and there is change in serializaiton format + * this test would break as we are comparing with protocol buffer 2.5 generated + * serialized data. + * + * @author: syedbahm + * + */ + + +public class ThreePhaseCommitCohortMessagesTest extends AbstractMessagesTest { + + + @Test + public void verifySerialization() throws Exception { + + + + ThreePhaseCommitCohortMessages.CanCommitTransactionReply.Builder builder = + ThreePhaseCommitCohortMessages.CanCommitTransactionReply.newBuilder(); + builder.setCanCommit(true); + + writeToFile((com.google.protobuf.GeneratedMessage.Builder) builder); + + // Here we will read from the just serialized data + + ThreePhaseCommitCohortMessages.CanCommitTransactionReply newCanCommitTransactionReply = + (ThreePhaseCommitCohortMessages.CanCommitTransactionReply) readFromFile(ThreePhaseCommitCohortMessages.CanCommitTransactionReply.PARSER); + + Assert.assertTrue(newCanCommitTransactionReply.getCanCommit()); + + + // Here we will read the same from our test-data file and check we got back what we had saved + // earlier + ThreePhaseCommitCohortMessages.CanCommitTransactionReply originalCanCommitTransactionReply = + (ThreePhaseCommitCohortMessages.CanCommitTransactionReply) readFromTestDataFile(ThreePhaseCommitCohortMessages.CanCommitTransactionReply.PARSER); + + Assert.assertEquals(newCanCommitTransactionReply.getCanCommit(), + originalCanCommitTransactionReply.getCanCommit()); + + } + + @Override + public String getTestFileName() { + return ThreePhaseCommitCohortMessagesTest.class.getSimpleName(); + } + + +} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java new file mode 100644 index 0000000000..c68eceace4 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java @@ -0,0 +1,58 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.protobuff.messages.common; + +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; + +/** + * This test case is present to ensure that if others have used proper version of protocol buffer + * for the common.proto messages + * + * If a different version of protocol buffer and there is change in serializaiton format + * this test would break as we are comparing with protocol buffer 2.5 generated + * serialized data. + * + * @author: syedbahm + * + */ + +public class NormalizedNodeMessagesTest extends AbstractMessagesTest { + + @Override + @Test + public void verifySerialization() throws Exception { + NormalizedNodeMessages.Attribute.Builder builder = + NormalizedNodeMessages.Attribute.newBuilder(); + builder.setName("test"); + builder.setType("fake"); + builder.setValue("testValue"); + writeToFile((com.google.protobuf.GeneratedMessage.Builder) builder); + + NormalizedNodeMessages.Attribute attributeNew = + (NormalizedNodeMessages.Attribute) readFromFile(NormalizedNodeMessages.Attribute.PARSER); + Assert.assertEquals("test", attributeNew.getName()); + Assert.assertEquals("fake", attributeNew.getType()); + Assert.assertEquals("testValue", attributeNew.getValue()); + + NormalizedNodeMessages.Attribute attributeOriginal = + (NormalizedNodeMessages.Attribute) readFromTestDataFile(NormalizedNodeMessages.Attribute.PARSER); + Assert.assertEquals(attributeNew.getName(), attributeOriginal.getName()); + } + + @Override + public String getTestFileName() { + return NormalizedNodeMessagesTest.class.getSimpleName(); + } + + +} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessagesTest.java new file mode 100644 index 0000000000..e9339286f9 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessagesTest.java @@ -0,0 +1,78 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.protobuff.messages.datachange.notification; + +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; +import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; +import org.opendaylight.yangtools.yang.common.QName; + +/** + * This test case is present to ensure that if others have used proper version of protocol buffer + * for the DataChangeListener.proto messages + * + * If a different version of protocol buffer and there is change in serializaiton format + * this test would break as we are comparing with protocol buffer 2.5 generated + * serialized data. + * + * @author: syedbahm + * + */ + +public class DataChangeListenerMessagesTest extends AbstractMessagesTest { + + private final String namespace = "urn:protobuff", revision = "2014-07-31", + localName = "test"; + + @Override + @Test + public void verifySerialization() throws Exception { + NormalizedNodeMessages.InstanceIdentifier.Builder instanceIdentifierBuilder = + NormalizedNodeMessages.InstanceIdentifier.newBuilder(); + NormalizedNodeMessages.PathArgument.Builder pathArgument = + NormalizedNodeMessages.PathArgument.newBuilder(); + pathArgument.setNodeType(NormalizedNodeMessages.QName.newBuilder() + .setValue(QName.create(namespace, revision, localName).toString()) + .build()); + pathArgument.setValue("test"); + instanceIdentifierBuilder.addArguments(pathArgument.build()); + + NormalizedNodeMessages.InstanceIdentifier expectedOne = + instanceIdentifierBuilder.build(); + DataChangeListenerMessages.DataChanged.Builder builder = + DataChangeListenerMessages.DataChanged.newBuilder(); + builder.addRemovedPaths(expectedOne); + + writeToFile((com.google.protobuf.GeneratedMessage.Builder) builder); + + DataChangeListenerMessages.DataChanged dataChangedNew = + (DataChangeListenerMessages.DataChanged) readFromFile(DataChangeListenerMessages.DataChanged.PARSER); + Assert.assertEquals(expectedOne.getArgumentsCount(), dataChangedNew + .getRemovedPaths(0).getArgumentsCount()); + Assert.assertEquals(expectedOne.getArguments(0).getType(), dataChangedNew + .getRemovedPaths(0).getArguments(0).getType()); + + DataChangeListenerMessages.DataChanged dataChangedOriginal = + (DataChangeListenerMessages.DataChanged) readFromTestDataFile(DataChangeListenerMessages.DataChanged.PARSER); + Assert.assertEquals(dataChangedNew.getRemovedPathsCount(), + dataChangedOriginal.getRemovedPathsCount()); + Assert.assertEquals(dataChangedNew.getRemovedPaths(0).getArguments(0) + .getValue(), dataChangedOriginal.getRemovedPaths(0).getArguments(0) + .getValue()); + + } + + @Override + public String getTestFileName() { + return DataChangeListenerMessages.class.getSimpleName(); + } +} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessagesTest.java new file mode 100644 index 0000000000..a8ade30099 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessagesTest.java @@ -0,0 +1,82 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.protobuff.messages.persistent; + +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; +import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; +import org.opendaylight.yangtools.yang.common.QName; + + +/** + * This test case is present to ensure that if others have used proper version of protocol buffer + * for the peristent.proto messages + * + * If a different version of protocol buffer and there is change in serializaiton format + * this test would break as we are comparing with protocol buffer 2.5 generated + * serialized data. + * + * @author: syedbahm + * + */ + +public class PersistentMessagesTest extends AbstractMessagesTest { + + private final String namespace = "urn:protobuff", revision = "2014-07-31", + localName = "test"; + + @Override + @Test + public void verifySerialization() throws Exception { + NormalizedNodeMessages.InstanceIdentifier.Builder instanceIdentifierBuilder = + NormalizedNodeMessages.InstanceIdentifier.newBuilder(); + NormalizedNodeMessages.PathArgument.Builder pathArgument = + NormalizedNodeMessages.PathArgument.newBuilder(); + pathArgument.setNodeType(NormalizedNodeMessages.QName.newBuilder() + .setValue(QName.create(namespace, revision, localName).toString()) + .build()); + pathArgument.setValue("test"); + instanceIdentifierBuilder.addArguments(pathArgument.build()); + NormalizedNodeMessages.InstanceIdentifier expectedOne = + instanceIdentifierBuilder.build(); + + PersistentMessages.Modification.Builder builder = + PersistentMessages.Modification.newBuilder(); + builder.setType("test"); + builder.setPath(expectedOne); + + writeToFile((com.google.protobuf.GeneratedMessage.Builder) builder); + + PersistentMessages.Modification modificationNew = + (PersistentMessages.Modification) readFromFile(PersistentMessages.Modification.PARSER); + Assert.assertEquals("test", modificationNew.getType()); + Assert.assertEquals(expectedOne.getArguments(0).getValue(), modificationNew + .getPath().getArguments(0).getValue()); + Assert.assertEquals(expectedOne.getArguments(0).getType(), modificationNew + .getPath().getArguments(0).getType()); + + // we will compare with the serialized data that we had shipped + PersistentMessages.Modification modificationOriginal = + (PersistentMessages.Modification) readFromTestDataFile(PersistentMessages.Modification.PARSER); + Assert.assertEquals(modificationOriginal.getPath().getArguments(0) + .getValue(), modificationNew.getPath().getArguments(0).getValue()); + Assert.assertEquals(modificationOriginal.getPath().getArguments(0) + .getType(), modificationNew.getPath().getArguments(0).getType()); + + + } + + @Override + public String getTestFileName() { + return PersistentMessagesTest.class.getSimpleName(); + } +} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessagesTest.java new file mode 100644 index 0000000000..1d50872a66 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessagesTest.java @@ -0,0 +1,58 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.protobuff.messages.registration; + +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; + +/** + * This test case is present to ensure that if others have used proper version of protocol buffer + * for the ListenerRegistration.proto messages + * + * If a different version of protocol buffer and there is change in serializaiton format + * this test would break as we are comparing with protocol buffer 2.5 generated + * serialized data. + * + * @author: syedbahm + * + */ + +public class ListenerRegistrationMessagesTest extends AbstractMessagesTest { + + @Override + @Test + public void verifySerialization() throws Exception { + String testListenerRegistrationPath = + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test?revision=2014-04-15)family"; + ListenerRegistrationMessages.RegisterChangeListenerReply.Builder builder = + ListenerRegistrationMessages.RegisterChangeListenerReply.newBuilder(); + builder.setListenerRegistrationPath(testListenerRegistrationPath); + + writeToFile((com.google.protobuf.GeneratedMessage.Builder) builder); + + ListenerRegistrationMessages.RegisterChangeListenerReply rclrNew = + (ListenerRegistrationMessages.RegisterChangeListenerReply) readFromFile(ListenerRegistrationMessages.RegisterChangeListenerReply.PARSER); + Assert.assertEquals(testListenerRegistrationPath, + rclrNew.getListenerRegistrationPath()); + + ListenerRegistrationMessages.RegisterChangeListenerReply rclrOriginal = + (ListenerRegistrationMessages.RegisterChangeListenerReply) readFromTestDataFile(ListenerRegistrationMessages.RegisterChangeListenerReply.PARSER); + Assert.assertEquals(rclrOriginal.getListenerRegistrationPath(), + rclrNew.getListenerRegistrationPath()); + + } + + @Override + public String getTestFileName() { + return ListenerRegistrationMessages.class.getSimpleName(); + } +} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessagesTest.java new file mode 100644 index 0000000000..45dcd12d05 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessagesTest.java @@ -0,0 +1,61 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.protobuff.messages.shard; + +/** + * This test case is present to ensure that if others have used proper version of protocol buffer + * for the ShardManager.proto messages + * + * If a different version of protocol buffer and there is change in serializaiton format + * this test would break as we are comparing with protocol buffer 2.5 generated + * serialized data. + * + * @author: syedbahm + * + */ + +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; + +public class ShardManagerMessagesTest extends AbstractMessagesTest { + + @Test + public void verifySerialization() throws Exception { + ShardManagerMessages.FindPrimary.Builder builder = + ShardManagerMessages.FindPrimary.newBuilder(); + builder.setShardName("Inventory"); + + writeToFile((com.google.protobuf.GeneratedMessage.Builder) builder); + + + // Here we will read the same and check we got back what we had saved + ShardManagerMessages.FindPrimary findPrimaryNew = + (ShardManagerMessages.FindPrimary) readFromFile(ShardManagerMessages.FindPrimary.PARSER); + + Assert.assertEquals("Inventory", findPrimaryNew.getShardName()); + + // Here we compare with the version we had shipped to catch any protobuff compiler version + // changes + ShardManagerMessages.FindPrimary findPrimaryOriginal = + (ShardManagerMessages.FindPrimary) readFromTestDataFile(ShardManagerMessages.FindPrimary.PARSER); + + Assert.assertEquals(findPrimaryNew.getShardName(), + findPrimaryOriginal.getShardName()); + + } + + @Override + public String getTestFileName() { + return ShardManagerMessagesTest.class.getSimpleName(); + } + +} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessagesTest.java new file mode 100644 index 0000000000..c0e91ab0d0 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessagesTest.java @@ -0,0 +1,69 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.protobuff.messages.transaction; + +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; +import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; +import org.opendaylight.yangtools.yang.common.QName; + +/** + * This test case is present to ensure that if others have used proper version of protocol buffer + * for the ShardTransactionChain.proto messages + * + * If a different version of protocol buffer and there is change in serializaiton format + * this test would break as we are comparing with protocol buffer 2.5 generated + * serialized data. + * + * @author: syedbahm + * + */ + + +public class ShardTransactionChainMessagesTest extends AbstractMessagesTest { + + @Override + @Test + public void verifySerialization() throws Exception { + String testTransactionChainPath = + "/actor/path"; + + ShardTransactionChainMessages.CreateTransactionChainReply.Builder builder = + ShardTransactionChainMessages.CreateTransactionChainReply.newBuilder(); + builder.setTransactionChainPath(testTransactionChainPath); + + writeToFile((com.google.protobuf.GeneratedMessage.Builder) builder); + + // Here we will read the same and check we got back what we had saved + ShardTransactionChainMessages.CreateTransactionChainReply replyNew = + (ShardTransactionChainMessages.CreateTransactionChainReply) readFromFile(ShardTransactionChainMessages.CreateTransactionChainReply.PARSER); + + Assert.assertEquals(replyNew.getTransactionChainPath(),testTransactionChainPath); + + // the following will compare with the version we had shipped + ShardTransactionChainMessages.CreateTransactionChainReply replyOriginal = + (ShardTransactionChainMessages.CreateTransactionChainReply) readFromTestDataFile(ShardTransactionChainMessages.CreateTransactionChainReply.PARSER); + + + Assert.assertEquals(replyOriginal.getTransactionChainPath(), + replyNew.getTransactionChainPath()); + + } + + @Override + public String getTestFileName() { + return ShardTransactionChainMessagesTest.class.getSimpleName(); + } + + + +} diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessagesTest.java index 2b1ee5630c..6b538dab0d 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessagesTest.java +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessagesTest.java @@ -1,10 +1,85 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + package org.opendaylight.controller.protobuff.messages.transaction; +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; +import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; +import org.opendaylight.yangtools.yang.common.QName; + /** + * This test case is present to ensure that if others have used proper version of protocol buffer + * for the ShardTransaction.proto messages + * + * If a different version of protocol buffer and there is change in serializaiton format + * this test would break as we are comparing with protocol buffer 2.5 generated + * serialized data. + * * @author: syedbahm - * Date: 7/7/14 + * */ -public class ShardTransactionMessagesTest { + + +public class ShardTransactionMessagesTest extends AbstractMessagesTest { + + private final String namespace = "urn:protobuff", revision = "2014-07-31", + localName = "test"; + + @Test + public void verifySerialization() throws Exception { + NormalizedNodeMessages.InstanceIdentifier.Builder instanceIdentifierBuilder = + NormalizedNodeMessages.InstanceIdentifier.newBuilder(); + NormalizedNodeMessages.PathArgument.Builder pathArgument = + NormalizedNodeMessages.PathArgument.newBuilder(); + pathArgument.setNodeType(NormalizedNodeMessages.QName.newBuilder() + .setValue(QName.create(namespace, revision, localName).toString()) + .build()); + pathArgument.setValue("test"); + instanceIdentifierBuilder.addArguments(pathArgument.build()); + ShardTransactionMessages.ReadData.Builder builder = + ShardTransactionMessages.ReadData.newBuilder(); + NormalizedNodeMessages.InstanceIdentifier expectedOne = + instanceIdentifierBuilder.build(); + builder.setInstanceIdentifierPathArguments(expectedOne); + + writeToFile((com.google.protobuf.GeneratedMessage.Builder) builder); + + // Here we will read the same and check we got back what we had saved + ShardTransactionMessages.ReadData readDataNew = + (ShardTransactionMessages.ReadData) readFromFile(ShardTransactionMessages.ReadData.PARSER); + + + Assert.assertEquals(expectedOne.getArgumentsCount(), readDataNew + .getInstanceIdentifierPathArguments().getArgumentsCount()); + Assert.assertEquals(expectedOne.getArguments(0), readDataNew + .getInstanceIdentifierPathArguments().getArguments(0)); + + + // the following will compare with the version we had shipped + ShardTransactionMessages.ReadData readDataOriginal = + (ShardTransactionMessages.ReadData) readFromTestDataFile(ShardTransactionMessages.ReadData.PARSER); + + + Assert.assertEquals(readDataNew.getInstanceIdentifierPathArguments() + .getArguments(0), readDataOriginal.getInstanceIdentifierPathArguments() + .getArguments(0)); + + } + + @Override + public String getTestFileName() { + return ShardTransactionMessagesTest.class.getSimpleName(); + } + } diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.xml b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.xml index c5a581cecc..7de3d077b4 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.xml +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.xml @@ -1,3 +1,13 @@ + + 2 diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/simple_xml_with_attributes.xml b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/simple_xml_with_attributes.xml index 0316d7a4a8..934d876747 100644 --- a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/simple_xml_with_attributes.xml +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/simple_xml_with_attributes.xml @@ -1,3 +1,13 @@ + + diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/DataChangeListenerMessagesData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/DataChangeListenerMessagesData new file mode 100644 index 0000000000..883bcad86c --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/DataChangeListenerMessagesData @@ -0,0 +1,4 @@ +23 +1 +test) +'(urn:protobuff?revision=2014-07-31)test \ No newline at end of file diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ListenerRegistrationMessagesData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ListenerRegistrationMessagesData new file mode 100644 index 0000000000..1718a01d48 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ListenerRegistrationMessagesData @@ -0,0 +1,2 @@ + +m(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test?revision=2014-04-15)family \ No newline at end of file diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/NormalizedNodeMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/NormalizedNodeMessagesTestData new file mode 100644 index 0000000000..c4ec3776d2 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/NormalizedNodeMessagesTestData @@ -0,0 +1,2 @@ + +test testValuefake \ No newline at end of file diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/PersistentMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/PersistentMessagesTestData new file mode 100644 index 0000000000..efb8e15bcc --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/PersistentMessagesTestData @@ -0,0 +1,5 @@ + +test3 +1 +test) +'(urn:protobuff?revision=2014-07-31)test \ No newline at end of file diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardManagerMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardManagerMessagesTestData new file mode 100644 index 0000000000..82eea07964 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardManagerMessagesTestData @@ -0,0 +1,2 @@ + + Inventory \ No newline at end of file diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionChainMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionChainMessagesTestData new file mode 100644 index 0000000000..577d9c4efc --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionChainMessagesTestData @@ -0,0 +1,2 @@ + + /actor/path \ No newline at end of file diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionMessagesTestData new file mode 100644 index 0000000000..db43fa48f4 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionMessagesTestData @@ -0,0 +1,5 @@ + +3 +1 +test) +'(urn:protobuff?revision=2014-07-31)test \ No newline at end of file diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ThreePhaseCommitCohortMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ThreePhaseCommitCohortMessagesTestData new file mode 100644 index 0000000000..e19a122a54 --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ThreePhaseCommitCohortMessagesTestData @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/readme.txt b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/readme.txt new file mode 100644 index 0000000000..06a561e36c --- /dev/null +++ b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/readme.txt @@ -0,0 +1,18 @@ +This directory contains one serialized test data file for one of the messages in each .proto file. +These files are utilized as part of the test cases, mostly to fail the test cases in case some engineer has used +a different version of protocol buffer than what we ship with (Protocol Buffer 2.5.0) to generate the messages source f +file. + +1. If you see protocolbuffer version/invalid message exception in the test case + 1. ensure you are using the right version of protocol buffer/protoc compiler i.e protocol + +2. If you have knowingly updated an existing .proto message than please update the corresponding version-compatibility-serialized-data +file. You can get the file by commenting out the test file deletion in AbstractMessagesTest look for comments + + /* we will delete only the test file -- comment below if you want to capture the + version-compatibility-serialized-data test data file.The file will be generated at root of the sal-protocolbuffer-encoding + and you need to move it to version-compatbility-serialized-data folder renaming the file to include suffix "Data" + */ + +3. If you are creating a new .proto file -- Follow an existing test case e.g. ThreePhaseCommitCohortMessagesTest to + check how the test case is created and create the corresponding serialized test data file in version-compatibility-serialized-data diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/ActorConstants.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/ActorConstants.java new file mode 100644 index 0000000000..1f1a0f5cc6 --- /dev/null +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/ActorConstants.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.remote.rpc; + + +public class ActorConstants { + public static final String RPC_BROKER = "rpc-broker"; + public static final String RPC_REGISTRY = "rpc-registry"; + public static final String RPC_MANAGER = "rpc"; + + public static final String RPC_BROKER_PATH= "/user/rpc/rpc-broker"; + public static final String RPC_REGISTRY_PATH = "/user/rpc/rpc-registry"; +} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RemoteRpcProvider.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RemoteRpcProvider.java index 3df572d7c2..ac50b8fe5b 100644 --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RemoteRpcProvider.java +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RemoteRpcProvider.java @@ -68,7 +68,7 @@ public class RemoteRpcProvider implements AutoCloseable, Provider, SchemaContext SchemaService schemaService = brokerSession.getService(SchemaService.class); schemaContext = schemaService.getGlobalContext(); - rpcManager = actorSystem.actorOf(RpcManager.props(clusterWrapper, schemaContext, brokerSession, rpcProvisionRegistry), "rpc"); + rpcManager = actorSystem.actorOf(RpcManager.props(clusterWrapper, schemaContext, brokerSession, rpcProvisionRegistry), ActorConstants.RPC_MANAGER); LOG.debug("Rpc actors are created."); } diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java index 4925a17c13..5c56455bd0 100644 --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java @@ -72,14 +72,14 @@ public class RpcManager extends AbstractUntypedActor { private void createRpcActors() { LOG.debug("Create rpc registry and broker actors"); - rpcRegistry = getContext().actorOf(RpcRegistry.props(clusterWrapper), "rpc-registry"); - rpcBroker = getContext().actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), "rpc-broker"); + rpcRegistry = getContext().actorOf(RpcRegistry.props(clusterWrapper), ActorConstants.RPC_REGISTRY); + rpcBroker = getContext().actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), ActorConstants.RPC_BROKER); } private void startListeners() { LOG.debug("Registers rpc listeners"); - String rpcBrokerPath = clusterWrapper.getAddress().toString() + "/user/rpc/rpc-broker"; + String rpcBrokerPath = clusterWrapper.getAddress().toString() + ActorConstants.RPC_BROKER_PATH; rpcListener = new RpcListener(rpcRegistry, rpcBrokerPath); routeChangeListener = new RoutedRpcListener(rpcRegistry, rpcBrokerPath); rpcImplementation = new RemoteRpcImplementation(rpcBroker, schemaContext); diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistry.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistry.java index 7cb505aa98..e36060cc13 100644 --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistry.java +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistry.java @@ -14,6 +14,7 @@ import akka.cluster.ClusterEvent; import akka.cluster.Member; import akka.japi.Creator; import org.opendaylight.controller.remote.rpc.AbstractUntypedActor; +import org.opendaylight.controller.remote.rpc.ActorConstants; import org.opendaylight.controller.remote.rpc.messages.AddRoutedRpc; import org.opendaylight.controller.remote.rpc.messages.AddRpc; import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpc; @@ -171,7 +172,7 @@ public class RpcRegistry extends AbstractUntypedActor { } if(i == index) { if(!currentNodeAddress.equals(member.address())) { - actor = this.context().actorSelection(member.address() + "/user/rpc-registry"); + actor = this.context().actorSelection(member.address() + ActorConstants.RPC_REGISTRY_PATH); break; } else if(index < memberSize-1){ // pick the next element in the set index++; @@ -180,7 +181,7 @@ public class RpcRegistry extends AbstractUntypedActor { i++; } if(actor == null && previousMember != null) { - actor = this.context().actorSelection(previousMember.address() + "/user/rpc-registry"); + actor = this.context().actorSelection(previousMember.address() + ActorConstants.RPC_REGISTRY_PATH); } } return actor; diff --git a/opendaylight/md-sal/sal-rest-connector/pom.xml b/opendaylight/md-sal/sal-rest-connector/pom.xml index 09fb5b3677..2856a302d2 100644 --- a/opendaylight/md-sal/sal-rest-connector/pom.xml +++ b/opendaylight/md-sal/sal-rest-connector/pom.xml @@ -105,6 +105,11 @@ org.opendaylight.controller sal-core-spi + + org.opendaylight.yangtools + yang-data-composite-node + 0.6.2-SNAPSHOT + diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/rest/connector/RestConnectorModule.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/rest/connector/RestConnectorModule.java index 582c657868..52115a8f32 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/rest/connector/RestConnectorModule.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/rest/connector/RestConnectorModule.java @@ -2,6 +2,7 @@ package org.opendaylight.controller.config.yang.md.sal.rest.connector; import org.opendaylight.controller.sal.rest.impl.RestconfProviderImpl; + public class RestConnectorModule extends org.opendaylight.controller.config.yang.md.sal.rest.connector.AbstractRestConnectorModule { public RestConnectorModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { @@ -28,3 +29,4 @@ public class RestConnectorModule extends org.opendaylight.controller.config.yang return instance; } } + diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/rest/connector/RestConnectorModuleFactory.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/rest/connector/RestConnectorModuleFactory.java index 957b08f6ae..1964a17472 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/rest/connector/RestConnectorModuleFactory.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/rest/connector/RestConnectorModuleFactory.java @@ -9,7 +9,6 @@ */ package org.opendaylight.controller.config.yang.md.sal.rest.connector; - public class RestConnectorModuleFactory extends org.opendaylight.controller.config.yang.md.sal.rest.connector.AbstractRestConnectorModuleFactory { } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java index a6c4ea5ab8..9c149a21e6 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java @@ -23,6 +23,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.opendaylight.controller.sal.restconf.impl.StructuredData; import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; /** * The URI hierarchy for the RESTCONF resources consists of an entry point container, 4 top-level resources, and 1 @@ -30,15 +31,18 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode; *
    *
  • /restconf - {@link #getRoot()} *
      - *
    • /config - {@link #readConfigurationData(String)} {@link #updateConfigurationData(String, CompositeNode)} - * {@link #createConfigurationData(CompositeNode)} {@link #createConfigurationData(String, CompositeNode)} + *
    • /config - {@link #readConfigurationData(String)} + * {@link #updateConfigurationData(String, CompositeNode)} + * {@link #createConfigurationData(CompositeNode)} + * {@link #createConfigurationData(String, CompositeNode)} * {@link #deleteConfigurationData(String)} *
    • /operational - {@link #readOperationalData(String)} *
    • /modules - {@link #getModules()} *
        *
      • /module *
      - *
    • /operations - {@link #invokeRpc(String, CompositeNode)} {@link #invokeRpc(String, CompositeNode)} + *
    • /operations - {@link #invokeRpc(String, CompositeNode)} + * {@link #invokeRpc(String, CompositeNode)} *
    • /version (field) *
    *
@@ -119,19 +123,19 @@ public interface RestconfService { @Path("/config/{identifier:.+}") @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) - public Response updateConfigurationData(@Encoded @PathParam("identifier") String identifier, CompositeNode payload); + public Response updateConfigurationData(@Encoded @PathParam("identifier") String identifier, Node payload); @POST @Path("/config/{identifier:.+}") @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) - public Response createConfigurationData(@Encoded @PathParam("identifier") String identifier, CompositeNode payload); + public Response createConfigurationData(@Encoded @PathParam("identifier") String identifier, Node payload); @POST @Path("/config") @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) - public Response createConfigurationData(CompositeNode payload); + public Response createConfigurationData(Node payload); @DELETE @Path("/config/{identifier:.+}") diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java index 34aa829b6f..863de10325 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java @@ -19,7 +19,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; import javax.activation.UnsupportedDataTypeException; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue; @@ -52,9 +52,9 @@ import org.slf4j.LoggerFactory; class JsonMapper { private static final Logger LOG = LoggerFactory.getLogger(JsonMapper.class); - private final MountInstance mountPoint; + private final DOMMountPoint mountPoint; - public JsonMapper(final MountInstance mountPoint) { + public JsonMapper(final DOMMountPoint mountPoint) { this.mountPoint = mountPoint; } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java index 2f3499e269..caff848180 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java @@ -22,14 +22,14 @@ import org.opendaylight.controller.sal.rest.api.RestconfService; import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Provider @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON }) -public enum JsonToCompositeNodeProvider implements MessageBodyReader { +public enum JsonToCompositeNodeProvider implements MessageBodyReader> { INSTANCE; private final static Logger LOG = LoggerFactory.getLogger(JsonToCompositeNodeProvider.class); @@ -41,7 +41,7 @@ public enum JsonToCompositeNodeProvider implements MessageBodyReader type, final Type genericType, + public Node readFrom(final Class> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException { diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProviderImpl.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProviderImpl.java index 559be5aa6f..2fa99819d5 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProviderImpl.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProviderImpl.java @@ -9,12 +9,11 @@ package org.opendaylight.controller.sal.rest.impl; import java.util.Collection; import java.util.Collections; - +import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.controller.sal.core.api.Broker.ProviderSession; import org.opendaylight.controller.sal.core.api.Provider; -import org.opendaylight.controller.sal.core.api.data.DataBrokerService; import org.opendaylight.controller.sal.core.api.model.SchemaService; -import org.opendaylight.controller.sal.core.api.mount.MountService; import org.opendaylight.controller.sal.rest.api.RestConnector; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; @@ -37,15 +36,15 @@ public class RestconfProviderImpl implements Provider, AutoCloseable, RestConnec @Override public void onSessionInitiated(ProviderSession session) { - DataBrokerService dataService = session.getService(DataBrokerService.class); + final DOMDataBroker domDataBroker = session.getService(DOMDataBroker.class); BrokerFacade.getInstance().setContext(session); - BrokerFacade.getInstance().setDataService(dataService); + BrokerFacade.getInstance().setDomDataBroker( domDataBroker); SchemaService schemaService = session.getService(SchemaService.class); listenerRegistration = schemaService.registerSchemaContextListener(ControllerContext.getInstance()); ControllerContext.getInstance().setSchemas(schemaService.getGlobalContext()); - ControllerContext.getInstance().setMountService(session.getService(MountService.class)); + ControllerContext.getInstance().setMountService(session.getService(DOMMountPointService.class)); webSocketServerThread = new Thread(WebSocketServer.createInstance(port.getValue().intValue())); webSocketServerThread.setName("Web socket server on port " + port); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeProvider.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeProvider.java index 31e9c96462..d56a32e36e 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeProvider.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeProvider.java @@ -23,25 +23,25 @@ import org.opendaylight.controller.sal.rest.api.RestconfService; import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Provider @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) -public enum XmlToCompositeNodeProvider implements MessageBodyReader { +public enum XmlToCompositeNodeProvider implements MessageBodyReader> { INSTANCE; - private final static Logger LOG = LoggerFactory.getLogger(XmlToCompositeNodeProvider.class); @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + public boolean isReadable(final Class type, final Type genericType, final Annotation[] annotations, + final MediaType mediaType) { return true; } @Override - public CompositeNode readFrom(Class type, Type genericType, Annotation[] annotations, + public Node readFrom(final Class> type, final Type genericType, final Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { XmlToCompositeNodeReader xmlReader = new XmlToCompositeNodeReader(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java index 413823f520..5944d6003e 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java @@ -33,10 +33,11 @@ public class XmlToCompositeNodeReader { private final static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); private XMLEventReader eventReader; - public CompositeNodeWrapper read(InputStream entityStream) throws XMLStreamException, UnsupportedFormatException, - IOException { - // Get an XML stream which can be marked, and reset, so we can check and - // see if there is any content being provided. + public Node read(InputStream entityStream) throws XMLStreamException, + UnsupportedFormatException, + IOException { + //Get an XML stream which can be marked, and reset, so we can check and see if there is + //any content being provided. entityStream = getMarkableStream(entityStream); if (isInputStreamEmpty(entityStream)) { @@ -52,12 +53,8 @@ public class XmlToCompositeNodeReader { } } - if (eventReader.hasNext() && !isCompositeNodeEvent(eventReader.peek())) { - throw new UnsupportedFormatException("Root element of XML has to be composite element."); - } - final Stack> processingQueue = new Stack<>(); - CompositeNodeWrapper root = null; + NodeWrapper root = null; NodeWrapper element = null; while (eventReader.hasNext()) { final XMLEvent event = eventReader.nextEvent(); @@ -70,17 +67,15 @@ public class XmlToCompositeNodeReader { } NodeWrapper newNode = null; if (isCompositeNodeEvent(event)) { + newNode = resolveCompositeNodeFromStartElement(startElement); if (root == null) { - root = resolveCompositeNodeFromStartElement(startElement); - newNode = root; - } else { - newNode = resolveCompositeNodeFromStartElement(startElement); + root = newNode; } } else if (isSimpleNodeEvent(event)) { + newNode = resolveSimpleNodeFromStartElement(startElement); if (root == null) { - throw new UnsupportedFormatException("Root element of XML has to be composite element."); + root = newNode; } - newNode = resolveSimpleNodeFromStartElement(startElement); } if (newNode != null) { @@ -98,7 +93,7 @@ public class XmlToCompositeNodeReader { throw new UnsupportedFormatException("XML should contain only one root element"); } - return root; + return (Node) root; } /** diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToNormalizedNodeReaderWithSchema.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToNormalizedNodeReaderWithSchema.java new file mode 100644 index 0000000000..935d96cb12 --- /dev/null +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToNormalizedNodeReaderWithSchema.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.sal.rest.impl; + +import static com.google.common.base.Preconditions.checkArgument; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; +import java.util.Stack; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.Characters; +import javax.xml.stream.events.StartElement; +import javax.xml.stream.events.XMLEvent; +import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper; +import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO; +import org.opendaylight.controller.sal.restconf.impl.InstanceIdWithSchemaNode; +import org.opendaylight.controller.sal.restconf.impl.NodeWrapper; +import org.opendaylight.controller.sal.restconf.impl.RestCodec; +import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; +import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; +import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType; +import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.data.api.Node; +import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; +import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; +import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; +import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; +import org.opendaylight.yangtools.yang.model.api.TypeDefinition; + +public class XmlToNormalizedNodeReaderWithSchema { + + private final static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); + private XMLEventReader eventReader; + private InstanceIdWithSchemaNode iiWithSchema; + + public XmlToNormalizedNodeReaderWithSchema(final InstanceIdWithSchemaNode iiWithSchema) { + this.iiWithSchema = iiWithSchema; + } + + public Node read(InputStream entityStream) throws XMLStreamException, UnsupportedFormatException, IOException { + // Get an XML stream which can be marked, and reset, so we can check and see if there is + // any content being provided. + entityStream = getMarkableStream(entityStream); + + if (isInputStreamEmpty(entityStream)) { + return null; + } + + eventReader = xmlInputFactory.createXMLEventReader(entityStream); + if (eventReader.hasNext()) { + XMLEvent element = eventReader.peek(); + if (element.isStartDocument()) { + eventReader.nextEvent(); + } + } + + final Stack> processingQueue = new Stack<>(); + NodeWrapper root = null; + NodeWrapper element = null; + Stack processingQueueSchema = new Stack<>(); + + while (eventReader.hasNext()) { + final XMLEvent event = eventReader.nextEvent(); + + if (event.isStartElement()) { + final StartElement startElement = event.asStartElement(); + CompositeNodeWrapper compParentNode = null; + if (!processingQueue.isEmpty() && processingQueue.peek() instanceof CompositeNodeWrapper) { + compParentNode = (CompositeNodeWrapper) processingQueue.peek(); + findSchemaNodeForElement(startElement, processingQueueSchema); + } else { + processingQueueSchema = checkElementAndSchemaNodeNameAndNamespace(startElement, + iiWithSchema.getSchemaNode()); + DataSchemaNode currentSchemaNode = processingQueueSchema.peek(); + if (!(currentSchemaNode instanceof ListSchemaNode) + && !(currentSchemaNode instanceof ContainerSchemaNode)) { + throw new UnsupportedFormatException( + "Top level element has to be of type list or container schema node."); + } + } + + NodeWrapper newNode = null; + if (isCompositeNodeEvent(event)) { + newNode = resolveCompositeNodeFromStartElement(processingQueueSchema.peek().getQName()); + if (root == null) { + root = newNode; + } + } else if (isSimpleNodeEvent(event)) { + newNode = resolveSimpleNodeFromStartElement(processingQueueSchema.peek(), getValueOf(startElement)); + if (root == null) { + root = newNode; + } + } + + if (newNode != null) { + processingQueue.push(newNode); + if (compParentNode != null) { + compParentNode.addValue(newNode); + } + } + } else if (event.isEndElement()) { + element = processingQueue.pop(); +// if(((EndElement)event).getName().getLocalPart().equals + processingQueueSchema.pop(); + } + } + + if (!root.getLocalName().equals(element.getLocalName())) { + throw new UnsupportedFormatException("XML should contain only one root element"); + } + + return root.unwrap(); + } + + private void findSchemaNodeForElement(StartElement element, Stack processingQueueSchema) { + DataSchemaNode currentSchemaNode = processingQueueSchema.peek(); + if (currentSchemaNode instanceof DataNodeContainer) { + final URI realNamespace = getNamespaceFor(element); + final String realName = getLocalNameFor(element); + Map childNamesakes = resolveChildsWithNameAsElement( + ((DataNodeContainer) currentSchemaNode), realName); + DataSchemaNode childDataSchemaNode = childNamesakes.get(realNamespace); + if (childDataSchemaNode == null) { + throw new RestconfDocumentedException("Element " + realName + " has namespace " + realNamespace + + ". Available namespaces are: " + childNamesakes.keySet(), ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE); + } + processingQueueSchema.push(childDataSchemaNode); + } else { + throw new RestconfDocumentedException("Element " + processingQueueSchema.peek().getQName().getLocalName() + + " should be data node container .", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE); + } + + } + + /** + * Returns map of data schema node which are accesible by URI which have equal name + */ + private Map resolveChildsWithNameAsElement(final DataNodeContainer dataNodeContainer, + final String realName) { + final Map namespaceToDataSchemaNode = new HashMap(); + for (DataSchemaNode dataSchemaNode : dataNodeContainer.getChildNodes()) { + if (dataSchemaNode.equals(realName)) { + namespaceToDataSchemaNode.put(dataSchemaNode.getQName().getNamespace(), dataSchemaNode); + } + } + return namespaceToDataSchemaNode; + } + + private final Stack checkElementAndSchemaNodeNameAndNamespace(final StartElement startElement, + final DataSchemaNode node) { + checkArgument(startElement != null, "Start Element cannot be NULL!"); + final String expectedName = node.getQName().getLocalName(); + final String xmlName = getLocalNameFor(startElement); + final URI expectedNamespace = node.getQName().getNamespace(); + final URI xmlNamespace = getNamespaceFor(startElement); + if (!expectedName.equals(xmlName)) { + throw new RestconfDocumentedException("Xml element name: " + xmlName + "\nSchema node name: " + + expectedName, org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE); + } + + if (xmlNamespace != null && !expectedNamespace.equals(xmlNamespace)) { + throw new RestconfDocumentedException("Xml element ns: " + xmlNamespace + "\nSchema node ns: " + + expectedNamespace, + org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE); + } + Stack processingQueueSchema = new Stack<>(); + processingQueueSchema.push(node); + return processingQueueSchema; + } + + /** + * If the input stream is not markable, then it wraps the input stream with a buffered stream, which is mark able. + * That way we can check if the stream is empty safely. + * + * @param entityStream + * @return + */ + private InputStream getMarkableStream(InputStream entityStream) { + if (!entityStream.markSupported()) { + entityStream = new BufferedInputStream(entityStream); + } + return entityStream; + } + + private boolean isInputStreamEmpty(final InputStream entityStream) throws IOException { + boolean isEmpty = false; + entityStream.mark(1); + if (entityStream.read() == -1) { + isEmpty = true; + } + entityStream.reset(); + return isEmpty; + } + + private boolean isSimpleNodeEvent(final XMLEvent event) throws XMLStreamException { + checkArgument(event != null, "XML Event cannot be NULL!"); + if (event.isStartElement()) { + XMLEvent innerEvent = skipCommentsAndWhitespace(); + if (innerEvent != null && (innerEvent.isCharacters() || innerEvent.isEndElement())) { + return true; + } + } + return false; + } + + private boolean isCompositeNodeEvent(final XMLEvent event) throws XMLStreamException { + checkArgument(event != null, "XML Event cannot be NULL!"); + if (event.isStartElement()) { + XMLEvent innerEvent = skipCommentsAndWhitespace(); + if (innerEvent != null) { + if (innerEvent.isStartElement()) { + return true; + } + } + } + return false; + } + + private XMLEvent skipCommentsAndWhitespace() throws XMLStreamException { + while (eventReader.hasNext()) { + XMLEvent event = eventReader.peek(); + if (event.getEventType() == XMLStreamConstants.COMMENT) { + eventReader.nextEvent(); + continue; + } + + if (event.isCharacters()) { + Characters chars = event.asCharacters(); + if (chars.isWhiteSpace()) { + eventReader.nextEvent(); + continue; + } + } + return event; + } + return null; + } + + private CompositeNodeWrapper resolveCompositeNodeFromStartElement(final QName qName) { + // checkArgument(startElement != null, "Start Element cannot be NULL!"); + CompositeNodeWrapper compositeNodeWrapper = new CompositeNodeWrapper("dummy"); + compositeNodeWrapper.setQname(qName); + return compositeNodeWrapper; + + } + + private SimpleNodeWrapper resolveSimpleNodeFromStartElement(final DataSchemaNode node, final String value) + throws XMLStreamException { + // checkArgument(startElement != null, "Start Element cannot be NULL!"); + Object deserializedValue = null; + + if (node instanceof LeafSchemaNode) { + TypeDefinition baseType = RestUtil.resolveBaseTypeFrom(((LeafSchemaNode) node).getType()); + deserializedValue = RestCodec.from(baseType, iiWithSchema.getMountPoint()).deserialize(value); + } else if (node instanceof LeafListSchemaNode) { + TypeDefinition baseType = RestUtil.resolveBaseTypeFrom(((LeafListSchemaNode) node).getType()); + deserializedValue = RestCodec.from(baseType, iiWithSchema.getMountPoint()).deserialize(value); + } + // String data; + // if (data == null) { + // return new EmptyNodeWrapper(getNamespaceFor(startElement), getLocalNameFor(startElement)); + // } + SimpleNodeWrapper simpleNodeWrapper = new SimpleNodeWrapper("dummy", deserializedValue); + simpleNodeWrapper.setQname(node.getQName()); + return simpleNodeWrapper; + } + + private String getValueOf(final StartElement startElement) throws XMLStreamException { + String data = null; + if (eventReader.hasNext()) { + final XMLEvent innerEvent = eventReader.peek(); + if (innerEvent.isCharacters()) { + final Characters chars = innerEvent.asCharacters(); + if (!chars.isWhiteSpace()) { + data = innerEvent.asCharacters().getData(); + data = data + getAdditionalData(eventReader.nextEvent()); + } + } else if (innerEvent.isEndElement()) { + if (startElement.getLocation().getCharacterOffset() == innerEvent.getLocation().getCharacterOffset()) { + data = null; + } else { + data = ""; + } + } + } + return data == null ? null : data.trim(); + } + + private String getAdditionalData(final XMLEvent event) throws XMLStreamException { + String data = ""; + if (eventReader.hasNext()) { + final XMLEvent innerEvent = eventReader.peek(); + if (innerEvent.isCharacters() && !innerEvent.isEndElement()) { + final Characters chars = innerEvent.asCharacters(); + if (!chars.isWhiteSpace()) { + data = innerEvent.asCharacters().getData(); + data = data + getAdditionalData(eventReader.nextEvent()); + } + } + } + return data; + } + + private String getLocalNameFor(final StartElement startElement) { + return startElement.getName().getLocalPart(); + } + + private URI getNamespaceFor(final StartElement startElement) { + String namespaceURI = startElement.getName().getNamespaceURI(); + return namespaceURI.isEmpty() ? null : URI.create(namespaceURI); + } + + private Object resolveValueOfElement(final String value, final StartElement startElement) { + // it could be instance-identifier Built-In Type + if (value.startsWith("/")) { + IdentityValuesDTO iiValue = RestUtil.asInstanceIdentifier(value, new RestUtil.PrefixMapingFromXml( + startElement)); + if (iiValue != null) { + return iiValue; + } + } + // it could be identityref Built-In Type + String[] namespaceAndValue = value.split(":"); + if (namespaceAndValue.length == 2) { + String namespace = startElement.getNamespaceContext().getNamespaceURI(namespaceAndValue[0]); + if (namespace != null && !namespace.isEmpty()) { + return new IdentityValuesDTO(namespace, namespaceAndValue[1], namespaceAndValue[0], value); + } + } + // it is not "prefix:value" but just "value" + return value; + } + +} diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java index 861aaac3d8..be24fd26dd 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java @@ -7,38 +7,43 @@ */ package org.opendaylight.controller.sal.restconf.impl; -import com.google.common.util.concurrent.Futures; +import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION; +import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL; +import com.google.common.base.Optional; +import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.ListenableFuture; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; - import javax.ws.rs.core.Response.Status; - -import org.opendaylight.controller.md.sal.common.api.TransactionStatus; -import org.opendaylight.controller.md.sal.common.api.data.DataReader; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; +import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; +import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession; -import org.opendaylight.controller.sal.core.api.data.DataBrokerService; -import org.opendaylight.controller.sal.core.api.data.DataChangeListener; -import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType; import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class BrokerFacade implements DataReader { +public class BrokerFacade { private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class); private final static BrokerFacade INSTANCE = new BrokerFacade(); - - private volatile DataBrokerService dataService; private volatile ConsumerSession context; + private DOMDataBroker domDataBroker; private BrokerFacade() { } @@ -47,154 +52,175 @@ public class BrokerFacade implements DataReader readConfigurationData(final YangInstanceIdentifier path) { + checkPreconditions(); + return readDataViaTransaction(domDataBroker.newReadOnlyTransaction(), CONFIGURATION, path); + } - return dataService.readConfigurationData(path); + public NormalizedNode readConfigurationData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) { + final Optional domDataBrokerService = mountPoint.getService(DOMDataBroker.class); + if (domDataBrokerService.isPresent()) { + return readDataViaTransaction(domDataBrokerService.get().newReadOnlyTransaction(), CONFIGURATION, path); + } + throw new RestconfDocumentedException("DOM data broker service isn't available for mount point."); } - public CompositeNode readConfigurationDataBehindMountPoint(final MountInstance mountPoint, - final YangInstanceIdentifier path) { - this.checkPreconditions(); + // READ operational + public NormalizedNode readOperationalData(final YangInstanceIdentifier path) { + checkPreconditions(); + return readDataViaTransaction(domDataBroker.newReadOnlyTransaction(), OPERATIONAL, path); + } - LOG.trace("Read Configuration via Restconf: {}", path); + public NormalizedNode readOperationalData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) { + final Optional domDataBrokerService = mountPoint.getService(DOMDataBroker.class); + if (domDataBrokerService.isPresent()) { + return readDataViaTransaction(domDataBrokerService.get().newReadOnlyTransaction(), OPERATIONAL, path); + } + throw new RestconfDocumentedException("DOM data broker service isn't available for mount point."); + } - return mountPoint.readConfigurationData(path); + // PUT configuration + public CheckedFuture commitConfigurationDataPut( + final YangInstanceIdentifier path, final NormalizedNode payload) { + checkPreconditions(); + return putDataViaTransaction(domDataBroker.newWriteOnlyTransaction(), CONFIGURATION, path, payload); } - @Override - public CompositeNode readOperationalData(final YangInstanceIdentifier path) { - this.checkPreconditions(); + public CheckedFuture commitConfigurationDataPut( + final DOMMountPoint mountPoint, final YangInstanceIdentifier path, final NormalizedNode payload) { + final Optional domDataBrokerService = mountPoint.getService(DOMDataBroker.class); + if (domDataBrokerService.isPresent()) { + return putDataViaTransaction(domDataBrokerService.get().newWriteOnlyTransaction(), CONFIGURATION, path, + payload); + } + throw new RestconfDocumentedException("DOM data broker service isn't available for mount point."); + } - BrokerFacade.LOG.trace("Read Operational via Restconf: {}", path); + // POST configuration + public CheckedFuture commitConfigurationDataPost( + final YangInstanceIdentifier path, final NormalizedNode payload) { + checkPreconditions(); + return postDataViaTransaction(domDataBroker.newReadWriteTransaction(), CONFIGURATION, path, payload); + } - return dataService.readOperationalData(path); + public CheckedFuture commitConfigurationDataPost( + final DOMMountPoint mountPoint, final YangInstanceIdentifier path, final NormalizedNode payload) { + final Optional domDataBrokerService = mountPoint.getService(DOMDataBroker.class); + if (domDataBrokerService.isPresent()) { + return postDataViaTransaction(domDataBrokerService.get().newReadWriteTransaction(), CONFIGURATION, path, + payload); + } + throw new RestconfDocumentedException("DOM data broker service isn't available for mount point."); } - public CompositeNode readOperationalDataBehindMountPoint(final MountInstance mountPoint, + // DELETE configuration + public CheckedFuture commitConfigurationDataDelete( final YangInstanceIdentifier path) { - this.checkPreconditions(); - - BrokerFacade.LOG.trace("Read Operational via Restconf: {}", path); + checkPreconditions(); + return deleteDataViaTransaction(domDataBroker.newWriteOnlyTransaction(), CONFIGURATION, path); + } - return mountPoint.readOperationalData(path); + public CheckedFuture commitConfigurationDataDelete( + final DOMMountPoint mountPoint, final YangInstanceIdentifier path) { + final Optional domDataBrokerService = mountPoint.getService(DOMDataBroker.class); + if (domDataBrokerService.isPresent()) { + return deleteDataViaTransaction(domDataBrokerService.get().newWriteOnlyTransaction(), CONFIGURATION, path); + } + throw new RestconfDocumentedException("DOM data broker service isn't available for mount point."); } + // RPC public Future> invokeRpc(final QName type, final CompositeNode payload) { this.checkPreconditions(); return context.rpc(type, payload); } - public Future> commitConfigurationDataPut(final YangInstanceIdentifier path, - final CompositeNode payload) { + public void registerToListenDataChanges(final LogicalDatastoreType datastore, final DataChangeScope scope, + final ListenerAdapter listener) { this.checkPreconditions(); - final DataModificationTransaction transaction = dataService.beginTransaction(); - BrokerFacade.LOG.trace("Put Configuration via Restconf: {}", path); - transaction.putConfigurationData(path, payload); - return transaction.commit(); - } + if (listener.isListening()) { + return; + } - public Future> commitConfigurationDataPutBehindMountPoint( - final MountInstance mountPoint, final YangInstanceIdentifier path, final CompositeNode payload) { - this.checkPreconditions(); + YangInstanceIdentifier path = listener.getPath(); + final ListenerRegistration registration = domDataBroker.registerDataChangeListener( + datastore, path, listener, scope); - final DataModificationTransaction transaction = mountPoint.beginTransaction(); - BrokerFacade.LOG.trace("Put Configuration via Restconf: {}", path); - transaction.putConfigurationData(path, payload); - return transaction.commit(); + listener.setRegistration(registration); } - public Future> commitConfigurationDataPost(final YangInstanceIdentifier path, - final CompositeNode payload) { - this.checkPreconditions(); - - final DataModificationTransaction transaction = dataService.beginTransaction(); - /* check for available Node in Configuration DataStore by path */ - CompositeNode availableNode = transaction.readConfigurationData(path); - if (availableNode != null) { - String errMsg = "Post Configuration via Restconf was not executed because data already exists"; - BrokerFacade.LOG.warn((new StringBuilder(errMsg)).append(" : ").append(path).toString()); - - throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL, - ErrorTag.DATA_EXISTS); + private NormalizedNode readDataViaTransaction(final DOMDataReadTransaction transaction, + LogicalDatastoreType datastore, YangInstanceIdentifier path) { + LOG.trace("Read " + datastore.name() + " via Restconf: {}", path); + final ListenableFuture>> listenableFuture = transaction.read(datastore, path); + if (listenableFuture != null) { + Optional> optional; + try { + LOG.debug("Reading result data from transaction."); + optional = listenableFuture.get(); + } catch (InterruptedException | ExecutionException e) { + throw new RestconfDocumentedException("Problem to get data from transaction.", e.getCause()); + + } + if (optional != null) { + if (optional.isPresent()) { + return optional.get(); + } + } } - BrokerFacade.LOG.trace("Post Configuration via Restconf: {}", path); - transaction.putConfigurationData(path, payload); - return transaction.commit(); - } - - public Future> commitConfigurationDataPostBehindMountPoint( - final MountInstance mountPoint, final YangInstanceIdentifier path, final CompositeNode payload) { - this.checkPreconditions(); - - final DataModificationTransaction transaction = mountPoint.beginTransaction(); - /* check for available Node in Configuration DataStore by path */ - CompositeNode availableNode = transaction.readConfigurationData(path); - if (availableNode != null) { - String errMsg = "Post Configuration via Restconf was not executed because data already exists"; - BrokerFacade.LOG.warn((new StringBuilder(errMsg)).append(" : ").append(path).toString()); - - throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL, - ErrorTag.DATA_EXISTS); + return null; + } + + private CheckedFuture postDataViaTransaction( + final DOMDataReadWriteTransaction rWTransaction, final LogicalDatastoreType datastore, + final YangInstanceIdentifier path, final NormalizedNode payload) { + ListenableFuture>> futureDatastoreData = rWTransaction.read(datastore, path); + try { + final Optional> optionalDatastoreData = futureDatastoreData.get(); + if (optionalDatastoreData.isPresent() && payload.equals(optionalDatastoreData.get())) { + String errMsg = "Post Configuration via Restconf was not executed because data already exists"; + LOG.trace(errMsg + ":{}", path); + throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL, + ErrorTag.DATA_EXISTS); + } + } catch (InterruptedException | ExecutionException e) { + LOG.trace("It wasn't possible to get data loaded from datastore at path " + path); } - BrokerFacade.LOG.trace("Post Configuration via Restconf: {}", path); - transaction.putConfigurationData(path, payload); - return transaction.commit(); - } - - public Future> commitConfigurationDataDelete(final YangInstanceIdentifier path) { - this.checkPreconditions(); - return deleteDataAtTarget(path, dataService.beginTransaction()); + rWTransaction.merge(datastore, path, payload); + LOG.trace("Post " + datastore.name() + " via Restconf: {}", path); + return rWTransaction.submit(); } - public Future> commitConfigurationDataDeleteBehindMountPoint( - final MountInstance mountPoint, final YangInstanceIdentifier path) { - this.checkPreconditions(); - return deleteDataAtTarget(path, mountPoint.beginTransaction()); + private CheckedFuture putDataViaTransaction( + final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType datastore, + final YangInstanceIdentifier path, final NormalizedNode payload) { + LOG.trace("Put " + datastore.name() + " via Restconf: {}", path); + writeTransaction.put(datastore, path, payload); + return writeTransaction.submit(); } - private Future> deleteDataAtTarget(final YangInstanceIdentifier path, - final DataModificationTransaction transaction) { - LOG.info("Delete Configuration via Restconf: {}", path); - CompositeNode redDataAtPath = transaction.readConfigurationData(path); - if (redDataAtPath == null) { - return Futures.immediateFuture(RpcResultBuilder. - success(TransactionStatus.COMMITED).build()); - } - transaction.removeConfigurationData(path); - return transaction.commit(); + private CheckedFuture deleteDataViaTransaction( + final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType datastore, + YangInstanceIdentifier path) { + LOG.info("Delete " + datastore.name() + " via Restconf: {}", path); + writeTransaction.delete(datastore, path); + return writeTransaction.submit(); } - public void registerToListenDataChanges(final ListenerAdapter listener) { - this.checkPreconditions(); - - if (listener.isListening()) { - return; - } - - YangInstanceIdentifier path = listener.getPath(); - final ListenerRegistration registration = dataService.registerDataChangeListener(path, - listener); - - listener.setRegistration(registration); + public void setDomDataBroker(DOMDataBroker domDataBroker) { + this.domDataBroker = domDataBroker; } } 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 f8bcbe3c61..695f9f82af 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 @@ -9,6 +9,7 @@ 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; @@ -17,7 +18,6 @@ import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; - import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; @@ -31,11 +31,9 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; - import javax.ws.rs.core.Response.Status; - -import org.opendaylight.controller.sal.core.api.mount.MountInstance; -import org.opendaylight.controller.sal.core.api.mount.MountService; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.controller.sal.rest.api.Draft02; import org.opendaylight.controller.sal.rest.impl.RestUtil; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; @@ -91,13 +89,13 @@ public class ControllerContext implements SchemaContextListener { new AtomicReference<>(Collections.emptyMap()); private volatile SchemaContext globalSchema; - private volatile MountService mountService; + private volatile DOMMountPointService mountService; public void setGlobalSchema(final SchemaContext globalSchema) { this.globalSchema = globalSchema; } - public void setMountService(final MountService mountService) { + public void setMountService(final DOMMountPointService mountService) { this.mountService = mountService; } @@ -143,7 +141,7 @@ public class ControllerContext implements SchemaContextListener { } InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder(); - Module latestModule = this.getLatestModule(globalSchema, startModule); + Module latestModule = globalSchema.findModuleByName(startModule, null); InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null, toMountPointIdentifier); @@ -175,59 +173,38 @@ public class ControllerContext implements SchemaContextListener { return list; } - - private Module getLatestModule(final SchemaContext schema, final String moduleName) { - Preconditions.checkArgument(schema != null); - Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty()); - - Predicate filter = new Predicate() { - @Override - public boolean apply(final Module m) { - return Objects.equal(m.getName(), moduleName); - } - }; - - Iterable modules = Iterables.filter(schema.getModules(), filter); - return this.filterLatestModule(modules); - } - - private Module filterLatestModule(final Iterable modules) { - Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null; - for (final Module module : modules) { - if (module.getRevision().after(latestModule.getRevision())) { - latestModule = module; - } - } - return latestModule; - } - public Module findModuleByName(final String moduleName) { this.checkPreconditions(); Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty()); - return this.getLatestModule(globalSchema, moduleName); + return globalSchema.findModuleByName(moduleName, null); } - public Module findModuleByName(final MountInstance mountPoint, final String moduleName) { + public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) { Preconditions.checkArgument(moduleName != null && mountPoint != null); final SchemaContext mountPointSchema = mountPoint.getSchemaContext(); - return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName); + if (mountPointSchema == null) { + return null; + } + + return mountPointSchema.findModuleByName(moduleName, null); } public Module findModuleByNamespace(final URI namespace) { this.checkPreconditions(); Preconditions.checkArgument(namespace != null); - - final Set moduleSchemas = globalSchema.findModuleByNamespace(namespace); - return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas); + return globalSchema.findModuleByNamespaceAndRevision(namespace, null); } - public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) { + public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) { Preconditions.checkArgument(namespace != null && mountPoint != null); final SchemaContext mountPointSchema = mountPoint.getSchemaContext(); - Set moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace); - return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas); + if (mountPointSchema == null) { + return null; + } + + return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null); } public Module findModuleByNameAndRevision(final QName module) { @@ -237,7 +214,7 @@ public class ControllerContext implements SchemaContextListener { return globalSchema.findModuleByName(module.getLocalName(), module.getRevision()); } - public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) { + public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) { this.checkPreconditions(); Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null && mountPoint != null); @@ -306,7 +283,7 @@ public class ControllerContext implements SchemaContextListener { return moduleName; } - public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) { + public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) { final Module module = this.findModuleByNamespace(mountPoint, namespace); return module == null ? null : module.getName(); } @@ -324,12 +301,12 @@ public class ControllerContext implements SchemaContextListener { return namespace; } - public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) { + public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) { final Module module = this.findModuleByName(mountPoint, moduleName); return module == null ? null : module.getNamespace(); } - public Set getAllModules(final MountInstance mountPoint) { + public Set getAllModules(final DOMMountPoint mountPoint) { this.checkPreconditions(); SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext(); @@ -363,7 +340,7 @@ public class ControllerContext implements SchemaContextListener { return builder.toString(); } - public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) { + public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) { if (mountPoint == null) { return null; } @@ -387,6 +364,13 @@ public class ControllerContext implements SchemaContextListener { return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME); } + private static final Predicate ERRORS_GROUPING_FILTER = new Predicate() { + @Override + public boolean apply(final GroupingDefinition g) { + return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()); + } + }; + public DataSchemaNode getRestconfModuleErrorsSchemaNode() { Module restconfModule = getRestconfModule(); if (restconfModule == null) { @@ -395,14 +379,7 @@ public class ControllerContext implements SchemaContextListener { Set groupings = restconfModule.getGroupings(); - final Predicate filter = new Predicate() { - @Override - public boolean apply(final GroupingDefinition g) { - return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE); - } - }; - - Iterable filteredGroups = Iterables.filter(groupings, filter); + Iterable filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER); final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null); @@ -411,6 +388,13 @@ public class ControllerContext implements SchemaContextListener { return Iterables.getFirst(instanceDataChildrenByName, null); } + private static final Predicate GROUPING_FILTER = new Predicate() { + @Override + public boolean apply(final GroupingDefinition g) { + return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()); + } + }; + public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) { Module restconfModule = inRestconfModule; if (restconfModule == null) { @@ -422,16 +406,7 @@ public class ControllerContext implements SchemaContextListener { } Set groupings = restconfModule.getGroupings(); - - final Predicate filter = new Predicate() { - @Override - public boolean apply(final GroupingDefinition g) { - return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE); - } - }; - - Iterable filteredGroups = Iterables.filter(groupings, filter); - + Iterable filteredGroups = Iterables.filter(groupings, GROUPING_FILTER); final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null); List instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping, @@ -525,7 +500,7 @@ public class ControllerContext implements SchemaContextListener { } private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder, - final List strings, final DataNodeContainer parentNode, final MountInstance mountPoint, + final List strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint, final boolean returnJustMountPoint) { Preconditions.> checkNotNull(strings); @@ -557,12 +532,13 @@ public class ControllerContext implements SchemaContextListener { } final YangInstanceIdentifier partialPath = builder.toInstance(); - final MountInstance mount = mountService.getMountPoint(partialPath); - if (mount == null) { + final Optional mountOpt = mountService.getMountPoint(partialPath); + if (!mountOpt.isPresent()) { LOG.debug("Instance identifier to missing mount point: {}", partialPath); throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } + DOMMountPoint mount = mountOpt.get(); final SchemaContext mountPointSchema = mount.getSchemaContext(); if (mountPointSchema == null) { @@ -587,8 +563,7 @@ public class ControllerContext implements SchemaContextListener { ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - final Module moduleBehindMountPoint = this - .getLatestModule(mountPointSchema, moduleNameBehindMountPoint); + final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null); if (moduleBehindMountPoint == null) { throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); @@ -601,14 +576,18 @@ public class ControllerContext implements SchemaContextListener { Module module = null; if (mountPoint == null) { - module = this.getLatestModule(globalSchema, moduleName); + module = globalSchema.findModuleByName(moduleName, null); if (module == null) { throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } } else { SchemaContext schemaContext = mountPoint.getSchemaContext(); - module = schemaContext == null ? null : this.getLatestModule(schemaContext, moduleName); + if (schemaContext != null) { + module = schemaContext.findModuleByName(moduleName, null); + } else { + module = null; + } if (module == null) { throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); @@ -719,6 +698,13 @@ public class ControllerContext implements SchemaContextListener { return instantiatedDataNodeContainers; } + private static final Function> CHOICE_FUNCTION = new Function>() { + @Override + public Set apply(final ChoiceNode node) { + return node.getCases(); + } + }; + private void collectInstanceDataNodeContainers(final List potentialSchemaNodes, final DataNodeContainer container, final String name) { @@ -739,17 +725,8 @@ public class ControllerContext implements SchemaContextListener { } } - Iterable choiceNodes = Iterables. filter(container.getChildNodes(), ChoiceNode.class); - - final Function> choiceFunction = new Function>() { - @Override - public Set apply(final ChoiceNode node) { - return node.getCases(); - } - }; - - Iterable> map = Iterables.> transform(choiceNodes, - choiceFunction); + Iterable choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class); + Iterable> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION); final Iterable allCases = Iterables. concat(map); for (final ChoiceCaseNode caze : allCases) { @@ -764,7 +741,7 @@ public class ControllerContext implements SchemaContextListener { } private void addKeyValue(final HashMap map, final DataSchemaNode node, final String uriValue, - final MountInstance mountPoint) { + final DOMMountPoint mountPoint) { Preconditions. checkNotNull(uriValue); Preconditions.checkArgument((node instanceof LeafSchemaNode)); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java index 12c1ba66ec..b58a6eeaea 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java @@ -7,7 +7,7 @@ */ package org.opendaylight.controller.sal.restconf.impl; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; @@ -15,10 +15,10 @@ public class InstanceIdWithSchemaNode { private final YangInstanceIdentifier instanceIdentifier; private final DataSchemaNode schemaNode; - private final MountInstance mountPoint; + private final DOMMountPoint mountPoint; public InstanceIdWithSchemaNode(YangInstanceIdentifier instanceIdentifier, DataSchemaNode schemaNode, - MountInstance mountPoint) { + DOMMountPoint mountPoint) { this.instanceIdentifier = instanceIdentifier; this.schemaNode = schemaNode; this.mountPoint = mountPoint; @@ -32,7 +32,7 @@ public class InstanceIdWithSchemaNode { return schemaNode; } - public MountInstance getMountPoint() { + public DOMMountPoint getMountPoint() { return mountPoint; } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java index ff90dd8439..d61ccfdacf 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java @@ -12,7 +12,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.controller.sal.rest.impl.RestUtil; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate; @@ -47,7 +47,7 @@ public class RestCodec { } public static final Codec from(final TypeDefinition typeDefinition, - final MountInstance mountPoint) { + final DOMMountPoint mountPoint) { return new ObjectCodec(typeDefinition, mountPoint); } @@ -62,7 +62,7 @@ public class RestCodec { private final TypeDefinition type; - private ObjectCodec(final TypeDefinition typeDefinition, final MountInstance mountPoint) { + private ObjectCodec(final TypeDefinition typeDefinition, final DOMMountPoint mountPoint) { type = RestUtil.resolveBaseTypeFrom(typeDefinition); if (type instanceof IdentityrefTypeDefinition) { identityrefCodec = new IdentityrefCodecImpl(mountPoint); @@ -158,9 +158,9 @@ public class RestCodec { private final Logger logger = LoggerFactory.getLogger(IdentityrefCodecImpl.class); - private final MountInstance mountPoint; + private final DOMMountPoint mountPoint; - public IdentityrefCodecImpl(final MountInstance mountPoint) { + public IdentityrefCodecImpl(final DOMMountPoint mountPoint) { this.mountPoint = mountPoint; } @@ -200,9 +200,9 @@ public class RestCodec { public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec { private final Logger logger = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class); - private final MountInstance mountPoint; + private final DOMMountPoint mountPoint; - public InstanceIdentifierCodecImpl(final MountInstance mountPoint) { + public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint) { this.mountPoint = mountPoint; } @@ -318,7 +318,7 @@ public class RestCodec { } } - private static Module getModuleByNamespace(final String namespace, final MountInstance mountPoint) { + private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint) { URI validNamespace = resolveValidNamespace(namespace, mountPoint); Module module = null; @@ -334,7 +334,7 @@ public class RestCodec { return module; } - private static URI resolveValidNamespace(final String namespace, final MountInstance mountPoint) { + private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint) { URI validNamespace; if (mountPoint != null) { validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace); 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 4c005c6ae5..b68bee2f0c 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 @@ -24,17 +24,19 @@ import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; 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; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.controller.sal.rest.api.Draft02; import org.opendaylight.controller.sal.rest.api.RestconfService; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; @@ -47,16 +49,23 @@ import org.opendaylight.controller.sal.streams.listeners.Notificator; import org.opendaylight.controller.sal.streams.websockets.WebSocketServer; import org.opendaylight.yangtools.concepts.Codec; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.QNameModule; import org.opendaylight.yangtools.yang.common.RpcError; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; +import org.opendaylight.yangtools.yang.data.api.SimpleNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; -import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode; -import org.opendaylight.yangtools.yang.data.api.Node; -import org.opendaylight.yangtools.yang.data.api.SimpleNode; +import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory; +import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer.CnSnFromNormalizedNodeSerializerFactory; import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; import org.opendaylight.yangtools.yang.data.impl.NodeFactory; import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; @@ -76,6 +85,8 @@ import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; import org.opendaylight.yangtools.yang.model.util.EmptyType; import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder; import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class RestconfImpl implements RestconfService { private enum UriParameters { @@ -96,6 +107,8 @@ public class RestconfImpl implements RestconfService { private final static RestconfImpl INSTANCE = new RestconfImpl(); + private static final int NOTIFICATION_PORT = 8181; + private static final int CHAR_NOT_FOUND = -1; private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf"; @@ -110,6 +123,30 @@ public class RestconfImpl implements RestconfService { private ControllerContext controllerContext; + private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class); + + private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE; + + private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION; + + private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription"); + + private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION; + + private static final String DATASTORE_PARAM_NAME = "datastore"; + + private static final String SCOPE_PARAM_NAME = "scope"; + + static { + try { + EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08"); + } catch (ParseException e) { + throw new RestconfDocumentedException( + "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION, + ErrorTag.OPERATION_FAILED); + } + } + public void setBroker(final BrokerFacade broker) { this.broker = broker; } @@ -168,7 +205,7 @@ public class RestconfImpl implements RestconfService { @Override public StructuredData getModules(final String identifier, final UriInfo uriInfo) { Set modules = null; - MountInstance mountPoint = null; + DOMMountPoint mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); @@ -199,7 +236,7 @@ public class RestconfImpl implements RestconfService { public StructuredData getModule(final String identifier, final UriInfo uriInfo) { final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier); Module module = null; - MountInstance mountPoint = null; + DOMMountPoint mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); @@ -230,7 +267,7 @@ public class RestconfImpl implements RestconfService { @Override public StructuredData getOperations(final String identifier, final UriInfo uriInfo) { Set modules = null; - MountInstance mountPoint = null; + DOMMountPoint mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); @@ -245,7 +282,7 @@ public class RestconfImpl implements RestconfService { } private StructuredData operationsFromModulesToStructuredData(final Set modules, - final MountInstance mountPoint, boolean prettyPrint) { + final DOMMountPoint mountPoint, boolean prettyPrint) { final List> operationsAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( @@ -405,7 +442,7 @@ public class RestconfImpl implements RestconfService { return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo)); } - private void validateInput(final DataSchemaNode inputSchema, final CompositeNode payload) { + private void validateInput(final DataSchemaNode inputSchema, final Node payload) { if (inputSchema != null && payload == null) { // expected a non null payload throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE); @@ -416,6 +453,7 @@ public class RestconfImpl implements RestconfService { // else // { // TODO: Validate "mandatory" and "config" values here??? Or should those be + // those be // validate in a more central location inside MD-SAL core. // } } @@ -436,7 +474,15 @@ public class RestconfImpl implements RestconfService { String streamName = null; if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) { String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier); - streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier); + + LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME); + datastore = datastore == null ? DEFAULT_DATASTORE : datastore; + + DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME); + scope = scope == null ? DEFAULT_SCOPE : scope; + + streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + + "/scope=" + scope); } if (Strings.isNullOrEmpty(streamName)) { @@ -453,7 +499,7 @@ public class RestconfImpl implements RestconfService { final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(), null, output, null, null); - if (!Notificator.existListenerFor(pathIdentifier)) { + if (!Notificator.existListenerFor(streamName)) { Notificator.createListener(pathIdentifier, streamName); } @@ -470,7 +516,7 @@ public class RestconfImpl implements RestconfService { private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) { String identifierEncoded = null; - MountInstance mountPoint = null; + DOMMountPoint mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { // mounted RPC call - look up mount instance. InstanceIdWithSchemaNode mountPointId = controllerContext.toMountPointIdentifier(identifier); @@ -582,18 +628,20 @@ public class RestconfImpl implements RestconfService { @Override public StructuredData readConfigurationData(final String identifier, final UriInfo uriInfo) { - final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier); - CompositeNode data = null; - MountInstance mountPoint = iiWithData.getMountPoint(); + final InstanceIdWithSchemaNode iiWithData = normalizeInstanceIdentifierWithSchemaNode( + this.controllerContext.toInstanceIdentifier(identifier), true); + DOMMountPoint mountPoint = iiWithData.getMountPoint(); + NormalizedNode data = null; if (mountPoint != null) { - data = broker.readConfigurationDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier()); + data = broker.readConfigurationData(mountPoint, iiWithData.getInstanceIdentifier()); } else { data = broker.readConfigurationData(iiWithData.getInstanceIdentifier()); } + CompositeNode compositeNode = datastoreNormalizedNodeToCompositeNode(data, iiWithData.getSchemaNode()); - data = pruneDataAtDepth(data, parseDepthParameter(uriInfo)); + compositeNode = pruneDataAtDepth(compositeNode, parseDepthParameter(uriInfo)); boolean prettyPrintMode = parsePrettyPrintParameter(uriInfo); - return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint(), prettyPrintMode); + return new StructuredData(compositeNode, iiWithData.getSchemaNode(), iiWithData.getMountPoint(), prettyPrintMode); } @SuppressWarnings("unchecked") @@ -640,18 +688,21 @@ public class RestconfImpl implements RestconfService { @Override public StructuredData readOperationalData(final String identifier, final UriInfo info) { - final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier); - CompositeNode data = null; - MountInstance mountPoint = iiWithData.getMountPoint(); + final InstanceIdWithSchemaNode iiWithData = normalizeInstanceIdentifierWithSchemaNode( + this.controllerContext.toInstanceIdentifier(identifier), true); + NormalizedNode data = null; + + DOMMountPoint mountPoint = iiWithData.getMountPoint(); if (mountPoint != null) { - data = broker.readOperationalDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier()); + data = broker.readOperationalData(mountPoint, iiWithData.getInstanceIdentifier()); } else { data = broker.readOperationalData(iiWithData.getInstanceIdentifier()); } - data = pruneDataAtDepth(data, parseDepthParameter(info)); - boolean prettyPrintMode = parsePrettyPrintParameter(info); - return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode); + final CompositeNode compositeNode = datastoreNormalizedNodeToCompositeNode(data, iiWithData.getSchemaNode()); + final CompositeNode prunedCompositeNode = pruneDataAtDepth(compositeNode, parseDepthParameter(info)); + final boolean prettyPrintMode = parsePrettyPrintParameter(info); + return new StructuredData(prunedCompositeNode, iiWithData.getSchemaNode(), mountPoint,prettyPrintMode); } private boolean parsePrettyPrintParameter(UriInfo info) { @@ -660,32 +711,31 @@ public class RestconfImpl implements RestconfService { } @Override - public Response updateConfigurationData(final String identifier, final CompositeNode payload) { - final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier); + public Response updateConfigurationData(final String identifier, final Node payload) { + final InstanceIdWithSchemaNode iiWithData = normalizeInstanceIdentifierWithSchemaNode(this.controllerContext + .toInstanceIdentifier(identifier)); validateInput(iiWithData.getSchemaNode(), payload); - MountInstance mountPoint = iiWithData.getMountPoint(); + DOMMountPoint mountPoint = iiWithData.getMountPoint(); final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint); - validateListKeysEqualityInPayloadAndUri(iiWithData, payload); - RpcResult status = null; + validateListKeysEqualityInPayloadAndUri(iiWithData, value); + final NormalizedNode datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value, + iiWithData.getSchemaNode()); try { if (mountPoint != null) { - status = broker.commitConfigurationDataPutBehindMountPoint(mountPoint, - iiWithData.getInstanceIdentifier(), value).get(); + broker.commitConfigurationDataPut(mountPoint, iiWithData.getInstanceIdentifier(), + datastoreNormalizedNode).get(); } else { - status = broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), value).get(); + broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), datastoreNormalizedNode) + .get(); } } catch (Exception e) { throw new RestconfDocumentedException("Error updating data", e); } - if (status.getResult() == TransactionStatus.COMMITED) { - return Response.status(Status.OK).build(); - } - - return Response.status(Status.INTERNAL_SERVER_ERROR).build(); + return Response.status(Status.OK).build(); } /** @@ -734,7 +784,7 @@ public class RestconfImpl implements RestconfService { } @Override - public Response createConfigurationData(final String identifier, final CompositeNode payload) { + public Response createConfigurationData(final String identifier, final Node payload) { if (payload == null) { throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE); } @@ -765,8 +815,8 @@ public class RestconfImpl implements RestconfService { final InstanceIdWithSchemaNode incompleteInstIdWithData = this.controllerContext .toInstanceIdentifier(identifier); final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode(); - MountInstance mountPoint = incompleteInstIdWithData.getMountPoint(); - final Module module = this.findModule(mountPoint, payload); + DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint(); + final Module module = findModule(mountPoint, payload); if (module == null) { throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); @@ -777,38 +827,30 @@ public class RestconfImpl implements RestconfService { parentSchema, payloadName, module.getNamespace()); value = this.normalizeNode(payload, schemaNode, mountPoint); - iiWithData = this.addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode); + iiWithData = normalizeInstanceIdentifierWithSchemaNode(this.addLastIdentifierFromData( + incompleteInstIdWithData, value, schemaNode)); } - RpcResult status = null; - MountInstance mountPoint = iiWithData.getMountPoint(); + final NormalizedNode datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, + iiWithData.getSchemaNode()); + DOMMountPoint mountPoint = iiWithData.getMountPoint(); try { if (mountPoint != null) { - Future> future = broker.commitConfigurationDataPostBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value); - status = future == null ? null : future.get(); + broker.commitConfigurationDataPost(mountPoint, + iiWithData.getInstanceIdentifier(), datastoreNormalizedData); } else { - Future> future = broker.commitConfigurationDataPost( - iiWithData.getInstanceIdentifier(), value); - status = future == null ? null : future.get(); + broker.commitConfigurationDataPost( + iiWithData.getInstanceIdentifier(), datastoreNormalizedData); } } catch (Exception e) { throw new RestconfDocumentedException("Error creating data", e); } - if (status == null) { - return Response.status(Status.ACCEPTED).build(); - } - - if (status.getResult() == TransactionStatus.COMMITED) { - return Response.status(Status.NO_CONTENT).build(); - } - - return Response.status(Status.INTERNAL_SERVER_ERROR).build(); + return Response.status(Status.NO_CONTENT).build(); } @Override - public Response createConfigurationData(final CompositeNode payload) { + public Response createConfigurationData(final Node payload) { if (payload == null) { throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE); } @@ -833,57 +875,56 @@ public class RestconfImpl implements RestconfService { final CompositeNode value = this.normalizeNode(payload, schemaNode, null); final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode); RpcResult status = null; - MountInstance mountPoint = iiWithData.getMountPoint(); + final NormalizedNode datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode); + DOMMountPoint mountPoint = iiWithData.getMountPoint(); try { if (mountPoint != null) { - Future> future = broker.commitConfigurationDataPostBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value); - status = future == null ? null : future.get(); + broker.commitConfigurationDataPost(mountPoint, + iiWithData.getInstanceIdentifier(), datastoreNormalizedData); } else { - Future> future = broker.commitConfigurationDataPost( - iiWithData.getInstanceIdentifier(), value); - status = future == null ? null : future.get(); + broker.commitConfigurationDataPost( + iiWithData.getInstanceIdentifier(), datastoreNormalizedData); } } catch (Exception e) { throw new RestconfDocumentedException("Error creating data", e); } - if (status == null) { - return Response.status(Status.ACCEPTED).build(); - } - - if (status.getResult() == TransactionStatus.COMMITED) { - return Response.status(Status.NO_CONTENT).build(); - } - - return Response.status(Status.INTERNAL_SERVER_ERROR).build(); + return Response.status(Status.NO_CONTENT).build(); } @Override public Response deleteConfigurationData(final String identifier) { - final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier); + final InstanceIdWithSchemaNode iiWithData = normalizeInstanceIdentifierWithSchemaNode(this.controllerContext + .toInstanceIdentifier(identifier)); RpcResult status = null; - MountInstance mountPoint = iiWithData.getMountPoint(); + DOMMountPoint mountPoint = iiWithData.getMountPoint(); try { if (mountPoint != null) { - status = broker.commitConfigurationDataDeleteBehindMountPoint(mountPoint, - iiWithData.getInstanceIdentifier()).get(); + broker.commitConfigurationDataDelete(mountPoint, iiWithData.getInstanceIdentifier()).get(); } else { - status = broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get(); + broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get(); } } catch (Exception e) { throw new RestconfDocumentedException("Error creating data", e); } - if (status.getResult() == TransactionStatus.COMMITED) { - return Response.status(Status.OK).build(); - } - - return Response.status(Status.INTERNAL_SERVER_ERROR).build(); + return Response.status(Status.OK).build(); } + /** + * Subscribes to some path in schema context (stream) to listen on changes + * on this stream. + * + * Additional parameters for subscribing to stream are loaded via rpc input + * parameters: + *
    + *
  • datastore
  • - default CONFIGURATION (other values of + * {@link LogicalDatastoreType} enum type) + *
  • scope
  • - default BASE (other values of {@link DataChangeScope}) + *
+ */ @Override public Response subscribeToStream(final String identifier, final UriInfo uriInfo) { final String streamName = Notificator.createStreamNameFromUri(identifier); @@ -896,18 +937,100 @@ public class RestconfImpl implements RestconfService { throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } - broker.registerToListenDataChanges(listener); + Map paramToValues = resolveValuesFromUri(identifier); + LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class, + paramToValues.get(DATASTORE_PARAM_NAME)); + if (datastore == null) { + throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)", + ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE); + } + DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME)); + if (scope == null) { + throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)", + ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE); + } + + broker.registerToListenDataChanges(datastore, scope, listener); final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder(); - UriBuilder port = uriBuilder.port(WebSocketServer.getInstance().getPort()); + int notificationPort = NOTIFICATION_PORT; + try { + WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(); + notificationPort = webSocketServerInstance.getPort(); + } catch (NullPointerException e) { + WebSocketServer.createInstance(NOTIFICATION_PORT); + } + UriBuilder port = uriBuilder.port(notificationPort); final URI uriToWebsocketServer = port.replacePath(streamName).build(); return Response.status(Status.OK).location(uriToWebsocketServer).build(); } - private Module findModule(final MountInstance mountPoint, final CompositeNode data) { - if (data instanceof CompositeNodeWrapper) { - return findModule(mountPoint, (CompositeNodeWrapper) data); + /** + * Load parameter for subscribing to stream from input composite node + * + * @param compNode + * contains value + * @return enum object if its string value is equal to {@code paramName}. In + * other cases null. + */ + private T parseEnumTypeParameter(final CompositeNode compNode, final Class classDescriptor, + final String paramName) { + QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, + EVENT_SUBSCRIPTION_AUGMENT_REVISION); + SimpleNode simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName)); + if (simpleNode == null) { + return null; + } + Object rawValue = simpleNode.getValue(); + if (!(rawValue instanceof String)) { + return null; + } + + return resolveAsEnum(classDescriptor, (String) rawValue); + } + + /** + * Checks whether {@code value} is one of the string representation of + * enumeration {@code classDescriptor} + * + * @return enum object if string value of {@code classDescriptor} + * enumeration is equal to {@code value}. Other cases null. + */ + private T parserURIEnumParameter(final Class classDescriptor, final String value) { + if (Strings.isNullOrEmpty(value)) { + return null; + } + return resolveAsEnum(classDescriptor, value); + } + + private T resolveAsEnum(Class classDescriptor, String value) { + T[] enumConstants = classDescriptor.getEnumConstants(); + if (enumConstants != null) { + for (T enm : classDescriptor.getEnumConstants()) { + if (((Enum) enm).name().equals(value)) { + return enm; + } + } + } + return null; + } + + private Map resolveValuesFromUri(String uri) { + Map result = new HashMap<>(); + String[] tokens = uri.split("/"); + for (int i = 1; i < tokens.length; i++) { + String[] parameterTokens = tokens[i].split("="); + if (parameterTokens.length == 2) { + result.put(parameterTokens[0], parameterTokens[1]); + } + } + return result; + } + + private Module findModule(final DOMMountPoint mountPoint, final Node data) { + if (data instanceof NodeWrapper) { + return findModule(mountPoint, (NodeWrapper) data); } else if (data != null) { URI namespace = data.getNodeType().getNamespace(); if (mountPoint != null) { @@ -921,7 +1044,7 @@ public class RestconfImpl implements RestconfService { } } - private Module findModule(final MountInstance mountPoint, final CompositeNodeWrapper data) { + private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper data) { URI namespace = data.getNamespace(); Preconditions. checkNotNull(namespace); @@ -956,15 +1079,10 @@ public class RestconfImpl implements RestconfService { iiBuilder = YangInstanceIdentifier.builder(iiOriginal); } - if ((schemaOfData instanceof ListSchemaNode)) { - HashMap keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data); - iiBuilder.nodeWithKey(schemaOfData.getQName(), keys); - } else { - iiBuilder.node(schemaOfData.getQName()); - } + iiBuilder.node(schemaOfData.getQName()); YangInstanceIdentifier instance = iiBuilder.toInstance(); - MountInstance mountPoint = null; + DOMMountPoint mountPoint = null; if (identifierWithSchemaNode != null) { mountPoint = identifierWithSchemaNode.getMountPoint(); } @@ -1004,7 +1122,7 @@ public class RestconfImpl implements RestconfService { return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/"); } - private boolean representsMountPointRootData(final CompositeNode data) { + private boolean representsMountPointRootData(final Node data) { URI namespace = this.namespace(data); return (SchemaContext.NAME.getNamespace().equals(namespace) /* * || MOUNT_POINT_MODULE_NAME .equals( namespace . @@ -1022,8 +1140,7 @@ public class RestconfImpl implements RestconfService { return identifier + "/" + ControllerContext.MOUNT; } - private CompositeNode normalizeNode(final CompositeNode node, final DataSchemaNode schema, - final MountInstance mountPoint) { + private CompositeNode normalizeNode(final Node node, final DataSchemaNode schema, final DOMMountPoint mountPoint) { if (schema == null) { QName nodeType = node == null ? null : node.getNodeType(); String localName = nodeType == null ? null : nodeType.getLocalName(); @@ -1037,24 +1154,32 @@ public class RestconfImpl implements RestconfService { ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - if ((node instanceof CompositeNodeWrapper)) { - boolean isChangeAllowed = ((CompositeNodeWrapper) node).isChangeAllowed(); + if ((node instanceof NodeWrapper)) { + NodeWrapper nodeWrap = (NodeWrapper) node; + boolean isChangeAllowed = ((NodeWrapper) node).isChangeAllowed(); if (isChangeAllowed) { + nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper) node, schema); try { - this.normalizeNode(((CompositeNodeWrapper) node), schema, null, mountPoint); + this.normalizeNode(nodeWrap, schema, null, mountPoint); } catch (IllegalArgumentException e) { throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } + if (nodeWrap instanceof CompositeNodeWrapper) { + return ((CompositeNodeWrapper) nodeWrap).unwrap(); + } } + } - return ((CompositeNodeWrapper) node).unwrap(); + if (node instanceof CompositeNode) { + return (CompositeNode) node; } - return node; + throw new RestconfDocumentedException("Top level element is not interpreted as composite node.", + ErrorType.APPLICATION, ErrorTag.INVALID_VALUE); } private void normalizeNode(final NodeWrapper nodeBuilder, final DataSchemaNode schema, - final QName previousAugment, final MountInstance mountPoint) { + final QName previousAugment, final DOMMountPoint mountPoint) { if (schema == null) { throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName() + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); @@ -1111,7 +1236,7 @@ public class RestconfImpl implements RestconfService { } private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema, - final MountInstance mountPoint) { + final DOMMountPoint mountPoint) { final Object value = simpleNode.getValue(); Object inputValue = value; TypeDefinition typeDefinition = this.typeDefinition(schema); @@ -1133,7 +1258,7 @@ public class RestconfImpl implements RestconfService { } private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder, - final DataNodeContainer schema, final MountInstance mountPoint, final QName currentAugment) { + final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) { final List> children = compositeNodeBuilder.getValues(); checkNodeMultiplicityAccordingToSchema(schema, children); for (final NodeWrapper child : children) { @@ -1214,7 +1339,7 @@ public class RestconfImpl implements RestconfService { } private QName normalizeNodeName(final NodeWrapper nodeBuilder, final DataSchemaNode schema, - final QName previousAugment, final MountInstance mountPoint) { + final QName previousAugment, final DOMMountPoint mountPoint) { QName validQName = schema.getQName(); QName currentAugment = previousAugment; if (schema.isAugmenting()) { @@ -1248,9 +1373,9 @@ public class RestconfImpl implements RestconfService { return currentAugment; } - private URI namespace(final CompositeNode data) { - if (data instanceof CompositeNodeWrapper) { - return ((CompositeNodeWrapper) data).getNamespace(); + private URI namespace(final Node data) { + if (data instanceof NodeWrapper) { + return ((NodeWrapper) data).getNamespace(); } else if (data != null) { return data.getNodeType().getNamespace(); } else { @@ -1258,9 +1383,9 @@ public class RestconfImpl implements RestconfService { } } - private String localName(final CompositeNode data) { - if (data instanceof CompositeNodeWrapper) { - return ((CompositeNodeWrapper) data).getLocalName(); + private String localName(final Node data) { + if (data instanceof NodeWrapper) { + return ((NodeWrapper) data).getLocalName(); } else if (data != null) { return data.getNodeType().getLocalName(); } else { @@ -1268,9 +1393,9 @@ public class RestconfImpl implements RestconfService { } } - private String getName(final CompositeNode data) { - if (data instanceof CompositeNodeWrapper) { - return ((CompositeNodeWrapper) data).getLocalName(); + private String getName(final Node data) { + if (data instanceof NodeWrapper) { + return ((NodeWrapper) data).getLocalName(); } else if (data != null) { return data.getNodeType().getLocalName(); } else { @@ -1307,4 +1432,99 @@ public class RestconfImpl implements RestconfService { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays. asList(node).toString()); } } + + private CompositeNode datastoreNormalizedNodeToCompositeNode(NormalizedNode dataNode, DataSchemaNode schema) { + Iterable> nodes = null; + if (dataNode == null) { + throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING, + "No data was found.")); + } + if (schema instanceof ContainerSchemaNode && dataNode instanceof ContainerNode) { + nodes = CnSnFromNormalizedNodeSerializerFactory.getInstance().getContainerNodeSerializer() + .serialize((ContainerSchemaNode) schema, (ContainerNode) dataNode); + } else if (schema instanceof ListSchemaNode && dataNode instanceof MapNode) { + nodes = CnSnFromNormalizedNodeSerializerFactory.getInstance().getMapNodeSerializer() + .serialize((ListSchemaNode) schema, (MapNode) dataNode); + } else if (schema instanceof ListSchemaNode && dataNode instanceof MapEntryNode) { + nodes = CnSnFromNormalizedNodeSerializerFactory.getInstance().getMapEntryNodeSerializer() + .serialize((ListSchemaNode) schema, (MapEntryNode) dataNode); + } + if (nodes != null) { + if (nodes.iterator().hasNext()) { + Node nodeOldStruct = nodes.iterator().next(); + return (CompositeNode) nodeOldStruct; + } else { + LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode."); + } + } else { + LOG.error("Top level node isn't of type Container or List schema node but " + + schema.getClass().getSimpleName()); + } + + throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, + "It wasn't possible to correctly interpret data.")); + } + + private NormalizedNode compositeNodeToDatastoreNormalizedNode(CompositeNode compNode, DataSchemaNode schema) { + List> lst = new ArrayList>(); + lst.add(compNode); + if (schema instanceof ContainerSchemaNode) { + return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser() + .parse(lst, (ContainerSchemaNode) schema); + } else if (schema instanceof ListSchemaNode) { + return CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser() + .parse(lst, (ListSchemaNode) schema); + } + + LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName()); + + throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, + "It wasn't possible to translate specified data to datastore readable form.")); + } + + private InstanceIdWithSchemaNode normalizeInstanceIdentifierWithSchemaNode(InstanceIdWithSchemaNode iiWithSchemaNode) { + return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false); + } + + private InstanceIdWithSchemaNode normalizeInstanceIdentifierWithSchemaNode( + InstanceIdWithSchemaNode iiWithSchemaNode, boolean unwrapLastListNode) { + return new InstanceIdWithSchemaNode(instanceIdentifierToReadableFormForNormalizeNode( + iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(), + iiWithSchemaNode.getMountPoint()); + } + + private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(YangInstanceIdentifier instIdentifier, + boolean unwrapLastListNode) { + Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null"); + final List result = new ArrayList(); + final Iterator iter = instIdentifier.getPathArguments().iterator(); + while (iter.hasNext()) { + final PathArgument pathArgument = iter.next(); + if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) { + result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType())); + } + result.add(pathArgument); + } + return YangInstanceIdentifier.create(result); + } + + private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper node, + final DataSchemaNode schemaNode) { + if (node instanceof CompositeNodeWrapper) { + return (CompositeNodeWrapper) node; + } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) { + final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node; + return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper)); + } + + throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, + "Top level element has to be composite node or has to represent data container node.")); + } + + private boolean isDataContainerNode(final DataSchemaNode schemaNode) { + if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) { + return true; + } + return false; + } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/StructuredData.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/StructuredData.java index c745a8009d..2935434967 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/StructuredData.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/StructuredData.java @@ -7,7 +7,7 @@ */ package org.opendaylight.controller.sal.restconf.impl; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; @@ -15,14 +15,14 @@ public class StructuredData { private final CompositeNode data; private final DataSchemaNode schema; - private final MountInstance mountPoint; + private final DOMMountPoint mountPoint; private final boolean prettyPrintMode; - public StructuredData(final CompositeNode data, final DataSchemaNode schema, final MountInstance mountPoint) { + public StructuredData(final CompositeNode data, final DataSchemaNode schema, final DOMMountPoint mountPoint) { this(data, schema, mountPoint, false); } - public StructuredData(final CompositeNode data, final DataSchemaNode schema, final MountInstance mountPoint, + public StructuredData(final CompositeNode data, final DataSchemaNode schema, final DOMMountPoint mountPoint, final boolean preattyPrintMode) { this.data = data; this.schema = schema; @@ -38,7 +38,7 @@ public class StructuredData { return schema; } - public MountInstance getMountPoint() { + public DOMMountPoint getMountPoint() { return mountPoint; } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java index 36502656c2..efb3e0a1d3 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java @@ -7,9 +7,12 @@ */ package org.opendaylight.controller.sal.restconf.rpc.impl; +import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.util.concurrent.Future; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; +import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry; +import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; @@ -21,9 +24,9 @@ import org.opendaylight.yangtools.yang.model.api.RpcDefinition; * */ public class MountPointRpcExecutor extends AbstractRpcExecutor { - private final MountInstance mountPoint; + private final DOMMountPoint mountPoint; - public MountPointRpcExecutor(RpcDefinition rpcDef, MountInstance mountPoint) { + public MountPointRpcExecutor(RpcDefinition rpcDef, DOMMountPoint mountPoint) { super(rpcDef); this.mountPoint = mountPoint; Preconditions.checkNotNull(mountPoint, "MountInstance can not be null."); @@ -31,6 +34,10 @@ public class MountPointRpcExecutor extends AbstractRpcExecutor { @Override protected Future> invokeRpcUnchecked(CompositeNode rpcRequest) { - return mountPoint.rpc(getRpcDefinition().getQName(), rpcRequest); + Optional service = mountPoint.getService(RpcProvisionRegistry.class); + if (service.isPresent()) { + return service.get().invokeRpc(getRpcDefinition().getQName(), rpcRequest); + } + throw new RestconfDocumentedException("Rpc service is missing."); } } \ No newline at end of file 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 2b7b0246e3..a6e02632ce 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 @@ -38,8 +38,8 @@ import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent; -import org.opendaylight.controller.sal.core.api.data.DataChangeListener; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; +import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener; import org.opendaylight.controller.sal.rest.impl.XmlMapper; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.yangtools.concepts.ListenerRegistration; @@ -49,6 +49,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; 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.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,7 +60,7 @@ import org.w3c.dom.Node; /** * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source. */ -public class ListenerAdapter implements DataChangeListener { +public class ListenerAdapter implements DOMDataChangeListener { private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class); private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance(); @@ -70,7 +71,7 @@ public class ListenerAdapter implements DataChangeListener { private final SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); private final YangInstanceIdentifier path; - private ListenerRegistration registration; + private ListenerRegistration registration; private final String streamName; private Set subscribers = new ConcurrentSet<>(); private final EventBus eventBus; @@ -95,10 +96,11 @@ public class ListenerAdapter implements DataChangeListener { } @Override - public void onDataChanged(final DataChangeEvent change) { - if (!change.getCreatedConfigurationData().isEmpty() || !change.getCreatedOperationalData().isEmpty() - || !change.getUpdatedConfigurationData().isEmpty() || !change.getUpdatedOperationalData().isEmpty() - || !change.getRemovedConfigurationData().isEmpty() || !change.getRemovedOperationalData().isEmpty()) { + public void onDataChanged(AsyncDataChangeEvent> change) { + // TODO Auto-generated method stub + + if (!change.getCreatedData().isEmpty() || !change.getUpdatedData().isEmpty() + || !change.getRemovedPaths().isEmpty()) { String xml = prepareXmlFrom(change); Event event = new Event(EventType.NOTIFY); event.setData(xml); @@ -216,7 +218,7 @@ public class ListenerAdapter implements DataChangeListener { * DataChangeEvent * @return Data in printable form. */ - private String prepareXmlFrom(final DataChangeEvent change) { + private String prepareXmlFrom(AsyncDataChangeEvent> change) { Document doc = createDocument(); Element notificationElement = doc.createElementNS("urn:ietf:params:xml:ns:netconf:notification:1.0", "notification"); @@ -262,7 +264,6 @@ public class ListenerAdapter implements DataChangeListener { /** * Creates {@link Document} document. - * * @return {@link Document} document. */ private Document createDocument() { @@ -287,23 +288,15 @@ public class ListenerAdapter implements DataChangeListener { */ private void addValuesToDataChangedNotificationEventElement(final Document doc, final Element dataChangedNotificationEventElement, - final DataChangeEvent change) { - addValuesFromDataToElement(doc, change.getCreatedConfigurationData(), dataChangedNotificationEventElement, - Store.CONFIG, Operation.CREATED); - addValuesFromDataToElement(doc, change.getCreatedOperationalData(), dataChangedNotificationEventElement, - Store.OPERATION, Operation.CREATED); - if (change.getCreatedConfigurationData().isEmpty()) { - addValuesFromDataToElement(doc, change.getUpdatedConfigurationData(), dataChangedNotificationEventElement, - Store.CONFIG, Operation.UPDATED); - } - if (change.getCreatedOperationalData().isEmpty()) { - addValuesFromDataToElement(doc, change.getUpdatedOperationalData(), dataChangedNotificationEventElement, - Store.OPERATION, Operation.UPDATED); + AsyncDataChangeEvent> change) { + addValuesFromDataToElement(doc, change.getCreatedData().keySet(), dataChangedNotificationEventElement, + Operation.CREATED); + if (change.getCreatedData().isEmpty()) { + addValuesFromDataToElement(doc, change.getUpdatedData().keySet(), dataChangedNotificationEventElement, + Operation.UPDATED); } - addValuesFromDataToElement(doc, change.getRemovedConfigurationData(), dataChangedNotificationEventElement, - Store.CONFIG, Operation.DELETED); - addValuesFromDataToElement(doc, change.getRemovedOperationalData(), dataChangedNotificationEventElement, - Store.OPERATION, Operation.DELETED); + addValuesFromDataToElement(doc, change.getRemovedPaths(), dataChangedNotificationEventElement, + Operation.DELETED); } /** @@ -320,13 +313,13 @@ public class ListenerAdapter implements DataChangeListener { * @param operation * {@link Operation} */ - private void addValuesFromDataToElement(final Document doc, final Set data, - final Element element, final Store store, final Operation operation) { + private void addValuesFromDataToElement(Document doc, Set data, Element element, + Operation operation) { if (data == null || data.isEmpty()) { return; } for (YangInstanceIdentifier path : data) { - Node node = createDataChangeEventElement(doc, path, null, store, operation); + Node node = createDataChangeEventElement(doc, path, null, operation); element.appendChild(node); } } @@ -345,13 +338,13 @@ public class ListenerAdapter implements DataChangeListener { * @param operation * {@link Operation} */ - private void addValuesFromDataToElement(final Document doc, final Map data, - final Element element, final Store store, final Operation operation) { + private void addValuesFromDataToElement(Document doc, Map data, Element element, + Operation operation) { if (data == null || data.isEmpty()) { return; } for (Entry entry : data.entrySet()) { - Node node = createDataChangeEventElement(doc, entry.getKey(), entry.getValue(), store, operation); + Node node = createDataChangeEventElement(doc, entry.getKey(), entry.getValue(), operation); element.appendChild(node); } } @@ -371,17 +364,17 @@ public class ListenerAdapter implements DataChangeListener { * {@link Operation} * @return {@link Node} node represented by changed event element. */ - private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path, - final CompositeNode data, final Store store, final Operation operation) { + private Node createDataChangeEventElement(Document doc, YangInstanceIdentifier path, CompositeNode data, + Operation operation) { Element dataChangeEventElement = doc.createElement("data-change-event"); Element pathElement = doc.createElement("path"); addPathAsValueToElement(path, pathElement); dataChangeEventElement.appendChild(pathElement); - Element storeElement = doc.createElement("store"); - storeElement.setTextContent(store.value); - dataChangeEventElement.appendChild(storeElement); + // Element storeElement = doc.createElement("store"); + // storeElement.setTextContent(store.value); + // dataChangeEventElement.appendChild(storeElement); Element operationElement = doc.createElement("operation"); operationElement.setTextContent(operation.value); @@ -530,7 +523,7 @@ public class ListenerAdapter implements DataChangeListener { * @param registration * ListenerRegistration */ - public void setRegistration(final ListenerRegistration registration) { + public void setRegistration(final ListenerRegistration registration) { this.registration = registration; } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java index 99bd8c5aaf..17565a6b8c 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java @@ -15,12 +15,12 @@ import java.util.concurrent.locks.ReentrantLock; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; /** - * {@link Notificator} is responsible to create, remove and find {@link ListenerAdapter} listener. + * {@link Notificator} is responsible to create, remove and find + * {@link ListenerAdapter} listener. */ public class Notificator { private static Map listenersByStreamName = new ConcurrentHashMap<>(); - private static Map listenersByInstanceIdentifier = new ConcurrentHashMap<>(); private static final Lock lock = new ReentrantLock(); private Notificator() { @@ -44,26 +44,14 @@ public class Notificator { return listenersByStreamName.get(streamName); } - /** - * Gets {@link ListenerAdapter} listener specified by {@link YangInstanceIdentifier} path. - * - * @param path - * Path to data in data repository. - * @return ListenerAdapter - */ - public static ListenerAdapter getListenerFor(YangInstanceIdentifier path) { - return listenersByInstanceIdentifier.get(path); - } - /** * Checks if the listener specified by {@link YangInstanceIdentifier} path exist. * - * @param path - * Path to data in data repository. + * @param streamName * @return True if the listener exist, false otherwise. */ - public static boolean existListenerFor(YangInstanceIdentifier path) { - return listenersByInstanceIdentifier.containsKey(path); + public static boolean existListenerFor(String streamName) { + return listenersByStreamName.containsKey(streamName); } /** @@ -79,7 +67,6 @@ public class Notificator { ListenerAdapter listener = new ListenerAdapter(path, streamName); try { lock.lock(); - listenersByInstanceIdentifier.put(path, listener); listenersByStreamName.put(streamName, listener); } finally { lock.unlock(); @@ -89,16 +76,6 @@ public class Notificator { /** * Looks for listener determined by {@link YangInstanceIdentifier} path and removes it. - * - * @param path - * InstanceIdentifier - */ - public static void removeListener(YangInstanceIdentifier path) { - ListenerAdapter listener = listenersByInstanceIdentifier.get(path); - deleteListener(listener); - } - - /** * Creates String representation of stream name from URI. Removes slash from URI in start and end position. * * @param uri @@ -123,7 +100,7 @@ public class Notificator { * Removes all listeners. */ public static void removeAllListeners() { - for (ListenerAdapter listener : listenersByInstanceIdentifier.values()) { + for (ListenerAdapter listener : listenersByStreamName.values()) { try { listener.close(); } catch (Exception e) { @@ -132,7 +109,6 @@ public class Notificator { try { lock.lock(); listenersByStreamName = new ConcurrentHashMap<>(); - listenersByInstanceIdentifier = new ConcurrentHashMap<>(); } finally { lock.unlock(); } @@ -164,7 +140,6 @@ public class Notificator { } try { lock.lock(); - listenersByInstanceIdentifier.remove(listener.getPath()); listenersByStreamName.remove(listener.getStreamName()); } finally { lock.unlock(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/yang/sal-remote-augment.yang b/opendaylight/md-sal/sal-rest-connector/src/main/yang/sal-remote-augment.yang new file mode 100644 index 0000000000..83934568cc --- /dev/null +++ b/opendaylight/md-sal/sal-rest-connector/src/main/yang/sal-remote-augment.yang @@ -0,0 +1,31 @@ +module sal-remote-augment { + + yang-version 1; + namespace "urn:sal:restconf:event:subscription"; + prefix "salrmt-aug-ev-subscr"; + + import sal-remote {prefix salrmt; revision-date "2014-01-14";} + + description + "Added input parameters to rpc create-data-change-event-subscription"; + + revision "2014-7-8" { + } + + augment "/salrmt:create-data-change-event-subscription/salrmt:input" { + leaf datastore { + type enumeration { + enum OPERATIONAL; + enum CONFIGURATION; + } + } + leaf scope { + type enumeration { + enum BASE; + enum ONE; + enum SUBTREE; + } + } + } + +} \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java index 0f059f5024..d9dc26d888 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java @@ -35,6 +35,7 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.ModifyAction; import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode; import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode; +import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.impl.NodeFactory; public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { @@ -67,12 +68,12 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { */ @Test public void xmlAndYangTypesWithJsonReaderTest() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-yang-types/xml/data.xml", + Node node = TestUtils.readInputToCnSn("/cnsn-to-json/simple-yang-types/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE); - TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName); + TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName); String jsonOutput = null; try { - jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode, + jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode, StructuredDataToJsonProvider.INSTANCE); } catch (WebApplicationException | IOException e) { } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java index 0d0ce5cdd3..632d2490ee 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java @@ -17,7 +17,8 @@ import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider; import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.test.TestUtils; import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.valid.DataValidationException; public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader { @@ -31,7 +32,7 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader { * return error because nodes has to be from one case below concrete choice. * */ - @Test + @Test(expected=DataValidationException.class) public void nodeSchemasOnVariousChoiceCasePathTest() { testWrapper("/cnsn-to-json/choice/xml/data_various_path_err.xml", "choice-case-test:cont"); } @@ -42,7 +43,7 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader { * choice. * */ - @Test + @Test(expected=DataValidationException.class) public void nodeSchemasOnVariousChoiceCasePathAndMultipleChoicesTest() { testWrapper("/cnsn-to-json/choice/xml/data_more_choices_same_level_various_paths_err.xml", "choice-case-test:cont"); @@ -116,10 +117,10 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader { } private void testWrapper(String xmlPath, String pathToSchemaNode) { - CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, XmlToCompositeNodeProvider.INSTANCE); - TestUtils.normalizeCompositeNode(compNode, modules, pathToSchemaNode); + Node node = TestUtils.readInputToCnSn(xmlPath, XmlToCompositeNodeProvider.INSTANCE); + TestUtils.normalizeCompositeNode(node, modules, pathToSchemaNode); try { - TestUtils.writeCompNodeWithSchemaContextToOutput(compNode, modules, dataSchemaNode, + TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode, StructuredDataToJsonProvider.INSTANCE); } catch (WebApplicationException | IOException e) { // shouldn't end here diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java index 4b8b71440a..11051cc733 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java @@ -27,7 +27,7 @@ import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; import org.opendaylight.controller.sal.restconf.impl.test.TestUtils; import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader { @@ -189,12 +189,12 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader @Test public void simpleYangDataTest() throws Exception { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", + Node node = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE); - TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont"); + TestUtils.normalizeCompositeNode(node, modules, "simple-data-types:cont"); - String jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode, + String jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode, StructuredDataToJsonProvider.INSTANCE); assertNotNull(jsonOutput); @@ -303,10 +303,10 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader public void testBadData() throws Exception { try { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/bad-data.xml", + Node node = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/bad-data.xml", XmlToCompositeNodeProvider.INSTANCE); - TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont"); + TestUtils.normalizeCompositeNode(node, modules, "simple-data-types:cont"); fail("Expected RestconfDocumentedException"); } catch (RestconfDocumentedException e) { assertEquals("getErrorTag", ErrorTag.INVALID_VALUE, e.getErrors().get(0).getErrorTag()); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java index 50c834b1ff..3bd600dbf1 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java @@ -21,7 +21,7 @@ import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.test.TestUtils; import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; @@ -145,16 +145,15 @@ public class CnSnToJsonIncorrectTopLevelTest extends YangAndXmlAndDataSchemaLoad @Test public void incorrectTopLevelElementTest() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", - XmlToCompositeNodeProvider.INSTANCE); + Node node = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE); DataSchemaNode incorrectDataSchema = null; incorrectDataSchema = new IncorrectDataSchema(); - TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont"); + TestUtils.normalizeCompositeNode(node, modules, "simple-data-types:cont"); boolean exceptionRaised = false; try { - TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, incorrectDataSchema, + TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, incorrectDataSchema, StructuredDataToJsonProvider.INSTANCE); } catch (UnsupportedDataTypeException e) { exceptionRaised = true; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java index 6e41dcb577..b5d3528e95 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java @@ -20,7 +20,7 @@ import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider; import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.test.TestUtils; import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; /** * @@ -95,9 +95,9 @@ public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader { private String toJson(String xmlDataPath) { try { - CompositeNode compositeNode = TestUtils.readInputToCnSn(xmlDataPath, XmlToCompositeNodeProvider.INSTANCE); - TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName); - return TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode, + Node node = TestUtils.readInputToCnSn(xmlDataPath, XmlToCompositeNodeProvider.INSTANCE); + TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName); + return TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode, StructuredDataToJsonProvider.INSTANCE); } catch (WebApplicationException | IOException e) { } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java index eb6a5b9e00..72b9ed93d4 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java @@ -19,7 +19,7 @@ import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider; import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.test.TestUtils; import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader { @@ -33,13 +33,13 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader { */ @Test public void augmentedElementsToJson() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/augmentation/xml/data.xml", + Node node = TestUtils.readInputToCnSn("/cnsn-to-json/augmentation/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE); - TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName); + TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName); String jsonOutput = null; try { - jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode, + jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode, StructuredDataToJsonProvider.INSTANCE); } catch (WebApplicationException | IOException e) { } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java index 4210944de7..3adfee7f5b 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java @@ -13,12 +13,12 @@ import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.common.util.concurrent.CheckedFuture; import java.io.FileNotFoundException; import java.net.URI; import java.util.List; import org.junit.Before; import org.junit.Test; -import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; @@ -28,13 +28,10 @@ import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper; -import org.opendaylight.controller.sal.restconf.impl.test.DummyFuture; -import org.opendaylight.controller.sal.restconf.impl.test.DummyFuture.Builder; -import org.opendaylight.controller.sal.restconf.impl.test.DummyRpcResult; import org.opendaylight.controller.sal.restconf.impl.test.TestUtils; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -62,11 +59,8 @@ public class RestPutListDataTest { restconfImpl = RestconfImpl.getInstance(); restconfImpl.setBroker(brokerFacade); restconfImpl.setControllerContext(controllerContext); - Builder futureBuilder = new DummyFuture.Builder(); - futureBuilder.rpcResult(new DummyRpcResult.Builder().result(TransactionStatus.COMMITED) - .build()); - when(brokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(CompositeNode.class))) - .thenReturn(futureBuilder.build()); + when(brokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(NormalizedNode.class))) + .thenReturn(mock(CheckedFuture.class)); } /** diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java index 23b040a9a3..cda635e847 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java @@ -31,15 +31,16 @@ public class JsonIdentityrefToCnSnTest extends YangAndXmlAndDataSchemaLoader { @Test public void jsonIdentityrefToCompositeNode() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/identityref/json/data.json", false, + Node node = TestUtils.readInputToCnSn("/json-to-cnsn/identityref/json/data.json", false, JsonToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); + assertNotNull(node); - TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName); + TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName); - assertEquals("cont", compositeNode.getNodeType().getLocalName()); + assertEquals("cont", node.getNodeType().getLocalName()); - List> childs = compositeNode.getValue(); + assert(node instanceof CompositeNode); + List> childs = ((CompositeNode)node).getValue(); assertEquals(1, childs.size()); Node nd = childs.iterator().next(); assertTrue(nd instanceof CompositeNode); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java index 913e9f2d70..59696bc534 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java @@ -32,15 +32,16 @@ public class JsonLeafrefToCnSnTest extends YangAndXmlAndDataSchemaLoader { */ @Test public void jsonIdentityrefToCompositeNode() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/leafref/json/data.json", false, + Node node = TestUtils.readInputToCnSn("/json-to-cnsn/leafref/json/data.json", false, JsonToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); - TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName); + assertNotNull(node); + TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName); - assertEquals("cont", compositeNode.getNodeType().getLocalName()); + assertEquals("cont", node.getNodeType().getLocalName()); SimpleNode lf2 = null; - for (Node childNode : compositeNode.getValue()) { + assertTrue(node instanceof CompositeNode); + for (Node childNode : ((CompositeNode) node).getValue()) { if (childNode instanceof SimpleNode) { if (childNode.getNodeType().getLocalName().equals("lf2")) { lf2 = (SimpleNode) childNode; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java index 7b71e42ab8..3699e4924f 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java @@ -11,6 +11,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -52,19 +53,21 @@ public class JsonToCnSnTest { */ @Test public void multipleItemsInLeafList() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/multiple-leaflist-items.json", true, + Node node = TestUtils.readInputToCnSn("/json-to-cnsn/multiple-leaflist-items.json", true, JsonToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); + assertNotNull(node); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; assertEquals(3, compositeNode.getValue().size()); boolean lflst1_1 = false; boolean lflst1_2 = false; boolean lflst1_3 = false; - for (Node node : compositeNode.getValue()) { - assertEquals("lflst1", node.getNodeType().getLocalName()); - assertTrue(node instanceof SimpleNode); - SimpleNode simpleNode = (SimpleNode) node; + for (Node nd : compositeNode.getValue()) { + assertEquals("lflst1", nd.getNodeType().getLocalName()); + assertTrue(nd instanceof SimpleNode); + SimpleNode simpleNode = (SimpleNode) nd; if (simpleNode.getValue().equals("45")) { lflst1_1 = true; } else if (simpleNode.getValue().equals("55")) { @@ -86,9 +89,12 @@ public class JsonToCnSnTest { */ @Test public void multipleItemsInListTest() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/multiple-items-in-list.json", true, + Node node = TestUtils.readInputToCnSn("/json-to-cnsn/multiple-items-in-list.json", true, JsonToCompositeNodeProvider.INSTANCE); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; + assertNotNull(compositeNode); assertEquals("lst", compositeNode.getNodeType().getLocalName()); @@ -97,9 +103,10 @@ public class JsonToCnSnTest { @Test public void nullArrayToSimpleNodeWithNullValueTest() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/array-with-null.json", true, + Node node = TestUtils.readInputToCnSn("/json-to-cnsn/array-with-null.json", true, JsonToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; assertEquals("cont", compositeNode.getNodeType().getLocalName()); assertNotNull(compositeNode.getValue()); @@ -163,10 +170,10 @@ public class JsonToCnSnTest { */ @Test public void emptyDataReadTest() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/empty-data.json", true, + Node node = TestUtils.readInputToCnSn("/json-to-cnsn/empty-data.json", true, JsonToCompositeNodeProvider.INSTANCE); - - assertNotNull(compositeNode); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; assertEquals("cont", compositeNode.getNodeType().getLocalName()); assertTrue(compositeNode instanceof CompositeNode); @@ -189,9 +196,9 @@ public class JsonToCnSnTest { @Test public void testJsonBlankInput() throws Exception { InputStream inputStream = new ByteArrayInputStream("".getBytes()); - CompositeNode compositeNode = JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, - inputStream); - assertNull(compositeNode); + Node node = + JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream); + assertNull( node ); } /** @@ -202,9 +209,10 @@ public class JsonToCnSnTest { @Test public void notSupplyNamespaceIfAlreadySupplied() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/simple-list.json", false, + Node node = TestUtils.readInputToCnSn("/json-to-cnsn/simple-list.json", false, JsonToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; // supplement namespaces according to first data schema - // "simple:data:types1" @@ -223,15 +231,21 @@ public class JsonToCnSnTest { assertEquals("lst", compNode.getNodeType().getLocalName()); verifyCompositeNode(compNode, "simple:list:yang1"); - TestUtils.normalizeCompositeNode(compositeNode, modules2, "simple-list-yang2:lst"); + try { + TestUtils.normalizeCompositeNode(compositeNode, modules2, "simple-list-yang2:lst"); + fail("Conversion to normalized node shouldn't be successfull because of different namespaces"); + } catch (IllegalStateException e) { + } +// veryfing has still meaning. despite exception, first phase where normalization of NodeWrappers is called passed successfuly. verifyCompositeNode(compNode, "simple:list:yang1"); } @Test public void jsonIdentityrefToCompositeNode() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/identityref/json/data.json", false, + Node node = TestUtils.readInputToCnSn("/json-to-cnsn/identityref/json/data.json", false, JsonToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; Set modules = TestUtils.loadModulesFrom("/json-to-cnsn/identityref"); assertEquals(2, modules.size()); @@ -298,8 +312,9 @@ public class JsonToCnSnTest { private CompositeNode loadAndNormalizeData(final String jsonPath, final String yangPath, final String topLevelElementName, final String moduleName) { - CompositeNode compositeNode = TestUtils.readInputToCnSn(jsonPath, false, JsonToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); + Node node = TestUtils.readInputToCnSn(jsonPath, false, JsonToCompositeNodeProvider.INSTANCE); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; Set modules = null; modules = TestUtils.loadModulesFrom(yangPath); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java index 73f828c646..e50c07e05a 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java @@ -12,28 +12,34 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import com.google.common.collect.ImmutableMap; +import com.google.common.base.Optional; +import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; -import java.util.Map; +import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.Future; +import org.apache.commons.lang.StringEscapeUtils; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.opendaylight.controller.md.sal.common.api.TransactionStatus; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; +import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; +import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession; -import org.opendaylight.controller.sal.core.api.data.DataBrokerService; -import org.opendaylight.controller.sal.core.api.data.DataChangeListener; -import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; -import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.controller.sal.restconf.impl.RestconfError; @@ -44,7 +50,9 @@ import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.impl.schema.Builders; /** * Unit tests for BrokerFacade. @@ -54,73 +62,83 @@ import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; public class BrokerFacadeTest { @Mock - DataBrokerService dataBroker; - - @Mock - DataModificationTransaction mockTransaction; + DOMDataBroker domDataBroker; @Mock ConsumerSession mockConsumerSession; @Mock - MountInstance mockMountInstance; + DOMMountPoint mockMountInstance; BrokerFacade brokerFacade = BrokerFacade.getInstance(); - CompositeNode dataNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml", - XmlToCompositeNodeProvider.INSTANCE); + CompositeNode dataNode; + + NormalizedNode dummyNode = createDummyNode("dummy:namespace", "2014-07-01", "dummy local name"); + ListenableFuture>> dummyNodeInFuture = wrapDummyNode(dummyNode); QName qname = QName.create("node"); YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(qname).toInstance(); + @Mock + DOMDataReadOnlyTransaction rTransaction; + + @Mock + DOMDataWriteTransaction wTransaction; + + @Mock + DOMDataReadWriteTransaction rwTransaction; + @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - - brokerFacade.setDataService(dataBroker); + // TODO it is started before every test method + brokerFacade.setDomDataBroker(domDataBroker); brokerFacade.setContext(mockConsumerSession); - } - - @Test - public void testReadConfigurationData() { - when(dataBroker.readConfigurationData(instanceID)).thenReturn(dataNode); + when(domDataBroker.newReadOnlyTransaction()).thenReturn(rTransaction); + when(domDataBroker.newWriteOnlyTransaction()).thenReturn(wTransaction); + when(domDataBroker.newReadWriteTransaction()).thenReturn(rwTransaction); - CompositeNode actualNode = brokerFacade.readConfigurationData(instanceID); + dataNode = TestUtils.prepareCompositeNodeWithIetfInterfacesInterfacesData(); - assertSame("readConfigurationData", dataNode, actualNode); } - @Test - public void testReadConfigurationDataBehindMountPoint() { - when(mockMountInstance.readConfigurationData(instanceID)).thenReturn(dataNode); - - CompositeNode actualNode = brokerFacade.readConfigurationDataBehindMountPoint(mockMountInstance, instanceID); + private ListenableFuture>> wrapDummyNode(NormalizedNode dummyNode) { + return Futures.>> immediateFuture(Optional.> of(dummyNode)); + } - assertSame("readConfigurationDataBehindMountPoint", dataNode, actualNode); + /** + * Value of this node shouldn't be important for testing purposes + */ + private NormalizedNode createDummyNode(String namespace, String date, String localName) { + return Builders.containerBuilder() + .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build(); } @Test - public void testReadOperationalData() { - when(dataBroker.readOperationalData(instanceID)).thenReturn(dataNode); + public void testReadConfigurationData() { + when(rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn( + dummyNodeInFuture); - CompositeNode actualNode = brokerFacade.readOperationalData(instanceID); + NormalizedNode actualNode = brokerFacade.readConfigurationData(instanceID); - assertSame("readOperationalData", dataNode, actualNode); + assertSame("readConfigurationData", dummyNode, actualNode); } @Test - public void testReadOperationalDataBehindMountPoint() { - when(mockMountInstance.readOperationalData(instanceID)).thenReturn(dataNode); + public void testReadOperationalData() { + when(rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn( + dummyNodeInFuture); - CompositeNode actualNode = brokerFacade.readOperationalDataBehindMountPoint(mockMountInstance, instanceID); + NormalizedNode actualNode = brokerFacade.readOperationalData(instanceID); - assertSame("readOperationalDataBehindMountPoint", dataNode, actualNode); + assertSame("readOperationalData", dummyNode, actualNode); } @Test(expected = RestconfDocumentedException.class) public void testReadOperationalDataWithNoDataBroker() { - brokerFacade.setDataService(null); + brokerFacade.setDomDataBroker(null); brokerFacade.readOperationalData(instanceID); } @@ -148,109 +166,46 @@ public class BrokerFacadeTest { @Test public void testCommitConfigurationDataPut() { - Future> expFuture = Futures.immediateFuture(null); - - when(dataBroker.beginTransaction()).thenReturn(mockTransaction); - mockTransaction.putConfigurationData(instanceID, dataNode); - when(mockTransaction.commit()).thenReturn(expFuture); + CheckedFuture expFuture = mock(CheckedFuture.class); - Future> actualFuture = brokerFacade.commitConfigurationDataPut(instanceID, - dataNode); + when(wTransaction.submit()).thenReturn(expFuture); - assertSame("invokeRpc", expFuture, actualFuture); + Future actualFuture = brokerFacade.commitConfigurationDataPut(instanceID, dummyNode); - InOrder inOrder = inOrder(dataBroker, mockTransaction); - inOrder.verify(dataBroker).beginTransaction(); - inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode); - inOrder.verify(mockTransaction).commit(); - } - - @Test - public void testCommitConfigurationDataPutBehindMountPoint() { - Future> expFuture = Futures.immediateFuture(null); - - when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction); - mockTransaction.putConfigurationData(instanceID, dataNode); - when(mockTransaction.commit()).thenReturn(expFuture); - - Future> actualFuture = brokerFacade.commitConfigurationDataPutBehindMountPoint( - mockMountInstance, instanceID, dataNode); - - assertSame("invokeRpc", expFuture, actualFuture); + assertSame("commitConfigurationDataPut", expFuture, actualFuture); - InOrder inOrder = inOrder(mockMountInstance, mockTransaction); - inOrder.verify(mockMountInstance).beginTransaction(); - inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode); - inOrder.verify(mockTransaction).commit(); + InOrder inOrder = inOrder(domDataBroker, wTransaction); + inOrder.verify(domDataBroker).newWriteOnlyTransaction(); + inOrder.verify(wTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode); + inOrder.verify(wTransaction).submit(); } @Test public void testCommitConfigurationDataPost() { - Future> expFuture = Futures.immediateFuture(null); + CheckedFuture expFuture = mock(CheckedFuture.class); - Map nodeMap = new ImmutableMap.Builder() - .put(instanceID, dataNode).build(); + NormalizedNode dummyNode2 = createDummyNode("dummy:namespace2", "2014-07-01", "dummy local name2"); + when(rwTransaction.read(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class))).thenReturn( + wrapDummyNode(dummyNode2)); + when(rwTransaction.submit()).thenReturn(expFuture); - when(dataBroker.beginTransaction()).thenReturn(mockTransaction); - mockTransaction.putConfigurationData(instanceID, dataNode); - when(mockTransaction.getCreatedConfigurationData()).thenReturn(nodeMap); - when(mockTransaction.commit()).thenReturn(expFuture); + CheckedFuture actualFuture = brokerFacade.commitConfigurationDataPost( + instanceID, dummyNode); - Future> actualFuture = brokerFacade.commitConfigurationDataPost(instanceID, - dataNode); + assertSame("commitConfigurationDataPost", expFuture, actualFuture); - assertSame("commitConfigurationDataPut", expFuture, actualFuture); - - InOrder inOrder = inOrder(dataBroker, mockTransaction); - inOrder.verify(dataBroker).beginTransaction(); - inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode); - inOrder.verify(mockTransaction).commit(); + InOrder inOrder = inOrder(domDataBroker, rwTransaction); + inOrder.verify(domDataBroker).newReadWriteTransaction(); + inOrder.verify(rwTransaction).merge(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode); + inOrder.verify(rwTransaction).submit(); } @Test(expected = RestconfDocumentedException.class) public void testCommitConfigurationDataPostAlreadyExists() { - when(dataBroker.beginTransaction()).thenReturn(mockTransaction); - mockTransaction.putConfigurationData(instanceID, dataNode); - when(mockTransaction.readConfigurationData(instanceID)).thenReturn(dataNode); - try { - brokerFacade.commitConfigurationDataPost(instanceID, dataNode); - } catch (RestconfDocumentedException e) { - assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag()); - throw e; - } - } - - @Test - public void testCommitConfigurationDataPostBehindMountPoint() { - Future> expFuture = Futures.immediateFuture(null); - - Map nodeMap = new ImmutableMap.Builder() - .put(instanceID, dataNode).build(); - - when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction); - mockTransaction.putConfigurationData(instanceID, dataNode); - when(mockTransaction.getCreatedConfigurationData()).thenReturn(nodeMap); - when(mockTransaction.commit()).thenReturn(expFuture); - - Future> actualFuture = brokerFacade.commitConfigurationDataPostBehindMountPoint( - mockMountInstance, instanceID, dataNode); - - assertSame("commitConfigurationDataPostBehindMountPoint", expFuture, actualFuture); - - InOrder inOrder = inOrder(mockMountInstance, mockTransaction); - inOrder.verify(mockMountInstance).beginTransaction(); - inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode); - inOrder.verify(mockTransaction).commit(); - } - - @Test(expected = RestconfDocumentedException.class) - public void testCommitConfigurationDataPostBehindMountPointAlreadyExists() { - - when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction); - mockTransaction.putConfigurationData(instanceID, dataNode); - when(mockTransaction.readConfigurationData(instanceID)).thenReturn(dataNode); + when(rwTransaction.read(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class))).thenReturn( + dummyNodeInFuture); try { - brokerFacade.commitConfigurationDataPostBehindMountPoint(mockMountInstance, instanceID, dataNode); + brokerFacade.commitConfigurationDataPost(instanceID, dummyNode); } catch (RestconfDocumentedException e) { assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag()); throw e; @@ -259,43 +214,19 @@ public class BrokerFacadeTest { @Test public void testCommitConfigurationDataDelete() { - Future> expFuture = Futures.immediateFuture(null); + CheckedFuture expFuture = mock(CheckedFuture.class); - when(dataBroker.beginTransaction()).thenReturn(mockTransaction); - when(mockTransaction.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn( - ImmutableCompositeNode.builder().toInstance()); - mockTransaction.removeConfigurationData(instanceID); - when(mockTransaction.commit()).thenReturn(expFuture); + when(wTransaction.submit()).thenReturn(expFuture); - Future> actualFuture = brokerFacade.commitConfigurationDataDelete(instanceID); + CheckedFuture actualFuture = brokerFacade + .commitConfigurationDataDelete(instanceID); assertSame("commitConfigurationDataDelete", expFuture, actualFuture); - InOrder inOrder = inOrder(dataBroker, mockTransaction); - inOrder.verify(dataBroker).beginTransaction(); - inOrder.verify(mockTransaction).removeConfigurationData(instanceID); - inOrder.verify(mockTransaction).commit(); - } - - @Test - public void testCommitConfigurationDataDeleteBehindMountPoint() { - Future> expFuture = Futures.immediateFuture(null); - - when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction); - when(mockTransaction.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn( - ImmutableCompositeNode.builder().toInstance()); - mockTransaction.removeConfigurationData(instanceID); - when(mockTransaction.commit()).thenReturn(expFuture); - - Future> actualFuture = brokerFacade.commitConfigurationDataDeleteBehindMountPoint( - mockMountInstance, instanceID); - - assertSame("commitConfigurationDataDeleteBehindMountPoint", expFuture, actualFuture); - - InOrder inOrder = inOrder(mockMountInstance, mockTransaction); - inOrder.verify(mockMountInstance).beginTransaction(); - inOrder.verify(mockTransaction).removeConfigurationData(instanceID); - inOrder.verify(mockTransaction).commit(); + InOrder inOrder = inOrder(domDataBroker, wTransaction); + inOrder.verify(domDataBroker).newWriteOnlyTransaction(); + inOrder.verify(wTransaction).delete(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)); + inOrder.verify(wTransaction).submit(); } @SuppressWarnings("unchecked") @@ -303,16 +234,23 @@ public class BrokerFacadeTest { public void testRegisterToListenDataChanges() { ListenerAdapter listener = Notificator.createListener(instanceID, "stream"); - ListenerRegistration mockRegistration = mock(ListenerRegistration.class); - when(dataBroker.registerDataChangeListener(instanceID, listener)).thenReturn(mockRegistration); + ListenerRegistration mockRegistration = mock(ListenerRegistration.class); + + when( + domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(instanceID), eq(listener), + eq(DataChangeScope.BASE))).thenReturn(mockRegistration); - brokerFacade.registerToListenDataChanges(listener); + brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener); - verify(dataBroker).registerDataChangeListener(instanceID, listener); + verify(domDataBroker).registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, instanceID, listener, + DataChangeScope.BASE); assertEquals("isListening", true, listener.isListening()); - brokerFacade.registerToListenDataChanges(listener); - verifyNoMoreInteractions(dataBroker); + brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener); + verifyNoMoreInteractions(domDataBroker); + + String escapeXml = StringEscapeUtils.escapeXml("data might contain & or ! or % or ' "); + System.out.println(escapeXml); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java index 9aab841546..500baafab3 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java @@ -36,7 +36,8 @@ import javax.ws.rs.core.UriInfo; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; +import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.InstanceIdWithSchemaNode; @@ -317,9 +318,10 @@ public class InvokeRpcMethodTest { RpcDefinition mockRpc = mock(RpcDefinition.class); when(mockRpc.getQName()).thenReturn(cancelToastQName); - MountInstance mockMountPoint = mock(MountInstance.class); - when(mockMountPoint.rpc(eq(cancelToastQName), any(CompositeNode.class))).thenReturn(mockListener); - + DOMMountPoint mockMountPoint = mock(DOMMountPoint.class); + RpcProvisionRegistry mockedRpcProvisionRegistry = mock(RpcProvisionRegistry.class); + when(mockedRpcProvisionRegistry.invokeRpc(eq(cancelToastQName), any(CompositeNode.class))).thenReturn(mockListener); + when(mockMountPoint.getService(eq(RpcProvisionRegistry.class))).thenReturn(Optional.of(mockedRpcProvisionRegistry)); when(mockMountPoint.getSchemaContext()).thenReturn(TestUtils.loadSchemaContext("/invoke-rpc")); InstanceIdWithSchemaNode mockedInstanceId = mock(InstanceIdWithSchemaNode.class); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java index 5fbfc45352..478565f033 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java @@ -21,7 +21,7 @@ import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException import org.opendaylight.controller.sal.restconf.impl.RestconfError; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.model.api.Module; /** @@ -57,16 +57,16 @@ public class MultipleEqualNamesForDataNodesTest { } private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag, - MessageBodyReader messageBodyReader) { + MessageBodyReader> messageBodyReader) { try { - CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false, messageBodyReader); - assertNotNull(compositeNode); + Node node = TestUtils.readInputToCnSn(path, false, messageBodyReader); + assertNotNull(node); Set modules = null; modules = TestUtils.loadModulesFrom("/equal-data-node-names/yang"); assertNotNull(modules); - TestUtils.normalizeCompositeNode(compositeNode, modules, "equal-data-node-names" + ":" + "cont"); + TestUtils.normalizeCompositeNode(node, modules, "equal-data-node-names" + ":" + "cont"); fail("Exception RestconfDocumentedException should be raised"); } catch (RestconfDocumentedException e) { List errors = e.getErrors(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java index 66ced81817..8d5cac0204 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java @@ -10,13 +10,14 @@ package org.opendaylight.controller.sal.restconf.impl.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.common.util.concurrent.CheckedFuture; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.Set; -import java.util.concurrent.Future; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -24,13 +25,12 @@ import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.BeforeClass; import org.junit.Test; -import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider; import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; +import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; -import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -70,21 +70,14 @@ public class RestDeleteOperationTest extends JerseyTest { @Test public void deleteConfigStatusCodes() throws UnsupportedEncodingException { String uri = "/config/test-interface:interfaces"; - Future> dummyFuture = createFuture(TransactionStatus.COMMITED); - when(brokerFacade.commitConfigurationDataDelete(any(YangInstanceIdentifier.class))).thenReturn(dummyFuture); + when(brokerFacade.commitConfigurationDataDelete(any(YangInstanceIdentifier.class))).thenReturn( + mock(CheckedFuture.class)); Response response = target(uri).request(MediaType.APPLICATION_XML).delete(); assertEquals(200, response.getStatus()); - dummyFuture = createFuture(TransactionStatus.FAILED); - when(brokerFacade.commitConfigurationDataDelete(any(YangInstanceIdentifier.class))).thenReturn(dummyFuture); + doThrow(RestconfDocumentedException.class).when(brokerFacade).commitConfigurationDataDelete( + any(YangInstanceIdentifier.class)); response = target(uri).request(MediaType.APPLICATION_XML).delete(); assertEquals(500, response.getStatus()); } - - private Future> createFuture(TransactionStatus statusName) { - RpcResult rpcResult = new DummyRpcResult.Builder().result(statusName) - .build(); - return new DummyFuture.Builder().rpcResult(rpcResult).build(); - } - } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java index ac660e32bc..d4f6909081 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java @@ -18,8 +18,10 @@ import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import java.io.FileNotFoundException; -import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; @@ -33,40 +35,46 @@ import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; - import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; - import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; -import org.opendaylight.controller.sal.core.api.mount.MountService; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider; import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper; import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider; import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider; import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; -import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; -import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; -import org.opendaylight.yangtools.yang.data.api.Node; +import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; +import org.opendaylight.yangtools.yang.data.impl.schema.Builders; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder; import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder; +import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -74,9 +82,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - public class RestGetOperationTest extends JerseyTest { static class NodeData { @@ -93,7 +98,7 @@ public class RestGetOperationTest extends JerseyTest { private static RestconfImpl restconfImpl; private static SchemaContext schemaContextYangsIetf; private static SchemaContext schemaContextTestModule; - private static CompositeNode answerFromGet; + private static NormalizedNode answerFromGet; private static SchemaContext schemaContextModules; private static SchemaContext schemaContextBehindMountPoint; @@ -101,7 +106,7 @@ public class RestGetOperationTest extends JerseyTest { private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf"; @BeforeClass - public static void init() throws FileNotFoundException { + public static void init() throws FileNotFoundException, ParseException { schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs"); schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module"); ControllerContext controllerContext = ControllerContext.getInstance(); @@ -110,7 +115,7 @@ public class RestGetOperationTest extends JerseyTest { restconfImpl = RestconfImpl.getInstance(); restconfImpl.setBroker(brokerFacade); restconfImpl.setControllerContext(controllerContext); - answerFromGet = prepareCompositeNodeWithIetfInterfacesInterfacesData(); + answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData(); schemaContextModules = TestUtils.loadSchemaContext("/modules"); schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point"); @@ -161,14 +166,13 @@ public class RestGetOperationTest extends JerseyTest { * MountPoint test. URI represents mount point. */ @Test - public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException { - when( - brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class), - any(YangInstanceIdentifier.class))).thenReturn(prepareCnDataForMountPointTest()); - MountInstance mountInstance = mock(MountInstance.class); + public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException, ParseException { + when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn( + prepareCnDataForMountPointTest(false)); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); ControllerContext.getInstance().setMountService(mockMountService); @@ -188,20 +192,18 @@ public class RestGetOperationTest extends JerseyTest { * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, YangInstanceIdentifier)} which is called in * method {@link RestconfImpl#readConfigurationData} * - * * @throws ParseException */ @Test public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException, ParseException { YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList(); - when( - brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class), - eq(awaitedInstanceIdentifier))).thenReturn(prepareCnDataForMountPointTest()); - MountInstance mountInstance = mock(MountInstance.class); + when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier))).thenReturn( + prepareCnDataForSlashesBehindMountPointTest()); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); ControllerContext.getInstance().setMountService(mockMountService); @@ -219,24 +221,25 @@ public class RestGetOperationTest extends JerseyTest { QName qNameKeyList = QName.create(uri, revision, "lf11"); parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameCont)); + parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameList)); parameters.add(new YangInstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList, "GigabitEthernet0/0/0/0")); return YangInstanceIdentifier.create(parameters); } @Test - public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException { - when( - brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class), - any(YangInstanceIdentifier.class))).thenReturn(prepareCnDataForMountPointTest()); - MountInstance mountInstance = mock(MountInstance.class); + public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException, + ParseException { + when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn( + prepareCnDataForMountPointTest(true)); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); ControllerContext.getInstance().setMountService(mockMountService); - String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"; + String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont"; assertEquals(200, get(uri, MediaType.APPLICATION_XML)); } @@ -361,10 +364,10 @@ public class RestGetOperationTest extends JerseyTest { ControllerContext controllerContext = ControllerContext.getInstance(); controllerContext.setGlobalSchema(schemaContextModules); - MountInstance mountInstance = mock(MountInstance.class); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); controllerContext.setMountService(mockMountService); @@ -450,10 +453,10 @@ public class RestGetOperationTest extends JerseyTest { ControllerContext controllerContext = ControllerContext.getInstance(); controllerContext.setGlobalSchema(schemaContextModules); - MountInstance mountInstance = mock(MountInstance.class); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); controllerContext.setMountService(mockMountService); @@ -484,10 +487,10 @@ public class RestGetOperationTest extends JerseyTest { ControllerContext controllerContext = ControllerContext.getInstance(); controllerContext.setGlobalSchema(schemaContextModules); - MountInstance mountInstance = mock(MountInstance.class); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); controllerContext.setMountService(mockMountService); @@ -636,11 +639,30 @@ public class RestGetOperationTest extends JerseyTest { return target(uri).request(mediaType).get().getStatus(); } - private CompositeNode prepareCnDataForMountPointTest() throws URISyntaxException { - CompositeNodeWrapper cont1 = new CompositeNodeWrapper(new URI("test:module"), "cont1"); - SimpleNodeWrapper lf11 = new SimpleNodeWrapper(new URI("test:module"), "lf11", "lf11 value"); - cont1.addValue(lf11); - return cont1.unwrap(); + /** + container cont { + container cont1 { + leaf lf11 { + type string; + } + */ + private NormalizedNode prepareCnDataForMountPointTest(boolean wrapToCont) throws URISyntaxException, ParseException { + String testModuleDate = "2014-01-09"; + ContainerNode contChild = Builders + .containerBuilder() + .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate)) + .withChild( + Builders.leafBuilder() + .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate)) + .withValue("lf11 value").build()).build(); + + if (wrapToCont) { + return Builders.containerBuilder() + .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate)) + .withChild(contChild).build(); + } + return contChild; + } private void mockReadOperationalDataMethod() { @@ -651,22 +673,20 @@ public class RestGetOperationTest extends JerseyTest { when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet); } - private static CompositeNode prepareCompositeNodeWithIetfInterfacesInterfacesData() { - CompositeNode intface; - try { - intface = new CompositeNodeWrapper(new URI("interface"), "interface"); - List> childs = new ArrayList<>(); - - childs.add(new SimpleNodeWrapper(new URI("name"), "name", "eth0")); - childs.add(new SimpleNodeWrapper(new URI("type"), "type", "ethernetCsmacd")); - childs.add(new SimpleNodeWrapper(new URI("enabled"), "enabled", Boolean.FALSE)); - childs.add(new SimpleNodeWrapper(new URI("description"), "description", "some interface")); - intface.setValue(childs); - return intface; - } catch (URISyntaxException e) { - } - - return null; + private NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws ParseException { + CollectionNodeBuilder lst1 = ImmutableMapNodeBuilder.create(); + lst1.withNodeIdentifier(TestUtils.getNodeIdentifier("lst1", "test:module", "2014-01-09")); + lst1.withChild(ImmutableMapEntryNodeBuilder + .create() + .withNodeIdentifier( + TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11", + "GigabitEthernet0/0/0/0")) + .withChild( + ImmutableLeafNodeBuilder.create() + .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09")) + .withValue("GigabitEthernet0/0/0/0").build()).build()); + + return lst1.build(); } /** @@ -682,6 +702,7 @@ public class RestGetOperationTest extends JerseyTest { private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws UnsupportedEncodingException { mockReadConfigurationDataMethod(); + mockReadOperationalDataMethod(); String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0"; Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get(); String xmlData = response.readEntity(String.class); @@ -726,7 +747,14 @@ public class RestGetOperationTest extends JerseyTest { toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")), toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value"))); - when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(depth1Cont); + Module module = TestUtils.findModule(schemaContextModules.getModules(), "nested-module"); + assertNotNull(module); + + DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode("depth1-cont", module); + assertNotNull(dataSchemaNode); + + when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn( + TestUtils.compositeNodeToDatastoreNormalizedNode(depth1Cont, dataSchemaNode)); // Test config with depth 1 @@ -852,7 +880,18 @@ public class RestGetOperationTest extends JerseyTest { toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")), toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value"))); - when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(depth2Cont1); + assertTrue(dataSchemaNode instanceof DataNodeContainer); + DataSchemaNode depth2cont1Schema = null; + for (DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) { + if (childNode.getQName().getLocalName().equals("depth2-cont1")) { + depth2cont1Schema = childNode; + break; + } + } + assertNotNull(depth2Cont1); + + when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn( + TestUtils.compositeNodeToDatastoreNormalizedNode(depth2Cont1, depth2cont1Schema)); response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3") .request("application/xml").get(); @@ -876,7 +915,7 @@ public class RestGetOperationTest extends JerseyTest { UriInfo mockInfo = mock(UriInfo.class); when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer>() { @Override - public MultivaluedMap answer(final InvocationOnMock invocation) { + public MultivaluedMap answer(InvocationOnMock invocation) { return paramMap; } }); @@ -901,8 +940,9 @@ public class RestGetOperationTest extends JerseyTest { } private void verifyXMLResponse(final Response response, final NodeData nodeData) { - - Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity()); + Document doc = response.readEntity(Document.class); +// Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity()); +// System.out.println(); assertNotNull("Could not parse XML document", doc); // System.out.println(TestUtils.getDocumentInPrintableForm( doc )); @@ -913,11 +953,11 @@ public class RestGetOperationTest extends JerseyTest { @SuppressWarnings("unchecked") private void verifyContainerElement(final Element element, final NodeData nodeData) { - assertEquals("Element local name", nodeData.key, element.getNodeName()); + assertEquals("Element local name", nodeData.key, element.getLocalName()); NodeList childNodes = element.getChildNodes(); if (nodeData.data == null) { // empty container - assertTrue("Expected no child elements for \"" + element.getNodeName() + "\"", childNodes.getLength() == 0); + assertTrue("Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0); return; } @@ -933,21 +973,21 @@ public class RestGetOperationTest extends JerseyTest { } Element actualElement = (Element) actualChild; - NodeData expChild = expChildMap.remove(actualElement.getNodeName()); + NodeData expChild = expChildMap.remove(actualElement.getLocalName()); assertNotNull( - "Unexpected child element for parent \"" + element.getNodeName() + "\": " - + actualElement.getNodeName(), expChild); + "Unexpected child element for parent \"" + element.getLocalName() + "\": " + + actualElement.getLocalName(), expChild); if (expChild.data == null || expChild.data instanceof List) { verifyContainerElement(actualElement, expChild); } else { - assertEquals("Text content for element: " + actualElement.getNodeName(), expChild.data, + assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data, actualElement.getTextContent()); } } if (!expChildMap.isEmpty()) { - fail("Missing elements for parent \"" + element.getNodeName() + "\": " + expChildMap.keySet()); + fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet()); } } @@ -990,4 +1030,5 @@ public class RestGetOperationTest extends JerseyTest { private NodeData toSimpleNodeData(final QName key, final Object value) { return new NodeData(key, value); } + } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java index 979b58b78a..97cd67d34b 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java @@ -9,12 +9,16 @@ package org.opendaylight.controller.sal.restconf.impl.test; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML; +import com.google.common.base.Optional; +import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import java.io.IOException; import java.io.InputStream; @@ -27,7 +31,6 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; -import java.util.concurrent.Future; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; @@ -37,8 +40,8 @@ import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.opendaylight.controller.md.sal.common.api.TransactionStatus; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; -import org.opendaylight.controller.sal.core.api.mount.MountService; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.controller.sal.rest.api.Draft02; import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider; import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper; @@ -48,14 +51,16 @@ import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; +import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -77,7 +82,7 @@ public class RestPostOperationTest extends JerseyTest { private static SchemaContext schemaContextTestModule; private static SchemaContext schemaContext; - private static MountService mountService; + private static DOMMountPointService mountService; @BeforeClass public static void init() throws URISyntaxException, IOException { @@ -124,10 +129,9 @@ public class RestPostOperationTest extends JerseyTest { assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput)); List rpcErrors = new ArrayList<>(); - rpcErrors.add( RpcResultBuilder.newError( ErrorType.RPC, "tag1", "message1", - "applicationTag1", "info1", null ) ); - rpcErrors.add( RpcResultBuilder.newWarning( ErrorType.PROTOCOL, "tag2", "message2", - "applicationTag2", "info2", null ) ); + rpcErrors.add(RpcResultBuilder.newError(ErrorType.RPC, "tag1", "message1", "applicationTag1", "info1", null)); + rpcErrors.add(RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "tag2", "message2", "applicationTag2", "info2", + null)); mockInvokeRpc(null, false, rpcErrors); assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput)); @@ -138,28 +142,25 @@ public class RestPostOperationTest extends JerseyTest { @Test public void postConfigOnlyStatusCodes() throws UnsupportedEncodingException { controllerContext.setSchemas(schemaContextYangsIetf); - mockCommitConfigurationDataPostMethod(TransactionStatus.COMMITED); String uri = "/config"; + mockCommitConfigurationDataPostMethod(true); assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath)); - mockCommitConfigurationDataPostMethod(null); - assertEquals(202, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath)); - - mockCommitConfigurationDataPostMethod(TransactionStatus.FAILED); + mockCommitConfigurationDataPostMethod(false); assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath)); + + assertEquals(400, post(uri, MediaType.APPLICATION_XML, "")); } @Test public void postConfigStatusCodes() throws UnsupportedEncodingException { controllerContext.setSchemas(schemaContextYangsIetf); - mockCommitConfigurationDataPostMethod(TransactionStatus.COMMITED); String uri = "/config/ietf-interfaces:interfaces"; - assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath)); - mockCommitConfigurationDataPostMethod(null); - assertEquals(202, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath)); + mockCommitConfigurationDataPostMethod(true); + assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath)); - mockCommitConfigurationDataPostMethod(TransactionStatus.FAILED); + mockCommitConfigurationDataPostMethod(false); assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath)); assertEquals(400, post(uri, MediaType.APPLICATION_JSON, "")); @@ -168,18 +169,14 @@ public class RestPostOperationTest extends JerseyTest { @Test public void postDataViaUrlMountPoint() throws UnsupportedEncodingException { controllerContext.setSchemas(schemaContextYangsIetf); - RpcResult rpcResult = new DummyRpcResult.Builder().result( - TransactionStatus.COMMITED).build(); - Future> dummyFuture = new DummyFuture.Builder().rpcResult( - rpcResult).build(); when( - brokerFacade.commitConfigurationDataPostBehindMountPoint(any(MountInstance.class), - any(YangInstanceIdentifier.class), any(CompositeNode.class))).thenReturn(dummyFuture); + brokerFacade.commitConfigurationDataPost(any(DOMMountPoint.class), any(YangInstanceIdentifier.class), + any(NormalizedNode.class))).thenReturn(mock(CheckedFuture.class)); - MountInstance mountInstance = mock(MountInstance.class); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); ControllerContext.getInstance().setMountService(mockMountService); @@ -207,18 +204,13 @@ public class RestPostOperationTest extends JerseyTest { mockInvokeRpc(result, sucessful, Collections. emptyList()); } - private void mockCommitConfigurationDataPostMethod(TransactionStatus statusName) { - RpcResult rpcResult = new DummyRpcResult.Builder().result(statusName) - .build(); - Future> dummyFuture = null; - if (statusName != null) { - dummyFuture = new DummyFuture.Builder().rpcResult(rpcResult).build(); + private void mockCommitConfigurationDataPostMethod(final boolean succesfulComit) { + if (succesfulComit) { + doReturn(mock(CheckedFuture.class)).when(brokerFacade).commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class)); } else { - dummyFuture = new DummyFuture.Builder().build(); + doThrow(RestconfDocumentedException.class).when(brokerFacade).commitConfigurationDataPost( + any(YangInstanceIdentifier.class), any(NormalizedNode.class)); } - - when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(CompositeNode.class))) - .thenReturn(dummyFuture); } @Test @@ -226,14 +218,12 @@ public class RestPostOperationTest extends JerseyTest { initMocking(); RpcResult rpcResult = new DummyRpcResult.Builder().result( TransactionStatus.COMMITED).build(); - Future> dummyFuture = new DummyFuture.Builder().rpcResult( - rpcResult).build(); - when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(CompositeNode.class))) - .thenReturn(dummyFuture); + when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class))) + .thenReturn(mock(CheckedFuture.class)); ArgumentCaptor instanceIdCaptor = ArgumentCaptor.forClass(YangInstanceIdentifier.class); - ArgumentCaptor compNodeCaptor = ArgumentCaptor.forClass(CompositeNode.class); + ArgumentCaptor compNodeCaptor = ArgumentCaptor.forClass(NormalizedNode.class); String URI_1 = "/config"; assertEquals(204, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface)); @@ -253,20 +243,20 @@ public class RestPostOperationTest extends JerseyTest { public void createConfigurationDataNullTest() throws UnsupportedEncodingException { initMocking(); - when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(CompositeNode.class))) + when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class))) .thenReturn(null); String URI_1 = "/config"; - assertEquals(202, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface)); + assertEquals(204, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface)); String URI_2 = "/config/test-interface:interfaces"; - assertEquals(202, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData)); + assertEquals(204, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData)); } private static void initMocking() { controllerContext = ControllerContext.getInstance(); controllerContext.setSchemas(schemaContext); - mountService = mock(MountService.class); + mountService = mock(DOMMountPointService.class); controllerContext.setMountService(mountService); brokerFacade = mock(BrokerFacade.class); restconfImpl = RestconfImpl.getInstance(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPutOperationTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPutOperationTest.java index 5d837f42bd..3284546dcb 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPutOperationTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPutOperationTest.java @@ -9,15 +9,18 @@ package org.opendaylight.controller.sal.restconf.impl.test; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.common.base.Optional; +import com.google.common.util.concurrent.CheckedFuture; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; -import java.util.concurrent.Future; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; @@ -26,9 +29,9 @@ import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.BeforeClass; import org.junit.Test; -import org.opendaylight.controller.md.sal.common.api.TransactionStatus; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; -import org.opendaylight.controller.sal.core.api.mount.MountService; +import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider; import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper; import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider; @@ -36,10 +39,10 @@ import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider; import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; +import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; public class RestPutOperationTest extends JerseyTest { @@ -96,10 +99,10 @@ public class RestPutOperationTest extends JerseyTest { @Test public void putConfigStatusCodes() throws UnsupportedEncodingException { String uri = "/config/ietf-interfaces:interfaces/interface/eth0"; - mockCommitConfigurationDataPutMethod(TransactionStatus.COMMITED); + mockCommitConfigurationDataPutMethod(true); assertEquals(200, put(uri, MediaType.APPLICATION_XML, xmlData)); - mockCommitConfigurationDataPutMethod(TransactionStatus.FAILED); + mockCommitConfigurationDataPutMethod(false); assertEquals(500, put(uri, MediaType.APPLICATION_XML, xmlData)); assertEquals(400, put(uri, MediaType.APPLICATION_JSON, "")); @@ -117,18 +120,16 @@ public class RestPutOperationTest extends JerseyTest { public void testRpcResultCommitedToStatusCodesWithMountPoint() throws UnsupportedEncodingException, FileNotFoundException, URISyntaxException { - RpcResult rpcResult = new DummyRpcResult.Builder().result( - TransactionStatus.COMMITED).build(); - Future> dummyFuture = new DummyFuture.Builder().rpcResult( - rpcResult).build(); + CheckedFuture dummyFuture = mock(CheckedFuture.class); + when( - brokerFacade.commitConfigurationDataPutBehindMountPoint(any(MountInstance.class), - any(YangInstanceIdentifier.class), any(CompositeNode.class))).thenReturn(dummyFuture); + brokerFacade.commitConfigurationDataPut(any(DOMMountPoint.class), any(YangInstanceIdentifier.class), + any(NormalizedNode.class))).thenReturn(dummyFuture); - MountInstance mountInstance = mock(MountInstance.class); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); ControllerContext.getInstance().setMountService(mockMountService); @@ -141,18 +142,15 @@ public class RestPutOperationTest extends JerseyTest { @Test public void putDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException { - RpcResult rpcResult = new DummyRpcResult.Builder().result( - TransactionStatus.COMMITED).build(); - Future> dummyFuture = new DummyFuture.Builder().rpcResult( - rpcResult).build(); + CheckedFuture dummyFuture = mock(CheckedFuture.class); when( - brokerFacade.commitConfigurationDataPutBehindMountPoint(any(MountInstance.class), - any(YangInstanceIdentifier.class), any(CompositeNode.class))).thenReturn(dummyFuture); + brokerFacade.commitConfigurationDataPut(any(DOMMountPoint.class), any(YangInstanceIdentifier.class), + any(NormalizedNode.class))).thenReturn(dummyFuture); - MountInstance mountInstance = mock(MountInstance.class); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule); - MountService mockMountService = mock(MountService.class); - when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + DOMMountPointService mockMountService = mock(DOMMountPointService.class); + when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); ControllerContext.getInstance().setMountService(mockMountService); @@ -164,13 +162,14 @@ public class RestPutOperationTest extends JerseyTest { return target(uri).request(mediaType).put(Entity.entity(data, mediaType)).getStatus(); } - private void mockCommitConfigurationDataPutMethod(TransactionStatus statusName) { - RpcResult rpcResult = new DummyRpcResult.Builder().result(statusName) - .build(); - Future> dummyFuture = new DummyFuture.Builder().rpcResult( - rpcResult).build(); - when(brokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(CompositeNode.class))) - .thenReturn(dummyFuture); + private void mockCommitConfigurationDataPutMethod(final boolean noErrors) { + if (noErrors) { + doReturn(mock(CheckedFuture.class)).when(brokerFacade).commitConfigurationDataPut( + any(YangInstanceIdentifier.class), any(NormalizedNode.class)); + } else { + doThrow(RestconfDocumentedException.class).when(brokerFacade).commitConfigurationDataPut( + any(YangInstanceIdentifier.class), any(NormalizedNode.class)); + } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java index 236712b454..906695b3aa 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java @@ -15,16 +15,16 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.io.FileNotFoundException; +import java.text.ParseException; import java.util.Set; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -54,12 +54,12 @@ public class RestconfImplTest { } @Test - public void testExample() throws FileNotFoundException { - CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml", - XmlToCompositeNodeProvider.INSTANCE); + public void testExample() throws FileNotFoundException, ParseException { + NormalizedNode normalizedNodeData = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData(); BrokerFacade brokerFacade = mock(BrokerFacade.class); - when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(loadedCompositeNode); - assertEquals(loadedCompositeNode, brokerFacade.readOperationalData(null)); + when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(normalizedNodeData); + assertEquals(normalizedNodeData, + brokerFacade.readOperationalData(null)); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java index 67d98f6b55..562cac0bcf 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java @@ -14,6 +14,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.common.base.Preconditions; +import com.google.common.util.concurrent.CheckedFuture; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; @@ -25,8 +26,12 @@ import java.io.OutputStreamWriter; import java.net.URI; import java.net.URISyntaxException; import java.sql.Date; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -42,20 +47,37 @@ import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.NodeWrapper; +import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; +import org.opendaylight.controller.sal.restconf.impl.RestconfError; +import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; +import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; import org.opendaylight.controller.sal.restconf.impl.StructuredData; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory; +import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder; +import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser; +import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser; import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,7 +88,7 @@ public final class TestUtils { private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class); - private final static YangModelParser parser = new YangParserImpl(); + private final static YangContextParser parser = new YangParserImpl(); private static Set loadModules(String resourceDirectory) throws FileNotFoundException { final File testDir = new File(resourceDirectory); @@ -151,12 +173,12 @@ public final class TestUtils { * {@code dataSchemaNode}. The method {@link RestconfImpl#createConfigurationData createConfigurationData} is used * because it contains calling of method {code normalizeNode} */ - public static void normalizeCompositeNode(CompositeNode compositeNode, Set modules, String schemaNodePath) { + public static void normalizeCompositeNode(Node node, Set modules, String schemaNodePath) { RestconfImpl restconf = RestconfImpl.getInstance(); ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules)); prepareMocksForRestconf(modules, restconf); - restconf.updateConfigurationData(schemaNodePath, compositeNode); + restconf.updateConfigurationData(schemaNodePath, node); } /** @@ -229,33 +251,30 @@ public final class TestUtils { controllerContext.setSchemas(TestUtils.loadSchemaContext(modules)); - when(mockedBrokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(CompositeNode.class))) - .thenReturn( - new DummyFuture.Builder().rpcResult( - new DummyRpcResult.Builder().result(TransactionStatus.COMMITED) - .build()).build()); + when(mockedBrokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(NormalizedNode.class))) + .thenReturn(mock(CheckedFuture.class)); restconf.setControllerContext(controllerContext); restconf.setBroker(mockedBrokerFacade); } - public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces, - MessageBodyReader reader) throws WebApplicationException { + public static Node readInputToCnSn(String path, boolean dummyNamespaces, + MessageBodyReader> reader) throws WebApplicationException { InputStream inputStream = TestUtils.class.getResourceAsStream(path); try { - CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream); - assertTrue(compositeNode instanceof CompositeNodeWrapper); + final Node node = reader.readFrom(null, null, null, null, null, inputStream); + assertTrue(node instanceof CompositeNodeWrapper); if (dummyNamespaces) { try { - TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode); - return ((CompositeNodeWrapper) compositeNode).unwrap(); + TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) node); + return ((CompositeNodeWrapper) node).unwrap(); } catch (URISyntaxException e) { LOG.error(e.getMessage()); assertTrue(e.getMessage(), false); } } - return compositeNode; + return node; } catch (IOException e) { LOG.error(e.getMessage()); assertTrue(e.getMessage(), false); @@ -263,21 +282,33 @@ public final class TestUtils { return null; } - public static CompositeNode readInputToCnSn(String path, MessageBodyReader reader) { +// public static Node readInputToCnSnNew(String path, MessageBodyReader> reader) throws WebApplicationException { +// InputStream inputStream = TestUtils.class.getResourceAsStream(path); +// try { +// return reader.readFrom(null, null, null, null, null, inputStream); +// } catch (IOException e) { +// LOG.error(e.getMessage()); +// assertTrue(e.getMessage(), false); +// } +// return null; +// } + + public static Node readInputToCnSn(String path, MessageBodyReader> reader) { return readInputToCnSn(path, false, reader); } - public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set modules, + public static String writeCompNodeWithSchemaContextToOutput(Node node, Set modules, DataSchemaNode dataSchemaNode, MessageBodyWriter messageBodyWriter) throws IOException, WebApplicationException { assertNotNull(dataSchemaNode); - assertNotNull("Composite node can't be null", compositeNode); + assertNotNull("Composite node can't be null", node); ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); ControllerContext.getInstance().setSchemas(loadSchemaContext(modules)); - messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null, + assertTrue(node instanceof CompositeNode); + messageBodyWriter.writeTo(new StructuredData((CompositeNode)node, dataSchemaNode, null), null, null, null, null, null, byteArrayOS); return byteArrayOS.toString(); @@ -312,4 +343,96 @@ public final class TestUtils { Matcher matcher = pattern.matcher(jsonOutput); return matcher.matches(); } + + public static NormalizedNode compositeNodeToDatastoreNormalizedNode(final CompositeNode compositeNode, + final DataSchemaNode schema) { + List> lst = new ArrayList>(); + lst.add(compositeNode); + if (schema instanceof ContainerSchemaNode) { + return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser() + .parse(lst, (ContainerSchemaNode) schema); + } else if (schema instanceof ListSchemaNode) { + return CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser() + .parse(lst, (ListSchemaNode) schema); + } + + LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName()); + + throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, + "It wasn't possible to translate specified data to datastore readable form.")); + } + + public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(String localName, String namespace, + String revision) throws ParseException { + return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName)); + } + + public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(String localName, + String namespace, String revision, Map keys) throws ParseException { + Map predicate = new HashMap<>(); + for (String key : keys.keySet()) { + predicate.put(QName.create(namespace, revision, key), keys.get(key)); + } + + return new YangInstanceIdentifier.NodeIdentifierWithPredicates( + + QName.create(namespace, revision, localName), predicate); + } + + public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(String localName, + String namespace, String revision, String... keysAndValues) throws ParseException { + java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(revision); + if (keysAndValues.length % 2 != 0) { + new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)"); + } + Map predicate = new HashMap<>(); + + int i = 0; + while (i < keysAndValues.length) { + predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]); + } + + return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName), + predicate); + } + + public static CompositeNode prepareCompositeNodeWithIetfInterfacesInterfacesData() { + CompositeNodeBuilder interfaceBuilder = ImmutableCompositeNode.builder(); + interfaceBuilder.addLeaf(buildQName("name", "dummy", "2014-07-29"), "eth0"); + interfaceBuilder.addLeaf(buildQName("type", "dummy", "2014-07-29"), "ethernetCsmacd"); + interfaceBuilder.addLeaf(buildQName("enabled", "dummy", "2014-07-29"), "false"); + interfaceBuilder.addLeaf(buildQName("description", "dummy", "2014-07-29"), "some interface"); + return interfaceBuilder.toInstance(); + } + + static NormalizedNode prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException { + String ietfInterfacesDate = "2013-07-04"; + CollectionNodeBuilder intface = ImmutableMapNodeBuilder.create(); + String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces"; + intface.withNodeIdentifier(getNodeIdentifier("interface", namespace, ietfInterfacesDate)); + DataContainerNodeAttrBuilder mapEntryNode = ImmutableMapEntryNodeBuilder.create(); + + Map predicates = new HashMap<>(); + predicates.put("name", "eth0"); + + mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate, + predicates)); + mapEntryNode + .withChild(new ImmutableLeafNodeBuilder() + .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0") + .build()); + mapEntryNode.withChild(new ImmutableLeafNodeBuilder() + .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate)) + .withValue("ethernetCsmacd").build()); + mapEntryNode.withChild(new ImmutableLeafNodeBuilder() + .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate)) + .withValue(Boolean.FALSE).build()); + mapEntryNode.withChild(new ImmutableLeafNodeBuilder() + .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate)) + .withValue("some interface").build()); + + intface.withChild(mapEntryNode.build()); + + return intface.build(); + } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URIParametersParsing.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URIParametersParsing.java new file mode 100644 index 0000000000..3c954f840a --- /dev/null +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URIParametersParsing.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.sal.restconf.impl.test; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.FileNotFoundException; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import org.junit.Before; +import org.junit.Test; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; +import org.opendaylight.controller.sal.restconf.impl.ControllerContext; +import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; +import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter; +import org.opendaylight.controller.sal.streams.listeners.Notificator; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder; +import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; +import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder; + +public class URIParametersParsing { + + private RestconfImpl restconf; + private BrokerFacade mockedBrokerFacade; + + @Before + public void init() throws FileNotFoundException { + restconf = RestconfImpl.getInstance(); + mockedBrokerFacade = mock(BrokerFacade.class); + ControllerContext controllerContext = ControllerContext.getInstance(); + controllerContext.setSchemas(TestUtils.loadSchemaContext("/datastore-and-scope-specification")); + restconf.setControllerContext(controllerContext); + restconf.setBroker(mockedBrokerFacade); + } + + @Test + public void resolveURIParametersConcreteValues() { + resolveURIParameters("OPERATIONAL", "SUBTREE", LogicalDatastoreType.OPERATIONAL, DataChangeScope.SUBTREE); + } + + @Test + public void resolveURIParametersDefaultValues() { + resolveURIParameters(null, null, LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE); + } + + private void resolveURIParameters(final String datastore, final String scope, + final LogicalDatastoreType datastoreExpected, final DataChangeScope scopeExpected) { + + InstanceIdentifierBuilder iiBuilder = YangInstanceIdentifier.builder(); + iiBuilder.node(QName.create("dummyStreamName")); + + final String datastoreValue = datastore == null ? "CONFIGURATION" : datastore; + final String scopeValue = scope == null ? "BASE" : scope + ""; + Notificator.createListener(iiBuilder.build(), "dummyStreamName/datastore=" + datastoreValue + "/scope=" + + scopeValue); + + UriInfo mockedUriInfo = mock(UriInfo.class); + MultivaluedMap mockedMultivaluedMap = mock(MultivaluedMap.class); + when(mockedMultivaluedMap.getFirst(eq("datastore"))).thenReturn(datastoreValue); + when(mockedMultivaluedMap.getFirst(eq("scope"))).thenReturn(scopeValue); + + when(mockedUriInfo.getQueryParameters(eq(false))).thenReturn(mockedMultivaluedMap); + + UriBuilder uriBuilder = UriBuilder.fromUri("www.whatever.com"); + when(mockedUriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder); + + restconf.invokeRpc("sal-remote:create-data-change-event-subscription", prepareRpcNode(datastore, scope), + mockedUriInfo); + + ListenerAdapter listener = Notificator.getListenerFor("opendaylight-inventory:nodes/datastore=" + + datastoreValue + "/scope=" + scopeValue); + assertNotNull(listener); + + } + + private CompositeNode prepareRpcNode(final String datastore, final String scope) { + CompositeNodeBuilder inputBuilder = ImmutableCompositeNode.builder(); + inputBuilder.setQName(QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", + "2014-01-14", "input")); + inputBuilder.addLeaf( + QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "2014-01-14", "path"), + YangInstanceIdentifier.builder().node(QName.create("urn:opendaylight:inventory", "2013-08-19", "nodes")).build()); + inputBuilder.addLeaf(QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "datastore"), datastore); + inputBuilder.addLeaf(QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "scope"), scope); + return inputBuilder.toInstance(); + } +} 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 655aba267f..ed871bb527 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,7 @@ import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.common.base.Optional; import com.google.common.collect.Iterables; import java.io.FileNotFoundException; import java.util.Set; @@ -21,8 +22,8 @@ import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.opendaylight.controller.sal.core.api.mount.MountInstance; -import org.opendaylight.controller.sal.core.api.mount.MountService; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; +import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.InstanceIdWithSchemaNode; @@ -153,7 +154,7 @@ public class URITest { } public void initMountService(final boolean withSchema) { - MountService mountService = mock(MountService.class); + DOMMountPointService mountService = mock(DOMMountPointService.class); controllerContext.setMountService(mountService); BrokerFacade brokerFacade = mock(BrokerFacade.class); RestconfImpl restconfImpl = RestconfImpl.getInstance(); @@ -162,12 +163,12 @@ public class URITest { Set modules2 = TestUtils.loadModulesFrom("/test-config-data/yang2"); SchemaContext schemaContext2 = TestUtils.loadSchemaContext(modules2); - MountInstance mountInstance = mock(MountInstance.class); + DOMMountPoint mountInstance = mock(DOMMountPoint.class); if (withSchema) { when(mountInstance.getSchemaContext()).thenReturn(schemaContext2); } else { when(mountInstance.getSchemaContext()).thenReturn(null); } - when(mountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountInstance); + when(mountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance)); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java index f4e869f99f..23e868c8b2 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java @@ -26,6 +26,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; 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.Node; import org.opendaylight.yangtools.yang.data.api.SimpleNode; public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSchemaLoader { @@ -37,32 +38,44 @@ public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSch @Test public void loadXmlToCnSn() throws WebApplicationException, IOException, URISyntaxException { - CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata.xml", + Node node = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata.xml", XmlToCompositeNodeProvider.INSTANCE); + + assertTrue(node instanceof CompositeNode); + CompositeNode cnSn = (CompositeNode)node; TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath); verifyListPredicate(cnSn); } @Test public void loadXmlLeafListToCnSn() throws WebApplicationException, IOException, URISyntaxException { - CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata_leaf_list.xml", + Node node = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata_leaf_list.xml", XmlToCompositeNodeProvider.INSTANCE); + + assertTrue(node instanceof CompositeNode); + CompositeNode cnSn = (CompositeNode)node; TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath); verifyLeafListPredicate(cnSn); } @Test public void loadJsonToCnSn() throws WebApplicationException, IOException, URISyntaxException { - CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata.json", + Node node = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata.json", JsonToCompositeNodeProvider.INSTANCE); + + assertTrue(node instanceof CompositeNode); + CompositeNode cnSn = (CompositeNode)node; TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath); verifyListPredicate(cnSn); } @Test public void loadJsonLeafListToCnSn() throws WebApplicationException, IOException, URISyntaxException { - CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata_leaf_list.json", + Node node = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata_leaf_list.json", JsonToCompositeNodeProvider.INSTANCE); + assertTrue(node instanceof CompositeNode); + CompositeNode cnSn = (CompositeNode)node; + TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath); verifyLeafListPredicate(cnSn); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java index 483d90da0d..1c8e53e69f 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java @@ -8,6 +8,7 @@ package org.opendaylight.controller.sal.restconf.impl.test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URISyntaxException; @@ -29,15 +30,22 @@ public class XmlAndJsonToCnSnLeafRefTest extends YangAndXmlAndDataSchemaLoader { @Test public void loadXmlToCnSn() throws WebApplicationException, IOException, URISyntaxException { - CompositeNode cnSn = TestUtils.readInputToCnSn("/leafref/xml/xmldata.xml", XmlToCompositeNodeProvider.INSTANCE); + Node node = TestUtils.readInputToCnSn("/leafref/xml/xmldata.xml", XmlToCompositeNodeProvider.INSTANCE); + + assertTrue(node instanceof CompositeNode); + CompositeNode cnSn = (CompositeNode)node; + TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath); verifyContPredicate(cnSn, "/ns:cont/ns:lf1", "/cont/lf1", "/ns:cont/ns:lf1", "../lf1"); } @Test public void loadJsonToCnSn() throws WebApplicationException, IOException, URISyntaxException { - CompositeNode cnSn = TestUtils.readInputToCnSn("/leafref/json/jsondata.json", + Node node = TestUtils.readInputToCnSn("/leafref/json/jsondata.json", JsonToCompositeNodeProvider.INSTANCE); + assertTrue(node instanceof CompositeNode); + CompositeNode cnSn = (CompositeNode)node; + TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath); verifyContPredicate(cnSn, "/leafref-module:cont/leafref-module:lf1", "/leafref-module:cont/leafref-module:lf1", "/referenced-module:cont/referenced-module:lf1", "/leafref-module:cont/leafref-module:lf1"); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java index 70f0f050dc..121a3865bd 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java @@ -32,6 +32,9 @@ import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; import org.opendaylight.controller.sal.restconf.impl.test.TestUtils; import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; public class RestStream extends JerseyTest { @@ -68,17 +71,20 @@ public class RestStream extends JerseyTest { public void testCallRpcCallGet() throws UnsupportedEncodingException, InterruptedException { String uri = "/operations/sal-remote:create-data-change-event-subscription"; Response responseWithStreamName = post(uri, MediaType.APPLICATION_XML, getRpcInput()); - String xmlResponse = responseWithStreamName.readEntity(String.class); + Document xmlResponse = responseWithStreamName.readEntity(Document.class); assertNotNull(xmlResponse); - assertTrue(xmlResponse - .contains("ietf-interfaces:interfaces/ietf-interfaces:interface/eth0")); + Element outputElement = xmlResponse.getDocumentElement(); + assertEquals("output",outputElement.getLocalName()); - uri = "/streams/stream/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0"; + Node streamNameElement = outputElement.getFirstChild(); + assertEquals("stream-name",streamNameElement.getLocalName()); + assertEquals("ietf-interfaces:interfaces/ietf-interfaces:interface/eth0/datastore=CONFIGURATION/scope=BASE",streamNameElement.getTextContent()); + + uri = "/streams/stream/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0/datastore=CONFIGURATION/scope=BASE"; Response responseWithRedirectionUri = get(uri, MediaType.APPLICATION_XML); final URI websocketServerUri = responseWithRedirectionUri.getLocation(); assertNotNull(websocketServerUri); - assertEquals(websocketServerUri.toString(), - "http://localhost:8181/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0"); + assertTrue(websocketServerUri.toString().matches(".*http://localhost:[\\d]+/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0.*")); } private Response post(String uri, String mediaType, String data) { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java index 5a5a621d93..e992e1214e 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java @@ -8,12 +8,14 @@ package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Test; import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; import org.opendaylight.controller.sal.restconf.impl.test.TestUtils; import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.model.api.Module; public class XmlAugmentedElementToCnSnTest { @@ -25,12 +27,15 @@ public class XmlAugmentedElementToCnSnTest { } private void loadAndNormalizeData(String xmlPath, String yangPath, String topLevelElementName, String moduleName) { - CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE); - assertNotNull(compNode); + Node node = TestUtils.readInputToCnSn(xmlPath, false, + XmlToCompositeNodeProvider.INSTANCE); + assertTrue(node instanceof CompositeNode); + CompositeNode cnSn = (CompositeNode)node; + Set modules = TestUtils.loadModulesFrom(yangPath); assertNotNull(modules); - TestUtils.normalizeCompositeNode(compNode, modules, topLevelElementName + ":" + moduleName); + TestUtils.normalizeCompositeNode(cnSn, modules, topLevelElementName + ":" + moduleName); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java index 6c11bc1861..1c62b7fbdb 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java @@ -33,8 +33,11 @@ public class XmlLeafrefToCnSnTest { */ @Test public void testXmlDataContainer() { - CompositeNode compNode = TestUtils.readInputToCnSn("/xml-to-cnsn/data-container.xml", false, + Node node = TestUtils.readInputToCnSn("/xml-to-cnsn/data-container.xml", false, XmlToCompositeNodeProvider.INSTANCE); + assertTrue(node instanceof CompositeNode); + CompositeNode compNode = (CompositeNode)node; + assertNotNull(compNode); Set modules = TestUtils.loadModulesFrom("/xml-to-cnsn/data-container-yang"); @@ -76,9 +79,11 @@ public class XmlLeafrefToCnSnTest { @Test public void testXmlDataList() { - CompositeNode compNode = TestUtils.readInputToCnSn("/xml-to-cnsn/data-list.xml", false, + Node node = TestUtils.readInputToCnSn("/xml-to-cnsn/data-list.xml", false, XmlToCompositeNodeProvider.INSTANCE); - assertNotNull(compNode); + assertTrue(node instanceof CompositeNode); + CompositeNode compNode = (CompositeNode)node; + Set modules = TestUtils.loadModulesFrom("/xml-to-cnsn/data-list-yang"); assertNotNull(modules); @@ -93,22 +98,22 @@ public class XmlLeafrefToCnSnTest { CompositeNode lst1_1 = null; CompositeNode lst1_2 = null; int loopCount = 0; - for (Node node : compNode.getValue()) { - if (node.getNodeType().getLocalName().equals("lf1")) { - assertEquals(nameSpaceList, node.getNodeType().getNamespace().toString()); - assertTrue(node instanceof SimpleNode); - assertEquals("lf1", node.getValue()); + for (Node nd : compNode.getValue()) { + if (nd.getNodeType().getLocalName().equals("lf1")) { + assertEquals(nameSpaceList, nd.getNodeType().getNamespace().toString()); + assertTrue(nd instanceof SimpleNode); + assertEquals("lf1", nd.getValue()); } else { - assertTrue(node instanceof CompositeNode); + assertTrue(nd instanceof CompositeNode); switch (loopCount++) { case 0: - lst1_1 = (CompositeNode) node; + lst1_1 = (CompositeNode) nd; break; case 1: - lst1_2 = (CompositeNode) node; + lst1_2 = (CompositeNode) nd; break; } - assertEquals(nameSpaceCont, node.getNodeType().getNamespace().toString()); + assertEquals(nameSpaceCont, nd.getNodeType().getNamespace().toString()); } } // lst1_1 @@ -118,15 +123,15 @@ public class XmlLeafrefToCnSnTest { // lst1_2 SimpleNode lflst11 = null; CompositeNode cont11 = null; - for (Node node : lst1_2.getValue()) { - String nodeName = node.getNodeType().getLocalName(); + for (Node nd : lst1_2.getValue()) { + String nodeName = nd.getNodeType().getLocalName(); if (nodeName.equals("lflst11")) { - assertTrue(node instanceof SimpleNode); - lflst11 = (SimpleNode) node; + assertTrue(nd instanceof SimpleNode); + lflst11 = (SimpleNode) nd; } else if (nodeName.equals("cont11")) { - assertTrue(node instanceof CompositeNode); - cont11 = (CompositeNode) node; + assertTrue(nd instanceof CompositeNode); + cont11 = (CompositeNode) nd; } assertEquals(nameSpaceCont, compNode.getNodeType().getNamespace().toString()); } @@ -144,32 +149,35 @@ public class XmlLeafrefToCnSnTest { @Test public void testXmlEmptyData() { - CompositeNode compNode = TestUtils.readInputToCnSn("/xml-to-cnsn/empty-data.xml", true, + Node node = TestUtils.readInputToCnSn("/xml-to-cnsn/empty-data.xml", true, XmlToCompositeNodeProvider.INSTANCE); + assertTrue(node instanceof CompositeNode); + CompositeNode compNode = (CompositeNode)node; + assertEquals("cont", compNode.getNodeType().getLocalName()); SimpleNode lf1 = null; SimpleNode lflst1_1 = null; SimpleNode lflst1_2 = null; CompositeNode lst1 = null; int lflst1Count = 0; - for (Node node : compNode.getValue()) { - if (node.getNodeType().getLocalName().equals("lf1")) { - assertTrue(node instanceof SimpleNode); - lf1 = (SimpleNode) node; - } else if (node.getNodeType().getLocalName().equals("lflst1")) { - assertTrue(node instanceof SimpleNode); + for (Node nd : compNode.getValue()) { + if (nd.getNodeType().getLocalName().equals("lf1")) { + assertTrue(nd instanceof SimpleNode); + lf1 = (SimpleNode) nd; + } else if (nd.getNodeType().getLocalName().equals("lflst1")) { + assertTrue(nd instanceof SimpleNode); switch (lflst1Count++) { case 0: - lflst1_1 = (SimpleNode) node; + lflst1_1 = (SimpleNode) nd; break; case 1: - lflst1_2 = (SimpleNode) node; + lflst1_2 = (SimpleNode) nd; break; } - } else if (node.getNodeType().getLocalName().equals("lst1")) { - assertTrue(node instanceof CompositeNode); - lst1 = (CompositeNode) node; + } else if (nd.getNodeType().getLocalName().equals("lst1")) { + assertTrue(nd instanceof CompositeNode); + lst1 = (CompositeNode) nd; } } @@ -317,8 +325,10 @@ public class XmlLeafrefToCnSnTest { private void testIdentityrefToCnSn(final String xmlPath, final String yangPath, final String moduleName, final String schemaName, final int moduleCount, final String resultLocalName, final String resultNamespace) { - CompositeNode compositeNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); + Node node = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; + Set modules = TestUtils.loadModulesFrom(yangPath); assertEquals(moduleCount, modules.size()); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java index e2621d635b..d0af29e913 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java @@ -32,9 +32,12 @@ public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader { @Test public void testXmlLeafrefToCnSn() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/xml-to-cnsn/leafref/xml/data.xml", false, + Node node = TestUtils.readInputToCnSn("/xml-to-cnsn/leafref/xml/data.xml", false, XmlToCompositeNodeProvider.INSTANCE); - assertNotNull(compositeNode); + assertTrue(node instanceof CompositeNode); + CompositeNode compositeNode = (CompositeNode)node; + + assertNotNull(dataSchemaNode); TestUtils.normalizeCompositeNode(compositeNode, modules, schemaNodePath); @@ -58,10 +61,10 @@ public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader { @Test public void testXmlBlankInput() throws Exception { InputStream inputStream = new ByteArrayInputStream("".getBytes()); - CompositeNode compositeNode = XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, - inputStream); + Node node = + XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream); - assertNull(compositeNode); + assertNull( node ); } @Test @@ -72,10 +75,10 @@ public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader { return false; } }; - CompositeNode compositeNode = XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, - inputStream); + Node node = + XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream); - assertNull(compositeNode); + assertNull( node ); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/opendaylight-inventory.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/opendaylight-inventory.yang new file mode 100644 index 0000000000..e4247bee1e --- /dev/null +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/opendaylight-inventory.yang @@ -0,0 +1,19 @@ +module opendaylight-inventory { + namespace "urn:opendaylight:inventory"; + prefix inv; + + revision "2013-08-19" { + description "Initial revision of Inventory model"; + } + + + container nodes { + list node { + key "id"; + leaf id { + type string; + } + } + } + +} diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/sal-remote-augment.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/sal-remote-augment.yang new file mode 100644 index 0000000000..83934568cc --- /dev/null +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/sal-remote-augment.yang @@ -0,0 +1,31 @@ +module sal-remote-augment { + + yang-version 1; + namespace "urn:sal:restconf:event:subscription"; + prefix "salrmt-aug-ev-subscr"; + + import sal-remote {prefix salrmt; revision-date "2014-01-14";} + + description + "Added input parameters to rpc create-data-change-event-subscription"; + + revision "2014-7-8" { + } + + augment "/salrmt:create-data-change-event-subscription/salrmt:input" { + leaf datastore { + type enumeration { + enum OPERATIONAL; + enum CONFIGURATION; + } + } + leaf scope { + type enumeration { + enum BASE; + enum ONE; + enum SUBTREE; + } + } + } + +} \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/sal-remote@2014-01-14.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/sal-remote@2014-01-14.yang new file mode 100644 index 0000000000..d12e252711 --- /dev/null +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/datastore-and-scope-specification/sal-remote@2014-01-14.yang @@ -0,0 +1,98 @@ +module sal-remote { + + yang-version 1; + namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote"; + prefix "sal-remote"; + + + organization "Cisco Systems, Inc."; + contact "Martin Bobak "; + + description + "This module contains the definition of methods related to + sal remote model. + + Copyright (c)2013 Cisco Systems, Inc. All rights reserved. + + This program and the accompanying materials are made available + under the terms of the Eclipse Public License v1.0 which + accompanies this distribution, and is available at + http://www.eclipse.org/legal/epl-v10.html"; + + revision "2014-01-14" { + description + "Initial revision"; + } + + + typedef q-name { + type string; + reference + "http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#QName"; + } + + rpc create-data-change-event-subscription { + input { + leaf path { + type instance-identifier; + description "Subtree path. "; + } + } + output { + leaf stream-name { + type string; + description "Notification stream name."; + } + } + } + + notification data-changed-notification { + description "Data change notification."; + list data-change-event { + key path; + leaf path { + type instance-identifier; + } + leaf store { + type enumeration { + enum config; + enum operation; + } + } + leaf operation { + type enumeration { + enum created; + enum updated; + enum deleted; + } + } + anyxml data{ + description "DataObject "; + } + } + } + + rpc create-notification-stream { + input { + leaf-list notifications { + type q-name; + description "Notification QNames"; + } + } + output { + leaf notification-stream-identifier { + type string; + description "Unique notification stream identifier, in which notifications will be propagated"; + } + } + } + + rpc begin-transaction{ + output{ + anyxml data-modification-transaction{ + description "DataModificationTransaction xml"; + } + } + } + +} \ No newline at end of file diff --git a/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/Activator.java b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/Activator.java index 1e2cd47c9c..45070ca8b0 100644 --- a/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/Activator.java +++ b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/Activator.java @@ -8,23 +8,26 @@ package org.opendaylight.controller.networkconfig.neutron.implementation; -import java.util.Hashtable; -import java.util.Dictionary; - import org.apache.felix.dm.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.opendaylight.controller.clustering.services.IClusterContainerServices; import org.opendaylight.controller.configuration.IConfigurationContainerAware; import org.opendaylight.controller.configuration.IConfigurationContainerService; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallCRUD; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyCRUD; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleCRUD; import org.opendaylight.controller.networkconfig.neutron.INeutronFloatingIPCRUD; import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD; import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD; import org.opendaylight.controller.networkconfig.neutron.INeutronRouterCRUD; -import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD; import org.opendaylight.controller.networkconfig.neutron.INeutronSecurityGroupCRUD; import org.opendaylight.controller.networkconfig.neutron.INeutronSecurityRuleCRUD; +import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD; import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Dictionary; +import java.util.Hashtable; public class Activator extends ComponentActivatorAbstractBase { protected static final Logger logger = LoggerFactory @@ -68,7 +71,10 @@ public class Activator extends ComponentActivatorAbstractBase { NeutronSubnetInterface.class, NeutronNetworkInterface.class, NeutronSecurityGroupInterface.class, - NeutronSecurityRuleInterface.class}; + NeutronSecurityRuleInterface.class, + NeutronFirewallInterface.class, + NeutronFirewallPolicyInterface.class, + NeutronFirewallRuleInterface.class}; return res; } @@ -199,5 +205,53 @@ public class Activator extends ComponentActivatorAbstractBase { "setConfigurationContainerService", "unsetConfigurationContainerService").setRequired(true)); } + if (imp.equals(NeutronFirewallInterface.class)) { + // export the service + c.setInterface( + new String[] { INeutronFirewallCRUD.class.getName(), + IConfigurationContainerAware.class.getName()}, null); + Dictionary props = new Hashtable(); + props.put("salListenerName", "neutron"); + c.add(createContainerServiceDependency(containerName) + .setService(IClusterContainerServices.class) + .setCallbacks("setClusterContainerService", + "unsetClusterContainerService").setRequired(true)); + c.add(createContainerServiceDependency(containerName).setService( + IConfigurationContainerService.class).setCallbacks( + "setConfigurationContainerService", + "unsetConfigurationContainerService").setRequired(true)); + } + if (imp.equals(NeutronFirewallPolicyInterface.class)) { + // export the service + c.setInterface( + new String[] { INeutronFirewallPolicyCRUD.class.getName(), + IConfigurationContainerAware.class.getName()}, null); + Dictionary props = new Hashtable(); + props.put("salListenerName", "neutron"); + c.add(createContainerServiceDependency(containerName) + .setService(IClusterContainerServices.class) + .setCallbacks("setClusterContainerService", + "unsetClusterContainerService").setRequired(true)); + c.add(createContainerServiceDependency(containerName).setService( + IConfigurationContainerService.class).setCallbacks( + "setConfigurationContainerService", + "unsetConfigurationContainerService").setRequired(true)); + } + if (imp.equals(NeutronFirewallRuleInterface.class)) { + // export the service + c.setInterface( + new String[] { INeutronFirewallRuleCRUD.class.getName(), + IConfigurationContainerAware.class.getName()}, null); + Dictionary props = new Hashtable(); + props.put("salListenerName", "neutron"); + c.add(createContainerServiceDependency(containerName) + .setService(IClusterContainerServices.class) + .setCallbacks("setClusterContainerService", + "unsetClusterContainerService").setRequired(true)); + c.add(createContainerServiceDependency(containerName).setService( + IConfigurationContainerService.class).setCallbacks( + "setConfigurationContainerService", + "unsetConfigurationContainerService").setRequired(true)); + } } } diff --git a/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallInterface.java b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallInterface.java new file mode 100644 index 0000000000..60476a1d34 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallInterface.java @@ -0,0 +1,264 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.implementation; + +import org.apache.felix.dm.Component; +import org.opendaylight.controller.clustering.services.CacheConfigException; +import org.opendaylight.controller.clustering.services.CacheExistException; +import org.opendaylight.controller.clustering.services.IClusterContainerServices; +import org.opendaylight.controller.clustering.services.IClusterServices; +import org.opendaylight.controller.configuration.ConfigurationObject; +import org.opendaylight.controller.configuration.IConfigurationContainerAware; +import org.opendaylight.controller.configuration.IConfigurationContainerService; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallCRUD; +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewall; +import org.opendaylight.controller.sal.utils.IObjectReader; +import org.opendaylight.controller.sal.utils.Status; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentMap; + +public class NeutronFirewallInterface implements INeutronFirewallCRUD, IConfigurationContainerAware, IObjectReader { + private static final Logger logger = LoggerFactory.getLogger(NeutronFirewallInterface.class); + private static final String FILE_NAME = "neutron.firewall.conf"; + private String containerName = null; + + private IClusterContainerServices clusterContainerService = null; + private IConfigurationContainerService configurationService; + private ConcurrentMap firewallDB; + + // methods needed for creating caches + void setClusterContainerService(IClusterContainerServices s) { + logger.debug("Cluster Service set"); + clusterContainerService = s; + } + + void unsetClusterContainerService(IClusterContainerServices s) { + if (clusterContainerService == s) { + logger.debug("Cluster Service removed!"); + clusterContainerService = null; + } + } + + public void setConfigurationContainerService(IConfigurationContainerService service) { + logger.trace("Configuration service set: {}", service); + configurationService = service; + } + + public void unsetConfigurationContainerService(IConfigurationContainerService service) { + logger.trace("Configuration service removed: {}", service); + configurationService = null; + } + + private void allocateCache() { + if (this.clusterContainerService == null) { + logger.error("un-initialized clusterContainerService, can't create cache"); + return; + } + logger.debug("Creating Cache for Neutron Firewall"); + try { + // neutron caches + this.clusterContainerService.createCache("neutronFirewalls", + EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL)); + } catch (CacheConfigException cce) { + logger.error("Cache couldn't be created for Neutron Firewall - check cache mode"); + } catch (CacheExistException cce) { + logger.error("Cache for Neutron Firewall already exists, destroy and recreate"); + } + logger.debug("Cache successfully created for Neutron Firewall"); + } + + @SuppressWarnings ({"unchecked"}) + private void retrieveCache() { + if (clusterContainerService == null) { + logger.error("un-initialized clusterContainerService, can't retrieve cache"); + return; + } + + logger.debug("Retrieving cache for Neutron Firewall"); + firewallDB = (ConcurrentMap) clusterContainerService + .getCache("neutronFirewalls"); + if (firewallDB == null) { + logger.error("Cache couldn't be retrieved for Neutron Firewall"); + } + logger.debug("Cache was successfully retrieved for Neutron Firewall"); + } + + private void destroyCache() { + if (clusterContainerService == null) { + logger.error("un-initialized clusterMger, can't destroy cache"); + return; + } + logger.debug("Destroying Cache for HostTracker"); + clusterContainerService.destroyCache("neutronFirewalls"); + } + + private void startUp() { + allocateCache(); + retrieveCache(); + loadConfiguration(); + } + + /** + * Function called by the dependency manager when all the required + * dependencies are satisfied + */ + void init(Component c) { + Dictionary props = c.getServiceProperties(); + if (props != null) { + this.containerName = (String) props.get("containerName"); + logger.debug("Running containerName: {}", this.containerName); + } else { + // In the Global instance case the containerName is empty + this.containerName = ""; + } + startUp(); + } + + /** + * Function called by the dependency manager when at least one dependency + * become unsatisfied or when the component is shutting down because for + * example bundle is being stopped. + */ + void destroy() { + destroyCache(); + } + + /** + * Function called by dependency manager after "init ()" is called and after + * the services provided by the class are registered in the service registry + */ + void start() { + } + + /** + * Function called by the dependency manager before the services exported by + * the component are unregistered, this will be followed by a "destroy ()" + * calls + */ + void stop() { + } + + // this method uses reflection to update an object from it's delta. + + private boolean overwrite(Object target, Object delta) { + Method[] methods = target.getClass().getMethods(); + + for (Method toMethod : methods) { + if (toMethod.getDeclaringClass().equals(target.getClass()) + && toMethod.getName().startsWith("set")) { + + String toName = toMethod.getName(); + String fromName = toName.replace("set", "get"); + + try { + Method fromMethod = delta.getClass().getMethod(fromName); + Object value = fromMethod.invoke(delta, (Object[]) null); + if (value != null) { + toMethod.invoke(target, value); + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + } + return true; + } + + @Override + public boolean neutronFirewallExists(String uuid) { + return firewallDB.containsKey(uuid); + } + + @Override + public NeutronFirewall getNeutronFirewall(String uuid) { + if (!neutronFirewallExists(uuid)) { + logger.debug("No Firewall Have Been Defined"); + return null; + } + return firewallDB.get(uuid); + } + + @Override + public List getAllNeutronFirewalls() { + Set allFirewalls = new HashSet(); + for (Entry entry : firewallDB.entrySet()) { + NeutronFirewall firewall = entry.getValue(); + allFirewalls.add(firewall); + } + logger.debug("Exiting getFirewalls, Found {} OpenStackFirewall", allFirewalls.size()); + List ans = new ArrayList(); + ans.addAll(allFirewalls); + return ans; + } + + @Override + public boolean addNeutronFirewall(NeutronFirewall input) { + if (neutronFirewallExists(input.getFirewallUUID())) { + return false; + } + firewallDB.putIfAbsent(input.getFirewallUUID(), input); + return true; + } + + @Override + public boolean removeNeutronFirewall(String uuid) { + if (!neutronFirewallExists(uuid)) { + return false; + } + firewallDB.remove(uuid); + return true; + } + + @Override + public boolean updateNeutronFirewall(String uuid, NeutronFirewall delta) { + if (!neutronFirewallExists(uuid)) { + return false; + } + NeutronFirewall target = firewallDB.get(uuid); + return overwrite(target, delta); + } + + @Override + public boolean neutronFirewallInUse(String firewallUUID) { + return !neutronFirewallExists(firewallUUID); + } + + private void loadConfiguration() { + for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) { + NeutronFirewall nn = (NeutronFirewall) conf; + firewallDB.put(nn.getFirewallUUID(), nn); + } + } + + @Override + public Status saveConfiguration() { + return configurationService.persistConfiguration(new ArrayList(firewallDB.values()), + FILE_NAME); + } + + @Override + public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { + return ois.readObject(); + } + +} \ No newline at end of file diff --git a/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallPolicyInterface.java b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallPolicyInterface.java new file mode 100644 index 0000000000..84592628f0 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallPolicyInterface.java @@ -0,0 +1,268 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.implementation; + +import org.apache.felix.dm.Component; +import org.opendaylight.controller.clustering.services.CacheConfigException; +import org.opendaylight.controller.clustering.services.CacheExistException; +import org.opendaylight.controller.clustering.services.IClusterContainerServices; +import org.opendaylight.controller.clustering.services.IClusterServices; +import org.opendaylight.controller.configuration.ConfigurationObject; +import org.opendaylight.controller.configuration.IConfigurationContainerAware; +import org.opendaylight.controller.configuration.IConfigurationContainerService; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyCRUD; +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallPolicy; +import org.opendaylight.controller.sal.utils.IObjectReader; +import org.opendaylight.controller.sal.utils.Status; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentMap; + +public class NeutronFirewallPolicyInterface implements INeutronFirewallPolicyCRUD, IConfigurationContainerAware, IObjectReader { + private static final Logger logger = LoggerFactory.getLogger(NeutronFirewallPolicyInterface.class); + private static final String FILE_NAME ="neutron.firewallpolicy.conf"; + private String containerName = null; + + private IClusterContainerServices clusterContainerService = null; + private IConfigurationContainerService configurationService; + private ConcurrentMap firewallPolicyDB; + + // methods needed for creating caches + void setClusterContainerService(IClusterContainerServices s) { + logger.debug("Cluster Service set"); + clusterContainerService = s; + } + + void unsetClusterContainerService(IClusterContainerServices s) { + if (clusterContainerService == s) { + logger.debug("Cluster Service removed!"); + clusterContainerService = null; + } + } + + public void setConfigurationContainerService(IConfigurationContainerService service) { + logger.trace("Configuration service set: {}", service); + configurationService = service; + } + + public void unsetConfigurationContainerService(IConfigurationContainerService service) { + logger.trace("Configuration service removed: {}", service); + configurationService = null; + } + + private void allocateCache() { + if (this.clusterContainerService == null) { + logger.error("un-initialized clusterContainerService, can't create cache"); + return; + } + logger.debug("Creating Cache for Neutron Firewall Rule"); + try { + // neutron caches + this.clusterContainerService.createCache("neutronFirewallPolicies", + EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL)); + } catch (CacheConfigException cce) { + logger.error("Cache couldn't be created for Neutron Firewall Rule - check cache mode"); + } catch (CacheExistException cce) { + logger.error("Cache for Neutron Firewall Rule already exists, destroy and recreate"); + } + logger.debug("Cache successfully created for Neutron Firewall Rule"); + } + + @SuppressWarnings({ "unchecked" }) + private void retrieveCache() { + if (clusterContainerService == null) { + logger.error("un-initialized clusterContainerService, can't retrieve cache"); + return; + } + + logger.debug("Retrieving cache for Neutron Firewall Rule"); + firewallPolicyDB = (ConcurrentMap) clusterContainerService + .getCache("neutronFirewallPolicies"); + if (firewallPolicyDB == null) { + logger.error("Cache couldn't be retrieved for Neutron Firewall Rule"); + } + logger.debug("Cache was successfully retrieved for Neutron Firewall Rule"); + } + + private void destroyCache() { + if (clusterContainerService == null) { + logger.error("un-initialized clusterMger, can't destroy cache"); + return; + } + logger.debug("Destroying Cache for HostTracker"); + clusterContainerService.destroyCache("neutronFirewallPolicies"); + } + + private void startUp() { + allocateCache(); + retrieveCache(); + loadConfiguration(); + } + + /** + * Function called by the dependency manager when all the required + * dependencies are satisfied + * + */ + void init(Component c) { + Dictionary props = c.getServiceProperties(); + if (props != null) { + this.containerName = (String) props.get("containerName"); + logger.debug("Running containerName: {}", this.containerName); + } else { + // In the Global instance case the containerName is empty + this.containerName = ""; + } + startUp(); + } + + /** + * Function called by the dependency manager when at least one dependency + * become unsatisfied or when the component is shutting down because for + * example bundle is being stopped. + * + */ + void destroy() { + destroyCache(); + } + + /** + * Function called by dependency manager after "init ()" is called and after + * the services provided by the class are registered in the service registry + * + */ + void start() { + } + + /** + * Function called by the dependency manager before the services exported by + * the component are unregistered, this will be followed by a "destroy ()" + * calls + * + */ + void stop() { + } + + // this method uses reflection to update an object from it's delta. + + private boolean overwrite(Object target, Object delta) { + Method[] methods = target.getClass().getMethods(); + + for(Method toMethod: methods){ + if(toMethod.getDeclaringClass().equals(target.getClass()) + && toMethod.getName().startsWith("set")){ + + String toName = toMethod.getName(); + String fromName = toName.replace("set", "get"); + + try { + Method fromMethod = delta.getClass().getMethod(fromName); + Object value = fromMethod.invoke(delta, (Object[])null); + if(value != null){ + toMethod.invoke(target, value); + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + } + return true; + } + + @Override + public boolean neutronFirewallPolicyExists(String uuid) { + return firewallPolicyDB.containsKey(uuid); + } + + @Override + public NeutronFirewallPolicy getNeutronFirewallPolicy(String uuid) { + if (!neutronFirewallPolicyExists(uuid)) { + logger.debug("No Firewall Rule Have Been Defined"); + return null; + } + return firewallPolicyDB.get(uuid); + } + + @Override + public List getAllNeutronFirewallPolicies() { + Set allFirewallPolicies = new HashSet(); + for (Entry entry : firewallPolicyDB.entrySet()) { + NeutronFirewallPolicy firewallPolicy = entry.getValue(); + allFirewallPolicies.add(firewallPolicy); + } + logger.debug("Exiting getFirewallPolicies, Found {} OpenStackFirewallPolicy", allFirewallPolicies.size()); + List ans = new ArrayList(); + ans.addAll(allFirewallPolicies); + return ans; + } + + @Override + public boolean addNeutronFirewallPolicy(NeutronFirewallPolicy input) { + if (neutronFirewallPolicyExists(input.getFirewallPolicyUUID())) { + return false; + } + firewallPolicyDB.putIfAbsent(input.getFirewallPolicyUUID(), input); + return true; + } + + @Override + public boolean removeNeutronFirewallPolicy(String uuid) { + if (!neutronFirewallPolicyExists(uuid)) { + return false; + } + firewallPolicyDB.remove(uuid); + return true; + } + + @Override + public boolean updateNeutronFirewallPolicy(String uuid, NeutronFirewallPolicy delta) { + if (!neutronFirewallPolicyExists(uuid)) { + return false; + } + NeutronFirewallPolicy target = firewallPolicyDB.get(uuid); + return overwrite(target, delta); + } + + @Override + public boolean neutronFirewallPolicyInUse(String firewallPolicyUUID) { + return !neutronFirewallPolicyExists(firewallPolicyUUID); + } + + private void loadConfiguration() { + for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) { + NeutronFirewallPolicy nn = (NeutronFirewallPolicy) conf; + firewallPolicyDB.put(nn.getFirewallPolicyUUID(), nn); + } + } + + @Override + public Status saveConfiguration() { + return configurationService.persistConfiguration(new ArrayList(firewallPolicyDB.values()), + FILE_NAME); + } + + @Override + public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { + return ois.readObject(); + } + +} \ No newline at end of file diff --git a/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallRuleInterface.java b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallRuleInterface.java new file mode 100644 index 0000000000..ba84500cd7 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallRuleInterface.java @@ -0,0 +1,267 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.implementation; + +import org.apache.felix.dm.Component; +import org.opendaylight.controller.clustering.services.CacheConfigException; +import org.opendaylight.controller.clustering.services.CacheExistException; +import org.opendaylight.controller.clustering.services.IClusterContainerServices; +import org.opendaylight.controller.clustering.services.IClusterServices; +import org.opendaylight.controller.configuration.ConfigurationObject; +import org.opendaylight.controller.configuration.IConfigurationContainerAware; +import org.opendaylight.controller.configuration.IConfigurationContainerService; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleCRUD; +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallRule; +import org.opendaylight.controller.sal.utils.IObjectReader; +import org.opendaylight.controller.sal.utils.Status; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentMap; + +public class NeutronFirewallRuleInterface implements INeutronFirewallRuleCRUD, IConfigurationContainerAware, IObjectReader { + private static final Logger logger = LoggerFactory.getLogger(NeutronFirewallRuleInterface.class); + private static final String FILE_NAME ="neutron.firewallrules.conf"; + private String containerName = null; + + private IClusterContainerServices clusterContainerService = null; + private IConfigurationContainerService configurationService; + private ConcurrentMap firewallRuleDB; + + // methods needed for creating caches + void setClusterContainerService(IClusterContainerServices s) { + logger.debug("Cluster Service set"); + clusterContainerService = s; + } + + void unsetClusterContainerService(IClusterContainerServices s) { + if (clusterContainerService == s) { + logger.debug("Cluster Service removed!"); + clusterContainerService = null; + } + } + + public void setConfigurationContainerService(IConfigurationContainerService service) { + logger.trace("Configuration service set: {}", service); + configurationService = service; + } + + public void unsetConfigurationContainerService(IConfigurationContainerService service) { + logger.trace("Configuration service removed: {}", service); + configurationService = null; + } + + private void allocateCache() { + if (this.clusterContainerService == null) { + logger.error("un-initialized clusterContainerService, can't create cache"); + return; + } + logger.debug("Creating Cache for Neutron Firewall Rule"); + try { + // neutron caches + this.clusterContainerService.createCache("neutronFirewallRules", + EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL)); + } catch (CacheConfigException cce) { + logger.error("Cache couldn't be created for Neutron Firewall Rule - check cache mode"); + } catch (CacheExistException cce) { + logger.error("Cache for Neutron Firewall Rule already exists, destroy and recreate"); + } + logger.debug("Cache successfully created for Neutron Firewall Rule"); + } + + @SuppressWarnings({ "unchecked" }) + private void retrieveCache() { + if (clusterContainerService == null) { + logger.error("un-initialized clusterContainerService, can't retrieve cache"); + return; + } + + logger.debug("Retrieving cache for Neutron Firewall Rule"); + firewallRuleDB = (ConcurrentMap) clusterContainerService + .getCache("neutronFirewallRules"); + if (firewallRuleDB == null) { + logger.error("Cache couldn't be retrieved for Neutron Firewall Rule"); + } + logger.debug("Cache was successfully retrieved for Neutron Firewall Rule"); + } + + private void destroyCache() { + if (clusterContainerService == null) { + logger.error("un-initialized clusterMger, can't destroy cache"); + return; + } + logger.debug("Destroying Cache for HostTracker"); + clusterContainerService.destroyCache("neutronFirewallRules"); + } + + private void startUp() { + allocateCache(); + retrieveCache(); + loadConfiguration(); + } + + /** + * Function called by the dependency manager when all the required + * dependencies are satisfied + * + */ + void init(Component c) { + Dictionary props = c.getServiceProperties(); + if (props != null) { + this.containerName = (String) props.get("containerName"); + logger.debug("Running containerName: {}", this.containerName); + } else { + // In the Global instance case the containerName is empty + this.containerName = ""; + } + startUp(); + } + + /** + * Function called by the dependency manager when at least one dependency + * become unsatisfied or when the component is shutting down because for + * example bundle is being stopped. + * + */ + void destroy() { + destroyCache(); + } + + /** + * Function called by dependency manager after "init ()" is called and after + * the services provided by the class are registered in the service registry + * + */ + void start() { + } + + /** + * Function called by the dependency manager before the services exported by + * the component are unregistered, this will be followed by a "destroy ()" + * calls + * + */ + void stop() { + } + + // this method uses reflection to update an object from it's delta. + + private boolean overwrite(Object target, Object delta) { + Method[] methods = target.getClass().getMethods(); + + for(Method toMethod: methods){ + if(toMethod.getDeclaringClass().equals(target.getClass()) + && toMethod.getName().startsWith("set")){ + + String toName = toMethod.getName(); + String fromName = toName.replace("set", "get"); + + try { + Method fromMethod = delta.getClass().getMethod(fromName); + Object value = fromMethod.invoke(delta, (Object[])null); + if(value != null){ + toMethod.invoke(target, value); + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + } + return true; + } + + @Override + public boolean neutronFirewallRuleExists(String uuid) { + return firewallRuleDB.containsKey(uuid); + } + + @Override + public NeutronFirewallRule getNeutronFirewallRule(String uuid) { + if (!neutronFirewallRuleExists(uuid)) { + logger.debug("No Firewall Rule Have Been Defined"); + return null; + } + return firewallRuleDB.get(uuid); + } + + @Override + public List getAllNeutronFirewallRules() { + Set allFirewallRules = new HashSet(); + for (Entry entry : firewallRuleDB.entrySet()) { + NeutronFirewallRule firewallRule = entry.getValue(); + allFirewallRules.add(firewallRule); + } + logger.debug("Exiting getFirewallRules, Found {} OpenStackFirewallRule", allFirewallRules.size()); + List ans = new ArrayList(); + ans.addAll(allFirewallRules); + return ans; + } + + @Override + public boolean addNeutronFirewallRule(NeutronFirewallRule input) { + if (neutronFirewallRuleExists(input.getFirewallRuleUUID())) { + return false; + } + firewallRuleDB.putIfAbsent(input.getFirewallRuleUUID(), input); + return true; + } + + @Override + public boolean removeNeutronFirewallRule(String uuid) { + if (!neutronFirewallRuleExists(uuid)) { + return false; + } + firewallRuleDB.remove(uuid); + return true; + } + + @Override + public boolean updateNeutronFirewallRule(String uuid, NeutronFirewallRule delta) { + if (!neutronFirewallRuleExists(uuid)) { + return false; + } + NeutronFirewallRule target = firewallRuleDB.get(uuid); + return overwrite(target, delta); + } + + @Override + public boolean neutronFirewallRuleInUse(String firewallRuleUUID) { + return !neutronFirewallRuleExists(firewallRuleUUID); + } + + private void loadConfiguration() { + for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) { + NeutronFirewallRule nn = (NeutronFirewallRule) conf; + firewallRuleDB.put(nn.getFirewallRuleUUID(), nn); + } + } + + @Override + public Status saveConfiguration() { + return configurationService.persistConfiguration(new ArrayList(firewallRuleDB.values()), + FILE_NAME); + } + + @Override + public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { + return ois.readObject(); + } + +} \ No newline at end of file diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallAware.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallAware.java new file mode 100644 index 0000000000..9b4f579025 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallAware.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +/** + * This interface defines the methods a service that wishes to be aware of Firewall Rules needs to implement + * + */ + +public interface INeutronFirewallAware { + + /** + * Services provide this interface method to indicate if the specified firewall can be created + * + * @param firewall + * instance of proposed new Firewall object + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the create operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canCreateNeutronFirewall(NeutronFirewall firewall); + + /** + * Services provide this interface method for taking action after a firewall has been created + * + * @param firewall + * instance of new Firewall object + * @return void + */ + public void neutronFirewallCreated(NeutronFirewall firewall); + + /** + * Services provide this interface method to indicate if the specified firewall can be changed using the specified + * delta + * + * @param delta + * updates to the firewall object using patch semantics + * @param original + * instance of the Firewall object to be updated + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the update operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canUpdateNeutronFirewall(NeutronFirewall delta, NeutronFirewall original); + + /** + * Services provide this interface method for taking action after a firewall has been updated + * + * @param firewall + * instance of modified Firewall object + * @return void + */ + public void neutronFirewallUpdated(NeutronFirewall firewall); + + /** + * Services provide this interface method to indicate if the specified firewall can be deleted + * + * @param firewall + * instance of the Firewall object to be deleted + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the delete operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canDeleteNeutronFirewall(NeutronFirewall firewall); + + /** + * Services provide this interface method for taking action after a firewall has been deleted + * + * @param firewall + * instance of deleted Firewall object + * @return void + */ + public void neutronFirewallDeleted(NeutronFirewall firewall); +} diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallCRUD.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallCRUD.java new file mode 100644 index 0000000000..c986bffd6b --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallCRUD.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +import java.util.List; + +/** + * This interface defines the methods for CRUD of NB OpenStack Firewall objects + * + */ + +public interface INeutronFirewallCRUD { + /** + * Applications call this interface method to determine if a particular + *Firewall object exists + * + * @param uuid + * UUID of the Firewall object + * @return boolean + */ + + public boolean neutronFirewallExists(String uuid); + + /** + * Applications call this interface method to return if a particular + * Firewall object exists + * + * @param uuid + * UUID of the Firewall object + * @return {@link org.opendaylight.controller.networkconfig.neutron.NeutronFirewall} + * OpenStackFirewall class + */ + + public NeutronFirewall getNeutronFirewall(String uuid); + + /** + * Applications call this interface method to return all Firewall objects + * + * @return List of OpenStackNetworks objects + */ + + public List getAllNeutronFirewalls(); + + /** + * Applications call this interface method to add a Firewall object to the + * concurrent map + * + * @param input + * OpenStackNetwork object + * @return boolean on whether the object was added or not + */ + + public boolean addNeutronFirewall(NeutronFirewall input); + + /** + * Applications call this interface method to remove a Neutron Firewall object to the + * concurrent map + * + * @param uuid + * identifier for the Firewall object + * @return boolean on whether the object was removed or not + */ + + public boolean removeNeutronFirewall(String uuid); + + /** + * Applications call this interface method to edit a Firewall object + * + * @param uuid + * identifier of the Firewall object + * @param delta + * OpenStackFirewall object containing changes to apply + * @return boolean on whether the object was updated or not + */ + + public boolean updateNeutronFirewall(String uuid, NeutronFirewall delta); + + /** + * Applications call this interface method to see if a MAC address is in use + * + * @param uuid + * identifier of the Firewall object + * @return boolean on whether the macAddress is already associated with a + * port or not + */ + + public boolean neutronFirewallInUse(String uuid); + +} diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyAware.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyAware.java new file mode 100644 index 0000000000..203d513923 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyAware.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +/** + * This interface defines the methods a service that wishes to be aware of Firewall Policys needs to implement + * + */ + +public interface INeutronFirewallPolicyAware { + + /** + * Services provide this interface method to indicate if the specified firewallPolicy can be created + * + * @param firewallPolicy + * instance of proposed new Firewall Policy object + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the create operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canCreateNeutronFirewallPolicy(NeutronFirewallPolicy firewallPolicy); + + /** + * Services provide this interface method for taking action after a firewallPolicy has been created + * + * @param firewallPolicy + * instance of new Firewall Policy object + * @return void + */ + public void neutronFirewallPolicyCreated(NeutronFirewallPolicy firewallPolicy); + + /** + * Services provide this interface method to indicate if the specified firewallPolicy can be changed using the specified + * delta + * + * @param delta + * updates to the firewallPolicy object using patch semantics + * @param original + * instance of the Firewall Policy object to be updated + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the update operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canUpdateNeutronFirewallPolicy(NeutronFirewallPolicy delta, NeutronFirewallPolicy original); + + /** + * Services provide this interface method for taking action after a firewallPolicy has been updated + * + * @param firewallPolicy + * instance of modified Firewall Policy object + * @return void + */ + public void neutronFirewallPolicyUpdated(NeutronFirewallPolicy firewallPolicy); + + /** + * Services provide this interface method to indicate if the specified firewallPolicy can be deleted + * + * @param firewallPolicy + * instance of the Firewall Policy object to be deleted + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the delete operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canDeleteNeutronFirewallPolicy(NeutronFirewallPolicy firewallPolicy); + + /** + * Services provide this interface method for taking action after a firewallPolicy has been deleted + * + * @param firewallPolicy + * instance of deleted Firewall Policy object + * @return void + */ + public void neutronFirewallPolicyDeleted(NeutronFirewallPolicy firewallPolicy); +} diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyCRUD.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyCRUD.java new file mode 100644 index 0000000000..6049656a6e --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyCRUD.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +import java.util.List; + +/** + * This interface defines the methods for CRUD of NB OpenStack Firewall Policy objects + * + */ + +public interface INeutronFirewallPolicyCRUD { + /** + * Applications call this interface method to determine if a particular + *FirewallPolicy object exists + * + * @param uuid + * UUID of the Firewall Policy object + * @return boolean + */ + + public boolean neutronFirewallPolicyExists(String uuid); + + /** + * Applications call this interface method to return if a particular + * FirewallPolicy object exists + * + * @param uuid + * UUID of the Firewall Policy object + * @return {@link NeutronFirewallPolicy} + * OpenStackFirewallPolicy class + */ + + public NeutronFirewallPolicy getNeutronFirewallPolicy(String uuid); + + /** + * Applications call this interface method to return all Firewall Policy objects + * + * @return List of OpenStack Firewall Policy objects + */ + + public List getAllNeutronFirewallPolicies(); + + /** + * Applications call this interface method to add a Firewall Policy object to the + * concurrent map + * + * @param input + * OpenStackNetwork object + * @return boolean on whether the object was added or not + */ + + public boolean addNeutronFirewallPolicy(NeutronFirewallPolicy input); + + /** + * Applications call this interface method to remove a Neutron FirewallPolicy object to the + * concurrent map + * + * @param uuid + * identifier for the Firewall Policy object + * @return boolean on whether the object was removed or not + */ + + public boolean removeNeutronFirewallPolicy(String uuid); + + /** + * Applications call this interface method to edit a FirewallPolicy object + * + * @param uuid + * identifier of the Firewall Policy object + * @param delta + * OpenStackFirewallPolicy object containing changes to apply + * @return boolean on whether the object was updated or not + */ + + public boolean updateNeutronFirewallPolicy(String uuid, NeutronFirewallPolicy delta); + + /** + * Applications call this interface method to see if a MAC address is in use + * + * @param uuid + * identifier of the Firewall Policy object + * @return boolean on whether the macAddress is already associated with a + * port or not + */ + + public boolean neutronFirewallPolicyInUse(String uuid); + +} diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleAware.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleAware.java new file mode 100644 index 0000000000..a663058328 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleAware.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +/** + * This interface defines the methods a service that wishes to be aware of Firewall Rules needs to implement + * + */ + +public interface INeutronFirewallRuleAware { + + /** + * Services provide this interface method to indicate if the specified firewallRule can be created + * + * @param firewallRule + * instance of proposed new Firewall Rule object + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the create operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canCreateNeutronFirewallRule(NeutronFirewallRule firewallRule); + + /** + * Services provide this interface method for taking action after a firewallRule has been created + * + * @param firewallRule + * instance of new Firewall Rule object + * @return void + */ + public void neutronFirewallRuleCreated(NeutronFirewallRule firewallRule); + + /** + * Services provide this interface method to indicate if the specified firewallRule can be changed using the specified + * delta + * + * @param delta + * updates to the firewallRule object using patch semantics + * @param original + * instance of the Firewall Rule object to be updated + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the update operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canUpdateNeutronFirewallRule(NeutronFirewallRule delta, NeutronFirewallRule original); + + /** + * Services provide this interface method for taking action after a firewallRule has been updated + * + * @param firewallRule + * instance of modified Firewall Rule object + * @return void + */ + public void neutronFirewallRuleUpdated(NeutronFirewallRule firewallRule); + + /** + * Services provide this interface method to indicate if the specified firewallRule can be deleted + * + * @param firewallRule + * instance of the Firewall Rule object to be deleted + * @return integer + * the return value is understood to be a HTTP status code. A return value outside of 200 through 299 + * results in the delete operation being interrupted and the returned status value reflected in the + * HTTP response. + */ + public int canDeleteNeutronFirewallRule(NeutronFirewallRule firewallRule); + + /** + * Services provide this interface method for taking action after a firewallRule has been deleted + * + * @param firewallRule + * instance of deleted Firewall Rule object + * @return void + */ + public void neutronFirewallRuleDeleted(NeutronFirewallRule firewallRule); +} diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleCRUD.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleCRUD.java new file mode 100644 index 0000000000..990896bdb7 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleCRUD.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +import java.util.List; + +/** + * This interface defines the methods for CRUD of NB OpenStack Firewall Rule objects + * + */ + +public interface INeutronFirewallRuleCRUD { + /** + * Applications call this interface method to determine if a particular + *FirewallRule object exists + * + * @param uuid + * UUID of the Firewall Rule object + * @return boolean + */ + + public boolean neutronFirewallRuleExists(String uuid); + + /** + * Applications call this interface method to return if a particular + * FirewallRule object exists + * + * @param uuid + * UUID of the Firewall Rule object + * @return {@link NeutronFirewallRule} + * OpenStackFirewall Rule class + */ + + public NeutronFirewallRule getNeutronFirewallRule(String uuid); + + /** + * Applications call this interface method to return all Firewall Rule objects + * + * @return List of OpenStackNetworks objects + */ + + public List getAllNeutronFirewallRules(); + + /** + * Applications call this interface method to add a Firewall Rule object to the + * concurrent map + * + * @param input + * OpenStackNetwork object + * @return boolean on whether the object was added or not + */ + + public boolean addNeutronFirewallRule(NeutronFirewallRule input); + + /** + * Applications call this interface method to remove a Neutron FirewallRule object to the + * concurrent map + * + * @param uuid + * identifier for the Firewall Rule object + * @return boolean on whether the object was removed or not + */ + + public boolean removeNeutronFirewallRule(String uuid); + + /** + * Applications call this interface method to edit a FirewallRule object + * + * @param uuid + * identifier of the Firewall Rule object + * @param delta + * OpenStackFirewallRule object containing changes to apply + * @return boolean on whether the object was updated or not + */ + + public boolean updateNeutronFirewallRule(String uuid, NeutronFirewallRule delta); + + /** + * Applications call this interface method to see if a MAC address is in use + * + * @param uuid + * identifier of the Firewall Rule object + * @return boolean on whether the macAddress is already associated with a + * port or not + */ + + public boolean neutronFirewallRuleInUse(String uuid); + +} diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronCRUDInterfaces.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronCRUDInterfaces.java index 21cfdb1305..6ce5499cdf 100644 --- a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronCRUDInterfaces.java +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronCRUDInterfaces.java @@ -46,4 +46,19 @@ public class NeutronCRUDInterfaces { INeutronSecurityRuleCRUD answer = (INeutronSecurityRuleCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityRuleCRUD.class, o); return answer; } + + public static INeutronFirewallCRUD getINeutronFirewallCRUD(Object o) { + INeutronFirewallCRUD answer = (INeutronFirewallCRUD) ServiceHelper.getGlobalInstance(INeutronFirewallCRUD.class, o); + return answer; + } + + public static INeutronFirewallPolicyCRUD getINeutronFirewallPolicyCRUD(Object o) { + INeutronFirewallPolicyCRUD answer = (INeutronFirewallPolicyCRUD) ServiceHelper.getGlobalInstance(INeutronFirewallPolicyCRUD.class, o); + return answer; + } + + public static INeutronFirewallRuleCRUD getINeutronFirewallRuleCRUD(Object o) { + INeutronFirewallRuleCRUD answer = (INeutronFirewallRuleCRUD) ServiceHelper.getGlobalInstance(INeutronFirewallRuleCRUD.class, o); + return answer; + } } \ No newline at end of file diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewall.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewall.java new file mode 100644 index 0000000000..39f04c9b2b --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewall.java @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +import org.opendaylight.controller.configuration.ConfigurationObject; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.Iterator; +import java.util.List; + +/** + * OpenStack Neutron v2.0 Firewall as a service + * (FWaaS) bindings. See OpenStack Network API + * v2.0 Reference for description of the fields: + * Implemented fields are as follows: + * + * id uuid-str + * tenant_id uuid-str + * name String + * description String + * admin_state_up Bool + * status String + * shared Bool + * firewall_policy_id uuid-str + * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf + */ + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) + +public class NeutronFirewall extends ConfigurationObject implements Serializable { + private static final long serialVersionUID = 1L; + + @XmlElement(name="id") + String firewallUUID; + + @XmlElement (name="tenant_id") + String firewallTenantID; + + @XmlElement (name="name") + String firewallName; + + @XmlElement (name="description") + String firewallDescription; + + @XmlElement (defaultValue="true", name="admin_state_up") + Boolean firewallAdminStateIsUp; + + @XmlElement (name="status") + String firewallStatus; + + @XmlElement (defaultValue="false", name="shared") + Boolean firewallIsShared; + + @XmlElement (name="firewall_policy_id") + String neutronFirewallPolicyID; + + public String getFirewallUUID() { + return firewallUUID; + } + + public void setFirewallUUID(String firewallUUID) { + this.firewallUUID = firewallUUID; + } + + public String getFirewallTenantID() { + return firewallTenantID; + } + + public void setFirewallTenantID(String firewallTenantID) { + this.firewallTenantID = firewallTenantID; + } + + public String getFirewallName() { + return firewallName; + } + + public void setFirewallName(String firewallName) { + this.firewallName = firewallName; + } + + public String getFirewallDescription() { + return firewallDescription; + } + + public void setFirewallDescription(String firewallDescription) { + this.firewallDescription = firewallDescription; + } + + public Boolean getFirewallAdminStateIsUp() { + return firewallAdminStateIsUp; + } + + public void setFirewallAdminStateIsUp(Boolean firewallAdminStateIsUp) { + this.firewallAdminStateIsUp = firewallAdminStateIsUp; + } + + public String getFirewallStatus() { + return firewallStatus; + } + + public void setFirewallStatus(String firewallStatus) { + this.firewallStatus = firewallStatus; + } + + public Boolean getFirewallIsShared() { + return firewallIsShared; + } + + public void setFirewallIsShared(Boolean firewallIsShared) { + this.firewallIsShared = firewallIsShared; + } + + public String getFirewallPolicyID() { + return neutronFirewallPolicyID; + } + + public void setNeutronFirewallPolicyID(String firewallPolicy) { + this.neutronFirewallPolicyID = firewallPolicy; + } + + public NeutronFirewall extractFields(List fields) { + NeutronFirewall ans = new NeutronFirewall(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + String s = i.next(); + if (s.equals("id")) { + ans.setFirewallUUID(this.getFirewallUUID()); + } + if (s.equals("tenant_id")) { + ans.setFirewallTenantID(this.getFirewallTenantID()); + } + if (s.equals("name")) { + ans.setFirewallName(this.getFirewallName()); + } + if(s.equals("description")) { + ans.setFirewallDescription(this.getFirewallDescription()); + } + if (s.equals("admin_state_up")) { + ans.setFirewallAdminStateIsUp(firewallAdminStateIsUp); + } + if (s.equals("status")) { + ans.setFirewallStatus(this.getFirewallStatus()); + } + if (s.equals("shared")) { + ans.setFirewallIsShared(firewallIsShared); + } + if (s.equals("firewall_policy_id")) { + ans.setNeutronFirewallPolicyID(this.getFirewallPolicyID()); + } + } + return ans; + } + + @Override + public String toString() { + return "NeutronFirewall{" + + "firewallUUID='" + firewallUUID + '\'' + + ", firewallTenantID='" + firewallTenantID + '\'' + + ", firewallName='" + firewallName + '\'' + + ", firewallDescription='" + firewallDescription + '\'' + + ", firewallAdminStateIsUp=" + firewallAdminStateIsUp + + ", firewallStatus='" + firewallStatus + '\'' + + ", firewallIsShared=" + firewallIsShared + + ", firewallRulePolicyID=" + neutronFirewallPolicyID + + '}'; + } +} diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallPolicy.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallPolicy.java new file mode 100644 index 0000000000..46436b52f4 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallPolicy.java @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +import org.opendaylight.controller.configuration.ConfigurationObject; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * OpenStack Neutron v2.0 Firewall as a service + * (FWaaS) bindings. See OpenStack Network API + * v2.0 Reference for description of the fields. + * The implemented fields are as follows: + * + * id uuid-str + * tenant_id uuid-str + * name String + * description String + * shared Boolean + * firewall_rules List + * audited Boolean + * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf + */ + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) + +public class NeutronFirewallPolicy extends ConfigurationObject implements Serializable { + private static final long serialVersionUID = 1L; + + @XmlElement(name="id") + String firewallPolicyUUID; + + @XmlElement (name="tenant_id") + String firewallPolicyTenantID; + + @XmlElement (name="name") + String firewallPolicyName; + + @XmlElement (name="description") + String firewallPolicyDescription; + + @XmlElement (defaultValue="false", name="shared") + Boolean firewallPolicyIsShared; + + @XmlElement (name="firewall_rules") + List firewallPolicyRules; + + @XmlElement (defaultValue="false", name="audited") + String firewallPolicyIsAudited; + + public String getFirewallPolicyIsAudited() { + return firewallPolicyIsAudited; + } + + public void setFirewallPolicyIsAudited(String firewallPolicyIsAudited) { + this.firewallPolicyIsAudited = firewallPolicyIsAudited; + } + + public void setFirewallPolicyRules(List firewallPolicyRules) { + this.firewallPolicyRules = firewallPolicyRules; + } + + public List getFirewallPolicyRules() { + return firewallPolicyRules; + } + + public Boolean getFirewallPolicyIsShared() { + return firewallPolicyIsShared; + } + + public void setFirewallPolicyIsShared(Boolean firewallPolicyIsShared) { + this.firewallPolicyIsShared = firewallPolicyIsShared; + } + + public String getFirewallPolicyDescription() { + return firewallPolicyDescription; + } + + public void setFirewallPolicyDescription(String firewallPolicyDescription) { + this.firewallPolicyDescription = firewallPolicyDescription; + } + + public String getFirewallPolicyName() { + return firewallPolicyName; + } + + public void setFirewallPolicyName(String firewallPolicyName) { + this.firewallPolicyName = firewallPolicyName; + } + + public String getFirewallPolicyTenantID() { + return firewallPolicyTenantID; + } + + public void setFirewallPolicyTenantID(String firewallPolicyTenantID) { + this.firewallPolicyTenantID = firewallPolicyTenantID; + } + + public String getFirewallPolicyUUID() { + return firewallPolicyUUID; + } + + public void setFirewallPolicyUUID(String firewallPolicyUUID) { + this.firewallPolicyUUID = firewallPolicyUUID; + } + + public NeutronFirewallPolicy extractFields(List fields) { + NeutronFirewallPolicy ans = new NeutronFirewallPolicy(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + String s = i.next(); + if (s.equals("id")) { + ans.setFirewallPolicyUUID(this.getFirewallPolicyUUID()); + } + if (s.equals("tenant_id")) { + ans.setFirewallPolicyTenantID(this.getFirewallPolicyTenantID()); + } + if (s.equals("name")) { + ans.setFirewallPolicyName(this.getFirewallPolicyName()); + } + if(s.equals("description")) { + ans.setFirewallPolicyDescription(this.getFirewallPolicyDescription()); + } + if (s.equals("shared")) { + ans.setFirewallPolicyIsShared(firewallPolicyIsShared); + } + if (s.equals("firewall_rules")) { + List firewallRuleList = new ArrayList(); + firewallRuleList.addAll(this.getFirewallPolicyRules()); + ans.setFirewallPolicyRules(firewallRuleList); + } + if (s.equals("audited")) { + ans.setFirewallPolicyIsAudited(firewallPolicyIsAudited); + } + } + return ans; + } + + @Override + public String toString() { + return "NeutronFirewallPolicy{" + + "firewallPolicyUUID='" + firewallPolicyUUID + '\'' + + ", firewallPolicyTenantID='" + firewallPolicyTenantID + '\'' + + ", firewallPolicyName='" + firewallPolicyName + '\'' + + ", firewallPolicyDescription='" + firewallPolicyDescription + '\'' + + ", firewallPolicyIsShared=" + firewallPolicyIsShared + + ", firewallPolicyRules=" + firewallPolicyRules + + ", firewallPolicyIsAudited='" + firewallPolicyIsAudited + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallRule.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallRule.java new file mode 100644 index 0000000000..63a65a27f9 --- /dev/null +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallRule.java @@ -0,0 +1,323 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron; + +import org.opendaylight.controller.configuration.ConfigurationObject; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.Iterator; +import java.util.List; + +/** + * OpenStack Neutron v2.0 Firewall as a service + * (FWaaS) bindings. See OpenStack Network API + * v2.0 Reference for description of the fields. + * The implemented fields are as follows: + * + * tenant_id uuid-str + * name String + * description String + * admin_state_up Bool + * status String + * shared Bool + * firewall_policy_id uuid-str + * protocol String + * ip_version Integer + * source_ip_address String (IP addr or CIDR) + * destination_ip_address String (IP addr or CIDR) + * source_port Integer + * destination_port Integer + * position Integer + * action String + * enabled Bool + * id uuid-str + * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf + */ + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) + +public class NeutronFirewallRule extends ConfigurationObject implements Serializable { + private static final long serialVersionUID = 1L; + + @XmlElement(name = "id") + String firewallRuleUUID; + + @XmlElement(name = "tenant_id") + String firewallRuleTenantID; + + @XmlElement(name = "name") + String firewallRuleName; + + @XmlElement(name = "description") + String firewallRuleDescription; + + @XmlElement(defaultValue = "true", name = "admin_state_up") + Boolean firewallRuleAdminStateIsUp; + + @XmlElement(name = "status") + String firewallRuleStatus; + + @XmlElement(defaultValue = "false", name = "shared") + Boolean firewallRuleIsShared; + + @XmlElement(name = "firewall_policy_id") + String firewallRulePolicyID; + + @XmlElement(name = "protocol") + String firewallRuleProtocol; + + @XmlElement(name = "ip_version") + Integer firewallRuleIpVer; + + @XmlElement(name = "source_ip_address") + String firewallRuleSrcIpAddr; + + @XmlElement(name = "destination_ip_address") + String firewallRuleDstIpAddr; + + @XmlElement(name = "source_port") + Integer firewallRuleSrcPort; + + @XmlElement(name = "destination_port") + Integer firewallRuleDstPort; + + @XmlElement(name = "position") + Integer firewallRulePosition; + + @XmlElement(name = "action") + String firewallRuleAction; + + @XmlElement(name = "enabled") + Boolean firewallRuleIsEnabled; + + public Boolean getFirewallRuleIsEnabled() { + return firewallRuleIsEnabled; + } + + public void setFirewallRuleIsEnabled(Boolean firewallRuleIsEnabled) { + this.firewallRuleIsEnabled = firewallRuleIsEnabled; + } + + public String getFirewallRuleAction() { + return firewallRuleAction; + } + + public void setFirewallRuleAction(String firewallRuleAction) { + this.firewallRuleAction = firewallRuleAction; + } + + public Integer getFirewallRulePosition() { + return firewallRulePosition; + } + + public void setFirewallRulePosition(Integer firewallRulePosition) { + this.firewallRulePosition = firewallRulePosition; + } + + public Integer getFirewallRuleDstPort() { + return firewallRuleDstPort; + } + + public void setFirewallRuleDstPort(Integer firewallRuleDstPort) { + this.firewallRuleDstPort = firewallRuleDstPort; + } + + public Integer getFirewallRuleSrcPort() { + return firewallRuleSrcPort; + } + + public void setFirewallRuleSrcPort(Integer firewallRuleSrcPort) { + this.firewallRuleSrcPort = firewallRuleSrcPort; + } + + public String getFirewallRuleDstIpAddr() { + return firewallRuleDstIpAddr; + } + + public void setFirewallRuleDstIpAddr(String firewallRuleDstIpAddr) { + this.firewallRuleDstIpAddr = firewallRuleDstIpAddr; + } + + public String getFirewallRuleSrcIpAddr() { + return firewallRuleSrcIpAddr; + } + + public void setFirewallRuleSrcIpAddr(String firewallRuleSrcIpAddr) { + this.firewallRuleSrcIpAddr = firewallRuleSrcIpAddr; + } + + public Integer getFirewallRuleIpVer() { + return firewallRuleIpVer; + } + + public void setFirewallRuleIpVer(Integer firewallRuleIpVer) { + this.firewallRuleIpVer = firewallRuleIpVer; + } + + public String getFirewallRuleProtocol() { + return firewallRuleProtocol; + } + + public void setFirewallRuleProtocol(String firewallRuleProtocol) { + this.firewallRuleProtocol = firewallRuleProtocol; + } + + public String getFirewallRulePolicyID() { + return firewallRulePolicyID; + } + + public void setFirewallRulesPolicyID(String firewallRulePolicyID) { + this.firewallRulePolicyID = firewallRulePolicyID; + } + + public Boolean getFirewallRuleIsShared() { + return firewallRuleIsShared; + } + + public void setFirewallRuleIsShared(Boolean firewallRuleIsShared) { + this.firewallRuleIsShared = firewallRuleIsShared; + } + + public String getFirewallRuleStatus() { + return firewallRuleStatus; + } + + public void setFirewallRuleStatus(String firewallRuleStatus) { + this.firewallRuleStatus = firewallRuleStatus; + } + + public Boolean getFirewallRuleAdminStateIsUp() { + return firewallRuleAdminStateIsUp; + } + + public void setFirewallRuleAdminStateIsUp(Boolean firewallRuleAdminStateIsUp) { + this.firewallRuleAdminStateIsUp = firewallRuleAdminStateIsUp; + } + + public String getFirewallRuleDescription() { + return firewallRuleDescription; + } + + public void setFirewallRuleDescription(String firewallRuleDescription) { + this.firewallRuleDescription = firewallRuleDescription; + } + + public String getFirewallRuleName() { + return firewallRuleName; + } + + public void setFirewallRuleName(String firewallRuleName) { + this.firewallRuleName = firewallRuleName; + } + + public String getFirewallRuleTenantID() { + return firewallRuleTenantID; + } + + public void setFirewallRuleTenantID(String firewallRuleTenantID) { + this.firewallRuleTenantID = firewallRuleTenantID; + } + + public String getFirewallRuleUUID() { + return firewallRuleUUID; + } + + public void setFirewallRuleUUID(String firewallRuleUUID) { + this.firewallRuleUUID = firewallRuleUUID; + } + + public NeutronFirewallRule extractFields(List fields) { + NeutronFirewallRule ans = new NeutronFirewallRule(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + String s = i.next(); + if (s.equals("id")) { + ans.setFirewallRuleUUID(this.getFirewallRuleUUID()); + } + if (s.equals("tenant_id")) { + ans.setFirewallRuleTenantID(this.getFirewallRuleTenantID()); + } + if (s.equals("name")) { + ans.setFirewallRuleName(this.getFirewallRuleName()); + } + if (s.equals("description")) { + ans.setFirewallRuleDescription(this.getFirewallRuleDescription()); + } + if (s.equals("admin_state_up")) { + ans.setFirewallRuleAdminStateIsUp(firewallRuleAdminStateIsUp); + } + if (s.equals("status")) { + ans.setFirewallRuleStatus(this.getFirewallRuleStatus()); + } + if (s.equals("shared")) { + ans.setFirewallRuleIsShared(firewallRuleIsShared); + } + if (s.equals("firewall_policy_id")) { + ans.setFirewallRulesPolicyID(this.getFirewallRulePolicyID()); + } + if (s.equals("protocol")) { + ans.setFirewallRuleProtocol(this.getFirewallRuleProtocol()); + } + if (s.equals("source_ip_address")) { + ans.setFirewallRuleSrcIpAddr(this.getFirewallRuleSrcIpAddr()); + } + if (s.equals("destination_ip_address")) { + ans.setFirewallRuleDstIpAddr(this.getFirewallRuleDstIpAddr()); + } + if (s.equals("source_port")) { + ans.setFirewallRuleSrcPort(this.getFirewallRuleSrcPort()); + } + if (s.equals("destination_port")) { + ans.setFirewallRuleDstPort(this.getFirewallRuleDstPort()); + } + if (s.equals("position")) { + ans.setFirewallRulePosition(this.getFirewallRulePosition()); + } + if (s.equals("action")) { + ans.setFirewallRuleAction(this.getFirewallRuleAction()); + } + if (s.equals("enabled")) { + ans.setFirewallRuleIsEnabled(firewallRuleIsEnabled); + } + + } + return ans; + } + + @Override + public String toString() { + return "firewallPolicyRules{" + + "firewallRuleUUID='" + firewallRuleUUID + '\'' + + ", firewallRuleTenantID='" + firewallRuleTenantID + '\'' + + ", firewallRuleName='" + firewallRuleName + '\'' + + ", firewallRuleDescription='" + firewallRuleDescription + '\'' + + ", firewallRuleAdminStateIsUp=" + firewallRuleAdminStateIsUp + + ", firewallRuleStatus='" + firewallRuleStatus + '\'' + + ", firewallRuleIsShared=" + firewallRuleIsShared + + ", firewallRulePolicyID=" + firewallRulePolicyID + + ", firewallRuleProtocol='" + firewallRuleProtocol + '\'' + + ", firewallRuleIpVer=" + firewallRuleIpVer + + ", firewallRuleSrcIpAddr='" + firewallRuleSrcIpAddr + '\'' + + ", firewallRuleDstIpAddr='" + firewallRuleDstIpAddr + '\'' + + ", firewallRuleSrcPort=" + firewallRuleSrcPort + + ", firewallRuleDstPort=" + firewallRuleDstPort + + ", firewallRulePosition=" + firewallRulePosition + + ", firewallRuleAction='" + firewallRuleAction + '\'' + + ", firewallRuleIsEnabled=" + firewallRuleIsEnabled + + '}'; + } + + public void initDefaults() { + } +} \ No newline at end of file diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java new file mode 100644 index 0000000000..204c9f5176 --- /dev/null +++ b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java @@ -0,0 +1,381 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.northbound; + + +import org.codehaus.enunciate.jaxrs.ResponseCode; +import org.codehaus.enunciate.jaxrs.StatusCodes; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallAware; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallCRUD; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleCRUD; +import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces; +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewall; +import org.opendaylight.controller.northbound.commons.RestMessages; +import org.opendaylight.controller.northbound.commons.exception.BadRequestException; +import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; +import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; +import org.opendaylight.controller.sal.utils.ServiceHelper; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * Neutron Northbound REST APIs for Firewall.
+ * This class provides REST APIs for managing neutron Firewall + * + *
+ *
+ * Authentication scheme : HTTP Basic
+ * Authentication realm : opendaylight
+ * Transport : HTTP and HTTPS
+ *
+ * HTTPS Authentication is disabled by default. Administrator can enable it in + * tomcat-server.xml after adding a proper keystore / SSL certificate from a + * trusted authority.
+ * More info : + * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration + * + */ +@Path("/fw/firewalls") +public class NeutronFirewallNorthbound { + + private NeutronFirewall extractFields(NeutronFirewall o, List fields) { + return o.extractFields(fields); + } + + /** + * Returns a list of all Firewalls */ + @GET + @Produces({ MediaType.APPLICATION_JSON }) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + + public Response listGroups( + // return fields + @QueryParam("fields") List fields, + // OpenStack firewall attributes + @QueryParam("id") String queryFirewallUUID, + @QueryParam("tenant_id") String queryFirewallTenantID, + @QueryParam("name") String queryFirewallName, + @QueryParam("description") String queryFirewallDescription, + @QueryParam("shared") Boolean queryFirewallAdminStateIsUp, + @QueryParam("status") String queryFirewallStatus, + @QueryParam("shared") Boolean queryFirewallIsShared, + @QueryParam("firewall_policy_id") String queryFirewallPolicyID, + // pagination + @QueryParam("limit") String limit, + @QueryParam("marker") String marker, + @QueryParam("page_reverse") String pageReverse + // sorting not supported + ) { + INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this); + INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this); + + if (firewallInterface == null) { + throw new ServiceUnavailableException("Firewall CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + List allFirewalls = firewallInterface.getAllNeutronFirewalls(); + List ans = new ArrayList(); + Iterator i = allFirewalls.iterator(); + while (i.hasNext()) { + NeutronFirewall nsg = i.next(); + if ((queryFirewallUUID == null || + queryFirewallUUID.equals(nsg.getFirewallUUID())) && + (queryFirewallTenantID == null || + queryFirewallTenantID.equals(nsg.getFirewallTenantID())) && + (queryFirewallName == null || + queryFirewallName.equals(nsg.getFirewallName())) && + (queryFirewallDescription == null || + queryFirewallDescription.equals(nsg.getFirewallDescription())) && + (queryFirewallAdminStateIsUp == null || + queryFirewallAdminStateIsUp.equals(nsg.getFirewallAdminStateIsUp())) && + (queryFirewallStatus == null || + queryFirewallStatus.equals(nsg.getFirewallStatus())) && + (queryFirewallIsShared == null || + queryFirewallIsShared.equals(nsg.getFirewallIsShared())) && + (queryFirewallPolicyID == null || + queryFirewallPolicyID.equals(nsg.getFirewallPolicyID()))) { + if (fields.size() > 0) { + ans.add(extractFields(nsg,fields)); + } else { + ans.add(nsg); + } + } + } + //TODO: apply pagination to results + return Response.status(200).entity( + new NeutronFirewallRequest(ans)).build(); + } + + /** + * Returns a specific Firewall */ + + @Path("{firewallUUID}") + @GET + @Produces({ MediaType.APPLICATION_JSON }) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + public Response showFirewall(@PathParam("firewallUUID") String firewallUUID, + // return fields + @QueryParam("fields") List fields) { + INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this); + if (firewallInterface == null) { + throw new ServiceUnavailableException("Firewall CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + if (!firewallInterface.neutronFirewallExists(firewallUUID)) { + throw new ResourceNotFoundException("Firewall UUID does not exist."); + } + if (fields.size() > 0) { + NeutronFirewall ans = firewallInterface.getNeutronFirewall(firewallUUID); + return Response.status(200).entity( + new NeutronFirewallRequest(extractFields(ans, fields))).build(); + } else { + return Response.status(200).entity(new NeutronFirewallRequest(firewallInterface.getNeutronFirewall(firewallUUID))).build(); + } + } + + /** + * Creates new Firewall */ + + @POST + @Produces({ MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.APPLICATION_JSON }) + @StatusCodes({ + @ResponseCode(code = 201, condition = "Created"), + @ResponseCode(code = 400, condition = "Bad Request"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 403, condition = "Forbidden"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 409, condition = "Conflict"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + public Response createFirewalls(final NeutronFirewallRequest input) { + INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this); + if (firewallInterface == null) { + throw new ServiceUnavailableException("Firewall CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + if (input.isSingleton()) { + NeutronFirewall singleton = input.getSingleton(); + + /* + * Verify that the Firewall doesn't already exist. + */ + if (firewallInterface.neutronFirewallExists(singleton.getFirewallUUID())) { + throw new BadRequestException("Firewall UUID already exists"); + } + firewallInterface.addNeutronFirewall(singleton); + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallAware service = (INeutronFirewallAware) instance; + int status = service.canCreateNeutronFirewall(singleton); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + firewallInterface.addNeutronFirewall(singleton); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallAware service = (INeutronFirewallAware) instance; + service.neutronFirewallCreated(singleton); + } + } + } else { + List bulk = input.getBulk(); + Iterator i = bulk.iterator(); + HashMap testMap = new HashMap(); + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallAware.class, this, null); + while (i.hasNext()) { + NeutronFirewall test = i.next(); + + /* + * Verify that the secruity group doesn't already exist + */ + if (firewallInterface.neutronFirewallExists(test.getFirewallUUID())) { + throw new BadRequestException("Firewall UUID already is already created"); + } + if (testMap.containsKey(test.getFirewallUUID())) { + throw new BadRequestException("Firewall UUID already exists"); + } + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallAware service = (INeutronFirewallAware) instance; + int status = service.canCreateNeutronFirewall(test); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + } + + /* + * now, each element of the bulk request can be added to the cache + */ + i = bulk.iterator(); + while (i.hasNext()) { + NeutronFirewall test = i.next(); + firewallInterface.addNeutronFirewall(test); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallAware service = (INeutronFirewallAware) instance; + service.neutronFirewallCreated(test); + } + } + } + } + return Response.status(201).entity(input).build(); + } + + /** + * Updates a Firewall */ + + @Path("{firewallUUID}") + @PUT + @Produces({ MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.APPLICATION_JSON }) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 400, condition = "Bad Request"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 403, condition = "Forbidden"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + public Response updateFirewall( + @PathParam("firewallUUID") String firewallUUID, final NeutronFirewallRequest input) { + INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this); + if (firewallInterface == null) { + throw new ServiceUnavailableException("Firewall CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + + /* + * verify the Firewall exists and there is only one delta provided + */ + if (!firewallInterface.neutronFirewallExists(firewallUUID)) { + throw new ResourceNotFoundException("Firewall UUID does not exist."); + } + if (!input.isSingleton()) { + throw new BadRequestException("Only singleton edit supported"); + } + NeutronFirewall delta = input.getSingleton(); + NeutronFirewall original = firewallInterface.getNeutronFirewall(firewallUUID); + + /* + * updates restricted by Neutron + */ + if (delta.getFirewallUUID() != null || + delta.getFirewallTenantID() != null || + delta.getFirewallName() != null || + delta.getFirewallDescription() != null || + delta.getFirewallAdminStateIsUp() != null || + delta.getFirewallStatus() != null || + delta.getFirewallIsShared() != null || + delta.getFirewallPolicyID() != null) { + throw new BadRequestException("Attribute edit blocked by Neutron"); + } + + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallAware service = (INeutronFirewallAware) instance; + int status = service.canUpdateNeutronFirewall(delta, original); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + + /* + * update the object and return it + */ + firewallInterface.updateNeutronFirewall(firewallUUID, delta); + NeutronFirewall updatedFirewall = firewallInterface.getNeutronFirewall(firewallUUID); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallAware service = (INeutronFirewallAware) instance; + service.neutronFirewallUpdated(updatedFirewall); + } + } + return Response.status(200).entity(new NeutronFirewallRequest(firewallInterface.getNeutronFirewall(firewallUUID))).build(); + } + + /** + * Deletes a Firewall */ + + @Path("{firewallUUID}") + @DELETE + @StatusCodes({ + @ResponseCode(code = 204, condition = "No Content"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 409, condition = "Conflict"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + public Response deleteFirewall( + @PathParam("firewallUUID") String firewallUUID) { + INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this); + if (firewallInterface == null) { + throw new ServiceUnavailableException("Firewall CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + + /* + * verify the Firewall exists and it isn't currently in use + */ + if (!firewallInterface.neutronFirewallExists(firewallUUID)) { + throw new ResourceNotFoundException("Firewall UUID does not exist."); + } + if (firewallInterface.neutronFirewallInUse(firewallUUID)) { + return Response.status(409).build(); + } + NeutronFirewall singleton = firewallInterface.getNeutronFirewall(firewallUUID); + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallAware service = (INeutronFirewallAware) instance; + int status = service.canDeleteNeutronFirewall(singleton); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + + /* + * remove it and return 204 status + */ + firewallInterface.removeNeutronFirewall(firewallUUID); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallAware service = (INeutronFirewallAware) instance; + service.neutronFirewallDeleted(singleton); + } + } + return Response.status(204).build(); + } +} diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java new file mode 100644 index 0000000000..bfe2c922bd --- /dev/null +++ b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java @@ -0,0 +1,374 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.northbound; + + +import org.codehaus.enunciate.jaxrs.ResponseCode; +import org.codehaus.enunciate.jaxrs.StatusCodes; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyAware; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyCRUD; +import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces; +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallPolicy; +import org.opendaylight.controller.northbound.commons.RestMessages; +import org.opendaylight.controller.northbound.commons.exception.BadRequestException; +import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; +import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; +import org.opendaylight.controller.sal.utils.ServiceHelper; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * Neutron Northbound REST APIs for Firewall Policies.
+ * This class provides REST APIs for managing neutron Firewall Policies + * + *
+ *
+ * Authentication scheme : HTTP Basic
+ * Authentication realm : opendaylight
+ * Transport : HTTP and HTTPS
+ *
+ * HTTPS Authentication is disabled by default. Administrator can enable it in + * tomcat-server.xml after adding a proper keystore / SSL certificate from a + * trusted authority.
+ * More info : + * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration + * + */ +@Path("/fw/firewalls_policies") +public class NeutronFirewallPolicyNorthbound { + + private NeutronFirewallPolicy extractFields(NeutronFirewallPolicy o, List fields) { + return o.extractFields(fields); + } + + /** + * Returns a list of all Firewall Policies */ + @GET + @Produces({ MediaType.APPLICATION_JSON }) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + + public Response listGroups( + // return fields + @QueryParam("fields") List fields, + // OpenStack Firewall Policy attributes + @QueryParam("id") String queryFirewallPolicyUUID, + @QueryParam("tenant_id") String queryFirewallPolicyTenantID, + @QueryParam("name") String queryFirewallPolicyName, + @QueryParam("description") String querySecurityPolicyDescription, + @QueryParam("shared") String querySecurityPolicyIsShared, + @QueryParam("firewall_rules") List querySecurityPolicyFirewallRules, + @QueryParam("audited") Boolean querySecurityPolicyIsAudited, + // pagination + @QueryParam("limit") String limit, + @QueryParam("marker") String marker, + @QueryParam("page_reverse") String pageReverse + // sorting not supported + ) { + INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this); + + if (firewallPolicyInterface == null) { + throw new ServiceUnavailableException("Firewall Policy CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + List allFirewallPolicies = firewallPolicyInterface.getAllNeutronFirewallPolicies(); + List ans = new ArrayList(); + Iterator i = allFirewallPolicies.iterator(); + while (i.hasNext()) { + NeutronFirewallPolicy nsg = i.next(); + if ((queryFirewallPolicyUUID == null || + queryFirewallPolicyUUID.equals(nsg.getFirewallPolicyUUID())) && + (queryFirewallPolicyTenantID == null || + queryFirewallPolicyTenantID.equals(nsg.getFirewallPolicyTenantID())) && + (queryFirewallPolicyName == null || + queryFirewallPolicyName.equals(nsg.getFirewallPolicyName())) && + (querySecurityPolicyDescription == null || + querySecurityPolicyDescription.equals(nsg.getFirewallPolicyDescription())) && + (querySecurityPolicyIsShared == null || + querySecurityPolicyIsShared.equals(nsg.getFirewallPolicyIsShared())) && + (querySecurityPolicyFirewallRules.size() == 0 || + querySecurityPolicyFirewallRules.equals(nsg.getFirewallPolicyRules())) && + (querySecurityPolicyIsAudited == null || + querySecurityPolicyIsAudited.equals(nsg.getFirewallPolicyIsAudited()))) { + if (fields.size() > 0) { + ans.add(extractFields(nsg,fields)); + } else { + ans.add(nsg); + } + } + } // ans.add((NeutronFirewallPolicy) rules); + //TODO: apply pagination to results + return Response.status(200).entity( + new NeutronFirewallPolicyRequest(ans)).build(); + } + + /** + * Returns a specific Firewall Policy */ + + @Path("{firewallPolicyUUID}") + @GET + @Produces({ MediaType.APPLICATION_JSON }) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + public Response showFirewallPolicy(@PathParam("firewallPolicyUUID") String firewallPolicyUUID, + // return fields + @QueryParam("fields") List fields) { + INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this); + if (firewallPolicyInterface == null) { + throw new ServiceUnavailableException("Firewall Policy CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + if (!firewallPolicyInterface.neutronFirewallPolicyExists(firewallPolicyUUID)) { + throw new ResourceNotFoundException("Firewall Policy UUID does not exist."); + } + if (fields.size() > 0) { + NeutronFirewallPolicy ans = firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID); + return Response.status(200).entity( + new NeutronFirewallPolicyRequest(extractFields(ans, fields))).build(); + } else { + return Response.status(200).entity(new NeutronFirewallPolicyRequest(firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID))).build(); + } + } + + /** + * Creates new Firewall Policy + * */ + @POST + @Produces({ MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.APPLICATION_JSON }) + @StatusCodes({ + @ResponseCode(code = 201, condition = "Created"), + @ResponseCode(code = 400, condition = "Bad Request"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 403, condition = "Forbidden"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 409, condition = "Conflict"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + public Response createFirewallPolicies(final NeutronFirewallPolicyRequest input) { + INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this); + if (firewallPolicyInterface == null) { + throw new ServiceUnavailableException("Firewall Policy CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + if (input.isSingleton()) { + NeutronFirewallPolicy singleton = input.getSingleton(); + + /* + * Verify that the Firewall Policy doesn't already exist. + */ + if (firewallPolicyInterface.neutronFirewallPolicyExists(singleton.getFirewallPolicyUUID())) { + throw new BadRequestException("Firewall Policy UUID already exists"); + } + firewallPolicyInterface.addNeutronFirewallPolicy(singleton); + + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallPolicyAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance; + int status = service.canCreateNeutronFirewallPolicy(singleton); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + firewallPolicyInterface.addNeutronFirewallPolicy(singleton); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance; + service.neutronFirewallPolicyCreated(singleton); + } + } + } else { + List bulk = input.getBulk(); + Iterator i = bulk.iterator(); + HashMap testMap = new HashMap(); + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallPolicyAware.class, this, null); + while (i.hasNext()) { + NeutronFirewallPolicy test = i.next(); + + /* + * Verify that the firewall policy doesn't already exist + */ + + if (firewallPolicyInterface.neutronFirewallPolicyExists(test.getFirewallPolicyUUID())) { + throw new BadRequestException("Firewall Policy UUID already is already created"); + } + if (testMap.containsKey(test.getFirewallPolicyUUID())) { + throw new BadRequestException("Firewall Policy UUID already exists"); + } + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance; + int status = service.canCreateNeutronFirewallPolicy(test); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + } + /* + * now, each element of the bulk request can be added to the cache + */ + i = bulk.iterator(); + while (i.hasNext()) { + NeutronFirewallPolicy test = i.next(); + firewallPolicyInterface.addNeutronFirewallPolicy(test); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance; + service.neutronFirewallPolicyCreated(test); + } + } + } + } + return Response.status(201).entity(input).build(); + } + + /** + * Updates a Firewall Policy + */ + @Path("{firewallPolicyUUID}") + @PUT + @Produces({ MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.APPLICATION_JSON }) + //@TypeHint(OpenStackSubnets.class) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 400, condition = "Bad Request"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 403, condition = "Forbidden"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + public Response updateFirewallPolicy( + @PathParam("firewallPolicyUUID") String firewallPolicyUUID, final NeutronFirewallPolicyRequest input) { + INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this); + if (firewallPolicyInterface == null) { + throw new ServiceUnavailableException("Firewall Policy CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + + /* + * verify the Firewall Policy exists and there is only one delta provided + */ + if (!firewallPolicyInterface.neutronFirewallPolicyExists(firewallPolicyUUID)) { + throw new ResourceNotFoundException("Firewall Policy UUID does not exist."); + } + if (!input.isSingleton()) { + throw new BadRequestException("Only singleton edit supported"); + } + NeutronFirewallPolicy delta = input.getSingleton(); + NeutronFirewallPolicy original = firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID); + + /* + * updates restricted by Neutron + */ + if (delta.getFirewallPolicyUUID() != null || + delta.getFirewallPolicyTenantID() != null || + delta.getFirewallPolicyName() != null || + delta.getFirewallPolicyDescription() != null || + delta.getFirewallPolicyIsShared() != null || + delta.getFirewallPolicyRules().size() > 0 || + delta.getFirewallPolicyIsAudited() != null) { + throw new BadRequestException("Attribute edit blocked by Neutron"); + } + + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallPolicyAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance; + int status = service.canUpdateNeutronFirewallPolicy(delta, original); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + + /* + * update the object and return it + */ + firewallPolicyInterface.updateNeutronFirewallPolicy(firewallPolicyUUID, delta); + NeutronFirewallPolicy updatedFirewallPolicy = firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance; + service.neutronFirewallPolicyUpdated(updatedFirewallPolicy); + } + } + return Response.status(200).entity(new NeutronFirewallPolicyRequest(firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID))).build(); + } + + /** + * Deletes a Firewall Policy */ + + @Path("{firewallPolicyUUID}") + @DELETE + @StatusCodes({ + @ResponseCode(code = 204, condition = "No Content"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 409, condition = "Conflict"), + @ResponseCode(code = 501, condition = "Not Implemented") }) + public Response deleteFirewallPolicy( + @PathParam("firewallPolicyUUID") String firewallPolicyUUID) { + INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this); + if (firewallPolicyInterface == null) { + throw new ServiceUnavailableException("Firewall Policy CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + + /* + * verify the Firewall Policy exists and it isn't currently in use + */ + if (!firewallPolicyInterface.neutronFirewallPolicyExists(firewallPolicyUUID)) { + throw new ResourceNotFoundException("Firewall Policy UUID does not exist."); + } + if (firewallPolicyInterface.neutronFirewallPolicyInUse(firewallPolicyUUID)) { + return Response.status(409).build(); + } + NeutronFirewallPolicy singleton = firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID); + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallPolicyAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance; + int status = service.canDeleteNeutronFirewallPolicy(singleton); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + + firewallPolicyInterface.removeNeutronFirewallPolicy(firewallPolicyUUID); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance; + service.neutronFirewallPolicyDeleted(singleton); + } + } + return Response.status(204).build(); + } +} diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java new file mode 100644 index 0000000000..473846a6d9 --- /dev/null +++ b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.northbound; + +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallPolicy; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) + +public class NeutronFirewallPolicyRequest { + /** + * See OpenStack Network API v2.0 Reference for description of + * http://docs.openstack.org/api/openstack-network/2.0/content/ + */ + + @XmlElement(name="firewall_policy") + NeutronFirewallPolicy singletonFirewallPolicy; + + @XmlElement(name="firewall_policies") + List bulkRequest; + + NeutronFirewallPolicyRequest() { + } + + NeutronFirewallPolicyRequest(List bulk) { + bulkRequest = bulk; + singletonFirewallPolicy = null; + } + + NeutronFirewallPolicyRequest(NeutronFirewallPolicy group) { + singletonFirewallPolicy = group; + } + + public List getBulk() { + return bulkRequest; + } + + public NeutronFirewallPolicy getSingleton() { + return singletonFirewallPolicy; + } + + public boolean isSingleton() { + return (singletonFirewallPolicy != null); + } +} \ No newline at end of file diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java new file mode 100644 index 0000000000..11a7836b22 --- /dev/null +++ b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.northbound; + +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewall; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) + +public class NeutronFirewallRequest { + /** + * See OpenStack Network API v2.0 Reference for description of + * http://docs.openstack.org/api/openstack-network/2.0/content/ + */ + + @XmlElement(name="firewall") + NeutronFirewall singletonFirewall; + + @XmlElement(name="firewalls") + List bulkRequest; + + NeutronFirewallRequest() { + } + + NeutronFirewallRequest(List bulk) { + bulkRequest = bulk; + singletonFirewall = null; + } + + NeutronFirewallRequest(NeutronFirewall group) { + singletonFirewall = group; + } + + public List getBulk() { + return bulkRequest; + } + + public NeutronFirewall getSingleton() { + return singletonFirewall; + } + + public boolean isSingleton() { + return (singletonFirewall != null); + } +} \ No newline at end of file diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java new file mode 100644 index 0000000000..19e67dd234 --- /dev/null +++ b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.northbound; + +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallRule; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) + +public class NeutronFirewallRuleRequest { + /** + * See OpenStack Network API v2.0 Reference for description of + * http://docs.openstack.org/api/openstack-network/2.0/content/ + */ + + @XmlElement(name="firewall_rule") + NeutronFirewallRule singletonFirewallRule; + + @XmlElement(name="firewall_rules") + List bulkRequest; + + NeutronFirewallRuleRequest() { + } + + NeutronFirewallRuleRequest(List bulk) { + bulkRequest = bulk; + singletonFirewallRule = null; + } + + NeutronFirewallRuleRequest(NeutronFirewallRule group) { + singletonFirewallRule = group; + } + + public List getBulk() { + return bulkRequest; + } + + public NeutronFirewallRule getSingleton() { + return singletonFirewallRule; + } + + public boolean isSingleton() { + return (singletonFirewallRule != null); + } +} \ No newline at end of file diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java new file mode 100644 index 0000000000..9911b4dfd4 --- /dev/null +++ b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java @@ -0,0 +1,427 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.networkconfig.neutron.northbound; + + +import org.codehaus.enunciate.jaxrs.ResponseCode; +import org.codehaus.enunciate.jaxrs.StatusCodes; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyCRUD; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleAware; +import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleCRUD; +import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces; +import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallRule; +import org.opendaylight.controller.northbound.commons.RestMessages; +import org.opendaylight.controller.northbound.commons.exception.BadRequestException; +import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; +import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; +import org.opendaylight.controller.sal.utils.ServiceHelper; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * Neutron Northbound REST APIs for Firewall Rule.
+ * This class provides REST APIs for managing neutron Firewall Rule + * + *
+ *
+ * Authentication scheme : HTTP Basic
+ * Authentication realm : opendaylight
+ * Transport : HTTP and HTTPS
+ *
+ * HTTPS Authentication is disabled by default. Administrator can enable it in + * tomcat-server.xml after adding a proper keystore / SSL certificate from a + * trusted authority.
+ * More info : + * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration + */ + +@Path("fw/firewalls_rules") +public class NeutronFirewallRulesNorthbound { + + private NeutronFirewallRule extractFields(NeutronFirewallRule o, List fields) { + return o.extractFields(fields); + } + + /** + * Returns a list of all Firewall Rules + */ + @GET + @Produces({MediaType.APPLICATION_JSON}) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 501, condition = "Not Implemented")}) + public Response listRules( + // return fields + @QueryParam("fields") List fields, + // OpenStack firewall rule attributes + @QueryParam("id") String queryFirewallRuleUUID, + @QueryParam("tenant_id") String queryFirewallRuleTenantID, + @QueryParam("name") String queryFirewallRuleName, + @QueryParam("description") String queryFirewallRuleDescription, + @QueryParam("admin_state_up") Boolean queryFirewallRuleAdminStateIsUp, + @QueryParam("status") String queryFirewallRuleStatus, + @QueryParam("shared") Boolean queryFirewallRuleIsShared, + @QueryParam("firewall_policy_id") String queryFirewallRulePolicyID, + @QueryParam("protocol") String queryFirewallRuleProtocol, + @QueryParam("ip_version") Integer queryFirewallRuleIpVer, + @QueryParam("source_ip_address") String queryFirewallRuleSrcIpAddr, + @QueryParam("destination_ip_address") String queryFirewallRuleDstIpAddr, + @QueryParam("source_port") Integer queryFirewallRuleSrcPort, + @QueryParam("destination_port") Integer queryFirewallRuleDstPort, + @QueryParam("position") Integer queryFirewallRulePosition, + @QueryParam("action") String queryFirewallRuleAction, + @QueryParam("enabled") Boolean queryFirewallRuleIsEnabled, + // pagination + @QueryParam("limit") String limit, + @QueryParam("marker") String marker, + @QueryParam("page_reverse") String pageReverse + // sorting not supported + ) { + INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this); + if (firewallRuleInterface == null) { + throw new ServiceUnavailableException("Firewall Rule CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + List allFirewallRules = firewallRuleInterface.getAllNeutronFirewallRules(); + List ans = new ArrayList(); + Iterator i = allFirewallRules.iterator(); + while (i.hasNext()) { + NeutronFirewallRule nsr = i.next(); + if ((queryFirewallRuleUUID == null || + queryFirewallRuleUUID.equals(nsr.getFirewallRuleUUID())) && + (queryFirewallRuleTenantID == null || + queryFirewallRuleTenantID.equals(nsr.getFirewallRuleTenantID())) && + (queryFirewallRuleName == null || + queryFirewallRuleName.equals(nsr.getFirewallRuleName())) && + (queryFirewallRuleDescription == null || + queryFirewallRuleDescription.equals(nsr.getFirewallRuleDescription())) && + (queryFirewallRuleAdminStateIsUp == null || + queryFirewallRuleAdminStateIsUp.equals(nsr.getFirewallRuleAdminStateIsUp())) && + (queryFirewallRuleStatus == null || + queryFirewallRuleStatus.equals(nsr.getFirewallRuleStatus())) && + (queryFirewallRuleIsShared == null || + queryFirewallRuleIsShared.equals(nsr.getFirewallRuleIsShared())) && + (queryFirewallRulePolicyID == null || + queryFirewallRulePolicyID.equals(nsr.getFirewallRulePolicyID())) && + (queryFirewallRuleProtocol == null || + queryFirewallRuleProtocol.equals(nsr.getFirewallRuleProtocol())) && + (queryFirewallRuleIpVer == null || + queryFirewallRuleIpVer.equals(nsr.getFirewallRuleIpVer())) && + (queryFirewallRuleSrcIpAddr == null || + queryFirewallRuleSrcIpAddr.equals(nsr.getFirewallRuleSrcIpAddr())) && + (queryFirewallRuleDstIpAddr == null || + queryFirewallRuleDstIpAddr.equals(nsr.getFirewallRuleDstIpAddr())) && + (queryFirewallRuleSrcPort == null || + queryFirewallRuleSrcPort.equals(nsr.getFirewallRuleSrcPort())) && + (queryFirewallRuleDstPort == null || + queryFirewallRuleDstPort.equals(nsr.getFirewallRuleDstPort())) && + (queryFirewallRulePosition == null || + queryFirewallRulePosition.equals(nsr.getFirewallRulePosition())) && + (queryFirewallRuleAction == null || + queryFirewallRuleAction.equals(nsr.getFirewallRuleAction())) && + (queryFirewallRuleIsEnabled == null || + queryFirewallRuleIsEnabled.equals(nsr.getFirewallRuleIsEnabled()))) { + if (fields.size() > 0) { + ans.add(extractFields(nsr, fields)); + } else { + ans.add(nsr); + } + } + } + //TODO: apply pagination to results + return Response.status(200).entity( + new NeutronFirewallRuleRequest(ans)).build(); + } + + /** + * Returns a specific Firewall Rule + */ + + @Path("{firewallRuleUUID}") + @GET + @Produces({MediaType.APPLICATION_JSON}) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 501, condition = "Not Implemented")}) + public Response showFirewallRule(@PathParam("firewallRuleUUID") String firewallRuleUUID, + // return fields + @QueryParam("fields") List fields) { + INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this); + if (firewallRuleInterface == null) { + throw new ServiceUnavailableException("Firewall Rule CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + if (!firewallRuleInterface.neutronFirewallRuleExists(firewallRuleUUID)) { + throw new ResourceNotFoundException("Firewall Rule UUID does not exist."); + } + if (fields.size() > 0) { + NeutronFirewallRule ans = firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID); + return Response.status(200).entity( + new NeutronFirewallRuleRequest(extractFields(ans, fields))).build(); + } else { + return Response.status(200) + .entity(new NeutronFirewallRuleRequest( + firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID))) + .build(); + } + } + + /** + * Creates new Firewall Rule + */ + + @POST + @Produces({MediaType.APPLICATION_JSON}) + @Consumes({MediaType.APPLICATION_JSON}) + @StatusCodes({ + @ResponseCode(code = 201, condition = "Created"), + @ResponseCode(code = 400, condition = "Bad Request"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 403, condition = "Forbidden"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 409, condition = "Conflict"), + @ResponseCode(code = 501, condition = "Not Implemented")}) + public Response createFirewallRules(final NeutronFirewallRuleRequest input) { + INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this); + if (firewallRuleInterface == null) { + throw new ServiceUnavailableException("Firewall Rule CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this); + if (firewallPolicyInterface == null) { + throw new ServiceUnavailableException("Firewall Policy CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + + if (input.isSingleton()) { + NeutronFirewallRule singleton = input.getSingleton(); + if (firewallRuleInterface.neutronFirewallRuleExists(singleton.getFirewallRuleUUID())) { + throw new BadRequestException("Firewall Rule UUID already exists"); + } + firewallRuleInterface.addNeutronFirewallRule(singleton); + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallRuleAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance; + int status = service.canCreateNeutronFirewallRule(singleton); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + // add rule to cache + singleton.initDefaults(); + firewallRuleInterface.addNeutronFirewallRule(singleton); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance; + service.neutronFirewallRuleCreated(singleton); + } + } + } else { + List bulk = input.getBulk(); + Iterator i = bulk.iterator(); + HashMap testMap = new HashMap(); + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallRuleAware.class, this, null); + while (i.hasNext()) { + NeutronFirewallRule test = i.next(); + + /* + * Verify that the Firewall rule doesn't already exist + */ + + if (firewallRuleInterface.neutronFirewallRuleExists(test.getFirewallRuleUUID())) { + throw new BadRequestException("Firewall Rule UUID already exists"); + } + if (testMap.containsKey(test.getFirewallRuleUUID())) { + throw new BadRequestException("Firewall Rule UUID already exists"); + } + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance; + int status = service.canCreateNeutronFirewallRule(test); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + } + /* + * now, each element of the bulk request can be added to the cache + */ + i = bulk.iterator(); + while (i.hasNext()) { + NeutronFirewallRule test = i.next(); + firewallRuleInterface.addNeutronFirewallRule(test); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance; + service.neutronFirewallRuleCreated(test); + } + } + } + } + return Response.status(201).entity(input).build(); + } + + /** + * Updates a Firewall Rule + */ + @Path("{firewallRuleUUID}") + @PUT + @Produces({MediaType.APPLICATION_JSON}) + @Consumes({MediaType.APPLICATION_JSON}) + @StatusCodes({ + @ResponseCode(code = 200, condition = "Operation successful"), + @ResponseCode(code = 400, condition = "Bad Request"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 403, condition = "Forbidden"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 501, condition = "Not Implemented")}) + public Response updateFirewallRule( + @PathParam("firewallRuleUUID") String firewallRuleUUID, final NeutronFirewallRuleRequest input) { + INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this); + if (firewallRuleInterface == null) { + throw new ServiceUnavailableException("Firewall Rule CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + /* + * verify the Firewall Rule exists + */ + if (!firewallRuleInterface.neutronFirewallRuleExists(firewallRuleUUID)) { + throw new ResourceNotFoundException("Firewall Rule UUID does not exist."); + } + if (!input.isSingleton()) { + throw new BadRequestException("Only singleton edit supported"); + } + NeutronFirewallRule delta = input.getSingleton(); + NeutronFirewallRule original = firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID); + + /* + * updates restricted by Neutron + * + */ + if (delta.getFirewallRuleUUID() != null || + delta.getFirewallRuleTenantID() != null || + delta.getFirewallRuleName() != null || + delta.getFirewallRuleDescription() != null || + delta.getFirewallRuleAdminStateIsUp() != null || + delta.getFirewallRuleStatus() != null || + delta.getFirewallRuleIsShared() != null || + delta.getFirewallRulePolicyID() != null || + delta.getFirewallRuleProtocol() != null || + delta.getFirewallRuleIpVer() != null || + delta.getFirewallRuleSrcIpAddr() != null || + delta.getFirewallRuleDstIpAddr() != null || + delta.getFirewallRuleSrcPort() != null || + delta.getFirewallRuleDstPort() != null || + delta.getFirewallRulePosition() != null || + delta.getFirewallRuleAction() != null || + delta.getFirewallRuleIsEnabled() != null) { + throw new BadRequestException("Attribute edit blocked by Neutron"); + } + + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallRuleAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance; + int status = service.canUpdateNeutronFirewallRule(delta, original); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + + /* + * update the object and return it + */ + firewallRuleInterface.updateNeutronFirewallRule(firewallRuleUUID, delta); + NeutronFirewallRule updatedFirewallRule = firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance; + service.neutronFirewallRuleUpdated(updatedFirewallRule); + } + } + return Response.status(200) + .entity(new NeutronFirewallRuleRequest(firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID))) + .build(); + } + + /** + * Deletes a Firewall Rule + */ + + @Path("{firewallRuleUUID}") + @DELETE + @StatusCodes({ + @ResponseCode(code = 204, condition = "No Content"), + @ResponseCode(code = 401, condition = "Unauthorized"), + @ResponseCode(code = 404, condition = "Not Found"), + @ResponseCode(code = 409, condition = "Conflict"), + @ResponseCode(code = 501, condition = "Not Implemented")}) + public Response deleteFirewallRule( + @PathParam("firewallRuleUUID") String firewallRuleUUID) { + INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this); + if (firewallRuleInterface == null) { + throw new ServiceUnavailableException("Firewall Rule CRUD Interface " + + RestMessages.SERVICEUNAVAILABLE.toString()); + } + + /* + * verify the Firewall Rule exists and it isn't currently in use + */ + if (!firewallRuleInterface.neutronFirewallRuleExists(firewallRuleUUID)) { + throw new ResourceNotFoundException("Firewall Rule UUID does not exist."); + } + if (firewallRuleInterface.neutronFirewallRuleInUse(firewallRuleUUID)) { + return Response.status(409).build(); + } + NeutronFirewallRule singleton = firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID); + Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallRuleAware.class, this, null); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance; + int status = service.canDeleteNeutronFirewallRule(singleton); + if (status < 200 || status > 299) { + return Response.status(status).build(); + } + } + } + + /* + * remove it and return 204 status + */ + firewallRuleInterface.removeNeutronFirewallRule(firewallRuleUUID); + if (instances != null) { + for (Object instance : instances) { + INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance; + service.neutronFirewallRuleDeleted(singleton); + } + } + return Response.status(204).build(); + } +} diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java index 3fe03a2dac..9abcca7c53 100644 --- a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java +++ b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java @@ -8,12 +8,13 @@ package org.opendaylight.controller.networkconfig.neutron.northbound; +import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider; + +import javax.ws.rs.core.Application; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.ws.rs.core.Application; -import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider; /** @@ -34,6 +35,9 @@ public class NeutronNorthboundRSApplication extends Application { classes.add(NeutronFloatingIPsNorthbound.class); classes.add(NeutronSecurityGroupsNorthbound.class); classes.add(NeutronSecurityRulesNorthbound.class); + classes.add(NeutronFirewallNorthbound.class); + classes.add(NeutronFirewallPolicyNorthbound.class); + classes.add(NeutronFirewallRulesNorthbound.class); return classes; } diff --git a/opendaylight/topologymanager/implementation/pom.xml b/opendaylight/topologymanager/implementation/pom.xml index 196982b361..746135891e 100644 --- a/opendaylight/topologymanager/implementation/pom.xml +++ b/opendaylight/topologymanager/implementation/pom.xml @@ -44,6 +44,7 @@ org.apache.felix maven-bundle-plugin + ${bundle.plugin.version} true diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java b/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java new file mode 100644 index 0000000000..22bd9c0512 --- /dev/null +++ b/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java @@ -0,0 +1,17 @@ +/** +* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. +* +* This program and the accompanying materials are made available under the +* terms of the Eclipse Public License v1.0 which accompanies this distribution, +* and is available at http://www.eclipse.org/legal/epl-v10.html +*/ +package org.opendaylight.controller.topologymanager; + +import java.util.List; + +public interface ITopologyManagerShell { + public List printUserLink(); + public List addUserLink(String name, String ncStr1, String ncStr2); + public List deleteUserLinkShell(String name); + public List printNodeEdges(); +} diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java b/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java index 4ccbb0197d..80d7083ec0 100644 --- a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java +++ b/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java @@ -26,6 +26,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager; import org.opendaylight.controller.topologymanager.ITopologyManager; import org.opendaylight.controller.topologymanager.ITopologyManagerAware; import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware; +import org.opendaylight.controller.topologymanager.ITopologyManagerShell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,6 +74,7 @@ public class Activator extends ComponentActivatorAbstractBase { c.setInterface(new String[] { IListenTopoUpdates.class.getName(), ITopologyManager.class.getName(), + ITopologyManagerShell.class.getName(), IConfigurationContainerAware.class.getName(), ICacheUpdateAware.class.getName() }, props); diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java b/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java index ff1c026a34..b0e87c48f3 100644 --- a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java +++ b/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java @@ -57,6 +57,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager; import org.opendaylight.controller.topologymanager.ITopologyManager; import org.opendaylight.controller.topologymanager.ITopologyManagerAware; import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware; +import org.opendaylight.controller.topologymanager.ITopologyManagerShell; import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; @@ -71,6 +72,7 @@ import org.slf4j.LoggerFactory; public class TopologyManagerImpl implements ICacheUpdateAware, ITopologyManager, + ITopologyManagerShell, IConfigurationContainerAware, IListenTopoUpdates, IObjectReader, @@ -1010,4 +1012,82 @@ public class TopologyManagerImpl implements } } } + + public List printUserLink() { + List result = new ArrayList(); + for (String name : this.userLinksDB.keySet()) { + TopologyUserLinkConfig linkConfig = userLinksDB.get(name); + result.add("Name : " + name); + result.add(linkConfig.toString()); + result.add("Edge " + getLinkTuple(linkConfig)); + result.add("Reverse Edge " + getReverseLinkTuple(linkConfig)); + } + return result; + } + + public List addUserLink(String name, String ncStr1, String ncStr2) { + List result = new ArrayList(); + if ((name == null)) { + result.add("Please enter a valid Name"); + return result; + } + + if (ncStr1 == null) { + result.add("Please enter two node connector strings"); + return result; + } + if (ncStr2 == null) { + result.add("Please enter second node connector string"); + return result; + } + + NodeConnector nc1 = NodeConnector.fromString(ncStr1); + if (nc1 == null) { + result.add("Invalid input node connector 1 string: " + ncStr1); + return result; + } + NodeConnector nc2 = NodeConnector.fromString(ncStr2); + if (nc2 == null) { + result.add("Invalid input node connector 2 string: " + ncStr2); + return result; + } + + TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2); + result.add(this.addUserLink(config).toString()); + return result; + } + + public List deleteUserLinkShell(String name) { + List result = new ArrayList(); + if ((name == null)) { + result.add("Please enter a valid Name"); + return result; + } + this.deleteUserLink(name); + return result; + } + + public List printNodeEdges() { + List result = new ArrayList(); + Map> nodeEdges = getNodeEdges(); + if (nodeEdges == null) { + return result; + } + Set nodeSet = nodeEdges.keySet(); + if (nodeSet == null) { + return result; + } + result.add(" Node Edge"); + for (Node node : nodeSet) { + Set edgeSet = nodeEdges.get(node); + if (edgeSet == null) { + continue; + } + for (Edge edge : edgeSet) { + result.add(node + " " + edge); + } + } + return result; + } + } diff --git a/opendaylight/topologymanager/shell/pom.xml b/opendaylight/topologymanager/shell/pom.xml new file mode 100644 index 0000000000..078b55c596 --- /dev/null +++ b/opendaylight/topologymanager/shell/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + org.opendaylight.controller + commons.opendaylight + 1.4.2-SNAPSHOT + ../../commons/opendaylight + + topologymanager.shell + ${topologymanager.shell.version} + bundle + + + junit + junit + + + org.apache.karaf.shell + org.apache.karaf.shell.console + ${karaf.shell.version} + + + org.mockito + mockito-all + + + org.opendaylight.controller + topologymanager + ${topologymanager.version} + + + + + + + org.apache.felix + maven-bundle-plugin + ${bundle.plugin.version} + + + org.apache.felix.service.command, + org.apache.karaf.shell.commands, + org.apache.karaf.shell.console, + * + + + + + + + diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java new file mode 100644 index 0000000000..1565a8733b --- /dev/null +++ b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java @@ -0,0 +1,39 @@ +/** +* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. +* +* This program and the accompanying materials are made available under the +* terms of the Eclipse Public License v1.0 which accompanies this distribution, +* and is available at http://www.eclipse.org/legal/epl-v10.html +*/ +package org.opendaylight.controller.topologymanager.shell; + +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Argument; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.opendaylight.controller.topologymanager.ITopologyManagerShell; + +@Command(scope = "topologymanager", name = "addUserLink", description="Adds user link") +public class AddUserLink extends OsgiCommandSupport{ + private ITopologyManagerShell topologyManager; + + @Argument(index=0, name="name", description="name", required=true, multiValued=false) + String name = null; + + @Argument(index=1, name="ncStr1", description="ncStr1", required=true, multiValued=false) + String ncStr1 = null; + + @Argument(index=2, name="ncStr2", description="ncStr2", required=true, multiValued=false) + String ncStr2 = null; + + @Override + protected Object doExecute() throws Exception { + for(String p : topologyManager.addUserLink(name, ncStr1, ncStr2)) { + System.out.println(p); + } + return null; + } + + public void setTopologyManager(ITopologyManagerShell topologyManager){ + this.topologyManager = topologyManager; + } +} diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java new file mode 100644 index 0000000000..b226c3c2e2 --- /dev/null +++ b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java @@ -0,0 +1,33 @@ +/** +* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. +* +* This program and the accompanying materials are made available under the +* terms of the Eclipse Public License v1.0 which accompanies this distribution, +* and is available at http://www.eclipse.org/legal/epl-v10.html +*/ +package org.opendaylight.controller.topologymanager.shell; + +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Argument; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.opendaylight.controller.topologymanager.ITopologyManagerShell; + +@Command(scope = "topologymanager", name = "deleteUserLink", description="deletes user link") +public class DeleteUserLink extends OsgiCommandSupport{ + private ITopologyManagerShell topologyManager; + + @Argument(index=0, name="name", description="name", required=true, multiValued=false) + String name = null; + + @Override + protected Object doExecute() throws Exception { + for(String p : topologyManager.deleteUserLinkShell(name)) { + System.out.println(p); + } + return null; + } + + public void setTopologyManager(ITopologyManagerShell topologyManager){ + this.topologyManager = topologyManager; + } +} diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java new file mode 100644 index 0000000000..9c5e806b6d --- /dev/null +++ b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java @@ -0,0 +1,29 @@ +/** +* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. +* +* This program and the accompanying materials are made available under the +* terms of the Eclipse Public License v1.0 which accompanies this distribution, +* and is available at http://www.eclipse.org/legal/epl-v10.html +*/ +package org.opendaylight.controller.topologymanager.shell; + +import org.apache.felix.gogo.commands.Command; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.opendaylight.controller.topologymanager.ITopologyManagerShell; + +@Command(scope = "topologymanager", name = "printNodeEdges", description="Prints node edges") +public class PrintNodeEdges extends OsgiCommandSupport{ + private ITopologyManagerShell topologyManager; + + @Override + protected Object doExecute() throws Exception { + for(String p : topologyManager.printNodeEdges()) { + System.out.println(p); + } + return null; + } + + public void setTopologyManager(ITopologyManagerShell topologyManager){ + this.topologyManager = topologyManager; + } +} diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java new file mode 100644 index 0000000000..df7ab35073 --- /dev/null +++ b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java @@ -0,0 +1,29 @@ +/** +* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. +* +* This program and the accompanying materials are made available under the +* terms of the Eclipse Public License v1.0 which accompanies this distribution, +* and is available at http://www.eclipse.org/legal/epl-v10.html +*/ +package org.opendaylight.controller.topologymanager.shell; + +import org.apache.felix.gogo.commands.Command; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.opendaylight.controller.topologymanager.ITopologyManagerShell; + +@Command(scope = "topologymanager", name = "printUserLink", description="Prints user link") +public class PrintUserLink extends OsgiCommandSupport{ + private ITopologyManagerShell topologyManager; + + @Override + protected Object doExecute() throws Exception { + for(String p : topologyManager.printUserLink()) { + System.out.println(p); + } + return null; + } + + public void setTopologyManager(ITopologyManagerShell topologyManager){ + this.topologyManager = topologyManager; + } +} diff --git a/opendaylight/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 0000000000..96b0b10f10 --- /dev/null +++ b/opendaylight/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +