Merge "Bug 1283: Made return types of AsyncDataChangeEvent consistent"
authorDevin Avery <devin.avery@brocade.com>
Tue, 8 Jul 2014 12:36:06 +0000 (12:36 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Tue, 8 Jul 2014 12:36:06 +0000 (12:36 +0000)
27 files changed:
opendaylight/distribution/opendaylight/src/main/resources/configuration/config.ini
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/NotificationListener.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/NotificationProviderService.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/NotificationService.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/BrokerImplClassLoader.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingIndependentConnector.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/CompositeNodeUtils.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/Constants.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DataModificationTracker.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/package-info.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/DelegateProxy.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RemoteRpcRouter.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RouteChangeListener.java [deleted file]
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/notify/NotificationPublishService.java
opendaylight/md-sal/sal-compability/src/main/java/org/opendaylight/controller/sal/compability/ToSalPropertyClassUtils.java [deleted file]
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/StructuredData.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MediaTypesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java

index f05afbb346f7f157162b313981874c4d3d6bdd40..f4bf4835796aa5536d8cc9b7f4c4bdeda826a373 100644 (file)
@@ -113,8 +113,8 @@ org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
 ovsdb.listenPort=6640
 
 # ovsdb creates Openflow nodes/bridges. This configuration configures the bridge's Openflow version.
-# default Openflow version = 1.0, we also support 1.3.
-ovsdb.of.version=1.3
+# default Openflow version = 1.3, we also support 1.0.
+ovsdb.of.version=1.3
 
 # TLS configuration
 # To enable TLS, set secureChannelEnabled=true and specify the location of controller Java KeyStore and TrustStore files.
index 9429d3f8fa33372dedbbc8b0a00201db695d99a9..be8e0cefc1a3115329ed3391d99bbc8a38810dcd 100644 (file)
@@ -12,20 +12,20 @@ import java.util.EventListener;
 import org.opendaylight.yangtools.yang.binding.Notification;
 
 /**
- * Interface implemented by objects interested in some sort of Notification. This
- * class acts as a base interface for specific listeners which usually are a type
+ * Interface for a generic listener that is interested in receiving YANG modeled notifications.
+ * This interface acts as a base interface for specific listeners which usually are a type
  * capture of this interface.
  *
- * @param <T> Notification type
+ * @param <T> the interested notification type
  */
 public interface NotificationListener<T extends Notification> extends EventListener {
     /**
-     * Invoked to deliver the notification. Note that this method may be invoked
-     * from a shared thread pool, so implementations SHOULD NOT perform CPU-intensive
-     * operations and they definitely MUST NOT invoke any potentially blocking
-     * operations.
+     * Invoked to deliver a notification.
+     * <p>
+     * Note that this method may be invoked from a shared thread pool, so implementations SHOULD NOT
+     * perform CPU-intensive operations and MUST NOT invoke any potentially blocking operations.
      *
-     * @param notification Notification being delivered.
+     * @param notification the notification.
      */
     void onNotification(T notification);
 }
index b94695b83d437e31194e1e862da479b787ba8d80..00db80c19f7fd3fc9399dd303df74f7987eb2ce7 100644 (file)
@@ -14,29 +14,62 @@ import org.opendaylight.controller.md.sal.common.api.notify.NotificationPublishS
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.Notification;
 
+/**
+ * Interface for a notification service that provides publish/subscribe capabilities for YANG
+ * modeled notifications. This interface is a combination of the {@link NotificationService} and
+ * {@link NotificationPublishService} interfaces.
+ */
 public interface NotificationProviderService extends NotificationService, NotificationPublishService<Notification> {
+
     /**
-     * Publishes a notification.
-     *
-     * @param Notification
-     *            notification to publish.
-     *
+     * {@inheritDoc}
      */
     @Override
-    void publish(Notification notification);
+    public void publish(Notification notification);
 
     /**
-     * Publishes a notification, listener calls are done in provided executor.
-     *
+     * {@inheritDoc}
      */
     @Override
-    void publish(Notification notification, ExecutorService service);
+    void publish(Notification notification, ExecutorService executor);
 
+    /**
+     * Registers a listener to be notified about notification subscriptions. This
+     * enables a component to know when there is a notification listener subscribed
+     * for a particular notification type.
+     * <p>
+     * On registration of this listener, the
+     * {@link NotificationInterestListener#onNotificationSubscribtion(Class)} method
+     * will be invoked for every notification type that currently has a notification listener
+     * subscribed.
+     *
+     * @param interestListener the listener that will be notified when subscriptions
+     *                         for new notification types occur.
+     * @return a {@link ListenerRegistration} instance that should be used to unregister the listener
+     *         by invoking the {@link ListenerRegistration#close()} method when no longer needed.
+     */
     ListenerRegistration<NotificationInterestListener> registerInterestListener(
             NotificationInterestListener interestListener);
 
+    /**
+     * Interface for a listener interested in being notified about notification subscriptions.
+     */
     public interface NotificationInterestListener extends EventListener {
 
+        /**
+         * Callback that is invoked when a notification listener subscribes for a
+         * particular notification type.
+         * <p>
+         * This method is only called for the first subscription that occurs for a
+         * particular notification type. Subsequent subscriptions for the same
+         * notification type do not trigger invocation of this method.
+         * <p>
+         * <b>Note:</b>This callback is delivered from thread not owned by this listener,
+         * all processing should be as fast as possible and implementations should
+         * not do any blocking calls or block this thread.
+         *
+         * @param notificationType the notification type for the subscription that occurred.
+         */
         void onNotificationSubscribtion(Class<? extends Notification> notificationType);
     }
 }
index 46e372aea652e29439408da9b6d1ccc963e86acc..335f55bcbbade9ce84898eafee05ff146ef2d382 100644 (file)
@@ -10,24 +10,108 @@ package org.opendaylight.controller.sal.binding.api;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.Notification;
 
+/**
+ * Notification broker which allows clients to subscribe for and publish YANG-modeled notifications.
+ *
+ *<p>
+ * Two styles of listeners are supported:
+ * <ul>
+ * <li>Generic listener</li>
+ * <li>Dispatch listener - listener, which implements <code>{ModelName}Listener</code> interface,
+ * which has dispatch methods for each defined notification. Methods are invoked based on notification type (class).
+ * </li>
+ *
+ * <h3>Generic Listener</h3>
+ * <p>
+ * A generic listener implements the {@link NotificationListener} interface which has one callback method
+ * <code>onNotification</code> that is invoked for any notification type the listener is subscribed to.
+ * <p>
+ * A generic listener is subscribed using the {@link #registerNotificationListener(Class, NotificationListener)}
+ * method by which you specify the type of notification to receive. A generic listener may be registered for
+ * multiple notification types via multiple subscriptions.
+ * <p>
+ * Generic listeners allow for a more flexible approach, allowing you to subscribe for just
+ * one type of notification from a YANG model. You could also have a general subscription
+ * for all notification in the system via
+ * <pre>
+ *   service.registerNotificationListener(Notification.class, listener);
+ * </pre>
+ *
+ * <h3>Dispatch Listener</h3>
+ * <p>
+ * A dispatch listener implements a YANG-generated module interface <code>{ModuleName}Listener</code>
+ * which handles all the notifications defined in the YANG model. Each notification type translates to
+ * a specific method of the form <code>on{NotificationType}</code> on the generated interface.
+ * The generated interface also extends the
+ * {@link org.opendaylight.yangtools.yang.binding.NotificationListener} interface and implementations
+ * are registered using {@link #registerNotificationListener(org.opendaylight.yangtools.yang.binding.NotificationListener)}
+ * method.
+ *
+ * <h5>Dispatch Listener Example</h5>
+ * <p>
+ * Lets assume we have following YANG model:
+ *
+ * <pre>
+ * module example {
+ *      ...
+ *
+ *      notification start {
+ *          ...
+ *      }
+ *
+ *      notification stop {
+ *           ...
+ *      }
+ * }
+ * </pre>
+ *
+ * The generated interface will be:
+ * <pre>
+ *  public interface ExampleListener extends NotificationListener {
+ *      void onStart(Start notification);
+ *      void onStop(Stop notification);
+ *  }
+ * </pre>
+ * The following defines an implementation of the generated interface:
+ * <pre>
+ *  public class MyExampleListener implements ExampleListener {
+ *      public void onStart(Start notification) {
+ *          // do something
+ *      }
+ *
+ *      public void onStop(Stop notification) {
+ *          // do something
+ *      }
+ *  }
+ * </pre>
+ * The implementation is registered as follows:
+ * <pre>
+ *  MyExampleListener listener = new MyExampleListener();
+ *  ListenerRegistration<NotificationListener> reg = service.registerNotificationListener( listener );
+ * </pre>
+ * The <code>onStart</code> method will be invoked when someone publishes a <code>Start</code> notification and
+ * the <code>onStop</code> method will be invoked when someone publishes a <code>Stop</code> notification.
+ */
 public interface NotificationService extends BindingAwareService {
     /**
-     * Register a generic listener for specified notification type only.
+     * Registers a generic listener implementation for a specified notification type.
      *
-     * @param notificationType
-     * @param listener
-     * @return Registration for listener. To unregister listener invoke {@link ListenerRegistration#close()} method.
+     * @param notificationType the YANG-generated interface of the notification type.
+     * @param listener the listener implementation that will receive notifications.
+     * @return a {@link ListenerRegistration} instance that should be used to unregister the listener
+     *         by invoking the {@link ListenerRegistration#close()} method when no longer needed.
      */
     <T extends Notification> ListenerRegistration<NotificationListener<T>> registerNotificationListener(
             Class<T> notificationType, NotificationListener<T> listener);
 
     /**
-     * Register a listener which implements generated notification interfaces derived from
+     * Registers a listener which implements a YANG-generated notification interface derived from
      * {@link org.opendaylight.yangtools.yang.binding.NotificationListener}.
-     * Listener is registered for all notifications present in implemented interfaces.
+     * The listener is registered for all notifications present in the implemented interface.
      *
-     * @param listener
-     * @return Registration for listener. To unregister listener invoke {@link ListenerRegistration#close()} method.
+     * @param listener the listener implementation that will receive notifications.
+     * @return a {@link ListenerRegistration} instance that should be used to unregister the listener
+     *         by invoking the {@link ListenerRegistration#close()} method when no longer needed.
      */
     ListenerRegistration<org.opendaylight.yangtools.yang.binding.NotificationListener> registerNotificationListener(
             org.opendaylight.yangtools.yang.binding.NotificationListener listener);
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/BrokerImplClassLoader.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/BrokerImplClassLoader.java
deleted file mode 100644 (file)
index fdd9350..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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.binding.codegen.impl;
-
-public class BrokerImplClassLoader extends ClassLoader {
-    private final ClassLoader spiClassLoader;
-
-    public BrokerImplClassLoader(final ClassLoader model, final ClassLoader spi) {
-        super(model);
-        this.spiClassLoader = spi;
-    }
-
-    @Override
-    public Class<? extends Object> loadClass(final String name) throws ClassNotFoundException {
-        try {
-            return super.loadClass(name);
-        } catch (ClassNotFoundException e) {
-            return this.spiClassLoader.loadClass(name);
-        }
-    }
-}
index c45cb9011b9b94b0756499555c716723c2e548d2..fe8c4a151c1691495ea4e5f00bf443b77878d930 100644 (file)
@@ -28,7 +28,6 @@ import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
 
-import com.google.common.base.Optional;
 import org.opendaylight.controller.md.sal.binding.impl.AbstractForwardedDataBroker;
 import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
@@ -62,7 +61,10 @@ import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
 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.CompositeObjectRegistration;
+import org.opendaylight.yangtools.concepts.CompositeObjectRegistration.CompositeObjectRegistrationBuilder;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.ObjectRegistration;
 import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
@@ -85,6 +87,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.google.common.base.Function;
+import com.google.common.base.Optional;
 import com.google.common.collect.FluentIterable;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.ImmutableSet.Builder;
@@ -491,7 +494,7 @@ public class BindingIndependentConnector implements //
         public void onRegister(
                 final DataCommitHandlerRegistration<InstanceIdentifier<? extends DataObject>, DataObject> registration) {
 
-            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = mappingService.toDataDom(registration
+            mappingService.toDataDom(registration
                     .getPath());
 
         }
@@ -594,7 +597,7 @@ public class BindingIndependentConnector implements //
         }
 
         @Override
-        public void onRpcImplementationAdded(QName name) {
+        public void onRpcImplementationAdded(final QName name) {
 
             final Optional<Class<? extends RpcService>> rpcInterface = mappingService.getRpcServiceClassFor(
                     name.getNamespace().toString(), name.getFormattedRevision());
@@ -604,7 +607,7 @@ public class BindingIndependentConnector implements //
         }
 
         @Override
-        public void onRpcImplementationRemoved(QName name) {
+        public void onRpcImplementationRemoved(final QName name) {
 
         }
     }
@@ -617,6 +620,7 @@ public class BindingIndependentConnector implements //
         private final Map<QName, RpcInvocationStrategy> strategiesByQName = new HashMap<>();
         private final WeakHashMap<Method, RpcInvocationStrategy> strategiesByMethod = new WeakHashMap<>();
         private final RpcService proxy;
+        private ObjectRegistration<?> forwarderRegistration;
 
         public DomToBindingRpcForwarder(final Class<? extends RpcService> service) {
             this.rpcServiceType = new WeakReference<Class<? extends RpcService>>(service);
@@ -665,13 +669,27 @@ public class BindingIndependentConnector implements //
 
         }
 
+        /**
+         * Registers RPC Forwarder to DOM Broker,
+         * this means Binding Aware Broker has implementation of RPC
+         * which is registered to it.
+         *
+         * If RPC Forwarder was previously registered to DOM Broker
+         * or to Bidning Broker this method is noop to prevent
+         * creating forwarding loop.
+         *
+         */
         public void registerToDOMBroker() {
-            try {
-                for (QName rpc : supportedRpcs) {
-                    biRpcRegistry.addRpcImplementation(rpc, this);
+            if(forwarderRegistration == null) {
+                CompositeObjectRegistrationBuilder<DomToBindingRpcForwarder> builder = CompositeObjectRegistration.builderFor(this);
+                try {
+                    for (QName rpc : supportedRpcs) {
+                        builder.add(biRpcRegistry.addRpcImplementation(rpc, this));
+                    }
+                } catch (Exception e) {
+                    LOG.error("Could not forward Rpcs of type {}", rpcServiceType.get(), e);
                 }
-            } catch (Exception e) {
-                LOG.error("Could not forward Rpcs of type {}", rpcServiceType.get(), e);
+                this.forwarderRegistration = builder.toInstance();
             }
         }
 
@@ -773,8 +791,24 @@ public class BindingIndependentConnector implements //
             });
         }
 
+        /**
+         * Registers RPC Forwarder to Binding Broker,
+         * this means DOM Broekr has implementation of RPC
+         * which is registered to it.
+         *
+         * If RPC Forwarder was previously registered to DOM Broker
+         * or to Bidning Broker this method is noop to prevent
+         * creating forwarding loop.
+         *
+         */
         public void registerToBidningBroker() {
-               baRpcRegistry.addRpcImplementation((Class)rpcServiceType.get(), proxy);
+            if(forwarderRegistration == null) {
+               try {
+                   this.forwarderRegistration = baRpcRegistry.addRpcImplementation((Class)rpcServiceType.get(), proxy);
+               } catch (Exception e) {
+                   LOG.error("Unable to forward RPCs for {}",rpcServiceType.get(),e);
+               }
+            }
         }
     }
 
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/CompositeNodeUtils.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/CompositeNodeUtils.java
deleted file mode 100644 (file)
index 1a8d179..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
- * 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;
-
-public class CompositeNodeUtils {
-
-}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/Constants.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/Constants.java
deleted file mode 100644 (file)
index 211589f..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
- * 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;
-
-public class Constants {
-    public static final Class<byte[]> BYTES_CLASS = byte[].class;
-}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DataModificationTracker.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DataModificationTracker.java
deleted file mode 100644 (file)
index 8278b36..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import org.opendaylight.controller.md.sal.common.api.data.DataModification;
-import org.opendaylight.yangtools.concepts.Path;
-
-public final class DataModificationTracker<P extends Path<P>,D> {
-    ConcurrentMap<Object, DataModification<P,D>> trackedTransactions = new ConcurrentHashMap<>();
-
-    public void startTrackingModification(DataModification<P,D> modification) {
-        trackedTransactions.putIfAbsent(modification.getIdentifier(), modification);
-    }
-
-    public boolean containsIdentifier(Object identifier) {
-        return trackedTransactions.containsKey(identifier);
-    }
-}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/package-info.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/package-info.java
deleted file mode 100644 (file)
index e5f26b9..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-/*
-  * 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.binding.impl;
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/DelegateProxy.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/DelegateProxy.java
deleted file mode 100644 (file)
index d22335e..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * 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.binding.spi;
-
-public interface DelegateProxy<T> {
-
-    void setDelegate(T delegate);
-    T getDelegate();
-}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RemoteRpcRouter.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RemoteRpcRouter.java
deleted file mode 100644 (file)
index 068c68a..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * 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.spi.remote;
-
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-
-public interface RemoteRpcRouter {
-
-
-
-
-
-
-    ListenerRegistration<RouteChangeListener> registerRouteChangeListener(RouteChangeListener listener);
-
-
-
-
-}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RouteChangeListener.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RouteChangeListener.java
deleted file mode 100644 (file)
index 9e66fb8..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * 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.spi.remote;
-
-import java.util.EventListener;
-
-import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-public interface RouteChangeListener extends EventListener {
-
-    void onRouteChange(RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change);
-
-}
index f5f03a106b36119b188ca489924d514f88b12f00..bb866f276e713151ccf18b0e57e589c65633647f 100644 (file)
@@ -9,9 +9,63 @@ package org.opendaylight.controller.md.sal.common.api.notify;
 
 import java.util.concurrent.ExecutorService;
 
+/**
+ * Interface for publishing YANG-modeled notifications.
+ * <p>
+ * Users of this interface can publish any YANG-modeled notification which will
+ * be delivered to all subscribed listeners.
+ * <p>
+ * Prefered way of publishing of notifications is done by invoking {@link #publish(Object)}.
+ *
+ * <p>You may consider using {@link #publish(Object, ExecutorService)} if and only if
+ * your use-case requires customized  execution policy or run-to-completion
+ * inside process.
+ *
+ * <p>
+ * The metadata required to deliver a notification to the correct listeners is
+ * extracted from the published notification.
+ *
+ *
+ * FIXME: Consider clarification of execution/delivery policy, how it will be
+ * affected by Actor model and cluster-wide notifications.
+ *
+ * @param <N>
+ *            the type of notifications
+ */
 public interface NotificationPublishService<N> {
 
+    /**
+     * Publishes a notification and notifies subscribed listeners. All listener
+     * notifications are done via a default executor.
+     * <p>
+     * <b>Note:</b> This call will block when the default executor is saturated
+     * and the notification queue for this executor is full.
+     *
+     * @param notification
+     *            the notification to publish.
+     */
     void publish(N notification);
 
-    void publish(N notification,ExecutorService executor);
+    /**
+     * Publishes a notification and notifies subscribed listeners. All listener
+     * notifications are done via the provided executor.
+     * <p>
+     * <b>Note:</b> Use only if ineccessary. Consider using
+     * {@link #publish(Object)} for most use-cases.
+     *
+     * <p>
+     * By using this method you could customize execution policy of listeners present
+     * inside process (e.g. using  single-threaded executor or even same-thread executor
+     * delivery.
+     *
+     * <p>
+     * This executor is used only for inside-process notification deliveries.
+     *
+     * @param notification
+     *            the notification to publish.
+     * @param executor
+     *            the executor that will be used to deliver notifications to
+     *            subscribed listeners.
+     */
+    void publish(N notification, ExecutorService executor);
 }
diff --git a/opendaylight/md-sal/sal-compability/src/main/java/org/opendaylight/controller/sal/compability/ToSalPropertyClassUtils.java b/opendaylight/md-sal/sal-compability/src/main/java/org/opendaylight/controller/sal/compability/ToSalPropertyClassUtils.java
deleted file mode 100644 (file)
index 3894fbe..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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.compability;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
-
-public class ToSalPropertyClassUtils {
-    public static Bandwidth salAdvertisedBandwidthFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        PortFeatures portFeatures = flowCapNodeConn.getAdvertisedFeatures();
-        return new AdvertisedBandwidth(resolveBandwidth(portFeatures));
-    }
-
-    public static Bandwidth salPeerBandwidthFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        PortFeatures portFeatures = flowCapNodeConn.getPeerFeatures();
-        return new PeerBandwidth(resolveBandwidth(portFeatures));
-    }
-
-    public static Bandwidth salSupportedBandwidthFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        PortFeatures portFeatures = flowCapNodeConn.getSupported();
-        return new SupportedBandwidth(resolveBandwidth(portFeatures));
-    }
-
-    public static MacAddress salMacAddressFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        String hwAddress = flowCapNodeConn.getHardwareAddress().getValue();
-        return new MacAddress(bytesFrom(hwAddress));
-    }
-
-
-    public static Name salNameFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        return new Name(flowCapNodeConn.getName());
-    }
-
-
-
-    private static byte[] bytesFrom(String hwAddress) {
-        String[] mac = hwAddress.split(":");
-        byte[] macAddress = new byte[6]; // mac.length == 6 bytes
-        for (int i = 0; i < mac.length; i++) {
-            macAddress[i] = Integer.decode("0x" + mac[i]).byteValue();
-        }
-        return macAddress;
-    }
-
-    private static long resolveBandwidth(PortFeatures portFeatures) {
-        if (portFeatures.is_1tbFd()) {
-            return Bandwidth.BW1Tbps;
-        } else if (portFeatures.is_100gbFd()) {
-            return Bandwidth.BW100Gbps;
-        } else if (portFeatures.is_40gbFd()) {
-            return Bandwidth.BW40Gbps;
-        } else if (portFeatures.is_10gbFd()) {
-            return Bandwidth.BW10Gbps;
-        } else if (portFeatures.is_1gbHd() || portFeatures.is_1gbFd()) {
-            return Bandwidth.BW1Gbps;
-        } else if (portFeatures.is_100mbHd() || portFeatures.is_100mbFd()) {
-            return Bandwidth.BW100Mbps;
-        } else if (portFeatures.is_10mbHd() || portFeatures.is_10mbFd()) {
-            return Bandwidth.BW10Mbps;
-        } else {
-            return Bandwidth.BWUNK;
-        }
-    }
-
-}
index 056be72d4e057b249a17c0286e87b9b0ebe19e72..2f11d8ed7d72d40282c37ac437de530351efc151 100644 (file)
@@ -10,42 +10,41 @@ package org.opendaylight.controller.sal.rest.api;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.DefaultValue;
+import javax.ws.rs.Encoded;
 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.Encoded;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.UriInfo;
