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;
}
*/
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
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>();
}
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);
}
*/
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);
<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.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.cluster.datastore.node.utils.serialization;
+import com.google.protobuf.ByteString;
import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
import org.opendaylight.controller.cluster.datastore.util.InstanceIdentifierUtils;
import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
InstanceIdentifierUtils.toSerializable((YangInstanceIdentifier) value, context));
} else if(value instanceof Set) {
Set set = (Set) value;
- if(!set.isEmpty()){
- for(Object o : set){
- if(o instanceof String){
+ if (!set.isEmpty()) {
+ for (Object o : set) {
+ if (o instanceof String) {
builder.addBitsValue(o.toString());
} else {
throw new IllegalArgumentException("Expected value type to be Bits but was : " +
- value.toString());
+ value.toString());
}
}
}
+ } else if(value instanceof byte[]){
+ builder.setBytesValue(ByteString.copyFrom((byte[]) value));
} else {
builder.setValue(value.toString());
}
node.getInstanceIdentifierValue(), context);
} else if(node.getIntValueType() == ValueType.BITS_TYPE.ordinal()){
return new HashSet(node.getBitsValueList());
+ } else if(node.getIntValueType() == ValueType.BINARY_TYPE.ordinal()){
+ return node.getBytesValue().toByteArray();
}
return deSerializeBasicTypes(node.getIntValueType(), node.getValue());
}
YANG_IDENTIFIER_TYPE,
STRING_TYPE,
BIG_INTEGER_TYPE,
- BIG_DECIMAL_TYPE;
+ BIG_DECIMAL_TYPE,
+ BINARY_TYPE;
private static Map<Class, ValueType> types = new HashMap<>();
types.put(Short.class,SHORT_TYPE);
types.put(BigInteger.class, BIG_INTEGER_TYPE);
types.put(BigDecimal.class, BIG_DECIMAL_TYPE);
+ types.put(byte[].class, BINARY_TYPE);
}
public static final ValueType getSerializableType(Object node){
*/
com.google.protobuf.ByteString
getCodeBytes(int index);
+
+ // optional bytes bytesValue = 13;
+ /**
+ * <code>optional bytes bytesValue = 13;</code>
+ */
+ boolean hasBytesValue();
+ /**
+ * <code>optional bytes bytesValue = 13;</code>
+ */
+ com.google.protobuf.ByteString getBytesValue();
}
/**
* Protobuf type {@code org.opendaylight.controller.mdsal.Node}
code_.add(input.readBytes());
break;
}
+ case 106: {
+ bitField0_ |= 0x00000100;
+ bytesValue_ = input.readBytes();
+ break;
+ }
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
return code_.getByteString(index);
}
+ // optional bytes bytesValue = 13;
+ public static final int BYTESVALUE_FIELD_NUMBER = 13;
+ private com.google.protobuf.ByteString bytesValue_;
+ /**
+ * <code>optional bytes bytesValue = 13;</code>
+ */
+ public boolean hasBytesValue() {
+ return ((bitField0_ & 0x00000100) == 0x00000100);
+ }
+ /**
+ * <code>optional bytes bytesValue = 13;</code>
+ */
+ public com.google.protobuf.ByteString getBytesValue() {
+ return bytesValue_;
+ }
+
private void initFields() {
path_ = "";
type_ = "";
instanceIdentifierValue_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.getDefaultInstance();
bitsValue_ = com.google.protobuf.LazyStringArrayList.EMPTY;
code_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+ bytesValue_ = com.google.protobuf.ByteString.EMPTY;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
for (int i = 0; i < code_.size(); i++) {
output.writeBytes(12, code_.getByteString(i));
}
+ if (((bitField0_ & 0x00000100) == 0x00000100)) {
+ output.writeBytes(13, bytesValue_);
+ }
getUnknownFields().writeTo(output);
}
size += dataSize;
size += 1 * getCodeList().size();
}
+ if (((bitField0_ & 0x00000100) == 0x00000100)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(13, bytesValue_);
+ }
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
bitField0_ = (bitField0_ & ~0x00000400);
code_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000800);
+ bytesValue_ = com.google.protobuf.ByteString.EMPTY;
+ bitField0_ = (bitField0_ & ~0x00001000);
return this;
}
bitField0_ = (bitField0_ & ~0x00000800);
}
result.code_ = code_;
+ if (((from_bitField0_ & 0x00001000) == 0x00001000)) {
+ to_bitField0_ |= 0x00000100;
+ }
+ result.bytesValue_ = bytesValue_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
onChanged();
}
+ if (other.hasBytesValue()) {
+ setBytesValue(other.getBytesValue());
+ }
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
return this;
}
+ // optional bytes bytesValue = 13;
+ private com.google.protobuf.ByteString bytesValue_ = com.google.protobuf.ByteString.EMPTY;
+ /**
+ * <code>optional bytes bytesValue = 13;</code>
+ */
+ public boolean hasBytesValue() {
+ return ((bitField0_ & 0x00001000) == 0x00001000);
+ }
+ /**
+ * <code>optional bytes bytesValue = 13;</code>
+ */
+ public com.google.protobuf.ByteString getBytesValue() {
+ return bytesValue_;
+ }
+ /**
+ * <code>optional bytes bytesValue = 13;</code>
+ */
+ public Builder setBytesValue(com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00001000;
+ bytesValue_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * <code>optional bytes bytesValue = 13;</code>
+ */
+ public Builder clearBytesValue() {
+ bitField0_ = (bitField0_ & ~0x00001000);
+ bytesValue_ = getDefaultInstance().getBytesValue();
+ onChanged();
+ return this;
+ }
+
// @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.Node)
}
"ntroller.mdsal.Attribute\022\017\n\007intType\030\006 \001(" +
"\005\"f\n\022InstanceIdentifier\022B\n\targuments\030\001 \003" +
"(\0132/.org.opendaylight.controller.mdsal.P" +
- "athArgument\022\014\n\004code\030\002 \003(\t\"\245\003\n\004Node\022\014\n\004pa" +
+ "athArgument\022\014\n\004code\030\002 \003(\t\"\271\003\n\004Node\022\014\n\004pa" +
"th\030\001 \001(\t\022\014\n\004type\030\002 \001(\t\022E\n\014pathArgument\030\003" +
" \001(\0132/.org.opendaylight.controller.mdsal" +
".PathArgument\022\017\n\007intType\030\004 \001(\005\022@\n\nattrib",
"pe\030\t \001(\005\022V\n\027instanceIdentifierValue\030\n \001(" +
"\01325.org.opendaylight.controller.mdsal.In" +
"stanceIdentifier\022\021\n\tbitsValue\030\013 \003(\t\022\014\n\004c" +
- "ode\030\014 \003(\t\"`\n\tContainer\022\022\n\nparentPath\030\001 \002" +
- "(\t\022?\n\016normalizedNode\030\002 \001(\0132\'.org.openday" +
- "light.controller.mdsal.Node\"\246\001\n\014NodeMapE",
- "ntry\022U\n\026instanceIdentifierPath\030\001 \002(\01325.o" +
- "rg.opendaylight.controller.mdsal.Instanc" +
- "eIdentifier\022?\n\016normalizedNode\030\002 \001(\0132\'.or" +
- "g.opendaylight.controller.mdsal.Node\"N\n\007" +
- "NodeMap\022C\n\nmapEntries\030\001 \003(\0132/.org.openda" +
- "ylight.controller.mdsal.NodeMapEntryBO\n5" +
- "org.opendaylight.controller.protobuff.me" +
- "ssages.commonB\026NormalizedNodeMessages"
+ "ode\030\014 \003(\t\022\022\n\nbytesValue\030\r \001(\014\"`\n\tContain" +
+ "er\022\022\n\nparentPath\030\001 \002(\t\022?\n\016normalizedNode" +
+ "\030\002 \001(\0132\'.org.opendaylight.controller.mds",
+ "al.Node\"\246\001\n\014NodeMapEntry\022U\n\026instanceIden" +
+ "tifierPath\030\001 \002(\01325.org.opendaylight.cont" +
+ "roller.mdsal.InstanceIdentifier\022?\n\016norma" +
+ "lizedNode\030\002 \001(\0132\'.org.opendaylight.contr" +
+ "oller.mdsal.Node\"N\n\007NodeMap\022C\n\nmapEntrie" +
+ "s\030\001 \003(\0132/.org.opendaylight.controller.md" +
+ "sal.NodeMapEntryBO\n5org.opendaylight.con" +
+ "troller.protobuff.messages.commonB\026Norma" +
+ "lizedNodeMessages"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
internal_static_org_opendaylight_controller_mdsal_Node_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_opendaylight_controller_mdsal_Node_descriptor,
- new java.lang.String[] { "Path", "Type", "PathArgument", "IntType", "Attributes", "Child", "Value", "ValueType", "IntValueType", "InstanceIdentifierValue", "BitsValue", "Code", });
+ new java.lang.String[] { "Path", "Type", "PathArgument", "IntType", "Attributes", "Child", "Value", "ValueType", "IntValueType", "InstanceIdentifierValue", "BitsValue", "Code", "BytesValue", });
internal_static_org_opendaylight_controller_mdsal_Container_descriptor =
getDescriptor().getMessageTypes().get(6);
internal_static_org_opendaylight_controller_mdsal_Container_fieldAccessorTable = new
repeated string bitsValue = 11; // intValueType = Bits
repeated string code = 12; // A list of string codes which can be used for any repeated strings in the NormalizedNode
+
+ optional bytes bytesValue = 13;
}
message Container{
package org.opendaylight.controller.cluster.datastore.node.utils.serialization;
+import com.google.common.base.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opendaylight.controller.cluster.datastore.util.TestModel;
import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
public class NormalizedNodeSerializerTest {
// created by serializing the original node and deSerializing it back.
assertEquals(expectedNode, actualNode);
+ byte[] binaryData = new byte[5];
+ for(byte i=0;i<5;i++){
+ binaryData[i] = i;
+ }
+
+ ContainerNode node1 = TestModel.createBaseTestContainerBuilder()
+ .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATE_QNAME, binaryData))
+ .build();
+
+ NormalizedNodeMessages.Node serializedNode1 = NormalizedNodeSerializer
+ .serialize(node1);
+
+ ContainerNode node2 =
+ (ContainerNode) NormalizedNodeSerializer.deSerialize(serializedNode1);
+
+
+ // FIXME: This will not work due to BUG 2326. Once that is fixed we can uncomment this assertion
+ // assertEquals(node1, node2);
+
+ Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = node2.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.SOME_BINARY_DATE_QNAME));
+
+ Object value = child.get().getValue();
+
+ assertTrue("value should be of type byte[]", value instanceof byte[]);
+
+ byte[] bytesValue = (byte[]) value;
+
+ for(byte i=0;i<5;i++){
+ assertEquals(i, bytesValue[i]);
+ }
+
}
@Test(expected = NullPointerException.class)
--- /dev/null
+package org.opendaylight.controller.cluster.datastore.node.utils.serialization;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class ValueTypeTest {
+
+ @Test
+ public void testGetSerializableType(){
+ byte[] b = new byte[10];
+ b[0] = 1;
+ b[2] = 2;
+
+ ValueType serializableType = ValueType.getSerializableType(b);
+ assertEquals(ValueType.BINARY_TYPE, serializableType);
+ }
+}
\ No newline at end of file
public static final QName DESC_QNAME = QName.create(TEST_QNAME, "desc");
public static final QName POINTER_QNAME = QName.create(TEST_QNAME, "pointer");
+ public static final QName SOME_BINARY_DATE_QNAME = QName.create(TEST_QNAME, "some-binary-data");
public static final QName SOME_REF_QNAME = QName.create(TEST_QNAME,
"some-ref");
public static final QName MYIDENTITY_QNAME = QName.create(TEST_QNAME,
}
- public static ContainerNode createTestContainer() {
-
-
- // Create a list of shoes
- // This is to test leaf list entry
- final LeafSetEntryNode<Object> nike =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeWithValue(QName.create(
- TEST_QNAME, "shoe"), "nike")).withValue("nike").build();
-
- final LeafSetEntryNode<Object> puma =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeWithValue(QName.create(
- TEST_QNAME, "shoe"), "puma")).withValue("puma").build();
-
- final LeafSetNode<Object> shoes =
- ImmutableLeafSetNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(QName.create(
- TEST_QNAME, "shoe"))).withChild(nike).withChild(puma)
- .build();
-
-
- // Test a leaf-list where each entry contains an identity
- final LeafSetEntryNode<Object> cap1 =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeWithValue(QName.create(
- TEST_QNAME, "capability"), DESC_QNAME))
- .withValue(DESC_QNAME).build();
-
- final LeafSetNode<Object> capabilities =
- ImmutableLeafSetNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(QName.create(
- TEST_QNAME, "capability"))).withChild(cap1).build();
-
- ContainerNode switchFeatures =
- ImmutableContainerNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(SWITCH_FEATURES_QNAME))
- .withChild(capabilities).build();
-
- // Create a leaf list with numbers
- final LeafSetEntryNode<Object> five =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- (new YangInstanceIdentifier.NodeWithValue(QName.create(
- TEST_QNAME, "number"), 5))).withValue(5).build();
- final LeafSetEntryNode<Object> fifteen =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- (new YangInstanceIdentifier.NodeWithValue(QName.create(
- TEST_QNAME, "number"), 15))).withValue(15).build();
- final LeafSetNode<Object> numbers =
- ImmutableLeafSetNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(QName.create(
- TEST_QNAME, "number"))).withChild(five).withChild(fifteen)
- .build();
-
-
- // Create augmentations
- MapEntryNode mapEntry = createAugmentedListEntry(1, "First Test");
-
- // Create a bits leaf
+ public static DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> createBaseTestContainerBuilder() {
+ // Create a list of shoes
+ // This is to test leaf list entry
+ final LeafSetEntryNode<Object> nike =
+ ImmutableLeafSetEntryNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeWithValue(QName.create(
+ TEST_QNAME, "shoe"), "nike")).withValue("nike").build();
+
+ final LeafSetEntryNode<Object> puma =
+ ImmutableLeafSetEntryNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeWithValue(QName.create(
+ TEST_QNAME, "shoe"), "puma")).withValue("puma").build();
+
+ final LeafSetNode<Object> shoes =
+ ImmutableLeafSetNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(QName.create(
+ TEST_QNAME, "shoe"))).withChild(nike).withChild(puma)
+ .build();
+
+
+ // Test a leaf-list where each entry contains an identity
+ final LeafSetEntryNode<Object> cap1 =
+ ImmutableLeafSetEntryNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeWithValue(QName.create(
+ TEST_QNAME, "capability"), DESC_QNAME))
+ .withValue(DESC_QNAME).build();
+
+ final LeafSetNode<Object> capabilities =
+ ImmutableLeafSetNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(QName.create(
+ TEST_QNAME, "capability"))).withChild(cap1).build();
+
+ ContainerNode switchFeatures =
+ ImmutableContainerNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(SWITCH_FEATURES_QNAME))
+ .withChild(capabilities).build();
+
+ // Create a leaf list with numbers
+ final LeafSetEntryNode<Object> five =
+ ImmutableLeafSetEntryNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ (new YangInstanceIdentifier.NodeWithValue(QName.create(
+ TEST_QNAME, "number"), 5))).withValue(5).build();
+ final LeafSetEntryNode<Object> fifteen =
+ ImmutableLeafSetEntryNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ (new YangInstanceIdentifier.NodeWithValue(QName.create(
+ TEST_QNAME, "number"), 15))).withValue(15).build();
+ final LeafSetNode<Object> numbers =
+ ImmutableLeafSetNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(QName.create(
+ TEST_QNAME, "number"))).withChild(five).withChild(fifteen)
+ .build();
+
+
+ // Create augmentations
+ MapEntryNode mapEntry = createAugmentedListEntry(1, "First Test");
+
+ // Create a bits leaf
NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>>
- myBits = Builders.leafBuilder().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(
- QName.create(TEST_QNAME, "my-bits"))).withValue(
- ImmutableSet.of("foo", "bar"));
+ myBits = Builders.leafBuilder().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(
+ QName.create(TEST_QNAME, "my-bits"))).withValue(
+ ImmutableSet.of("foo", "bar"));
// Create the document
- return ImmutableContainerNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME))
- .withChild(myBits.build())
- .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC))
- .withChild(ImmutableNodes.leafNode(POINTER_QNAME, "pointer"))
- .withChild(
- ImmutableNodes.leafNode(SOME_REF_QNAME, YangInstanceIdentifier
- .builder().build()))
- .withChild(ImmutableNodes.leafNode(MYIDENTITY_QNAME, DESC_QNAME))
-
- // .withChild(augmentationNode)
- .withChild(shoes)
- .withChild(numbers)
- .withChild(switchFeatures)
- .withChild(
- mapNodeBuilder(AUGMENTED_LIST_QNAME).withChild(mapEntry).build())
- .withChild(
- mapNodeBuilder(OUTER_LIST_QNAME)
- .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID))
- .withChild(BAR_NODE).build()).build();
+ return ImmutableContainerNodeBuilder
+ .create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME))
+ .withChild(myBits.build())
+ .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC))
+ .withChild(ImmutableNodes.leafNode(POINTER_QNAME, "pointer"))
+ .withChild(
+ ImmutableNodes.leafNode(SOME_REF_QNAME, YangInstanceIdentifier
+ .builder().build()))
+ .withChild(ImmutableNodes.leafNode(MYIDENTITY_QNAME, DESC_QNAME))
+
+ // .withChild(augmentationNode)
+ .withChild(shoes)
+ .withChild(numbers)
+ .withChild(switchFeatures)
+ .withChild(
+ mapNodeBuilder(AUGMENTED_LIST_QNAME).withChild(mapEntry).build())
+ .withChild(
+ mapNodeBuilder(OUTER_LIST_QNAME)
+ .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID))
+ .withChild(BAR_NODE).build());
+ }
+ public static ContainerNode createTestContainer() {
+ return createBaseTestContainerBuilder().build();
}
public static MapEntryNode createAugmentedListEntry(int id, String name) {
}
}
+ leaf some-binary-data {
+ type binary;
+ }
+
}
}
<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();
}
}
package org.opendaylight.controller.cluster.datastore;
import akka.actor.ActorSelection;
-import akka.dispatch.Futures;
+import akka.dispatch.OnComplete;
+import java.util.AbstractMap.SimpleEntry;
+import java.util.List;
import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
-import scala.concurrent.Await;
import scala.concurrent.Future;
-
-import java.util.Collections;
-import java.util.List;
+import scala.concurrent.Promise;
/**
* TransactionChainProxy acts as a proxy for a DOMStoreTransactionChain created on a remote shard
public class TransactionChainProxy implements DOMStoreTransactionChain{
private final ActorContext actorContext;
private final String transactionChainId;
- private volatile List<Future<ActorSelection>> cohortFutures = Collections.emptyList();
+ private volatile SimpleEntry<Object, List<Future<ActorSelection>>> previousTxReadyFutures;
public TransactionChainProxy(ActorContext actorContext) {
this.actorContext = actorContext;
@Override
public DOMStoreReadTransaction newReadOnlyTransaction() {
- return new TransactionProxy(actorContext,
- TransactionProxy.TransactionType.READ_ONLY, this);
+ return new ChainedTransactionProxy(actorContext, TransactionProxy.TransactionType.READ_ONLY);
}
@Override
public DOMStoreReadWriteTransaction newReadWriteTransaction() {
- return new TransactionProxy(actorContext,
- TransactionProxy.TransactionType.READ_WRITE, this);
+ return new ChainedTransactionProxy(actorContext, TransactionProxy.TransactionType.READ_WRITE);
}
@Override
public DOMStoreWriteTransaction newWriteOnlyTransaction() {
- return new TransactionProxy(actorContext,
- TransactionProxy.TransactionType.WRITE_ONLY, this);
+ return new ChainedTransactionProxy(actorContext, TransactionProxy.TransactionType.WRITE_ONLY);
}
@Override
return transactionChainId;
}
- public void onTransactionReady(List<Future<ActorSelection>> cohortFutures){
- this.cohortFutures = cohortFutures;
- }
+ private class ChainedTransactionProxy extends TransactionProxy {
+
+ ChainedTransactionProxy(ActorContext actorContext, TransactionType transactionType) {
+ super(actorContext, transactionType, transactionChainId);
+ }
+
+ @Override
+ protected void onTransactionReady(List<Future<ActorSelection>> cohortFutures) {
+ if(!cohortFutures.isEmpty()) {
+ previousTxReadyFutures = new SimpleEntry<>(getIdentifier(), cohortFutures);
+ } else {
+ previousTxReadyFutures = null;
+ }
+ }
+
+ /**
+ * This method is overridden to ensure the previous Tx's ready operations complete
+ * before we create the next shard Tx in the chain to avoid creation failures if the
+ * previous Tx's ready operations haven't completed yet.
+ */
+ @Override
+ protected Future<Object> sendCreateTransaction(final ActorSelection shard,
+ final Object serializedCreateMessage) {
+ // Check if there are any previous ready Futures. Also make sure the previous ready
+ // Futures aren't for this Tx as deadlock would occur if tried to wait on our own
+ // Futures. This may happen b/c the shard Tx creates are done async so it's possible
+ // for the client to ready this Tx before we've even attempted to create a shard Tx.
+ if(previousTxReadyFutures == null ||
+ previousTxReadyFutures.getKey().equals(getIdentifier())) {
+ return super.sendCreateTransaction(shard, serializedCreateMessage);
+ }
+
+ // Combine the ready Futures into 1.
+ Future<Iterable<ActorSelection>> combinedFutures = akka.dispatch.Futures.sequence(
+ previousTxReadyFutures.getValue(), actorContext.getActorSystem().dispatcher());
+
+ // Add a callback for completion of the combined Futures.
+ final Promise<Object> createTxPromise = akka.dispatch.Futures.promise();
+ OnComplete<Iterable<ActorSelection>> onComplete = new OnComplete<Iterable<ActorSelection>>() {
+ @Override
+ public void onComplete(Throwable failure, Iterable<ActorSelection> notUsed) {
+ if(failure != null) {
+ // A Ready Future failed so fail the returned Promise.
+ createTxPromise.failure(failure);
+ } else {
+ // Send the CreateTx message and use the resulting Future to complete the
+ // returned Promise.
+ createTxPromise.completeWith(actorContext.executeOperationAsync(shard,
+ serializedCreateMessage));
+ }
+ }
+ };
+
+ combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
- public void waitTillCurrentTransactionReady(){
- try {
- Await.result(Futures
- .sequence(this.cohortFutures, actorContext.getActorSystem().dispatcher()),
- actorContext.getOperationDuration());
- } catch (Exception e) {
- throw new IllegalStateException("Failed when waiting for transaction on a chain to become ready", e);
+ return createTxPromise.future();
}
}
}
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
import scala.concurrent.Promise;
import scala.concurrent.duration.FiniteDuration;
-import javax.annotation.concurrent.GuardedBy;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-
/**
* TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard
* <p>
private final TransactionType transactionType;
private final ActorContext actorContext;
private final TransactionIdentifier identifier;
- private final TransactionChainProxy transactionChainProxy;
+ private final String transactionChainId;
private final SchemaContext schemaContext;
private boolean inReadyState;
public TransactionProxy(ActorContext actorContext, TransactionType transactionType) {
- this(actorContext, transactionType, null);
+ this(actorContext, transactionType, "");
}
public TransactionProxy(ActorContext actorContext, TransactionType transactionType,
- TransactionChainProxy transactionChainProxy) {
+ String transactionChainId) {
this.actorContext = Preconditions.checkNotNull(actorContext,
"actorContext should not be null");
this.transactionType = Preconditions.checkNotNull(transactionType,
"transactionType should not be null");
this.schemaContext = Preconditions.checkNotNull(actorContext.getSchemaContext(),
"schemaContext should not be null");
- this.transactionChainProxy = transactionChainProxy;
+ this.transactionChainId = transactionChainId;
String memberName = actorContext.getCurrentMemberName();
if(memberName == null){
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) {
}
}
- if(transactionChainProxy != null){
- transactionChainProxy.onTransactionReady(cohortFutures);
- }
+ onTransactionReady(cohortFutures);
return new ThreePhaseCommitCohortProxy(actorContext, cohortFutures,
identifier.toString());
}
+ /**
+ * Method for derived classes to be notified when the transaction has been readied.
+ *
+ * @param cohortFutures the cohort Futures for each shard transaction.
+ */
+ protected void onTransactionReady(List<Future<ActorSelection>> cohortFutures) {
+ }
+
+ /**
+ * Method called to send a CreateTransaction message to a shard.
+ *
+ * @param shard the shard actor to send to
+ * @param serializedCreateMessage the serialized message to send
+ * @return the response Future
+ */
+ protected Future<Object> sendCreateTransaction(ActorSelection shard,
+ Object serializedCreateMessage) {
+ return actorContext.executeOperationAsync(shard, serializedCreateMessage);
+ }
+
@Override
public Object getIdentifier() {
return this.identifier;
}
public String getTransactionChainId() {
- if(transactionChainProxy == null){
- return "";
- }
- return transactionChainProxy.getTransactionChainId();
+ return transactionChainId;
}
/**
* Performs a CreateTransaction try async.
*/
private void tryCreateTransaction() {
- Future<Object> createTxFuture = actorContext.executeOperationAsync(primaryShard,
+ Future<Object> createTxFuture = sendCreateTransaction(primaryShard,
new CreateTransaction(identifier.toString(),
TransactionProxy.this.transactionType.ordinal(),
getTransactionChainId()).toSerializable());
// 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());
package org.opendaylight.controller.cluster.datastore;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.PoisonPill;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Uninterruptibles;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
public class DistributedDataStoreIntegrationTest extends AbstractActorTest {
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
// 2. Write some data
- NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- writeTx.write(TestModel.TEST_PATH, containerNode);
+ NormalizedNode<?, ?> testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ writeTx.write(TestModel.TEST_PATH, testNode);
// 3. Ready the Tx for commit
- DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
+ final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
- // 4. Commit the Tx
+ // 4. Commit the Tx on another thread that first waits for the second read 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);
+ final CountDownLatch continueCommit1 = new CountDownLatch(1);
+ final CountDownLatch commit1Done = new CountDownLatch(1);
+ final AtomicReference<Exception> commit1Error = new AtomicReference<>();
+ new Thread() {
+ @Override
+ public void run() {
+ try {
+ continueCommit1.await();
+ doCommit(cohort1);
+ } catch (Exception e) {
+ commit1Error.set(e);
+ } finally {
+ commit1Done.countDown();
+ }
+ }
+ }.start();
- // 5. Verify the data in the store
+ // 5. Create a new read Tx from the chain to read and verify the data from the first
+ // Tx is visible after being readied.
DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
-
Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", containerNode, optional.get());
+ assertEquals("Data node", testNode, optional.get());
+
+ // 6. Create a new RW Tx from the chain, write more data, and ready it
+
+ DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
+ MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
+ rwTx.write(TestModel.OUTER_LIST_PATH, outerNode);
+
+ DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready();
+
+ // 7. Create a new read Tx from the chain to read the data from the last RW Tx to
+ // verify it is visible.
+
+ readTx = txChain.newReadOnlyTransaction();
+ optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", outerNode, optional.get());
+
+ // 8. Wait for the 2 commits to complete and close the chain.
+
+ continueCommit1.countDown();
+ Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS);
+
+ if(commit1Error.get() != null) {
+ throw commit1Error.get();
+ }
+
+ doCommit(cohort2);
txChain.close();
+ // 9. Create a new read Tx from the data store and verify committed data.
+
+ readTx = dataStore.newReadOnlyTransaction();
+ optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", outerNode, optional.get());
+
cleanup(dataStore);
}};
}
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;
<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
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) {
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");
- }
}
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;
--- /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());
+ }
+ }
+}
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
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;