<properties>\r
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\r
<nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>\r
- <yang.version>0.6.1</yang.version>\r
- <yang.codegen.version>0.6.1</yang.codegen.version>\r
+ <yang.version>0.6.2-SNAPSHOT</yang.version>\r
+ <yang.codegen.version>0.6.2-SNAPSHOT</yang.codegen.version>\r
<bundle.plugin.version>2.3.7</bundle.plugin.version>\r
</properties>\r
<scm>\r
<enforcer.version>1.3.1</enforcer.version>
<bundle.plugin.version>2.3.7</bundle.plugin.version>
<junit.version>4.8.1</junit.version>
- <yangtools.version>0.6.1</yangtools.version>
+ <yangtools.version>0.6.2-SNAPSHOT</yangtools.version>
<!--versions for bits of the controller -->
<controller.version>0.4.2-SNAPSHOT</controller.version>
<hosttracker.api.version>0.5.2-SNAPSHOT</hosttracker.api.version>
package org.opendaylight.controller.config.persist.storage.directory.autodetect;
import java.io.File;
+import java.io.IOException;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.matchers.JUnitMatchers;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
import org.opendaylight.controller.config.persist.test.PropertiesProviderTest;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
public class AutodetectDirectoryPersisterTest {
String snapFromXml = configs.get(1).getConfigSnapshot();
org.junit.Assert.assertThat(snapFromXml, JUnitMatchers.containsString("<config>xml</config>"));
- Assert.assertEquals(configs.get(0).getCapabilities(), configs.get(1).getCapabilities()); }
+ Assert.assertEquals(configs.get(0).getCapabilities(), configs.get(1).getCapabilities());
+ }
+
+ @Test
+ public void testInvalidXml() throws Exception {
+ File resourcePath = FileTypeTest.getResourceAsFile("/bad_controller.xml.config");
+ File parentFile = resourcePath.getParentFile();
+
+ AutodetectDirectoryStorageAdapter adapter = new AutodetectDirectoryStorageAdapter();
+
+ PropertiesProviderTest pp = new PropertiesProviderTest();
+ pp.addProperty("directoryStorage",parentFile.getPath());
+ AutodetectDirectoryPersister persister = (AutodetectDirectoryPersister) adapter.instantiate(pp);
+ try {
+ List<ConfigSnapshotHolder> configs = persister.loadLastConfigs();
+ fail("An exception of type " + IllegalStateException.class + " was expected");
+ } catch (IllegalStateException ise){
+ String message = ise.getMessage();
+ assertThat(message, JUnitMatchers.containsString("Unable to restore configuration snapshot from "));
+ }
+
+ }
+
+ @Test
+ public void testPersistConfig() throws Exception {
+ File resourcePath = FileTypeTest.getResourceAsFile("/combined/1controller.txt.config");
+ File parentFile = resourcePath.getParentFile();
+
+ AutodetectDirectoryStorageAdapter adapter = new AutodetectDirectoryStorageAdapter();
+
+ PropertiesProviderTest pp = new PropertiesProviderTest();
+ pp.addProperty("directoryStorage",parentFile.getPath());
+ AutodetectDirectoryPersister persister = (AutodetectDirectoryPersister) adapter.instantiate(pp);
+ List<ConfigSnapshotHolder> configs = null;
+ try {
+ configs = persister.loadLastConfigs();
+ } catch (IOException e) {
+ fail("An exception of type " + UnsupportedOperationException.class + " was expected");
+ }
+ Assert.assertEquals(2, configs.size());
+ try {
+ persister.persistConfig(configs.get(0));
+ } catch (UnsupportedOperationException uoe){
+ String message = uoe.getMessage();
+ assertThat(message,JUnitMatchers.containsString("This adapter is read only. Please set readonly=true on class"));
+ }
+ }
+
}
--- /dev/null
+<snapshot>
+ <required-capabilities>
+ <capability
+ <capability>cap2</capability>
+ <capability>capa a</capability>
+ </required-capabilities>
+ <configuration>
+ <config>xml</config>
+ </configuration>
+</snapshot>
\ No newline at end of file
+++ /dev/null
-/*
- * 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
- */
-package org.opendaylight.controller.config.persist.storage.file.xml.model;
-
-import javax.xml.bind.ValidationEventHandler;
-import javax.xml.bind.annotation.DomHandler;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.stream.StreamSource;
-import java.io.StringReader;
-import java.io.StringWriter;
-
-class CapabilityHandler implements DomHandler<String, StreamResult> {
-
- private static final String START_TAG = "<capability>";
- private static final String END_TAG = "</capability>";
-
- private StringWriter xmlWriter = new StringWriter();
-
- public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
- xmlWriter.getBuffer().setLength(0);
- return new StreamResult(xmlWriter);
- }
-
- public String getElement(StreamResult rt) {
- String xml = rt.getWriter().toString();
- int beginIndex = xml.indexOf(START_TAG) + START_TAG.length();
- int endIndex = xml.indexOf(END_TAG);
- return xml.substring(beginIndex, endIndex);
- }
-
- public Source marshal(String n, ValidationEventHandler errorHandler) {
- try {
- String xml = START_TAG + n.trim() + END_TAG;
- StringReader xmlReader = new StringReader(xml);
- return new StreamSource(xmlReader);
- } catch(Exception e) {
- throw new RuntimeException(e);
- }
- }
-
-}
import com.google.common.base.Charsets;
import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.SortedSet;
private static int i;
private File file;
+ private static final String NON_EXISTENT_DIRECTORY = "./nonExistentDir/";
+ private static final String NON_EXISTENT_FILE = "nonExistent.txt";
@Before
public void setUp() throws Exception {
i = 1;
}
+ @Test
+ public void testNewFile() throws Exception {
+ XmlFileStorageAdapter storage = new XmlFileStorageAdapter();
+ PropertiesProviderTest pp = new PropertiesProviderTest();
+ pp.addProperty("fileStorage",NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE);
+ pp.addProperty("numberOfBackups",Integer.toString(Integer.MAX_VALUE));
+ storage.instantiate(pp);
+
+ final ConfigSnapshotHolder holder = new ConfigSnapshotHolder() {
+ @Override
+ public String getConfigSnapshot() {
+ return createConfig();
+ }
+
+ @Override
+ public SortedSet<String> getCapabilities() {
+ return createCaps();
+ }
+ };
+ storage.persistConfig(holder);
+
+ storage.persistConfig(holder);
+
+ Assert.assertEquals(storage.toString().replace("\\","/"),"XmlFileStorageAdapter [storage="+NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE+"]");
+ delete(new File(NON_EXISTENT_DIRECTORY));
+ }
@Test
public void testFileAdapter() throws Exception {
XmlFileStorageAdapter storage = new XmlFileStorageAdapter();
return "<config>" + i++ + "</config>";
}
+ private void delete(File f) throws IOException {
+ if (f.isDirectory()) {
+ for (File c : f.listFiles())
+ delete(c);
+ }
+ if (!f.delete())
+ throw new FileNotFoundException("Failed to delete file: " + f);
+ }
}
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-binding</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>binding-type-provider</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
<type>jar</type>
</dependency>
</dependencies>
choice band-type {
case drop {
leaf drop-rate {
+ description "Rate for dropping packets";
type uint32;
}
leaf drop-burst-size {
+ description "Size of bursts";
type uint32;
}
}
case dscp-remark {
leaf dscp-remark-rate {
+ description "Rate for remarking packets";
type uint32;
}
leaf dscp-remark-burst-size {
+ description "Size of bursts";
type uint32;
}
leaf perc_level {
+ description "Number of drop precedence level to add";
type uint8;
}
}
case experimenter {
leaf experimenter-rate {
+ description "Rate for remarking packets";
type uint32;
}
leaf experimenter-burst-size {
+ description "Size of bursts";
type uint32;
}
leaf experimenter {
+ description "Experimenter id";
type uint32;
}
}
grouping meter {
leaf flags {
+ description "Meter configuration flags";
type meter-flags;
}
leaf meter-id {
+ description "Meter instance";
type meter-id;
}
leaf barrier {
+ description "If true, barrier message is sent";
type boolean;
}
leaf meter-name {
+ description "Name of meter instance";
type string;
}
leaf container-name {
+ description "Name of container";
type string;
}
list meter-band-header {
key "band-id";
leaf band-id {
+ description "Meter band id";
type band-id;
}
container meter-band-types {
leaf flags {
+ description "Meter band flags";
type meter-band-type;
}
}
leaf band-rate {
+ description "Rate for this band";
type uint32;
}
leaf band-burst-size {
+ description "Size of bursts";
type uint32;
}
uses band-type;
</profiles>
<properties>
- <yangtools.version>0.6.1</yangtools.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>
<!-- Java Versions -->
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.8.1</version>
- <configuration>
- <stylesheet>maven</stylesheet>
- <failOnError>false</failOnError>
- </configuration>
- <executions>
- <execution>
- <goals>
- <goal>aggregate</goal>
- </goals>
- <phase>site</phase>
- </execution>
- </executions>
- </plugin>
<plugin>
<!-- FIXME: BUG-272: remove this configuration override -->
<groupId>org.apache.maven.plugins</groupId>
*/
package org.opendaylight.controller.sal.binding.api;
+import java.util.EventListener;
import java.util.concurrent.ExecutorService;
import org.opendaylight.controller.md.sal.common.api.notify.NotificationPublishService;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.Notification;
public interface NotificationProviderService extends NotificationService, NotificationPublishService<Notification> {
+
/**
* Deprecated. Use {@link #publish(Notification)}.
*
/**
* Publishes a notification.
*
- * @param Notification notification to publish.
+ * @param Notification
+ * notification to publish.
*
*/
@Override
*/
@Override
void publish(Notification notification, ExecutorService service);
+
+ ListenerRegistration<NotificationInterestListener> registerInterestListener(
+ NotificationInterestListener interestListener);
+
+ public interface NotificationInterestListener extends EventListener {
+
+ void onNotificationSubscribtion(Class<? extends Notification> notificationType);
+ }
}
--- /dev/null
+/*
+ * 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.binding.api.data;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Future;
+
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.yangtools.concepts.Delegator;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * Synchronized wrapper for DataModificationTransaction.
+ *
+ * To get instance of synchronized wrapper use {@link #from(DataModificationTransaction)}
+ *
+ */
+public final class SynchronizedTransaction implements DataModificationTransaction,Delegator<DataModificationTransaction> {
+
+ private final DataModificationTransaction delegate;
+
+ private SynchronizedTransaction(DataModificationTransaction delegate) {
+ this.delegate = delegate;
+ }
+
+ /**
+ * Returns synchronized wrapper on supplied transaction.
+ *
+ * @param transaction Transaction for which synchronized wrapper should be created.
+ * @return Synchronized wrapper over transaction.
+ */
+ public static final SynchronizedTransaction from(DataModificationTransaction transaction) {
+ Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
+ if (transaction instanceof SynchronizedTransaction) {
+ return (SynchronizedTransaction) transaction;
+ }
+ return new SynchronizedTransaction(transaction);
+ }
+
+ @Override
+ public synchronized Map<InstanceIdentifier<? extends DataObject>, DataObject> getCreatedOperationalData() {
+ return delegate.getCreatedOperationalData();
+ }
+
+ @Override
+ public synchronized Map<InstanceIdentifier<? extends DataObject>, DataObject> getCreatedConfigurationData() {
+ return delegate.getCreatedConfigurationData();
+ }
+
+ @Override
+ public synchronized DataObject readOperationalData(InstanceIdentifier<? extends DataObject> path) {
+ return delegate.readOperationalData(path);
+ }
+
+ @Override
+ public synchronized TransactionStatus getStatus() {
+ return delegate.getStatus();
+ }
+
+ @Override
+ public synchronized Map<InstanceIdentifier<? extends DataObject>, DataObject> getUpdatedOperationalData() {
+ return delegate.getUpdatedOperationalData();
+ }
+
+ @Deprecated
+ public synchronized void putRuntimeData(InstanceIdentifier<? extends DataObject> path, DataObject data) {
+ delegate.putRuntimeData(path, data);
+ }
+
+ @Override
+ public synchronized Object getIdentifier() {
+ return delegate.getIdentifier();
+ }
+
+ @Override
+ public synchronized DataObject readConfigurationData(InstanceIdentifier<? extends DataObject> path) {
+ return delegate.readConfigurationData(path);
+ }
+
+ @Override
+ public synchronized Future<RpcResult<TransactionStatus>> commit() {
+ return delegate.commit();
+ }
+
+ @Override
+ public synchronized void putOperationalData(InstanceIdentifier<? extends DataObject> path, DataObject data) {
+ delegate.putOperationalData(path, data);
+ }
+
+ @Override
+ public synchronized void putConfigurationData(InstanceIdentifier<? extends DataObject> path, DataObject data) {
+ delegate.putConfigurationData(path, data);
+ }
+
+ @Override
+ public synchronized Map<InstanceIdentifier<? extends DataObject>, DataObject> getUpdatedConfigurationData() {
+ return delegate.getUpdatedConfigurationData();
+ }
+
+ @Deprecated
+ public synchronized void removeRuntimeData(InstanceIdentifier<? extends DataObject> path) {
+ delegate.removeRuntimeData(path);
+ }
+
+ @Override
+ public synchronized void removeOperationalData(InstanceIdentifier<? extends DataObject> path) {
+ delegate.removeOperationalData(path);
+ }
+
+ @Override
+ public synchronized void removeConfigurationData(InstanceIdentifier<? extends DataObject> path) {
+ delegate.removeConfigurationData(path);
+ }
+
+ @Override
+ public synchronized Set<InstanceIdentifier<? extends DataObject>> getRemovedConfigurationData() {
+ return delegate.getRemovedConfigurationData();
+ }
+
+ @Override
+ public synchronized Set<InstanceIdentifier<? extends DataObject>> getRemovedOperationalData() {
+ return delegate.getRemovedOperationalData();
+ }
+
+ @Override
+ public synchronized Map<InstanceIdentifier<? extends DataObject>, DataObject> getOriginalConfigurationData() {
+ return delegate.getOriginalConfigurationData();
+ }
+
+ @Override
+ public synchronized ListenerRegistration<DataTransactionListener> registerListener(DataTransactionListener listener) {
+ return delegate.registerListener(listener);
+ }
+
+ @Override
+ public synchronized Map<InstanceIdentifier<? extends DataObject>, DataObject> getOriginalOperationalData() {
+ return delegate.getOriginalOperationalData();
+ }
+
+ @Override
+ public synchronized DataModificationTransaction getDelegate() {
+ return delegate;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((delegate == null) ? 0 : delegate.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()){
+ return false;
+ }
+ SynchronizedTransaction other = (SynchronizedTransaction) obj;
+ if (delegate == null) {
+ if (other.delegate != null) {
+ return false;
+ }
+ } else if (!delegate.equals(other.delegate)) {
+ return false;
+ }
+ return true;
+ }
+}
+
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
<type>jar</type>
</dependency>
</dependencies>
import org.opendaylight.yangtools.concepts.Registration\r
import org.opendaylight.yangtools.yang.binding.Notification\r
import org.slf4j.LoggerFactory\r
-import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder\rimport com.google.common.collect.Multimaps
-
-class NotificationBrokerImpl implements NotificationProviderService, AutoCloseable {\r
+import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder\rimport com.google.common.collect.Multimaps\r
+import org.opendaylight.yangtools.concepts.util.ListenerRegistry\r
+import org.opendaylight.controller.sal.binding.api.NotificationProviderService.NotificationInterestListener\r
\r
+class NotificationBrokerImpl implements NotificationProviderService, AutoCloseable {\r
+ \r
+ val ListenerRegistry<NotificationInterestListener> interestListeners = ListenerRegistry.create;\r
+ \r
val Multimap<Class<? extends Notification>, NotificationListener<?>> listeners;\r
\r
@Property\r
var ExecutorService executor;\r
+ \r
+ val logger = LoggerFactory.getLogger(NotificationBrokerImpl)\r
\r
new() {\r
listeners = Multimaps.synchronizedSetMultimap(HashMultimap.create())\r
NotificationListener<T> listener) {\r
val reg = new GenericNotificationRegistration<T>(notificationType, listener, this);\r
listeners.put(notificationType, listener);\r
+ announceNotificationSubscription(notificationType);\r
return reg;\r
}\r
+ \r
+ def announceNotificationSubscription(Class<? extends Notification> notification) {\r
+ for (listener : interestListeners) {\r
+ try {\r
+ listener.instance.onNotificationSubscribtion(notification);\r
+ } catch (Exception e) {\r
+ logger.error("", e.message)\r
+ }\r
+ }\r
+ }\r
\r
override registerNotificationListener(\r
org.opendaylight.yangtools.yang.binding.NotificationListener listener) {\r
val invoker = SingletonHolder.INVOKER_FACTORY.invokerFor(listener);\r
for (notifyType : invoker.supportedNotifications) {\r
listeners.put(notifyType, invoker.invocationProxy)\r
+ announceNotificationSubscription(notifyType)\r
}\r
val registration = new GeneratedListenerRegistration(listener, invoker,this);\r
return registration as Registration<org.opendaylight.yangtools.yang.binding.NotificationListener>;\r
//FIXME: implement properly.\r
}\r
\r
+ override registerInterestListener(NotificationInterestListener interestListener) {\r
+ val registration = interestListeners.register(interestListener);\r
+ \r
+ for(notification : listeners.keySet) {\r
+ interestListener.onNotificationSubscribtion(notification);\r
+ }\r
+ return registration\r
+ }\r
}\r
\r
class GenericNotificationRegistration<T extends Notification> extends AbstractObjectRegistration<NotificationListener<T>> implements ListenerRegistration<NotificationListener<T>> {\r
connector.startDataForwarding();
}
- public static void startNotificationForwarding(BindingIndependentConnector connector, NotificationProviderService baService, NotificationPublishService domService) {
+ public static void startNotificationForwarding(BindingIndependentConnector connector,
+ NotificationProviderService baService, NotificationPublishService domService) {
if(connector.isNotificationForwarding()) {
return;
}
-
- // FIXME
+ connector.setBindingNotificationService(baService);
+ connector.setDomNotificationService(domService);
+ connector.startNotificationForwarding();
}
//
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
+import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
+import org.opendaylight.controller.sal.binding.api.NotificationProviderService.NotificationInterestListener;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
import org.opendaylight.controller.sal.binding.api.data.RuntimeDataProvider;
import org.opendaylight.controller.sal.core.api.RpcImplementation;
import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction;
+import org.opendaylight.controller.sal.core.api.notify.NotificationListener;
+import org.opendaylight.controller.sal.core.api.notify.NotificationPublishService;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.concepts.util.ClassLoaderUtils;
import org.opendaylight.yangtools.yang.binding.DataContainer;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.Notification;
import org.opendaylight.yangtools.yang.binding.RpcService;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
import org.opendaylight.yangtools.yang.common.QName;
private final Logger LOG = LoggerFactory.getLogger(BindingIndependentConnector.class);
- @SuppressWarnings( "deprecation")
+ @SuppressWarnings("deprecation")
private static final InstanceIdentifier<? extends DataObject> ROOT = InstanceIdentifier.builder().toInstance();
private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier ROOT_BI = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
private final static Method EQUALS_METHOD;
-
private BindingIndependentMappingService mappingService;
private org.opendaylight.controller.sal.core.api.data.DataProviderService biDataService;
private org.opendaylight.controller.sal.dom.broker.spi.RpcRouter biRouter;
+ private NotificationProviderService baNotifyService;
+
+ private NotificationPublishService domNotificationService;
static {
try {
- EQUALS_METHOD = Object.class.getMethod("equals", Object.class);
+ EQUALS_METHOD = Object.class.getMethod("equals", Object.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
baRpcRegistryImpl.registerRouterInstantiationListener(domToBindingRpcManager.getInstance());
baRpcRegistryImpl.registerGlobalRpcRegistrationListener(domToBindingRpcManager.getInstance());
}
- if(biRpcRegistry instanceof org.opendaylight.controller.sal.dom.broker.spi.RpcRouter) {
+ if (biRpcRegistry instanceof org.opendaylight.controller.sal.dom.broker.spi.RpcRouter) {
biRouter = (org.opendaylight.controller.sal.dom.broker.spi.RpcRouter) biRpcRegistry;
}
rpcForwarding = true;
public void startNotificationForwarding() {
checkState(!notificationForwarding, "Connector is already forwarding notifications.");
- notificationForwarding = true;
+ if (baNotifyService != null && domNotificationService != null) {
+ baNotifyService.registerInterestListener(new DomToBindingNotificationForwarder());
+
+ notificationForwarding = true;
+ }
}
protected void setMappingService(BindingIndependentMappingService mappingService) {
}
createDefaultDomForwarder();
} catch (Exception e) {
- LOG.error("Could not forward Rpcs of type {}", service.getName(),e);
+ LOG.error("Could not forward Rpcs of type {}", service.getName(), e);
}
registrations = registrationsBuilder.build();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- if(EQUALS_METHOD.equals(method)) {
+ if (EQUALS_METHOD.equals(method)) {
return false;
}
RpcInvocationStrategy strategy = strategiesByMethod.get(method);
checkState(strategy != null);
checkArgument(args.length <= 2);
- if(args.length == 1) {
+ if (args.length == 1) {
checkArgument(args[0] instanceof DataObject);
return strategy.forwardToDomBroker((DataObject) args[0]);
}
RpcInvocationStrategy strategy = null;
if (outputClass.isPresent()) {
if (inputClass.isPresent()) {
- strategy = new DefaultInvocationStrategy(rpc,targetMethod, outputClass.get(), inputClass.get());
+ strategy = new DefaultInvocationStrategy(rpc, targetMethod, outputClass.get(), inputClass
+ .get());
} else {
- strategy = new NoInputNoOutputInvocationStrategy(rpc,targetMethod);
+ strategy = new NoInputNoOutputInvocationStrategy(rpc, targetMethod);
}
} else if(inputClass.isPresent()){
strategy = new NoOutputInvocationStrategy(rpc,targetMethod, inputClass.get());
protected final Method targetMethod;
protected final QName rpc;
- public RpcInvocationStrategy(QName rpc,Method targetMethod) {
+ public RpcInvocationStrategy(QName rpc, Method targetMethod) {
this.targetMethod = targetMethod;
this.rpc = rpc;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public DefaultInvocationStrategy(QName rpc, Method targetMethod, Class<?> outputClass,
Class<? extends DataContainer> inputClass) {
- super(rpc,targetMethod);
+ super(rpc, targetMethod);
this.outputClass = new WeakReference(outputClass);
this.inputClass = new WeakReference(inputClass);
}
+ @SuppressWarnings("unchecked")
@Override
public RpcResult<CompositeNode> uncheckedInvoke(RpcService rpcService, CompositeNode domInput) throws Exception {
DataContainer bindingInput = mappingService.dataObjectFromDataDom(inputClass.get(), domInput);
- Future<RpcResult<?>> result = (Future<RpcResult<?>>) targetMethod.invoke(rpcService, bindingInput);
- if (result == null) {
+ Future<RpcResult<?>> futureResult = (Future<RpcResult<?>>) targetMethod.invoke(rpcService, bindingInput);
+ if (futureResult == null) {
return Rpcs.getRpcResult(false);
}
- RpcResult<?> bindingResult = result.get();
+ RpcResult<?> bindingResult = futureResult.get();
+ final Object resultObj = bindingResult.getResult();
+ if (resultObj instanceof DataObject) {
+ final CompositeNode output = mappingService.toDataDom((DataObject)resultObj);
+ return Rpcs.getRpcResult(true, output, Collections.<RpcError>emptySet());
+ }
return Rpcs.getRpcResult(true);
}
public Future<RpcResult<?>> forwardToDomBroker(DataObject input) {
if(biRouter != null) {
CompositeNode xml = mappingService.toDataDom(input);
- CompositeNode wrappedXml = ImmutableCompositeNode.create(rpc,ImmutableList.<Node<?>>of(xml));
+ CompositeNode wrappedXml = ImmutableCompositeNode.create(rpc, ImmutableList.<Node<?>> of(xml));
RpcResult<CompositeNode> result = biRouter.invokeRpc(rpc, wrappedXml);
Object baResultValue = null;
- if(result.getResult() != null) {
+ if (result.getResult() != null) {
baResultValue = mappingService.dataObjectFromDataDom(outputClass.get(), result.getResult());
}
RpcResult<?> baResult = Rpcs.getRpcResult(result.isSuccessful(), baResultValue, result.getErrors());
- return Futures.<RpcResult<?>>immediateFuture(baResult);
+ return Futures.<RpcResult<?>> immediateFuture(baResult);
}
- return Futures.<RpcResult<?>>immediateFuture(Rpcs.getRpcResult(false));
+ return Futures.<RpcResult<?>> immediateFuture(Rpcs.getRpcResult(false));
}
}
private class NoInputNoOutputInvocationStrategy extends RpcInvocationStrategy {
public NoInputNoOutputInvocationStrategy(QName rpc, Method targetMethod) {
- super(rpc,targetMethod);
+ super(rpc, targetMethod);
}
public RpcResult<CompositeNode> uncheckedInvoke(RpcService rpcService, CompositeNode domInput) throws Exception {
public BindingIndependentMappingService getMappingService() {
return mappingService;
}
+
+ public void setBindingNotificationService(NotificationProviderService baService) {
+ this.baNotifyService = baService;
+
+ }
+
+ public void setDomNotificationService(NotificationPublishService domService) {
+ this.domNotificationService = domService;
+ }
+
+ private class DomToBindingNotificationForwarder implements NotificationInterestListener, NotificationListener {
+
+ private ConcurrentMap<QName, WeakReference<Class<? extends Notification>>> notifications = new ConcurrentHashMap<>();
+ private Set<QName> supportedNotifications = new HashSet<>();
+
+ @Override
+ public Set<QName> getSupportedNotifications() {
+ return Collections.unmodifiableSet(supportedNotifications);
+ }
+
+ @Override
+ public void onNotification(CompositeNode notification) {
+ QName qname = notification.getNodeType();
+ WeakReference<Class<? extends Notification>> potential = notifications.get(qname);
+ if (potential != null) {
+ Class<? extends Notification> potentialClass = potential.get();
+ if (potentialClass != null) {
+ final DataContainer baNotification = mappingService.dataObjectFromDataDom(potentialClass,
+ notification);
+
+ if (baNotification instanceof Notification) {
+ baNotifyService.publish((Notification) baNotification);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onNotificationSubscribtion(Class<? extends Notification> notificationType) {
+ QName qname = BindingReflections.findQName(notificationType);
+ if (qname != null) {
+ WeakReference<Class<? extends Notification>> already = notifications.putIfAbsent(qname,
+ new WeakReference<Class<? extends Notification>>(notificationType));
+ if (already == null) {
+ domNotificationService.addNotificationListener(qname, this);
+ supportedNotifications.add(qname);
+ }
+ }
+ }
+ }
}
+++ /dev/null
-/*
- * 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.binding.impl.connect.dom;
-
-import java.util.concurrent.ConcurrentMap;
-
-import org.opendaylight.controller.sal.binding.api.mount.MountProviderInstance;
-import org.opendaylight.controller.sal.binding.api.mount.MountProviderService;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
-import org.opendaylight.controller.sal.core.api.mount.MountProvisionInstance;
-import org.opendaylight.controller.sal.core.api.mount.MountProvisionService;
-import org.opendaylight.controller.sal.core.api.mount.MountProvisionService.MountProvisionListener;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-public class BindingIndependentMountPointForwarder {
-
- private MountProvisionService domMountService;
- private MountProviderService baMountService;
- private BindingIndependentMappingService mappingService;
-
- private final DomMountPointForwardingManager domForwardingManager = new DomMountPointForwardingManager();
- private final BindingMountPointForwardingManager bindingForwardingManager = new BindingMountPointForwardingManager();
-
- private ConcurrentMap<InstanceIdentifier<?>, BindingIndependentConnector> connectors;
- private ConcurrentMap<InstanceIdentifier<?>, org.opendaylight.yangtools.yang.data.api.InstanceIdentifier> forwarded;
- private ListenerRegistration<MountProvisionListener> domListenerRegistration;
- private ListenerRegistration<org.opendaylight.controller.sal.binding.api.mount.MountProviderService.MountProvisionListener> baListenerRegistration;
-
- public MountProvisionService getDomMountService() {
- return domMountService;
- }
-
- public void setDomMountService(MountProvisionService domMountService) {
- this.domMountService = domMountService;
- }
-
- public void start() {
- if(domMountService != null && baMountService != null) {
- domListenerRegistration = domMountService.registerProvisionListener(domForwardingManager);
- baListenerRegistration = baMountService.registerProvisionListener(bindingForwardingManager);
- }
- }
-
- private void tryToDeployConnector(InstanceIdentifier<?> baPath,
- org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biPath) {
- org.opendaylight.yangtools.yang.data.api.InstanceIdentifier previous = forwarded.putIfAbsent(baPath, biPath);
- if(previous != null) {
- return;
- }
- MountProviderInstance baMountPoint = baMountService.getMountPoint(baPath);
- MountProvisionInstance domMountPoint = domMountService.getMountPoint(biPath);
- BindingIndependentConnector connector = createForwarder(baPath, baMountPoint, domMountPoint);
- connectors.put(baPath, connector);
- connector.startDataForwarding();
- connector.startRpcForwarding();
- connector.startNotificationForwarding();
- }
-
- private BindingIndependentConnector createForwarder(InstanceIdentifier<?> path, MountProviderInstance baMountPoint,
- MountProvisionInstance domMountPoint) {
- BindingIndependentConnector connector = new BindingIndependentConnector();
-
- connector.setBindingDataService(baMountPoint);
- connector.setBindingRpcRegistry(baMountPoint);
- //connector.setBindingNotificationBroker(baMountPoint);
-
- connector.setDomDataService(domMountPoint);
- connector.setDomRpcRegistry(domMountPoint);
- //connector.setDomNotificationBroker(domMountPoint);
- return connector;
- }
-
- public synchronized void tryToDeployDomForwarder(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath) {
- InstanceIdentifier<?> baPath;
- try {
- baPath = mappingService.fromDataDom(domPath);
- BindingIndependentConnector potentialConnector = connectors.get(baPath);
- if(potentialConnector != null) {
- return;
- }
- tryToDeployConnector(baPath,domPath);
- } catch (DeserializationException e) {
-
- }
- }
-
- public synchronized void tryToDeployBindingForwarder(InstanceIdentifier<?> baPath) {
- BindingIndependentConnector potentialConnector =connectors.get(baPath);
- if(potentialConnector != null) {
- return;
- }
- org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = mappingService.toDataDom(baPath);
- tryToDeployConnector(baPath, domPath);
- }
-
- public synchronized void undeployBindingForwarder(InstanceIdentifier<?> baPath) {
- // FIXME: Implement closeMountPoint
- }
-
- public synchronized void undeployDomForwarder(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biPath) {
- // FIXME: Implement closeMountPoint
- }
-
- private class DomMountPointForwardingManager implements MountProvisionListener {
-
- @Override
- public void onMountPointCreated(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier path) {
- tryToDeployDomForwarder(path);
- }
-
- @Override
- public void onMountPointRemoved(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier path) {
- undeployDomForwarder(path);
- }
- }
-
- private class BindingMountPointForwardingManager implements
- org.opendaylight.controller.sal.binding.api.mount.MountProviderService.MountProvisionListener {
-
- @Override
- public void onMountPointCreated(InstanceIdentifier<?> path) {
- tryToDeployBindingForwarder(path);
- }
-
- @Override
- public void onMountPointRemoved(InstanceIdentifier<?> path) {
- undeployBindingForwarder(path);
- }
- }
-}
BindingDomConnectorDeployer.startRpcForwarding(mountConnector, baMountPoint, domMountPoint);
BindingDomConnectorDeployer.startNotificationForwarding(mountConnector, baMountPoint, domMountPoint);
// connector.setDomNotificationBroker(domMountPoint);
- return connector;
+ return mountConnector;
}
public synchronized void tryToDeployDomForwarder(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath) {
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
<type>jar</type>
</dependency>
</dependencies>
L listener) {
return getRpcRegistryChecked().registerRouteChangeListener(listener);
}
+
+ @Override
+ public ListenerRegistration<NotificationInterestListener> registerInterestListener(
+ NotificationInterestListener interestListener) {
+ return getNotificationBrokerChecked().registerInterestListener(interestListener);
+ }
}
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>concepts</artifactId>
- <version>0.6.1</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
\r
import static com.google.common.base.Preconditions.*\rimport org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent
import com.google.common.collect.Multimaps
+import java.util.concurrent.locks.Lock
+import java.util.concurrent.locks.ReentrantLock
abstract class AbstractDataBroker<P extends Path<P>, D, DCL extends DataChangeListener<P, D>> implements DataModificationTransactionFactory<P, D>, //\r
DataReader<P, D>, //\r
\r
Multimap<P, DataChangeListenerRegistration<P, D, DCL>> listeners = Multimaps.synchronizedSetMultimap(HashMultimap.create());\r
Multimap<P, DataCommitHandlerRegistrationImpl<P, D>> commitHandlers = Multimaps.synchronizedSetMultimap(HashMultimap.create());\r
+
+ private val Lock registrationLock = new ReentrantLock;
\r
val ListenerRegistry<RegistrationListener<DataCommitHandlerRegistration<P,D>>> commitHandlerRegistrationListeners = new ListenerRegistry();\r
public new() {\r
}\r
\r
protected def /*Iterator<Entry<Collection<DataChangeListenerRegistration<P,D,DCL>>,D>>*/ affectedCommitHandlers(\r
- HashSet<P> paths) {\r
- return FluentIterable.from(commitHandlers.asMap.entrySet).filter[key.isAffectedBy(paths)] //\r
- .transformAndConcat[value] //\r
- .transform[instance].toList()\r
+ HashSet<P> paths) {
+ return withLock(registrationLock) [|\r
+ return FluentIterable.from(commitHandlers.asMap.entrySet).filter[key.isAffectedBy(paths)] //\r
+ .transformAndConcat[value] //\r
+ .transform[instance].toList()
+ ]\r
}\r
\r
override final readConfigurationData(P path) {\r
\r
override final readOperationalData(P path) {\r
return dataReadRouter.readOperationalData(path);\r
- }\r
-\r
- override final registerCommitHandler(P path, DataCommitHandler<P, D> commitHandler) {\r
- val registration = new DataCommitHandlerRegistrationImpl(path, commitHandler, this);\r
- commitHandlers.put(path, registration)\r
- LOG.trace("Registering Commit Handler {} for path: {}",commitHandler,path);\r
- for(listener : commitHandlerRegistrationListeners) {\r
- try {\r
- listener.instance.onRegister(registration);\r
- } catch (Exception e) {\r
- LOG.error("Unexpected exception in listener {} during invoking onRegister",listener.instance,e);\r
- }\r
- }\r
- return registration;\r
+ }
+
+ private static def <T> withLock(Lock lock,Callable<T> method) {
+ lock.lock
+ try {
+ return method.call
+ } finally {
+ lock.unlock
+ }
+ } \r
+\r
+ override final registerCommitHandler(P path, DataCommitHandler<P, D> commitHandler) {
+ return withLock(registrationLock) [|\r
+ val registration = new DataCommitHandlerRegistrationImpl(path, commitHandler, this);\r
+ commitHandlers.put(path, registration)\r
+ LOG.trace("Registering Commit Handler {} for path: {}",commitHandler,path);\r
+ for(listener : commitHandlerRegistrationListeners) {\r
+ try {\r
+ listener.instance.onRegister(registration);\r
+ } catch (Exception e) {\r
+ LOG.error("Unexpected exception in listener {} during invoking onRegister",listener.instance,e);\r
+ }\r
+ }
+ return registration;
+ ]\r
}\r
\r
override final def registerDataChangeListener(P path, DCL listener) {\r
- val reg = new DataChangeListenerRegistration(path, listener, this);\r
- listeners.put(path, reg);\r
- val initialConfig = dataReadRouter.readConfigurationData(path);\r
- val initialOperational = dataReadRouter.readOperationalData(path);\r
- val event = createInitialListenerEvent(path,initialConfig,initialOperational);\r
- listener.onDataChanged(event);\r
- return reg;\r
+ return withLock(registrationLock) [|
+ val reg = new DataChangeListenerRegistration(path, listener, this);\r
+ listeners.put(path, reg);\r
+ val initialConfig = dataReadRouter.readConfigurationData(path);\r
+ val initialOperational = dataReadRouter.readOperationalData(path);\r
+ val event = createInitialListenerEvent(path,initialConfig,initialOperational);\r
+ listener.onDataChanged(event);\r
+ return reg;
+ ]\r
}\r
\r
final def registerDataReader(P path, DataReader<P, D> reader) {\r
-\r
- val confReg = dataReadRouter.registerConfigurationReader(path, reader);\r
- val dataReg = dataReadRouter.registerOperationalReader(path, reader);\r
-\r
- return new CompositeObjectRegistration(reader, Arrays.asList(confReg, dataReg));\r
+ return withLock(registrationLock) [|\r
+ val confReg = dataReadRouter.registerConfigurationReader(path, reader);\r
+ val dataReg = dataReadRouter.registerOperationalReader(path, reader);\r
+ \r
+ return new CompositeObjectRegistration(reader, Arrays.asList(confReg, dataReg));
+ ]\r
}\r
\r
override registerCommitHandlerListener(RegistrationListener<DataCommitHandlerRegistration<P, D>> commitHandlerListener) {\r
val ret = commitHandlerRegistrationListeners.register(commitHandlerListener);\r
- \r
return ret;\r
}\r
\r
\r
}\r
\r
- protected final def removeListener(DataChangeListenerRegistration<P, D, DCL> registration) {\r
- listeners.remove(registration.path, registration);\r
+ protected final def removeListener(DataChangeListenerRegistration<P, D, DCL> registration) {
+ return withLock(registrationLock) [|\r
+ listeners.remove(registration.path, registration);
+ ]\r
}\r
\r
protected final def removeCommitHandler(DataCommitHandlerRegistrationImpl<P, D> registration) {\r
- commitHandlers.remove(registration.path, registration);\r
- \r
- LOG.trace("Removing Commit Handler {} for path: {}",registration.instance,registration.path);\r
- for(listener : commitHandlerRegistrationListeners) {\r
- try {\r
- listener.instance.onUnregister(registration);\r
- } catch (Exception e) {\r
- LOG.error("Unexpected exception in listener {} during invoking onUnregister",listener.instance,e);\r
- }\r
- }\r
+ return withLock(registrationLock) [|
+ commitHandlers.remove(registration.path, registration);\r
+ LOG.trace("Removing Commit Handler {} for path: {}",registration.instance,registration.path);\r
+ for(listener : commitHandlerRegistrationListeners) {\r
+ try {\r
+ listener.instance.onUnregister(registration);\r
+ } catch (Exception e) {\r
+ LOG.error("Unexpected exception in listener {} during invoking onUnregister",listener.instance,e);\r
+ }\r
+ }
+ return null;
+ ]\r
}\r
\r
protected final def getActiveCommitHandlers() {\r
}\r
\r
protected def /*Iterator<Entry<Collection<DataChangeListenerRegistration<P,D,DCL>>,D>>*/ affectedListenersWithInitialState(\r
- HashSet<P> paths) {\r
- return FluentIterable.from(listeners.asMap.entrySet).filter[key.isAffectedBy(paths)].transform [\r
- val operationalState = readOperationalData(key)\r
- val configurationState = readConfigurationData(key)\r
- return new ListenerStateCapture(key, value, operationalState, configurationState)\r
- ].toList()\r
+ HashSet<P> paths) {
+ return withLock(registrationLock) [|\r
+ return FluentIterable.from(listeners.asMap.entrySet).filter[key.isAffectedBy(paths)].transform [\r
+ val operationalState = readOperationalData(key)\r
+ val configurationState = readConfigurationData(key)\r
+ return new ListenerStateCapture(key, value, operationalState, configurationState)\r
+ ].toList()
+ ]\r
}\r
\r
protected def boolean isAffectedBy(P key, Set<P> paths) {\r
affectedPaths.addAll(transaction.createdOperationalData.keySet);\r
affectedPaths.addAll(transaction.updatedOperationalData.keySet);\r
affectedPaths.addAll(transaction.removedOperationalData);\r
-\r
+
val listeners = dataBroker.affectedListenersWithInitialState(affectedPaths);\r
\r
val transactionId = transaction.identifier;\r
\r
log.trace("Transaction: {} Started.",transactionId);\r
+ log.trace("Transaction: {} Affected Subtrees:",transactionId,affectedPaths);
// requesting commits\r
val Iterable<DataCommitHandler<P, D>> commitHandlers = dataBroker.affectedCommitHandlers(affectedPaths);\r
val List<DataCommitTransaction<P, D>> handlerTransactions = new ArrayList();\r
} catch (Exception e) {\r
log.error("Transaction: {} Request Commit failed", transactionId,e);\r
dataBroker.failedTransactionsCount.andIncrement\r
+ transaction.changeStatus(TransactionStatus.FAILED)
return rollback(handlerTransactions, e);\r
}\r
val List<RpcResult<Void>> results = new ArrayList();\r
listeners.publishDataChangeEvent();\r
} catch (Exception e) {\r
log.error("Transaction: {} Finish Commit failed",transactionId, e);\r
- dataBroker.failedTransactionsCount.andIncrement\r
+ dataBroker.failedTransactionsCount.andIncrement
+ transaction.changeStatus(TransactionStatus.FAILED)\r
return rollback(handlerTransactions, e);\r
}\r
log.trace("Transaction: {} Finished successfully.",transactionId);\r
- dataBroker.finishedTransactionsCount.andIncrement;\r
+ dataBroker.finishedTransactionsCount.andIncrement;
+ transaction.changeStatus(TransactionStatus.COMMITED)\r
return Rpcs.getRpcResult(true, TransactionStatus.COMMITED, Collections.emptySet());\r
\r
}\r
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>concepts</artifactId>
- <version>0.6.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
<type>jar</type>
</dependency>
</dependencies>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
<type>jar</type>
</dependency>
</dependencies>
def registerMountPoint(MountPointImpl impl) {
//dataBroker?.registerConfigurationReader(impl.mountPath,impl.readWrapper);
//dataBroker?.registerOperationalReader(impl.mountPath,impl.readWrapper);
-
}
override registerProvisionListener(MountProvisionListener listener) {
val simpleNode = node.getSimpleNodesByName(keyValue.key);
if(simpleNode !== null && !simpleNode.empty) {
checkState(simpleNode.size <= 1,"Only one simple node for key $s is allowed in node $s",keyValue.key,node);
- checkState(simpleNode.get(0).value == keyValue.value,"Key node must equals to instance identifier value");
+ checkState(simpleNode.get(0).value == keyValue.value,"Key node must equal to instance identifier value in node $s",node);
ret.put(keyValue.key,simpleNode.get(0));
}
val compositeNode = node.getCompositesByName(keyValue.key);
private static Logger log = LoggerFactory.getLogger(NotificationRouterImpl.class);
private Multimap<QName, Registration<NotificationListener>> listeners = Multimaps.synchronizedSetMultimap(HashMultimap.<QName, Registration<NotificationListener>>create());
-
+// private Registration<NotificationListener> defaultListener;
+
private void sendNotification(CompositeNode notification) {
- QName type = notification.getNodeType();
- Collection<Registration<NotificationListener>> toNotify = listeners.get(type);
+ final QName type = notification.getNodeType();
+ final Collection<Registration<NotificationListener>> toNotify = listeners.get(type);
log.trace("Publishing notification " + type);
- if (toNotify == null) {
- // No listeners were registered - returns.
+ if ((toNotify == null) || toNotify.isEmpty()) {
+ log.debug("No listener registered for handling of notification {}", type);
return;
}
log.error("Uncaught exception in NotificationListener", e);
}
}
-
}
@Override
public void publish(CompositeNode notification) {
sendNotification(notification);
}
-
+
@Override
public Registration<NotificationListener> addNotificationListener(QName notification, NotificationListener listener) {
ListenerRegistration ret = new ListenerRegistration(notification, listener);
+ listeners.put(notification, ret);
return ret;
}
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
<type>jar</type>
</dependency>
</dependencies>
*/
public void onNotification(final NetconfClientSession session, final NetconfMessage message) {
this.device.logger.debug("Received NETCONF notification.", message);
- CompositeNode _notificationBody = null;
- CompositeNode _compositeNode = null;
+ CompositeNode domNotification = null;
if (message != null) {
- _compositeNode = NetconfMapping.toCompositeNode(message,device.getSchemaContext());
+ domNotification = NetconfMapping.toNotificationNode(message, device.getSchemaContext());
}
- if (_compositeNode != null) {
- _notificationBody = NetconfDeviceListener.getNotificationBody(_compositeNode);
- }
- final CompositeNode domNotification = _notificationBody;
- boolean _notEquals = (!Objects.equal(domNotification, null));
- if (_notEquals) {
+ if (domNotification != null) {
MountProvisionInstance _mountInstance = null;
if (this.device != null) {
_mountInstance = this.device.getMountInstance();
import com.google.common.base.Optional
import org.opendaylight.yangtools.yang.model.api.SchemaContext
import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils
+import org.opendaylight.yangtools.yang.model.api.NotificationDefinition
+import java.util.Set
class NetconfMapping {
}
static def CompositeNode toCompositeNode(NetconfMessage message,Optional<SchemaContext> ctx) {
- return null//message.toRpcResult().result;
+ //TODO: implement general normalization to normalize incoming Netconf Message
+ // for Schema Context counterpart
+ return null
+ }
+
+ static def CompositeNode toNotificationNode(NetconfMessage message,Optional<SchemaContext> ctx) {
+ if (ctx.present) {
+ val schemaContext = ctx.get
+ val notifications = schemaContext.notifications
+ val document = message.document
+ return XmlDocumentUtils.notificationToDomNodes(document, Optional.<Set<NotificationDefinition>>fromNullable(notifications))
+ }
+ return null
}
static def NetconfMessage toRpcMessage(QName rpc, CompositeNode node,Optional<SchemaContext> ctx) {
if(isDataRetrievalReply(rpc)) {
val xmlData = message.document.dataSubtree
- val dataNodes = XmlDocumentUtils.toDomNodes(xmlData,Optional.of(context.get.dataDefinitions))
+ val dataNodes = XmlDocumentUtils.toDomNodes(xmlData, Optional.of(context.get.dataDefinitions))
val it = ImmutableCompositeNode.builder()
setQName(NETCONF_RPC_REPLY_QNAME)
- add(ImmutableCompositeNode.create(NETCONF_DATA_QNAME,dataNodes));
+ add(ImmutableCompositeNode.create(NETCONF_DATA_QNAME, dataNodes));
rawRpc = it.toInstance;
//sys(xmlData)
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>0.6.1</version>
+ <version>${yangtools.version}</version>
<type>jar</type>
</dependency>
</dependencies>
+++ /dev/null
-/*
- * 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
- */
-package org.opendaylight.controller.sal.rest.api;
-
-public class Draft01 {
- public static class MediaTypes {
- public static final String API = "application/vnd.yang.api";
- public static final String DATASTORE = "application/vnd.yang.datastore";
- public static final String DATA = "application/vnd.yang.data";
- public static final String EVENT = "application/vnd.yang.event";
- public static final String OPERATION = "application/vnd.yang.operation";
- public static final String PATCH = "application/vnd.yang.patch";
- }
-}
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
/**
* The URI hierarchy for the RESTCONF resources consists of an entry
- * point container, 3 top-level resources, and 1 field. Refer to
- * Section 5 for details on each URI.
- * <ul>
+ * point container, 4 top-level resources, and 1 field.
+ * <ul>
* <li><b>/restconf</b> - {@link #getRoot()}
- * <ul><li><b>/config</b>
- * <li><b>/operational</b> - {@link #readAllData()} - Added in Draft02
- * <li><b>/datastore</b> - {@link #readAllData()}
- * <ul>
- * <li>/(top-level-data-nodes) (config=true or false)
- * </ul>
- * <li>/modules
- * <ul><li>/module
- * <li>/name
- * <li>/revision
- * <li>/namespace
- * <li>/feature
- * <li>/deviation
- * </ul>
- * <li>/operations
- * <ul>
- * <li>/(custom protocol operations)
- * </ul>
- * <li>/version (field)
+ * <ul>
+ * <li><b>/config</b> - {@link #readConfigurationData(String)}
+ * {@link #updateConfigurationData(String, CompositeNode)}
+ * {@link #createConfigurationData(CompositeNode)}
+ * {@link #createConfigurationData(String, CompositeNode)}
+ * {@link #deleteConfigurationData(String)}
+ * <li><b>/operational</b> - {@link #readOperationalData(String)}
+ * <li>/modules - {@link #getModules()}
+ * <ul>
+ * <li>/module
+ * </ul>
+ * <li><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)}
+ * {@link #invokeRpc(String, CompositeNode)}
+ * <li>/version (field)
* </ul>
+ * </ul>
*/
@Path("/")
-public interface RestconfService extends RestconfServiceLegacy {
+public interface RestconfService {
public static final String XML = "+xml";
public static final String JSON = "+json";
@GET
@Path("/modules")
- @Produces({Draft01.MediaTypes.API+JSON,Draft01.MediaTypes.API+XML,
- Draft02.MediaTypes.API+JSON,Draft02.MediaTypes.API+XML})
+ @Produces({Draft02.MediaTypes.API+JSON,Draft02.MediaTypes.API+XML})
public StructuredData getModules();
@POST
@Path("/operations/{identifier}")
- @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
+ @Produces({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
+ Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- @Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
+ @Consumes({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
+ Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
public StructuredData invokeRpc(@PathParam("identifier") String identifier, CompositeNode payload);
@POST
@Path("/operations/{identifier}")
- @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
+ @Produces({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
+ Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public StructuredData invokeRpc(@PathParam("identifier") String identifier);
+ public StructuredData invokeRpc(@PathParam("identifier") String identifier, @DefaultValue("") String noPayload);
@GET
@Path("/config/{identifier:.+}")
+++ /dev/null
-/*
- * 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.api;
-
-import javax.ws.rs.Consumes;
-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.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.opendaylight.controller.sal.restconf.impl.StructuredData;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-
-public interface RestconfServiceLegacy {
-
- public static final String XML = "+xml";
- public static final String JSON = "+json";
-
- @Deprecated
- @GET
- @Path("/datastore")
- @Produces({Draft01.MediaTypes.DATASTORE+JSON,Draft01.MediaTypes.DATASTORE+XML})
- public StructuredData readAllData();
-
- @Deprecated
- @GET
- @Path("/datastore/{identifier:.+}")
- @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public StructuredData readData(@PathParam("identifier") String identifier);
-
- @Deprecated
- @POST
- @Path("/datastore/{identifier:.+}")
- @Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public Response createConfigurationDataLegacy(@PathParam("identifier") String identifier, CompositeNode payload);
-
- @Deprecated
- @PUT
- @Path("/datastore/{identifier:.+}")
- @Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public Response updateConfigurationDataLegacy(@PathParam("identifier") String identifier, CompositeNode payload);
-
-}
private DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
for (DataSchemaNode dsn : dataSchemaNode) {
- if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
+ if (node.getNodeType().equals(dsn.getQName())) {
return dsn;
} else if (dsn instanceof ChoiceNode) {
for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
result.append("/");
writeModuleNameAndIdentifier(result, identityValue);
- if (identityValue.getPredicates() != null) {
+ if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
for (Predicate predicate : identityValue.getPredicates()) {
IdentityValue identityValuePredicate = predicate.getName();
result.append("[");
- writeModuleNameAndIdentifier(result, identityValuePredicate);
- result.append("=\"");
+ if (identityValuePredicate == null) {
+ result.append(".");
+ } else {
+ writeModuleNameAndIdentifier(result, identityValuePredicate);
+ }
+ result.append("='");
result.append(predicate.getValue());
- result.append("\"");
+ result.append("'");
result.append("]");
}
}
String nameForOutput = node.getNodeType().getLocalName();
if (schema.isAugmenting()) {
ControllerContext contContext = ControllerContext.getInstance();
- CharSequence moduleName;
- moduleName = contContext.toRestconfIdentifier(schema.getQName());
+ CharSequence moduleName = null;
+ if (mountPoint == null) {
+ moduleName = contContext.toRestconfIdentifier(schema.getQName());
+ } else {
+ moduleName = contContext.toRestconfIdentifier(mountPoint, schema.getQName());
+ }
if (moduleName != null) {
nameForOutput = moduleName.toString();
+ } else {
+ logger.info("Module '{}' was not found in schema from mount point", schema.getQName());
}
}
writer.name(nameForOutput);
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
-import org.opendaylight.controller.sal.rest.api.Draft01;
import org.opendaylight.controller.sal.rest.api.Draft02;
import org.opendaylight.controller.sal.rest.api.RestconfService;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@Provider
-@Consumes({ Draft01.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
+@Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
MediaType.APPLICATION_JSON })
public enum JsonToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
INSTANCE;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
-import org.opendaylight.controller.sal.rest.api.Draft01;
import org.opendaylight.controller.sal.rest.api.Draft02;
import org.opendaylight.controller.sal.rest.api.RestconfService;
import org.opendaylight.controller.sal.restconf.impl.ResponseException;
import com.google.gson.stream.JsonWriter;
@Provider
-@Produces({ Draft01.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
+@Produces({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
MediaType.APPLICATION_JSON })
public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
INSTANCE;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-import org.opendaylight.controller.sal.rest.api.Draft01;
import org.opendaylight.controller.sal.rest.api.Draft02;
import org.opendaylight.controller.sal.rest.api.RestconfService;
import org.opendaylight.controller.sal.restconf.impl.ResponseException;
import org.w3c.dom.Document;
@Provider
-@Produces({ Draft01.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
+@Produces({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredData> {
INSTANCE;
import javax.ws.rs.ext.Provider;
import javax.xml.stream.XMLStreamException;
-import org.opendaylight.controller.sal.rest.api.Draft01;
import org.opendaylight.controller.sal.rest.api.Draft02;
import org.opendaylight.controller.sal.rest.api.RestconfService;
import org.opendaylight.controller.sal.restconf.impl.ResponseException;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@Provider
-@Consumes({ Draft01.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
+@Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
public enum XmlToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
INSTANCE;
var module = uriToModuleName.get(qname.namespace)
if (module === null) {
val moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
- if(moduleSchema === null) throw new IllegalArgumentException()
+ if(moduleSchema === null) return null
uriToModuleName.put(qname.namespace, moduleSchema.name)
module = moduleSchema.name;
}
return '''«module»:«qname.localName»''';
}
+ def CharSequence toRestconfIdentifier(MountInstance mountPoint, QName qname) {
+ val moduleSchema = mountPoint?.schemaContext.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
+ if(moduleSchema === null) return null
+ val module = moduleSchema.name;
+ return '''«module»:«qname.localName»''';
+ }
+
private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
for (caze : container.cases) {
val ret = caze.childByQName(name)
List<Predicate> predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument)
.getKeyValues());
identityValue.setPredicates(predicates);
+ } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
+ List<Predicate> predicates = new ArrayList<>();
+ String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
+ predicates.add(new Predicate(null, value));
+ identityValue.setPredicates(predicates);
}
identityValuesDTO.add(identityValue);
}
return INSTANCE
}
- override readAllData() {
-
- // return broker.readOperationalData("".toInstanceIdentifier.getInstanceIdentifier);
- throw new UnsupportedOperationException("Reading all data is currently not supported.")
- }
-
override getModules() {
throw new UnsupportedOperationException("TODO: auto-generated method stub")
}
return callRpc(identifier.rpcDefinition, payload)
}
- override invokeRpc(String identifier) {
+ override invokeRpc(String identifier, String noPayload) {
+ if (!noPayload.nullOrEmpty) {
+ throw new ResponseException(UNSUPPORTED_MEDIA_TYPE, "Content-Type contains unsupported Media Type.");
+ }
return callRpc(identifier.rpcDefinition, null)
}
return new StructuredData(rpcResult.result, rpc.output, null)
}
- override readData(String identifier) {
- val iiWithData = identifier.toInstanceIdentifier
- var CompositeNode data = null;
- if (iiWithData.mountPoint !== null) {
- data = broker.readOperationalDataBehindMountPoint(iiWithData.mountPoint, iiWithData.instanceIdentifier)
- } else {
- data = broker.readOperationalData(iiWithData.getInstanceIdentifier);
- }
- return new StructuredData(data, iiWithData.schemaNode, iiWithData.mountPoint)
- }
-
override readConfigurationData(String identifier) {
val iiWithData = identifier.toInstanceIdentifier
var CompositeNode data = null;
return new StructuredData(data, iiWithData.schemaNode, iiWithData.mountPoint)
}
- override updateConfigurationDataLegacy(String identifier, CompositeNode payload) {
- updateConfigurationData(identifier, payload);
- }
-
override updateConfigurationData(String identifier, CompositeNode payload) {
val iiWithData = identifier.toInstanceIdentifier
val value = normalizeNode(payload, iiWithData.schemaNode, iiWithData.mountPoint)
}
}
- override createConfigurationDataLegacy(String identifier, CompositeNode payload) {
- createConfigurationData(identifier, payload);
- }
-
override createConfigurationData(String identifier, CompositeNode payload) {
if (payload.namespace === null) {
throw new ResponseException(BAD_REQUEST,
* Test of json output when as input are specified composite node with empty
* data + YANG file
*/
+
@Test
public void compositeNodeAndYangWithJsonReaderEmptyDataTest() {
CompositeNode compositeNode = prepareCompositeNodeWithEmpties();
TestUtils.buildQName("cont1", "simple:yang:types", "2013-11-5"), null, null, ModifyAction.CREATE, null);
// lst11_1
- MutableCompositeNode lst11_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11"), cont1,
+ MutableCompositeNode lst11_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
null, ModifyAction.CREATE, null);
cont1.getChildren().add(lst11_1);
- MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111"), lst11_1,
+ MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_1,
(short) 1, ModifyAction.CREATE, null);
lst11_1.getChildren().add(lf111_1);
// lst111_1_1
- MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111"),
+ MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
lst11_1, null, ModifyAction.CREATE, null);
lst11_1.getChildren().add(lst111_1_1);
- MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111"),
+ MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111","simple:yang:types","2013-11-5"),
lst111_1_1, (int) 34, ModifyAction.CREATE, null);
lst111_1_1.getChildren().add(lf1111_1_1);
lst111_1_1.init();
// :lst111_1_1
// lst111_1_2
- MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111"),
+ MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
lst11_1, null, ModifyAction.CREATE, null);
lst11_1.getChildren().add(lst111_1_2);
- MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111"),
+ MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111","simple:yang:types","2013-11-5"),
lst111_1_2, (int) 35, ModifyAction.CREATE, null);
lst111_1_2.getChildren().add(lf1111_1_2);
lst111_1_2.init();
// :lst111_1_2
// lst111_1_3
- MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111"),
+ MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
lst11_1, null, ModifyAction.CREATE, null);
lst11_1.getChildren().add(lst111_1_3);
lst111_1_2.init();
// :lst111_1_3
// lst111_1_4
- MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111"),
+ MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
lst11_1, null, ModifyAction.CREATE, null);
lst11_1.getChildren().add(lst111_1_4);
lst111_1_2.init();
// :lst111_1_4
- MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111"),
+ MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
lst11_1, null, ModifyAction.CREATE, null);
lst11_1.getChildren().add(cont111_1);
// :lst11_1
// lst11_2
- MutableCompositeNode lst11_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11"), cont1,
+ MutableCompositeNode lst11_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
null, ModifyAction.CREATE, null);
cont1.getChildren().add(lst11_2);
- MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111"), lst11_2,
+ MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_2,
(short) 2, ModifyAction.CREATE, null);
lst11_2.getChildren().add(lf111_2);
// cont111_2
- MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111"),
+ MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
lst11_2, null, ModifyAction.CREATE, null);
lst11_2.getChildren().add(cont111_2);
- MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111"),
+ MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111","simple:yang:types","2013-11-5"),
cont111_2, (int) 1024, ModifyAction.CREATE, null);
cont111_2.getChildren().add(lflst1111_2_2);
- MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111"),
+ MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111","simple:yang:types","2013-11-5"),
cont111_2, (int) 4096, ModifyAction.CREATE, null);
cont111_2.getChildren().add(lflst1111_2_3);
// lst1111_2
- MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111"),
+ MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
cont111_2, null, ModifyAction.CREATE, null);
cont111_2.getChildren().add(lst1111_2_1);
- MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111B"),
+ MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111B","simple:yang:types","2013-11-5"),
lst1111_2_1, (short) 4, ModifyAction.CREATE, null);
lst1111_2_1.getChildren().add(lf1111B_2_1);
lst1111_2_1.init();
- MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111"),
+ MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
cont111_2, null, ModifyAction.CREATE, null);
cont111_2.getChildren().add(lst1111_2_2);
- MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111A"),
+ MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111A","simple:yang:types","2013-11-5"),
lst1111_2_2, "lf1111A str12", ModifyAction.CREATE, null);
lst1111_2_2.getChildren().add(lf1111A_2_2);
lst1111_2_2.init();
cont111_2.init();
// :cont111_2
- MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst112"), lst11_2,
+ MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst112","simple:yang:types","2013-11-5"), lst11_2,
null, ModifyAction.CREATE, null);
lst11_2.getChildren().add(lst112_2);
lst112_2.init();
// :lst11_2
// lst11_3
- MutableCompositeNode lst11_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11"), cont1,
+ MutableCompositeNode lst11_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
null, ModifyAction.CREATE, null);
cont1.getChildren().add(lst11_3);
- MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111"), lst11_3,
+ MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_3,
(short) 3, ModifyAction.CREATE, null);
lst11_3.getChildren().add(lf111_3);
// cont111_3
- MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111"),
+ MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
lst11_3, null, ModifyAction.CREATE, null);
lst11_3.getChildren().add(cont111_3);
- MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111"),
+ MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
cont111_3, null, ModifyAction.CREATE, null);
cont111_3.getChildren().add(lst1111_3_1);
lst1111_3_1.init();
- MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111"),
+ MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
cont111_3, null, ModifyAction.CREATE, null);
cont111_3.getChildren().add(lst1111_3_2);
lst1111_3_2.init();
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.*;
+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.impl.NodeFactory;
public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
}
private CompositeNode prepareCompositeNode(Object value) {
- MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont"), null, null,
+ MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont","identityref:module","2013-12-2"), null, null,
ModifyAction.CREATE, null);
- MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont1"), cont, null,
+ MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont1","identityref:module","2013-12-2"), cont, null,
ModifyAction.CREATE, null);
cont.getChildren().add(cont1);
- MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1"), cont1, value,
+ MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1","identityref:module","2013-12-2"), cont1, value,
ModifyAction.CREATE, null);
cont1.getChildren().add(lf1);
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.*;
-import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyType;
+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.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
dataLoad("/cnsn-to-json/simple-data-types");
}
- // FIXME
- @Ignore
@Test
- public void incorrectTopLevelElementTest() {
-
+ public void incorrectTopLevelElementTest() throws WebApplicationException, IOException {
String jsonOutput = null;
- try {
- jsonOutput = TestUtils
- .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
- (Set<Module>) Collections.EMPTY_SET, prepareDataSchemaNode(),
- StructuredDataToJsonProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- LOG.error("WebApplicationException or IOException was raised");
- }
+ jsonOutput = TestUtils
+ .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
+ (Set<Module>) Collections.EMPTY_SET, prepareDataSchemaNode(),
+ StructuredDataToJsonProvider.INSTANCE);
assertNotNull(jsonOutput);
assertTrue(jsonOutput.contains("\"lf1\": \"\""));
}
import static org.junit.Assert.assertTrue;
import java.io.IOException;
-import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
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.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class CnSnToJsonWithDataFromSeveralModulesTest extends YangAndXmlAndDataSchemaLoader {
@BeforeClass
public static void initialize() {
- dataLoad("/xml-to-cnsn/data-of-several-modules/yang",2,"module1","cont_m1");
+ dataLoad("/xml-to-cnsn/data-of-several-modules/yang", 2, "module1", "cont_m1");
}
@Test
String output = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCnSn(), modules, schemaContext,
StructuredDataToJsonProvider.INSTANCE);
-// String output =
-// String.format("\"data\" : {\n" +
-// "\t\"cont_m1\" : {\n" +
-// "\t\t\"lf1_m1\" : \"lf1 m1 value\"\n" +
-// "\t}\n" +
-// "\t\"cont_m2\" : {\n" +
-// "\t\t\"lf1_m2\" : \"lf1 m2 value\"\n" +
-// "\t}\n" +
-// "}");
+ // String output =
+ // String.format("\"data\" : {\n" +
+ // "\t\"cont_m1\" : {\n" +
+ // "\t\t\"lf1_m1\" : \"lf1 m1 value\"\n" +
+ // "\t}\n" +
+ // "\t\"cont_m2\" : {\n" +
+ // "\t\t\"lf1_m2\" : \"lf1 m2 value\"\n" +
+ // "\t}\n" +
+ // "}");
StringBuilder regex = new StringBuilder();
regex.append("^");
regex.append(".*\"data\"");
regex.append(".*:");
regex.append(".*\\{");
-
- regex.append(".*\"contB_m1\"");
+
+ regex.append(".*\"cont_m1\"");
regex.append(".*:");
regex.append(".*\\{");
regex.append(".*\\}");
-
- regex.append(".*\"cont_m1\"");
+
+ regex.append(".*\"contB_m1\"");
regex.append(".*:");
regex.append(".*\\{");
regex.append(".*\\}");
- regex.append(".*\"contB_m2\"");
+ regex.append(".*\"cont_m2\"");
regex.append(".*:");
regex.append(".*\\{");
regex.append(".*\\}");
-
- regex.append(".*\"cont_m2\"");
+
+ regex.append(".*\"contB_m2\"");
regex.append(".*:");
regex.append(".*\\{");
regex.append(".*\\}");
-
+
regex.append(".*\\}");
regex.append(".*");
}
private CompositeNode prepareCnSn() throws URISyntaxException {
- CompositeNodeWrapper data = new CompositeNodeWrapper(new URI("urn:ietf:params:xml:ns:netconf:base:1.0"), "data");
-
- URI uriModule1 = new URI("module:one");
- CompositeNodeWrapper cont_m1 = new CompositeNodeWrapper(uriModule1, "cont_m1");
- SimpleNodeWrapper lf1_m1 = new SimpleNodeWrapper(uriModule1, "lf1_m1", "lf1 m1 value");
- cont_m1.addValue(lf1_m1);
- CompositeNodeWrapper contB_m1 = new CompositeNodeWrapper(uriModule1, "contB_m1");
-
- data.addValue(contB_m1);
- data.addValue(cont_m1);
-
- URI uriModule2 = new URI("module:two");
- CompositeNodeWrapper cont_m2 = new CompositeNodeWrapper(uriModule2, "cont_m2");
- SimpleNodeWrapper lf1_m2 = new SimpleNodeWrapper(uriModule2, "lf1_m2", "lf1 m2 value");
- cont_m2.addValue(lf1_m2);
- CompositeNodeWrapper contB_m2 = new CompositeNodeWrapper(uriModule2, "contB_m2");
- data.addValue(contB_m2);
- data.addValue(cont_m2);
+ String uri1 = "module:one";
+ String rev1 = "2014-01-17";
+
+ MutableCompositeNode data = NodeFactory.createMutableCompositeNode(
+ TestUtils.buildQName("data", "urn:ietf:params:xml:ns:netconf:base:1.0", "2000-01-01"), null, null,
+ null, null);
+
+ MutableCompositeNode cont_m1 = NodeFactory.createMutableCompositeNode(
+ TestUtils.buildQName("cont_m1", uri1, rev1), data, null, null, null);
+ data.getChildren().add(cont_m1);
+
+ MutableSimpleNode<?> lf1_m1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1_m1", uri1, rev1),
+ cont_m1, "lf1 m1 value", null, null);
+ cont_m1.getChildren().add(lf1_m1);
+ cont_m1.init();
+
+ MutableCompositeNode contB_m1 = NodeFactory.createMutableCompositeNode(
+ TestUtils.buildQName("contB_m1", uri1, rev1), data, null, null, null);
+ data.getChildren().add(contB_m1);
+ contB_m1.init();
+
+ String uri2 = "module:two";
+ String rev2 = "2014-01-17";
+ MutableCompositeNode cont_m2 = NodeFactory.createMutableCompositeNode(
+ TestUtils.buildQName("cont_m2", uri2, rev2), data, null, null, null);
+ data.getChildren().add(cont_m2);
+
+ MutableSimpleNode<?> lf1_m2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1_m2", uri2, rev2),
+ cont_m1, "lf1 m2 value", null, null);
+ cont_m2.getChildren().add(lf1_m2);
+ cont_m2.init();
+
+ MutableCompositeNode contB_m2 = NodeFactory.createMutableCompositeNode(
+ TestUtils.buildQName("contB_m2", uri2, rev2), data, null, null, null);
+ data.getChildren().add(contB_m2);
+ contB_m2.init();
+
+ data.init();
return data;
}
@BeforeClass
public static void initialization() throws URISyntaxException {
- dataLoad("/instanceidentifier/yang", 3, "instance-identifier-module", "cont");
+ dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
}
@Test
import javax.xml.stream.events.XMLEvent;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-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.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSchemaLoader {
@BeforeClass
public static void initialize() {
- dataLoad("/instanceidentifier/yang", 3, "instance-identifier-module", "cont");
+ dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
}
@Test
- public void saveCnSnToXml() throws WebApplicationException, IOException, URISyntaxException, XMLStreamException {
- CompositeNode cnSn = prepareCnSn();
+ public void saveCnSnToXmlTest() throws WebApplicationException, IOException, URISyntaxException, XMLStreamException {
+ CompositeNode cnSn = prepareCnSn(createInstanceIdentifier());
String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
StructuredDataToXmlProvider.INSTANCE);
+ //uncomment for debug
+ // System.out.println(output);
validateXmlOutput(output);
+
+ }
+
+ @Ignore
+ @Test
+ public void saveCnSnWithLeafListInstIdentifierToXmlTest() throws WebApplicationException, IOException,
+ URISyntaxException, XMLStreamException {
+ CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
+ String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
+ StructuredDataToXmlProvider.INSTANCE);
+ //uncomment for debug
// System.out.println(output);
+ validateXmlOutputWithLeafList(output);
+ }
+
+ @Test
+ public void saveCnSnToJsonTest() throws WebApplicationException, IOException, URISyntaxException {
+ CompositeNode cnSn = prepareCnSn(createInstanceIdentifier());
+ String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
+ StructuredDataToJsonProvider.INSTANCE);
+ boolean strInOutput = false;
+ strInOutput = output
+ .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11[augment-module:keyvalue111=\\\"value1\\\"][augment-module:keyvalue112=\\\"value2\\\"]/augment-augment-module:lf112\"");
+ if (!strInOutput) {
+ strInOutput = output
+ .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11[augment-module:keyvalue111='value1'][augment-module:keyvalue112='value2']/augment-augment-module:lf112\"");
+ }
+ //uncomment for debug
+ // System.out.println(output);
+ assertTrue(strInOutput);
}
+
@Test
- public void saveCnSnToJson() throws WebApplicationException, IOException, URISyntaxException {
- CompositeNode cnSn = prepareCnSn();
+ public void saveCnSnWithLeafListInstIdentifierToJsonTest() throws WebApplicationException, IOException,
+ URISyntaxException {
+ CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
StructuredDataToJsonProvider.INSTANCE);
- assertTrue(output
- .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11[augment-module:keyvalue111=\\\"value1\\\"][augment-module:keyvalue112=\\\"value2\\\"]/augment-augment-module:lf112\""));
+ //uncomment for debug
// System.out.println(output);
+ boolean strInOutput = false;
+ strInOutput = output
+ .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11[.='lflst11_1']\"");
+ if (!strInOutput) {
+ strInOutput = output
+ .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11[.=\\\"lflst11_1\\\"]\"");
+ }
+
+ assertTrue(strInOutput);
}
private void validateXmlOutput(String xml) throws XMLStreamException {
+ ":lst11[" + aModulePrefix + ":keyvalue111='value1'][" + aModulePrefix + ":keyvalue112='value2']/"
+ aaModulePrefix + ":lf112";
-// System.out.println(xml);
assertTrue(xml.contains(instanceIdentifierValue));
}
- private CompositeNode prepareCnSn() throws URISyntaxException {
- CompositeNodeWrapper cont = new CompositeNodeWrapper(new URI("instance:identifier:module"), "cont");
- CompositeNodeWrapper cont1 = new CompositeNodeWrapper(new URI("instance:identifier:module"), "cont1");
- CompositeNodeWrapper lst11 = new CompositeNodeWrapper(new URI("augment:module"), "lst11");
- InstanceIdentifier instanceIdentifier = createInstanceIdentifier();
- SimpleNodeWrapper lf111 = new SimpleNodeWrapper(new URI("augment:augment:module"), "lf111", instanceIdentifier);
+ private void validateXmlOutputWithLeafList(String xml) throws XMLStreamException {
+ XMLInputFactory xmlInFactory = XMLInputFactory.newInstance();
+ XMLEventReader eventReader;
- lst11.addValue(lf111);
- cont1.addValue(lst11);
- cont.addValue(cont1);
+ eventReader = xmlInFactory.createXMLEventReader(new ByteArrayInputStream(xml.getBytes()));
+ String aModuleLfLstPrefix = null;
+ String iiModulePrefix = null;
+ while (eventReader.hasNext()) {
+ XMLEvent nextEvent = eventReader.nextEvent();
+ if (nextEvent.isStartElement()) {
+ StartElement startElement = (StartElement) nextEvent;
+ if (startElement.getName().getLocalPart().equals("lf111")) {
+ Iterator prefixes = startElement.getNamespaceContext().getPrefixes("augment:module:leaf:list");
+
+ while (prefixes.hasNext() && aModuleLfLstPrefix == null) {
+ String prefix = (String) prefixes.next();
+ if (!prefix.isEmpty()) {
+ aModuleLfLstPrefix = prefix;
+ }
+ }
+ iiModulePrefix = startElement.getNamespaceContext().getPrefix("instance:identifier:module");
+ break;
+ }
+ }
+ }
+
+ assertNotNull(aModuleLfLstPrefix);
+ assertNotNull(iiModulePrefix);
+
+ String instanceIdentifierValue = "/" + iiModulePrefix + ":cont/" + iiModulePrefix + ":cont1/"
+ + aModuleLfLstPrefix + ":lflst11[.='lflst11_1']";
+
+ assertTrue(xml.contains(instanceIdentifierValue));
+
+ }
+
+ private CompositeNode prepareCnSn(InstanceIdentifier instanceIdentifier) throws URISyntaxException {
+ MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
+ TestUtils.buildQName("cont", "instance:identifier:module", "2014-01-17"), null, null,null,null);
+ MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(
+ TestUtils.buildQName("cont1", "instance:identifier:module", "2014-01-17"), cont, null,null,null);
+ MutableCompositeNode lst11 = NodeFactory.createMutableCompositeNode(
+ TestUtils.buildQName("lst11", "augment:module", "2014-01-17"), cont1, null,null,null);
+
+ MutableSimpleNode<?> lf111 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111", "augment:augment:module", "2014-01-17"),
+ lst11, instanceIdentifier,null,null);
+
+
+ lst11.getChildren().add(lf111);
+ lst11.init();
+
+ cont1.getChildren().add(lst11);
+ cont1.init();
+
+ cont.getChildren().add(cont1);
+ cont.init();
return cont;
}
return new InstanceIdentifier(pathArguments);
}
+ private InstanceIdentifier createInstanceIdentifierWithLeafList() throws URISyntaxException {
+ List<PathArgument> pathArguments = new ArrayList<>();
+ pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont")));
+ pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1")));
+ pathArguments.add(new NodeWithValue(new QName(new URI("augment:module:leaf:list"), "lflst11"), "lflst11_1"));
+
+ return new InstanceIdentifier(pathArguments);
+ }
+
}
String uriPath = "ietf-interfaces:interfaces";
String uri = createUri(uriPrefix, uriPath);
when(restconfService.invokeRpc(eq(uriPath), any(CompositeNode.class))).thenReturn(null);
- post(uri, Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+JSON, jsonData);
+ post(uri, Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+JSON, jsonData);
verify(restconfService, times(1)).invokeRpc(eq(uriPath), any(CompositeNode.class));
- post(uri, Draft02.MediaTypes.DATA+XML, Draft02.MediaTypes.DATA+XML, xmlData);
+ post(uri, Draft02.MediaTypes.OPERATION+XML, Draft02.MediaTypes.OPERATION+XML, xmlData);
verify(restconfService, times(2)).invokeRpc(eq(uriPath), any(CompositeNode.class));
post(uri, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, jsonData);
verify(restconfService, times(3)).invokeRpc(eq(uriPath), any(CompositeNode.class));
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.createUri;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
-import java.util.logging.Level;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
-import org.glassfish.jersey.test.TestProperties;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.core.api.mount.MountInstance;
import org.opendaylight.controller.sal.core.api.mount.MountService;
-import org.opendaylight.controller.sal.rest.api.Draft02;
import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
return resourceConfig;
}
- /**
- * Tests of status codes for "/datastore/{identifier}".
- */
- @Test
- public void getDatastoreStatusCodes() throws FileNotFoundException, UnsupportedEncodingException {
- mockReadOperationalDataMethod();
- String uri = createUri("/datastore/", "ietf-interfaces:interfaces/interface/eth0");
- assertEquals(200, get(uri, MediaType.APPLICATION_XML));
-
- uri = createUri("/datastore/", "wrong-module:interfaces/interface/eth0");
- assertEquals(400, get(uri, MediaType.APPLICATION_XML));
-
- // Test of request for not existing data. Returning status code 404
- uri = createUri("/datastore/", "ietf-interfaces:interfaces/interface/eth0");
- when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(null);
- assertEquals(404, get(uri, MediaType.APPLICATION_XML));
- }
-
/**
* Tests of status codes for "/operational/{identifier}".
*/
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
-import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.createUri;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlMapper;
import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
}
- @Test
- public void postDatastoreStatusCodes() throws UnsupportedEncodingException {
- controllerContext.setSchemas(schemaContextYangsIetf);
- mockCommitConfigurationDataPostMethod(TransactionStatus.COMMITED);
- String uri = createUri("/datastore/", "ietf-interfaces:interfaces");
- assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
-
- mockCommitConfigurationDataPostMethod(null);
- assertEquals(202, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
-
- mockCommitConfigurationDataPostMethod(TransactionStatus.FAILED);
- assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
- }
-
@Test
public void postDataViaUrlMountPoint() throws UnsupportedEncodingException {
controllerContext.setSchemas(schemaContextYangsIetf);
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.createUri;
import java.io.FileNotFoundException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.BeforeClass;
-import org.junit.Ignore;
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.sal.rest.api.Draft02;
import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
assertEquals(500, put(uri, MediaType.APPLICATION_XML, xmlData));
}
- /**
- * Tests of status codes for "/datastore/{identifier}".
- */
- @Test
- public void putDatastoreStatusCodes() throws UnsupportedEncodingException {
- String uri = createUri("/datastore/", "ietf-interfaces:interfaces/interface/eth0");
- mockCommitConfigurationDataPutMethod(TransactionStatus.COMMITED);
- assertEquals(200, put(uri, MediaType.APPLICATION_XML, xmlData));
-
- mockCommitConfigurationDataPutMethod(TransactionStatus.FAILED);
- assertEquals(500, put(uri, MediaType.APPLICATION_XML, xmlData));
- }
-
@Test
public void testRpcResultCommitedToStatusCodesWithMountPoint() throws UnsupportedEncodingException,
FileNotFoundException, URISyntaxException {
brokerFacade.commitConfigurationDataPutBehindMountPoint(any(MountInstance.class),
any(InstanceIdentifier.class), any(CompositeNode.class))).thenReturn(dummyFuture);
- InputStream xmlStream = RestconfImplTest.class.getResourceAsStream("/full-versions/test-data2/data2.xml");
- String xml = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
- Entity<String> entity = Entity.entity(xml, Draft02.MediaTypes.DATA + XML);
-
MountInstance mountInstance = mock(MountInstance.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
MountService mockMountService = mock(MountService.class);
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.SimpleNode;
@BeforeClass
public static void initialize() {
- dataLoad("/instanceidentifier/yang", 3, "instance-identifier-module", "cont");
+ dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
}
@Test
CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata.xml",
XmlToCompositeNodeProvider.INSTANCE);
TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
- verify(cnSn);
+ verifyListPredicate(cnSn);
+ }
+
+ @Test
+ public void loadXmlLeafListToCnSn() throws WebApplicationException, IOException, URISyntaxException {
+ CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata_leaf_list.xml",
+ XmlToCompositeNodeProvider.INSTANCE);
+ TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
+ verifyLeafListPredicate(cnSn);
}
@Test
CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata.json",
JsonToCompositeNodeProvider.INSTANCE);
TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
- verify(cnSn);
+ verifyListPredicate(cnSn);
}
- private void verify(CompositeNode cnSn) throws URISyntaxException {
- SimpleNode<?> lf111 = getSnWithInstanceIdentifier(cnSn);
+ @Test
+ public void loadJsonLeafListToCnSn() throws WebApplicationException, IOException, URISyntaxException {
+ CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata_leaf_list.json",
+ JsonToCompositeNodeProvider.INSTANCE);
+ TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
+ verifyLeafListPredicate(cnSn);
+ }
+
+ private void verifyLeafListPredicate(CompositeNode cnSn) throws URISyntaxException {
+ SimpleNode<?> lf11 = getSnWithInstanceIdentifierWhenLeafList(cnSn);
+ Object value = lf11.getValue();
+ assertTrue(value instanceof InstanceIdentifier);
+
+ InstanceIdentifier instanceIdentifier = (InstanceIdentifier) value;
+ List<PathArgument> pathArguments = instanceIdentifier.getPath();
+ assertEquals(3, pathArguments.size());
+ String revisionDate = "2014-01-17";
+ assertEquals(TestUtils.buildQName("cont", "instance:identifier:module", revisionDate), pathArguments.get(0)
+ .getNodeType());
+ assertEquals(TestUtils.buildQName("cont1", "instance:identifier:module", revisionDate), pathArguments.get(1)
+ .getNodeType());
+ assertEquals(TestUtils.buildQName("lflst11", "augment:module:leaf:list", "2014-01-27"), pathArguments.get(2)
+ .getNodeType());
+
+ assertTrue(pathArguments.get(2) instanceof NodeWithValue);
+ assertEquals("lflst11_1", ((NodeWithValue) pathArguments.get(2)).getValue());
+
+ }
+
+ private void verifyListPredicate(CompositeNode cnSn) throws URISyntaxException {
+ SimpleNode<?> lf111 = getSnWithInstanceIdentifierWhenList(cnSn);
Object value = lf111.getValue();
assertTrue(value instanceof InstanceIdentifier);
assertEquals("value2", predicates.get(TestUtils.buildQName("keyvalue112", "augment:module", revisionDate)));
}
- private SimpleNode<?> getSnWithInstanceIdentifier(CompositeNode cnSn) throws URISyntaxException {
+ private SimpleNode<?> getSnWithInstanceIdentifierWhenList(CompositeNode cnSn) throws URISyntaxException {
CompositeNode cont1 = cnSn.getFirstCompositeByName(TestUtils.buildQName("cont1", "instance:identifier:module",
"2014-01-17"));
assertNotNull(cont1);
return lf111;
}
+ private SimpleNode<?> getSnWithInstanceIdentifierWhenLeafList(CompositeNode cnSn) throws URISyntaxException {
+ CompositeNode cont1 = cnSn.getFirstCompositeByName(TestUtils.buildQName("cont1", "instance:identifier:module",
+ "2014-01-17"));
+ assertNotNull(cont1);
+ SimpleNode<?> lf11 = cont1.getFirstSimpleByName(TestUtils.buildQName("lf11", "augment:module:leaf:list",
+ "2014-01-27"));
+ assertNotNull(lf11);
+ return lf11;
+ }
+
}
--- /dev/null
+{
+ "instance-identifier-module:cont": {
+ "cont1": {
+ "augment-module-leaf-list:lf11" : "/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11[.=\"lflst11_1\"]"
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+<cont xmlns="instance:identifier:module">
+ <cont1>
+ <lflst11 xmlns="augment:module:leaf:list">lflst11_1</lflst11>
+ <lflst11 xmlns="augment:module:leaf:list">lflst11_2</lflst11>
+ <lflst11 xmlns="augment:module:leaf:list">lflst11_3</lflst11>
+ <lf11 xmlns:a="instance:identifier:module" xmlns:b="augment:module:leaf:list" xmlns="augment:module:leaf:list">/a:cont/a:cont1/b:lflst11[.="lflst11_1"]</lf11>
+ </cont1>
+</cont>
--- /dev/null
+module augment-module-leaf-list {
+ namespace "augment:module:leaf:list";
+
+ prefix "amodulelflst";
+
+ import instance-identifier-module {prefix imodule; revision-date 2014-01-17;}
+
+ revision 2014-01-27 {
+ }
+
+ augment "/imodule:cont/imodule:cont1" {
+ leaf-list lflst11 {
+ type string;
+ }
+ leaf lf11 {
+ type instance-identifier;
+ }
+ }
+
+}
\ No newline at end of file
cache.put(notification.getId(), new NodeStatisticsAger(statisticsManager,key));
}
NodeStatisticsAger nsa = cache.get(notification.getId());
- FlowEntry flowStatsEntry = nsa.new FlowEntry(tableId,flowRule);
- cache.get(notification.getId()).updateFlowStats(flowStatsEntry);
//Augment the data to the flow node
flowBuilder.addAugmentation(FlowStatisticsData.class, flowStatisticsData.build());
sucLogger.debug("Found matching flow in the datastore, augmenting statistics");
foundOriginalFlow = true;
+ // Update entry with timestamp of latest response
+ flow.setKey(existingFlow.getKey());
+ FlowEntry flowStatsEntry = nsa.new FlowEntry(tableId,flow.build());
+ cache.get(notification.getId()).updateFlowStats(flowStatsEntry);
+
it.putOperationalData(flowRef, flowBuilder.build());
it.commit();
}
flowBuilder.addAugmentation(FlowStatisticsData.class, flowStatisticsData.build());
sucLogger.debug("Found matching unaccounted flow in the operational datastore, augmenting statistics");
foundOriginalFlow = true;
+
+ // Update entry with timestamp of latest response
+ flow.setKey(existingFlow.getKey());
+ FlowEntry flowStatsEntry = nsa.new FlowEntry(tableId,flow.build());
+ cache.get(notification.getId()).updateFlowStats(flowStatsEntry);
+
it.putOperationalData(flowRef, flowBuilder.build());
it.commit();
break;
}
}
if(!foundOriginalFlow){
- long flowKey = Long.parseLong(new String("1"+Short.toString(tableId)+"0"+Integer.toString(this.unaccountedFlowsCounter)));
+ String flowKey = "#UF$TABLE*"+Short.toString(tableId)+"*"+Integer.toString(this.unaccountedFlowsCounter);
this.unaccountedFlowsCounter++;
- FlowKey newFlowKey = new FlowKey(new FlowId(Long.toString(flowKey)));
+ FlowKey newFlowKey = new FlowKey(new FlowId(flowKey));
InstanceIdentifier<Flow> flowRef = InstanceIdentifier.builder(Nodes.class).child(Node.class, key)
.augmentation(FlowCapableNode.class)
.child(Table.class, new TableKey(tableId))
flowBuilder.setKey(newFlowKey);
flowBuilder.addAugmentation(FlowStatisticsData.class, flowStatisticsData.build());
sucLogger.debug("Flow {} is not present in config data store, augmenting statistics as an unaccounted flow",flowBuilder.build());
+
+ // Update entry with timestamp of latest response
+ flow.setKey(newFlowKey);
+ FlowEntry flowStatsEntry = nsa.new FlowEntry(tableId,flow.build());
+ cache.get(notification.getId()).updateFlowStats(flowStatsEntry);
+
it.putOperationalData(flowRef, flowBuilder.build());
it.commit();
}
try {
NetconfOperationServiceImpl.checkConsistencyBetweenYangStoreAndConfig(mockJmxClient("qname1"),
mockYangStoreSnapshot("qname2", "qname1"));
- fail("An exception of type " + IllegalArgumentException.class + " was expected");
+ fail("An exception of type " + IllegalStateException.class + " was expected");
} catch (IllegalStateException e) {
String message = e.getMessage();
Assert.assertThat(
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <version>${yangtools.version}</version>
- <executions>
- <execution>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <yangFilesRootDir>src/main/yang</yangFilesRootDir>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>
- org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl
- </codeGeneratorClass>
- <outputBaseDir>
- ${project.build.directory}/generated-sources/monitoring
- </outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>${yangtools.version}</version>
- </dependency>
- </dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
- <version>1.7</version>
- <executions>
- <execution>
- <phase>generate-sources</phase>
- <goals>
- <goal>add-source</goal>
- </goals>
- <configuration>
- <sources>
- <source>${project.build.directory}/generated-sources/monitoring</source>
- </sources>
- </configuration>
- </execution>
- </executions>
</plugin>
<plugin>
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <version>${yangtools.version}</version>
- <executions>
- <execution>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <yangFilesRootDir>src/main/yang</yangFilesRootDir>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>
- org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl
- </codeGeneratorClass>
- <outputBaseDir>
- ${project.build.directory}/generated-sources/monitoring
- </outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>${yangtools.version}</version>
- </dependency>
- </dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
- <version>1.7</version>
- <executions>
- <execution>
- <phase>generate-sources</phase>
- <goals>
- <goal>add-source</goal>
- </goals>
- <configuration>
- <sources>
- <source>${project.build.directory}/generated-sources/monitoring</source>
- </sources>
- </configuration>
- </execution>
- </executions>
</plugin>
<plugin>
<netconf.netty.version>4.0.10.Final</netconf.netty.version>
<netconf.version>0.2.4-SNAPSHOT</netconf.version>
<config.version>0.2.4-SNAPSHOT</config.version>
+ <salGeneratorPath>${project.build.directory}/generated-sources/sal</salGeneratorPath>
</properties>
<dependencies>
</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-maven-plugin</artifactId>
+ <version>${yangtools.version}</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>generate-sources</goal>
+ </goals>
+ <configuration>
+ <yangFilesRootDir>src/main/yang</yangFilesRootDir>
+ <codeGenerators>
+ <generator>
+ <codeGeneratorClass>
+ org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl
+ </codeGeneratorClass>
+ <outputBaseDir>
+ ${salGeneratorPath}
+ </outputBaseDir>
+ </generator>
+ <generator>
+ <codeGeneratorClass>org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl</codeGeneratorClass>
+ <outputBaseDir>${project.build.directory}/site/models</outputBaseDir>
+ </generator>
+ </codeGenerators>
+ <inspectDependencies>true</inspectDependencies>
+ </configuration>
+ </execution>
+ </executions>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>maven-sal-api-gen-plugin</artifactId>
+ <version>${yangtools.version}</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>1.7</version>
+ <executions>
+ <execution>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>add-source</goal>
+ </goals>
+ <configuration>
+ <sources>
+ <source>${salGeneratorPath}</source>
+ </sources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</pluginManagement>
this.myAppData = ByteBuffer
.allocate(session.getApplicationBufferSize());
this.peerAppData = ByteBuffer.allocate(session
- .getApplicationBufferSize());
+ .getApplicationBufferSize() * 2);
this.myNetData = ByteBuffer.allocate(session.getPacketBufferSize());
- this.peerNetData = ByteBuffer.allocate(session.getPacketBufferSize());
+ this.peerNetData = ByteBuffer.allocate(session.getPacketBufferSize() * 2);
}
@Override
salMatch.setField(new MatchField(MatchType.DL_VLAN,
vlan));
}
- if (ofMatch.getDataLayerVirtualLanPriorityCodePoint() != 0) {
+ if ((ofMatch.getWildcards() & OFMatch.OFPFW_DL_VLAN_PCP) == 0) {
salMatch.setField(MatchType.DL_VLAN_PR, ofMatch
.getDataLayerVirtualLanPriorityCodePoint());
}
salMatch.setField(new MatchField(MatchType.DL_VLAN,
vlan));
}
- if (v6Match.getDataLayerVirtualLanPriorityCodePoint() != 0) {
+ if ((v6Match.getWildcards() & OFMatch.OFPFW_DL_VLAN_PCP) == 0) {
salMatch.setField(MatchType.DL_VLAN_PR, v6Match
.getDataLayerVirtualLanPriorityCodePoint());
}
this.dlVlanIDState = MatchFieldState.MATCH_ABSENT;
}
- if (match.getDataLayerVirtualLanPriorityCodePoint() != 0) {
+ if ((match.getWildcards() & OFMatch.OFPFW_DL_VLAN_PCP) == 0) {
this.setDataLayerVirtualLanPriorityCodePoint(
match.getDataLayerVirtualLanPriorityCodePoint(), (byte) 0);
} else {
// extract the vlan id
super.setDataLayerVirtualLan(getVlanID(firstByte,
secondByte));
- } else {
this.wildcards ^= (1 << 1); // Sync with 0F 1.0 Match
}
if ((this.dataLayerVirtualLanTCIMask & 0xe000) != 0) {
// else if its a vlan pcp mask
// extract the vlan pcp
super.setDataLayerVirtualLanPriorityCodePoint(getVlanPCP(firstByte));
- } else {
this.wildcards ^= (1 << 20);
}
this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_WITH_MASK;
super.setDataLayerVirtualLan(getVlanID(firstByte, secondByte));
this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_ONLY;
this.match_len += 6;
+ this.wildcards ^= (1 << 1); // Sync with 0F 1.0 Match
+ this.wildcards ^= (1 << 20);
}
}
}
// ipv4 dest processing
this.wildcards ^= (((1 << 5) - 1) << 14);
}
- } else {
- this.wildcards = 0;
}
}
import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6Match;
-import org.openflow.protocol.OFMatch;
-import org.openflow.protocol.action.OFAction;
-
import org.opendaylight.controller.sal.action.Action;
import org.opendaylight.controller.sal.action.Flood;
import org.opendaylight.controller.sal.action.FloodAll;
import org.opendaylight.controller.sal.utils.IPProtocols;
import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
import org.opendaylight.controller.sal.utils.NodeCreator;
+import org.openflow.protocol.OFMatch;
+import org.openflow.protocol.action.OFAction;
+import org.openflow.util.U32;
public class FlowProgrammerServiceTest {
*/
FlowConverter salToOF = new FlowConverter(aFlow);
V6Match v6Match = (V6Match) salToOF.getOFMatch();
+ // need this hardcoding here to make the test pass.
+ // this should not be a problem in actual code.
+ // in the test the sal match is converted to a V6 match.
+ // we lose the wildcard info as the V6 match is used for nicira extensions
+ // and nicira deals with wildcards in a different way.
+ // converting the V6 match back to sal match is not going to preserve the wildcard info.
+ // and we need the wildcard info for reading the vlan pcp now.
+ // when creating a V6Match using the readFrom method
+ // we do convert the nicira extensions format correctly to populate the wildcard info.
+ v6Match.setWildcards(U32.t(Long.valueOf(~OFMatch.OFPFW_DL_VLAN_PCP)));
List<OFAction> ofActions = salToOF.getOFActions();
/*
import org.junit.Assert;
import org.junit.Test;
import org.openflow.protocol.OFMatch;
+import org.openflow.util.U32;
public class V6ExtensionTest {
match.fromString("input_port=1");
match.fromString("dl_dst=20:A0:11:10:00:99");
match.fromString("dl_src=00:10:08:22:12:75");
-
match.fromString("ip_src=10.1.1.1");
match.fromString("ip_dst=1.2.3.4");
match.fromString("eth_type=0x800");
match.fromString("dl_vlan=10");
- match.fromString("dl_vpcp=1");
match.fromString("nw_proto=6");
match.fromString("nw_tos=100");
match.fromString("tp_dst=8080");
match.fromString("tp_src=60");
+ match.fromString("dl_vpcp=1");
Assert.assertTrue(match.getInputPort() == 1);
// Assert.assertTrue(match.getIPv6MatchLen()==6);
-
ofm.setInputPort((short) 1);
// V6Match is meant for IPv6, but if using OFMatch, it will be set to
// IPv4 values, as OF1.0 doesn't support IPv6.
ofm.setTransportSource((short) 60);
ofm.setTransportDestination((short) 8080);
+ // this v6match ctor now looks at the wildcard field to
+ // determine if vlan pcp has been set
+ // so set the wildcards appropriately to reflect that vlan pcp
+ // has been set.
+ int wildcards = OFMatch.OFPFW_ALL;
+ wildcards &= ~OFMatch.OFPFW_DL_VLAN_PCP;
+ ofm.setWildcards(U32.t(Long.valueOf(wildcards)));
V6Match match3 = new V6Match(ofm);
Assert.assertTrue(match.getInputPort() == match3.getInputPort());
one.lib.helper = {
parseInt : function(value) {
- return (value !== null && value !== '') ?
+ return (value != null && value.trim() !== '') ?
parseInt(value) : ''
},
parseFloat : function(value) {
- return (value !== null && value !== '') ?
+ return (value != null && value.trim() !== '') ?
parseFloat(value) : ''
}
}
public class Troubleshoot implements IDaylightWeb {
private static final UserLevel AUTH_LEVEL = UserLevel.CONTAINERUSER;
private static final List<String> flowStatsColumnNames = Arrays.asList("Node", "In Port",
- "DL Src", "DL Dst", "DL Type", "DL Vlan", "NW Src", "NW Dst",
+ "DL Src", "DL Dst", "DL Type", "DL Vlan","Vlan Priority", "NW Src", "NW Dst","ToS Bits",
"NW Proto", "TP Src", "TP Dst", "Actions", "Bytes", "Packets",
"Time (s)", "Timeout (s)",
"Priority");
private Map<String, String> convertPortsStatistics(
NodeConnectorStatistics ncStats, String containerName) {
+
Map<String, String> row = new HashMap<String, String>();
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
} else {
row.put(MatchType.DL_VLAN.id(), "*");
}
+ //Vlan Priority
+ if (match.isPresent(MatchType.DL_VLAN_PR)) {
+ if (((Byte) flow.getMatch().getField(MatchType.DL_VLAN_PR).getValue())
+ .shortValue() < 0) {
+ row.put(MatchType.DL_VLAN_PR.id(), "0");
+ } else {
+ row.put(MatchType.DL_VLAN_PR.id(), ((Byte) flow.getMatch()
+ .getField(MatchType.DL_VLAN_PR).getValue()).toString());
+ }
+ } else {
+ row.put(MatchType.DL_VLAN_PR.id(), "*");
+ }
+
if (match.isPresent(MatchType.NW_SRC)) {
row.put(MatchType.NW_SRC.id(), ((InetAddress) flow.getMatch()
.getField(MatchType.NW_SRC).getValue()).getHostAddress());
} else {
row.put(MatchType.NW_DST.id(), "*");
}
+ if (match.isPresent(MatchType.NW_TOS)) {
+ row.put(MatchType.NW_TOS.id(), ((Byte) flow.getMatch()
+ .getField(MatchType.NW_TOS).getValue()).toString());
+ } else {
+ row.put(MatchType.NW_TOS.id(), "*");
+ }
if (match.isPresent(MatchType.NW_PROTO)) {
row.put(MatchType.NW_PROTO.id(),
IPProtocols.getProtocolName(((Byte) flow.getMatch()
row.put("durationSeconds",
((Integer) flowOnNode.getDurationSeconds()).toString());
row.put("idleTimeout", ((Short) flow.getIdleTimeout()).toString());
- row.put("priority", String.valueOf(flow.getPriority()));
+ row.put("priority", String.valueOf(NetUtils.getUnsignedShort(flow.getPriority())));
return row;
}
label: 'DL Vlan',
sortable: true
},
+ {
+ property: 'dlVlanPriority',
+ label: 'Vlan PCP',
+ sortable: true
+ },
{
property: 'nwSrc',
label: 'NW Src',
label: 'NW Dst',
sortable: true
},
+ {
+ property: 'nwTOS',
+ label: 'ToS Bits',
+ sortable: true
+ },
{
property: 'nwProto',
label: 'NW Proto',
entry.push(value["dlVlan"]);
entry.push(value["nwSrc"]);
entry.push(value["nwDst"]);
+ entry.push(value["nwTOS"]);
entry.push(value["nwProto"]);
entry.push(value["tpSrc"]);
entry.push(value["tpDst"]);