-
 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 /**
- *   The URI hierarchy for the RESTCONF resources consists of an entry
- *   point container, 4 top-level resources, and 1 field.
- *   <ul>
- *    <li><b>/restconf</b> - {@link #getRoot()}
- *     <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>
+ * The URI hierarchy for the RESTCONF resources consists of an entry point
+ * container, 4 top-level resources, and 1 field.
+ * <ul>
+ * <li><b>/restconf</b> - {@link #getRoot()}
+ * <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 {
@@ -58,81 +57,81 @@ public interface RestconfService {
 
     @GET
     @Path("/modules")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getModules();
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getModules(@Context UriInfo uriInfo);
 
     @GET
     @Path("/modules/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getModules(@PathParam("identifier") String identifier);
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getModules(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
 
     @GET
     @Path("/modules/module/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getModule(@PathParam("identifier") String identifier);
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getModule(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
 
     @GET
     @Path("/operations")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getOperations();
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getOperations(@Context UriInfo uriInfo);
 
     @GET
     @Path("/operations/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getOperations(@PathParam("identifier") String identifier);
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getOperations(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
 
     @POST
     @Path("/operations/{identifier:.+}")
-    @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({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(@Encoded @PathParam("identifier") String identifier, CompositeNode payload);
+    @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({ 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(@Encoded @PathParam("identifier") String identifier, CompositeNode payload, @Context UriInfo uriInfo);
 
     @POST
     @Path("/operations/{identifier:.+}")
-    @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(@Encoded @PathParam("identifier") String identifier, @DefaultValue("") String noPayload);
+    @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(@Encoded @PathParam("identifier") String identifier,
+            @DefaultValue("") String noPayload, @Context UriInfo uriInfo);
 
     @GET
     @Path("/config/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Produces({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public StructuredData readConfigurationData(@Encoded @PathParam("identifier") String identifier,
-                                                @Context UriInfo depth);
+            @Context UriInfo uriInfo);
 
     @GET
     @Path("/operational/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData readOperationalData(@Encoded @PathParam("identifier") String identifier,
-                                              @Context UriInfo depth);
+    @Produces({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData readOperationalData(@Encoded @PathParam("identifier") String identifier, @Context UriInfo uriInfo);
 
     @PUT
     @Path("/config/{identifier:.+}")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public Response updateConfigurationData(@Encoded @PathParam("identifier") String identifier, CompositeNode payload);
 
     @POST
     @Path("/config/{identifier:.+}")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public Response createConfigurationData(@Encoded @PathParam("identifier") String identifier, CompositeNode payload);
 
     @POST
     @Path("/config")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public Response createConfigurationData(CompositeNode payload);
 
     @DELETE
@@ -145,9 +144,8 @@ public interface RestconfService {
 
     @GET
     @Path("/streams")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getAvailableStreams();
-
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getAvailableStreams(@Context UriInfo uriInfo);
 
 }
index 1c2e9c5009897f741efaa6a1320665d7ba2a4b0a..063d2f51afffdd0c7094d7363d95795182b5cd8e 100644 (file)
@@ -9,13 +9,11 @@ package org.opendaylight.controller.sal.rest.impl;
 
 import com.google.common.base.Charsets;
 import com.google.gson.stream.JsonWriter;
-
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.Type;
-
 import javax.ws.rs.Produces;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
@@ -23,7 +21,6 @@ import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.ext.MessageBodyWriter;
 import javax.ws.rs.ext.Provider;
-
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
@@ -39,7 +36,7 @@ public enum StructuredDataToJsonProvider implements MessageBodyWriter<Structured
 
     @Override
     public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
-        return type.equals( StructuredData.class );
+        return type.equals(StructuredData.class);
     }
 
     @Override
@@ -57,10 +54,14 @@ public enum StructuredDataToJsonProvider implements MessageBodyWriter<Structured
         }
 
         JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, Charsets.UTF_8));
-        writer.setIndent("    ");
+
+        if (t.isPrettyPrintMode()) {
+            writer.setIndent("    ");
+        } else {
+            writer.setIndent("");
+        }
         JsonMapper jsonMapper = new JsonMapper(t.getMountPoint());
         jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema());
         writer.flush();
     }
-
 }
index e5a56cf47566c6ca4d3d8e1113b817706b404d71..3a235ced858a4be9af6dc24d9152602ff806bc09 100644 (file)
@@ -11,7 +11,6 @@ import java.io.IOException;
 import java.io.OutputStream;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.Type;
-
 import javax.ws.rs.Produces;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
@@ -26,7 +25,6 @@ import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
@@ -70,7 +68,7 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredD
 
     @Override
     public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
-        return type.equals( StructuredData.class );
+        return type.equals(StructuredData.class);
     }
 
     @Override
@@ -90,6 +88,11 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredD
         final Transformer trans;
         try {
             trans = TRANSFORMER.get();
+            if (t.isPrettyPrintMode()) {
+                trans.setOutputProperty(OutputKeys.INDENT, "yes");
+            } else {
+                trans.setOutputProperty(OutputKeys.INDENT, "no");
+            }
         } catch (RuntimeException e) {
             throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT,
                     ErrorTag.OPERATION_FAILED);
index 5a16c04aedb1fb7ed3d44b77bd1595897215d73f..3834a383db8e94da989f7b1bd4076285cd250935 100644 (file)
@@ -15,7 +15,6 @@ import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
-
 import java.net.URI;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
@@ -28,12 +27,10 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.Future;
-
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
 import javax.ws.rs.core.UriBuilder;
 import javax.ws.rs.core.UriInfo;
-
 import org.apache.commons.lang3.StringUtils;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
@@ -78,6 +75,21 @@ import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBu
 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
 
 public class RestconfImpl implements RestconfService {
+    private enum UriParameters {
+        PRETTY_PRINT( "prettyPrint"),
+        DEPTH( "depth");
+
+        private String uriParameterName;
+        UriParameters(String uriParameterName) {
+            this.uriParameterName = uriParameterName;
+        }
+
+        @Override
+        public String toString() {
+            return uriParameterName;
+        }
+    }
+
     private final static RestconfImpl INSTANCE = new RestconfImpl();
 
     private static final int CHAR_NOT_FOUND = -1;
@@ -110,7 +122,7 @@ public class RestconfImpl implements RestconfService {
     }
 
     @Override
-    public StructuredData getModules() {
+    public StructuredData getModules(final UriInfo uriInfo) {
         final Module restconfModule = this.getRestconfModule();
 
         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
@@ -127,11 +139,11 @@ public class RestconfImpl implements RestconfService {
                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
         QName qName = modulesSchemaNode.getQName();
         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
-        return new StructuredData(modulesNode, modulesSchemaNode, null);
+        return new StructuredData(modulesNode, modulesSchemaNode, null,parsePrettyPrintParameter( uriInfo ));
     }
 
     @Override
-    public StructuredData getAvailableStreams() {
+    public StructuredData getAvailableStreams(final UriInfo uriInfo) {
         Set<String> availableStreams = Notificator.getStreamNames();
 
         final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
@@ -146,11 +158,11 @@ public class RestconfImpl implements RestconfService {
                 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
         QName qName = streamsSchemaNode.getQName();
         final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
-        return new StructuredData(streamsNode, streamsSchemaNode, null);
+        return new StructuredData(streamsNode, streamsSchemaNode, null,parsePrettyPrintParameter( uriInfo ));
     }
 
     @Override
-    public StructuredData getModules(final String identifier) {
+    public StructuredData getModules(final String identifier,final UriInfo uriInfo) {
         Set<Module> modules = null;
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
@@ -178,11 +190,11 @@ public class RestconfImpl implements RestconfService {
                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
         QName qName = modulesSchemaNode.getQName();
         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
-        return new StructuredData(modulesNode, modulesSchemaNode, mountPoint);
+        return new StructuredData(modulesNode, modulesSchemaNode, mountPoint,parsePrettyPrintParameter( uriInfo ));
     }
 
     @Override
-    public StructuredData getModule(final String identifier) {
+    public StructuredData getModule(final String identifier,final UriInfo uriInfo) {
         final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
         Module module = null;
         MountInstance mountPoint = null;
@@ -207,17 +219,17 @@ public class RestconfImpl implements RestconfService {
         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
         final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
-        return new StructuredData(moduleNode, moduleSchemaNode, mountPoint);
+        return new StructuredData(moduleNode, moduleSchemaNode, mountPoint,parsePrettyPrintParameter( uriInfo ));
     }
 
     @Override
-    public StructuredData getOperations() {
+    public StructuredData getOperations(final UriInfo uriInfo) {
         Set<Module> allModules = this.controllerContext.getAllModules();
-        return this.operationsFromModulesToStructuredData(allModules, null);
+        return this.operationsFromModulesToStructuredData(allModules, null,parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getOperations(final String identifier) {
+    public StructuredData getOperations(final String identifier,final UriInfo uriInfo) {
         Set<Module> modules = null;
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
@@ -232,11 +244,11 @@ public class RestconfImpl implements RestconfService {
                             ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
         }
 
-        return this.operationsFromModulesToStructuredData(modules, mountPoint);
+        return this.operationsFromModulesToStructuredData(modules, mountPoint,parsePrettyPrintParameter(uriInfo));
     }
 
     private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
-            final MountInstance mountPoint) {
+                                                                 final MountInstance mountPoint,boolean prettyPrint) {
         final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
         Module restconfModule = this.getRestconfModule();
         final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
@@ -269,7 +281,7 @@ public class RestconfImpl implements RestconfService {
         final CompositeNode operationsNode =
                 NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
         ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
-        return new StructuredData(operationsNode, schemaNode, mountPoint);
+        return new StructuredData(operationsNode, schemaNode, mountPoint,prettyPrint);
     }
 
     private Module getRestconfModule() {
@@ -389,18 +401,18 @@ public class RestconfImpl implements RestconfService {
     }
 
     @Override
-    public StructuredData invokeRpc(final String identifier, final CompositeNode payload) {
+    public StructuredData invokeRpc(final String identifier, final CompositeNode payload,final UriInfo uriInfo) {
         final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
         QName rpcName = rpc.getRpcDefinition().getQName();
         URI rpcNamespace = rpcName.getNamespace();
         if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE) &&
                 Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
-            return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition());
+            return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(),parsePrettyPrintParameter(uriInfo));
         }
 
         validateInput( rpc.getRpcDefinition().getInput(), payload );
 
-        return callRpc(rpc, payload);
+        return callRpc(rpc, payload,parsePrettyPrintParameter(uriInfo));
     }
 
     private void validateInput(final DataSchemaNode inputSchema, final CompositeNode payload) {
@@ -426,7 +438,7 @@ public class RestconfImpl implements RestconfService {
     }
 
     private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload,
-            final RpcDefinition rpc) {
+                                                          final RpcDefinition rpc,final boolean prettyPrint) {
         final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
         final SimpleNode<? extends Object> pathNode = value == null ? null :
             value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") );
@@ -463,16 +475,16 @@ public class RestconfImpl implements RestconfService {
             Notificator.createListener(pathIdentifier, streamName);
         }
 
-        return new StructuredData(responseData, rpc.getOutput(), null);
+        return new StructuredData(responseData, rpc.getOutput(), null,prettyPrint);
     }
 
     @Override
-    public StructuredData invokeRpc(final String identifier, final String noPayload) {
+    public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
         if (StringUtils.isNotBlank(noPayload)) {
             throw new RestconfDocumentedException(
                     "Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
         }
-        return invokeRpc( identifier, (CompositeNode)null );
+        return invokeRpc( identifier, (CompositeNode)null,uriInfo);
     }
 
     private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
@@ -516,7 +528,7 @@ public class RestconfImpl implements RestconfService {
 
     }
 
-    private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload) {
+    private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload,boolean prettyPrint) {
         if (rpcExecutor == null) {
             throw new RestconfDocumentedException(
                     "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT );
@@ -547,7 +559,7 @@ public class RestconfImpl implements RestconfService {
             return null; //no output, nothing to send back.
         }
 
-        return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null);
+        return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null,prettyPrint);
     }
 
     private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
@@ -570,7 +582,7 @@ public class RestconfImpl implements RestconfService {
     }
 
     @Override
-    public StructuredData readConfigurationData(final String identifier, final UriInfo info) {
+    public StructuredData readConfigurationData(final String identifier, final UriInfo uriInfo) {
         final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
         CompositeNode data = null;
         MountInstance mountPoint = iiWithData.getMountPoint();
@@ -581,8 +593,9 @@ public class RestconfImpl implements RestconfService {
             data = broker.readConfigurationData(iiWithData.getInstanceIdentifier());
         }
 
-        data = pruneDataAtDepth( data, parseDepthParameter( info ) );
-        return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
+        data = pruneDataAtDepth( data, parseDepthParameter( uriInfo ) );
+        boolean prettyPrintMode = parsePrettyPrintParameter( uriInfo );
+        return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint(),prettyPrintMode);
     }
 
     @SuppressWarnings("unchecked")
@@ -607,7 +620,7 @@ public class RestconfImpl implements RestconfService {
     }
 
     private Integer parseDepthParameter( final UriInfo info ) {
-        String param = info.getQueryParameters( false ).getFirst( "depth" );
+        String param = info.getQueryParameters( false ).getFirst( UriParameters.DEPTH.toString() );
         if( Strings.isNullOrEmpty( param ) || "unbounded".equals( param ) ) {
             return null;
         }
@@ -643,7 +656,13 @@ public class RestconfImpl implements RestconfService {
         }
 
         data = pruneDataAtDepth( data, parseDepthParameter( info ) );
-        return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint);
+        boolean prettyPrintMode = parsePrettyPrintParameter( info );
+        return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint,prettyPrintMode);
+    }
+
+    private boolean parsePrettyPrintParameter(UriInfo info) {
+        String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
+        return Boolean.parseBoolean(param);
     }
 
     @Override
index 231fe7e02eedfdee29d2996a7d0ebc4839f73646..c745a8009deac75a70a7249626b07f56457d9243 100644 (file)
@@ -16,11 +16,18 @@ public class StructuredData {
     private final CompositeNode data;
     private final DataSchemaNode schema;
     private final MountInstance mountPoint;
+    private final boolean prettyPrintMode;
 
     public StructuredData(final CompositeNode data, final DataSchemaNode schema, final MountInstance mountPoint) {
+        this(data, schema, mountPoint, false);
+    }
+
+    public StructuredData(final CompositeNode data, final DataSchemaNode schema, final MountInstance mountPoint,
+            final boolean preattyPrintMode) {
         this.data = data;
         this.schema = schema;
         this.mountPoint = mountPoint;
+        this.prettyPrintMode = preattyPrintMode;
     }
 
     public CompositeNode getData() {
@@ -34,4 +41,8 @@ public class StructuredData {
     public MountInstance getMountPoint() {
         return mountPoint;
     }
+
+    public boolean isPrettyPrintMode() {
+        return prettyPrintMode;
+    }
 }
index 24dba17c90cdff4e9a87d0a059160357dcbaad88..3f89c97367efd2f849802a61d5e4fec1f12149f1 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
 
 import java.io.IOException;
 import java.util.Collections;
@@ -50,7 +51,9 @@ public class CnSnToJsonNotExistingLeafTypeTest extends YangAndXmlAndDataSchemaLo
                         Collections.<Module>emptySet(), prepareDataSchemaNode(),
                         StructuredDataToJsonProvider.INSTANCE);
         assertNotNull(jsonOutput);
-        assertTrue(jsonOutput.contains("\"lf1\": \"\""));
+
+//      pattern for e.g. >    "lf1"   : ""    < or >"lf1":""<
+        assertTrue(containsStringData(jsonOutput, "\"lf1\"",":","\"\""));
     }
 
     private CompositeNode prepareCompositeNode() {
index e116129bf7cc63736760688234b1f7665dcf9533..3d25955b3caae0bff5a51b5dec49f53b270160e5 100644 (file)
@@ -9,11 +9,10 @@ package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
 
 import java.io.IOException;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -47,12 +46,12 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader {
         }
         assertNotNull(jsonOutput);
 
-        assertTrue(jsonOutput.contains("\"augment-leaf:lf2\": \"lf2\""));
-        assertTrue(jsonOutput.contains("\"augment-container:cont1\": {"));
-        assertTrue(jsonOutput.contains("\"augment-container:lf11\": \"lf11\""));
-        assertTrue(jsonOutput.contains("\"augment-list:lst1\": ["));
-        assertTrue(jsonOutput.contains("\"augment-list:lf11\": \"lf1_1\""));
-        assertTrue(jsonOutput.contains("\"augment-list:lf11\": \"lf1_2\""));
-        assertTrue(jsonOutput.contains("\"augment-leaflist:lflst1\": ["));
+        assertTrue(containsStringData(jsonOutput,"\"augment-leaf:lf2\"",":", "\"lf2\""));
+        assertTrue(containsStringData(jsonOutput,"\"augment-container:cont1\"",":", "\\{"));
+        assertTrue(containsStringData(jsonOutput,"\"augment-container:lf11\"",":", "\"lf11\""));
+        assertTrue(containsStringData(jsonOutput,"\"augment-list:lst1\"",":", "\\["));
+        assertTrue(containsStringData(jsonOutput,"\"augment-list:lf11\"",":", "\"lf1_1\""));
+        assertTrue(containsStringData(jsonOutput,"\"augment-list:lf11\"",":", "\"lf1_2\""));
+        assertTrue(containsStringData(jsonOutput,"\"augment-leaflist:lflst1\"",":", "\\["));
     }
 }
index 3f2c212bd87785ccbf021749d9bddb1db069bf6f..47171bf2470141bc509d2d96423b676a850826da 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
 
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
@@ -19,16 +20,13 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-
 import javax.ws.rs.WebApplicationException;
 import javax.xml.stream.XMLEventReader;
 import javax.xml.stream.XMLInputFactory;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.events.StartElement;
 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;
@@ -39,9 +37,10 @@ import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifie
 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.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
 
 public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSchemaLoader {
 
@@ -55,21 +54,16 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
         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 {
+            URISyntaxException, XMLStreamException {
         CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
                 StructuredDataToXmlProvider.INSTANCE);
-        //uncomment for debug
-        // System.out.println(output);
         validateXmlOutputWithLeafList(output);
     }
 
@@ -79,33 +73,40 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
         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\"");
+        strInOutput = containsStringData(
+                output,
+                "\"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\"");
+            strInOutput = containsStringData(
+                    output,
+                    "\"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 saveCnSnWithLeafListInstIdentifierToJsonTest() throws WebApplicationException, IOException,
-    URISyntaxException {
+            URISyntaxException {
         CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
                 StructuredDataToJsonProvider.INSTANCE);
-        //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']\"");
+        strInOutput = containsStringData(
+                output,
+                "\"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\\\"]\"");
+            strInOutput = containsStringData(
+                    output,
+                    "\"augment-augment-module:lf111\"",
+                    ":",
+                    "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11\\[.=\\\\\"lflst11_1\\\\\"\\]\"");
         }
 
         assertTrue(strInOutput);
@@ -189,27 +190,21 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
     }
 
     private CompositeNode prepareCnSn(final 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.getValue().add(lf111);
-        lst11.init();
+        CompositeNodeBuilder<ImmutableCompositeNode> cont = ImmutableCompositeNode.builder();
+        cont.setQName(QName.create("instance:identifier:module", "2014-01-17", "cont"));
 
-        cont1.getValue().add(lst11);
-        cont1.init();
+        CompositeNodeBuilder<ImmutableCompositeNode> cont1 = ImmutableCompositeNode.builder();
+        cont1.setQName(QName.create("instance:identifier:module", "2014-01-17", "cont1"));
 
-        cont.getValue().add(cont1);
-        cont.init();
+        CompositeNodeBuilder<ImmutableCompositeNode> lst11 = ImmutableCompositeNode.builder();
+        lst11.setQName(QName.create("augment:module", "2014-01-17", "lst11"));
 
-        return cont;
+        SimpleNode<?> lf111 = NodeFactory.createImmutableSimpleNode(
+                QName.create("augment:augment:module", "2014-01-17", "lf111"), null, instanceIdentifier);
+        lst11.add(lf111);
+        cont1.add(lst11.toInstance());
+        cont.add(cont1.toInstance());
+        return cont.toInstance();
     }
 
     private InstanceIdentifier createInstanceIdentifier() throws URISyntaxException {
index 910ca8e20aab453d02b4e320b0493775666d3575..b90097bc94a0e7888b589f33960343cc94d36c12 100644 (file)
@@ -19,6 +19,9 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
 
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
 import java.io.FileNotFoundException;
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -27,7 +30,9 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriInfo;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -56,14 +61,11 @@ import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-
 public class InvokeRpcMethodTest {
 
     private RestconfImpl restconfImpl = null;
     private static ControllerContext controllerContext = null;
+    private static UriInfo uriInfo;
 
 
     @BeforeClass
@@ -77,7 +79,10 @@ public class InvokeRpcMethodTest {
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
         controllerContext = spy( ControllerContext.getInstance() );
         controllerContext.setSchemas(schemaContext);
-
+        uriInfo = mock(UriInfo.class);
+        MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
+        map.put("prettyPrint", Collections.singletonList("true"));
+        when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
     }
 
     @Before
@@ -114,7 +119,7 @@ public class InvokeRpcMethodTest {
             .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture(
                                                Rpcs.<CompositeNode>getRpcResult( true ) ) );
 
-        StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload);
+        StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload,uriInfo);
         assertTrue(structData == null);
 
     }
@@ -143,7 +148,7 @@ public class InvokeRpcMethodTest {
         restconfImpl.setBroker(brokerFacade);
 
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", "");
+            restconfImpl.invokeRpc("toaster:cancel-toast", "",uriInfo);
             fail("Expected an exception to be thrown.");
         }
         catch (RestconfDocumentedException e) {
@@ -196,7 +201,7 @@ public class InvokeRpcMethodTest {
         restconfImpl.setBroker(brokerFacade);
 
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", "");
+            restconfImpl.invokeRpc("toaster:cancel-toast", "",uriInfo);
             fail("Expected an exception to be thrown.");
         }
         catch (RestconfDocumentedException e) {
@@ -220,7 +225,7 @@ public class InvokeRpcMethodTest {
         restconfImpl.setBroker(brokerFacade);
 
         StructuredData output = restconfImpl.invokeRpc("toaster:cancel-toast",
-                "");
+                "",uriInfo);
         assertEquals(null, output);
         //additional validation in the fact that the restconfImpl does not throw an exception.
     }
@@ -228,7 +233,7 @@ public class InvokeRpcMethodTest {
     @Test
     public void testInvokeRpcMethodExpectingNoPayloadButProvidePayload() {
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ");
+            restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ",uriInfo);
             fail("Expected an exception");
         } catch (RestconfDocumentedException e) {
             verifyRestconfDocumentedException( e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
@@ -239,7 +244,7 @@ public class InvokeRpcMethodTest {
     @Test
     public void testInvokeRpcMethodWithBadMethodName() {
         try {
-            restconfImpl.invokeRpc("toaster:bad-method", "");
+            restconfImpl.invokeRpc("toaster:bad-method", "",uriInfo);
             fail("Expected an exception");
         }
         catch (RestconfDocumentedException e) {
@@ -263,7 +268,7 @@ public class InvokeRpcMethodTest {
         restconfImpl.setBroker(brokerFacade);
 
         StructuredData output = restconfImpl.invokeRpc("toaster:make-toast",
-                payload);
+                payload,uriInfo);
         assertEquals(null, output);
         //additional validation in the fact that the restconfImpl does not throw an exception.
     }
@@ -271,7 +276,7 @@ public class InvokeRpcMethodTest {
     @Test
     public void testThrowExceptionWhenSlashInModuleName() {
         try {
-            restconfImpl.invokeRpc("toaster/slash", "");
+            restconfImpl.invokeRpc("toaster/slash", "",uriInfo);
             fail("Expected an exception.");
         }
         catch (RestconfDocumentedException e) {
@@ -294,7 +299,7 @@ public class InvokeRpcMethodTest {
 
         restconfImpl.setBroker(brokerFacade);
 
-        StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "");
+        StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "",uriInfo);
         assertNotNull( output );
         assertSame( compositeNode, output.getData() );
         assertNotNull( output.getSchema() );
@@ -330,7 +335,7 @@ public class InvokeRpcMethodTest {
         restconfImpl.setControllerContext( mockedContext );
         StructuredData output = restconfImpl.invokeRpc(
                 "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/toaster:cancel-toast",
-                "");
+                "",uriInfo);
         assertEquals(null, output);
 
         //additional validation in the fact that the restconfImpl does not throw an exception.
index 319603dfc14b1f6a4965d6de46e99bf1a6199f8f..3dd3101a2e2a325f8da94cdacef60dbaa0c0add0 100644 (file)
@@ -19,12 +19,10 @@ import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUt
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
-
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.UriInfo;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
@@ -55,10 +53,10 @@ public class MediaTypesTest extends JerseyTest {
     @Override
     protected Application configure() {
         /* enable/disable Jersey logs to console */
