package org.opendaylight.controller.filtervalve.cors.jaxb;
import static org.hamcrest.core.Is.is;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import com.google.common.base.Optional;
import java.io.File;
package org.opendaylight.controller.sal.packet;
-import junit.framework.Assert;
-
+import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.liblldp.BitBufferHelper;
<dependencies>
<!-- project specific dependencies -->
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-artifacts</artifactId>
+ <version>${config.version}</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-artifacts</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
+
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
</dependency>
<!-- config-->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-api</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager</artifactId>
- <version>${config.version}</version>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-api</artifactId>
- <version>${config.version}</version>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-api</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-directory-xml-adapter</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-file-xml-adapter</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-feature-adapter</artifactId>
- <version>${config.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- <version>${config.version}</version>
- <type>test-jar</type>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>configuration</artifactId>
<artifactId>liblldp</artifactId>
<version>${sal.version}</version>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>logback-config</artifactId>
- <version>${config.version}</version>
- </dependency>
<!-- Debug and logging -->
<dependency>
<groupId>org.opendaylight.controller</groupId>
<version>${dummy-console.version}</version>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-config-api</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-event-executor-config</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-threadgroup-config</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-timer-config</artifactId>
- <version>${config.version}</version>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>networkconfig.bridgedomain.northbound</artifactId>
<artifactId>sal-rest-connector-config</artifactId>
<version>${mdsal.version}</version>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-netty-config</artifactId>
- <version>${config.version}</version>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>md-sal-config</artifactId>
<version>${karaf.security.version}</version>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>shutdown-api</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>shutdown-impl</artifactId>
- <version>${config.version}</version>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>statistics.northbound</artifactId>
<version>${switchmanager.northbound.version}</version>
</dependency>
- <!-- threadpool -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-api</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-impl</artifactId>
- <version>${config.version}</version>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>topology.northbound</artifactId>
<artifactId>web</artifactId>
<version>${web.version}</version>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- <version>${config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- <version>${config.version}</version>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-test</artifactId>
- <version>${config.version}</version>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller.md</groupId>
<artifactId>forwardingrules-manager</artifactId>
<type>xml</type>
<scope>runtime</scope>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-config-netty</artifactId>
- <version>${config.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-flow</artifactId>
<version>${mdsal.version}</version>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-config</artifactId>
- <version>${config.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-protocol-framework</artifactId>
<type>xml</type>
<scope>runtime</scope>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-config-persister</artifactId>
- <version>${config.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-netty-features</artifactId>
- <version>${config.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-base</artifactId>
package org.opendaylight.controller.config.api;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import org.junit.Assert;
import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-import javax.management.*;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.*;
-
public class IdentityAttributeRefTest {
IdentityAttributeRef attr = new IdentityAttributeRef("attr");
package org.opendaylight.controller.config.api;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import com.google.common.collect.Lists;
import java.nio.file.AccessDeniedException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-
-import com.google.common.collect.Lists;
import org.hamcrest.CoreMatchers;
-import org.junit.Assert;
-import org.junit.Before;
import org.junit.Test;
-import javax.management.Query;
-
-import static org.junit.Assert.*;
-
public class JmxAttributeValidationExceptionTest {
- private JmxAttribute jmxAttribute = new JmxAttribute("attr1");
+ private final JmxAttribute jmxAttribute = new JmxAttribute("attr1");
@Test
public void testJmxAttributeValidationExceptionElement() throws Exception {
@Test
public void testJmxAttributeValidationExceptionList() throws Exception {
- List attributeNames = new ArrayList<JmxAttribute>();
+ List<JmxAttribute> attributeNames = new ArrayList<>();
attributeNames.add(new JmxAttribute("att1"));
attributeNames.add(new JmxAttribute("att2"));
attributeNames.add(new JmxAttribute("att3"));
@Test
public void testJmxAttributeValidationExceptionList2() throws Exception {
- List attributeNames = new ArrayList<JmxAttribute>();
+ List<JmxAttribute> attributeNames = new ArrayList<>();
attributeNames.add(new JmxAttribute("att1"));
attributeNames.add(new JmxAttribute("att2"));
attributeNames.add(new JmxAttribute("att3"));
JmxAttributeValidationException.checkCondition(false, "message", jmxAttribute);
}
- private void assertJmxEx(JmxAttributeValidationException e, String message, JmxAttribute... attrNames) {
+ private void assertJmxEx(final JmxAttributeValidationException e, final String message, final JmxAttribute... attrNames) {
assertEquals(message, e.getMessage());
assertEquals(Lists.newArrayList(attrNames), e.getAttributeNames());
}
package org.opendaylight.controller.config.api;
-import junit.framework.Assert;
-import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
+import org.junit.Test;
public class ModuleIdentifierTest {
String fact = new String("factory");
package org.opendaylight.controller.config.api;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.fail;
-import static org.junit.Assert.assertNotEquals;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.containsString;
-
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import com.google.common.collect.Lists;
import java.util.Map;
-
import org.junit.Assert;
import org.junit.Test;
public class ValidationExceptionTest {
- private String instance = "instance";
+ private final String instance = "instance";
private final ModuleIdentifier mi = new ModuleIdentifier("module", instance);
- private String instance2 = "instance2";
+ private final String instance2 = "instance2";
private final ModuleIdentifier mi2 = new ModuleIdentifier("module", instance2);
private final String message = "ex message";
private final Exception e = new IllegalStateException(message);
package org.opendaylight.controller.config.api.jmx;
+import java.util.ArrayList;
+import java.util.List;
+import javax.management.ObjectName;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import javax.management.ObjectName;
-import java.util.ArrayList;
-import java.util.List;
-
public class CommitStatusTest {
- List newInst = new ArrayList<ObjectName>();
- List reusedInst = new ArrayList<ObjectName>();
- List recreatedInst = new ArrayList<ObjectName>();
+ List<ObjectName> newInst = new ArrayList<>();
+ List<ObjectName> reusedInst = new ArrayList<>();
+ List<ObjectName> recreatedInst = new ArrayList<>();
@Before
public void setUp() throws Exception {
@Test
public void testNotEqual() throws Exception {
- List newInst2 = new ArrayList<ObjectName>();
- List reusedInst2 = new ArrayList<ObjectName>();
- List recreatedInst2 = new ArrayList<ObjectName>();
+ List<ObjectName> newInst2 = new ArrayList<>();
+ List<ObjectName> reusedInst2 = new ArrayList<>();
+ List<ObjectName> recreatedInst2 = new ArrayList<>();
newInst2.add(new ObjectName("first: key1 = value1"));
reusedInst2.add(new ObjectName("second: key = val"));
*/
package org.opendaylight.controller.config.api.jmx;
-import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
+import static org.junit.Assert.fail;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
-
import java.util.HashMap;
import java.util.Map;
import javax.management.ObjectName;
-import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.ModuleIdentifier;
assertPattern(on, pattern);
}
- private void assertPattern(ObjectName test, ObjectName pattern) {
+ private void assertPattern(final ObjectName test, final ObjectName pattern) {
assertTrue(pattern.isPattern());
assertTrue(pattern.apply(test));
}
}, IllegalArgumentException.class);
}
- private void assertFailure(Runnable test, Class<? extends Exception> ex) {
+ private void assertFailure(final Runnable test, final Class<? extends Exception> ex) {
try {
test.run();
} catch(Exception e) {
- Assert.assertTrue("Failed with wrong exception: " + Throwables.getStackTraceAsString(e),
+ assertTrue("Failed with wrong exception: " + Throwables.getStackTraceAsString(e),
e.getClass().isAssignableFrom(ex));
return;
}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ 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
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-artifacts</artifactId>
+ <version>0.3.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-manager</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-manager</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-module-archetype</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-netty-config</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-api</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-directory-adapter</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-directory-autodetect-adapter</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-directory-xml-adapter</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-feature-adapter</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-file-adapter</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-file-xml-adapter</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-plugin-parent</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-util</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-util</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>logback-config</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>logback-config-loader</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>netty-config-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>netty-event-executor-config</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>netty-threadgroup-config</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>netty-timer-config</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>shutdown-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>shutdown-impl</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>threadpool-config-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>threadpool-config-impl</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>yang-jmx-generator</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>yang-jmx-generator</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>yang-jmx-generator-plugin</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>yang-store-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>yang-store-impl</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>yang-test</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>features-config</artifactId>
+ <version>${project.version}</version>
+ <classifier>features</classifier>
+ <type>xml</type>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>features-config-netty</artifactId>
+ <version>${project.version}</version>
+ <classifier>features</classifier>
+ <type>xml</type>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>features-config-persister</artifactId>
+ <version>${project.version}</version>
+ <classifier>features</classifier>
+ <type>xml</type>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-netty-features</artifactId>
+ <version>${project.version}</version>
+ <classifier>features</classifier>
+ <type>xml</type>
+ <scope>runtime</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+</project>
+
*/
package org.opendaylight.controller.config.manager.impl.util;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-
-import javax.management.JMX;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
+import javax.management.JMX;
+import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
+import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
+import org.opendaylight.controller.config.spi.Module;
+import org.opendaylight.controller.config.spi.ModuleFactory;
public class InterfacesHelper {
}
- private static Set<Class<?>> getAllSuperInterfaces(Set<Class<?>> ifcs) {
+ private static Set<Class<?>> getAllSuperInterfaces(final Set<? extends Class<?>> ifcs) {
Set<Class<?>> interfaces = new HashSet<>(ifcs); // create copy to modify
// each interface can extend other interfaces
Set<Class<?>> result = new HashSet<>();
* Get interfaces that this class is derived from that are JMX interfaces.
*/
public static Set<Class<?>> getMXInterfaces(
- Class<? extends Module> configBeanClass) {
+ final Class<? extends Module> configBeanClass) {
Set<Class<?>> allInterfaces = getAllInterfaces(configBeanClass);
Set<Class<?>> result = new HashSet<>();
for (Class<?> clazz : allInterfaces) {
* annotation.
*/
public static Set<Class<?>> getServiceInterfaces(
- Class<? extends Module> configBeanClass) {
+ final Class<? extends Module> configBeanClass) {
Set<Class<?>> allInterfaces = getAllInterfaces(configBeanClass);
Set<Class<?>> result = new HashSet<>();
for (Class<?> clazz : allInterfaces) {
return result;
}
- public static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceClasses(Class<? extends Module> configBeanClass) {
+ public static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceClasses(final Class<? extends Module> configBeanClass) {
Set<Class<? extends AbstractServiceInterface>> foundGeneratedSIClasses = new HashSet<>();
for (Class<?> clazz : getAllInterfaces(configBeanClass)) {
* {@link org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation#osgiRegistrationType()}
*/
public static Set<Class<?>> getOsgiRegistrationTypes(
- Class<? extends Module> configBeanClass) {
+ final Class<? extends Module> configBeanClass) {
Set<Class<?>> serviceInterfaces = getServiceInterfaces(configBeanClass);
Set<Class<?>> result = new HashSet<>();
for (Class<?> clazz : serviceInterfaces) {
return result;
}
- public static Set<String> getQNames(Set<ServiceInterfaceAnnotation> siAnnotations) {
+ public static Set<String> getQNames(final Set<ServiceInterfaceAnnotation> siAnnotations) {
Set<String> qNames = new HashSet<>();
for (ServiceInterfaceAnnotation sia: siAnnotations) {
qNames.add(sia.value());
return Collections.unmodifiableSet(qNames);
}
- public static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(ModuleFactory factory) {
+ public static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(final ModuleFactory factory) {
Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces = Collections.unmodifiableSet(factory.getImplementedServiceIntefaces());
return getServiceInterfaceAnnotations(implementedServiceIntefaces);
}
- private static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces) {
+ private static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(final Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces) {
Set<Class<? extends AbstractServiceInterface>> inspected = getAllAbstractServiceInterfaceClasses(implementedServiceIntefaces);
Set<ServiceInterfaceAnnotation> result = new HashSet<>();
// SIs can form hierarchies, inspect superclass until it does not extend AbstractSI
}
static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceInterfaceClasses(
- Set<Class<? extends AbstractServiceInterface>> directlyImplementedAbstractSIs) {
+ final Set<Class<? extends AbstractServiceInterface>> directlyImplementedAbstractSIs) {
- Set<Class<?>> allInterfaces = getAllSuperInterfaces((Set) directlyImplementedAbstractSIs);
+ Set<Class<?>> allInterfaces = getAllSuperInterfaces(directlyImplementedAbstractSIs);
Set<Class<? extends AbstractServiceInterface>> result = new HashSet<>();
for(Class<?> ifc: allInterfaces){
if (AbstractServiceInterface.class.isAssignableFrom(ifc) &&
package org.opendaylight.controller.config.manager.impl.util;
import static com.google.common.base.Preconditions.checkNotNull;
-
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
}
@SafeVarargs
- public static <T> AutoCloseable registerService(BundleContext bundleContext, T service, Class<? super T> ... interfaces) {
+ public static <T> AutoCloseable registerService(final BundleContext bundleContext, final T service, final Class<? super T> ... interfaces) {
checkNotNull(service);
checkNotNull(interfaces);
List<AutoCloseable> autoCloseableList = new ArrayList<>();
};
}
- public static AutoCloseable wrap(final BundleTracker bundleTracker) {
+ public static AutoCloseable wrap(final BundleTracker<?> bundleTracker) {
checkNotNull(bundleTracker);
return new AutoCloseable() {
@Override
tested.put(moduleIdentifier,
mockedModule(),
- moduleFactory,
- maybeOldInternalInfo,
- transactionModuleJMXRegistration,
- isDefaultBean, mock(BundleContext.class));
+ moduleFactory,
+ maybeOldInternalInfo,
+ transactionModuleJMXRegistration,
+ isDefaultBean, mock(BundleContext.class));
}
private static Module mockedModule() {
package org.opendaylight.controller.config.manager.impl.osgi;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertSame;
-import static junit.framework.Assert.fail;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.Collections;
import javax.management.ObjectName;
import org.junit.Before;
package org.opendaylight.controller.config.manager.impl.osgi;
-import static junit.framework.Assert.fail;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-import static org.junit.matchers.JUnitMatchers.containsString;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-
import com.google.common.collect.Lists;
import java.util.Map;
import org.junit.Before;
@Mock
private BundleContext bundleContext;
private BundleContextBackedModuleFactoriesResolver resolver;
- private ServiceReference s1;
- private ServiceReference s2;
+ private ServiceReference<?> s1;
+ private ServiceReference<?> s2;
private ModuleFactory f1;
private ModuleFactory f2;
resolver = new BundleContextBackedModuleFactoriesResolver(bundleContext);
}
- private ModuleFactory getMockFactory(String name) {
+ private ModuleFactory getMockFactory(final String name) {
ModuleFactory mock = mock(ModuleFactory.class);
doReturn(name).when(mock).toString();
doReturn(name).when(mock).getImplementationName();
return mock;
}
- private ServiceReference getServiceRef() {
- ServiceReference mock = mock(ServiceReference.class);
+ private ServiceReference<?> getServiceRef() {
+ ServiceReference<?> mock = mock(ServiceReference.class);
doReturn("serviceRef").when(mock).toString();
final Bundle bundle = mock(Bundle.class);
doReturn(bundleContext).when(bundle).getBundleContext();
package org.opendaylight.controller.config.manager.impl.osgi;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.fail;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
-
import java.util.Dictionary;
import java.util.Set;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- doAnswer(new Answer() {
+ doAnswer(new Answer<Object>() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
return getClass().getClassLoader().loadClass((String) invocation.getArguments()[0]);
}
static class WrongConstructorTestingFactory extends TestingFactory {
- WrongConstructorTestingFactory(String randomParam) {
+ WrongConstructorTestingFactory(final String randomParam) {
}
}
package org.opendaylight.controller.config.manager.impl.osgi;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import java.util.Dictionary;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.controller.config.manager.impl.osgi.mapping.RefreshingSCPModuleInfoRegistry;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
-import java.util.*;
-
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
public class RefreshingSCPModuleInfoRegistryTest {
@Test
public void testConstructor() throws Exception {
doReturn("string").when(prov).toString();
BundleContext ctxt = mock(BundleContext.class);
- Dictionary dict = new Hashtable();
- ServiceRegistration servReg = mock(ServiceRegistration.class);
+ ServiceRegistration<?> servReg = mock(ServiceRegistration.class);
doReturn(servReg).when(ctxt).registerService(Mockito.any(Class.class), Mockito.any(SchemaContextProvider.class), Mockito.any(Dictionary.class));
doReturn(servReg).when(ctxt).registerService(Mockito.anyString(), Mockito.any(Object.class), Mockito.any(Dictionary.class));
RefreshingSCPModuleInfoRegistry scpreg = new RefreshingSCPModuleInfoRegistry(reg, prov, ctxt);
package org.opendaylight.controller.config.manager.impl.util;
import static org.junit.Assert.assertEquals;
-
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.util.Collections;
import java.util.HashSet;
input.add(clazz);
Set<Class<? extends AbstractServiceInterface>> result = InterfacesHelper.getAllAbstractServiceInterfaceClasses(input);
- Set<Class<?>> expected = Sets.newHashSet((Class<?>) TestingScheduledThreadPoolServiceInterface.class,
+ Set<Class<?>> expected = ImmutableSet.of((Class<?>) TestingScheduledThreadPoolServiceInterface.class,
TestingThreadPoolServiceInterface.class
);
assertEquals(expected, result);
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
OsgiRegistrationUtil.wrap(serviceReg).close();
verify(serviceReg).unregister();
- final BundleTracker tracker = mock(BundleTracker.class);
+ final BundleTracker<?> tracker = mock(BundleTracker.class);
doNothing().when(tracker).close();
OsgiRegistrationUtil.wrap(tracker).close();
verify(tracker).close();
}
private ServiceRegistration<?> mockServiceRegistration() {
- ServiceRegistration mock = mock(ServiceRegistration.class);
+ ServiceRegistration<?> mock = mock(ServiceRegistration.class);
doNothing().when(mock).unregister();
return mock;
}
*/
package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
-import com.google.common.collect.Sets;
+import com.google.common.collect.ImmutableSet;
+import java.util.HashSet;
+import java.util.Set;
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.controller.config.api.DependencyResolverFactory;
import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory {
public static final String NAME = "scheduled";
- private static Set<Class<? extends AbstractServiceInterface>> ifc = Collections.unmodifiableSet(Sets.newHashSet(
+ private static Set<Class<? extends AbstractServiceInterface>> ifc = ImmutableSet.of(
(Class<? extends AbstractServiceInterface>) TestingScheduledThreadPoolServiceInterface.class,
- TestingThreadPoolServiceInterface.class));
+ TestingThreadPoolServiceInterface.class);
@Override
public boolean isModuleImplementingServiceInterface(
- Class<? extends AbstractServiceInterface> serviceInterface) {
+ final Class<? extends AbstractServiceInterface> serviceInterface) {
return ifc.contains(serviceInterface);
}
}
@Override
- public Module createModule(String instanceName,
- DependencyResolver dependencyResolver, BundleContext bundleContext) {
+ public Module createModule(final String instanceName,
+ final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME,
instanceName), null, null);
}
@Override
- public Module createModule(String instanceName,
- DependencyResolver dependencyResolver, DynamicMBeanWithInstance old, BundleContext bundleContext)
+ public Module createModule(final String instanceName,
+ final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext)
throws Exception {
TestingScheduledThreadPoolImpl oldInstance;
try {
}
@Override
- public Set<Module> getDefaultModules(DependencyResolverFactory dependencyResolverFactory, BundleContext bundleContext) {
+ public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
return new HashSet<Module>();
}
*/
package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.test;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
-
import javax.annotation.Nullable;
import javax.management.DynamicMBean;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-
import org.junit.Test;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPConfigMXBean;
import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool
- .TestingScheduledThreadPoolModuleFactory;
+import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
public class TwoInterfacesExportTest extends AbstractScheduledTest {
- private void assertExists(String moduleName, String instanceName)
+ private void assertExists(final String moduleName, final String instanceName)
throws Exception {
assertExists(null, moduleName, instanceName);
}
- private void assertExists(@Nullable ConfigTransactionJMXClient transaction,
- String moduleName, String instanceName)
+ private void assertExists(@Nullable final ConfigTransactionJMXClient transaction,
+ final String moduleName, final String instanceName)
throws InstanceNotFoundException {
if (transaction != null) {
transaction.lookupConfigBean(moduleName, instanceName);
}
}
- private void assertNotExists(String moduleName, String instanceName) {
+ private void assertNotExists(final String moduleName, final String instanceName) {
assertNotExists(null, moduleName, instanceName);
}
private void assertNotExists(
- @Nullable ConfigTransactionJMXClient transaction,
- String moduleName, String instanceName) {
+ @Nullable final ConfigTransactionJMXClient transaction,
+ final String moduleName, final String instanceName) {
if (transaction != null) {
try {
*/
package org.opendaylight.controller.config.manager.testingservices.threadpool;
-import com.google.common.collect.Sets;
+import com.google.common.collect.ImmutableSet;
+import java.util.HashSet;
+import java.util.Set;
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.controller.config.api.DependencyResolverFactory;
import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory implements ModuleFactory {
public static final String NAME = "fixed";
- private static Set<Class<? extends AbstractServiceInterface>> ifc = Collections.unmodifiableSet(Sets.newHashSet(
+ private static final Set<Class<? extends AbstractServiceInterface>> ifc = ImmutableSet.of(
(Class<? extends AbstractServiceInterface>) ModifiableThreadPoolServiceInterface.class,
- TestingThreadPoolServiceInterface.class));
+ TestingThreadPoolServiceInterface.class);
@Override
public String getImplementationName() {
}
@Override
- public TestingFixedThreadPoolModule createModule(String instanceName,
- DependencyResolver dependencyResolver, BundleContext bundleContext) {
+ public TestingFixedThreadPoolModule createModule(final String instanceName,
+ final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
return new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME,
instanceName), null, null);
}
@Override
- public Module createModule(String instanceName,
- DependencyResolver dependencyResolver, DynamicMBeanWithInstance old, BundleContext bundleContext)
+ public Module createModule(final String instanceName,
+ final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext)
throws Exception {
int threadCount = (Integer) old.getAttribute("ThreadCount");
// is the instance compatible?
@Override
public boolean isModuleImplementingServiceInterface(
- Class<? extends AbstractServiceInterface> serviceInterface) {
+ final Class<? extends AbstractServiceInterface> serviceInterface) {
return ifc.contains(serviceInterface);
}
@Override
- public Set<Module> getDefaultModules(DependencyResolverFactory dependencyResolverFactory, BundleContext bundleContext) {
+ public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
return new HashSet<Module>();
}
<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
<!--
Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-subsystem</artifactId>
- <version>0.3.0-SNAPSHOT</version>
- </parent>
- <artifactId>config-netty-config</artifactId>
- <description>Configuration files for sal-rest-connector</description>
- <packaging>jar</packaging>
- <build>
- <plugins>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-artifacts</id>
- <goals>
- <goal>attach-artifact</goal>
- </goals>
- <phase>package</phase>
- <configuration>
- <artifacts>
- <artifact>
- <file>${project.build.directory}/classes/initial/00-netty.xml</file>
- <type>xml</type>
- <classifier>config</classifier>
- </artifact>
- </artifacts>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-subsystem</artifactId>
+ <version>0.3.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>config-netty-config</artifactId>
+ <description>Configuration files for sal-rest-connector</description>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-artifacts</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>${project.build.directory}/classes/initial/00-netty.xml</file>
+ <type>xml</type>
+ <classifier>config</classifier>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
</project>
*/
package org.opendaylight.controller.config.persist.storage.directory.xml;
+import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Optional;
import com.google.common.io.Files;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
-
-import static com.google.common.base.Preconditions.checkArgument;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
+import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class XmlDirectoryPersister implements Persister {
- private static final Logger logger = LoggerFactory.getLogger(XmlDirectoryPersister.class);
+ private static final Logger LOG = LoggerFactory.getLogger(XmlDirectoryPersister.class);
private final File storage;
private final Optional<FilenameFilter> extensionsFilter;
/**
* Creates XmlDirectoryPersister that picks up all files in specified folder
*/
- public XmlDirectoryPersister(File storage) {
+ public XmlDirectoryPersister(final File storage) {
this(storage, Optional.<FilenameFilter>absent());
}
/**
* Creates XmlDirectoryPersister that picks up files only with specified file extension
*/
- public XmlDirectoryPersister(File storage, Set<String> fileExtensions) {
+ public XmlDirectoryPersister(final File storage, final Set<String> fileExtensions) {
this(storage, Optional.of(getFilter(fileExtensions)));
}
- private XmlDirectoryPersister(File storage, Optional<FilenameFilter> extensionsFilter) {
+ private XmlDirectoryPersister(final File storage, final Optional<FilenameFilter> extensionsFilter) {
checkArgument(storage.exists() && storage.isDirectory(), "Storage directory does not exist: " + storage);
this.storage = storage;
this.extensionsFilter = extensionsFilter;
}
@Override
- public void persistConfig(ConfigSnapshotHolder holder) throws IOException {
+ public void persistConfig(final ConfigSnapshotHolder holder) throws IOException {
throw new UnsupportedOperationException("This adapter is read only. Please set readonly=true on " + getClass());
}
List<File> sortedFiles = new ArrayList<>(Arrays.asList(filesArray));
Collections.sort(sortedFiles);
// combine all found files
- logger.debug("Reading files in following order: {}", sortedFiles);
+ LOG.debug("Reading files in following order: {}", sortedFiles);
List<ConfigSnapshotHolder> result = new ArrayList<>();
for (File file : sortedFiles) {
- logger.trace("Adding file '{}' to combined result", file);
+ LOG.trace("Adding file '{}' to combined result", file);
Optional<ConfigSnapshotHolder> h = fromXmlSnapshot(file);
// Ignore non valid snapshot
if(h.isPresent() == false) {
return result;
}
- private Optional<ConfigSnapshotHolder> fromXmlSnapshot(File file) {
+ private Optional<ConfigSnapshotHolder> fromXmlSnapshot(final File file) {
try {
return Optional.of(loadLastConfig(file));
} catch (JAXBException e) {
// In case of parse error, issue a warning, ignore and continue
- logger.warn(
+ LOG.warn(
"Unable to parse configuration snapshot from {}. Initial config from {} will be IGNORED in this run. " +
"Note that subsequent config files may fail due to this problem. " +
"Xml markup in this file needs to be fixed, for detailed information see enclosed exception.",
return Optional.absent();
}
- public static ConfigSnapshotHolder loadLastConfig(File file) throws JAXBException {
+ public static ConfigSnapshotHolder loadLastConfig(final File file) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(ConfigSnapshot.class);
Unmarshaller um = jaxbContext.createUnmarshaller();
return new FilenameFilter() {
@Override
- public boolean accept(File dir, String name) {
+ public boolean accept(final File dir, final String name) {
String ext = Files.getFileExtension(name);
return fileExtensions.contains(ext);
}
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
+import java.io.File;
+import java.util.Set;
import org.opendaylight.controller.config.persist.api.Persister;
import org.opendaylight.controller.config.persist.api.PropertiesProvider;
import org.opendaylight.controller.config.persist.api.StorageAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.util.Set;
-
/**
* StorageAdapter that retrieves initial configuration from a directory. If multiple files are present, snapshot and
* required capabilities will be merged together. Writing to this persister is not supported.
*/
public class XmlDirectoryStorageAdapter implements StorageAdapter {
- private static final Logger logger = LoggerFactory.getLogger(XmlDirectoryStorageAdapter.class);
+ private static final Logger LOG = LoggerFactory.getLogger(XmlDirectoryStorageAdapter.class);
public static final String DIRECTORY_STORAGE_PROP = "directoryStorage";
public static final String INCLUDE_EXT_PROP = "includeExtensions";
@Override
- public Persister instantiate(PropertiesProvider propertiesProvider) {
+ public Persister instantiate(final PropertiesProvider propertiesProvider) {
String fileStorageProperty = propertiesProvider.getProperty(DIRECTORY_STORAGE_PROP);
Preconditions.checkNotNull(fileStorageProperty, "Unable to find " + propertiesProvider.getFullKeyForReporting(DIRECTORY_STORAGE_PROP));
File storage = new File(fileStorageProperty);
String fileExtensions = propertiesProvider.getProperty(INCLUDE_EXT_PROP);
- logger.debug("Using storage: {}", storage);
+ LOG.debug("Using storage: {}", storage);
if(fileExtensions != null) {
- logger.debug("Using extensions: {}", fileExtensions);
+ LOG.debug("Using extensions: {}", fileExtensions);
return new XmlDirectoryPersister(storage, splitExtensions(fileExtensions));
} else {
return new XmlDirectoryPersister(storage);
}
}
- private Set<String> splitExtensions(String fileExtensions) {
+ private Set<String> splitExtensions(final String fileExtensions) {
return Sets.newHashSet(Splitter.on(EXTENSIONS_SEPARATOR).trimResults().omitEmptyStrings()
.split(fileExtensions));
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
+import com.google.common.base.Optional;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
-
import org.junit.Test;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
import org.opendaylight.controller.config.persist.api.Persister;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
-import com.google.common.base.Optional;
-
public class DirectoryStorageAdapterTest {
+ private static final Logger LOG = LoggerFactory.getLogger(DirectoryStorageAdapterTest.class);
Persister tested;
- Logger logger = LoggerFactory.getLogger(DirectoryStorageAdapterTest.class.toString());
- private Persister instantiatePersisterFromAdapter(File file, Optional<String> extensions){
+ private Persister instantiatePersisterFromAdapter(final File file, final Optional<String> extensions){
PropertiesProviderTest pp = new PropertiesProviderTest();
pp.addProperty(XmlDirectoryStorageAdapter.DIRECTORY_STORAGE_PROP,file.getPath());
if(extensions.isPresent()) {
return dsa.instantiate(pp);
}
- private Persister instantiatePersisterFromAdapter(File file){
+ private Persister instantiatePersisterFromAdapter(final File file){
return instantiatePersisterFromAdapter(file, Optional.<String>absent());
}
}
}
- private File getFolder(String folderName) {
+ private File getFolder(final String folderName) {
File result = new File(("src/test/resources/" +
folderName).replace("/", File.separator));
assertTrue(result + " is not a directory", result.isDirectory());
File folder = getFolder("oneFile");
tested = instantiatePersisterFromAdapter(folder, Optional.of("xml"));
- logger.info("Testing : " + tested.toString());
+ LOG.info("Testing : {}", tested);
List<ConfigSnapshotHolder> results = tested.loadLastConfigs();
assertEquals(1, results.size());
ConfigSnapshotHolder result = results.get(0);
public void testOneFileWrongExtension() throws Exception {
File folder = getFolder("oneFile");
tested = instantiatePersisterFromAdapter(folder, Optional.of("aa, bb"));
- logger.info("Testing : " + tested.toString());
+ LOG.info("Testing : {}", tested);
}
- private void assertResult(ConfigSnapshotHolder result, String s, String... caps) throws SAXException, IOException {
+ private void assertResult(final ConfigSnapshotHolder result, final String s, final String... caps) throws SAXException, IOException {
assertXMLEqual(s, result.getConfigSnapshot());
int i = 0;
for (String capFromSnapshot : result.getCapabilities()) {
public void testTwoFilesAllExtensions() throws Exception {
File folder = getFolder("twoFiles");
tested = instantiatePersisterFromAdapter(folder);
- logger.info("Testing : " + tested.toString());
+ LOG.info("Testing : {}", tested);
List<ConfigSnapshotHolder> results = tested.loadLastConfigs();
assertEquals(2, results.size());
public void testTwoFilesTwoExtensions() throws Exception {
File folder = getFolder("twoFiles");
tested = instantiatePersisterFromAdapter(folder, Optional.of("xml, xml2"));
- logger.info("Testing : " + tested.toString());
+ LOG.info("Testing : {}", tested);
assertEquals(2, tested.loadLastConfigs().size());
}
public void testTwoFilesOnlyOneExtension() throws Exception {
File folder = getFolder("twoFiles");
tested = instantiatePersisterFromAdapter(folder, Optional.of("xml"));
- logger.info("Testing : " + tested.toString());
+ LOG.info("Testing : ", tested);
List<ConfigSnapshotHolder> results = tested.loadLastConfigs();
assertEquals(1, results.size());
public void testTwoFilesOneInvalid() throws Exception {
File folder = getFolder("twoFiles_corrupt");
tested = instantiatePersisterFromAdapter(folder, Optional.of("xml"));
- logger.info("Testing : " + tested.toString());
+ LOG.info("Testing : {}", tested);
List<ConfigSnapshotHolder> results = tested.loadLastConfigs();
assertEquals(1, results.size());
import org.slf4j.LoggerFactory;
public class ConfigPusherCustomizer implements ServiceTrackerCustomizer<ConfigPusher, ConfigPusher>, AutoCloseable {
- private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPusherCustomizer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherCustomizer.class);
private ConfigFeaturesListener configFeaturesListener = null;
private FeatureServiceCustomizer featureServiceCustomizer = null;
private ServiceTracker<FeaturesService,FeaturesService> fsst = null;
@Override
public ConfigPusher addingService(ServiceReference<ConfigPusher> configPusherServiceReference) {
- LOGGER.trace("Got ConfigPusherCustomizer.addingService {}", configPusherServiceReference);
+ LOG.trace("Got ConfigPusherCustomizer.addingService {}", configPusherServiceReference);
BundleContext bc = configPusherServiceReference.getBundle().getBundleContext();
ConfigPusher cpService = bc.getService(configPusherServiceReference);
featureServiceCustomizer = new FeatureServiceCustomizer(cpService);
while(true) {
try {
if(!interuppted) {
- if(toInstall.isEmpty()) {
- event = queue.take();
- } else {
- event = queue.poll(POLL_TIME, TimeUnit.MILLISECONDS);
- }
- if(event != null && event.getFeature() !=null) {
- processFeatureEvent(event,toInstall);
- }
+ if(toInstall.isEmpty()) {
+ event = queue.take();
+ } else {
+ event = queue.poll(POLL_TIME, TimeUnit.MILLISECONDS);
+ }
+ if(event != null && event.getFeature() !=null) {
+ processFeatureEvent(event,toInstall);
+ }
} else if(toInstall.isEmpty()) {
LOGGER.error("ConfigPushingRunnable - exiting");
return;
*/
package org.opendaylight.controller.configpusherfeature.internal;
+import com.google.common.collect.LinkedHashMultimap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
-
import org.apache.karaf.features.Feature;
import org.apache.karaf.features.FeaturesService;
import org.opendaylight.controller.config.persist.api.ConfigPusher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.collect.LinkedHashMultimap;
-
/*
* Simple class to push configs to the config subsystem from Feature's configfiles
*/
public class FeatureConfigPusher {
- private static final Logger LOGGER = LoggerFactory.getLogger(FeatureConfigPusher.class);
+ private static final Logger LOG = LoggerFactory.getLogger(FeatureConfigPusher.class);
private static final int MAX_RETRIES=100;
private static final int RETRY_PAUSE_MILLIS=1;
private FeaturesService featuresService = null;
/*
* @param p - ConfigPusher to push ConfigSnapshotHolders
*/
- public FeatureConfigPusher(ConfigPusher p, FeaturesService f) {
+ public FeatureConfigPusher(final ConfigPusher p, final FeaturesService f) {
pusher = p;
featuresService = f;
}
* If a Feature is not in the returned LinkedHashMultimap then we couldn't push its configs
* (Ususally because it was not yet installed)
*/
- public LinkedHashMultimap<Feature,FeatureConfigSnapshotHolder> pushConfigs(List<Feature> features) throws Exception, InterruptedException {
+ public LinkedHashMultimap<Feature,FeatureConfigSnapshotHolder> pushConfigs(final List<Feature> features) throws Exception, InterruptedException {
LinkedHashMultimap<Feature,FeatureConfigSnapshotHolder> pushedFeatures = LinkedHashMultimap.create();
for(Feature feature: features) {
LinkedHashSet<FeatureConfigSnapshotHolder> configSnapShots = pushConfig(feature);
return pushedFeatures;
}
- private LinkedHashSet<FeatureConfigSnapshotHolder> pushConfig(Feature feature) throws Exception, InterruptedException {
+ private LinkedHashSet<FeatureConfigSnapshotHolder> pushConfig(final Feature feature) throws Exception, InterruptedException {
LinkedHashSet<FeatureConfigSnapshotHolder> configs = new LinkedHashSet<FeatureConfigSnapshotHolder>();
if(isInstalled(feature)) {
ChildAwareFeatureWrapper wrappedFeature = new ChildAwareFeatureWrapper(feature,featuresService);
return configs;
}
- private boolean isInstalled(Feature feature) {
+ private boolean isInstalled(final Feature feature) {
for(int retries=0;retries<MAX_RETRIES;retries++) {
try {
List<Feature> installedFeatures = Arrays.asList(featuresService.listInstalledFeatures());
if(installedFeatures.contains(feature)) {
return true;
} else {
- LOGGER.warn("Karaf featuresService.listInstalledFeatures() has not yet finished installing feature (retry {}) {} {}",retries,feature.getName(),feature.getVersion());
+ LOG.warn("Karaf featuresService.listInstalledFeatures() has not yet finished installing feature (retry {}) {} {}",retries,feature.getName(),feature.getVersion());
}
} catch (Exception e) {
if(retries < MAX_RETRIES) {
- LOGGER.warn("Karaf featuresService.listInstalledFeatures() has thrown an exception, retry {}, Exception {}", retries,e);
+ LOG.warn("Karaf featuresService.listInstalledFeatures() has thrown an exception, retry {}", retries, e);
} else {
- LOGGER.error("Giving up on Karaf featuresService.listInstalledFeatures() which has thrown an exception, retry {}, Exception {}", retries,e);
+ LOG.error("Giving up on Karaf featuresService.listInstalledFeatures() which has thrown an exception, retry {}", retries, e);
throw e;
}
}
throw new IllegalStateException(e1);
}
}
- LOGGER.error("Giving up (after {} retries) on Karaf featuresService.listInstalledFeatures() which has not yet finished installing feature {} {}",MAX_RETRIES,feature.getName(),feature.getVersion());
+ LOG.error("Giving up (after {} retries) on Karaf featuresService.listInstalledFeatures() which has not yet finished installing feature {} {}",MAX_RETRIES,feature.getName(),feature.getVersion());
return false;
}
- private LinkedHashSet<FeatureConfigSnapshotHolder> pushConfig(LinkedHashSet<FeatureConfigSnapshotHolder> configs) throws InterruptedException {
+ private LinkedHashSet<FeatureConfigSnapshotHolder> pushConfig(final LinkedHashSet<FeatureConfigSnapshotHolder> configs) throws InterruptedException {
LinkedHashSet<FeatureConfigSnapshotHolder> configsToPush = new LinkedHashSet<FeatureConfigSnapshotHolder>(configs);
configsToPush.removeAll(pushedConfigs);
if(!configsToPush.isEmpty()) {
@Override
public String toString() {
- StringBuilder b = new StringBuilder();
- Path p = Paths.get(fileInfo.getFinalname());
- b.append(p.getFileName())
- .append("(")
- .append(getCauseFeature())
- .append(",")
- .append(getFeature())
- .append(")");
- return b.toString();
-
+ StringBuilder b = new StringBuilder();
+ Path p = Paths.get(fileInfo.getFinalname());
+ b.append(p.getFileName())
+ .append("(")
+ .append(getCauseFeature())
+ .append(",")
+ .append(getFeature())
+ .append(")");
+ return b.toString();
}
@Override
package org.opendaylight.controller.config.persist.storage.file.xml;
-import static junit.framework.Assert.assertFalse;
+import static org.junit.Assert.assertFalse;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-
+import com.google.common.base.Charsets;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
-
-import junit.framework.Assert;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
import org.opendaylight.controller.config.persist.test.PropertiesProviderTest;
-import com.google.common.base.Charsets;
-
public class FileStorageAdapterTest {
private static int i;
@Before
public void setUp() throws Exception {
file = Files.createTempFile("testFilePersist", ".txt").toFile();
- if (!file.exists())
+ if (!file.exists()) {
return;
+ }
com.google.common.io.Files.write("", file, Charsets.UTF_8);
i = 1;
}
storage.persistConfig(holder);
- Assert.assertEquals(storage.toString().replace("\\","/"),"XmlFileStorageAdapter [storage="+NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE+"]");
+ assertEquals(storage.toString().replace("\\","/"),"XmlFileStorageAdapter [storage="+NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE+"]");
delete(new File(NON_EXISTENT_DIRECTORY));
}
@Test
storage.setNumberOfBackups(Integer.MAX_VALUE);
List<ConfigSnapshotHolder> last = storage.loadLastConfigs();
- Assert.assertEquals(createCaps(), last.get(0).getCapabilities());
+ assertEquals(createCaps(), last.get(0).getCapabilities());
}
private SortedSet<String> createCaps() {
@Test
public void testNoLastConfig() throws Exception {
File file = Files.createTempFile("testFilePersist", ".txt").toFile();
- if (!file.exists())
+ if (!file.exists()) {
return;
+ }
XmlFileStorageAdapter storage = new XmlFileStorageAdapter();
storage.setFileStorage(file);
return "<config>" + i++ + "</config>";
}
- private void delete(File f) throws IOException {
+ private void delete(final File f) throws IOException {
if (f.isDirectory()) {
- for (File c : f.listFiles())
+ for (File c : f.listFiles()) {
delete(c);
+ }
}
- if (!f.delete())
+ if (!f.delete()) {
throw new FileNotFoundException("Failed to delete file: " + f);
+ }
}
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
*/
package org.opendaylight.controller.config.util;
+import static org.hamcrest.CoreMatchers.hasItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.hasItem;
-
+import com.google.common.collect.Sets;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
-
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.ConfigRegistry;
-import com.google.common.collect.Sets;
-
public class ConfigRegistryClientsTest {
private TestingConfigRegistry testingRegistry;
assertEquals(Sets.newHashSet(TestingConfigRegistry.run2, TestingConfigRegistry.run1, TestingConfigRegistry.run3), jmxLookup);
}
- private Set<ObjectName> lookupRuntimeBeans(ConfigRegistryClient client)
+ private Set<ObjectName> lookupRuntimeBeans(final ConfigRegistryClient client)
throws Exception {
Set<ObjectName> beans = client.lookupRuntimeBeans();
for (ObjectName on : beans) {
}
private Set<ObjectName> clientLookupRuntimeBeansWithModuleAndInstance(
- ConfigRegistryClient client, String moduleName, String instanceName) {
+ final ConfigRegistryClient client, final String moduleName, final String instanceName) {
Set<ObjectName> beans = client.lookupRuntimeBeans(moduleName, instanceName);
if (beans.size() > 0) {
assertEquals("RuntimeBean",
assertThat(clientLookupServiceInterfaceNames(testingRegistryON), hasItem(TestingConfigRegistry.serviceQName2));
}
- private Set<String> clientLookupServiceInterfaceNames(ObjectName client) throws InstanceNotFoundException{
+ private Set<String> clientLookupServiceInterfaceNames(final ObjectName client) throws InstanceNotFoundException{
return jmxRegistryClient.lookupServiceInterfaceNames(client);
}
public void testLookupConfigBeans2() throws Exception {
Method method = LookupRegistry.class.getMethod("lookupConfigBeans",
String.class, String.class);
- Object[] args = new Object[] { TestingConfigRegistry.moduleName1,
- TestingConfigRegistry.instName1 };
+ Object[] args = new Object[] { TestingConfigRegistry.moduleName1, TestingConfigRegistry.instName1 };
test(method, args);
}
public void testLookupConfigBean() throws Exception {
Method method = LookupRegistry.class.getMethod("lookupConfigBean",
String.class, String.class);
- Object[] args = new Object[] { TestingConfigRegistry.moduleName1,
- TestingConfigRegistry.instName1 };
+ Object[] args = new Object[] { TestingConfigRegistry.moduleName1, TestingConfigRegistry.instName1 };
test(method, args);
}
// check logs
String[] expectedLogs = new String[] {
- "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.LogbackConfigurationLoaderTest: LOGBACK ready -> about to use it",
- "LoggingEvent -> [TRACE] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: tracing",
- "LoggingEvent -> [DEBUG] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: debugging",
- "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: infoing",
- "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: warning",
- "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: erroring",
- "LoggingEvent -> [DEBUG] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: debugging",
- "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: infoing",
- "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: warning",
- "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: erroring",
- "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: infoing",
- "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: warning",
- "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: erroring",
- "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Warner: warning",
- "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Warner: erroring",
- "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Errorer: erroring"
-
+ "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.LogbackConfigurationLoaderTest: LOGBACK ready -> about to use it",
+ "LoggingEvent -> [TRACE] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: tracing",
+ "LoggingEvent -> [DEBUG] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: debugging",
+ "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: infoing",
+ "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: warning",
+ "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: erroring",
+ "LoggingEvent -> [DEBUG] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: debugging",
+ "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: infoing",
+ "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: warning",
+ "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: erroring",
+ "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: infoing",
+ "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: warning",
+ "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: erroring",
+ "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Warner: warning",
+ "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Warner: erroring",
+ "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Errorer: erroring"
};
List<String> logSnapshot = new ArrayList<>(TestAppender.getLogRecord());
-<?xml version="1.0" encoding="UTF-8"?>\r
-<configuration debug="true">\r
-\r
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">\r
- <encoder>\r
- <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n</pattern>\r
- </encoder>\r
- </appender>\r
-\r
- <root level="INFO">\r
- <appender-ref ref="STDOUT" />\r
- </root>\r
-\r
- <!-- Base log level -->\r
- <logger name="org.opendaylight.controller.logback.config.loader" level="DEBUG"/>\r
-\r
-</configuration>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration debug="true">
+
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n</pattern>
+ </encoder>
+ </appender>
+
+ <root level="INFO">
+ <appender-ref ref="STDOUT" />
+ </root>
+
+ <!-- Base log level -->
+ <logger name="org.opendaylight.controller.logback.config.loader" level="DEBUG"/>
+
+</configuration>
-<?xml version="1.0" encoding="UTF-8"?>\r
-<configuration debug="false">\r
-\r
- <appender name="TEST" class="org.opendaylight.controller.logback.config.loader.test.TestAppender"/>\r
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">\r
- <encoder>\r
- <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n</pattern>\r
- </encoder>\r
- </appender>\r
-\r
- <root level="INFO">\r
- <appender-ref ref="TEST" />\r
- <appender-ref ref="STDOUT" />\r
- </root>\r
-\r
- <!-- Base log level -->\r
- <logger name="org.opendaylight.controller.logback.config.loader" level="INFO"/>\r
-\r
-</configuration>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration debug="false">
+
+ <appender name="TEST" class="org.opendaylight.controller.logback.config.loader.test.TestAppender"/>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n</pattern>
+ </encoder>
+ </appender>
+
+ <root level="INFO">
+ <appender-ref ref="TEST" />
+ <appender-ref ref="STDOUT" />
+ </root>
+
+ <!-- Base log level -->
+ <logger name="org.opendaylight.controller.logback.config.loader" level="INFO"/>
+
+</configuration>
-<?xml version="1.0" encoding="UTF-8"?>\r
-<configuration debug="false">\r
-\r
- <!-- Base log level -->\r
- <logger name="org.opendaylight.controller.logback.config.loader" level="DEBUG"/>\r
- <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Tracer" level="TRACE"/>\r
-<!-- <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Debugger" level="DEBUG"/> -->\r
- <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Informer" level="DEBUG"/>\r
- <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Warner" level="ERROR"/>\r
- <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Errorer" level="ERROR"/>\r
-\r
-</configuration>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration debug="false">
+
+ <!-- Base log level -->
+ <logger name="org.opendaylight.controller.logback.config.loader" level="DEBUG"/>
+ <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Tracer" level="TRACE"/>
+<!-- <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Debugger" level="DEBUG"/> -->
+ <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Informer" level="DEBUG"/>
+ <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Warner" level="ERROR"/>
+ <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Errorer" level="ERROR"/>
+
+</configuration>
-<?xml version="1.0" encoding="UTF-8"?>\r
-<configuration debug="false">\r
- <root level="INFO">\r
- <appender-ref ref="TEST" />\r
- </root>\r
-\r
- <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Informer" level="INFO"/>\r
- <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Warner" level="WARN"/>\r
-\r
- <logger name="org.opendaylight.controller.logback.config.loader.test.LogbackConfigurationLoaderTest" level="TRACE"/>\r
-</configuration>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration debug="false">
+ <root level="INFO">
+ <appender-ref ref="TEST" />
+ </root>
+
+ <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Informer" level="INFO"/>
+ <logger name="org.opendaylight.controller.logback.config.loader.test.logwork.Warner" level="WARN"/>
+
+ <logger name="org.opendaylight.controller.logback.config.loader.test.LogbackConfigurationLoaderTest" level="TRACE"/>
+</configuration>
*/
package org.opendaylight.controller.config.yang.logback.config;
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.slf4j.LoggerFactory;
-
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
-
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.slf4j.LoggerFactory;
/**
* Implementation of {@link ContextSetter}. Resets running logback
private final LogbackStatusListener statusListener;
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ContextSetterImpl.class);
- public ContextSetterImpl(LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
+ public ContextSetterImpl(final LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
statusListener = new LogbackStatusListener(rootRuntimeBeanRegistratorWrapper);
statusListener.register();
}
- public void updateContext(LogbackModule module) {
+ @Override
+ public void updateContext(final LogbackModule module) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
List<ch.qos.logback.classic.Logger> loggersBefore = context.getLoggerList();
createLoggers(context, module, Sets.newHashSet(loggersBefore));
}
- private Map<String, Appender<ILoggingEvent>> createConsoleAppenders(LoggerContext context, LogbackModule module) {
+ private Map<String, Appender<ILoggingEvent>> createConsoleAppenders(final LoggerContext context, final LogbackModule module) {
Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
for (ConsoleAppenderTO appender : module.getConsoleAppenderTO()) {
Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false,
"Duplicate appender name %s", appender.getName());
- ch.qos.logback.core.ConsoleAppender app = new ch.qos.logback.core.ConsoleAppender();
+ ch.qos.logback.core.ConsoleAppender<ILoggingEvent> app = new ch.qos.logback.core.ConsoleAppender<>();
app.setContext(context);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(context);
return appendersMap;
}
- private void createLoggers(LoggerContext context, LogbackModule module,
- Set<ch.qos.logback.classic.Logger> loggersBefore) {
+ private void createLoggers(final LoggerContext context, final LogbackModule module,
+ final Set<ch.qos.logback.classic.Logger> loggersBefore) {
Map<String, Appender<ILoggingEvent>> appendersMap = getAppenders(module, context);
}
}
- private void addNewAppenders(Map<String, Appender<ILoggingEvent>> appendersMap, LoggerTO logger,
- ch.qos.logback.classic.Logger logbackLogger, Optional<Set<Appender<ILoggingEvent>>> appendersBefore) {
+ private void addNewAppenders(final Map<String, Appender<ILoggingEvent>> appendersMap, final LoggerTO logger,
+ final ch.qos.logback.classic.Logger logbackLogger, final Optional<Set<Appender<ILoggingEvent>>> appendersBefore) {
if (logger.getAppenders() != null) {
for (String appenderName : logger.getAppenders()) {
if (appendersMap.containsKey(appenderName)) {
}
}
- private void removeBeforeAppenders(Set<ch.qos.logback.classic.Logger> loggersBefore, LoggerTO logger,
- ch.qos.logback.classic.Logger logbackLogger, Optional<Set<Appender<ILoggingEvent>>> appendersBefore) {
+ private void removeBeforeAppenders(final Set<ch.qos.logback.classic.Logger> loggersBefore, final LoggerTO logger,
+ final ch.qos.logback.classic.Logger logbackLogger, final Optional<Set<Appender<ILoggingEvent>>> appendersBefore) {
if (appendersBefore.isPresent()) {
for (Appender<ILoggingEvent> appenderBefore : appendersBefore.get()) {
logbackLogger.detachAppender(appenderBefore);
}
}
- private Optional<Set<Appender<ILoggingEvent>>> getAppendersBefore(Set<ch.qos.logback.classic.Logger> loggersBefore,
- ch.qos.logback.classic.Logger logbackLogger) {
+ private Optional<Set<Appender<ILoggingEvent>>> getAppendersBefore(final Set<ch.qos.logback.classic.Logger> loggersBefore,
+ final ch.qos.logback.classic.Logger logbackLogger) {
if (loggersBefore.contains(logbackLogger)) {
Iterator<Appender<ILoggingEvent>> appenderIt = logbackLogger.iteratorForAppenders();
Set<Appender<ILoggingEvent>> appendersBefore = Sets.newHashSet();
}
- private Map<String, Appender<ILoggingEvent>> getAppenders(LogbackModule module, LoggerContext context) {
+ private Map<String, Appender<ILoggingEvent>> getAppenders(final LogbackModule module, final LoggerContext context) {
Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
addAllAppenders(appendersMap, createRollingAppenders(context, module));
addAllAppenders(appendersMap, createFileAppenders(context, module));
return appendersMap;
}
- private void addAllAppenders(Map<String, Appender<ILoggingEvent>> allAppenders,
- Map<String, Appender<ILoggingEvent>> appendersToAdd) {
+ private void addAllAppenders(final Map<String, Appender<ILoggingEvent>> allAppenders,
+ final Map<String, Appender<ILoggingEvent>> appendersToAdd) {
for (String appenderName : appendersToAdd.keySet()) {
Preconditions.checkState(allAppenders.containsKey(appenderName) == false, "Duplicate appender name %s",
appenderName);
}
}
- private Map<String, Appender<ILoggingEvent>> createFileAppenders(LoggerContext context, LogbackModule module) {
+ private Map<String, Appender<ILoggingEvent>> createFileAppenders(final LoggerContext context, final LogbackModule module) {
Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
for (FileAppenderTO appender : module.getFileAppenderTO()) {
Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false,
"Duplicate appender name %s", appender.getName());
- ch.qos.logback.core.FileAppender app = new ch.qos.logback.core.FileAppender<>();
+ ch.qos.logback.core.FileAppender<ILoggingEvent> app = new ch.qos.logback.core.FileAppender<>();
app.setAppend(appender.getAppend());
app.setContext(context);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
return appendersMap;
}
- private Map<String, Appender<ILoggingEvent>> createRollingAppenders(LoggerContext context, LogbackModule module) {
+ private Map<String, Appender<ILoggingEvent>> createRollingAppenders(final LoggerContext context, final LogbackModule module) {
Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
for (RollingFileAppenderTO appender : module.getRollingFileAppenderTO()) {
Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false,
"Duplicate appender name %s", appender.getName());
- ch.qos.logback.core.rolling.RollingFileAppender app = new ch.qos.logback.core.rolling.RollingFileAppender<>();
+ ch.qos.logback.core.rolling.RollingFileAppender<ILoggingEvent> app = new ch.qos.logback.core.rolling.RollingFileAppender<>();
app.setAppend(appender.getAppend());
app.setContext(context);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
policy.start();
app.setRollingPolicy(policy);
} else if (appender.getRollingPolicyType().equals("TimeBasedRollingPolicy")) {
- TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy();
+ TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<>();
policy.setContext(context);
policy.setMaxHistory(appender.getMaxHistory());
if (appender.getCleanHistoryOnStart() != null) {
policy.start();
app.setRollingPolicy(policy);
}
- SizeBasedTriggeringPolicy triggeringPolicy = new SizeBasedTriggeringPolicy();
+ SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<>();
triggeringPolicy.setContext(context);
triggeringPolicy.setMaxFileSize(appender.getMaxFileSize());
triggeringPolicy.start();
*/
package org.opendaylight.controller.config.yang.logback.config;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.LoggerContext;
+import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.classic.spi.LoggerComparator;
+import ch.qos.logback.core.Appender;
+import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
+import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
+import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-
import org.apache.commons.lang3.StringUtils;
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.controller.config.api.DependencyResolverFactory;
import org.osgi.framework.BundleContext;
import org.slf4j.LoggerFactory;
-import ch.qos.logback.classic.Logger;
-import ch.qos.logback.classic.LoggerContext;
-import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
-import ch.qos.logback.classic.spi.ILoggingEvent;
-import ch.qos.logback.classic.spi.LoggerComparator;
-import ch.qos.logback.core.Appender;
-import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
-import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
-import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
/**
*
*/
private Map<String, FileAppenderTO> fileDTOs;
@Override
- public LogbackModule instantiateModule(String instanceName, DependencyResolver dependencyResolver,
- BundleContext bundleContext) {
+ public LogbackModule instantiateModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final BundleContext bundleContext) {
Preconditions.checkArgument(instanceName.equals(INSTANCE_NAME),
"There should be just one instance of logback, named " + INSTANCE_NAME);
prepareDTOs();
}
@Override
- public LogbackModule instantiateModule(String instanceName, DependencyResolver dependencyResolver,
- LogbackModule oldModule, AutoCloseable oldInstance, BundleContext bundleContext) {
+ public LogbackModule instantiateModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final LogbackModule oldModule, final AutoCloseable oldInstance, final BundleContext bundleContext) {
Preconditions.checkArgument(instanceName.equals(INSTANCE_NAME),
"There should be just one instance of logback, named " + INSTANCE_NAME);
prepareDTOs();
prepareAppendersDTOs(context);
}
- private void prepareAppendersDTOs(LoggerContext context) {
+ private void prepareAppendersDTOs(final LoggerContext context) {
this.rollingDTOs = new HashMap<>();
this.consoleDTOs = new HashMap<>();
this.fileDTOs = new HashMap<>();
app.setFileNamePattern(rollingPolicy.getFileNamePattern());
app.setRollingPolicyType("FixedWindowRollingPolicy");
} else if (rollingApp.getRollingPolicy() instanceof TimeBasedRollingPolicy<?>) {
- TimeBasedRollingPolicy rollingPolicy = (TimeBasedRollingPolicy) rollingApp.getRollingPolicy();
+ TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = (TimeBasedRollingPolicy<ILoggingEvent>) rollingApp.getRollingPolicy();
app.setRollingPolicyType("TimeBasedRollingPolicy");
app.setFileNamePattern(rollingPolicy.getFileNamePattern());
app.setMaxHistory(rollingPolicy.getMaxHistory());
}
}
- private Map<String, LoggerTO> prepareLoggersDTOs(LoggerContext context) {
+ private Map<String, LoggerTO> prepareLoggersDTOs(final LoggerContext context) {
Map<String, LoggerTO> DTOs = new HashMap<>();
List<String> appenders = new ArrayList<>();
List<org.slf4j.Logger> loggersToBeAdd = removeUnusableLoggers(context.getLoggerList(),
return DTOs;
}
- private List<org.slf4j.Logger> removeUnusableLoggers(List<Logger> loggerList, Logger rootLogger) {
+ private List<org.slf4j.Logger> removeUnusableLoggers(final List<Logger> loggerList, final Logger rootLogger) {
Collections.sort(loggerList, new LoggerComparator());
Map<String, org.slf4j.Logger> loggersToReturn = new HashMap<>();
}
@Override
- public Set<LogbackModule> getDefaultModules(DependencyResolverFactory dependencyResolverFactory,
- BundleContext bundleContext) {
+ public Set<LogbackModule> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+ final BundleContext bundleContext) {
DependencyResolver resolver = dependencyResolverFactory.createDependencyResolver(new ModuleIdentifier(
getImplementationName(), INSTANCE_NAME));
LogbackModule defaultLogback = instantiateModule(INSTANCE_NAME, resolver, bundleContext);
*/
package org.opendaylight.controller.config.yang.logback.config;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
*/
-public final class NetconfClientDispatcherModule extends org.opendaylight.controller.config.yang.config.netconf.client.dispatcher.AbstractNetconfClientDispatcherModule
- {
+public final class NetconfClientDispatcherModule extends org.opendaylight.controller.config.yang.config.netconf.client.dispatcher.AbstractNetconfClientDispatcherModule {
public NetconfClientDispatcherModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
*/
package org.opendaylight.controller.config.yang.netty.timer;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-
-import junit.framework.Assert;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.ConflictingVersionException;
try {
createInstance(transaction, instanceName, 0L, 10, true);
transaction.validateConfig();
- Assert.fail();
+ fail();
} catch (ValidationException e) {
- Assert.assertTrue(e.getMessage().contains("TickDuration value must be greater than 0"));
+ assertTrue(e.getMessage().contains("TickDuration value must be greater than 0"));
}
}
try {
createInstance(transaction, instanceName, 500L, 0, true);
transaction.validateConfig();
- Assert.fail();
+ fail();
} catch (ValidationException e) {
- Assert.assertTrue(e.getMessage().contains("TicksPerWheel value must be greater than 0"));
+ assertTrue(e.getMessage().contains("TicksPerWheel value must be greater than 0"));
}
}
assertStatus(status, 0, 1, 1);
}
- private ObjectName createInstance(ConfigTransactionJMXClient transaction, String instanceName,
+ private ObjectName createInstance(final ConfigTransactionJMXClient transaction, final String instanceName,
final Long tickDuration, final Integer ticksPerWheel, final boolean hasThreadfactory)
throws InstanceAlreadyExistsException {
ObjectName nameCreated = transaction.createModule(factory.getImplementationName(), instanceName);
return nameCreated;
}
- private ObjectName createThreadfactoryInstance(ConfigTransactionJMXClient transaction, String instanceName,
+ private ObjectName createThreadfactoryInstance(final ConfigTransactionJMXClient transaction, final String instanceName,
final String namePrefix) throws InstanceAlreadyExistsException {
ObjectName nameCreated = transaction.createModule(threadFactory.getImplementationName(), instanceName);
NamingThreadFactoryModuleMXBean mxBean = transaction.newMBeanProxy(nameCreated,
<module>netconf-config-dispatcher</module>
<module>config-module-archetype</module>
<module>config-netty-config</module>
+
+ <module>config-artifacts</module>
</modules>
<dependencies>
*/
package org.opendaylight.controller.config.threadpool.async;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
public class SyncEventBusConfigBeanTest extends AbstractConfigTest {
*/
package org.opendaylight.controller.config.threadpool.fixed;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
public class FlexibleThreadPoolConfigBeanTest extends AbstractConfigTest {
*/
package org.opendaylight.controller.config.threadpool.naming;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
*/
package org.opendaylight.controller.config.threadpool.scheduled;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
String varName = BindingGeneratorUtil
.parseToValidParamName(attrEntry.getKey());
- {
- ModuleField field;
+ ModuleField field;
if (isIdentity) {
String identityBaseClass = getInnerTypeFromIdentity(((TypedAttribute) attributeIfc).getType());
IdentityRefModuleField identityField = new IdentityRefModuleField(type, varName,
nullableDefaultWrapped, isDependency, dependency, isListOfDependencies, needsDepResolver);
}
moduleFields.add(field);
- }
+
+
String getterName = "get"
+ attributeIfc.getUpperCaseCammelCase();
MethodDefinition getter = new MethodDefinition(type,
.append("}\n");
} else {
result.append(format(
- "private %s %sDependency;\n"+
- "protected final %s get%sDependency(){\n"+
- "return %sDependency;\n"+
- "}",
- osgi, moduleField.getName(), osgi, moduleField.getAttributeName(), moduleField.getName()));
+ "private %s %sDependency;\n"+
+ "protected final %s get%sDependency(){\n"+
+ "return %sDependency;\n"+
+ "}",
+ osgi, moduleField.getName(), osgi, moduleField.getAttributeName(), moduleField.getName()));
}
}
}
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants;
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
+import static org.junit.Assert.assertEquals;
import java.io.File;
-
-import junit.framework.Assert;
-
import org.junit.Test;
public class JMXGeneratorGeneratedFilesTrackerTest {
JMXGenerator.GeneratedFilesTracker tracker = new JMXGenerator.GeneratedFilesTracker();
tracker.addFile(new File("./a/b/c"));
- Assert.assertEquals(1, tracker.getFiles().size());
+ assertEquals(1, tracker.getFiles().size());
tracker.addFile(new File("./a/b/c"));
}
}
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
public class Dependency {
- private final ServiceInterfaceEntry sie;
- private final boolean mandatory;
+ private final ServiceInterfaceEntry sie;
+ private final boolean mandatory;
- public Dependency(ServiceInterfaceEntry sie, boolean mandatory) {
- this.sie = sie;
- this.mandatory = mandatory;
- }
+ public Dependency(ServiceInterfaceEntry sie, boolean mandatory) {
+ this.sie = sie;
+ this.mandatory = mandatory;
+ }
- public ServiceInterfaceEntry getSie() {
- return sie;
- }
+ public ServiceInterfaceEntry getSie() {
+ return sie;
+ }
- public boolean isMandatory() {
- return mandatory;
- }
+ public boolean isMandatory() {
+ return mandatory;
+ }
- @Override
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null || getClass() != o.getClass())
- return false;
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
- Dependency that = (Dependency) o;
+ Dependency that = (Dependency) o;
- if (mandatory != that.mandatory)
- return false;
- if (!sie.equals(that.sie))
- return false;
+ if (mandatory != that.mandatory)
+ return false;
+ if (!sie.equals(that.sie))
+ return false;
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = sie.hashCode();
- result = 31 * result + (mandatory ? 1 : 0);
- return result;
- }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = sie.hashCode();
+ result = 31 * result + (mandatory ? 1 : 0);
+ return result;
}
+}
*/
package org.opendaylight.controller.config.yangjmxgenerator;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.format;
+import static org.junit.Assert.assertNotNull;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
QName qName = identitySchemaNode.getQName();
Preconditions.checkArgument(
result.containsKey(qName) == false,
- format("Two identities of %s contain same " + "qname %s",
- module, qName));
+ "Two identities of %s contain same qname %s",
+ module, qName);
result.put(qName, identitySchemaNode);
}
return result;
*/
package org.opendaylight.controller.config.yangjmxgenerator;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import com.google.common.collect.Lists;
-import junit.framework.Assert;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.IdentityAttributeRef;
List<ObjectName> testingDeps = proxy.getTestingDeps();
ObjectName testingDep = proxy.getTestingDep();
- Assert.assertEquals(TESTING_DEP_PREFIX, ObjectNameUtil.getInstanceName(testingDep));
+ assertEquals(TESTING_DEP_PREFIX, ObjectNameUtil.getInstanceName(testingDep));
assertTestingDeps(testingDeps, 4);
transaction.abortConfig();
}
private void assertTestingDeps(List<ObjectName> testingDeps, int i) {
- Assert.assertEquals(i, testingDeps.size());
+ assertEquals(i, testingDeps.size());
int c = 1;
for (ObjectName testingDep : testingDeps) {
- Assert.assertEquals(TESTING_DEP_PREFIX + Integer.toString(c++), ObjectNameUtil.getInstanceName(testingDep));
+ assertEquals(TESTING_DEP_PREFIX + Integer.toString(c++), ObjectNameUtil.getInstanceName(testingDep));
}
}
<version>0.2.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
- <groupId>org.opendaylight.controller</groupId>
<artifactId>karaf.branding</artifactId>
<version>1.1.0-SNAPSHOT</version>
<packaging>bundle</packaging>
</parent>
<modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.controller</groupId>
<artifactId>benchmark-data-store</artifactId>
<dependencies>
*/
package org.opendaylight.controller.sal.compatibility.test;
-import junit.framework.Assert;
-
+import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.sal.action.Action;
import org.opendaylight.controller.sal.action.PushVlan;
import java.util.Collections;
import java.util.List;
-import junit.framework.Assert;
-
import org.junit.Test;
import org.opendaylight.controller.sal.action.Flood;
import org.opendaylight.controller.sal.action.FloodAll;
public void testFromNodeConnectorRef() throws ConstructionException {
Node node = new Node(NodeIDType.OPENFLOW, 42L);
NodeConnector nodeConnector = ToSalConversionsUtils.fromNodeConnectorRef(new Uri("1"), node);
- Assert.assertEquals("OF|1@OF|00:00:00:00:00:00:00:2a", nodeConnector.toString());
+ assertEquals("OF|1@OF|00:00:00:00:00:00:00:2a", nodeConnector.toString());
}
private void checkSalMatch(org.opendaylight.controller.sal.match.Match match, MtchType mt) throws ConstructionException {
*/
package org.opendaylight.controller.sal.compatibility.topology.test;
-import junit.framework.Assert;
+import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.opendaylight.controller.sal.compatibility.topology.TopologyMapping;
NodeId nodeId = new NodeId("openflow:1");
String observedNodeId = TopologyMapping.toADNodeId(nodeId);
- Assert.assertEquals("1", observedNodeId);
+ assertEquals("1", observedNodeId);
}
/**
TpId source = new TpId("foo:2");
NodeConnector observedNodeConnector = TopologyMapping.toADNodeConnector(source, nodeId);
- Assert.assertEquals("OF|2@OF|00:00:00:00:00:00:00:01", observedNodeConnector.toString());
+ assertEquals("OF|2@OF|00:00:00:00:00:00:00:01", observedNodeConnector.toString());
}
/**
TpId source = new TpId("foo:2");
String observedNodeConnectorId = TopologyMapping.toADNodeConnectorId(source);
- Assert.assertEquals("2", observedNodeConnectorId);
+ assertEquals("2", observedNodeConnectorId);
}
/**
NodeId nodeId = new NodeId("openflow:1");
Node observedNode = TopologyMapping.toADNode(nodeId);
- Assert.assertEquals("OF|00:00:00:00:00:00:00:01", observedNode.toString());
+ assertEquals("OF|00:00:00:00:00:00:00:01", observedNode.toString());
}
/**
TpId source = new TpId("192.168.0.1");
NodeConnector observedNodeConnector = TopologyMapping.toADNodeConnector(source, nodeId);
- Assert.assertEquals("MD_SAL_DEPRECATED|192.168.0.1@MD_SAL_DEPRECATED|some_unknown_node", observedNodeConnector.toString());
+ assertEquals("MD_SAL_DEPRECATED|192.168.0.1@MD_SAL_DEPRECATED|some_unknown_node", observedNodeConnector.toString());
}
}
import akka.japi.Creator;
import com.google.common.base.Optional;
import com.google.protobuf.ByteString;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.HashMap;
+import java.util.Map;
import org.opendaylight.controller.cluster.DataPersistenceProvider;
import org.opendaylight.controller.cluster.example.messages.KeyValue;
import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
import org.opendaylight.controller.cluster.example.messages.PrintState;
import org.opendaylight.controller.cluster.raft.ConfigParams;
import org.opendaylight.controller.cluster.raft.RaftActor;
+import org.opendaylight.controller.cluster.raft.RaftState;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
+import org.opendaylight.controller.cluster.raft.behaviors.Leader;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.HashMap;
-import java.util.Map;
-
/**
* A sample actor showing how the RaftActor is to be extended
*/
public class ExampleActor extends RaftActor {
- private final Map<String, String> state = new HashMap();
+ private final Map<String, String> state = new HashMap<>();
private final DataPersistenceProvider dataPersistenceProvider;
private long persistIdentifier = 1;
- public ExampleActor(String id, Map<String, String> peerAddresses,
- Optional<ConfigParams> configParams) {
+ public ExampleActor(final String id, final Map<String, String> peerAddresses,
+ final Optional<ConfigParams> configParams) {
super(id, peerAddresses, configParams);
this.dataPersistenceProvider = new PersistentDataProvider();
}
});
}
- @Override public void onReceiveCommand(Object message) throws Exception{
+ @Override public void onReceiveCommand(final Object message) throws Exception{
if(message instanceof KeyValue){
if(isLeader()) {
String persistId = Long.toString(persistIdentifier++);
} else if (message instanceof PrintRole) {
if(LOG.isDebugEnabled()) {
- LOG.debug("{} = {}, Peers={}", getId(), getRaftState(), getPeers());
+ String followers = "";
+ if (getRaftState() == RaftState.Leader) {
+ followers = ((Leader)this.getCurrentBehavior()).printFollowerStates();
+ LOG.debug("{} = {}, Peers={}, followers={}", getId(), getRaftState(), getPeers(), followers);
+ } else {
+ LOG.debug("{} = {}, Peers={}", getId(), getRaftState(), getPeers());
+ }
+
+
}
} else {
}
}
- @Override protected void applyState(ActorRef clientActor, String identifier,
- Object data) {
+ @Override protected void applyState(final ActorRef clientActor, final String identifier,
+ final Object data) {
if(data instanceof KeyValue){
KeyValue kv = (KeyValue) data;
state.put(kv.getKey(), kv.getValue());
getSelf().tell(new CaptureSnapshotReply(bs), null);
}
- @Override protected void applySnapshot(ByteString snapshot) {
+ @Override protected void applySnapshot(final ByteString snapshot) {
state.clear();
try {
state.putAll((HashMap) toObject(snapshot));
}
}
- private ByteString fromObject(Object snapshot) throws Exception {
+ private ByteString fromObject(final Object snapshot) throws Exception {
ByteArrayOutputStream b = null;
ObjectOutputStream o = null;
try {
}
}
- private Object toObject(ByteString bs) throws ClassNotFoundException, IOException {
+ private Object toObject(final ByteString bs) throws ClassNotFoundException, IOException {
Object obj = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
return dataPersistenceProvider;
}
- @Override public void onReceiveRecover(Object message)throws Exception {
+ @Override public void onReceiveRecover(final Object message)throws Exception {
super.onReceiveRecover(message);
}
}
@Override
- protected void startLogRecoveryBatch(int maxBatchSize) {
+ protected void startLogRecoveryBatch(final int maxBatchSize) {
}
@Override
- protected void appendRecoveredLogEntry(Payload data) {
+ protected void appendRecoveredLogEntry(final Payload data) {
}
@Override
}
@Override
- protected void applyRecoverySnapshot(ByteString snapshot) {
+ protected void applyRecoverySnapshot(final ByteString snapshot) {
}
}
public class ExampleConfigParamsImpl extends DefaultConfigParamsImpl {
@Override
public long getSnapshotBatchCount() {
- return 50;
+ return 25;
}
@Override
import org.opendaylight.controller.cluster.example.messages.PrintRole;
import org.opendaylight.controller.cluster.example.messages.PrintState;
import org.opendaylight.controller.cluster.raft.ConfigParams;
-import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
* Commands
* bye
* createNodes:{num}
- * addNodes:{num}
* stopNode:{nodeName}
* reinstateNode:{nodeName}
* addClients:{num}
int n = Integer.parseInt(arr[1]);
td.createNodes(n);
- } else if (command.startsWith("addNodes")) {
- String[] arr = command.split(":");
- int n = Integer.parseInt(arr[1]);
- td.addNodes(n);
-
} else if (command.startsWith("addClients")) {
String[] arr = command.split(":");
int n = Integer.parseInt(arr[1]);
}
}
- // add new nodes , pass in the count
- public void addNodes(int num) {
- Map<String, String> newPeers = new HashMap<>();
- for (int i=0; i < num; i++) {
- nameCounter = nameCounter + 1;
- newPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter);
- allPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter);
-
- }
- Map<String, ActorRef> newActorRefs = new HashMap<String, ActorRef>(num);
- for (Map.Entry<String, String> entry : newPeers.entrySet()) {
- ActorRef exampleActor = createExampleActor(entry.getKey());
- newActorRefs.put(entry.getKey(), exampleActor);
-
- //now also add these new nodes as peers from the previous nodes
- for (ActorRef actor : actorRefs.values()) {
- actor.tell(new AddRaftPeer(entry.getKey(), entry.getValue()), null);
- }
-
- System.out.println("Added node:" + entry);
- }
-
- actorRefs.putAll(newActorRefs);
- }
-
-
// add num clients to all nodes in the system
public void addClients(int num) {
for(Map.Entry<String,ActorRef> actorRefEntry : actorRefs.entrySet()) {
*/
package org.opendaylight.controller.cluster.raft;
-import com.google.protobuf.ByteString;
-
import java.util.ArrayList;
import java.util.List;
// We define this as ArrayList so we can use ensureCapacity.
protected ArrayList<ReplicatedLogEntry> journal;
- protected ByteString snapshot;
+
protected long snapshotIndex = -1;
protected long snapshotTerm = -1;
// to be used for rollback during save snapshot failure
protected ArrayList<ReplicatedLogEntry> snapshottedJournal;
- protected ByteString previousSnapshot;
protected long previousSnapshotIndex = -1;
protected long previousSnapshotTerm = -1;
- public AbstractReplicatedLogImpl(ByteString state, long snapshotIndex,
+ public AbstractReplicatedLogImpl(long snapshotIndex,
long snapshotTerm, List<ReplicatedLogEntry> unAppliedEntries) {
- this.snapshot = state;
this.snapshotIndex = snapshotIndex;
this.snapshotTerm = snapshotTerm;
this.journal = new ArrayList<>(unAppliedEntries);
}
-
public AbstractReplicatedLogImpl() {
- this.snapshot = null;
this.journal = new ArrayList<>();
}
return logEntryIndex <= snapshotIndex && snapshotIndex != -1;
}
- @Override
- public ByteString getSnapshot() {
- return snapshot;
- }
-
@Override
public long getSnapshotIndex() {
return snapshotIndex;
this.snapshotTerm = snapshotTerm;
}
- @Override
- public void setSnapshot(ByteString snapshot) {
- this.snapshot = snapshot;
- }
-
@Override
public void clear(int startIndex, int endIndex) {
journal.subList(startIndex, endIndex).clear();
}
@Override
- public void snapshotPreCommit(ByteString snapshot, long snapshotCapturedIndex, long snapshotCapturedTerm) {
+ public void snapshotPreCommit(long snapshotCapturedIndex, long snapshotCapturedTerm) {
snapshottedJournal = new ArrayList<>(journal.size());
snapshottedJournal.addAll(journal.subList(0, (int)(snapshotCapturedIndex - snapshotIndex)));
previousSnapshotTerm = snapshotTerm;
setSnapshotTerm(snapshotCapturedTerm);
-
- previousSnapshot = getSnapshot();
- setSnapshot(snapshot);
}
@Override
snapshottedJournal = null;
previousSnapshotIndex = -1;
previousSnapshotTerm = -1;
- previousSnapshot = null;
}
@Override
snapshotTerm = previousSnapshotTerm;
previousSnapshotTerm = -1;
-
- snapshot = previousSnapshot;
- previousSnapshot = null;
-
}
}
*/
public AtomicLong getMatchIndex();
+ /**
+ * Checks if the follower is active by comparing the last updated with the duration
+ * @return boolean
+ */
+ public boolean isFollowerActive();
+
+ /**
+ * restarts the timeout clock of the follower
+ */
+ public void markFollowerActive();
+
}
package org.opendaylight.controller.cluster.raft;
+import com.google.common.base.Stopwatch;
+import scala.concurrent.duration.FiniteDuration;
+
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class FollowerLogInformationImpl implements FollowerLogInformation{
private final AtomicLong matchIndex;
+ private final Stopwatch stopwatch;
+
+ private final long followerTimeoutMillis;
+
public FollowerLogInformationImpl(String id, AtomicLong nextIndex,
- AtomicLong matchIndex) {
+ AtomicLong matchIndex, FiniteDuration followerTimeoutDuration) {
this.id = id;
this.nextIndex = nextIndex;
this.matchIndex = matchIndex;
+ this.stopwatch = new Stopwatch();
+ this.followerTimeoutMillis = followerTimeoutDuration.toMillis();
}
public long incrNextIndex(){
return matchIndex;
}
+ @Override
+ public boolean isFollowerActive() {
+ long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
+ return (stopwatch.isRunning()) && (elapsed <= followerTimeoutMillis);
+ }
+
+ @Override
+ public void markFollowerActive() {
+ if (stopwatch.isRunning()) {
+ stopwatch.reset();
+ }
+ stopwatch.start();
+ }
}
import akka.persistence.SaveSnapshotSuccess;
import akka.persistence.SnapshotOffer;
import akka.persistence.SnapshotSelectionCriteria;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Stopwatch;
import com.google.protobuf.ByteString;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
+import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
+import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
import org.opendaylight.controller.cluster.raft.behaviors.Follower;
import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
-import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
-import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer;
import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages;
context.getReplicatedLog().getSnapshotTerm(),
context.getReplicatedLog().size());
- } else if (message instanceof AddRaftPeer){
-
- // FIXME : Do not add raft peers like this.
- // When adding a new Peer we have to ensure that the a majority of
- // the peers know about the new Peer. Doing it this way may cause
- // a situation where multiple Leaders may emerge
- AddRaftPeer arp = (AddRaftPeer)message;
- context.addToPeers(arp.getName(), arp.getAddress());
-
- } else if (message instanceof RemoveRaftPeer){
-
- RemoveRaftPeer rrp = (RemoveRaftPeer)message;
- context.removePeer(rrp.getName());
-
} else if (message instanceof CaptureSnapshot) {
LOG.info("CaptureSnapshot received by actor");
CaptureSnapshot cs = (CaptureSnapshot)message;
}
public java.util.Set<String> getPeers() {
+
return context.getPeerAddresses().keySet();
}
//be greedy and remove entries from in-mem journal which are in the snapshot
// and update snapshotIndex and snapshotTerm without waiting for the success,
- context.getReplicatedLog().snapshotPreCommit(stateInBytes,
+ context.getReplicatedLog().snapshotPreCommit(
captureSnapshot.getLastAppliedIndex(),
captureSnapshot.getLastAppliedTerm());
"and term:{}", captureSnapshot.getLastAppliedIndex(),
captureSnapshot.getLastAppliedTerm());
+ if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) {
+ // this would be call straight to the leader and won't initiate in serialization
+ currentBehavior.handleMessage(getSelf(), new SendInstallSnapshot(stateInBytes));
+ }
+
captureSnapshot = null;
hasSnapshotCaptureInitiated = false;
}
-
private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
public ReplicatedLogImpl(Snapshot snapshot) {
- super(ByteString.copyFrom(snapshot.getState()),
- snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
+ super(snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
snapshot.getUnAppliedEntries());
}
}
}
+ @VisibleForTesting
+ void setCurrentBehavior(AbstractRaftActorBehavior behavior) {
+ currentBehavior = behavior;
+ }
+
+ protected RaftActorBehavior getCurrentBehavior() {
+ return currentBehavior;
+ }
}
package org.opendaylight.controller.cluster.raft;
-import com.google.protobuf.ByteString;
-
import java.util.List;
/**
*/
boolean isInSnapshot(long index);
- /**
- * Get the snapshot
- *
- * @return an object representing the snapshot if it exists. null otherwise
- */
- ByteString getSnapshot();
-
/**
* Get the index of the snapshot
*
*/
public void setSnapshotTerm(long snapshotTerm);
- /**
- * sets the snapshot in bytes
- * @param snapshot
- */
- public void setSnapshot(ByteString snapshot);
-
/**
* Clears the journal entries with startIndex(inclusive) and endIndex (exclusive)
* @param startIndex
/**
* Handles all the bookkeeping in order to perform a rollback in the
* event of SaveSnapshotFailure
- * @param snapshot
* @param snapshotCapturedIndex
* @param snapshotCapturedTerm
*/
- public void snapshotPreCommit(ByteString snapshot,
- long snapshotCapturedIndex, long snapshotCapturedTerm);
+ public void snapshotPreCommit(long snapshotCapturedIndex, long snapshotCapturedTerm);
/**
* Sets the Replicated log to state after snapshot success.
private long lastAppliedTerm;
private long lastIndex;
private long lastTerm;
+ private boolean installSnapshotInitiated;
public CaptureSnapshot(long lastIndex, long lastTerm,
long lastAppliedIndex, long lastAppliedTerm) {
+ this(lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm, false);
+ }
+
+ public CaptureSnapshot(long lastIndex, long lastTerm,long lastAppliedIndex,
+ long lastAppliedTerm, boolean installSnapshotInitiated) {
this.lastIndex = lastIndex;
this.lastTerm = lastTerm;
this.lastAppliedIndex = lastAppliedIndex;
this.lastAppliedTerm = lastAppliedTerm;
+ this.installSnapshotInitiated = installSnapshotInitiated;
}
public long getLastAppliedIndex() {
public long getLastTerm() {
return lastTerm;
}
+
+ public boolean isInstallSnapshotInitiated() {
+ return installSnapshotInitiated;
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.raft.base.messages;
+
+/**
+ * Internal message by Leader to initiate an install snapshot
+ */
+public class InitiateInstallSnapshot {
+}
+
package org.opendaylight.controller.cluster.raft.base.messages;
-import java.io.Serializable;
+import com.google.protobuf.ByteString;
-public class SendInstallSnapshot implements Serializable {
+public class SendInstallSnapshot {
+ private ByteString snapshot;
+
+ public SendInstallSnapshot(ByteString snapshot) {
+ this.snapshot = snapshot;
+ }
+
+ public ByteString getSnapshot() {
+ return snapshot;
+ }
}
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.Cancellable;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.protobuf.ByteString;
import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
+import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
+import org.opendaylight.controller.cluster.raft.base.messages.InitiateInstallSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
public class Leader extends AbstractRaftActorBehavior {
- protected final Map<String, FollowerLogInformation> followerToLog =
- new HashMap();
+ protected final Map<String, FollowerLogInformation> followerToLog = new HashMap();
protected final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
private final Set<String> followers;
private final int minReplicationCount;
+ private Optional<ByteString> snapshot;
+
public Leader(RaftActorContext context) {
super(context);
FollowerLogInformation followerLogInformation =
new FollowerLogInformationImpl(followerId,
new AtomicLong(context.getCommitIndex()),
- new AtomicLong(-1));
+ new AtomicLong(-1),
+ context.getConfigParams().getElectionTimeOutInterval());
followerToLog.put(followerId, followerLogInformation);
}
minReplicationCount = 0;
}
+ snapshot = Optional.absent();
// Immediately schedule a heartbeat
// Upon election: send initial empty AppendEntries RPCs
}
+ private Optional<ByteString> getSnapshot() {
+ return snapshot;
+ }
+
+ @VisibleForTesting
+ void setSnapshot(Optional<ByteString> snapshot) {
+ this.snapshot = snapshot;
+ }
+
@Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
AppendEntries appendEntries) {
return this;
}
+ followerLogInformation.markFollowerActive();
+
if (appendEntriesReply.isSuccess()) {
followerLogInformation
.setMatchIndex(appendEntriesReply.getLogLastIndex());
if (message instanceof SendHeartBeat) {
sendHeartBeat();
return this;
- } else if(message instanceof SendInstallSnapshot) {
+
+ } else if(message instanceof InitiateInstallSnapshot) {
installSnapshotIfNeeded();
+
+ } else if(message instanceof SendInstallSnapshot) {
+ // received from RaftActor
+ setSnapshot(Optional.of(((SendInstallSnapshot) message).getSnapshot()));
+ sendInstallSnapshot();
+
} else if (message instanceof Replicate) {
replicate((Replicate) message);
+
} else if (message instanceof InstallSnapshotReply){
handleInstallSnapshotReply(
(InstallSnapshotReply) message);
private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
String followerId = reply.getFollowerId();
- FollowerToSnapshot followerToSnapshot =
- mapFollowerToSnapshot.get(followerId);
+ FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
+ FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
+ followerLogInformation.markFollowerActive();
if (followerToSnapshot != null &&
followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
);
}
- FollowerLogInformation followerLogInformation =
- followerToLog.get(followerId);
followerLogInformation.setMatchIndex(
context.getReplicatedLog().getSnapshotIndex());
followerLogInformation.setNextIndex(
followerToLog.get(followerId).getNextIndex().get());
}
+ if (mapFollowerToSnapshot.isEmpty()) {
+ // once there are no pending followers receiving snapshots
+ // we can remove snapshot from the memory
+ setSnapshot(Optional.<ByteString>absent());
+ }
+
} else {
followerToSnapshot.markSendStatus(true);
}
if (followerActor != null) {
FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
long followerNextIndex = followerLogInformation.getNextIndex().get();
- List<ReplicatedLogEntry> entries = Collections.emptyList();
+ boolean isFollowerActive = followerLogInformation.isFollowerActive();
+ List<ReplicatedLogEntry> entries = null;
if (mapFollowerToSnapshot.get(followerId) != null) {
- if (mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
+ // if install snapshot is in process , then sent next chunk if possible
+ if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
sendSnapshotChunk(followerActor, followerId);
+ } else {
+ // we send a heartbeat even if we have not received a reply for the last chunk
+ sendAppendEntriesToFollower(followerActor, followerNextIndex,
+ Collections.<ReplicatedLogEntry>emptyList());
}
} else {
+ long leaderLastIndex = context.getReplicatedLog().lastIndex();
+ long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
- if (context.getReplicatedLog().isPresent(followerNextIndex)) {
+ if (isFollowerActive &&
+ context.getReplicatedLog().isPresent(followerNextIndex)) {
// FIXME : Sending one entry at a time
entries = context.getReplicatedLog().getFrom(followerNextIndex, 1);
- followerActor.tell(
- new AppendEntries(currentTerm(), context.getId(),
- prevLogIndex(followerNextIndex),
- prevLogTerm(followerNextIndex), entries,
- context.getCommitIndex()).toSerializable(),
- actor()
- );
-
- } else {
- // if the followers next index is not present in the leaders log, then snapshot should be sent
- long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
- long leaderLastIndex = context.getReplicatedLog().lastIndex();
- if (followerNextIndex >= 0 && leaderLastIndex >= followerNextIndex ) {
- // if the follower is just not starting and leader's index
- // is more than followers index
- if(LOG.isDebugEnabled()) {
- LOG.debug("SendInstallSnapshot to follower:{}," +
- "follower-nextIndex:{}, leader-snapshot-index:{}, " +
- "leader-last-index:{}", followerId,
- followerNextIndex, leaderSnapShotIndex, leaderLastIndex
- );
- }
-
- actor().tell(new SendInstallSnapshot(), actor());
- } else {
- followerActor.tell(
- new AppendEntries(currentTerm(), context.getId(),
- prevLogIndex(followerNextIndex),
- prevLogTerm(followerNextIndex), entries,
- context.getCommitIndex()).toSerializable(),
- actor()
+ } else if (isFollowerActive && followerNextIndex >= 0 &&
+ leaderLastIndex >= followerNextIndex ) {
+ // if the followers next index is not present in the leaders log, and
+ // if the follower is just not starting and if leader's index is more than followers index
+ // then snapshot should be sent
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("InitiateInstallSnapshot to follower:{}," +
+ "follower-nextIndex:{}, leader-snapshot-index:{}, " +
+ "leader-last-index:{}", followerId,
+ followerNextIndex, leaderSnapShotIndex, leaderLastIndex
);
}
+ actor().tell(new InitiateInstallSnapshot(), actor());
+
+ // we would want to sent AE as the capture snapshot might take time
+ entries = Collections.<ReplicatedLogEntry>emptyList();
+
+ } else {
+ //we send an AppendEntries, even if the follower is inactive
+ // in-order to update the followers timestamp, in case it becomes active again
+ entries = Collections.<ReplicatedLogEntry>emptyList();
}
+
+ sendAppendEntriesToFollower(followerActor, followerNextIndex, entries);
+
}
}
}
}
+ private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
+ List<ReplicatedLogEntry> entries) {
+ followerActor.tell(
+ new AppendEntries(currentTerm(), context.getId(),
+ prevLogIndex(followerNextIndex),
+ prevLogTerm(followerNextIndex), entries,
+ context.getCommitIndex()).toSerializable(),
+ actor()
+ );
+ }
+
/**
* An installSnapshot is scheduled at a interval that is a multiple of
* a HEARTBEAT_INTERVAL. This is to avoid the need to check for installing
* snapshots at every heartbeat.
+ *
+ * Install Snapshot works as follows
+ * 1. Leader sends a InitiateInstallSnapshot message to self
+ * 2. Leader then initiates the capture snapshot by sending a CaptureSnapshot message to actor
+ * 3. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
+ * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
+ * 4. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
+ * 5. On complete, Follower sends back a InstallSnapshotReply.
+ * 6. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
+ * and replenishes the memory by deleting the snapshot in Replicated log.
+ *
*/
- private void installSnapshotIfNeeded(){
+ private void installSnapshotIfNeeded() {
for (String followerId : followers) {
ActorSelection followerActor =
context.getPeerActorSelection(followerId);
long nextIndex = followerLogInformation.getNextIndex().get();
+ if (!context.getReplicatedLog().isPresent(nextIndex) &&
+ context.getReplicatedLog().isInSnapshot(nextIndex)) {
+ LOG.info("{} follower needs a snapshot install", followerId);
+ if (snapshot.isPresent()) {
+ // if a snapshot is present in the memory, most likely another install is in progress
+ // no need to capture snapshot
+ sendSnapshotChunk(followerActor, followerId);
+
+ } else {
+ initiateCaptureSnapshot();
+ //we just need 1 follower who would need snapshot to be installed.
+ // when we have the snapshot captured, we would again check (in SendInstallSnapshot)
+ // who needs an install and send to all who need
+ break;
+ }
+
+ }
+ }
+ }
+ }
+
+ // on every install snapshot, we try to capture the snapshot.
+ // Once a capture is going on, another one issued will get ignored by RaftActor.
+ private void initiateCaptureSnapshot() {
+ LOG.info("Initiating Snapshot Capture to Install Snapshot, Leader:{}", getLeaderId());
+ ReplicatedLogEntry lastAppliedEntry = context.getReplicatedLog().get(context.getLastApplied());
+ long lastAppliedIndex = -1;
+ long lastAppliedTerm = -1;
+
+ if (lastAppliedEntry != null) {
+ lastAppliedIndex = lastAppliedEntry.getIndex();
+ lastAppliedTerm = lastAppliedEntry.getTerm();
+ } else if (context.getReplicatedLog().getSnapshotIndex() > -1) {
+ lastAppliedIndex = context.getReplicatedLog().getSnapshotIndex();
+ lastAppliedTerm = context.getReplicatedLog().getSnapshotTerm();
+ }
+
+ boolean isInstallSnapshotInitiated = true;
+ actor().tell(new CaptureSnapshot(lastIndex(), lastTerm(),
+ lastAppliedIndex, lastAppliedTerm, isInstallSnapshotInitiated),
+ actor());
+ }
+
+
+ private void sendInstallSnapshot() {
+ for (String followerId : followers) {
+ ActorSelection followerActor = context.getPeerActorSelection(followerId);
+
+ if(followerActor != null) {
+ FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
+ long nextIndex = followerLogInformation.getNextIndex().get();
+
if (!context.getReplicatedLog().isPresent(nextIndex) &&
context.getReplicatedLog().isInSnapshot(nextIndex)) {
sendSnapshotChunk(followerActor, followerId);
*/
private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
try {
- followerActor.tell(
- new InstallSnapshot(currentTerm(), context.getId(),
- context.getReplicatedLog().getSnapshotIndex(),
- context.getReplicatedLog().getSnapshotTerm(),
- getNextSnapshotChunk(followerId,
- context.getReplicatedLog().getSnapshot()),
- mapFollowerToSnapshot.get(followerId).incrementChunkIndex(),
- mapFollowerToSnapshot.get(followerId).getTotalChunks()
- ).toSerializable(),
- actor()
- );
- LOG.info("InstallSnapshot sent to follower {}, Chunk: {}/{}",
- followerActor.path(), mapFollowerToSnapshot.get(followerId).getChunkIndex(),
- mapFollowerToSnapshot.get(followerId).getTotalChunks());
+ if (snapshot.isPresent()) {
+ followerActor.tell(
+ new InstallSnapshot(currentTerm(), context.getId(),
+ context.getReplicatedLog().getSnapshotIndex(),
+ context.getReplicatedLog().getSnapshotTerm(),
+ getNextSnapshotChunk(followerId,snapshot.get()),
+ mapFollowerToSnapshot.get(followerId).incrementChunkIndex(),
+ mapFollowerToSnapshot.get(followerId).getTotalChunks()
+ ).toSerializable(),
+ actor()
+ );
+ LOG.info("InstallSnapshot sent to follower {}, Chunk: {}/{}",
+ followerActor.path(), mapFollowerToSnapshot.get(followerId).getChunkIndex(),
+ mapFollowerToSnapshot.get(followerId).getTotalChunks());
+ }
} catch (IOException e) {
LOG.error(e, "InstallSnapshot failed for Leader.");
}
mapFollowerToSnapshot.put(followerId, followerToSnapshot);
}
ByteString nextChunk = followerToSnapshot.getNextChunk();
- if(LOG.isDebugEnabled()) {
+ if (LOG.isDebugEnabled()) {
LOG.debug("Leader's snapshot nextChunk size:{}", nextChunk.size());
}
-
return nextChunk;
}
// Scheduling the heartbeat only once here because heartbeats do not
// need to be sent if there are other messages being sent to the remote
// actor.
- heartbeatSchedule =
- context.getActorSystem().scheduler().scheduleOnce(
- interval,
- context.getActor(), new SendHeartBeat(),
- context.getActorSystem().dispatcher(), context.getActor());
+ heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
+ interval, context.getActor(), new SendHeartBeat(),
+ context.getActorSystem().dispatcher(), context.getActor());
}
-
private void scheduleInstallSnapshotCheck(FiniteDuration interval) {
if(followers.size() == 0){
// Optimization - do not bother scheduling a heartbeat as there are
installSnapshotSchedule =
context.getActorSystem().scheduler().scheduleOnce(
interval,
- context.getActor(), new SendInstallSnapshot(),
+ context.getActor(), new InitiateInstallSnapshot(),
context.getActorSystem().dispatcher(), context.getActor());
}
}
}
+ // called from example-actor for printing the follower-states
+ public String printFollowerStates() {
+ StringBuilder sb = new StringBuilder();
+ for(FollowerLogInformation followerLogInformation : followerToLog.values()) {
+ boolean isFollowerActive = followerLogInformation.isFollowerActive();
+ sb.append("{"+followerLogInformation.getId() + " state:" + isFollowerActive + "},");
+
+ }
+ return "[" + sb.toString() + "]";
+ }
+
+ @VisibleForTesting
+ void markFollowerActive(String followerId) {
+ followerToLog.get(followerId).markFollowerActive();
+ }
}
+++ /dev/null
-package org.opendaylight.controller.cluster.raft.client.messages;
-
-/**
- * Created by kramesha on 7/17/14.
- */
-public class AddRaftPeer {
-
- private String name;
- private String address;
-
- public AddRaftPeer(String name, String address) {
- this.name = name;
- this.address = address;
- }
-
- public String getName() {
- return name;
- }
-
- public String getAddress() {
- return address;
- }
-}
+++ /dev/null
-package org.opendaylight.controller.cluster.raft.client.messages;
-
-/**
- * Created by kramesha on 7/17/14.
- */
-public class RemoveRaftPeer {
- private String name;
-
- public RemoveRaftPeer(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-}
*/
package org.opendaylight.controller.cluster.raft;
-import junit.framework.Assert;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
-import static org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockReplicatedLogEntry;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
+import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockReplicatedLogEntry;
/**
*
*/
// now create a snapshot of 3 entries, with 1 unapplied entry left in the log
// It removes the entries which have made it to snapshot
// and updates the snapshot index and term
- Map state = takeSnapshot(3);
+ Map<Long, String> state = takeSnapshot(3);
// check the values after the snapshot.
// each index value passed in the test is the logical index (log entry index)
}
// create a snapshot for test
- public Map takeSnapshot(int numEntries) {
- Map map = new HashMap(numEntries);
+ public Map<Long, String> takeSnapshot(final int numEntries) {
+ Map<Long, String> map = new HashMap<>(numEntries);
List<ReplicatedLogEntry> entries = replicatedLogImpl.getEntriesTill(numEntries);
for (ReplicatedLogEntry entry : entries) {
map.put(entry.getIndex(), entry.getData().toString());
}
class MockAbstractReplicatedLogImpl extends AbstractReplicatedLogImpl {
@Override
- public void appendAndPersist(ReplicatedLogEntry replicatedLogEntry) {
+ public void appendAndPersist(final ReplicatedLogEntry replicatedLogEntry) {
}
@Override
- public void removeFromAndPersist(long index) {
+ public void removeFromAndPersist(final long index) {
}
- public void setSnapshotIndex(long snapshotIndex) {
+ @Override
+ public void setSnapshotIndex(final long snapshotIndex) {
this.snapshotIndex = snapshotIndex;
}
- public void setSnapshotTerm(long snapshotTerm) {
+ @Override
+ public void setSnapshotTerm(final long snapshotTerm) {
this.snapshotTerm = snapshotTerm;
}
- public List<ReplicatedLogEntry> getEntriesTill(int index) {
+ public List<ReplicatedLogEntry> getEntriesTill(final int index) {
return journal.subList(0, index);
}
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.raft;
+
+
+import com.google.common.base.Stopwatch;
+import com.google.common.util.concurrent.Uninterruptibles;
+import org.junit.Test;
+import scala.concurrent.duration.FiniteDuration;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class FollowerLogInformationImplTest {
+
+ @Test
+ public void testIsFollowerActive() {
+
+ FiniteDuration timeoutDuration =
+ new FiniteDuration(500, TimeUnit.MILLISECONDS);
+
+ FollowerLogInformation followerLogInformation =
+ new FollowerLogInformationImpl(
+ "follower1", new AtomicLong(10), new AtomicLong(9), timeoutDuration);
+
+
+
+ assertFalse("Follower should be termed inactive before stopwatch starts",
+ followerLogInformation.isFollowerActive());
+
+ followerLogInformation.markFollowerActive();
+ if (sleepWithElaspsedTimeReturned(200) > 200) {
+ return;
+ }
+ assertTrue("Follower should be active", followerLogInformation.isFollowerActive());
+
+ if (sleepWithElaspsedTimeReturned(400) > 400) {
+ return;
+ }
+ assertFalse("Follower should be inactive after time lapsed",
+ followerLogInformation.isFollowerActive());
+
+ followerLogInformation.markFollowerActive();
+ assertTrue("Follower should be active from inactive",
+ followerLogInformation.isFollowerActive());
+ }
+
+ // we cannot rely comfortably that the sleep will indeed sleep for the desired time
+ // hence getting the actual elapsed time and do a match.
+ // if the sleep has spilled over, then return the test gracefully
+ private long sleepWithElaspsedTimeReturned(long millis) {
+ Stopwatch stopwatch = new Stopwatch();
+ stopwatch.start();
+ Uninterruptibles.sleepUninterruptibly(millis, TimeUnit.MILLISECONDS);
+ stopwatch.stop();
+ return stopwatch.elapsed(TimeUnit.MILLISECONDS);
+ }
+}
import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
+import org.opendaylight.controller.cluster.raft.behaviors.Follower;
+import org.opendaylight.controller.cluster.raft.behaviors.Leader;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
-
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId,
verify(dataPersistenceProvider, times(2)).persist(anyObject(), any(Procedure.class));
-
mockActorRef.tell(PoisonPill.getInstance(), getRef());
}
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
- TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId,
- Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
+ TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(),
+ MockRaftActor.props(persistenceId,Collections.EMPTY_MAP,
+ Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1,1,-1,1));
+ RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext();
+
+ mockRaftActor.setCurrentBehavior(new Leader(raftActorContext));
+
mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes));
verify(dataPersistenceProvider).saveSnapshot(anyObject());
new MockRaftActorContext.MockPayload("C"),
new MockRaftActorContext.MockPayload("D")));
+ RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext();
+ mockRaftActor.setCurrentBehavior(new Follower(raftActorContext));
+
mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1, 1, 2, 1));
verify(mockRaftActor.delegate).createSnapshot();
verify(dataPersistenceProvider).deleteMessages(100);
- assertNotNull("Snapshot should not be null", mockRaftActor.getReplicatedLog().getSnapshot());
-
assertEquals(2, mockRaftActor.getReplicatedLog().size());
assertNotNull(mockRaftActor.getReplicatedLog().get(3));
}
};
-
-
}
@Test
oldReplicatedLog.append(new MockRaftActorContext.MockReplicatedLogEntry(1,0,mock(Payload.class)));
oldReplicatedLog.append(new MockRaftActorContext.MockReplicatedLogEntry(1,1,mock(Payload.class)));
- oldReplicatedLog.append(new MockRaftActorContext.MockReplicatedLogEntry(1,2,mock(Payload.class)));
+ oldReplicatedLog.append(
+ new MockRaftActorContext.MockReplicatedLogEntry(1, 2,
+ mock(Payload.class)));
ByteString snapshotBytes = fromObject(Arrays.asList(
- new MockRaftActorContext.MockPayload("A"),
- new MockRaftActorContext.MockPayload("B"),
- new MockRaftActorContext.MockPayload("C"),
- new MockRaftActorContext.MockPayload("D")));
+ new MockRaftActorContext.MockPayload("A"),
+ new MockRaftActorContext.MockPayload("B"),
+ new MockRaftActorContext.MockPayload("C"),
+ new MockRaftActorContext.MockPayload("D")));
Snapshot snapshot = mock(Snapshot.class);
verify(mockRaftActor.delegate).applySnapshot(eq(snapshotBytes));
- assertTrue("The replicatedLog should have changed", oldReplicatedLog != mockRaftActor.getReplicatedLog());
+ assertTrue("The replicatedLog should have changed",
+ oldReplicatedLog != mockRaftActor.getReplicatedLog());
- assertEquals("lastApplied should be same as in the snapshot", (Long) 3L, mockRaftActor.getLastApplied());
+ assertEquals("lastApplied should be same as in the snapshot",
+ (Long) 3L, mockRaftActor.getLastApplied());
assertEquals(0, mockRaftActor.getReplicatedLog().size());
new MockRaftActorContext.MockPayload("C"),
new MockRaftActorContext.MockPayload("D")));
+ RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext();
+
+ mockRaftActor.setCurrentBehavior(new Leader(raftActorContext));
+
mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1,1,-1,1));
mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes));
assertEquals("Snapshot index should not have advanced because save snapshot failed", -1,
mockRaftActor.getReplicatedLog().getSnapshotIndex());
- assertNull("Snapshot should be null", mockRaftActor.getReplicatedLog().getSnapshot());
-
mockActorRef.tell(PoisonPill.getInstance(), getRef());
}
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.testkit.JavaTestKit;
-import junit.framework.Assert;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
import akka.actor.Props;
import akka.testkit.JavaTestKit;
import com.google.protobuf.ByteString;
-import junit.framework.Assert;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext;
RaftActorBehavior raftBehavior =
follower.handleMessage(followerActor, new ElectionTimeout());
- Assert.assertTrue(raftBehavior instanceof Candidate);
+ assertTrue(raftBehavior instanceof Candidate);
}
@Test
package org.opendaylight.controller.cluster.raft.behaviors;
import akka.actor.ActorRef;
-import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.testkit.JavaTestKit;
+import com.google.common.base.Optional;
import com.google.protobuf.ByteString;
import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
-import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
import org.opendaylight.controller.cluster.raft.SerializationUtils;
import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
+import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
+import org.opendaylight.controller.cluster.raft.base.messages.InitiateInstallSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages;
import org.opendaylight.controller.protobuff.messages.cluster.raft.InstallSnapshotMessages;
+import scala.concurrent.duration.FiniteDuration;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
ActorRef followerActor = getTestActor();
- MockRaftActorContext actorContext =
- (MockRaftActorContext) createActorContext();
+ MockRaftActorContext actorContext = (MockRaftActorContext) createActorContext();
Map<String, String> peerAddresses = new HashMap();
}.get(); // this extracts the received message
assertEquals("match", out);
-
}
-
-
};
}};
}
}
@Test
- public void testSendInstallSnapshot() {
- new LeaderTestKit(getSystem()) {{
+ public void testSendAppendEntriesOnAnInProgressInstallSnapshot() throws Exception {
+ new JavaTestKit(getSystem()) {{
+ ActorRef followerActor = getSystem().actorOf(Props.create(MessageCollectorActor.class));
- new Within(duration("1 seconds")) {
- protected void run() {
- ActorRef followerActor = getTestActor();
+ Map<String, String> peerAddresses = new HashMap();
+ peerAddresses.put(followerActor.path().toString(),
+ followerActor.path().toString());
- Map<String, String> peerAddresses = new HashMap();
- peerAddresses.put(followerActor.path().toString(),
- followerActor.path().toString());
+ MockRaftActorContext actorContext =
+ (MockRaftActorContext) createActorContext(leaderActor);
+ actorContext.setPeerAddresses(peerAddresses);
+ Map<String, String> leadersSnapshot = new HashMap<>();
+ leadersSnapshot.put("1", "A");
+ leadersSnapshot.put("2", "B");
+ leadersSnapshot.put("3", "C");
- MockRaftActorContext actorContext =
- (MockRaftActorContext) createActorContext(getRef());
- actorContext.setPeerAddresses(peerAddresses);
+ //clears leaders log
+ actorContext.getReplicatedLog().removeFrom(0);
+ final int followersLastIndex = 2;
+ final int snapshotIndex = 3;
+ final int newEntryIndex = 4;
+ final int snapshotTerm = 1;
+ final int currentTerm = 2;
- Map<String, String> leadersSnapshot = new HashMap<>();
- leadersSnapshot.put("1", "A");
- leadersSnapshot.put("2", "B");
- leadersSnapshot.put("3", "C");
+ // set the snapshot variables in replicatedlog
+ actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex);
+ actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm);
+ actorContext.setCommitIndex(followersLastIndex);
+ //set follower timeout to 2 mins, helps during debugging
+ actorContext.setConfigParams(new MockConfigParamsImpl(120000L, 10));
- //clears leaders log
- actorContext.getReplicatedLog().removeFrom(0);
+ MockLeader leader = new MockLeader(actorContext);
- final int followersLastIndex = 2;
- final int snapshotIndex = 3;
- final int newEntryIndex = 4;
- final int snapshotTerm = 1;
- final int currentTerm = 2;
+ // new entry
+ ReplicatedLogImplEntry entry =
+ new ReplicatedLogImplEntry(newEntryIndex, currentTerm,
+ new MockRaftActorContext.MockPayload("D"));
- // set the snapshot variables in replicatedlog
- actorContext.getReplicatedLog().setSnapshot(
- toByteString(leadersSnapshot));
- actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex);
- actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm);
+ //update follower timestamp
+ leader.markFollowerActive(followerActor.path().toString());
- MockLeader leader = new MockLeader(actorContext);
- // set the follower info in leader
- leader.addToFollowerToLog(followerActor.path().toString(), followersLastIndex, -1);
+ ByteString bs = toByteString(leadersSnapshot);
+ leader.setSnapshot(Optional.of(bs));
+ leader.createFollowerToSnapshot(followerActor.path().toString(), bs);
- // new entry
- ReplicatedLogImplEntry entry =
- new ReplicatedLogImplEntry(newEntryIndex, currentTerm,
- new MockRaftActorContext.MockPayload("D"));
+ //send first chunk and no InstallSnapshotReply received yet
+ leader.getFollowerToSnapshot().getNextChunk();
+ leader.getFollowerToSnapshot().incrementChunkIndex();
- // this should invoke a sendinstallsnapshot as followersLastIndex < snapshotIndex
- RaftActorBehavior raftBehavior = leader.handleMessage(
- senderActor, new Replicate(null, "state-id", entry));
+ leader.handleMessage(leaderActor, new SendHeartBeat());
- assertTrue(raftBehavior instanceof Leader);
+ AppendEntriesMessages.AppendEntries aeproto = (AppendEntriesMessages.AppendEntries)MessageCollectorActor.getFirstMatching(
+ followerActor, AppendEntries.SERIALIZABLE_CLASS);
- // we might receive some heartbeat messages, so wait till we SendInstallSnapshot
- Boolean[] matches = new ReceiveWhile<Boolean>(Boolean.class, duration("2 seconds")) {
- @Override
- protected Boolean match(Object o) throws Exception {
- if (o instanceof SendInstallSnapshot) {
- return true;
- }
- return false;
- }
- }.get();
+ assertNotNull("AppendEntries should be sent even if InstallSnapshotReply is not " +
+ "received", aeproto);
- boolean sendInstallSnapshotReceived = false;
- for (Boolean b: matches) {
- sendInstallSnapshotReceived = b | sendInstallSnapshotReceived;
- }
+ AppendEntries ae = (AppendEntries) SerializationUtils.fromSerializable(aeproto);
+
+ assertTrue("AppendEntries should be sent with empty entries", ae.getEntries().isEmpty());
+
+ //InstallSnapshotReply received
+ leader.getFollowerToSnapshot().markSendStatus(true);
+
+ leader.handleMessage(senderActor, new SendHeartBeat());
+
+ InstallSnapshotMessages.InstallSnapshot isproto = (InstallSnapshotMessages.InstallSnapshot)
+ MessageCollectorActor.getFirstMatching(followerActor,
+ InstallSnapshot.SERIALIZABLE_CLASS);
+
+ assertNotNull("Installsnapshot should get called for sending the next chunk of snapshot",
+ isproto);
+
+ InstallSnapshot is = (InstallSnapshot) SerializationUtils.fromSerializable(isproto);
- assertTrue(sendInstallSnapshotReceived);
+ assertEquals(snapshotIndex, is.getLastIncludedIndex());
+ }};
+ }
+
+ @Test
+ public void testSendAppendEntriesSnapshotScenario() {
+ new JavaTestKit(getSystem()) {{
+
+ ActorRef followerActor = getTestActor();
+
+ Map<String, String> peerAddresses = new HashMap();
+ peerAddresses.put(followerActor.path().toString(),
+ followerActor.path().toString());
+
+ MockRaftActorContext actorContext =
+ (MockRaftActorContext) createActorContext(getRef());
+ actorContext.setPeerAddresses(peerAddresses);
+
+ Map<String, String> leadersSnapshot = new HashMap<>();
+ leadersSnapshot.put("1", "A");
+ leadersSnapshot.put("2", "B");
+ leadersSnapshot.put("3", "C");
+
+ //clears leaders log
+ actorContext.getReplicatedLog().removeFrom(0);
+
+ final int followersLastIndex = 2;
+ final int snapshotIndex = 3;
+ final int newEntryIndex = 4;
+ final int snapshotTerm = 1;
+ final int currentTerm = 2;
+
+ // set the snapshot variables in replicatedlog
+ actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex);
+ actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm);
+ actorContext.setCommitIndex(followersLastIndex);
+
+ Leader leader = new Leader(actorContext);
+
+ // new entry
+ ReplicatedLogImplEntry entry =
+ new ReplicatedLogImplEntry(newEntryIndex, currentTerm,
+ new MockRaftActorContext.MockPayload("D"));
+
+ //update follower timestamp
+ leader.markFollowerActive(followerActor.path().toString());
+
+ // this should invoke a sendinstallsnapshot as followersLastIndex < snapshotIndex
+ RaftActorBehavior raftBehavior = leader.handleMessage(
+ senderActor, new Replicate(null, "state-id", entry));
+
+ assertTrue(raftBehavior instanceof Leader);
+
+ // we might receive some heartbeat messages, so wait till we InitiateInstallSnapshot
+ Boolean[] matches = new ReceiveWhile<Boolean>(Boolean.class, duration("2 seconds")) {
+ @Override
+ protected Boolean match(Object o) throws Exception {
+ if (o instanceof InitiateInstallSnapshot) {
+ return true;
+ }
+ return false;
}
- };
+ }.get();
+
+ boolean initiateInitiateInstallSnapshot = false;
+ for (Boolean b: matches) {
+ initiateInitiateInstallSnapshot = b | initiateInitiateInstallSnapshot;
+ }
+
+ assertTrue(initiateInitiateInstallSnapshot);
}};
}
@Test
- public void testInstallSnapshot() {
- new LeaderTestKit(getSystem()) {{
+ public void testInitiateInstallSnapshot() throws Exception {
+ new JavaTestKit(getSystem()) {{
- new Within(duration("1 seconds")) {
- protected void run() {
- ActorRef followerActor = getTestActor();
+ ActorRef leaderActor = getSystem().actorOf(Props.create(MessageCollectorActor.class));
- Map<String, String> peerAddresses = new HashMap();
- peerAddresses.put(followerActor.path().toString(),
- followerActor.path().toString());
+ ActorRef followerActor = getTestActor();
- MockRaftActorContext actorContext =
- (MockRaftActorContext) createActorContext();
- actorContext.setPeerAddresses(peerAddresses);
+ Map<String, String> peerAddresses = new HashMap();
+ peerAddresses.put(followerActor.path().toString(),
+ followerActor.path().toString());
- Map<String, String> leadersSnapshot = new HashMap<>();
- leadersSnapshot.put("1", "A");
- leadersSnapshot.put("2", "B");
- leadersSnapshot.put("3", "C");
+ MockRaftActorContext actorContext =
+ (MockRaftActorContext) createActorContext(leaderActor);
+ actorContext.setPeerAddresses(peerAddresses);
- //clears leaders log
- actorContext.getReplicatedLog().removeFrom(0);
+ Map<String, String> leadersSnapshot = new HashMap<>();
+ leadersSnapshot.put("1", "A");
+ leadersSnapshot.put("2", "B");
+ leadersSnapshot.put("3", "C");
- final int followersLastIndex = 2;
- final int snapshotIndex = 3;
- final int newEntryIndex = 4;
- final int snapshotTerm = 1;
- final int currentTerm = 2;
+ //clears leaders log
+ actorContext.getReplicatedLog().removeFrom(0);
- // set the snapshot variables in replicatedlog
- actorContext.getReplicatedLog().setSnapshot(toByteString(leadersSnapshot));
- actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex);
- actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm);
+ final int followersLastIndex = 2;
+ final int snapshotIndex = 3;
+ final int newEntryIndex = 4;
+ final int snapshotTerm = 1;
+ final int currentTerm = 2;
- actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString());
+ // set the snapshot variables in replicatedlog
+ actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex);
+ actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm);
+ actorContext.setLastApplied(3);
+ actorContext.setCommitIndex(followersLastIndex);
- MockLeader leader = new MockLeader(actorContext);
- // set the follower info in leader
- leader.addToFollowerToLog(followerActor.path().toString(), followersLastIndex, -1);
+ Leader leader = new Leader(actorContext);
+ // set the snapshot as absent and check if capture-snapshot is invoked.
+ leader.setSnapshot(Optional.<ByteString>absent());
- // new entry
- ReplicatedLogImplEntry entry =
- new ReplicatedLogImplEntry(newEntryIndex, currentTerm,
- new MockRaftActorContext.MockPayload("D"));
+ // new entry
+ ReplicatedLogImplEntry entry =
+ new ReplicatedLogImplEntry(newEntryIndex, currentTerm,
+ new MockRaftActorContext.MockPayload("D"));
- RaftActorBehavior raftBehavior = leader.handleMessage(senderActor, new SendInstallSnapshot());
+ actorContext.getReplicatedLog().append(entry);
- assertTrue(raftBehavior instanceof Leader);
+ // this should invoke a sendinstallsnapshot as followersLastIndex < snapshotIndex
+ RaftActorBehavior raftBehavior = leader.handleMessage(
+ leaderActor, new InitiateInstallSnapshot());
- // check if installsnapshot gets called with the correct values.
- final String out =
- new ExpectMsg<String>(duration("1 seconds"), "match hint") {
- // do not put code outside this method, will run afterwards
- protected String match(Object in) {
- if (in instanceof InstallSnapshotMessages.InstallSnapshot) {
- InstallSnapshot is = (InstallSnapshot)
- SerializationUtils.fromSerializable(in);
- if (is.getData() == null) {
- return "InstallSnapshot data is null";
- }
- if (is.getLastIncludedIndex() != snapshotIndex) {
- return is.getLastIncludedIndex() + "!=" + snapshotIndex;
- }
- if (is.getLastIncludedTerm() != snapshotTerm) {
- return is.getLastIncludedTerm() + "!=" + snapshotTerm;
- }
- if (is.getTerm() == currentTerm) {
- return is.getTerm() + "!=" + currentTerm;
- }
+ CaptureSnapshot cs = (CaptureSnapshot) MessageCollectorActor.
+ getFirstMatching(leaderActor, CaptureSnapshot.class);
- return "match";
+ assertNotNull(cs);
- } else {
- return "message mismatch:" + in.getClass();
- }
+ assertTrue(cs.isInstallSnapshotInitiated());
+ assertEquals(3, cs.getLastAppliedIndex());
+ assertEquals(1, cs.getLastAppliedTerm());
+ assertEquals(4, cs.getLastIndex());
+ assertEquals(2, cs.getLastTerm());
+ }};
+ }
+
+ @Test
+ public void testInstallSnapshot() {
+ new JavaTestKit(getSystem()) {{
+
+ ActorRef followerActor = getTestActor();
+
+ Map<String, String> peerAddresses = new HashMap();
+ peerAddresses.put(followerActor.path().toString(),
+ followerActor.path().toString());
+
+ MockRaftActorContext actorContext =
+ (MockRaftActorContext) createActorContext();
+ actorContext.setPeerAddresses(peerAddresses);
+
+
+ Map<String, String> leadersSnapshot = new HashMap<>();
+ leadersSnapshot.put("1", "A");
+ leadersSnapshot.put("2", "B");
+ leadersSnapshot.put("3", "C");
+
+ //clears leaders log
+ actorContext.getReplicatedLog().removeFrom(0);
+
+ final int followersLastIndex = 2;
+ final int snapshotIndex = 3;
+ final int newEntryIndex = 4;
+ final int snapshotTerm = 1;
+ final int currentTerm = 2;
+
+ // set the snapshot variables in replicatedlog
+ actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex);
+ actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm);
+ actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString());
+ actorContext.setCommitIndex(followersLastIndex);
+
+ Leader leader = new Leader(actorContext);
+
+ // new entry
+ ReplicatedLogImplEntry entry =
+ new ReplicatedLogImplEntry(newEntryIndex, currentTerm,
+ new MockRaftActorContext.MockPayload("D"));
+
+ RaftActorBehavior raftBehavior = leader.handleMessage(senderActor,
+ new SendInstallSnapshot(toByteString(leadersSnapshot)));
+
+ assertTrue(raftBehavior instanceof Leader);
+
+ // check if installsnapshot gets called with the correct values.
+ final String out =
+ new ExpectMsg<String>(duration("1 seconds"), "match hint") {
+ // do not put code outside this method, will run afterwards
+ protected String match(Object in) {
+ if (in instanceof InstallSnapshotMessages.InstallSnapshot) {
+ InstallSnapshot is = (InstallSnapshot)
+ SerializationUtils.fromSerializable(in);
+ if (is.getData() == null) {
+ return "InstallSnapshot data is null";
+ }
+ if (is.getLastIncludedIndex() != snapshotIndex) {
+ return is.getLastIncludedIndex() + "!=" + snapshotIndex;
+ }
+ if (is.getLastIncludedTerm() != snapshotTerm) {
+ return is.getLastIncludedTerm() + "!=" + snapshotTerm;
+ }
+ if (is.getTerm() == currentTerm) {
+ return is.getTerm() + "!=" + currentTerm;
}
- }.get(); // this extracts the received message
- assertEquals("match", out);
- }
- };
+ return "match";
+
+ } else {
+ return "message mismatch:" + in.getClass();
+ }
+ }
+ }.get(); // this extracts the received message
+
+ assertEquals("match", out);
}};
}
@Test
public void testHandleInstallSnapshotReplyLastChunk() {
- new LeaderTestKit(getSystem()) {{
- new Within(duration("1 seconds")) {
- protected void run() {
- ActorRef followerActor = getTestActor();
+ new JavaTestKit(getSystem()) {{
- Map<String, String> peerAddresses = new HashMap();
- peerAddresses.put(followerActor.path().toString(),
- followerActor.path().toString());
+ ActorRef followerActor = getTestActor();
- MockRaftActorContext actorContext =
- (MockRaftActorContext) createActorContext();
- actorContext.setPeerAddresses(peerAddresses);
+ Map<String, String> peerAddresses = new HashMap();
+ peerAddresses.put(followerActor.path().toString(),
+ followerActor.path().toString());
- final int followersLastIndex = 2;
- final int snapshotIndex = 3;
- final int newEntryIndex = 4;
- final int snapshotTerm = 1;
- final int currentTerm = 2;
-
- MockLeader leader = new MockLeader(actorContext);
- // set the follower info in leader
- leader.addToFollowerToLog(followerActor.path().toString(), followersLastIndex, -1);
-
- Map<String, String> leadersSnapshot = new HashMap<>();
- leadersSnapshot.put("1", "A");
- leadersSnapshot.put("2", "B");
- leadersSnapshot.put("3", "C");
-
- // set the snapshot variables in replicatedlog
- actorContext.getReplicatedLog().setSnapshot(
- toByteString(leadersSnapshot));
- actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex);
- actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm);
- actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString());
-
- ByteString bs = toByteString(leadersSnapshot);
- leader.createFollowerToSnapshot(followerActor.path().toString(), bs);
- while(!leader.getFollowerToSnapshot().isLastChunk(leader.getFollowerToSnapshot().getChunkIndex())) {
- leader.getFollowerToSnapshot().getNextChunk();
- leader.getFollowerToSnapshot().incrementChunkIndex();
- }
+ final int followersLastIndex = 2;
+ final int snapshotIndex = 3;
+ final int newEntryIndex = 4;
+ final int snapshotTerm = 1;
+ final int currentTerm = 2;
- //clears leaders log
- actorContext.getReplicatedLog().removeFrom(0);
+ MockRaftActorContext actorContext =
+ (MockRaftActorContext) createActorContext();
+ actorContext.setPeerAddresses(peerAddresses);
+ actorContext.setCommitIndex(followersLastIndex);
- RaftActorBehavior raftBehavior = leader.handleMessage(senderActor,
- new InstallSnapshotReply(currentTerm, followerActor.path().toString(),
- leader.getFollowerToSnapshot().getChunkIndex(), true));
+ MockLeader leader = new MockLeader(actorContext);
- assertTrue(raftBehavior instanceof Leader);
+ Map<String, String> leadersSnapshot = new HashMap<>();
+ leadersSnapshot.put("1", "A");
+ leadersSnapshot.put("2", "B");
+ leadersSnapshot.put("3", "C");
- assertEquals(leader.mapFollowerToSnapshot.size(), 0);
- assertEquals(leader.followerToLog.size(), 1);
- assertNotNull(leader.followerToLog.get(followerActor.path().toString()));
- FollowerLogInformation fli = leader.followerToLog.get(followerActor.path().toString());
- assertEquals(snapshotIndex, fli.getMatchIndex().get());
- assertEquals(snapshotIndex, fli.getMatchIndex().get());
- assertEquals(snapshotIndex + 1, fli.getNextIndex().get());
- }
- };
+ // set the snapshot variables in replicatedlog
+
+ actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex);
+ actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm);
+ actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString());
+
+ ByteString bs = toByteString(leadersSnapshot);
+ leader.setSnapshot(Optional.of(bs));
+ leader.createFollowerToSnapshot(followerActor.path().toString(), bs);
+ while(!leader.getFollowerToSnapshot().isLastChunk(leader.getFollowerToSnapshot().getChunkIndex())) {
+ leader.getFollowerToSnapshot().getNextChunk();
+ leader.getFollowerToSnapshot().incrementChunkIndex();
+ }
+
+ //clears leaders log
+ actorContext.getReplicatedLog().removeFrom(0);
+
+ RaftActorBehavior raftBehavior = leader.handleMessage(senderActor,
+ new InstallSnapshotReply(currentTerm, followerActor.path().toString(),
+ leader.getFollowerToSnapshot().getChunkIndex(), true));
+
+ assertTrue(raftBehavior instanceof Leader);
+
+ assertEquals(leader.mapFollowerToSnapshot.size(), 0);
+ assertEquals(leader.followerToLog.size(), 1);
+ assertNotNull(leader.followerToLog.get(followerActor.path().toString()));
+ FollowerLogInformation fli = leader.followerToLog.get(followerActor.path().toString());
+ assertEquals(snapshotIndex, fli.getMatchIndex().get());
+ assertEquals(snapshotIndex, fli.getMatchIndex().get());
+ assertEquals(snapshotIndex + 1, fli.getNextIndex().get());
}};
}
followerActorContext.setCommitIndex(1);
Leader leader = new Leader(leaderActorContext);
+ leader.markFollowerActive(followerActor.path().toString());
leader.handleMessage(leaderActor, new SendHeartBeat());
followerActorContext.setCommitIndex(2);
Leader leader = new Leader(leaderActorContext);
+ leader.markFollowerActive(followerActor.path().toString());
leader.handleMessage(leaderActor, new SendHeartBeat());
}
- private static class LeaderTestKit extends JavaTestKit {
-
- private LeaderTestKit(ActorSystem actorSystem) {
- super(actorSystem);
- }
-
- protected void waitForLogMessage(final Class logLevel, ActorRef subject, String logMessage){
- // Wait for a specific log message to show up
- final boolean result =
- new JavaTestKit.EventFilter<Boolean>(logLevel
- ) {
- @Override
- protected Boolean run() {
- return true;
- }
- }.from(subject.path().toString())
- .message(logMessage)
- .occurrences(1).exec();
-
- Assert.assertEquals(true, result);
-
- }
- }
-
class MockLeader extends Leader {
FollowerToSnapshot fts;
super(context);
}
- public void addToFollowerToLog(String followerId, long nextIndex, long matchIndex) {
- FollowerLogInformation followerLogInformation =
- new FollowerLogInformationImpl(followerId,
- new AtomicLong(nextIndex),
- new AtomicLong(matchIndex));
- followerToLog.put(followerId, followerLogInformation);
- }
-
public FollowerToSnapshot getFollowerToSnapshot() {
return fts;
}
}
}
+
+ private class MockConfigParamsImpl extends DefaultConfigParamsImpl {
+
+ private long electionTimeOutIntervalMillis;
+ private int snapshotChunkSize;
+
+ public MockConfigParamsImpl(long electionTimeOutIntervalMillis, int snapshotChunkSize) {
+ super();
+ this.electionTimeOutIntervalMillis = electionTimeOutIntervalMillis;
+ this.snapshotChunkSize = snapshotChunkSize;
+ }
+
+ @Override
+ public FiniteDuration getElectionTimeOutInterval() {
+ return new FiniteDuration(electionTimeOutIntervalMillis, TimeUnit.MILLISECONDS);
+ }
+
+ @Override
+ public int getSnapshotChunkSize() {
+ return snapshotChunkSize;
+ }
+ }
}
actor {
# enable to test serialization only.
- serialize-messages = on
+ serialize-messages = off
serializers {
java = "akka.serialization.JavaSerializer"
package org.opendaylight.controller.sal.binding.codegen.impl;
import com.google.common.base.Supplier;
-
-import java.util.Map;
-import java.util.WeakHashMap;
-
+import com.google.common.collect.Iterables;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
-
-import javax.annotation.concurrent.GuardedBy;
-
import org.eclipse.xtext.xbase.lib.Extension;
import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
import org.opendaylight.controller.sal.binding.codegen.RpcIsNotRoutedException;
import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
import org.opendaylight.yangtools.yang.binding.util.ClassLoaderUtils;
+import javax.annotation.concurrent.GuardedBy;
+import java.util.Map;
+import java.util.WeakHashMap;
+
abstract class AbstractRuntimeCodeGenerator implements org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator, NotificationInvokerFactory {
@GuardedBy("this")
private final Map<Class<? extends NotificationListener>, RuntimeGeneratedInvokerPrototype> invokerClasses = new WeakHashMap<>();
}
});
+ if (Iterables.isEmpty(metadata.getContexts())) {
+ throw new RpcIsNotRoutedException("Service doesn't have routing context associated.");
+ }
+
synchronized (utils) {
final T instance = ClassLoaderUtils.withClassLoader(serviceType.getClassLoader(), routerSupplier(serviceType, metadata));
return new RpcRouterCodegenInstance<T>(name, serviceType, instance, metadata.getContexts());
*/
package org.opendaylight.controller.sal.binding.test;
-import junit.framework.Assert;
-
-
+import static org.junit.Assert.assertNotNull;
import org.opendaylight.yangtools.yang.binding.Augmentable;
import org.opendaylight.yangtools.yang.binding.Augmentation;
public static <T extends Augmentable<T>> void assertHasAugmentation(T object,
Class<? extends Augmentation<T>> augmentation) {
- Assert.assertNotNull(object);
- Assert.assertNotNull("Augmentation " + augmentation.getSimpleName() + " is not present.", object.getAugmentation(augmentation));
+ assertNotNull(object);
+ assertNotNull("Augmentation " + augmentation.getSimpleName() + " is not present.", object.getAugmentation(augmentation));
}
public static <T extends Augmentable<T>> AugmentationVerifier<T> from(T obj) {
*/
package org.opendaylight.controller.sal.binding.test.connect.dom;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertNotSame;
-import static junit.framework.Assert.assertTrue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertTrue;
import java.math.BigInteger;
import java.util.Collections;
*/
package org.opendaylight.controller.sal.binding.test.connect.dom;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.fail;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.InputStream;
import java.util.Collections;
*/
package org.opendaylight.controller.sal.binding.test.connect.dom;
-import static junit.framework.Assert.assertNotNull;
+import static org.junit.Assert.assertNotNull;
import java.util.concurrent.Future;
import java.util.List;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class NormalizedNodeToNodeCodecTest {
package org.opendaylight.controller.cluster.datastore.node.utils;
-import junit.framework.Assert;
+import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
NodeIdentifierFactory
.getArgument("AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}");
- Assert
- .assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier);
+ assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier);
}
import org.opendaylight.controller.cluster.datastore.util.TestModel;
import org.opendaylight.yangtools.yang.common.QName;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.TestCase.assertEquals;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
public class QNameFactoryTest {
package org.opendaylight.controller.xml.codec;
-
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.io.ByteSource;
-import junit.framework.Assert;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-
public class XmlUtilsTest {
private static final DocumentBuilderFactory BUILDERFACTORY;
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-inmemory-datastore</artifactId>
- <version>1.2.0-SNAPSHOT</version>
</dependency>
<dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-clustering-commons</artifactId>
- <version>1.2.0-SNAPSHOT</version>
</dependency>
<dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
- <version>${slf4j.version}</version>
<scope>test</scope>
</dependency>
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigObject;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
+import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy;
+import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ConfigurationImpl implements Configuration {
// Look up maps to speed things up
// key = memberName, value = list of shardNames
- private Map<String, List<String>> memberShardNames = new HashMap<>();
+ private final Map<String, List<String>> memberShardNames = new HashMap<>();
// key = shardName, value = list of replicaNames (replicaNames are the same as memberNames)
- private Map<String, List<String>> shardReplicaNames = new HashMap<>();
+ private final Map<String, List<String>> shardReplicaNames = new HashMap<>();
- public ConfigurationImpl(String moduleShardsConfigPath,
+ public ConfigurationImpl(final String moduleShardsConfigPath,
- String modulesConfigPath){
+ final String modulesConfigPath){
Preconditions.checkNotNull(moduleShardsConfigPath, "moduleShardsConfigPath should not be null");
Preconditions.checkNotNull(modulesConfigPath, "modulesConfigPath should not be null");
readModules(modulesConfig);
}
- @Override public List<String> getMemberShardNames(String memberName){
+ @Override public List<String> getMemberShardNames(final String memberName){
Preconditions.checkNotNull(memberName, "memberName should not be null");
return memberShardNames.get(memberName);
}
- List<String> shards = new ArrayList();
+ List<String> shards = new ArrayList<>();
for(ModuleShard ms : moduleShards){
for(Shard s : ms.getShards()){
for(String m : s.getReplicas()){
}
- @Override public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
+ @Override public Optional<String> getModuleNameFromNameSpace(final String nameSpace) {
Preconditions.checkNotNull(nameSpace, "nameSpace should not be null");
return map;
}
- @Override public List<String> getShardNamesFromModuleName(String moduleName) {
+ @Override public List<String> getShardNamesFromModuleName(final String moduleName) {
Preconditions.checkNotNull(moduleName, "moduleName should not be null");
}
}
- return Collections.EMPTY_LIST;
+ return Collections.emptyList();
}
- @Override public List<String> getMembersFromShardName(String shardName) {
+ @Override public List<String> getMembersFromShardName(final String shardName) {
Preconditions.checkNotNull(shardName, "shardName should not be null");
}
}
}
- shardReplicaNames.put(shardName, Collections.EMPTY_LIST);
- return Collections.EMPTY_LIST;
+ shardReplicaNames.put(shardName, Collections.<String>emptyList());
+ return Collections.emptyList();
}
@Override public Set<String> getAllShardNames() {
- private void readModules(Config modulesConfig) {
+ private void readModules(final Config modulesConfig) {
List<? extends ConfigObject> modulesConfigObjectList =
modulesConfig.getObjectList("modules");
}
}
- private void readModuleShards(Config moduleShardsConfig) {
+ private void readModuleShards(final Config moduleShardsConfig) {
List<? extends ConfigObject> moduleShardsConfigObjectList =
moduleShardsConfig.getObjectList("module-shards");
private final String moduleName;
private final List<Shard> shards;
- public ModuleShard(String moduleName, List<Shard> shards) {
+ public ModuleShard(final String moduleName, final List<Shard> shards) {
this.moduleName = moduleName;
this.shards = shards;
}
private final String name;
private final List<String> replicas;
- Shard(String name, List<String> replicas) {
+ Shard(final String name, final List<String> replicas) {
this.name = name;
this.replicas = replicas;
}
private final String nameSpace;
private final ShardStrategy shardStrategy;
- Module(String name, String nameSpace, String shardStrategy) {
+ Module(final String name, final String nameSpace, final String shardStrategy) {
this.name = name;
this.nameSpace = nameSpace;
if(ModuleShardStrategy.NAME.equals(shardStrategy)){
private final ConfigObject configObject;
- ConfigObjectWrapper(ConfigObject configObject){
+ ConfigObjectWrapper(final ConfigObject configObject){
this.configObject = configObject;
}
- public String stringValue(String name){
+ public String stringValue(final String name){
return configObject.get(name).unwrapped().toString();
}
}
return recordedOperationFutures;
}
+ @VisibleForTesting
+ boolean hasTransactionContext() {
+ for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
+ TransactionContext transactionContext = txFutureCallback.getTransactionContext();
+ if(transactionContext != null) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(
final YangInstanceIdentifier path) {
// respect to #addTxOperationOnComplete to handle timing issues and ensure no
// TransactionOperation is missed and that they are processed in the order they occurred.
synchronized(txOperationsOnComplete) {
+ // Store the new TransactionContext locally until we've completed invoking the
+ // TransactionOperations. This avoids thread timing issues which could cause
+ // out-of-order TransactionOperations. Eg, on a modification operation, if the
+ // TransactionContext is non-null, then we directly call the TransactionContext.
+ // However, at the same time, the code may be executing the cached
+ // TransactionOperations. So to avoid thus timing, we don't publish the
+ // TransactionContext until after we've executed all cached TransactionOperations.
+ TransactionContext localTransactionContext;
if(failure != null) {
LOG.debug("Tx {} Creating NoOpTransaction because of error: {}", identifier,
failure.getMessage());
- transactionContext = new NoOpTransactionContext(failure, identifier);
+ localTransactionContext = new NoOpTransactionContext(failure, identifier);
} else if (response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)) {
- createValidTransactionContext(CreateTransactionReply.fromSerializable(response));
+ localTransactionContext = createValidTransactionContext(
+ CreateTransactionReply.fromSerializable(response));
} else {
IllegalArgumentException exception = new IllegalArgumentException(String.format(
"Invalid reply type %s for CreateTransaction", response.getClass()));
- transactionContext = new NoOpTransactionContext(exception, identifier);
+ localTransactionContext = new NoOpTransactionContext(exception, identifier);
}
for(TransactionOperation oper: txOperationsOnComplete) {
- oper.invoke(transactionContext);
+ oper.invoke(localTransactionContext);
}
txOperationsOnComplete.clear();
+
+ // We're done invoking the TransactionOperations so we can now publish the
+ // TransactionContext.
+ transactionContext = localTransactionContext;
}
}
- private void createValidTransactionContext(CreateTransactionReply reply) {
+ private TransactionContext createValidTransactionContext(CreateTransactionReply reply) {
String transactionPath = reply.getTransactionPath();
LOG.debug("Tx {} Received transaction actor path {}", identifier, transactionPath);
// Check if TxActor is created in the same node
boolean isTxActorLocal = actorContext.isLocalPath(transactionPath);
- transactionContext = new TransactionContextImpl(transactionPath, transactionActor, identifier,
+ return new TransactionContextImpl(transactionPath, transactionActor, identifier,
actorContext, schemaContext, isTxActorLocal, reply.getVersion());
}
}
import org.opendaylight.controller.protobuff.messages.cohort3pc.ThreePhaseCommitCohortMessages;
public class CanCommitTransactionReply implements SerializableMessage {
- public static Class<ThreePhaseCommitCohortMessages.CanCommitTransactionReply> SERIALIZABLE_CLASS =
+ public static final Class<ThreePhaseCommitCohortMessages.CanCommitTransactionReply> SERIALIZABLE_CLASS =
ThreePhaseCommitCohortMessages.CanCommitTransactionReply.class;
private final Boolean canCommit;
- public CanCommitTransactionReply(Boolean canCommit) {
+ public CanCommitTransactionReply(final Boolean canCommit) {
this.canCommit = canCommit;
}
return ThreePhaseCommitCohortMessages.CanCommitTransactionReply.newBuilder().setCanCommit(canCommit).build();
}
- public static CanCommitTransactionReply fromSerializable(Object message) {
+ public static CanCommitTransactionReply fromSerializable(final Object message) {
return new CanCommitTransactionReply(
((ThreePhaseCommitCohortMessages.CanCommitTransactionReply) message).getCanCommit());
}
import org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages;
public class CloseDataChangeListenerRegistration implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS = ListenerRegistrationMessages.CloseDataChangeListenerRegistration.class;
+ public static final Class<ListenerRegistrationMessages.CloseDataChangeListenerRegistration> SERIALIZABLE_CLASS =
+ ListenerRegistrationMessages.CloseDataChangeListenerRegistration.class;
@Override
public Object toSerializable() {
return ListenerRegistrationMessages.CloseDataChangeListenerRegistration.newBuilder().build();
import org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages;
public class CloseDataChangeListenerRegistrationReply implements SerializableMessage{
- public static Class SERIALIZABLE_CLASS = ListenerRegistrationMessages.CloseDataChangeListenerRegistrationReply.class;
+ public static final Class<ListenerRegistrationMessages.CloseDataChangeListenerRegistrationReply> SERIALIZABLE_CLASS =
+ ListenerRegistrationMessages.CloseDataChangeListenerRegistrationReply.class;
@Override
public Object toSerializable() {
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages;
public class CloseTransaction implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.CloseTransaction.class;
+ public static final Class<ShardTransactionMessages.CloseTransaction> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.CloseTransaction.class;
@Override
public Object toSerializable() {
return ShardTransactionMessages.CloseTransaction.newBuilder().build();
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages;
public class CloseTransactionChain implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS =
+ public static final Class<ShardTransactionChainMessages.CloseTransactionChain> SERIALIZABLE_CLASS =
ShardTransactionChainMessages.CloseTransactionChain.class;
private final String transactionChainId;
- public CloseTransactionChain(String transactionChainId){
+ public CloseTransactionChain(final String transactionChainId){
this.transactionChainId = transactionChainId;
}
.setTransactionChainId(transactionChainId).build();
}
- public static CloseTransactionChain fromSerializable(Object message){
+ public static CloseTransactionChain fromSerializable(final Object message){
ShardTransactionChainMessages.CloseTransactionChain closeTransactionChain
= (ShardTransactionChainMessages.CloseTransactionChain) message;
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages;
public class CloseTransactionChainReply implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS = ShardTransactionChainMessages.CloseTransactionChainReply.class;
+ public static final Class<ShardTransactionChainMessages.CloseTransactionChainReply> SERIALIZABLE_CLASS =
+ ShardTransactionChainMessages.CloseTransactionChainReply.class;
@Override
public Object toSerializable() {
return ShardTransactionChainMessages.CloseTransactionChainReply.newBuilder().build();
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages;
public class CloseTransactionReply implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.CloseTransactionReply.class;
+ public static final Class<ShardTransactionMessages.CloseTransactionReply> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.CloseTransactionReply.class;
@Override
public Object toSerializable() {
return ShardTransactionMessages.CloseTransactionReply.newBuilder().build();
public class CreateTransactionReply implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.CreateTransactionReply.class;
+ public static final Class<ShardTransactionMessages.CreateTransactionReply> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.CreateTransactionReply.class;
private final String transactionPath;
private final String transactionId;
private final int version;
- public CreateTransactionReply(String transactionPath,
- String transactionId) {
+ public CreateTransactionReply(final String transactionPath,
+ final String transactionId) {
this(transactionPath, transactionId, CreateTransaction.CURRENT_VERSION);
}
- public CreateTransactionReply(String transactionPath,
- String transactionId, int version) {
+ public CreateTransactionReply(final String transactionPath,
+ final String transactionId, final int version) {
this.transactionPath = transactionPath;
this.transactionId = transactionId;
this.version = version;
return version;
}
+ @Override
public Object toSerializable(){
return ShardTransactionMessages.CreateTransactionReply.newBuilder()
.setTransactionActorPath(transactionPath)
.build();
}
- public static CreateTransactionReply fromSerializable(Object serializable){
+ public static CreateTransactionReply fromSerializable(final Object serializable){
ShardTransactionMessages.CreateTransactionReply o = (ShardTransactionMessages.CreateTransactionReply) serializable;
return new CreateTransactionReply(o.getTransactionActorPath(), o.getTransactionId(), o.getMessageVersion());
}
import org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages;
public class DataChangedReply implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS = DataChangeListenerMessages.DataChangedReply.class;
+ public static final Class<DataChangeListenerMessages.DataChangedReply> SERIALIZABLE_CLASS =
+ DataChangeListenerMessages.DataChangedReply.class;
@Override
public Object toSerializable() {
return DataChangeListenerMessages.DataChangedReply.newBuilder().build();
public class DataExists implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DataExists.class;
+ public static final Class<ShardTransactionMessages.DataExists> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.DataExists.class;
private final YangInstanceIdentifier path;
- public DataExists(YangInstanceIdentifier path) {
+ public DataExists(final YangInstanceIdentifier path) {
this.path = path;
}
InstanceIdentifierUtils.toSerializable(path)).build();
}
- public static DataExists fromSerializable(Object serializable){
+ public static DataExists fromSerializable(final Object serializable){
ShardTransactionMessages.DataExists o = (ShardTransactionMessages.DataExists) serializable;
return new DataExists(InstanceIdentifierUtils.fromSerializable(o.getInstanceIdentifierPathArguments()));
}
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages;
public class DataExistsReply implements SerializableMessage{
-
-
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DataExistsReply.class;
+ public static final Class<ShardTransactionMessages.DataExistsReply> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.DataExistsReply.class;
private final boolean exists;
- public DataExistsReply(boolean exists) {
+ public DataExistsReply(final boolean exists) {
this.exists = exists;
}
.setExists(exists).build();
}
- public static DataExistsReply fromSerializable(Object serializable){
+ public static DataExistsReply fromSerializable(final Object serializable){
ShardTransactionMessages.DataExistsReply o = (ShardTransactionMessages.DataExistsReply) serializable;
return new DataExistsReply(o.getExists());
}
public class DeleteData implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DeleteData.class;
+ public static final Class<ShardTransactionMessages.DeleteData> SERIALIZABLE_CLASS = ShardTransactionMessages.DeleteData.class;
private final YangInstanceIdentifier path;
- public DeleteData(YangInstanceIdentifier path) {
+ public DeleteData(final YangInstanceIdentifier path) {
this.path = path;
}
.setInstanceIdentifierPathArguments(InstanceIdentifierUtils.toSerializable(path)).build();
}
- public static DeleteData fromSerializable(Object serializable){
+ public static DeleteData fromSerializable(final Object serializable){
ShardTransactionMessages.DeleteData o = (ShardTransactionMessages.DeleteData) serializable;
return new DeleteData(InstanceIdentifierUtils.fromSerializable(o.getInstanceIdentifierPathArguments()));
}
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages;
public class DeleteDataReply implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DeleteDataReply.class;
+ public static final Class<ShardTransactionMessages.DeleteDataReply> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.DeleteDataReply.class;
@Override
public Object toSerializable() {
return ShardTransactionMessages.DeleteDataReply.newBuilder().build();
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages;
public class MergeDataReply implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.MergeDataReply.class;
+ public static final Class<ShardTransactionMessages.MergeDataReply> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.MergeDataReply.class;
@Override
public Object toSerializable() {
public class PreCommitTransaction implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ThreePhaseCommitCohortMessages.PreCommitTransaction.class;
+ public static final Class<ThreePhaseCommitCohortMessages.PreCommitTransaction> SERIALIZABLE_CLASS =
+ ThreePhaseCommitCohortMessages.PreCommitTransaction.class;
@Override
public Object toSerializable() {
public class PreCommitTransactionReply implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ThreePhaseCommitCohortMessages.PreCommitTransactionReply.class;
+ public static final Class<ThreePhaseCommitCohortMessages.PreCommitTransactionReply> SERIALIZABLE_CLASS =
+ ThreePhaseCommitCohortMessages.PreCommitTransactionReply.class;
@Override
public Object toSerializable() {
public class PrimaryFound implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS = PrimaryFound.class;
+ public static final Class<PrimaryFound> SERIALIZABLE_CLASS = PrimaryFound.class;
private final String primaryPath;
- public PrimaryFound(String primaryPath) {
+ public PrimaryFound(final String primaryPath) {
this.primaryPath = primaryPath;
}
}
@Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
PrimaryFound that = (PrimaryFound) o;
- if (!primaryPath.equals(that.primaryPath)) return false;
+ if (!primaryPath.equals(that.primaryPath)) {
+ return false;
+ }
return true;
}
return this;
}
- public static PrimaryFound fromSerializable(Object message){
+ public static PrimaryFound fromSerializable(final Object message){
return (PrimaryFound) message;
}
}
import com.google.common.base.Preconditions;
public class PrimaryNotFound implements SerializableMessage {
- public static final Class SERIALIZABLE_CLASS = PrimaryNotFound.class;
+ public static final Class<PrimaryNotFound> SERIALIZABLE_CLASS = PrimaryNotFound.class;
private final String shardName;
- public PrimaryNotFound(String shardName){
+ public PrimaryNotFound(final String shardName){
Preconditions.checkNotNull(shardName, "shardName should not be null");
}
@Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
PrimaryNotFound that = (PrimaryNotFound) o;
- if (shardName != null ? !shardName.equals(that.shardName) : that.shardName != null) return false;
+ if (shardName != null ? !shardName.equals(that.shardName) : that.shardName != null) {
+ return false;
+ }
return true;
}
return this;
}
- public static PrimaryNotFound fromSerializable(Object message){
+ public static PrimaryNotFound fromSerializable(final Object message){
return (PrimaryNotFound) message;
}
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
public class ReadData {
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.ReadData.class;
+ public static final Class<ShardTransactionMessages.ReadData> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.ReadData.class;
private final YangInstanceIdentifier path;
- public ReadData(YangInstanceIdentifier path) {
+ public ReadData(final YangInstanceIdentifier path) {
this.path = path;
}
.build();
}
- public static ReadData fromSerializable(Object serializable){
+ public static ReadData fromSerializable(final Object serializable){
ShardTransactionMessages.ReadData o = (ShardTransactionMessages.ReadData) serializable;
return new ReadData(InstanceIdentifierUtils.fromSerializable(o.getInstanceIdentifierPathArguments()));
}
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages;
public class ReadyTransaction implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.ReadyTransaction.class;
+ public static final Class<ShardTransactionMessages.ReadyTransaction> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.ReadyTransaction.class;
@Override
public Object toSerializable() {
import org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages;
public class RegisterChangeListenerReply implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ListenerRegistrationMessages.RegisterChangeListenerReply.class;
+ public static final Class<ListenerRegistrationMessages.RegisterChangeListenerReply> SERIALIZABLE_CLASS =
+ ListenerRegistrationMessages.RegisterChangeListenerReply.class;
private final ActorPath listenerRegistrationPath;
- public RegisterChangeListenerReply(ActorPath listenerRegistrationPath) {
+ public RegisterChangeListenerReply(final ActorPath listenerRegistrationPath) {
this.listenerRegistrationPath = listenerRegistrationPath;
}
.setListenerRegistrationPath(listenerRegistrationPath.toString()).build();
}
- public static RegisterChangeListenerReply fromSerializable(ActorSystem actorSystem,Object serializable){
+ public static RegisterChangeListenerReply fromSerializable(final ActorSystem actorSystem,final Object serializable){
ListenerRegistrationMessages.RegisterChangeListenerReply o = (ListenerRegistrationMessages.RegisterChangeListenerReply) serializable;
return new RegisterChangeListenerReply(
actorSystem.actorFor(o.getListenerRegistrationPath()).path()
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages;
public class WriteDataReply implements SerializableMessage{
- public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.WriteDataReply.class;
+ public static final Class<ShardTransactionMessages.WriteDataReply> SERIALIZABLE_CLASS =
+ ShardTransactionMessages.WriteDataReply.class;
@Override
public Object toSerializable() {
return ShardTransactionMessages.WriteDataReply.newBuilder().build();
* MergeModification stores all the parameters required to merge data into the specified path
*/
public class MergeModification extends WriteModification {
+ private static final long serialVersionUID = 1L;
- public MergeModification(YangInstanceIdentifier path, NormalizedNode data,
- SchemaContext schemaContext) {
+ public MergeModification(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
+ final SchemaContext schemaContext) {
super(path, data, schemaContext);
}
@Override
- public void apply(DOMStoreWriteTransaction transaction) {
+ public void apply(final DOMStoreWriteTransaction transaction) {
transaction.merge(path, data);
}
- public static MergeModification fromSerializable(Object serializable, SchemaContext schemaContext) {
+ public static MergeModification fromSerializable(final Object serializable, final SchemaContext schemaContext) {
PersistentMessages.Modification o = (PersistentMessages.Modification) serializable;
Decoded decoded = new NormalizedNodeToNodeCodec(schemaContext).decode(o.getPath(), o.getData());
return new MergeModification(decoded.getDecodedPath(), decoded.getDecodedNode(), schemaContext);
* WriteModification stores all the parameters required to write data to the specified path
*/
public class WriteModification extends AbstractModification {
-
- protected final NormalizedNode data;
+ private static final long serialVersionUID = 1L;
+ protected final NormalizedNode<?, ?> data;
private final SchemaContext schemaContext;
- public WriteModification(YangInstanceIdentifier path, NormalizedNode data, SchemaContext schemaContext) {
+ public WriteModification(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final SchemaContext schemaContext) {
super(path);
this.data = data;
this.schemaContext = schemaContext;
}
@Override
- public void apply(DOMStoreWriteTransaction transaction) {
+ public void apply(final DOMStoreWriteTransaction transaction) {
transaction.write(path, data);
}
- public NormalizedNode getData() {
+ public NormalizedNode<?, ?> getData() {
return data;
}
.build();
}
- public static WriteModification fromSerializable(Object serializable, SchemaContext schemaContext) {
+ public static WriteModification fromSerializable(final Object serializable, final SchemaContext schemaContext) {
PersistentMessages.Modification o = (PersistentMessages.Modification) serializable;
Decoded decoded = new NormalizedNodeToNodeCodec(schemaContext).decode(o.getPath(), o.getData());
return new WriteModification(decoded.getDecodedPath(), decoded.getDecodedNode(), schemaContext);
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import org.opendaylight.controller.cluster.datastore.Configuration;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import org.opendaylight.controller.cluster.datastore.Configuration;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
public class ShardStrategyFactory {
private static Map<String, ShardStrategy> moduleNameToStrategyMap =
- new ConcurrentHashMap();
+ new ConcurrentHashMap<>();
private static final String UNKNOWN_MODULE_NAME = "unknown";
private static Configuration configuration;
- public static void setConfiguration(Configuration configuration){
+ public static void setConfiguration(final Configuration configuration){
ShardStrategyFactory.configuration = configuration;
moduleNameToStrategyMap = configuration.getModuleNameToShardStrategyMap();
}
- public static ShardStrategy getStrategy(YangInstanceIdentifier path) {
+ public static ShardStrategy getStrategy(final YangInstanceIdentifier path) {
Preconditions.checkState(configuration != null, "configuration should not be missing");
Preconditions.checkNotNull(path, "path should not be null");
}
- private static String getModuleName(YangInstanceIdentifier path) {
+ private static String getModuleName(final YangInstanceIdentifier path) {
String namespace = path.getPathArguments().iterator().next().getNodeType().getNamespace().toASCIIString();
Optional<String> optional =
package org.opendaylight.controller.cluster.datastore;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import com.typesafe.config.ConfigFactory;
-import junit.framework.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
import java.io.File;
import java.util.List;
import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
public class ConfigurationImplTest {
import akka.actor.ActorRef;
import akka.actor.Props;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.messages.DataChanged;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
public class DataChangeListenerProxyTest extends AbstractActorTest {
private static class MockDataChangedEvent implements AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> {
- Map<YangInstanceIdentifier,NormalizedNode<?,?>> createdData = new HashMap();
- Map<YangInstanceIdentifier,NormalizedNode<?,?>> updatedData = new HashMap();
- Map<YangInstanceIdentifier,NormalizedNode<?,?>> originalData = new HashMap();
+ Map<YangInstanceIdentifier,NormalizedNode<?,?>> createdData = new HashMap<>();
+ Map<YangInstanceIdentifier,NormalizedNode<?,?>> updatedData = new HashMap<>();
+ Map<YangInstanceIdentifier,NormalizedNode<?,?>> originalData = new HashMap<>();
Assert.assertTrue(messages instanceof List);
- List<Object> listMessages = (List<Object>) messages;
+ List<?> listMessages = (List<?>) messages;
Assert.assertEquals(1, listMessages.size());
DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
- Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS);
- assertEquals("canCommit", true, canCommit);
- cohort.preCommit().get(5, TimeUnit.SECONDS);
- cohort.commit().get(5, TimeUnit.SECONDS);
+ doCommit(cohort);
// Verify the data in the store
// 5. Commit the Tx
- Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS);
- assertEquals("canCommit", true, canCommit);
- cohort.preCommit().get(5, TimeUnit.SECONDS);
- cohort.commit().get(5, TimeUnit.SECONDS);
+ doCommit(cohort);
// 6. Verify the data in the store
// Wait for the Tx commit to complete.
- assertEquals("canCommit", true, txCohort.get().canCommit().get(5, TimeUnit.SECONDS));
- txCohort.get().preCommit().get(5, TimeUnit.SECONDS);
- txCohort.get().commit().get(5, TimeUnit.SECONDS);
+ doCommit(txCohort.get());
// Verify the data in the store
@Test
public void testTransactionChain() throws Exception{
- System.setProperty("shard.persistent", "true");
new IntegrationTestKit(getSystem()) {{
- DistributedDataStore dataStore =
- setupDistributedDataStore("transactionChainIntegrationTest", "test-1");
+ DistributedDataStore dataStore = setupDistributedDataStore("testTransactionChain", "test-1");
// 1. Create a Tx chain and write-only Tx
assertEquals("Data node", outerNode, optional.get());
cleanup(dataStore);
- }
-
- private void doCommit(final DOMStoreThreePhaseCommitCohort cohort1) throws Exception {
- Boolean canCommit = cohort1.canCommit().get(5, TimeUnit.SECONDS);
- assertEquals("canCommit", true, canCommit);
- cohort1.preCommit().get(5, TimeUnit.SECONDS);
- cohort1.commit().get(5, TimeUnit.SECONDS);
}};
}
DistributedDataStore dataStore =
setupDistributedDataStore("testChangeListenerRegistration", "test-1");
- MockDataChangeListener listener = new MockDataChangeListener(3);
+ testWriteTransaction(dataStore, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+
+ MockDataChangeListener listener = new MockDataChangeListener(1);
ListenerRegistration<MockDataChangeListener>
listenerReg = dataStore.registerChangeListener(TestModel.TEST_PATH, listener,
assertNotNull("registerChangeListener returned null", listenerReg);
- testWriteTransaction(dataStore, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ // Wait for the initial notification
+
+ listener.waitForChangeEvents(TestModel.TEST_PATH);
+
+ listener.reset(2);
+
+ // Write 2 updates.
testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
testWriteTransaction(dataStore, listPath,
ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
- listener.waitForChangeEvents(TestModel.TEST_PATH, TestModel.OUTER_LIST_PATH, listPath );
+ // Wait for the 2 updates.
+
+ listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath);
listenerReg.close();
// 4. Commit the Tx
- Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS);
- assertEquals("canCommit", true, canCommit);
- cohort.preCommit().get(5, TimeUnit.SECONDS);
- cohort.commit().get(5, TimeUnit.SECONDS);
+ doCommit(cohort);
// 5. Verify the data in the store
assertEquals("Data node", nodeToWrite, optional.get());
}
+ void doCommit(final DOMStoreThreePhaseCommitCohort cohort) throws Exception {
+ Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS);
+ assertEquals("canCommit", true, canCommit);
+ cohort.preCommit().get(5, TimeUnit.SECONDS);
+ cohort.commit().get(5, TimeUnit.SECONDS);
+ }
+
void cleanup(DistributedDataStore dataStore) {
dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), null);
}
package org.opendaylight.controller.cluster.datastore;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.opendaylight.controller.cluster.datastore.messages.CreateTransaction.CURRENT_VERSION;
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.actor.Props;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Uninterruptibles;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import scala.concurrent.Future;
import scala.concurrent.duration.FiniteDuration;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.inOrder;
-import static org.mockito.Mockito.mock;
-import static org.opendaylight.controller.cluster.datastore.messages.CreateTransaction.CURRENT_VERSION;
-
public class ShardTest extends AbstractActorTest {
}};
}
+ @SuppressWarnings("serial")
@Test
public void testPeerAddressResolved() throws Exception {
new ShardTestKit(getSystem()) {{
shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
}
- private CompositeModificationPayload newPayload(Modification... mods) {
+ private CompositeModificationPayload newPayload(final Modification... mods) {
MutableCompositeModification compMod = new MutableCompositeModification();
for(Modification mod: mods) {
compMod.addModification(mod);
return new CompositeModificationPayload(compMod.toSerializable());
}
- private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(String cohortName,
- InMemoryDOMDataStore dataStore, YangInstanceIdentifier path, NormalizedNode data,
- MutableCompositeModification modification) {
+ private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(final String cohortName,
+ final InMemoryDOMDataStore dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
+ final MutableCompositeModification modification) {
return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
}
- private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(String cohortName,
- InMemoryDOMDataStore dataStore, YangInstanceIdentifier path, NormalizedNode data,
- MutableCompositeModification modification,
+ private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(final String cohortName,
+ final InMemoryDOMDataStore dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
+ final MutableCompositeModification modification,
final Function<DOMStoreThreePhaseCommitCohort,ListenableFuture<Void>> preCommit) {
DOMStoreWriteTransaction tx = dataStore.newWriteOnlyTransaction();
doAnswer(new Answer<ListenableFuture<Boolean>>() {
@Override
- public ListenableFuture<Boolean> answer(InvocationOnMock invocation) {
+ public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
return realCohort.canCommit();
}
}).when(cohort).canCommit();
doAnswer(new Answer<ListenableFuture<Void>>() {
@Override
- public ListenableFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
+ public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
if(preCommit != null) {
return preCommit.apply(realCohort);
} else {
doAnswer(new Answer<ListenableFuture<Void>>() {
@Override
- public ListenableFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
+ public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
return realCohort.commit();
}
}).when(cohort).commit();
doAnswer(new Answer<ListenableFuture<Void>>() {
@Override
- public ListenableFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
+ public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
return realCohort.abort();
}
}).when(cohort).abort();
class OnFutureComplete extends OnComplete<Object> {
private final Class<?> expRespType;
- OnFutureComplete(Class<?> expRespType) {
+ OnFutureComplete(final Class<?> expRespType) {
this.expRespType = expRespType;
}
@Override
- public void onComplete(Throwable error, Object resp) {
+ public void onComplete(final Throwable error, final Object resp) {
if(error != null) {
caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
} else {
}
}
- void onSuccess(Object resp) throws Exception {
+ void onSuccess(final Object resp) throws Exception {
}
}
}
@Override
- public void onComplete(Throwable error, Object resp) {
+ public void onComplete(final Throwable error, final Object resp) {
super.onComplete(error, resp);
commitLatch.countDown();
}
class OnCanCommitFutureComplete extends OnFutureComplete {
private final String transactionID;
- OnCanCommitFutureComplete(String transactionID) {
+ OnCanCommitFutureComplete(final String transactionID) {
super(CanCommitTransactionReply.SERIALIZABLE_CLASS);
this.transactionID = transactionID;
}
@Override
- void onSuccess(Object resp) throws Exception {
+ void onSuccess(final Object resp) throws Exception {
CanCommitTransactionReply canCommitReply =
CanCommitTransactionReply.fromSerializable(resp);
assertEquals("Can commit", true, canCommitReply.getCanCommit());
final CountDownLatch latch = new CountDownLatch(1);
canCommitFuture.onComplete(new OnComplete<Object>() {
@Override
- public void onComplete(Throwable t, Object resp) {
+ public void onComplete(final Throwable t, final Object resp) {
latch.countDown();
}
}, getSystem().dispatcher());
new AbortTransaction(transactionID).toSerializable(), timeout);
abortFuture.onComplete(new OnComplete<Object>() {
@Override
- public void onComplete(Throwable e, Object resp) {
+ public void onComplete(final Throwable e, final Object resp) {
abortComplete.countDown();
}
}, getSystem().dispatcher());
final CountDownLatch latch = new CountDownLatch(1);
canCommitFuture.onComplete(new OnComplete<Object>() {
@Override
- public void onComplete(Throwable t, Object resp) {
+ public void onComplete(final Throwable t, final Object resp) {
latch.countDown();
}
}, getSystem().dispatcher());
testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
}
- public void testCreateSnapshot(boolean persistent, final String shardActorName) throws IOException, InterruptedException {
+ @SuppressWarnings("serial")
+ public void testCreateSnapshot(final boolean persistent, final String shardActorName) throws IOException, InterruptedException {
final DatastoreContext dataStoreContext = DatastoreContext.newBuilder().
shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(persistent).build();
return new Shard(shardID, Collections.<ShardIdentifier,String>emptyMap(),
dataStoreContext, SCHEMA_CONTEXT) {
@Override
- protected void commitSnapshot(long sequenceNumber) {
+ protected void commitSnapshot(final long sequenceNumber) {
super.commitSnapshot(sequenceNumber);
latch.get().countDown();
}
commitTransaction(putTransaction);
- NormalizedNode expected = readStore(store);
+ NormalizedNode<?, ?> expected = readStore(store);
DOMStoreWriteTransaction writeTransaction = store.newWriteOnlyTransaction();
commitTransaction(writeTransaction);
- NormalizedNode actual = readStore(store);
+ NormalizedNode<?, ?> actual = readStore(store);
assertEquals(expected, actual);
}
- private NormalizedNode readStore(InMemoryDOMDataStore store) throws ReadFailedException {
+ private NormalizedNode<?, ?> readStore(final InMemoryDOMDataStore store) throws ReadFailedException {
DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read =
transaction.read(YangInstanceIdentifier.builder().build());
return normalizedNode;
}
- private void commitTransaction(DOMStoreWriteTransaction transaction) {
+ private void commitTransaction(final DOMStoreWriteTransaction transaction) {
DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
ListenableFuture<Void> future =
commitCohort.preCommit();
return new AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>() {
@Override
public void onDataChanged(
- AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
+ final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
}
};
}
- static NormalizedNode<?,?> readStore(TestActorRef<Shard> shard, YangInstanceIdentifier id)
+ static NormalizedNode<?,?> readStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id)
throws ExecutionException, InterruptedException {
DOMStoreReadTransaction transaction = shard.underlyingActor().getDataStore().newReadOnlyTransaction();
return node;
}
- private void writeToStore(TestActorRef<Shard> shard, YangInstanceIdentifier id, NormalizedNode<?,?> node)
+ private void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id, final NormalizedNode<?,?> node)
throws ExecutionException, InterruptedException {
DOMStoreWriteTransaction transaction = shard.underlyingActor().getDataStore().newWriteOnlyTransaction();
commitCohort.commit().get();
}
+ @SuppressWarnings("serial")
private static final class DelegatingShardCreator implements Creator<Shard> {
private final Creator<Shard> delegate;
- DelegatingShardCreator(Creator<Shard> delegate) {
+ DelegatingShardCreator(final Creator<Shard> delegate) {
this.delegate = delegate;
}
package org.opendaylight.controller.cluster.datastore;
+import akka.actor.ActorRef;
+import akka.actor.Props;
+import akka.pattern.AskTimeoutException;
+import akka.testkit.TestActorRef;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.junit.BeforeClass;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;
-import akka.actor.ActorRef;
-import akka.actor.Props;
-import akka.pattern.AskTimeoutException;
-import akka.testkit.TestActorRef;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
/**
* Covers negative test cases
}
private ActorRef createShard(){
- return getSystem().actorOf(Shard.props(SHARD_IDENTIFIER, Collections.EMPTY_MAP, datastoreContext,
+ return getSystem().actorOf(Shard.props(SHARD_IDENTIFIER, Collections.<ShardIdentifier, String>emptyMap(), datastoreContext,
TestModel.createTestContext()));
}
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import akka.actor.ActorRef;
+import akka.actor.Props;
+import akka.actor.Terminated;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestActorRef;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.junit.BeforeClass;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import scala.concurrent.duration.Duration;
-import akka.actor.ActorRef;
-import akka.actor.Props;
-import akka.actor.Terminated;
-import akka.testkit.JavaTestKit;
-import akka.testkit.TestActorRef;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
public class ShardTransactionTest extends AbstractActorTest {
private static ListeningExecutorService storeExecutor =
private ActorRef createShard(){
return getSystem().actorOf(Shard.props(SHARD_IDENTIFIER,
- Collections.EMPTY_MAP, datastoreContext, TestModel.createTestContext()));
+ Collections.<ShardIdentifier, String>emptyMap(), datastoreContext, TestModel.createTestContext()));
}
@Test
package org.opendaylight.controller.cluster.datastore.shardstrategy;
-import junit.framework.Assert;
+import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
package org.opendaylight.controller.cluster.datastore.shardstrategy;
+import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import static junit.framework.Assert.assertEquals;
-
public class ModuleShardStrategyTest {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
package org.opendaylight.controller.cluster.datastore.shardstrategy;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertTrue;
-
public class ShardStrategyFactoryTest {
@Rule
package org.opendaylight.controller.cluster.datastore.utils;
import com.google.common.base.Optional;
-import org.opendaylight.controller.cluster.datastore.Configuration;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
-
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.opendaylight.controller.cluster.datastore.Configuration;
+import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
public class MockConfiguration implements Configuration{
- @Override public List<String> getMemberShardNames(String memberName) {
+ @Override public List<String> getMemberShardNames(final String memberName) {
return Arrays.asList("default");
}
@Override public Optional<String> getModuleNameFromNameSpace(
- String nameSpace) {
+ final String nameSpace) {
return Optional.absent();
}
@Override
public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
- return Collections.EMPTY_MAP;
+ return Collections.emptyMap();
}
@Override public List<String> getShardNamesFromModuleName(
- String moduleName) {
- return Collections.EMPTY_LIST;
+ final String moduleName) {
+ return Collections.emptyList();
}
- @Override public List<String> getMembersFromShardName(String shardName) {
+ @Override public List<String> getMembersFromShardName(final String shardName) {
if("default".equals(shardName)) {
return Arrays.asList("member-1", "member-2");
} else if("astronauts".equals(shardName)){
return Arrays.asList("member-2", "member-3");
}
- return Collections.EMPTY_LIST;
+ return Collections.emptyList();
}
@Override public Set<String> getAllShardNames() {
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Uninterruptibles;
+import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.Uninterruptibles;
/**
* A mock DataChangeListener implementation.
public class MockDataChangeListener implements
AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> {
- private final List<AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>>>
- changeList = Lists.newArrayList();
- private final CountDownLatch changeLatch;
- private final int expChangeEventCount;
+ private final List<AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>>> changeList =
+ Collections.synchronizedList(Lists.<AsyncDataChangeEvent<YangInstanceIdentifier,
+ NormalizedNode<?, ?>>>newArrayList());
+
+ private volatile CountDownLatch changeLatch;
+ private int expChangeEventCount;
public MockDataChangeListener(int expChangeEventCount) {
+ reset(expChangeEventCount);
+ }
+
+ public void reset(int expChangeEventCount) {
changeLatch = new CountDownLatch(expChangeEventCount);
this.expChangeEventCount = expChangeEventCount;
+ changeList.clear();
}
@Override
}
public void waitForChangeEvents(YangInstanceIdentifier... expPaths) {
- assertEquals("Change notifications complete", true,
- Uninterruptibles.awaitUninterruptibly(changeLatch, 5, TimeUnit.SECONDS));
+ boolean done = Uninterruptibles.awaitUninterruptibly(changeLatch, 5, TimeUnit.SECONDS);
+ if(!done) {
+ fail(String.format("Missing change notifications. Expected: %d. Actual: %d",
+ expChangeEventCount, (expChangeEventCount - changeLatch.getCount())));
+ }
+
+ assertEquals("Change notifications complete", true, done);
for(int i = 0; i < expPaths.length; i++) {
assertTrue(String.format("Change %d does not contain %s", (i+1), expPaths[i]),
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
-import junit.framework.Assert;
-
import java.util.List;
+import org.junit.Assert;
public class TestUtils {
- public static void assertFirstSentMessage(ActorSystem actorSystem, ActorRef actorRef, Class clazz){
+ public static void assertFirstSentMessage(final ActorSystem actorSystem, final ActorRef actorRef, final Class<?> clazz){
ActorContext testContext = new ActorContext(actorSystem, actorSystem.actorOf(
Props.create(DoNothingActor.class)), new MockClusterWrapper(), new MockConfiguration());
Object messages = testContext
Assert.assertTrue(messages instanceof List);
- List<Object> listMessages = (List<Object>) messages;
+ List<?> listMessages = (List<?>) messages;
Assert.assertEquals(1, listMessages.size());
public static final QName CAR_PRICE_QNAME = QName.create(CAR_QNAME, "price");
- public static NormalizedNode create(){
+ public static NormalizedNode<?, ?> create(){
// Create a list builder
CollectionNodeBuilder<MapEntryNode, MapNode> cars =
}
- public static NormalizedNode emptyContainer(){
+ public static NormalizedNode<?, ?> emptyContainer(){
return ImmutableContainerNodeBuilder.create()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(BASE_QNAME))
.build();
- public static NormalizedNode create(){
+ public static NormalizedNode<?, ?> create(){
// Create a list builder
CollectionNodeBuilder<MapEntryNode, MapNode> cars =
}
- public static NormalizedNode emptyContainer(){
+ public static NormalizedNode<?, ?> emptyContainer(){
return ImmutableContainerNodeBuilder.create()
.withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(BASE_QNAME))
package org.opendaylight.controller.md.cluster.datastore.model;
-import junit.framework.Assert;
+import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec;
import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
/**
- * Data Broker which provides data transaction and data change listener fuctionality
+ * Data Broker which provides data transaction and data change listener functionality
* using {@link NormalizedNode} data format.
*
* This interface is type capture of generic interfaces and returns type captures
package org.opendaylight.controller.sal.dom.broker;
-import static junit.framework.Assert.fail;
+import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
+import com.google.common.base.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Optional;
-
public class BackwardsCompatibleMountPointManagerTest {
private static final Logger log = LoggerFactory.getLogger(BackwardsCompatibleMountPointManagerTest.class);
private DOMMountPoint mockMountPoint() {
final DOMMountPoint mock = mock(DOMMountPoint.class);
- doAnswer(new Answer() {
+ doAnswer(new Answer<Object>() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
return Optional.of(mock(((Class<?>) invocation.getArguments()[0])));
package org.opendaylight.controller.sal.dom.broker;
-import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import com.google.common.base.Optional;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.AbstractMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@Deprecated
public class BackwardsCompatibleMountPointTest {
private static final Logger log = LoggerFactory.getLogger(BackwardsCompatibleMountPointManagerTest.class);
}
private NormalizedNode<?, ?> mockNormalizedNode() {
- final NormalizedNode mock = mock(NormalizedNode.class);
+ final NormalizedNode<?, ?> mock = mock(NormalizedNode.class);
doReturn("mockNormalizedNode").when(mock).toString();
return mock;
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.spi;
+
+import com.google.common.collect.ForwardingObject;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
+/**
+ * Utility {@link DOMDataBroker} implementation which forwards all interface
+ * method invocation to a delegate instance.
+ */
+public abstract class ForwardingDOMDataBroker extends ForwardingObject implements DOMDataBroker {
+ @Override
+ protected abstract @Nonnull DOMDataBroker delegate();
+
+ @Override
+ public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path, final DOMDataChangeListener listener,
+ final DataChangeScope triggeringScope) {
+ return delegate().registerDataChangeListener(store, path, listener, triggeringScope);
+ }
+
+ @Override
+ public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
+ return delegate().newReadOnlyTransaction();
+ }
+
+ @Override
+ public DOMDataReadWriteTransaction newReadWriteTransaction() {
+ return delegate().newReadWriteTransaction();
+ }
+
+ @Override
+ public DOMDataWriteTransaction newWriteOnlyTransaction() {
+ return delegate().newWriteOnlyTransaction();
+ }
+
+ @Override
+ public DOMTransactionChain createTransactionChain(final TransactionChainListener listener) {
+ return delegate().createTransactionChain(listener);
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.spi;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ForwardingObject;
+import com.google.common.util.concurrent.CheckedFuture;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * Utility {@link DOMDataReadOnlyTransaction} implementation which forwards all interface
+ * method invocation to a delegate instance.
+ */
+public abstract class ForwardingDOMDataReadOnlyTransaction extends ForwardingObject implements DOMDataReadOnlyTransaction {
+ @Override
+ protected abstract @Nonnull DOMDataReadOnlyTransaction delegate();
+
+ @Override
+ public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ return delegate().read(store, path);
+ }
+
+ @Override
+ public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ return delegate().exists(store, path);
+ }
+
+ @Override
+ public Object getIdentifier() {
+ return delegate().getIdentifier();
+ }
+
+ @Override
+ public void close() {
+ delegate().close();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.spi;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ForwardingObject;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * Utility {@link DOMDataReadWriteTransaction} implementation which forwards all interface
+ * method invocation to a delegate instance.
+ */
+public abstract class ForwardingDOMDataReadWriteTransaction extends ForwardingObject implements DOMDataReadWriteTransaction {
+ @Override
+ protected abstract @Nonnull DOMDataReadWriteTransaction delegate();
+
+ @Override
+ public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ return delegate().read(store, path);
+ }
+
+ @Override
+ public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ return delegate().exists(store, path);
+ }
+
+ @Override
+ public Object getIdentifier() {
+ return delegate().getIdentifier();
+ }
+
+ @Override
+ public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ delegate().put(store, path, data);
+ }
+
+ @Override
+ public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ delegate().merge(store, path, data);
+ }
+
+ @Override
+ public boolean cancel() {
+ return delegate().cancel();
+ }
+
+ @Override
+ public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ delegate().delete(store, path);
+ }
+
+ @Override
+ public CheckedFuture<Void, TransactionCommitFailedException> submit() {
+ return delegate().submit();
+ }
+
+ @Override
+ @Deprecated
+ public ListenableFuture<RpcResult<TransactionStatus>> commit() {
+ return delegate().commit();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.spi;
+
+import com.google.common.collect.ForwardingObject;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * Utility {@link DOMDataWriteTransaction} implementation which forwards all interface
+ * method invocation to a delegate instance.
+ */
+public abstract class ForwardingDOMDataWriteTransaction extends ForwardingObject implements DOMDataWriteTransaction {
+ @Override
+ protected abstract @Nonnull DOMDataWriteTransaction delegate();
+
+ @Override
+ public Object getIdentifier() {
+ return delegate().getIdentifier();
+ }
+
+ @Override
+ public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ delegate().put(store, path, data);
+ }
+
+ @Override
+ public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ delegate().merge(store, path, data);
+ }
+
+ @Override
+ public boolean cancel() {
+ return delegate().cancel();
+ }
+
+ @Override
+ public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ delegate().delete(store, path);
+ }
+
+ @Override
+ public CheckedFuture<Void, TransactionCommitFailedException> submit() {
+ return delegate().submit();
+ }
+
+ @Override
+ @Deprecated
+ public ListenableFuture<RpcResult<TransactionStatus>> commit() {
+ return delegate().commit();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.spi;
+
+import com.google.common.collect.ForwardingObject;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
+
+/**
+ * Utility {@link DOMTransactionChain} implementation which forwards all interface
+ * method invocation to a delegate instance.
+ */
+public abstract class ForwardingDOMTransactionChain extends ForwardingObject implements DOMTransactionChain {
+ @Override
+ protected abstract @Nonnull DOMTransactionChain delegate();
+
+ @Override
+ public void close() {
+ delegate().close();
+ }
+
+ @Override
+ public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
+ return delegate().newReadOnlyTransaction();
+ }
+
+ @Override
+ public DOMDataReadWriteTransaction newReadWriteTransaction() {
+ return delegate().newReadWriteTransaction();
+ }
+
+ @Override
+ public DOMDataWriteTransaction newWriteOnlyTransaction() {
+ return delegate().newWriteOnlyTransaction();
+ }
+}
<version>1.2.0-SNAPSHOT</version>\r
</parent>\r
<artifactId>sal-dom-xsql-config</artifactId>\r
- <groupId>org.opendaylight.controller</groupId>\r
<description>Configuration files for md-sal</description>\r
<packaging>jar</packaging>\r
<properties>\r
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
Preconditions.checkNotNull(rpcName);
Preconditions.checkNotNull(schemaContext);
- final NodeContainerProxy rpcBodyProxy = new NodeContainerProxy(rpcName, schemaContext.getChildNodes());
- return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(rpcBodyProxy));
+ for (final RpcDefinition rpcDefinition : schemaContext.getOperations()) {
+ if(rpcDefinition.getQName().equals(rpcName)) {
+ final NodeContainerProxy rpcBodyProxy = new NodeContainerProxy(rpcName, rpcDefinition.getInput().getChildNodes());
+ return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(rpcBodyProxy));
+ }
+ }
+ throw new IllegalArgumentException("Rpc " + rpcName + " not found in schema context " + schemaContext + ". Unable to invoke Rpc");
}
public static CompositeNodeTOImpl wrap(final QName name, final Node<?> node) {
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import com.google.common.base.Optional;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
// Make fallback attempt to fail due to empty resolved sources
final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
- doAnswer(new Answer() {
+ doAnswer(new Answer<Object>() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
if(((Collection<?>) invocation.getArguments()[0]).size() == 2) {
private SchemaSourceRegistry getSchemaRegistry() {
final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
- final SchemaSourceRegistration mockReg = mock(SchemaSourceRegistration.class);
+ final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
doNothing().when(mockReg).close();
doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
return mock;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.hasItem;
+import static org.hamcrest.CoreMatchers.hasItem;
import java.util.Set;
import org.junit.Test;
package org.opendaylight.controller.sal.connect.netconf;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertTrue;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Set;
-
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Before;
import org.junit.Test;
package org.opendaylight.controller.sal.connect.netconf;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertTrue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.util.Collections;
assertEquals(streamName.getLocalName(), "stream-name");
}
- @Test
- public void testNoSchemaContextToRpcRequest() throws Exception {
- final String exampleNamespace = "http://example.net/me/my-own/1.0";
- final String exampleRevision = "2014-07-22";
- final QName myOwnMethodRpcQName = QName.create(exampleNamespace, exampleRevision, "my-own-method");
-
- final CompositeNodeBuilder<ImmutableCompositeNode> rootBuilder = ImmutableCompositeNode.builder();
- rootBuilder.setQName(myOwnMethodRpcQName);
-
- final CompositeNodeBuilder<ImmutableCompositeNode> inputBuilder = ImmutableCompositeNode.builder();
- inputBuilder.setQName(QName.create(exampleNamespace, exampleRevision, "input"));
- inputBuilder.addLeaf(QName.create(exampleNamespace, exampleRevision, "my-first-parameter"), "14");
- inputBuilder.addLeaf(QName.create(exampleNamespace, exampleRevision, "another-parameter"), "fred");
-
- rootBuilder.add(inputBuilder.toInstance());
- final ImmutableCompositeNode root = rootBuilder.toInstance();
-
- final NetconfMessage message = messageTransformer.toRpcRequest(myOwnMethodRpcQName, root);
- assertNotNull(message);
-
- final Document xmlDoc = message.getDocument();
- final org.w3c.dom.Node rpcChild = xmlDoc.getFirstChild();
- assertEquals(rpcChild.getLocalName(), "rpc");
-
- final org.w3c.dom.Node myOwnMethodNode = rpcChild.getFirstChild();
- assertEquals(myOwnMethodNode.getLocalName(), "my-own-method");
-
- final org.w3c.dom.Node firstParamNode = myOwnMethodNode.getFirstChild();
- assertEquals(firstParamNode.getLocalName(), "my-first-parameter");
-
- final org.w3c.dom.Node secParamNode = firstParamNode.getNextSibling();
- assertEquals(secParamNode.getLocalName(), "another-parameter");
- }
}
package org.opendaylight.controller.sal.connect.netconf.listener;
+import static org.hamcrest.CoreMatchers.hasItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import com.google.common.collect.Lists;
import java.util.List;
import org.junit.Test;
-import org.junit.matchers.JUnitMatchers;
import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.yangtools.yang.common.QName;
final NetconfSessionCapabilities merged = sessionCaps1.replaceModuleCaps(sessionCaps2);
assertCaps(merged, 2, 2 + 1 /*Preserved monitoring*/);
for (final QName qName : sessionCaps2.getModuleBasedCaps()) {
- assertThat(merged.getModuleBasedCaps(), JUnitMatchers.hasItem(qName));
+ assertThat(merged.getModuleBasedCaps(), hasItem(qName));
}
- assertThat(merged.getModuleBasedCaps(), JUnitMatchers.hasItem(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING));
+ assertThat(merged.getModuleBasedCaps(), hasItem(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING));
- assertThat(merged.getNonModuleCaps(), JUnitMatchers.hasItem("urn:ietf:params:netconf:base:1.0"));
- assertThat(merged.getNonModuleCaps(), JUnitMatchers.hasItem("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
+ assertThat(merged.getNonModuleCaps(), hasItem("urn:ietf:params:netconf:base:1.0"));
+ assertThat(merged.getNonModuleCaps(), hasItem("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
}
@Test
package org.opendaylight.controller.sal.connect.netconf.sal.tx;
-import static junit.framework.Assert.fail;
+import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
package org.opendaylight.controller.remote.rpc.utils;
-
+import static org.junit.Assert.assertTrue;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.japi.Pair;
import akka.testkit.JavaTestKit;
import akka.testkit.TestProbe;
import com.typesafe.config.ConfigFactory;
-import junit.framework.Assert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
-
public class LatestEntryRoutingLogicTest {
static ActorSystem system;
pairList.add(new Pair<ActorRef, Long>(actor2, 3000L));
pairList.add(new Pair<ActorRef, Long>(actor3, 2000L));
RoutingLogic logic = new LatestEntryRoutingLogic(pairList);
- Assert.assertTrue(logic.select().equals(actor2));
+ assertTrue(logic.select().equals(actor2));
}
}
import java.util.Set;
import java.util.TreeSet;
import javax.ws.rs.core.UriInfo;
-import junit.framework.Assert;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
if (m.getKey().getAbsolutePath().endsWith("toaster.yang")) {
ApiDeclaration doc = generator.getSwaggerDocSpec(m.getValue(), "http://localhost:8080/restconf", "",
schemaContext);
- Assert.assertNotNull(doc);
+ assertNotNull(doc);
// testing bugs.opendaylight.org bug 1290. UnionType model type.
String jsonString = doc.getModels().toString();
org.opendaylight.controller.netconf.confignetconfconnector.util,
org.opendaylight.controller.netconf.confignetconfconnector.osgi,
org.opendaylight.controller.netconf.confignetconfconnector.exception,</Private-Package>
- <Import-Package>com.google.common.base,
- com.google.common.collect,
- javax.annotation,
- javax.management,
- javax.management.openmbean,
- org.opendaylight.controller.config.api,
- org.opendaylight.controller.config.api.jmx,
- org.opendaylight.controller.config.yangjmxgenerator,
- org.opendaylight.controller.config.yangjmxgenerator.attribute,
- org.opendaylight.controller.netconf.api,
- org.opendaylight.controller.netconf.mapping.api,
- org.opendaylight.controller.netconf.util.mapping,
- org.opendaylight.controller.netconf.util.xml,
- org.opendaylight.controller.netconf.util.exception,
- org.opendaylight.yangtools.yang.common,
- org.opendaylight.yangtools.yang.model.api,
- org.osgi.framework,
- org.osgi.util.tracker,
- org.slf4j,
- org.w3c.dom,
- com.google.common.io,
- org.opendaylight.yangtools.yang.model.api.type,
- org.opendaylight.yangtools.sal.binding.generator.spi,
- org.opendaylight.yangtools.sal.binding.yang.types,
- org.opendaylight.controller.config.util
- </Import-Package>
+ <Import-Package>*</Import-Package>
<Export-Package></Export-Package>
</instructions>
</configuration>
package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.Maps;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.management.ObjectName;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.ModuleRpcs;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.Modules;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.modules.Module;
-import javax.management.ObjectName;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.Maps;
/**
* Represents parsed xpath to runtime bean instance
return moduleName;
}
+ @VisibleForTesting
+ Map<String, String> getAdditionalAttributes() {
+ return additionalAttributes;
+ }
+
public String getInstanceName() {
return instanceName;
}
return ObjectNameUtil.createRuntimeBeanName(moduleName, instanceName, additionalAttributesJavaNames);
}
+ /**
+ * Pattern for an absolute instance identifier xpath pointing to a runtime bean instance e.g:
+ * <pre>
+ * /modules/module[name=instanceName][type=moduleType]
+ * </pre>
+ * or
+ * <pre>
+ * /a:modules/a:module[a:name=instanceName][a:type=moduleType]
+ * </pre>
+ */
private static final String xpathPatternBlueprint =
- "/" + XmlNetconfConstants.MODULES_KEY
- + "/" + XmlNetconfConstants.MODULE_KEY
- + "\\["
-
- + "(?<key1>type|name)"
- + "='(?<value1>[^']+)'"
- + "( and |\\]\\[)"
- + "(?<key2>type|name)"
- + "='(?<value2>[^']+)'"
-
- + "\\]"
- + "(?<additional>.*)";
+ "/" + getRegExForPrefixedName(Modules.QNAME.getLocalName())+ "/" + getRegExForPrefixedName(Module.QNAME.getLocalName())
+
+ + "\\["
+ + "(?<key1>" + getRegExForPrefixedName(XmlNetconfConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlNetconfConstants.NAME_KEY) + ")"
+ + "=('|\")?(?<value1>[^'\"\\]]+)('|\")?"
+ + "( and |\\]\\[)"
+ + "(?<key2>" + getRegExForPrefixedName(XmlNetconfConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlNetconfConstants.NAME_KEY) + ")"
+ + "=('|\")?(?<value2>[^'\"\\]]+)('|\")?"
+ + "\\]"
+
+ + "(?<additional>.*)";
+
+ /**
+ * Return reg ex that matches either the name with or without a prefix
+ */
+ private static String getRegExForPrefixedName(final String name) {
+ return "([^:]+:)?" + name;
+ }
private static final Pattern xpathPattern = Pattern.compile(xpathPatternBlueprint);
- private static final String additionalPatternBlueprint = "(?<additionalKey>.+)\\[(.+)='(?<additionalValue>.+)'\\]";
+
+ /**
+ * Pattern for additional path elements inside xpath for instance identifier pointing to an inner runtime bean e.g:
+ * <pre>
+ * /modules/module[name=instanceName and type=moduleType]/inner[key=b]
+ * </pre>
+ */
+ private static final String additionalPatternBlueprint = getRegExForPrefixedName("(?<additionalKey>.+)") + "\\[(?<prefixedKey>" + getRegExForPrefixedName("(.+)") + ")=('|\")?(?<additionalValue>[^'\"\\]]+)('|\")?\\]";
private static final Pattern additionalPattern = Pattern.compile(additionalPatternBlueprint);
public static RuntimeRpcElementResolved fromXpath(String xpath, String elementName, String namespace) {
PatternGroupResolver(String key1, String value1, String value2, String additional) {
this.key1 = Preconditions.checkNotNull(key1);
this.value1 = Preconditions.checkNotNull(value1);
-
this.value2 = Preconditions.checkNotNull(value2);
-
this.additional = Preconditions.checkNotNull(additional);
}
String getModuleName() {
- return key1.equals(XmlNetconfConstants.TYPE_KEY) ? value1 : value2;
+ return key1.contains(XmlNetconfConstants.TYPE_KEY) ? value1 : value2;
}
String getInstanceName() {
- return key1.equals(XmlNetconfConstants.NAME_KEY) ? value1 : value2;
+ return key1.contains(XmlNetconfConstants.NAME_KEY) ? value1 : value2;
}
+
Map<String, String> getAdditionalKeys(String elementName, String moduleName) {
HashMap<String, String> additionalAttributes = Maps.newHashMap();
Preconditions
.checkState(
matcher.matches(),
- "Attribute %s not in required form on rpc element %s, required format for additional attributes is %s",
+ "Attribute %s not in required form on rpc element %s, required format for additional attributes is: %s",
additionalKeyValue, elementName, additionalPatternBlueprint);
String name = matcher.group("additionalKey");
runtimeBeanYangName = name;
import org.custommonkey.xmlunit.NodeTester;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
+import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
-import org.junit.matchers.JUnitMatchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.config.api.ConflictingVersionException;
}
private void assertContainsString(String string, String substring) {
- assertThat(string, JUnitMatchers.containsString(substring));
+ assertThat(string, CoreMatchers.containsString(substring));
}
private void checkEnum(final Document response) throws Exception {
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(Parameterized.class)
+public class RuntimeRpcElementResolvedTest {
+
+ private static final String MODULE_TYPE = "moduleType";
+ private static final String INSTANCE_NAME = "instanceName";
+ @Parameterized.Parameter(0)
+ public String xpath;
+ @Parameterized.Parameter(1)
+ public Map<String, String> additional;
+
+ @Parameterized.Parameters(name = "{index}: parsed({0}) contains moduleName:{1} and instanceName:{2}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] {
+ // With namespaces
+ { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']",
+ new HashMap<String, String>() {{
+ put("listener-state", "127.0.0.1");
+ }}},
+ { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']",
+ null},
+
+ // Without namespaces
+ { "/modules/module[name=instanceName][type=moduleType]", null},
+ { "/modules/module[type=moduleType][name='instanceName']", null},
+ { "/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null},
+ { "/modules/module[type=moduleType and name=instanceName]", null},
+ { "/modules/module[name=\"instanceName\" and type=moduleType]", null},
+ { "/modules/module[type=\"moduleType\" and name=instanceName]", null},
+ { "/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null},
+
+ // With inner beans
+ { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]", Collections.singletonMap("inner", "b")},
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=b]", Collections.singletonMap("inner", "b")},
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']", Collections.singletonMap("inner", "b")},
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]", Collections.singletonMap("inner", "b")},
+
+ { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]",
+ new HashMap<String, String>() {{
+ put("inner", "a");
+ put("inner2", "b");
+ }}
+ },
+ });
+ }
+
+ @Test
+ public void testFromXpath() throws Exception {
+ final RuntimeRpcElementResolved resolved = RuntimeRpcElementResolved.fromXpath(xpath, "element", "namespace");
+ assertEquals(MODULE_TYPE, resolved.getModuleName());
+ assertEquals(INSTANCE_NAME, resolved.getInstanceName());
+ if (additional != null) {
+ assertEquals(additional, resolved.getAdditionalAttributes());
+ }
+ }
+}
import org.junit.Assert;
import org.junit.Test;
-import org.junit.matchers.JUnitMatchers;
+import org.hamcrest.CoreMatchers;
import org.opendaylight.controller.config.api.LookupRegistry;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.yangtools.yang.common.QName;
String message = e.getMessage();
Assert.assertThat(
message,
- JUnitMatchers
+ CoreMatchers
.containsString("missing from config subsystem but present in yangstore: [(namespace?revision=1970-01-01)qname2]"));
Assert.assertThat(
message,
- JUnitMatchers
+ CoreMatchers
.containsString("All modules present in config: [(namespace?revision=1970-01-01)qname1]"));
}
}
import java.util.List;
import java.util.Properties;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.opendaylight.controller.netconf.persist.impl.PersisterAggregator.PersisterWithConfiguration;
*/
package org.opendaylight.controller.netconf.persist.impl.osgi;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import org.junit.matchers.JUnitMatchers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private void assertException(Throwable t, Class<? extends Exception> exType, String exMessageToContain) {
assertEquals("Expected exception of type " + exType + " but was " + t, exType, t.getClass());
if(exMessageToContain!=null) {
- assertThat(t.getMessage(), JUnitMatchers.containsString(exMessageToContain));
+ assertThat(t.getMessage(), containsString(exMessageToContain));
}
}
import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
-import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import io.netty.util.concurrent.Promise;
-import org.apache.sshd.common.SessionListener;
import org.junit.Test;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
package org.opendaylight.controller.netconf.client;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import com.google.common.base.Optional;
-import io.netty.channel.*;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.ChannelProgressivePromise;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.HashedWheelTimer;
+import io.netty.util.Timer;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
-import org.apache.mina.handler.demux.ExceptionHandler;
+import java.util.Set;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.Mockito;
import org.mockito.internal.util.collections.Sets;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import io.netty.util.Timer;
import org.opendaylight.controller.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
import org.opendaylight.controller.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
import org.opendaylight.controller.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.openexi.proc.common.EXIOptions;
import org.w3c.dom.Document;
-import java.util.Set;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.*;
public class NetconfClientSessionNegotiatorTest {
return pipeline;
}
- private NetconfClientSessionNegotiator createNetconfClientSessionNegotiator(Promise promise,
- NetconfMessage startExi) {
+ private NetconfClientSessionNegotiator createNetconfClientSessionNegotiator(final Promise promise,
+ final NetconfMessage startExi) {
ChannelProgressivePromise progressivePromise = mock(ChannelProgressivePromise.class);
NetconfClientSessionPreferences preferences = new NetconfClientSessionPreferences(helloMessage, startExi);
doReturn(progressivePromise).when(promise).setFailure(any(Throwable.class));
Set caps = Sets.newSet("exi:1.0");
NetconfHelloMessage helloMessage = NetconfHelloMessage.createServerHello(caps, 10);
- doAnswer(new Answer() {
+ doAnswer(new Answer<Object>() {
@Override
- public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+ public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
channelInboundHandlerAdapter = ((ChannelInboundHandlerAdapter) invocationOnMock.getArguments()[2]);
return null;
}
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.controller.netconf.nettyutil.handler.NetconfEXICodec;
import org.openexi.proc.common.EXIOptions;
-import java.util.ArrayList;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.controller.config.yang.protocol.framework.NeverReconnectStrategyFactoryModule;
import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
package org.opendaylight.controller.netconf.client;
import io.netty.channel.*;
import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.Promise;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.collections.Sets;
import io.netty.channel.ChannelPipeline;
import io.netty.util.concurrent.Promise;
import org.junit.Test;
-import org.opendaylight.controller.netconf.nettyutil.AbstractChannelInitializer;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
-/*\r
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-package org.opendaylight.controller.netconf.impl.mapping.operations;\r
-\r
-import org.opendaylight.controller.netconf.impl.NetconfServerSession;\r
-\r
-public interface DefaultNetconfOperation {\r
- void setNetconfSession(NetconfServerSession s);\r
-}\r
+/*
+ * 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.netconf.impl.mapping.operations;
+
+import org.opendaylight.controller.netconf.impl.NetconfServerSession;
+
+public interface DefaultNetconfOperation {
+ void setNetconfSession(NetconfServerSession s);
+}
-/*\r
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-package org.opendaylight.controller.netconf.impl.mapping.operations;\r
-\r
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;\r
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;\r
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;\r
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;\r
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.controller.netconf.api.NetconfMessage;\r
-import org.opendaylight.controller.netconf.impl.NetconfServerSession;\r
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;\r
-import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;\r
-import org.opendaylight.controller.netconf.util.xml.XmlElement;\r
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-public class DefaultStartExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation {\r
- public static final String START_EXI = "start-exi";\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(DefaultStartExi.class);\r
- private NetconfServerSession netconfSession;\r
-\r
- public DefaultStartExi(String netconfSessionIdForReporting) {\r
- super(netconfSessionIdForReporting);\r
- }\r
-\r
- @Override\r
- public Document handle(Document message,\r
- NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {\r
- logger.debug("Received start-exi message {} ", XmlUtil.toString(message));\r
-\r
- try {\r
- netconfSession.startExiCommunication(new NetconfMessage(message));\r
- } catch (IllegalArgumentException e) {\r
- throw new NetconfDocumentedException("Failed to parse EXI parameters", ErrorType.protocol,\r
- ErrorTag.operation_failed, ErrorSeverity.error);\r
- }\r
-\r
- return super.handle(message, subsequentOperation);\r
- }\r
-\r
- @Override\r
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {\r
- Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);\r
- logger.trace("{} operation successful", START_EXI);\r
- return getSchemaResult;\r
- }\r
-\r
- @Override\r
- protected String getOperationName() {\r
- return START_EXI;\r
- }\r
-\r
- @Override\r
- protected String getOperationNamespace() {\r
- return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0;\r
- }\r
-\r
- @Override\r
- public void setNetconfSession(NetconfServerSession s) {\r
- netconfSession = s;\r
- }\r
-}\r
+/*
+ * 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.netconf.impl.mapping.operations;
+
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.netconf.impl.NetconfServerSession;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
+import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
+import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+public class DefaultStartExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation {
+ public static final String START_EXI = "start-exi";
+
+ private static final Logger logger = LoggerFactory.getLogger(DefaultStartExi.class);
+ private NetconfServerSession netconfSession;
+
+ public DefaultStartExi(String netconfSessionIdForReporting) {
+ super(netconfSessionIdForReporting);
+ }
+
+ @Override
+ public Document handle(Document message,
+ NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ logger.debug("Received start-exi message {} ", XmlUtil.toString(message));
+
+ try {
+ netconfSession.startExiCommunication(new NetconfMessage(message));
+ } catch (IllegalArgumentException e) {
+ throw new NetconfDocumentedException("Failed to parse EXI parameters", ErrorType.protocol,
+ ErrorTag.operation_failed, ErrorSeverity.error);
+ }
+
+ return super.handle(message, subsequentOperation);
+ }
+
+ @Override
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
+ Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
+ logger.trace("{} operation successful", START_EXI);
+ return getSchemaResult;
+ }
+
+ @Override
+ protected String getOperationName() {
+ return START_EXI;
+ }
+
+ @Override
+ protected String getOperationNamespace() {
+ return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0;
+ }
+
+ @Override
+ public void setNetconfSession(NetconfServerSession s) {
+ netconfSession = s;
+ }
+}
-/*\r
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-package org.opendaylight.controller.netconf.impl.mapping.operations;\r
-\r
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;\r
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.controller.netconf.impl.NetconfServerSession;\r
-import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;\r
-import org.opendaylight.controller.netconf.util.xml.XmlElement;\r
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-\r
-public class DefaultStopExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation {\r
-\r
- public static final String STOP_EXI = "stop-exi";\r
- private NetconfServerSession netconfSession;\r
-\r
- private static final Logger logger = LoggerFactory\r
- .getLogger(DefaultStartExi.class);\r
-\r
- public DefaultStopExi(String netconfSessionIdForReporting) {\r
- super(netconfSessionIdForReporting);\r
- }\r
-\r
- @Override\r
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {\r
- logger.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement));\r
-\r
- netconfSession.stopExiCommunication();\r
-\r
- Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);\r
- logger.trace("{} operation successful", STOP_EXI);\r
- return getSchemaResult;\r
- }\r
-\r
- @Override\r
- protected String getOperationName() {\r
- return STOP_EXI;\r
- }\r
-\r
- @Override\r
- protected String getOperationNamespace() {\r
- return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0;\r
- }\r
-\r
- @Override\r
- public void setNetconfSession(NetconfServerSession s) {\r
- this.netconfSession = s;\r
- }\r
-}\r
+/*
+ * 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.netconf.impl.mapping.operations;
+
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.controller.netconf.impl.NetconfServerSession;
+import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
+import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+public class DefaultStopExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation {
+
+ public static final String STOP_EXI = "stop-exi";
+ private NetconfServerSession netconfSession;
+
+ private static final Logger logger = LoggerFactory
+ .getLogger(DefaultStartExi.class);
+
+ public DefaultStopExi(String netconfSessionIdForReporting) {
+ super(netconfSessionIdForReporting);
+ }
+
+ @Override
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
+ logger.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement));
+
+ netconfSession.stopExiCommunication();
+
+ Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
+ logger.trace("{} operation successful", STOP_EXI);
+ return getSchemaResult;
+ }
+
+ @Override
+ protected String getOperationName() {
+ return STOP_EXI;
+ }
+
+ @Override
+ protected String getOperationNamespace() {
+ return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0;
+ }
+
+ @Override
+ public void setNetconfSession(NetconfServerSession s) {
+ this.netconfSession = s;
+ }
+}
*/
package org.opendaylight.controller.netconf.impl;
-import junit.framework.Assert;
-
+import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
public void testParsing() throws Exception {
String s = "[netconf;10.12.0.102:48528;ssh;;;;;;]";
NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(s);
- Assert.assertEquals("netconf", header.getUserName());
- Assert.assertEquals("10.12.0.102", header.getAddress());
- Assert.assertEquals("ssh", header.getTransport());
+ assertEquals("netconf", header.getUserName());
+ assertEquals("10.12.0.102", header.getAddress());
+ assertEquals("ssh", header.getTransport());
}
@Test
public void testParsing2() throws Exception {
String s = "[tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]";
NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(s);
- Assert.assertEquals("tomas", header.getUserName());
- Assert.assertEquals("10.0.0.0", header.getAddress());
- Assert.assertEquals("tcp", header.getTransport());
+ assertEquals("tomas", header.getUserName());
+ assertEquals("10.0.0.0", header.getAddress());
+ assertEquals("tcp", header.getTransport());
}
@Test(expected = IllegalArgumentException.class)
*/
package org.opendaylight.controller.netconf.impl;
-import static junit.framework.Assert.assertNotNull;
+import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
package org.opendaylight.controller.netconf.impl.mapping.operations;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
import com.google.common.base.Optional;
-import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-
public class DefaultGetSchemaTest {
private CapabilityProvider cap;
package org.opendaylight.controller.netconf.impl.osgi;
import java.util.Arrays;
-import java.util.Collection;
import java.util.Dictionary;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
-import org.osgi.framework.*;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Filter;
+import org.osgi.framework.ServiceListener;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
public class NetconfImplActivatorTest {
*/
package org.opendaylight.controller.netconf.it;
-import static junit.framework.Assert.assertEquals;
+import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
package org.opendaylight.controller.netconf.monitoring;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.TestCase.fail;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
-
import java.util.Collections;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
package org.opendaylight.controller.netconf.monitoring.osgi;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.*;
-
public class NetconfMonitoringActivatorTest {
@Mock
MockitoAnnotations.initMocks(this);
doReturn(filter).when(context).createFilter(anyString());
doNothing().when(context).addServiceListener(any(ServiceListener.class), anyString());
- ServiceReference[] refs = new ServiceReference[2];
+ ServiceReference<?>[] refs = new ServiceReference[2];
doReturn(Arrays.asList(refs)).when(context).getServiceReferences(any(Class.class), anyString());
doReturn(refs).when(context).getServiceReferences(anyString(), anyString());
}
package org.opendaylight.controller.netconf.monitoring.osgi;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import java.util.Hashtable;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyCollection;
-import static org.mockito.Mockito.*;
-
public class NetconfMonitoringServiceTrackerTest {
@Mock
- private ServiceReference reference;
+ private ServiceReference<NetconfMonitoringService> reference;
@Mock
private BundleContext context;
@Mock
- private ServiceRegistration serviceRegistration;
+ private ServiceRegistration<?> serviceRegistration;
@Mock
private Filter filter;
@Mock
final String alignmentTextContent = alignmentElement.getTextContent().trim();
switch (alignmentTextContent) {
- case EXI_PARAMETER_BIT_PACKED:
- options.setAlignmentType(AlignmentType.bitPacked);
- break;
- case EXI_PARAMETER_BYTE_ALIGNED:
- options.setAlignmentType(AlignmentType.byteAligned);
- break;
- case EXI_PARAMETER_COMPRESSED:
- options.setAlignmentType(AlignmentType.compress);
- break;
- case EXI_PARAMETER_PRE_COMPRESSION:
- options.setAlignmentType(AlignmentType.preCompress);
- break;
+ case EXI_PARAMETER_BIT_PACKED:
+ options.setAlignmentType(AlignmentType.bitPacked);
+ break;
+ case EXI_PARAMETER_BYTE_ALIGNED:
+ options.setAlignmentType(AlignmentType.byteAligned);
+ break;
+ case EXI_PARAMETER_COMPRESSED:
+ options.setAlignmentType(AlignmentType.compress);
+ break;
+ case EXI_PARAMETER_PRE_COMPRESSION:
+ options.setAlignmentType(AlignmentType.preCompress);
+ break;
}
}
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doAnswer;
-
import com.google.common.collect.Lists;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@Test
public void testEncode() throws Exception {
final List<ByteBuf> chunks = Lists.newArrayList();
- doAnswer(new Answer() {
+ doAnswer(new Answer<Object>() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
chunks.add((ByteBuf) invocation.getArguments()[0]);
package org.opendaylight.controller.netconf.nettyutil.handler;
-import static org.junit.Assert.*;
-
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
import com.google.common.collect.Lists;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.custommonkey.xmlunit.XMLUnit;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
-
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelPromise;
import java.io.IOException;
import java.net.SocketAddress;
-
import org.apache.sshd.ClientChannel;
import org.apache.sshd.ClientSession;
import org.apache.sshd.SshClient;
import org.mockito.stubbing.Answer;
import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelPromise;
-
public class AsyncSshHandlerTest {
@Mock
private <T extends SshFuture<T>> ListenableFuture<SshFutureListener<T>> stubAddListener(final T future) {
final SettableFuture<SshFutureListener<T>> listenerSettableFuture = SettableFuture.create();
- doAnswer(new Answer() {
+ doAnswer(new Answer<Object>() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
listenerSettableFuture.set((SshFutureListener<T>) invocation.getArguments()[0]);
package org.opendaylight.controller.netconf.util.mapping;
+import com.google.common.base.Optional;
import java.util.Map;
-
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
-import com.google.common.base.Optional;
-
public abstract class AbstractNetconfOperation implements NetconfOperation {
private final String netconfSessionIdForReporting;
- private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfOperation.class);
- protected AbstractNetconfOperation(String netconfSessionIdForReporting) {
+ protected AbstractNetconfOperation(final String netconfSessionIdForReporting) {
this.netconfSessionIdForReporting = netconfSessionIdForReporting;
}
}
@Override
- public HandlingPriority canHandle(Document message) throws NetconfDocumentedException {
+ public HandlingPriority canHandle(final Document message) throws NetconfDocumentedException {
OperationNameAndNamespace operationNameAndNamespace = null;
operationNameAndNamespace = new OperationNameAndNamespace(message);
return canHandle(operationNameAndNamespace.getOperationName(), operationNameAndNamespace.getNamespace());
private final String operationName, namespace;
private final XmlElement operationElement;
- public OperationNameAndNamespace(Document message) throws NetconfDocumentedException {
+ public OperationNameAndNamespace(final Document message) throws NetconfDocumentedException {
XmlElement requestElement = null;
requestElement = getRequestElementWithCheck(message);
operationElement = requestElement.getOnlyChildElement();
}
}
- protected static XmlElement getRequestElementWithCheck(Document message) throws NetconfDocumentedException {
+ protected static XmlElement getRequestElementWithCheck(final Document message) throws NetconfDocumentedException {
return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), XmlNetconfConstants.RPC_KEY,
XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
- protected HandlingPriority canHandle(String operationName, String operationNamespace) {
+ protected HandlingPriority canHandle(final String operationName, final String operationNamespace) {
return operationName.equals(getOperationName()) && operationNamespace.equals(getOperationNamespace())
? getHandlingPriority()
: HandlingPriority.CANNOT_HANDLE;
protected abstract String getOperationName();
@Override
- public Document handle(Document requestMessage,
- NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ public Document handle(final Document requestMessage,
+ final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
XmlElement requestElement = getRequestElementWithCheck(requestMessage);
*/
package org.opendaylight.controller.netconf.util;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
import org.junit.Test;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
-
public class NetconfUtilTest {
@Test
package org.opendaylight.controller.netconf.util.messages;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import com.google.common.base.Optional;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.collections.Sets;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
public class NetconfHelloMessageTest {
Set<String> caps;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
caps = Sets.newSet("cap1");
}
@Test
- public void testConstructor() throws Exception {
+ public void testConstructor() throws NetconfDocumentedException {
NetconfHelloMessageAdditionalHeader additionalHeader = new NetconfHelloMessageAdditionalHeader("name","host","1","transp","id");
NetconfHelloMessage message = NetconfHelloMessage.createClientHello(caps, Optional.of(additionalHeader));
- assertTrue(message.isHelloMessage(message));
+ assertTrue(NetconfHelloMessage.isHelloMessage(message));
assertEquals(Optional.of(additionalHeader), message.getAdditionalHeader());
NetconfHelloMessage serverMessage = NetconfHelloMessage.createServerHello(caps, 100L);
- assertTrue(serverMessage.isHelloMessage(serverMessage));
+ assertTrue(NetconfHelloMessage.isHelloMessage(serverMessage));
}
}
package org.opendaylight.controller.netconf.util.messages;
-import com.google.common.base.Charsets;
-import java.util.Arrays;
-import org.junit.Test;
-
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
+import com.google.common.base.Charsets;
+import org.junit.Test;
+@Deprecated
public class NetconfMessageHeaderTest {
@Test
public void testGet() throws Exception {
package org.opendaylight.controller.netconf.util.osgi;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import com.google.common.base.Optional;
import io.netty.channel.local.LocalAddress;
import java.net.InetSocketAddress;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.netconf.util.NetconfUtil;
import org.osgi.framework.BundleContext;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
public class NetconfConfigUtilTest {
private BundleContext bundleContext;
-<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" a="64" message-id="a">\r
-<start-exi xmlns="urn:ietf:params:xml:ns:netconf:exi:1.0">\r
-<alignment>pre-compression</alignment>\r
-<fidelity>\r
-<dtd/>\r
-<lexical-values/>\r
-</fidelity>\r
-</start-exi>\r
-</rpc>
\ No newline at end of file
+<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" a="64" message-id="a">
+<start-exi xmlns="urn:ietf:params:xml:ns:netconf:exi:1.0">
+<alignment>pre-compression</alignment>
+<fidelity>
+<dtd/>
+<lexical-values/>
+</fidelity>
+</start-exi>
+</rpc>
-<rpc message-id="a" a="64" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">\r
- <stop-exi xmlns="urn:ietf:params:xml:ns:netconf:exi:1.0"/>\r
-</rpc>
\ No newline at end of file
+<rpc message-id="a" a="64" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+ <stop-exi xmlns="urn:ietf:params:xml:ns:netconf:exi:1.0"/>
+</rpc>
*/
package org.opendaylight.controller.northbound.bundlescanner.internal;
-
-
import java.io.File;
import java.io.FileFilter;
import java.net.MalformedURLException;
import org.springframework.osgi.mock.MockBundle;
import org.springframework.osgi.mock.MockBundleContext;
-import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class BundleScannerTest {
*/
package org.opendaylight.controller.topology.northbound;
-
-
import org.junit.Test;
import org.opendaylight.controller.sal.core.Bandwidth;
import org.opendaylight.controller.sal.core.ConstructionException;
import java.util.List;
import java.util.Set;
-import static junit.framework.Assert.assertEquals;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class TopologyTest {