-//        enable(TestProperties.LOG_TRAFFIC);
-//        enable(TestProperties.DUMP_ENTITY);
-//        enable(TestProperties.RECORD_LOG_LEVEL);
-//        set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+        // enable(TestProperties.LOG_TRAFFIC);
+        // enable(TestProperties.DUMP_ENTITY);
+        // enable(TestProperties.RECORD_LOG_LEVEL);
+        // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
         ResourceConfig resourceConfig = new ResourceConfig();
         resourceConfig = resourceConfig.registerInstances(restconfService, StructuredDataToXmlProvider.INSTANCE,
                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
@@ -66,31 +64,31 @@ public class MediaTypesTest extends JerseyTest {
         return resourceConfig;
     }
 
-  @Test
-  public void testPostOperationsWithInputDataMediaTypes() throws UnsupportedEncodingException {
-      String uriPrefix = "/operations/";
-      String uriPath = "ietf-interfaces:interfaces";
-      String uri = uriPrefix + uriPath;
-      when(restconfService.invokeRpc(eq(uriPath), any(CompositeNode.class))).thenReturn(null);
-      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.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));
-      post(uri, MediaType.APPLICATION_XML, MediaType.APPLICATION_XML, xmlData);
-      verify(restconfService, times(4)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, MediaType.TEXT_XML, MediaType.TEXT_XML, xmlData);
-      verify(restconfService, times(5)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, null, MediaType.TEXT_XML, xmlData);
-      verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-
-      // negative tests
-      post(uri, MediaType.TEXT_PLAIN, MediaType.TEXT_XML, xmlData);
-      verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, MediaType.TEXT_XML, MediaType.TEXT_PLAIN, xmlData);
-      verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-  }
+    @Test
+    public void testPostOperationsWithInputDataMediaTypes() throws UnsupportedEncodingException {
+        String uriPrefix = "/operations/";
+        String uriPath = "ietf-interfaces:interfaces";
+        String uri = uriPrefix + uriPath;
+        when(restconfService.invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class))).thenReturn(null);
+        post(uri, Draft02.MediaTypes.OPERATION + JSON, Draft02.MediaTypes.OPERATION + JSON, jsonData);
+        verify(restconfService, times(1)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, Draft02.MediaTypes.OPERATION + XML, Draft02.MediaTypes.OPERATION + XML, xmlData);
+        verify(restconfService, times(2)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, jsonData);
+        verify(restconfService, times(3)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, MediaType.APPLICATION_XML, MediaType.APPLICATION_XML, xmlData);
+        verify(restconfService, times(4)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, MediaType.TEXT_XML, MediaType.TEXT_XML, xmlData);
+        verify(restconfService, times(5)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, null, MediaType.TEXT_XML, xmlData);
+        verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+
+        // negative tests
+        post(uri, MediaType.TEXT_PLAIN, MediaType.TEXT_XML, xmlData);
+        verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, MediaType.TEXT_XML, MediaType.TEXT_PLAIN, xmlData);
+        verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+    }
 
     @Test
     public void testGetConfigMediaTypes() throws UnsupportedEncodingException {
@@ -98,9 +96,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPath = "ietf-interfaces:interfaces";
         String uri = uriPrefix + uriPath;
         when(restconfService.readConfigurationData(eq(uriPath), any(UriInfo.class))).thenReturn(null);
-        get(uri, Draft02.MediaTypes.DATA+JSON);
+        get(uri, Draft02.MediaTypes.DATA + JSON);
         verify(restconfService, times(1)).readConfigurationData(eq(uriPath), any(UriInfo.class));
-        get(uri, Draft02.MediaTypes.DATA+XML);
+        get(uri, Draft02.MediaTypes.DATA + XML);
         verify(restconfService, times(2)).readConfigurationData(eq(uriPath), any(UriInfo.class));
         get(uri, MediaType.APPLICATION_JSON);
         verify(restconfService, times(3)).readConfigurationData(eq(uriPath), any(UriInfo.class));
@@ -120,9 +118,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPath = "ietf-interfaces:interfaces";
         String uri = uriPrefix + uriPath;
         when(restconfService.readOperationalData(eq(uriPath), any(UriInfo.class))).thenReturn(null);
-        get(uri, Draft02.MediaTypes.DATA+JSON);
+        get(uri, Draft02.MediaTypes.DATA + JSON);
         verify(restconfService, times(1)).readOperationalData(eq(uriPath), any(UriInfo.class));
-        get(uri, Draft02.MediaTypes.DATA+XML);
+        get(uri, Draft02.MediaTypes.DATA + XML);
         verify(restconfService, times(2)).readOperationalData(eq(uriPath), any(UriInfo.class));
         get(uri, MediaType.APPLICATION_JSON);
         verify(restconfService, times(3)).readOperationalData(eq(uriPath), any(UriInfo.class));
@@ -142,9 +140,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPath = "ietf-interfaces:interfaces";
         String uri = uriPrefix + uriPath;
         when(restconfService.updateConfigurationData(eq(uriPath), any(CompositeNode.class))).thenReturn(null);
-        put(uri, null, Draft02.MediaTypes.DATA+JSON, jsonData);
+        put(uri, null, Draft02.MediaTypes.DATA + JSON, jsonData);
         verify(restconfService, times(1)).updateConfigurationData(eq(uriPath), any(CompositeNode.class));
-        put(uri, null, Draft02.MediaTypes.DATA+XML, xmlData);
+        put(uri, null, Draft02.MediaTypes.DATA + XML, xmlData);
         verify(restconfService, times(2)).updateConfigurationData(eq(uriPath), any(CompositeNode.class));
         put(uri, null, MediaType.APPLICATION_JSON, jsonData);
         verify(restconfService, times(3)).updateConfigurationData(eq(uriPath), any(CompositeNode.class));
@@ -162,9 +160,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPath = "ietf-interfaces:interfaces";
         String uri = uriPrefix + uriPath;
         when(restconfService.createConfigurationData(eq(uriPath), any(CompositeNode.class))).thenReturn(null);
-        post(uri, null, Draft02.MediaTypes.DATA+JSON, jsonData);
+        post(uri, null, Draft02.MediaTypes.DATA + JSON, jsonData);
         verify(restconfService, times(1)).createConfigurationData(eq(uriPath), any(CompositeNode.class));
-        post(uri, null, Draft02.MediaTypes.DATA+XML, xmlData);
+        post(uri, null, Draft02.MediaTypes.DATA + XML, xmlData);
         verify(restconfService, times(2)).createConfigurationData(eq(uriPath), any(CompositeNode.class));
         post(uri, null, MediaType.APPLICATION_JSON, jsonData);
         verify(restconfService, times(3)).createConfigurationData(eq(uriPath), any(CompositeNode.class));
@@ -181,9 +179,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPrefix = "/config/";
         String uri = uriPrefix;
         when(restconfService.createConfigurationData(any(CompositeNode.class))).thenReturn(null);
-        post(uri, null, Draft02.MediaTypes.DATA+JSON, jsonData);
+        post(uri, null, Draft02.MediaTypes.DATA + JSON, jsonData);
         verify(restconfService, times(1)).createConfigurationData(any(CompositeNode.class));
-        post(uri, null, Draft02.MediaTypes.DATA+XML, xmlData);
+        post(uri, null, Draft02.MediaTypes.DATA + XML, xmlData);
         verify(restconfService, times(2)).createConfigurationData(any(CompositeNode.class));
         post(uri, null, MediaType.APPLICATION_JSON, jsonData);
         verify(restconfService, times(3)).createConfigurationData(any(CompositeNode.class));
index 41a1c3827d21973180e01b7fd3cb11e2e73f993c..9fd5128d19b51db4c71ad3678dae982aec1b3551 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -16,6 +17,8 @@ import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
 import java.io.FileNotFoundException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
@@ -29,14 +32,12 @@ import java.util.List;
 import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.MultivaluedHashMap;
 import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.UriInfo;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
@@ -68,9 +69,6 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;
 
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
 public class RestGetOperationTest extends JerseyTest {
 
     static class NodeData {
@@ -615,6 +613,39 @@ public class RestGetOperationTest extends JerseyTest {
         return null;
     }
 
+    /**
+     * If includeWhiteChars URI parameter is set to false then no white
+     * characters can be included in returned output
+     * @throws UnsupportedEncodingException
+     */
+    @Test
+    public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
+        getDataWithUriIncludeWhiteCharsParameter("config");
+        getDataWithUriIncludeWhiteCharsParameter("operational");
+    }
+
+
+    private void getDataWithUriIncludeWhiteCharsParameter(String target) throws UnsupportedEncodingException {
+        mockReadConfigurationDataMethod();
+        String uri = "/"+target+"/ietf-interfaces:interfaces/interface/eth0";
+        Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
+        String xmlData = response.readEntity(String.class);
+
+        Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
+        Matcher matcher = pattern.matcher(xmlData);
+        // XML element can't surrounded with white character (e.g ">    " or
+        // "    <")
+        assertFalse(matcher.matches());
+
+        response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
+        String jsonData = response.readEntity(String.class);
+        pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
+        matcher = pattern.matcher(jsonData);
+        // JSON element can't surrounded with white character (e.g "} ", " {",
+        // "] ", " [", " :" or ": ")
+        assertFalse(matcher.matches());
+    }
+
     @Test
     public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
 
index 853c19f93530c16449840b1043ac07d30edaab4f..449b79923edd40e0c21f922ba3ff6c271e45d3c5 100644 (file)
@@ -13,6 +13,7 @@ import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import com.google.common.base.Preconditions;
 import java.io.BufferedReader;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -27,7 +28,8 @@ import java.sql.Date;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
-
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.ext.MessageBodyReader;
 import javax.ws.rs.ext.MessageBodyWriter;
@@ -40,7 +42,6 @@ import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
@@ -61,8 +62,6 @@ import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.xml.sax.SAXException;
 
-import com.google.common.base.Preconditions;
-
 public final class TestUtils {
 
     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
@@ -297,6 +296,22 @@ public final class TestUtils {
         }
         bufReader.close();
         return result.toString();
+    }
+
+    private static Pattern patternForStringsSeparatedByWhiteChars(String ... substrings ) {
+        StringBuilder pattern = new StringBuilder();
+        pattern.append(".*");
+        for (String substring : substrings) {
+            pattern.append(substring);
+            pattern.append("\\s*");
+        }
+        pattern.append(".*");
+        return Pattern.compile(pattern.toString(), Pattern.DOTALL);
+    }
 
+    public static boolean containsStringData(String jsonOutput,String ...substrings ) {
+        Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
+        Matcher matcher = pattern.matcher(jsonOutput);
+        return matcher.matches();
     }
 }