</dependenciesToScan>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <version>2.8</version>
+ <executions>
+ <execution>
+ <id>unpack-static-documentation</id>
+ <goals>
+ <goal>unpack-dependencies</goal>
+ </goals>
+ <phase>generate-resources</phase>
+ <configuration>
+ <outputDirectory>${project.build.directory}/generated-resources/swagger-api-documentation</outputDirectory>
+ <includeArtifactIds>sal-rest-docgen</includeArtifactIds>
+ <includes>**/explorer/css/**/*, **/explorer/images/**/*, **/explorer/lib/**/*, **/explorer/static/**/*,</includes>
+ <excludeTransitive>true</excludeTransitive>
+ <ignorePermissions>false</ignorePermissions>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-maven-plugin</artifactId>
+ <version>${yangtools.version}</version>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>maven-sal-api-gen-plugin</artifactId>
+ <version>${yangtools.version}</version>
+ <type>jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-binding</artifactId>
+ <version>${yangtools.version}</version>
+ <type>jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-rest-docgen</artifactId>
+ <version>${mdsal.version}</version>
+ <type>jar</type>
+ </dependency>
+ </dependencies>
+ <executions>
+ <execution>
+ <goals>
+ <goal>generate-sources</goal>
+ </goals>
+ <configuration>
+ <yangFilesRootDir>src</yangFilesRootDir>
+ <codeGenerators>
+ <generator>
+ <codeGeneratorClass>org.opendaylight.controller.sal.rest.doc.impl.StaticDocGenerator</codeGeneratorClass>
+ <outputBaseDir>${project.build.directory}/generated-resources/swagger-api-documentation/explorer/static</outputBaseDir>
+ </generator>
+ </codeGenerators>
+ <inspectDependencies>true</inspectDependencies>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
<scm>
* dependencies are satisfied
*
*/
- @SuppressWarnings({ "unchecked", "rawtypes" })
+ @SuppressWarnings("unchecked")
public void init() {
log.debug("Routing init() is called");
this.topologyBWAware = new ConcurrentHashMap<Short, Graph<Node, Edge>>();
<config.configfile.directory>etc/opendaylight/karaf</config.configfile.directory>
<config.clustering.configfile>05-clustering.xml</config.clustering.configfile>
<config.netty.configfile>00-netty.xml</config.netty.configfile>
- <config.mdsal.configfile>01-mdsal.xml</config.mdsal.configfile>
+ <config.mdsal.configfile>01-md-sal.xml</config.mdsal.configfile>
<config.xsql.configfile>04-xsql.xml</config.xsql.configfile>
<config.netconf.client.configfile>01-netconf.xml</config.netconf.client.configfile>
<config.toaster.configfile>03-toaster-sample.xml</config.toaster.configfile>
import java.util.List;
import java.util.Set;
-
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.jmx.CommitStatus;
import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
package org.opendaylight.controller.config.api;
import java.util.Set;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
package org.opendaylight.controller.config.api;
import javax.management.DynamicMBean;
-
import org.opendaylight.controller.config.spi.Module;
/**
*/
package org.opendaylight.controller.config.api;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-
import java.beans.ConstructorProperties;
+import org.opendaylight.yangtools.yang.binding.BaseIdentity;
public final class IdentityAttributeRef {
*/
package org.opendaylight.controller.config.api;
+import java.util.Set;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-import java.util.Set;
public interface LookupRegistry {
*/
package org.opendaylight.controller.config.api;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
import java.util.Map;
import java.util.Set;
+import javax.management.InstanceNotFoundException;
+import javax.management.ObjectName;
public interface ServiceReferenceReadableRegistry {
*/
package org.opendaylight.controller.config.api.jmx;
-import javax.annotation.concurrent.Immutable;
-import javax.management.ObjectName;
import java.beans.ConstructorProperties;
import java.util.Collections;
import java.util.List;
+import javax.annotation.concurrent.Immutable;
+import javax.management.ObjectName;
@Immutable
public class CommitStatus {
private final List<ObjectName> newInstances, reusedInstances,
- recreatedInstances;
+ recreatedInstances;
/**
* @param newInstances newly created instances
*/
package org.opendaylight.controller.config.api.jmx;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
-
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import javax.annotation.concurrent.ThreadSafe;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import org.opendaylight.controller.config.api.ModuleIdentifier;
+import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
/**
* Provides ObjectName creation. Each created ObjectName consists of domain that
*/
package org.opendaylight.controller.config.spi;
+import javax.annotation.concurrent.NotThreadSafe;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.yangtools.concepts.Identifiable;
-import javax.annotation.concurrent.NotThreadSafe;
-
/**
* Represents one service that is to be configured. These methods need to be
*/
package org.opendaylight.controller.config.spi;
+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.api.annotations.AbstractServiceInterface;
import org.osgi.framework.BundleContext;
-import java.util.Set;
-
/**
* Factory which creates {@link Module instances. An instance of this interface
* needs to be exported into the OSGi Service Registry. Such an instance
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.opendaylight.yangtools.yang.binding.BaseIdentity;
package org.opendaylight.controller.config.api;
-import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+
public class JmxAttributeTest {
@Test
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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
+
import org.junit.Test;
public class ModuleIdentifierTest {
import static org.junit.Assert.assertThat;
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 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.Collections;
import java.util.List;
import java.util.Map;
-
import javax.annotation.concurrent.Immutable;
-
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.manager.impl.dependencyresolver.DestroyedModule;
import org.opendaylight.controller.config.manager.impl.dependencyresolver.ModuleInternalTransactionalInfo;
package org.opendaylight.controller.config.manager.impl;
import com.google.common.collect.Maps;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.NotThreadSafe;
+import javax.annotation.concurrent.ThreadSafe;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.ObjectName;
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.annotation.concurrent.GuardedBy;
-import javax.annotation.concurrent.NotThreadSafe;
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
/**
* Singleton that is responsible for creating and committing Config
* Transactions. It is registered in Platform MBean Server.
*/
@ThreadSafe
public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBean {
- private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRegistryImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigRegistryImpl.class);
private final ModuleFactoriesResolver resolver;
private final MBeanServer configMBeanServer;
for (ModuleInternalInfo moduleInternalInfo : currentConfig.getEntries()) {
String name = moduleInternalInfo.getModuleFactory().getImplementationName();
if (allCurrentFactories.containsKey(name) == false) {
- LOGGER.trace("Factory {} not found in SR, using reference from previous commit", name);
+ LOG.trace("Factory {} not found in SR, using reference from previous commit", name);
allCurrentFactories.put(name,
Maps.immutableEntry(moduleInternalInfo.getModuleFactory(), moduleInternalInfo.getBundleContext()));
}
throws ConflictingVersionException, ValidationException {
final String transactionName = ObjectNameUtil
.getTransactionName(transactionControllerON);
- LOGGER.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
+ LOG.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
// find ConfigTransactionController
Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder.getCurrentTransactions();
} catch (Error | RuntimeException t) { // some libs throw Errors: e.g.
// javax.xml.ws.spi.FactoryFinder$ConfigurationError
isHealthy = false;
- LOGGER.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
+ LOG.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
int orderingIdx = 0;
for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
- LOGGER.trace("Registering {}", moduleIdentifier);
+ LOG.trace("Registering {}", moduleIdentifier);
ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
.get(moduleIdentifier);
if (entry == null) {
configTransactionControllerEntry.getValue().close();
configTransactionController.abortConfig();
} catch (RuntimeException e) {
- LOGGER.warn("Ignoring exception while aborting {}",
+ LOG.warn("Ignoring exception while aborting {}",
configTransactionController, e);
}
}
ConfigTransactionControllerInternal,
ConfigTransactionControllerImplMXBean,
Identifiable<TransactionIdentifier> {
- private static final Logger LOGGER = LoggerFactory.getLogger(ConfigTransactionControllerImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigTransactionControllerImpl.class);
private final ConfigTransactionLookupRegistry txLookupRegistry;
private final ObjectName controllerON;
boolean isDefaultBean, BundleContext bundleContext)
throws InstanceAlreadyExistsException {
- LOGGER.debug("Adding module {} to transaction {}", moduleIdentifier, this);
+ LOG.debug("Adding module {} to transaction {}", moduleIdentifier, this);
if (moduleIdentifier.equals(module.getIdentifier()) == false) {
throw new IllegalStateException("Incorrect name reported by module. Expected "
+ moduleIdentifier + ", got " + module.getIdentifier());
}
private synchronized void destroyModule(ModuleIdentifier moduleIdentifier) {
- LOGGER.debug("Destroying module {} in transaction {}", moduleIdentifier, this);
+ LOG.debug("Destroying module {} in transaction {}", moduleIdentifier, this);
transactionStatus.checkNotAborted();
ModuleInternalTransactionalInfo found = dependencyResolverManager.findModuleInternalTransactionalInfo(moduleIdentifier);
if (blankTransaction == false &&
found.isDefaultBean()) {
- LOGGER.warn("Warning: removing default bean. This will be forbidden in next version of config-subsystem");
+ LOG.warn("Warning: removing default bean. This will be forbidden in next version of config-subsystem");
}
// first remove refNames, it checks for objectname existence
writableSRRegistry.removeServiceReferences(
ObjectNameUtil.createTransactionModuleON(getTransactionName(), moduleIdentifier));
} catch (InstanceNotFoundException e) {
- LOGGER.error("Possible code error: cannot find {} in {}", moduleIdentifier, writableSRRegistry);
+ LOG.error("Possible code error: cannot find {} in {}", moduleIdentifier, writableSRRegistry);
throw new IllegalStateException("Possible code error: cannot find " + moduleIdentifier, e);
}
private void validateNoLocks() throws ValidationException {
transactionStatus.checkNotAborted();
- LOGGER.trace("Validating transaction {}", getTransactionIdentifier());
+ LOG.trace("Validating transaction {}", getTransactionIdentifier());
// call validate()
List<ValidationException> collectedExceptions = new ArrayList<>();
for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager
try {
module.validate();
} catch (Exception e) {
- LOGGER.warn("Validation exception in {}", getTransactionName(),
+ LOG.warn("Validation exception in {}", getTransactionName(),
e);
collectedExceptions.add(ValidationException
.createForSingleException(name, e));
throw ValidationException
.createFromCollectedValidationExceptions(collectedExceptions);
}
- LOGGER.trace("Validated transaction {}", getTransactionIdentifier());
+ LOG.trace("Validated transaction {}", getTransactionIdentifier());
}
/**
try {
validateNoLocks();
} catch (ValidationException e) {
- LOGGER.trace("Commit failed on validation");
+ LOG.trace("Commit failed on validation");
configBeanModificationDisabled.set(false); // recoverable error
throw e;
}
+ "to obtain a lock");
}
- LOGGER.trace("Committing transaction {}", getTransactionIdentifier());
+ LOG.trace("Committing transaction {}", getTransactionIdentifier());
// call getInstance()
for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager
Module module = entry.getValue();
ModuleIdentifier name = entry.getKey();
try {
- LOGGER.debug("About to commit {} in transaction {}",
+ LOG.debug("About to commit {} in transaction {}",
name, getTransactionIdentifier());
AutoCloseable instance = module.getInstance();
checkNotNull(instance, "Instance is null:{} in transaction {}", name, getTransactionIdentifier());
} catch (Exception e) {
- LOGGER.error("Commit failed on {} in transaction {}", name,
+ LOG.error("Commit failed on {} in transaction {}", name,
getTransactionIdentifier(), e);
internalAbort();
throw new IllegalStateException(
// count dependency order
- LOGGER.trace("Committed configuration {}", getTransactionIdentifier());
+ LOG.trace("Committed configuration {}", getTransactionIdentifier());
transactionStatus.setCommitted();
return dependencyResolverManager.getSortedModuleIdentifiers();
}
private void internalAbort() {
- LOGGER.trace("Aborting {}", this);
+ LOG.trace("Aborting {}", this);
transactionStatus.setAborted();
close();
}
*/
package org.opendaylight.controller.config.manager.impl;
+import java.util.Collection;
+import java.util.List;
+import javax.management.ObjectName;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-import javax.management.ObjectName;
-import java.util.Collection;
-import java.util.List;
-
/**
* Defines contract between {@link ConfigTransactionControllerImpl} (producer)
* and {@link ConfigRegistryImpl} (consumer).
*/
package org.opendaylight.controller.config.manager.impl;
+import java.io.Closeable;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.ObjectName;
import org.opendaylight.controller.config.api.LookupRegistry;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.manager.impl.jmx.TransactionJMXRegistrator;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import java.io.Closeable;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
/**
* Responsible for creating TransactionJMXRegistrator, registering transaction and all its beans,
* lookup of beans, closing of TransactionJMXRegistrator.
package org.opendaylight.controller.config.manager.impl;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.GuardedBy;
import java.util.Deque;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.opendaylight.controller.config.api.ModuleIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class DeadlockMonitor implements AutoCloseable {
- private static final Logger LOGGER = LoggerFactory.getLogger(DeadlockMonitorRunnable.class);
+ private static final Logger LOG = LoggerFactory.getLogger(DeadlockMonitor.class);
private static final long WARN_AFTER_MILLIS = 5000;
moduleIdentifierWithNanosStack.push(current);
top = current;
}
- LOGGER.trace("setCurrentlyInstantiatedModule {}, top {}", currentlyInstantiatedModule, top);
+ LOG.trace("setCurrentlyInstantiatedModule {}, top {}", currentlyInstantiatedModule, top);
}
public boolean isAlive() {
// is the getInstance() running longer than WARN_AFTER_MILLIS ?
long runningTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - copy.nanoTime);
if (runningTime > WARN_AFTER_MILLIS) {
- LOGGER.warn("{} did not finish after {} ms", copy.moduleIdentifier, runningTime);
+ LOG.warn("{} did not finish after {} ms", copy.moduleIdentifier, runningTime);
}
}
try {
interrupt();
}
}
- LOGGER.trace("Exiting {}", this);
+ LOG.trace("Exiting {}", this);
}
@Override
package org.opendaylight.controller.config.manager.impl;
import javax.annotation.Nullable;
-
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.manager.impl.dependencyresolver.DestroyedModule;
import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
package org.opendaylight.controller.config.manager.impl;
import static com.google.common.base.Preconditions.checkNotNull;
+
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import org.slf4j.LoggerFactory;
public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
- private static final Logger LOGGER = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
private final Map<String, ModuleFactory> factories;
private final Map<String, Set<String>> factoryNamesToQNames;
boolean skipChecks = true;
newRegistry.saveServiceReference(refNameEntry.getKey(), currentImplementation, skipChecks);
} catch (InstanceNotFoundException e) {
- LOGGER.error("Cannot save service reference({}, {})", refNameEntry.getKey(), currentImplementation);
+ LOG.error("Cannot save service reference({}, {})", refNameEntry.getKey(), currentImplementation);
throw new IllegalStateException("Possible code error", e);
}
}
for (Entry<String, ModuleFactory> entry : factories.entrySet()) {
if (entry.getKey().equals(entry.getValue().getImplementationName()) == false) {
- LOGGER.error("Possible error in code: Mismatch between supplied and actual name of {}", entry);
+ LOG.error("Possible error in code: Mismatch between supplied and actual name of {}", entry);
throw new IllegalArgumentException("Possible error in code: Mismatch between supplied and actual name of " + entry);
}
Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(entry.getValue());
modifiableNamespacesToAnnotations.put(sia.namespace(), ofNamespace);
}
if (ofNamespace.containsKey(sia.localName())) {
- LOGGER.error("Cannot construct namespacesToAnnotations map, conflict between local names in {}, offending local name: {}, map so far {}",
+ LOG.error("Cannot construct namespacesToAnnotations map, conflict between local names in {}, offending local name: {}, map so far {}",
sia.namespace(), sia.localName(), modifiableNamespacesToAnnotations);
throw new IllegalArgumentException("Conflict between local names in " + sia.namespace() + " : " + sia.localName());
}
}
this.namespacesToAnnotations = ImmutableMap.copyOf(modifiableNamespacesToAnnotations);
this.serviceQNamesToAnnotations = ImmutableMap.copyOf(modifiableServiceQNamesToAnnotations);
- LOGGER.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames);
+ LOG.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames);
}
@Override
String factoryName = ObjectNameUtil.getFactoryName(objectName);
Set<String> serviceInterfaceAnnotations = factoryNamesToQNames.get(factoryName);
if (serviceInterfaceAnnotations == null) {
- LOGGER.error("Possible error in code: cannot find factory annotations of '{}' extracted from ON {} in {}",
+ LOG.error("Possible error in code: cannot find factory annotations of '{}' extracted from ON {} in {}",
factoryName, objectName, factoryNamesToQNames);
throw new IllegalArgumentException("Cannot find factory with name " + factoryName);
}
public synchronized String getServiceInterfaceName(final String namespace, final String localName) {
Map<String /* localName */, ServiceInterfaceAnnotation> ofNamespace = namespacesToAnnotations.get(namespace);
if (ofNamespace == null) {
- LOGGER.error("Cannot find namespace {} in {}", namespace, namespacesToAnnotations);
+ LOG.error("Cannot find namespace {} in {}", namespace, namespacesToAnnotations);
throw new IllegalArgumentException("Cannot find namespace " + namespace);
}
ServiceInterfaceAnnotation sia = ofNamespace.get(localName);
if (sia == null) {
- LOGGER.error("Cannot find local name {} in namespace {}, found only {}", localName, namespace, ofNamespace);
+ LOG.error("Cannot find local name {} in namespace {}, found only {}", localName, namespace, ofNamespace);
throw new IllegalArgumentException("Cannot find local name " + localName + " in namespace " + namespace);
}
return sia.value();
try {
on = lookupRegistry.lookupConfigBean(moduleIdentifier.getFactoryName(), moduleIdentifier.getInstanceName());
} catch (InstanceNotFoundException e) {
- LOGGER.error("Cannot find instance {}", moduleIdentifier);
+ LOG.error("Cannot find instance {}", moduleIdentifier);
throw new IllegalStateException("Cannot find instance " + moduleIdentifier, e);
}
return on;
ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName);
ModuleIdentifier moduleIdentifier = refNames.get(serviceReference);
if (moduleIdentifier == null) {
- LOGGER.error("Cannot find qname {} and refName {} in {}", serviceInterfaceQName, refName, refName);
+ LOG.error("Cannot find qname {} and refName {} in {}", serviceInterfaceQName, refName, refName);
throw new IllegalArgumentException("Cannot find " + serviceReference);
}
return getObjectName(moduleIdentifier);
Map<String, Map<String, ObjectName>> serviceMapping = getServiceMapping();
Map<String, ObjectName> innerMap = serviceMapping.get(serviceInterfaceQName);
if (innerMap == null) {
- LOGGER.error("Cannot find qname {} in {}", serviceInterfaceQName, refNames);
+ LOG.error("Cannot find qname {} in {}", serviceInterfaceQName, refNames);
throw new IllegalArgumentException("Cannot find " + serviceInterfaceQName);
}
return innerMap;
String referenceName = ObjectNameUtil.getReferenceName(objectName);
ServiceReference serviceReference = new ServiceReference(serviceQName, referenceName);
if (refNames.containsKey(serviceReference) == false) {
- LOGGER.warn("Cannot find {} in {}", serviceReference, refNames);
+ LOG.warn("Cannot find {} in {}", serviceReference, refNames);
throw new InstanceNotFoundException("Service reference not found:" + objectName);
}
}
// check that service interface name exist
Set<String> serviceInterfaceQNames = factoryNamesToQNames.get(moduleIdentifier.getFactoryName());
if (serviceInterfaceQNames == null) {
- LOGGER.error("Possible error in code: cannot find factoryName {} in {}, {}", moduleIdentifier.getFactoryName(),
+ LOG.error("Possible error in code: cannot find factoryName {} in {}, {}", moduleIdentifier.getFactoryName(),
factoryNamesToQNames, moduleIdentifier);
throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory " + moduleIdentifier.getFactoryName());
}
// supplied serviceInterfaceName must exist in this collection
if (serviceInterfaceQNames.contains(serviceReference.getServiceInterfaceQName()) == false) {
- LOGGER.error("Cannot find qName {} with factory name {}, found {}", serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(), serviceInterfaceQNames);
+ LOG.error("Cannot find qName {} with factory name {}, found {}", serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(), serviceInterfaceQNames);
throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName() + " within factory " + moduleIdentifier.getFactoryName());
}
}
private synchronized void removeServiceReference(final ServiceReference serviceReference) throws InstanceNotFoundException {
- LOGGER.debug("Removing service reference {} from {}", serviceReference, this);
+ LOG.debug("Removing service reference {} from {}", serviceReference, this);
assertWritable();
// is the qName known?
if (allQNames.contains(serviceReference.getServiceInterfaceQName()) == false) {
- LOGGER.error("Cannot find qname {} in {}", serviceReference.getServiceInterfaceQName(), allQNames);
+ LOG.error("Cannot find qname {} in {}", serviceReference.getServiceInterfaceQName(), allQNames);
throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName());
}
ModuleIdentifier removed = refNames.remove(serviceReference);
private Set<ServiceReference> findServiceReferencesLinkingTo(final ObjectName moduleObjectName, final Set<String> serviceInterfaceQNames) {
String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
if (serviceInterfaceQNames == null) {
- LOGGER.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName, factoryNamesToQNames, moduleObjectName);
+ LOG.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName, factoryNamesToQNames, moduleObjectName);
throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory " + factoryName);
}
String instanceName = ObjectNameUtil.getInstanceName(moduleObjectName);
*/
final class DependencyResolverImpl implements DependencyResolver,
Comparable<DependencyResolverImpl> {
- private static final Logger LOGGER = LoggerFactory.getLogger(DependencyResolverImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(DependencyResolverImpl.class);
private final ModulesHolder modulesHolder;
private final ModuleIdentifier name;
format("ObjectName should not contain "
+ "transaction name. %s set to %s. ", jmxAttribute,
dependentReadOnlyON
- ), jmxAttribute
+ ), jmxAttribute
);
ObjectName newDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
if (expectedBaseClass.isAssignableFrom(deserialized)) {
return (Class<T>) deserialized;
} else {
- LOGGER.error("Cannot resolve class of identity {} : deserialized class {} is not a subclass of {}.",
+ LOG.error("Cannot resolve class of identity {} : deserialized class {} is not a subclass of {}.",
identityRef, deserialized, expectedBaseClass);
throw new IllegalArgumentException("Deserialized identity " + deserialized + " cannot be cast to " + expectedBaseClass);
}
package org.opendaylight.controller.config.manager.impl.dependencyresolver;
import static com.google.common.base.Preconditions.checkState;
-
+import com.google.common.base.Preconditions;
import com.google.common.reflect.AbstractInvocationHandler;
import com.google.common.reflect.Reflection;
import java.lang.reflect.InvocationTargetException;
private final DeadlockMonitor deadlockMonitor;
private final MBeanServer mBeanServer;
- public DependencyResolverManager(TransactionIdentifier transactionIdentifier,
- TransactionStatus transactionStatus,
- ServiceReferenceReadableRegistry readableRegistry, CodecRegistry codecRegistry,
- MBeanServer mBeanServer) {
+ public DependencyResolverManager(final TransactionIdentifier transactionIdentifier,
+ final TransactionStatus transactionStatus,
+ final ServiceReferenceReadableRegistry readableRegistry, final CodecRegistry codecRegistry,
+ final MBeanServer mBeanServer) {
this.transactionIdentifier = transactionIdentifier;
this.modulesHolder = new ModulesHolder(transactionIdentifier);
this.transactionStatus = transactionStatus;
}
@Override
- public DependencyResolver createDependencyResolver(ModuleIdentifier moduleIdentifier) {
+ public DependencyResolver createDependencyResolver(final ModuleIdentifier moduleIdentifier) {
return getOrCreate(moduleIdentifier);
}
- public synchronized DependencyResolverImpl getOrCreate(ModuleIdentifier name) {
+ public synchronized DependencyResolverImpl getOrCreate(final ModuleIdentifier name) {
DependencyResolverImpl dependencyResolver = moduleIdentifiersToDependencyResolverMap.get(name);
if (dependencyResolver == null) {
transactionStatus.checkNotCommitted();
}
public ModuleInternalTransactionalInfo destroyModule(
- ModuleIdentifier moduleIdentifier) {
+ final ModuleIdentifier moduleIdentifier) {
transactionStatus.checkNotCommitted();
ModuleInternalTransactionalInfo found = modulesHolder
.destroyModule(moduleIdentifier);
// protect write access
+ private static final class ModuleInvocationHandler extends AbstractInvocationHandler {
+ private final DeadlockMonitor deadlockMonitor;
+ private final ModuleIdentifier moduleIdentifier;
+ private final Module module;
+
+ // optimization: subsequent calls to getInstance MUST return the same value during transaction,
+ // so it is safe to cache the response
+ private Object cachedInstance;
+
+ ModuleInvocationHandler(final DeadlockMonitor deadlockMonitor, final ModuleIdentifier moduleIdentifier, final Module module) {
+ this.deadlockMonitor = Preconditions.checkNotNull(deadlockMonitor);
+ this.moduleIdentifier = Preconditions.checkNotNull(moduleIdentifier);
+ this.module = Preconditions.checkNotNull(module);
+ }
+
+ @Override
+ protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable {
+ boolean isGetInstance = "getInstance".equals(method.getName());
+ if (isGetInstance) {
+ if (cachedInstance != null) {
+ return cachedInstance;
+ }
+
+ checkState(deadlockMonitor.isAlive(), "Deadlock monitor is not alive");
+ deadlockMonitor.setCurrentlyInstantiatedModule(moduleIdentifier);
+ }
+ try {
+ Object response = method.invoke(module, args);
+ if (isGetInstance) {
+ cachedInstance = response;
+ }
+ return response;
+ } catch(InvocationTargetException e) {
+ throw e.getCause();
+ } finally {
+ if (isGetInstance) {
+ deadlockMonitor.setCurrentlyInstantiatedModule(null);
+ }
+ }
+ }
+ }
+
public void put(
final ModuleIdentifier moduleIdentifier,
final Module module,
- ModuleFactory moduleFactory,
- ModuleInternalInfo maybeOldInternalInfo,
- TransactionModuleJMXRegistration transactionModuleJMXRegistration,
- boolean isDefaultBean, BundleContext bundleContext) {
+ final ModuleFactory moduleFactory,
+ final ModuleInternalInfo maybeOldInternalInfo,
+ final TransactionModuleJMXRegistration transactionModuleJMXRegistration,
+ final boolean isDefaultBean, final BundleContext bundleContext) {
transactionStatus.checkNotCommitted();
Class<? extends Module> moduleClass = Module.class;
if (module instanceof RuntimeBeanRegistratorAwareModule) {
moduleClass = RuntimeBeanRegistratorAwareModule.class;
}
- Module proxiedModule = Reflection.newProxy(moduleClass, new AbstractInvocationHandler() {
- // optimization: subsequent calls to getInstance MUST return the same value during transaction,
- // so it is safe to cache the response
- private Object cachedInstance;
-
- @Override
- protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
- boolean isGetInstance = "getInstance".equals(method.getName());
- if (isGetInstance) {
- if (cachedInstance != null) {
- return cachedInstance;
- }
-
- checkState(deadlockMonitor.isAlive(), "Deadlock monitor is not alive");
- deadlockMonitor.setCurrentlyInstantiatedModule(moduleIdentifier);
- }
- try {
- Object response = method.invoke(module, args);
- if (isGetInstance) {
- cachedInstance = response;
- }
- return response;
- } catch(InvocationTargetException e) {
- throw e.getCause();
- } finally {
- if (isGetInstance) {
- deadlockMonitor.setCurrentlyInstantiatedModule(null);
- }
- }
- }
- });
-
-
+ Module proxiedModule = Reflection.newProxy(moduleClass, new ModuleInvocationHandler(deadlockMonitor, moduleIdentifier, module));
ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = new ModuleInternalTransactionalInfo(
moduleIdentifier, proxiedModule, moduleFactory,
maybeOldInternalInfo, transactionModuleJMXRegistration, isDefaultBean, module, bundleContext);
return modulesHolder.toCommitInfo();
}
- public Module findModule(ModuleIdentifier moduleIdentifier,
- JmxAttribute jmxAttributeForReporting) {
+ public Module findModule(final ModuleIdentifier moduleIdentifier,
+ final JmxAttribute jmxAttributeForReporting) {
return modulesHolder.findModule(moduleIdentifier,
jmxAttributeForReporting);
}
- public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(ModuleIdentifier moduleIdentifier) {
+ public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(final ModuleIdentifier moduleIdentifier) {
return modulesHolder.findModuleInternalTransactionalInfo(moduleIdentifier);
}
- public ModuleFactory findModuleFactory(ModuleIdentifier moduleIdentifier,
- JmxAttribute jmxAttributeForReporting) {
+ public ModuleFactory findModuleFactory(final ModuleIdentifier moduleIdentifier,
+ final JmxAttribute jmxAttributeForReporting) {
return modulesHolder.findModuleFactory(moduleIdentifier,
jmxAttributeForReporting);
}
return modulesHolder.getAllModules();
}
- public void assertNotExists(ModuleIdentifier moduleIdentifier)
+ public void assertNotExists(final ModuleIdentifier moduleIdentifier)
throws InstanceAlreadyExistsException {
modulesHolder.assertNotExists(moduleIdentifier);
}
- public List<ModuleIdentifier> findAllByFactory(ModuleFactory factory) {
+ public List<ModuleIdentifier> findAllByFactory(final ModuleFactory factory) {
List<ModuleIdentifier> result = new ArrayList<>();
for (ModuleInternalTransactionalInfo info : modulesHolder.getAllInfos()) {
if (factory.equals(info.getModuleFactory())) {
return result;
}
+ @Override
public void close() {
deadlockMonitor.close();
}
*/
public class DestroyedModule implements AutoCloseable,
Comparable<DestroyedModule>, Identifiable<ModuleIdentifier> {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(DestroyedModule.class);
private final ModuleIdentifier identifier;
@Override
public void close() {
- LOGGER.trace("Destroying {}", identifier);
+ LOG.trace("Destroying {}", identifier);
try {
instance.close();
} catch (Exception e) {
- LOGGER.error("Error while closing instance of {}", identifier, e);
+ LOG.error("Error while closing instance of {}", identifier, e);
}
try {
oldJMXRegistrator.close();
} catch (Exception e) {
- LOGGER.error("Error while closing jmx registrator of {}", identifier, e);
+ LOG.error("Error while closing jmx registrator of {}", identifier, e);
}
try {
osgiRegistration.close();
} catch (Exception e) {
- LOGGER.error("Error while closing osgi registration of {}", identifier, e);
+ LOG.error("Error while closing osgi registration of {}", identifier, e);
}
}
*/
package org.opendaylight.controller.config.manager.impl.dependencyresolver;
+import javax.annotation.Nullable;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.manager.impl.ModuleInternalInfo;
import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
import org.opendaylight.controller.config.spi.Module;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.opendaylight.yangtools.concepts.Identifiable;
-
-import javax.annotation.Nullable;
import org.osgi.framework.BundleContext;
public class ModuleInternalTransactionalInfo implements Identifiable<ModuleIdentifier> {
*/
package org.opendaylight.controller.config.manager.impl.dependencyresolver;
-import org.opendaylight.controller.config.api.JmxAttribute;
-import org.opendaylight.controller.config.api.JmxAttributeValidationException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.manager.impl.CommitInfo;
-import org.opendaylight.controller.config.manager.impl.TransactionIdentifier;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-
-import javax.annotation.concurrent.GuardedBy;
-import javax.management.InstanceAlreadyExistsException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import javax.annotation.concurrent.GuardedBy;
+import javax.management.InstanceAlreadyExistsException;
+import org.opendaylight.controller.config.api.JmxAttribute;
+import org.opendaylight.controller.config.api.JmxAttributeValidationException;
+import org.opendaylight.controller.config.api.ModuleIdentifier;
+import org.opendaylight.controller.config.manager.impl.CommitInfo;
+import org.opendaylight.controller.config.manager.impl.TransactionIdentifier;
+import org.opendaylight.controller.config.spi.Module;
+import org.opendaylight.controller.config.spi.ModuleFactory;
/**
* Represents modules to be committed.
*/
package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.api.annotations.RequireInterface;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.util.InterfacesHelper;
-import org.opendaylight.controller.config.spi.Module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static java.lang.String.format;
+import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;
-import java.lang.reflect.Array;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import org.opendaylight.controller.config.api.ModuleIdentifier;
+import org.opendaylight.controller.config.api.annotations.Description;
+import org.opendaylight.controller.config.api.annotations.RequireInterface;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.config.manager.impl.util.InterfacesHelper;
+import org.opendaylight.controller.config.spi.Module;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import static java.lang.String.format;
* a read only wrapper.
*/
abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
- private static final Logger LOGGER = LoggerFactory
- .getLogger(AbstractDynamicWrapper.class);
+ private static final class ModuleNotificationListener implements NotificationListener {
+ private final ObjectName objectNameInternal;
+ private final MBeanServer internalServer;
+ private final ObjectName thisWrapperObjectName;
+ private final MBeanServer configMBeanServer;
+
+ private ModuleNotificationListener(final ObjectName objectNameInternal, final MBeanServer internalServer,
+ final ObjectName thisWrapperObjectName, final MBeanServer configMBeanServer) {
+ this.objectNameInternal = objectNameInternal;
+ this.internalServer = internalServer;
+ this.thisWrapperObjectName = thisWrapperObjectName;
+ this.configMBeanServer = configMBeanServer;
+ }
+ @Override
+ public void handleNotification(final Notification n, final Object handback) {
+ if (n instanceof MBeanServerNotification
+ && n.getType()
+ .equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
+ if (((MBeanServerNotification) n).getMBeanName().equals(
+ thisWrapperObjectName)) {
+ try {
+ internalServer.unregisterMBean(objectNameInternal);
+ configMBeanServer.removeNotificationListener(
+ MBeanServerDelegate.DELEGATE_NAME, this);
+ } catch (MBeanRegistrationException
+ | ListenerNotFoundException
+ | InstanceNotFoundException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ }
+ }
+ }
+
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractDynamicWrapper.class);
protected final boolean writable;
protected final Module module;
protected final ModuleIdentifier moduleIdentifier;
protected final MBeanServer internalServer;
- public AbstractDynamicWrapper(Module module, boolean writable,
- ModuleIdentifier moduleIdentifier,
- ObjectName thisWrapperObjectName, MBeanOperationInfo[] dOperations,
- MBeanServer internalServer, MBeanServer configMBeanServer) {
+ public AbstractDynamicWrapper(final Module module, final boolean writable,
+ final ModuleIdentifier moduleIdentifier,
+ final ObjectName thisWrapperObjectName, final MBeanOperationInfo[] dOperations,
+ final MBeanServer internalServer, final MBeanServer configMBeanServer) {
this.writable = writable;
this.module = module;
* platform mbean server. Wait until this wrapper gets unregistered, in that
* case unregister the module and remove listener.
*/
- private final NotificationListener registerActualModule(Module module,
+ private final NotificationListener registerActualModule(final Module module,
final ObjectName thisWrapperObjectName,
final ObjectName objectNameInternal,
final MBeanServer internalServer,
"Error occured during mbean registration with name " + objectNameInternal, e);
}
- NotificationListener listener = new NotificationListener() {
- @Override
- public void handleNotification(Notification n, Object handback) {
- if (n instanceof MBeanServerNotification
- && n.getType()
- .equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
- if (((MBeanServerNotification) n).getMBeanName().equals(
- thisWrapperObjectName)) {
- try {
- internalServer.unregisterMBean(objectNameInternal);
- configMBeanServer.removeNotificationListener(
- MBeanServerDelegate.DELEGATE_NAME, this);
- } catch (MBeanRegistrationException
- | ListenerNotFoundException
- | InstanceNotFoundException e) {
- throw new IllegalStateException(e);
- }
- }
- }
- }
- };
+ NotificationListener listener = new ModuleNotificationListener(objectNameInternal, internalServer, thisWrapperObjectName, configMBeanServer);
try {
configMBeanServer.addNotificationListener(
MBeanServerDelegate.DELEGATE_NAME, listener, null, null);
return listener;
}
- private static MBeanInfo generateMBeanInfo(String className, Module module,
- Map<String, AttributeHolder> attributeHolderMap,
- MBeanOperationInfo[] dOperations, Set<Class<?>> jmxInterfaces) {
+ private static MBeanInfo generateMBeanInfo(final String className, final Module module,
+ final Map<String, AttributeHolder> attributeHolderMap,
+ final MBeanOperationInfo[] dOperations, final Set<Class<?>> jmxInterfaces) {
String dDescription = findDescription(module.getClass(), jmxInterfaces);
MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[0];
dOperations, new MBeanNotificationInfo[0]);
}
- static String findDescription(Class<?> clazz, Set<Class<?>> jmxInterfaces) {
+ static String findDescription(final Class<?> clazz, final Set<Class<?>> jmxInterfaces) {
List<Description> descriptions = AnnotationsHelper
.findClassAnnotationInSuperClassesAndIfcs(clazz, Description.class, jmxInterfaces);
return AnnotationsHelper.aggregateDescriptions(descriptions);
// inspect all exported interfaces ending with MXBean, extract getters &
// setters into attribute holder
- private static Map<String, AttributeHolder> buildMBeanInfo(Module module,
- boolean writable, ModuleIdentifier moduleIdentifier,
- Set<Class<?>> jmxInterfaces, MBeanServer internalServer,
- ObjectName internalObjectName) {
+ private static Map<String, AttributeHolder> buildMBeanInfo(final Module module,
+ final boolean writable, final ModuleIdentifier moduleIdentifier,
+ final Set<Class<?>> jmxInterfaces, final MBeanServer internalServer,
+ final ObjectName internalObjectName) {
// internal variables for describing MBean elements
Set<Method> methods = new HashSet<>();
}
AttributeHolder attributeHolder = new AttributeHolder(
attribName, module, attributeMap.get(attribName)
- .getType(), writable, ifc, description);
+ .getType(), writable, ifc, description);
attributeHolderMap.put(attribName, attributeHolder);
}
}
}
@Override
- public Object getAttribute(String attributeName)
+ public Object getAttribute(final String attributeName)
throws AttributeNotFoundException, MBeanException,
ReflectionException {
if ("MBeanInfo".equals(attributeName)) {
return obj;
}
- private Object fixDependencyListAttribute(Object attribute) {
+ private Object fixDependencyListAttribute(final Object attribute) {
if (attribute.getClass().isArray() == false) {
throw new IllegalArgumentException("Unexpected attribute type, should be an array, but was " + attribute.getClass());
}
return attribute;
}
- private boolean isDependencyListAttr(String attributeName, Object attribute) {
+ private boolean isDependencyListAttr(final String attributeName, final Object attribute) {
if (attributeHolderMap.containsKey(attributeName) == false) {
return false;
}
return isDepList;
}
- protected ObjectName fixObjectName(ObjectName on) {
+ protected ObjectName fixObjectName(final ObjectName on) {
if (!ObjectNameUtil.ON_DOMAIN.equals(on.getDomain())) {
throw new IllegalArgumentException("Wrong domain, expected "
+ ObjectNameUtil.ON_DOMAIN + " setter on " + on);
}
@Override
- public AttributeList getAttributes(String[] attributes) {
+ public AttributeList getAttributes(final String[] attributes) {
AttributeList result = new AttributeList();
for (String attributeName : attributes) {
try {
result.add(new Attribute(attributeName, value));
} catch (Exception e) {
- LOGGER.debug("Getting attribute {} failed", attributeName, e);
+ LOG.debug("Getting attribute {} failed", attributeName, e);
}
}
return result;
}
@Override
- public Object invoke(String actionName, Object[] params, String[] signature)
+ public Object invoke(final String actionName, final Object[] params, final String[] signature)
throws MBeanException, ReflectionException {
if ("getAttribute".equals(actionName) && params.length == 1
&& signature[0].equals(String.class.getName())) {
&& signature[0].equals(AttributeList.class.getName())) {
return setAttributes((AttributeList) params[0]);
} else {
- LOGGER.debug("Operation not found {} ", actionName);
+ LOG.debug("Operation not found {} ", actionName);
throw new UnsupportedOperationException(
format("Operation not found on %s. Method invoke is only supported for getInstance and getAttribute(s) "
+ "method, got actionName %s, params %s, signature %s ",
}
@Override
- public final boolean equals(Object other) {
+ public final boolean equals(final Object other) {
return module.equals(other);
}
*/
package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-import org.opendaylight.controller.config.api.annotations.Description;
-
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
+import org.opendaylight.controller.config.api.annotations.Description;
public class AnnotationsHelper {
*/
package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.api.annotations.RequireInterface;
-
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.Immutable;
-import javax.management.MBeanAttributeInfo;
-import javax.management.ObjectName;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.Immutable;
+import javax.management.MBeanAttributeInfo;
+import javax.management.ObjectName;
+import org.opendaylight.controller.config.api.annotations.Description;
+import org.opendaylight.controller.config.api.annotations.RequireInterface;
@Immutable
class AttributeHolder {
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.ReflectionException;
-
import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
*/
package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.TransactionIdentifier;
-import org.opendaylight.controller.config.spi.Module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
+import java.lang.reflect.Method;
import javax.annotation.concurrent.ThreadSafe;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.ReflectionException;
-import java.lang.reflect.Method;
+import org.opendaylight.controller.config.api.ModuleIdentifier;
+import org.opendaylight.controller.config.api.ValidationException;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.config.manager.impl.TransactionIdentifier;
+import org.opendaylight.controller.config.spi.Module;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Wraps {@link org.opendaylight.controller.config.spi.Module} instance in a
*/
@ThreadSafe
public class DynamicWritableWrapper extends AbstractDynamicWrapper {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(DynamicWritableWrapper.class);
private final ReadOnlyAtomicBoolean configBeanModificationDisabled;
setAttribute(attribute);
result.add(attribute);
} catch (Exception e) {
- LOGGER.warn("Setting attribute {} failed on {}", attribute.getName(), moduleIdentifier, e);
+ LOG.warn("Setting attribute {} failed on {}", attribute.getName(), moduleIdentifier, e);
throw new IllegalArgumentException(
"Setting attribute failed - " + attribute.getName()
+ " on " + moduleIdentifier, e);
*/
package org.opendaylight.controller.config.manager.impl.factoriesresolver;
+import java.util.Map;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-import java.util.Map;
-
/**
* {@link org.opendaylight.controller.config.manager.impl.ConfigTransactionControllerImpl}
* receives list of factories using this interface. For testing, this could be
*/
package org.opendaylight.controller.config.manager.impl.jmx;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-
+import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.QueryExp;
-import java.util.Set;
+import org.opendaylight.controller.config.api.ModuleIdentifier;
public class BaseJMXRegistrator implements AutoCloseable, NestableJMXRegistrator {
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
-
import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
import org.opendaylight.controller.config.manager.impl.ConfigRegistryImplMXBean;
import java.util.HashMap;
import java.util.Map;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.api.runtime.HierarchicalRuntimeBeanRegistration;
*/
package org.opendaylight.controller.config.manager.impl.jmx;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
+import java.io.Closeable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import javax.annotation.concurrent.GuardedBy;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.QueryExp;
-import java.io.Closeable;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class InternalJMXRegistrator implements Closeable {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(InternalJMXRegistrator.class);
private final MBeanServer configMBeanServer;
try {
configMBeanServer.unregisterMBean(on);
} catch (Exception e) {
- LOGGER.warn("Ignoring error while unregistering {}", on, e);
+ LOG.warn("Ignoring error while unregistering {}", on, e);
}
}
registeredObjectNames.clear();
package org.opendaylight.controller.config.manager.impl.jmx;
import java.io.Closeable;
-
import javax.annotation.concurrent.ThreadSafe;
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator.InternalJMXRegistration;
package org.opendaylight.controller.config.manager.impl.jmx;
import java.util.Collections;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
*/
package org.opendaylight.controller.config.manager.impl.jmx;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator.InternalJMXRegistration;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator.InternalJMXRegistration;
public interface ServiceReferenceRegistrator extends AutoCloseable {
*/
package org.opendaylight.controller.config.manager.impl.jmx;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator.InternalJMXRegistration;
-
+import java.io.Closeable;
+import java.util.Set;
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
import javax.management.QueryExp;
-import java.io.Closeable;
-import java.util.Set;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator.InternalJMXRegistration;
/**
* Contains constraints on passed {@link ObjectName} parameters. Only allow (un)
import java.io.Closeable;
import java.util.Set;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
import javax.management.QueryExp;
-
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator.InternalJMXRegistration;
public static class OsgiRegistration implements AutoCloseable {
- private static final Logger LOGGER = LoggerFactory.getLogger(OsgiRegistration.class);
+ private static final Logger LOG = LoggerFactory.getLogger(OsgiRegistration.class);
@GuardedBy("this")
private AutoCloseable instance;
try {
serviceRegistration.unregister();
} catch(IllegalStateException e) {
- LOGGER.trace("Cannot unregister {}", serviceRegistration, e);
+ LOG.trace("Cannot unregister {}", serviceRegistration, e);
}
}
serviceRegistrations.clear();
notEquals |= newAnnotationMapping.equals(serviceNamesToAnnotations) == false;
if (notEquals) {
// FIXME: changing from old state to new state can be improved by computing the diff
- LOGGER.debug("Detected change in service registrations for {}: old: {}, new: {}", moduleIdentifier,
+ LOG.debug("Detected change in service registrations for {}: old: {}, new: {}", moduleIdentifier,
serviceNamesToAnnotations, newAnnotationMapping);
close();
this.instance = newInstance;
* functionality.
*/
public class BlankTransactionServiceTracker implements ServiceTrackerCustomizer<ModuleFactory, Object> {
- private static final Logger LOGGER = LoggerFactory.getLogger(BlankTransactionServiceTracker.class);
+ private static final Logger LOG = LoggerFactory.getLogger(BlankTransactionServiceTracker.class);
public static final int DEFAULT_MAX_ATTEMPTS = 10;
try {
// create transaction
CommitStatus commitStatus = blankTransaction.hit();
- LOGGER.debug("Committed blank transaction with status {}", commitStatus);
+ LOG.debug("Committed blank transaction with status {}", commitStatus);
return;
} catch (ConflictingVersionException e) {
lastException = e;
throw new IllegalStateException(interruptedException);
}
} catch (ValidationException e) {
- LOGGER.error("Validation exception while running blank transaction indicates programming error", e);
+ LOG.error("Validation exception while running blank transaction indicates programming error", e);
throw new RuntimeException("Validation exception while running blank transaction indicates programming error", e);
}
}
*/
package org.opendaylight.controller.config.manager.impl.osgi;
+import java.util.AbstractMap;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.AbstractMap;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
/**
* Retrieves list of currently registered Module Factories using bundlecontext.
*/
public class BundleContextBackedModuleFactoriesResolver implements
ModuleFactoriesResolver {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(BundleContextBackedModuleFactoriesResolver.class);
private final BundleContext bundleContext;
if (serviceReference.getBundle() == null || serviceReference.getBundle().getBundleContext() == null) {
throw new NullPointerException("Bundle context of " + factory + " ModuleFactory not found.");
}
- LOGGER.debug("Reading factory {} {}", moduleName, factory);
+ LOG.debug("Reading factory {} {}", moduleName, factory);
Map.Entry<ModuleFactory, BundleContext> conflicting = result.get(moduleName);
if (conflicting != null) {
String error = String
.format("Module name is not unique. Found two conflicting factories with same name '%s': '%s' '%s'",
moduleName, conflicting.getKey(), factory);
- LOGGER.error(error);
+ LOG.error(error);
throw new IllegalArgumentException(error);
} else {
result.put(moduleName, new AbstractMap.SimpleImmutableEntry<>(factory,
LOG.trace("AddingBundle for {} and event {} finished successfully",bundle,event);
return primaryTrackerRetVal;
} catch (Exception e) {
- LOG.error("Failed to add bundle {}",e);
+ LOG.error("Failed to add bundle ",e);
throw e;
}
}
import java.io.InputStream;
import java.net.URL;
import java.util.List;
-
import org.apache.commons.io.IOUtils;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.Bundle;
*/
public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Object> {
private final BlankTransactionServiceTracker blankTransactionServiceTracker;
- private static final Logger LOGGER = LoggerFactory.getLogger(ModuleFactoryBundleTracker.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ModuleFactoryBundleTracker.class);
public ModuleFactoryBundleTracker(BlankTransactionServiceTracker blankTransactionServiceTracker) {
this.blankTransactionServiceTracker = blankTransactionServiceTracker;
@Override
public Object addingBundle(Bundle bundle, BundleEvent event) {
URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
- LOGGER.trace("Got addingBundle event of bundle {}, resource {}, event {}",
+ LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}",
bundle, resource, event);
if (resource != null) {
try (InputStream inputStream = resource.openStream()) {
registerFactory(factoryClassName, bundle);
}
} catch (Exception e) {
- LOGGER.error("Error while reading {}", resource, e);
+ LOG.error("Error while reading {}", resource, e);
throw new RuntimeException(e);
}
}
Class<?> clazz = bundle.loadClass(factoryClassName);
if (ModuleFactory.class.isAssignableFrom(clazz)) {
try {
- LOGGER.debug("Registering {} in bundle {}",
+ LOG.debug("Registering {} in bundle {}",
clazz.getName(), bundle);
return bundle.getBundleContext().registerService(
ModuleFactory.class.getName(), clazz.newInstance(),
}
public static String logMessage(String slfMessage, Object... params) {
- LOGGER.info(slfMessage, params);
+ LOG.info(slfMessage, params);
String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
return format(formatMessage, params);
}
package org.opendaylight.controller.config.manager.impl.osgi.mapping;
import javassist.ClassPool;
-
import org.opendaylight.controller.config.manager.impl.util.OsgiRegistrationUtil;
import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
-
import org.apache.commons.io.IOUtils;
import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.sal.binding.generator.api.ModuleInfoRegistry;
*/
public final class ModuleInfoBundleTracker implements BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
- private static final Logger LOGGER = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
public static final String MODULE_INFO_PROVIDER_PATH_PREFIX = "META-INF/services/";
@Override
public Collection<ObjectRegistration<YangModuleInfo>> addingBundle(Bundle bundle, BundleEvent event) {
URL resource = bundle.getEntry(MODULE_INFO_PROVIDER_PATH_PREFIX + YangModelBindingProvider.class.getName());
- LOGGER.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
+ LOG.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
if(resource==null) {
return null;
}
try (InputStream inputStream = resource.openStream()) {
List<String> lines = IOUtils.readLines(inputStream);
for (String moduleInfoName : lines) {
- LOGGER.trace("Retrieve ModuleInfo({}, {})", moduleInfoName, bundle);
+ LOG.trace("Retrieve ModuleInfo({}, {})", moduleInfoName, bundle);
YangModuleInfo moduleInfo = retrieveModuleInfo(moduleInfoName, bundle);
registrations.add(moduleInfoRegistry.registerModuleInfo(moduleInfo));
}
} catch (Exception e) {
- LOGGER.error("Error while reading {}", resource, e);
+ LOG.error("Error while reading {}", resource, e);
throw new RuntimeException(e);
}
- LOGGER.trace("Got following registrations {}", registrations);
+ LOG.trace("Got following registrations {}", registrations);
return registrations;
}
} catch (NoClassDefFoundError e) {
- LOGGER.error("Error while executing getModuleInfo on {}", instance, e);
+ LOG.error("Error while executing getModuleInfo on {}", instance, e);
throw e;
}
}
}
public static String logMessage(String slfMessage, Object... params) {
- LOGGER.info(slfMessage, params);
+ LOG.info(slfMessage, params);
String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
return format(formatMessage, params);
}
package org.opendaylight.controller.config.manager.impl.osgi.mapping;
+import java.util.Hashtable;
import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.sal.binding.generator.api.ModuleInfoRegistry;
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
-import java.util.Hashtable;
-
/**
* Update SchemaContext service in Service Registry each time new YangModuleInfo is added or removed.
*/
package org.opendaylight.controller.config.manager.impl.util;
import java.util.Set;
-
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.LookupRegistry;
public class LookupBeansUtil {
*/
package org.opendaylight.controller.config.manager.impl.util;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.osgi.framework.BundleContext;
-
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import org.opendaylight.controller.config.spi.ModuleFactory;
+import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.osgi.framework.BundleContext;
public class ModuleQNameUtil {
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;
import org.slf4j.LoggerFactory;
public class OsgiRegistrationUtil {
- private static final Logger LOGGER = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
+ private static final Logger LOG = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
private OsgiRegistrationUtil() {
}
try {
ac.close();
} catch (Exception e) {
- LOGGER.warn("Exception while closing {}", ac, e);
+ LOG.warn("Exception while closing {}", ac, e);
if (firstException == null) {
firstException = e;
} else {
*/
package org.opendaylight.controller.config.manager;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyZeroInteractions;
+
+import java.lang.management.ManagementFactory;
import org.junit.Test;
import org.opendaylight.controller.config.manager.impl.AbstractLockedPlatformMBeanServerTest;
import org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.management.ManagementFactory;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verifyZeroInteractions;
-
public class ConfigRegistryImplTest extends
AbstractLockedPlatformMBeanServerTest {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(ConfigRegistryImplTest.class);
@Test
configRegistry.close();
} catch (Exception e) {
// ignore
- logger.warn("Ignoring exception", e);
+ LOG.warn("Ignoring exception", e);
}
}
}
*/
package org.opendaylight.controller.config.manager.impl;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.mock;
+
import com.google.common.base.Preconditions;
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.Dictionary;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.management.RuntimeMBeanException;
import org.junit.After;
import org.junit.Before;
import org.mockito.Matchers;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.management.RuntimeMBeanException;
-import java.lang.management.ManagementFactory;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.Dictionary;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
-
/**
* Each test that relies on
* {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
public static interface BundleContextServiceRegistrationHandler {
- void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
+ void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
}
Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
innerObject.getClass().getInterfaces(), new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- try {
- return method.invoke(innerObject, args);
- } catch (InvocationTargetException e) {
- try {
- throw e.getTargetException();
- } catch (RuntimeMBeanException e2) {
- throw e2.getTargetException();
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ try {
+ return method.invoke(innerObject, args);
+ } catch (InvocationTargetException e) {
+ try {
+ throw e.getTargetException();
+ } catch (RuntimeMBeanException e2) {
+ throw e2.getTargetException();
+ }
+ }
+ }
}
- }
- }
- });
+ );
return (T) proxy;
}
import java.lang.management.ManagementFactory;
import java.util.concurrent.locks.ReentrantLock;
-
import javax.management.MBeanServer;
-
import org.junit.After;
import org.junit.Before;
package org.opendaylight.controller.config.manager.impl;
import com.google.common.base.Preconditions;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+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.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
/**
* Creates new modules by reflection. Provided class must have this constructor:
* ctor(DynamicMBeanWithInstance.class, ModuleIdentifier.class).
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
+import com.google.common.collect.Sets;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
import org.opendaylight.controller.config.manager.impl.runtimembean.TestingRuntimeBean;
-import com.google.common.collect.Sets;
-
public class ConfigRegistryImplLookupTest extends
AbstractLockedPlatformMBeanServerTest {
*/
package org.opendaylight.controller.config.manager.impl;
+import static org.junit.Assert.assertEquals;
+
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.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.ObjectName;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import java.lang.management.ManagementFactory;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-
public class ConfigTransactionControllerImplTest extends
AbstractLockedPlatformMBeanServerTest {
*/
package org.opendaylight.controller.config.manager.impl;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+
+import javax.management.InstanceAlreadyExistsException;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import javax.management.InstanceAlreadyExistsException;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
-
public class ConfigTransactionManagerImplTest extends
AbstractConfigTest {
*/
package org.opendaylight.controller.config.manager.impl;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.config.api.jmx.ObjectNameUtil.withoutTransactionName;
+
import com.google.common.collect.ImmutableMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.management.Attribute;
+import javax.management.AttributeNotFoundException;
+import javax.management.InstanceNotFoundException;
+import javax.management.JMX;
+import javax.management.MBeanException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
import org.opendaylight.controller.config.manager.impl.AbstractConfigTest.RecordingBundleContextServiceRegistrationHandler.RegistrationHolder;
import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
import org.opendaylight.controller.config.manager.testingservices.parallelapsp.test.AbstractParallelAPSPTest;
import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import javax.management.Attribute;
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceNotFoundException;
-import javax.management.JMX;
-import javax.management.MBeanException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.config.api.jmx.ObjectNameUtil.withoutTransactionName;
-
public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest {
boolean isDefaultBean = false;
tested.put(moduleIdentifier,
- mockedModule(),
- moduleFactory,
- maybeOldInternalInfo,
- transactionModuleJMXRegistration,
- isDefaultBean, mock(BundleContext.class));
+ mockedModule(),
+ moduleFactory,
+ maybeOldInternalInfo,
+ transactionModuleJMXRegistration,
+ isDefaultBean, mock(BundleContext.class));
}
private static Module mockedModule() {
*/
package org.opendaylight.controller.config.manager.impl.dynamicmbean;
+import static org.junit.Assert.assertEquals;
+
+import java.lang.management.ManagementFactory;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.DynamicMBean;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
-import java.lang.management.ManagementFactory;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
import org.opendaylight.controller.config.spi.Module;
-import static org.junit.Assert.assertEquals;
-
public abstract class AbstractDynamicWrapperTest extends
AbstractLockedPlatformMBeanServerTest {
protected final MBeanServer platformMBeanServer = ManagementFactory
proxy.getAttribute(TRIGGER_NEW_INSTANCE_CREATION));
AttributeList attributes = proxy.getAttributes(new String[] {
- THREAD_COUNT, TRIGGER_NEW_INSTANCE_CREATION });
+ THREAD_COUNT, TRIGGER_NEW_INSTANCE_CREATION });
assertEquals(2, attributes.size());
Attribute threadCountAttr = (Attribute) attributes.get(0);
assertEquals(THREAD_COUNT, threadCountAttr.getName());
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import com.google.common.base.Throwables;
+import com.google.common.collect.Sets;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
-
import javax.management.ObjectName;
-
import org.junit.Test;
import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
import org.opendaylight.controller.config.api.annotations.Description;
import org.opendaylight.controller.config.api.annotations.RequireInterface;
import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import com.google.common.base.Throwables;
-import com.google.common.collect.Sets;
-
public class AnnotationsTest {
private final String setSomethingString = "setSomething";
package org.opendaylight.controller.config.manager.impl.dynamicmbean;
import java.lang.management.ManagementFactory;
-
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.spi.Module;
*/
package org.opendaylight.controller.config.manager.impl.dynamicmbean;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import javax.management.Attribute;
+import javax.management.AttributeList;
+import javax.management.DynamicMBean;
+import javax.management.JMX;
+import javax.management.MBeanServerFactory;
+import javax.management.ObjectName;
import org.junit.Test;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolConfigMXBean;
import org.opendaylight.controller.config.spi.Module;
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.DynamicMBean;
-import javax.management.JMX;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest {
private final int newThreadCount = 10;
private final AtomicBoolean atomicBoolean = new AtomicBoolean();
*/
package org.opendaylight.controller.config.manager.impl.factoriesresolver;
-import org.mockito.Matchers;
-import org.mockito.Mockito;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import java.io.Closeable;
+import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Dictionary;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.HashMap;
-import java.util.AbstractMap;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import org.opendaylight.controller.config.spi.ModuleFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceRegistration;
public class HardcodedModuleFactoriesResolver implements ModuleFactoriesResolver {
private Map<String, Map.Entry<ModuleFactory, BundleContext>> factories;
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;
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;
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 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
+
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
-
import java.lang.management.ManagementFactory;
import java.util.Map;
-
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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;
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;
package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
@ServiceInterfaceAnnotation(value = TestingParallelAPSPConfigMXBean.NAME, osgiRegistrationType = TestingAPSP.class,
import static com.google.common.base.Preconditions.checkArgument;
+import com.google.common.base.Strings;
import java.io.Closeable;
import java.io.IOException;
-
import javax.annotation.concurrent.NotThreadSafe;
-
import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-import com.google.common.base.Strings;
-
@NotThreadSafe
public class TestingParallelAPSPImpl implements TestingAPSP, Closeable {
public static final int MINIMAL_NUMBER_OF_THREADS = 10;
@NotThreadSafe
public class TestingParallelAPSPModule implements Module,
TestingParallelAPSPConfigMXBean {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(TestingParallelAPSPModule.class);
private final DependencyResolver dependencyResolver;
// changing thread pool is not supported
boolean reuse = threadPoolInstance == oldInstance.getThreadPool();
if (reuse) {
- logger.debug("Reusing old instance");
+ LOG.debug("Reusing old instance");
instance = oldInstance;
instance.setSomeParam(someParam);
}
}
if (instance == null) {
- logger.debug("Creating new instance");
+ LOG.debug("Creating new instance");
if (oldCloseable != null) {
try {
oldCloseable.close();
*/
package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import javax.annotation.concurrent.ThreadSafe;
+import javax.management.ObjectName;
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 javax.annotation.concurrent.ThreadSafe;
-import javax.management.ObjectName;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
@ThreadSafe
public class TestingParallelAPSPModuleFactory implements ModuleFactory {
*/
package org.opendaylight.controller.config.manager.testingservices.parallelapsp.test;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.ObjectName;
import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
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.threadpool.TestingFixedThreadPoolConfigMXBean;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-
public abstract class AbstractParallelAPSPTest extends AbstractConfigTest {
protected final String fixed1 = "fixed1";
protected final String apsp1 = "apsp-parallel";
import static org.junit.Assert.fail;
import java.util.Map;
-
import javax.management.ObjectName;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public void testUsingServiceReferences() throws Exception {
ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
ObjectName threadPoolON = createFixed1(transaction, 10);
- transaction.lookupConfigBean(getThreadPoolImplementationName(), fixed1);
+ transaction.lookupConfigBean(getThreadPoolImplementationName(), fixed1);
String refName = "ref";
ObjectName serviceReferenceON = transaction.saveServiceReference(TestingThreadPoolServiceInterface.QNAME, refName,
threadPoolON);
*/
package org.opendaylight.controller.config.manager.testingservices.parallelapsp.test;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.concurrent.Executor;
+import javax.management.ObjectName;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.opendaylight.controller.config.spi.Module;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import javax.management.ObjectName;
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.concurrent.Executor;
-
public class MockedDependenciesTest extends AbstractParallelAPSPTest {
private final String threadPoolImplementationName = "mockedthreadpool";
*/
package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
+import com.google.common.collect.Lists;
import java.io.Closeable;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
-
import org.opendaylight.controller.config.api.runtime.HierarchicalRuntimeBeanRegistration;
import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.runtimebeans
- .TestingScheduledRuntimeBean;
+import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.runtimebeans.TestingScheduledRuntimeBean;
import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-import com.google.common.collect.Lists;
-
public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc,
TestingScheduledThreadPoolIfc, Closeable {
private static volatile int numberOfCloseMethodCalls = 0;
import static org.junit.Assert.assertNull;
import java.io.Closeable;
-
import javax.annotation.Nullable;
-
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
*/
package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.test;
+import static org.junit.Assert.assertEquals;
+
import org.junit.After;
import org.junit.Before;
import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
-import static org.junit.Assert.assertEquals;
-
public abstract class AbstractScheduledTest extends AbstractConfigTest {
protected static final String scheduled1 = "scheduled1";
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
import java.util.Collections;
import java.util.List;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-
import org.junit.Test;
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool
- .TestingScheduledThreadPoolConfigBeanMXBean;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool
- .TestingScheduledThreadPoolModuleFactory;
+import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolConfigBeanMXBean;
+import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
/**
* TestingScheduledThreadPool exports 2 interfaces: <br>
* {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME}
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+
import javax.annotation.Nullable;
import javax.management.DynamicMBean;
import javax.management.InstanceAlreadyExistsException;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.common.collect.Lists;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
-import com.google.common.collect.Lists;
-
public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable,
TestingModifiableThreadPoolIfc {
private final ThreadPoolExecutor executorService;
import static com.google.common.base.Preconditions.checkState;
import java.io.Closeable;
-
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
-
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.manager.testingservices.seviceinterface.ModifiableThreadPoolServiceInterface;
import org.opendaylight.controller.config.spi.Module;
*/
package org.opendaylight.controller.config.manager.testingservices.threadpool.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
import com.google.common.collect.Sets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ThreadPoolExecutor;
+import javax.management.DynamicMBean;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import javax.management.DynamicMBean;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ThreadPoolExecutor;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
/**
* Tests basic functionality of configuration registry:
* <ol>
package org.opendaylight.controller.config.persist.storage.directory.xml;
import static com.google.common.base.Preconditions.checkArgument;
+
import com.google.common.base.Optional;
import com.google.common.io.Files;
import java.io.File;
} catch (JAXBException e) {
// In case of parse error, issue a warning, ignore and continue
LOG.warn(
- "Unable to parse configuration snapshot from {}. Initial config from {} will be IGNORED in this run. " +
- "Note that subsequent config files may fail due to this problem. " +
+ "Unable to parse configuration snapshot from {}. Initial config from {} will be IGNORED in this run. ",
+ file, file);
+ LOG.warn(
+ "Note that subsequent config files may fail due to this problem. ",
"Xml markup in this file needs to be fixed, for detailed information see enclosed exception.",
- file, file, e);
+ e);
}
return Optional.absent();
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+
import com.google.common.base.Optional;
import java.io.File;
import java.io.IOException;
*/
package org.opendaylight.controller.configpusherfeature.internal;
+import com.google.common.base.Preconditions;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
-
import javax.xml.bind.JAXBException;
-
import org.apache.karaf.features.BundleInfo;
import org.apache.karaf.features.Conditional;
import org.apache.karaf.features.ConfigFileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Preconditions;
-
/*
* Wrap a Feature for the purposes of extracting the FeatureConfigSnapshotHolders from
* its underlying ConfigFileInfo's
* Delegates the the contained feature and provides additional methods.
*/
public class AbstractFeatureWrapper implements Feature {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFeatureWrapper.class);
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractFeatureWrapper.class);
protected Feature feature = null;
protected AbstractFeatureWrapper() {
try {
snapShotHolders.add(new FeatureConfigSnapshotHolder(c,this));
} catch (JAXBException e) {
- LOGGER.debug("{} is not a config subsystem config file",c.getFinalname());
+ LOG.debug("{} is not a config subsystem config file",c.getFinalname());
}
}
return snapShotHolders;
*/
package org.opendaylight.controller.configpusherfeature.internal;
+import com.google.common.base.Preconditions;
import java.util.LinkedHashSet;
import java.util.List;
-
import javax.xml.bind.JAXBException;
-
import org.apache.felix.utils.version.VersionRange;
import org.apache.felix.utils.version.VersionTable;
import org.apache.karaf.features.Dependency;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Preconditions;
-
/*
* Wrap a Feature for the purposes of extracting the FeatureConfigSnapshotHolders from
* its underlying ConfigFileInfo's and those of its children recursively
* Delegates the the contained feature and provides additional methods.
*/
public class ChildAwareFeatureWrapper extends AbstractFeatureWrapper implements Feature {
- private static final Logger LOGGER = LoggerFactory.getLogger(ChildAwareFeatureWrapper.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ChildAwareFeatureWrapper.class);
private FeaturesService featuresService= null;
protected ChildAwareFeatureWrapper(Feature f) {
f = new FeatureConfigSnapshotHolder(h,this);
snapShotHolders.add(f);
} catch (JAXBException e) {
- LOGGER.debug("{} is not a config subsystem config file",h.getFileInfo().getFinalname());
+ LOG.debug("{} is not a config subsystem config file",h.getFileInfo().getFinalname());
}
}
}
Version v = VersionTable.getVersion(f.getVersion());
if (range.contains(v) &&
(fi == null || VersionTable.getVersion(fi.getVersion()).compareTo(v) < 0)) {
- fi = f;
- break;
+ fi = f;
+ break;
}
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
-
import org.apache.karaf.features.FeatureEvent;
import org.apache.karaf.features.FeaturesListener;
import org.apache.karaf.features.FeaturesService;
import org.slf4j.LoggerFactory;
public class ConfigFeaturesListener implements FeaturesListener, AutoCloseable {
- private static final Logger LOGGER = LoggerFactory.getLogger(ConfigFeaturesListener.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigFeaturesListener.class);
private static final int QUEUE_SIZE = 1000;
private BlockingQueue<FeatureEvent> queue = new LinkedBlockingQueue<FeatureEvent>(QUEUE_SIZE);
Thread pushingThread = null;
@Override
public void repositoryEvent(RepositoryEvent event) {
- LOGGER.debug("Repository: " + event.getType() + " " + event.getRepository());
+ LOG.debug("Repository: {} {}", event.getType(), event.getRepository());
}
@Override
*/
package org.opendaylight.controller.configpusherfeature.internal;
+import com.google.common.collect.LinkedHashMultimap;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
-
import org.apache.karaf.features.Feature;
import org.apache.karaf.features.FeatureEvent;
import org.apache.karaf.features.FeatureEvent.EventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.collect.LinkedHashMultimap;
-
public class ConfigPushingRunnable implements Runnable {
- private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPushingRunnable.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigPushingRunnable.class);
private static final int POLL_TIME = 1;
private BlockingQueue<FeatureEvent> queue;
private FeatureConfigPusher configPusher;
processFeatureEvent(event,toInstall);
}
} else if(toInstall.isEmpty()) {
- LOGGER.error("ConfigPushingRunnable - exiting");
+ LOG.error("ConfigPushingRunnable - exiting");
return;
}
} catch (InterruptedException e) {
- LOGGER.error("ConfigPushingRunnable - interupted");
+ LOG.error("ConfigPushingRunnable - interupted");
interuppted = true;
} catch (Exception e) {
- LOGGER.error("Exception while processing features {}", e);
+ LOG.error("Exception while processing features ", e);
}
}
}
protected void logPushResult(LinkedHashMultimap<Feature,FeatureConfigSnapshotHolder> results) {
for(Feature f:results.keySet()) {
- LOGGER.info("Pushed configs for feature {} {}",f,results.get(f));
+ LOG.info("Pushed configs for feature {} {}",f,results.get(f));
}
}
}
*/
package org.opendaylight.controller.configpusherfeature.internal;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
-
import org.apache.karaf.features.ConfigFileInfo;
import org.apache.karaf.features.Feature;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
/*
* A ConfigSnapshotHolder that can track all the additional information
* relavent to the fact we are getting these from a Feature.
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.SortedSet;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
import org.opendaylight.controller.config.persist.api.Persister;
import org.opendaylight.controller.config.persist.api.PropertiesProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.SortedSet;
-
/**
* StorageAdapter that stores configuration in an xml file.
*/
public class XmlFileStorageAdapter implements StorageAdapter, Persister {
- private static final Logger LOGGER = LoggerFactory.getLogger(XmlFileStorageAdapter.class);
+ private static final Logger LOG = LoggerFactory.getLogger(XmlFileStorageAdapter.class);
public static final String FILE_STORAGE_PROP = "fileStorage";
public static final String NUMBER_OF_BACKUPS = "numberOfBackups";
@Override
public Persister instantiate(PropertiesProvider propertiesProvider) {
File storage = extractStorageFileFromProperties(propertiesProvider);
- LOGGER.debug("Using file {}", storage.getAbsolutePath());
+ LOG.debug("Using file {}", storage.getAbsolutePath());
// Create file if it does not exist
File parentFile = storage.getAbsoluteFile().getParentFile();
if (parentFile.exists() == false) {
- LOGGER.debug("Creating parent folders {}", parentFile);
+ LOG.debug("Creating parent folders {}", parentFile);
parentFile.mkdirs();
}
if (storage.exists() == false) {
- LOGGER.debug("Storage file does not exist, creating empty file");
+ LOG.debug("Storage file does not exist, creating empty file");
try {
boolean result = storage.createNewFile();
if (result == false)
} else {
numberOfStoredBackups = Integer.MAX_VALUE;
}
- LOGGER.trace("Property {} set to {}", NUMBER_OF_BACKUPS, numberOfStoredBackups);
+ LOG.trace("Property {} set to {}", NUMBER_OF_BACKUPS, numberOfStoredBackups);
return result;
}
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
-import org.apache.commons.lang3.StringUtils;
-
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
+import org.apache.commons.lang3.StringUtils;
@XmlRootElement(name = "persisted-snapshots")
public final class Config {
*/
package org.opendaylight.controller.config.persist.storage.file.xml.model;
+import java.util.SortedSet;
import java.util.TreeSet;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-import java.util.SortedSet;
+import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
@XmlRootElement(name = ConfigSnapshot.SNAPSHOT_ROOT_ELEMENT_NAME)
public class ConfigSnapshot {
*/
package org.opendaylight.controller.config.persist.storage.file.xml.model;
+import java.io.StringReader;
+import java.io.StringWriter;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
-import java.io.StringReader;
-import java.io.StringWriter;
class SnapshotHandler implements DomHandler<String, StreamResult> {
package org.opendaylight.controller.config.persist.storage.file.xml;
-import static org.junit.Assert.assertFalse;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
+
import com.google.common.base.Charsets;
import java.io.File;
import java.io.FileNotFoundException;
package org.opendaylight.controller.config.util;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
public interface ConfigRegistryClient extends ConfigRegistryMXBean {
*/
package org.opendaylight.controller.config.util;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.JMException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.ReflectionException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import org.opendaylight.controller.config.api.ConflictingVersionException;
+import org.opendaylight.controller.config.api.ValidationException;
+import org.opendaylight.controller.config.api.jmx.CommitStatus;
+import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
public class ConfigRegistryJMXClient implements ConfigRegistryClient {
import javax.management.Attribute;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
import java.util.Map;
import java.util.Set;
-
import javax.management.Attribute;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
+
import com.google.common.collect.Sets;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import com.google.common.collect.Sets;
import java.lang.management.ManagementFactory;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
-
import javax.management.Attribute;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
-
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.opendaylight.controller.config.api.ValidationException.ExceptionMessageWithStackTrace;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import com.google.common.collect.Sets;
-
public class ConfigTransactionClientsTest {
private final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
private TestingConfigTransactionController transactionController;
@Ignore
public void testAssertVersion() {
jmxTransactionClient.assertVersion((int)jmxTransactionClient.getParentVersion(),
- (int)jmxTransactionClient.getVersion());
+ (int)jmxTransactionClient.getVersion());
}
@Test(expected = NullPointerException.class)
*/
package org.opendaylight.controller.config.util;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.Method;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import java.lang.management.ManagementFactory;
-import java.lang.reflect.Method;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
public class LookupTest {
private TestingConfigRegistry testingRegistry;
*/
package org.opendaylight.controller.config.util;
+import com.google.common.collect.Sets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import com.google.common.collect.Sets;
-
public class TestingConfigRegistry implements ConfigRegistryMXBean {
static final ObjectName conf1, conf2, conf3, run1, run2, run3;
*/
package org.opendaylight.controller.config.util;
+import com.google.common.collect.Sets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
-
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import com.google.common.collect.Sets;
-
public class TestingConfigTransactionController implements
ConfigTransactionControllerMXBean {
import java.io.File;
import java.util.List;
-
import org.opendaylight.controller.logback.config.loader.impl.LogbackConfigUtil;
import org.opendaylight.controller.logback.config.loader.impl.LogbackConfigurationLoader;
import org.osgi.framework.BundleActivator;
* logback configurations
*/
private static final String LOGBACK_CONFIG_D = "logback.config.d";
- private static Logger LOG = LoggerFactory.getLogger(Activator.class);
+ private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
@Override
public void start(BundleContext context) {
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*/
package org.opendaylight.controller.logback.config.loader.impl;
+import ch.qos.logback.classic.LoggerContext;
+import ch.qos.logback.classic.joran.JoranConfigurator;
+import ch.qos.logback.core.joran.spi.JoranException;
+import ch.qos.logback.core.util.StatusPrinter;
import java.io.File;
import java.net.URL;
-
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import ch.qos.logback.classic.LoggerContext;
-import ch.qos.logback.classic.joran.JoranConfigurator;
-import ch.qos.logback.core.joran.spi.JoranException;
-import ch.qos.logback.core.util.StatusPrinter;
-
/**
* Logback configuration loader.
* Strategy:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/** logback config root */
private static final String LOGBACK_D = "/logback.d";
- private static Logger LOG = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(LogbackConfigurationLoaderTest.class);
/**
*/
package org.opendaylight.controller.logback.config.loader.test;
-import java.util.ArrayList;
-import java.util.List;
-
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.status.Status;
+import java.util.ArrayList;
+import java.util.List;
/**
* dummy appender for collecting log messages
*/
public class Debugger {
- private static Logger LOG = LoggerFactory.getLogger(Debugger.class);
+ private static final Logger LOG = LoggerFactory.getLogger(Debugger.class);
/**
* all logging
*/
public class Errorer {
- private static Logger LOG = LoggerFactory.getLogger(Errorer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(Errorer.class);
/**
* all logging
*/
public class Informer {
- private static Logger LOG = LoggerFactory.getLogger(Informer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(Informer.class);
/**
* all logging
*/
public class Tracer {
- private static Logger LOG = LoggerFactory.getLogger(Tracer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(Tracer.class);
/**
* all logging
*/
public class Warner {
- private static Logger LOG = LoggerFactory.getLogger(Warner.class);
+ private static final Logger LOG = LoggerFactory.getLogger(Warner.class);
/**
* all logging
executor = MoreExecutors.listeningDecorator(
MoreExecutors.getExitingExecutorService((ThreadPoolExecutor)Executors.newFixedThreadPool(1), 1L, TimeUnit.SECONDS));
- InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", dsExec,
- MoreExecutors.sameThreadExecutor());
- InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", dsExec,
- MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", dsExec);
+ InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", dsExec);
Map<LogicalDatastoreType, DOMStore> datastores = ImmutableMap.of(
LogicalDatastoreType.OPERATIONAL, (DOMStore)operStore,
LogicalDatastoreType.CONFIGURATION, configStore);
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.md.sal.dom.store.benchmark;
-
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
-import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
-import org.openjdk.jmh.annotations.BenchmarkMode;
-import org.openjdk.jmh.annotations.Fork;
-import org.openjdk.jmh.annotations.Level;
-import org.openjdk.jmh.annotations.Mode;
-import org.openjdk.jmh.annotations.OutputTimeUnit;
-import org.openjdk.jmh.annotations.Scope;
-import org.openjdk.jmh.annotations.Setup;
-import org.openjdk.jmh.annotations.State;
-import org.openjdk.jmh.annotations.TearDown;
-
-/**
- * Benchmark for testing of performance of write operations for InMemoryDataStore. The instance
- * of benchmark creates InMemoryDataStore with Data Change Listener Executor Service as BlockingBoundedFastThreadPool
- * and DOM Store Executor Service as Blocking Bounded Fast Thread Pool.
- *
- * @see org.opendaylight.yangtools.util.concurrent.SpecialExecutors
- * @see org.opendaylight.controller.md.sal.dom.store.benchmark.AbstractInMemoryDatastoreWriteTransactionBenchmark
- *
- * @author Lukas Sedlak <lsedlak@cisco.com>
- */
-@State(Scope.Thread)
-@BenchmarkMode(Mode.AverageTime)
-@OutputTimeUnit(TimeUnit.MILLISECONDS)
-@Fork(1)
-public class InMemoryDataStoreWithExecutorServiceBenchmark extends AbstractInMemoryDatastoreWriteTransactionBenchmark {
-
- private static final int MAX_DATA_CHANGE_EXECUTOR_POOL_SIZE = 20;
- private static final int MAX_DATA_CHANGE_EXECUTOR_QUEUE_SIZE = 1000;
- private static final int MAX_DATA_STORE_EXECUTOR_QUEUE_SIZE = 5000;
-
- @Override
- @Setup(Level.Trial)
- public void setUp() throws Exception {
- final String name = "DS_BENCHMARK";
- final ExecutorService dataChangeListenerExecutor = SpecialExecutors.newBlockingBoundedFastThreadPool(
- MAX_DATA_CHANGE_EXECUTOR_POOL_SIZE, MAX_DATA_CHANGE_EXECUTOR_QUEUE_SIZE, name + "-DCL");
-
- final ListeningExecutorService domStoreExecutor = MoreExecutors.listeningDecorator(SpecialExecutors.newBoundedSingleThreadExecutor(
- MAX_DATA_STORE_EXECUTOR_QUEUE_SIZE, "DOMStore-" + name ));
-
- domStore = new InMemoryDOMDataStore(name, domStoreExecutor,
- dataChangeListenerExecutor);
- schemaContext = BenchmarkModel.createTestContext();
- domStore.onGlobalContextUpdated(schemaContext);
- initTestNode();
- }
-
- @Override
- @TearDown
- public void tearDown() {
- schemaContext = null;
- domStore = null;
- }
-}
*/
package org.opendaylight.controller.md.sal.dom.store.benchmark;
-import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
final ExecutorService dataChangeListenerExecutor = SpecialExecutors.newBlockingBoundedFastThreadPool(
MAX_DATA_CHANGE_EXECUTOR_POOL_SIZE, MAX_DATA_CHANGE_EXECUTOR_QUEUE_SIZE, name + "-DCL");
- domStore = new InMemoryDOMDataStore("SINGLE_THREADED_DS_BENCHMARK", MoreExecutors.sameThreadExecutor(),
- dataChangeListenerExecutor);
+ domStore = new InMemoryDOMDataStore("SINGLE_THREADED_DS_BENCHMARK", dataChangeListenerExecutor);
schemaContext = BenchmarkModel.createTestContext();
domStore.onGlobalContextUpdated(schemaContext);
initTestNode();
@Setup(Level.Trial)
public void setUp() throws Exception {
- domStore = new InMemoryDOMDataStore("SINGLE_THREADED_DS_BENCHMARK", MoreExecutors.sameThreadExecutor(),
- MoreExecutors.sameThreadExecutor());
+ domStore = new InMemoryDOMDataStore("SINGLE_THREADED_DS_BENCHMARK", MoreExecutors.sameThreadExecutor());
schemaContext = BenchmarkModel.createTestContext();
domStore.onGlobalContextUpdated(schemaContext);
initTestNode();
}
public DOMStore createConfigurationDatastore() {
- InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
schemaService.registerSchemaContextListener(store);
return store;
}
public DOMStore createOperationalDatastore() {
- InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
schemaService.registerSchemaContextListener(store);
return store;
}
package test.mock.util;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-@SuppressWarnings("deprecation")
public final class MockSchemaService implements SchemaService, SchemaContextProvider {
private SchemaContext schemaContext;
</schema-service>
</inmemory-operational-datastore-provider>
</module>
+
+ <!-- PingPong broker -->
+ <module>
+ <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:pingpong">prefix:pingpong-data-broker</type>
+ <name>pingpong-data-broker</name>
+ <data-broker>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-async-data-broker</type>
+ <name>inmemory-data-broker</name>
+ </data-broker>
+ </module>
+ <module>
+ <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:binding-forwarded-data-broker</type>
+ <name>pingpong-binding-data-broker</name>
+ <binding-forwarded-data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+ <dom-async-broker>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-async-data-broker</type>
+ <name>pingpong-broker</name>
+ </dom-async-broker>
+ <schema-service>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
+ <name>yang-schema-service</name>
+ </schema-service>
+ <binding-mapping-service>
+ <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">binding:binding-dom-mapping-service</type>
+ <name>runtime-mapping-singleton</name>
+ </binding-mapping-service>
+ </binding-forwarded-data-broker>
+ </module>
+
<!--
Tree-based in-memory data store. This is the data store which is currently
recommended for single-node deployments.
<name>binding-async-data-broker</name>
<binding-forwarded-data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
<dom-async-broker>
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
- <name>dom-broker</name>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-async-data-broker</type>
+ <name>inmemory-data-broker</name>
</dom-async-broker>
+ <schema-service>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
+ <name>yang-schema-service</name>
+ </schema-service>
<binding-mapping-service>
<type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">binding:binding-dom-mapping-service</type>
<name>runtime-mapping-singleton</name>
<name>binding-data-broker</name>
<provider>/modules/module[type='binding-forwarded-data-broker'][name='binding-async-data-broker']</provider>
</instance>
+ <instance>
+ <name>pingpong-binding-data-broker</name>
+ <provider>/modules/module[type='binding-forwarded-data-broker'][name='pingpong-binding-data-broker']</provider>
+ </instance>
</service>
<service>
<name>inmemory-data-broker</name>
<provider>/modules/module[type='dom-inmemory-data-broker'][name='inmemory-data-broker']</provider>
</instance>
+ <instance>
+ <name>pingpong-broker</name>
+ <provider>/modules/module[type='pingpong-data-broker'][name='pingpong-data-broker']</provider>
+ </instance>
</service>
</services>
</data>
<capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding?module=opendaylight-md-sal-binding&revision=2013-10-28</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom?module=opendaylight-md-sal-dom&revision=2013-10-28</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl?module=opendaylight-sal-binding-broker-impl&revision=2013-10-28</capability>
+ <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:pingpong?module=opendaylight-pingpong-broker&revision=2014-11-07</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl?module=opendaylight-sal-dom-broker-impl&revision=2013-10-28</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:common?module=opendaylight-md-sal-common&revision=2013-10-28</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:core:spi:config-dom-store?module=opendaylight-config-dom-datastore&revision=2014-06-17</capability>
*/
public void markFollowerActive();
+ /**
+ * This will stop the timeout clock
+ */
+ public void markFollowerInActive();
+
}
}
stopwatch.start();
}
+
+ @Override
+ public void markFollowerInActive() {
+ if (stopwatch.isRunning()) {
+ stopwatch.stop();
+ }
+ }
}
void markFollowerActive(String followerId) {
followerToLog.get(followerId).markFollowerActive();
}
+
+ @VisibleForTesting
+ void markFollowerInActive(String followerId) {
+ followerToLog.get(followerId).markFollowerInActive();
+ }
}
import akka.actor.Terminated;
import akka.testkit.JavaTestKit;
import com.google.common.base.Optional;
-import com.google.common.util.concurrent.Uninterruptibles;
import com.google.protobuf.ByteString;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
final Terminated termMsg1 = probe.expectMsgClass(Terminated.class);
assertEquals(termMsg1.getActor(), followerActor1);
- //sleep enough for all the follower stopwatches to lapse
- Uninterruptibles.sleepUninterruptibly(leaderActorContext.getConfigParams().
- getElectionTimeOutInterval().toMillis(), TimeUnit.MILLISECONDS);
-
+ leader.markFollowerInActive("follower-1");
leader.markFollowerActive("follower-2");
behavior = leader.handleMessage(leaderActor, new IsolatedLeaderCheck());
Assert.assertTrue("Behavior not instance of Leader when majority of followers are active",
final Terminated termMsg2 = probe.expectMsgClass(Terminated.class);
assertEquals(termMsg2.getActor(), followerActor2);
- //sleep enough for the remaining the follower stopwatches to lapse
- Uninterruptibles.sleepUninterruptibly(leaderActorContext.getConfigParams().
- getElectionTimeOutInterval().toMillis(), TimeUnit.MILLISECONDS);
-
+ leader.markFollowerInActive("follower-2");
behavior = leader.handleMessage(leaderActor, new IsolatedLeaderCheck());
Assert.assertTrue("Behavior not instance of IsolatedLeader when majority followers are inactive",
behavior instanceof IsolatedLeader);
@Override public void onReceive(Object message) throws Exception {
if(message instanceof String){
if("get-all-messages".equals(message)){
- getSender().tell(messages, getSelf());
+ getSender().tell(new ArrayList(messages), getSelf());
}
} else {
messages.add(message);
package org.opendaylight.controller.config.yang.md.sal.binding.impl;
-import java.util.Collection;
-import java.util.Collections;
import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
import org.opendaylight.controller.md.sal.binding.impl.ForwardedBindingDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
-import org.opendaylight.controller.sal.core.api.Provider;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
public class BindingAsyncDataBrokerImplModule extends
- org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingAsyncDataBrokerImplModule implements
- Provider {
+ org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingAsyncDataBrokerImplModule {
public BindingAsyncDataBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
@Override
public java.lang.AutoCloseable createInstance() {
- Broker domBroker = getDomAsyncBrokerDependency();
- BindingToNormalizedNodeCodec mappingService = getBindingMappingServiceDependency();
-
- // FIXME: Switch this to DOM Broker registration which would not require
- // BundleContext when API are updated.
- ProviderSession session = domBroker.registerProvider(this, null);
- DOMDataBroker domDataBroker = session.getService(DOMDataBroker.class);
- SchemaService schemaService = session.getService(SchemaService.class);
+ final BindingToNormalizedNodeCodec mappingService = getBindingMappingServiceDependency();
+ final DOMDataBroker domDataBroker = getDomAsyncBrokerDependency();
+ final SchemaService schemaService = getSchemaServiceDependency();
return new ForwardedBindingDataBroker(domDataBroker, mappingService, schemaService);
}
-
-
-
-
- @Override
- public Collection<ProviderFunctionality> getProviderFunctionality() {
- return Collections.emptySet();
- }
-
- @Override
- public void onSessionInitiated(final ProviderSession arg0) {
- // intentional NOOP
- }
-
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@SuppressWarnings("deprecation")
+@Deprecated
public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDataBroker implements DataProviderService, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(ForwardedBackwardsCompatibleDataBroker.class);
});
}
+ @Deprecated
private class ForwardedBackwardsCompatibleTransacion extends
AbstractReadWriteTransaction implements DataModificationTransaction {
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+@Deprecated
public abstract class LegacyDataChangeEvent implements
DataChangeEvent<InstanceIdentifier<? extends DataObject>, DataObject> {
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Maps;
+@Deprecated
public class DataBrokerImpl extends
AbstractDataBroker<InstanceIdentifier<? extends DataObject>, DataObject, DataChangeListener> //
implements DataProviderService, AutoCloseable {
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+@Deprecated
public class DataTransactionImpl extends AbstractDataTransaction<InstanceIdentifier<? extends DataObject>, DataObject>
implements DataModificationTransaction {
private final ListenerRegistry<DataTransactionListener> listeners = new ListenerRegistry<DataTransactionListener>();
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+@Deprecated
class BindingToDomTransaction implements
DataCommitHandler.DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> {
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+@Deprecated
class DomToBindingTransaction implements
DataCommitHandler.DataCommitTransaction<YangInstanceIdentifier, CompositeNode> {
case binding-forwarded-data-broker {
when "/config:modules/config:module/config:type = 'binding-forwarded-data-broker'";
container binding-forwarded-data-broker {
- uses dom-forwarding-component;
+ container dom-async-broker {
+ uses config:service-ref {
+ refine type {
+ mandatory true;
+ config:required-identity dom:dom-async-data-broker;
+ }
+ }
+ }
+
+ container binding-mapping-service {
+ uses config:service-ref {
+ refine type {
+ mandatory true;
+ config:required-identity binding-dom-mapping-service;
+ }
+ }
+ }
+
+ container schema-service {
+ uses config:service-ref {
+ refine type {
+ mandatory false;
+ config:required-identity dom:schema-service;
+ }
+ }
+ }
}
}
}
}
public DOMStore createConfigurationDatastore() {
- InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
schemaService.registerSchemaContextListener(store);
return store;
}
public DOMStore createOperationalDatastore() {
- InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
schemaService.registerSchemaContextListener(store);
return store;
}
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+@Deprecated
public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implements DataChangeListener {
private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
package org.opendaylight.controller.sal.binding.test.util;
import static com.google.common.base.Preconditions.checkState;
-
import com.google.common.annotations.Beta;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableClassToInstanceMap;
public void startNewDomDataBroker() {
checkState(executor != null, "Executor needs to be set");
- InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", executor,
- MoreExecutors.sameThreadExecutor());
- InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", executor,
- MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
newDatastores = ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
.put(LogicalDatastoreType.OPERATIONAL, operStore)
.put(LogicalDatastoreType.CONFIGURATION, configStore)
updateYangSchema(moduleInfos);
}
- @SuppressWarnings("deprecation")
+ @Deprecated
public DataProviderService getBindingDataBroker() {
return baData;
}
- @SuppressWarnings("deprecation")
+ @Deprecated
public org.opendaylight.controller.sal.core.api.data.DataProviderService getDomDataBroker() {
return biDataLegacyBroker;
}
package org.opendaylight.controller.sal.binding.test.util;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-@SuppressWarnings("deprecation")
public final class MockSchemaService implements SchemaService, SchemaContextProvider {
private SchemaContext schemaContext;
<name>binding-async-data-broker</name>
<binding-forwarded-data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
<dom-async-broker>
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
- <name>dom-broker</name>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-async-data-broker</type>
+ <name>inmemory-data-broker</name>
</dom-async-broker>
+ <schema-service>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
+ <name>yang-schema-service</name>
+ </schema-service>
<binding-mapping-service>
<type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">binding:binding-dom-mapping-service</type>
<name>runtime-mapping-singleton</name>
* Users of this interface can publish any YANG-modeled notification which will
* be delivered to all subscribed listeners.
* <p>
- * Prefered way of publishing of notifications is done by invoking {@link #publish(Object)}.
+ * Preferred way of publishing of notifications is done by invoking {@link #publish(Object)}.
*
* <p>You may consider using {@link #publish(Object, ExecutorService)} if and only if
* your use-case requires customized execution policy or run-to-completion
* Publishes a notification and notifies subscribed listeners. All listener
* notifications are done via the provided executor.
* <p>
- * <b>Note:</b> Use only if ineccessary. Consider using
+ * <b>Note:</b> Use only if necessary. Consider using
* {@link #publish(Object)} for most use-cases.
*
* <p>
package org.opendaylight.controller.md.sal.common.api.notify;
import java.util.EventListener;
-
import org.opendaylight.yangtools.concepts.ListenerRegistration;
-public interface NotificationSubscriptionService<T,N,L extends EventListener> {
+public interface NotificationSubscriptionService<T, N, L extends EventListener> {
- ListenerRegistration<L> registerNotificationListener(T type,L listener);
+ ListenerRegistration<L> registerNotificationListener(T type, L listener);
}
import org.opendaylight.controller.md.sal.common.api.data.DataReader;
import org.opendaylight.yangtools.concepts.Path;
+@Deprecated
public abstract class AbstractDataModification<P extends Path<P>, D> implements DataModification<P, D> {
private final Map<P, D> operationalOriginal;
* @param <P>
* @param <D>
*/
+@Deprecated
public abstract class AbstractDataReadRouter<P extends Path<P>, D> implements DataReader<P, D> {
Multimap<P, DataReaderRegistration<P, D>> configReaders = Multimaps.synchronizedSetMultimap(HashMultimap.<P, DataReaderRegistration<P, D>>create());
import com.google.common.collect.Multimaps;
import com.google.common.util.concurrent.MoreExecutors;
+@Deprecated
public abstract class AbstractDataBroker<P extends Path<P>, D extends Object, DCL extends DataChangeListener<P, D>>
implements DataModificationTransactionFactory<P, D>, DataReader<P, D>, DataChangePublisher<P, D, DCL>,
DataProvisionService<P, D> {
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@Deprecated
public abstract class AbstractDataTransaction<P extends Path<P>, D extends Object> extends
AbstractDataModification<P, D> {
private static final Logger LOG = LoggerFactory.getLogger(AbstractDataTransaction.class);
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.concepts.Path;
+@Deprecated
public class DataChangeEventImpl<P extends Path<P>, D> implements DataChangeEvent<P, D>, Immutable {
private final DataChange<P, D> dataChange;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+@Deprecated
public final class ImmutableDataChangeEvent<P extends Path<P>, D> implements DataChangeEvent<P,D> {
private final D updatedOperationalSubtree;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.concepts.Path;
+@Deprecated
public class InitialDataChangeEventImpl<P extends Path<P>,D> implements DataChangeEvent<P, D>, Immutable {
private final D updatedOperationalTree;
import com.google.common.base.Predicate;
+@Deprecated
public final class ListenerStateCapture<P extends Path<P>, D, DCL extends DataChangeListener<P, D>> {
final P path;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
+@Deprecated
public class TwoPhaseCommit<P extends Path<P>, D extends Object, DCL extends DataChangeListener<P, D>> implements
Callable<RpcResult<TransactionStatus>> {
private final static Logger log = LoggerFactory.getLogger(TwoPhaseCommit.class);
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
+/**
+ * @deprecated This class provides compatibility between {@link CompositeNode} and {@link NormalizedNode}.
+ * Users of this class should use {@link NormalizedNode}s directly.
+ */
+@Deprecated
public abstract class DataNormalizationOperation<T extends PathArgument> implements Identifiable<T> {
private final T identifier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
+/**
+ * @deprecated This class provides compatibility between {@link CompositeNode} and {@link NormalizedNode}.
+ * Users of this class should use {@link NormalizedNode}s directly.
+ */
+@Deprecated
public class DataNormalizer {
private final DataNormalizationOperation<?> operation;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+@Deprecated
public class DataNormalizerTest {
static class NormalizedNodeData {
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+/**
+ * @deprecated Utility class for {@link DataCommitTransaction}, will be removed at the same time.
+ */
+@Deprecated
public class CommitHandlerTransactions {
private static class AllwaysSuccessfulTransaction<P extends Path<P>,D> implements DataCommitTransaction<P, D> {
private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
- protected Shard(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
- DatastoreContext datastoreContext, SchemaContext schemaContext) {
+ protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
+ final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
super(name.toString(), mapPeerAddresses(peerAddresses),
Optional.of(datastoreContext.getShardRaftConfig()));
shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
datastoreContext.getDataStoreMXBeanType());
- shardMBean.setDataStoreExecutor(store.getDomStoreExecutor());
shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
if (isMetricsCaptureEnabled()) {
}
private static Map<String, String> mapPeerAddresses(
- Map<ShardIdentifier, String> peerAddresses) {
+ final Map<ShardIdentifier, String> peerAddresses) {
Map<String, String> map = new HashMap<>();
for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
public static Props props(final ShardIdentifier name,
final Map<ShardIdentifier, String> peerAddresses,
- DatastoreContext datastoreContext, SchemaContext schemaContext) {
+ final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
Preconditions.checkNotNull(name, "name should not be null");
Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
}
@Override
- public void onReceiveRecover(Object message) throws Exception {
+ public void onReceiveRecover(final Object message) throws Exception {
if(LOG.isDebugEnabled()) {
LOG.debug("onReceiveRecover: Received message {} from {}",
message.getClass().toString(),
}
@Override
- public void onReceiveCommand(Object message) throws Exception {
+ public void onReceiveCommand(final Object message) throws Exception {
if(LOG.isDebugEnabled()) {
LOG.debug("onReceiveCommand: Received message {} from {}", message, getSender());
}
}
}
- private void handleCommitTransaction(CommitTransaction commit) {
+ private void handleCommitTransaction(final CommitTransaction commit) {
final String transactionID = commit.getTransactionID();
LOG.debug("Committing transaction {}", transactionID);
commitCoordinator.currentTransactionComplete(transactionID, true);
}
- private void handleCanCommitTransaction(CanCommitTransaction canCommit) {
+ private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
LOG.debug("Can committing transaction {}", canCommit.getTransactionID());
commitCoordinator.handleCanCommit(canCommit, getSender(), self());
}
readyTransactionReply, getSelf());
}
- private void handleAbortTransaction(AbortTransaction abort) {
+ private void handleAbortTransaction(final AbortTransaction abort) {
doAbortTransaction(abort.getTransactionID(), getSender());
}
- private void doAbortTransaction(String transactionID, final ActorRef sender) {
+ private void doAbortTransaction(final String transactionID, final ActorRef sender) {
final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
if(cohortEntry != null) {
LOG.debug("Aborting transaction {}", transactionID);
Futures.addCallback(future, new FutureCallback<Void>() {
@Override
- public void onSuccess(Void v) {
+ public void onSuccess(final Void v) {
shardMBean.incrementAbortTransactionsCount();
if(sender != null) {
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(final Throwable t) {
LOG.error(t, "An exception happened during abort");
if(sender != null) {
}
}
- private void handleCreateTransaction(Object message) {
+ private void handleCreateTransaction(final Object message) {
if (isLeader()) {
createTransaction(CreateTransaction.fromSerializable(message));
} else if (getLeader() != null) {
}
}
- private void handleReadDataReply(Object message) {
+ private void handleReadDataReply(final Object message) {
// This must be for install snapshot. Don't want to open this up and trigger
// deSerialization
getSender().tell(PoisonPill.getInstance(), self());
}
- private void closeTransactionChain(CloseTransactionChain closeTransactionChain) {
+ private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
DOMStoreTransactionChain chain =
transactionChains.remove(closeTransactionChain.getTransactionChainId());
return transactionActor;
}
- private void syncCommitTransaction(DOMStoreWriteTransaction transaction)
+ private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
throws ExecutionException, InterruptedException {
DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
commitCohort.preCommit().get();
commitCohort.commit().get();
}
- private void commitWithNewTransaction(Modification modification) {
+ private void commitWithNewTransaction(final Modification modification) {
DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
modification.apply(tx);
try {
}
}
- private void updateSchemaContext(UpdateSchemaContext message) {
+ private void updateSchemaContext(final UpdateSchemaContext message) {
this.schemaContext = message.getSchemaContext();
updateSchemaContext(message.getSchemaContext());
store.onGlobalContextUpdated(message.getSchemaContext());
}
@VisibleForTesting
- void updateSchemaContext(SchemaContext schemaContext) {
+ void updateSchemaContext(final SchemaContext schemaContext) {
store.onGlobalContextUpdated(schemaContext);
}
- private void registerChangeListener(RegisterChangeListener registerChangeListener) {
+ private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
LOG.debug("registerDataChangeListener for {}", registerChangeListener.getPath());
private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
NormalizedNode<?, ?>>> doChangeListenerRegistration(
- RegisterChangeListener registerChangeListener) {
+ final RegisterChangeListener registerChangeListener) {
ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
registerChangeListener.getDataChangeListenerPath());
@Override
protected
- void startLogRecoveryBatch(int maxBatchSize) {
+ void startLogRecoveryBatch(final int maxBatchSize) {
currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
if(LOG.isDebugEnabled()) {
}
@Override
- protected void appendRecoveredLogEntry(Payload data) {
+ protected void appendRecoveredLogEntry(final Payload data) {
if (data instanceof CompositeModificationPayload) {
currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
} else {
}
@Override
- protected void applyRecoverySnapshot(ByteString snapshot) {
+ protected void applyRecoverySnapshot(final ByteString snapshot) {
if(recoveryCoordinator == null) {
recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
}
}
@Override
- protected void applyState(ActorRef clientActor, String identifier, Object data) {
+ protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
if (data instanceof CompositeModificationPayload) {
Object modification = ((CompositeModificationPayload) data).getModification();
@VisibleForTesting
@Override
- protected void applySnapshot(ByteString snapshot) {
+ protected void applySnapshot(final ByteString snapshot) {
// Since this will be done only on Recovery or when this actor is a Follower
// we can safely commit everything in here. We not need to worry about event notifications
// as they would have already been disabled on the follower
return dataPersistenceProvider;
}
- @Override protected void onLeaderChanged(String oldLeader, String newLeader) {
+ @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
shardMBean.setLeader(newLeader);
}
final DatastoreContext datastoreContext;
final SchemaContext schemaContext;
- ShardCreator(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
- DatastoreContext datastoreContext, SchemaContext schemaContext) {
+ ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
+ final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
this.name = name;
this.peerAddresses = peerAddresses;
this.datastoreContext = datastoreContext;
private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
NormalizedNode<?, ?>>> delegate;
- DelayedListenerRegistration(RegisterChangeListener registerChangeListener) {
+ DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
this.registerChangeListener = registerChangeListener;
}
- void setDelegate( ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
+ void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
NormalizedNode<?, ?>>> registration) {
this.delegate = registration;
}
*/
package org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.cache.Cache;
-import com.google.common.cache.CacheBuilder;
-
/**
* @author Basheeruddin syedbahm@cisco.com
*
private static final Logger LOG = LoggerFactory.getLogger(ShardMBeanFactory.class);
- private static Cache<String,ShardStats> shardMBeansCache =
+ private static final Cache<String,ShardStats> shardMBeansCache =
CacheBuilder.newBuilder().weakValues().build();
public static ShardStats getShardStatsMBean(final String shardName, final String mxBeanType) {
package org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard;
+import java.text.SimpleDateFormat;
+import java.util.Date;
import java.util.List;
-import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
-
import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
import org.opendaylight.controller.md.sal.common.util.jmx.QueuedNotificationManagerMXBeanImpl;
import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStats;
import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStatsMXBeanImpl;
+import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
import org.opendaylight.yangtools.util.concurrent.ListenerNotificationQueueStats;
import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
/**
* Maintains statistics for a shard.
*
private ThreadExecutorStatsMXBeanImpl notificationExecutorStatsBean;
- private ThreadExecutorStatsMXBeanImpl dataStoreExecutorStatsBean;
-
private QueuedNotificationManagerMXBeanImpl notificationManagerStatsBean;
private final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
- public ShardStats(String shardName, String mxBeanType) {
+ public ShardStats(final String shardName, final String mxBeanType) {
super(shardName, mxBeanType, JMX_CATEGORY_SHARD);
}
- public void setDataStoreExecutor(ExecutorService dsExecutor) {
- this.dataStoreExecutorStatsBean = ThreadExecutorStatsMXBeanImpl.create(dsExecutor);
- }
-
- public void setNotificationManager(QueuedNotificationManager<?, ?> manager) {
+ public void setNotificationManager(final QueuedNotificationManager<?, ?> manager) {
this.notificationManagerStatsBean = new QueuedNotificationManagerMXBeanImpl(manager,
"notification-manager", getMBeanType(), getMBeanCategory());
return abortTransactionsCount.incrementAndGet();
}
- public void setLeader(String leader) {
+ public void setLeader(final String leader) {
this.leader = leader;
}
- public void setRaftState(String raftState) {
+ public void setRaftState(final String raftState) {
this.raftState = raftState;
}
- public void setLastLogTerm(long lastLogTerm) {
+ public void setLastLogTerm(final long lastLogTerm) {
this.lastLogTerm = lastLogTerm;
}
- public void setLastLogIndex(long lastLogIndex) {
+ public void setLastLogIndex(final long lastLogIndex) {
this.lastLogIndex = lastLogIndex;
}
- public void setCurrentTerm(long currentTerm) {
+ public void setCurrentTerm(final long currentTerm) {
this.currentTerm = currentTerm;
}
- public void setCommitIndex(long commitIndex) {
+ public void setCommitIndex(final long commitIndex) {
this.commitIndex = commitIndex;
}
- public void setLastApplied(long lastApplied) {
+ public void setLastApplied(final long lastApplied) {
this.lastApplied = lastApplied;
}
- public void setLastCommittedTransactionTime(long lastCommittedTransactionTime) {
+ public void setLastCommittedTransactionTime(final long lastCommittedTransactionTime) {
this.lastCommittedTransactionTime = lastCommittedTransactionTime;
}
@Override
public ThreadExecutorStats getDataStoreExecutorStats() {
- return dataStoreExecutorStatsBean == null ? null :
- dataStoreExecutorStatsBean.toThreadExecutorStats();
+ // FIXME: this particular thing does not work, as it really is DS-specific
+ return null;
}
@Override
abortTransactionsCount.set(0);
}
+
+ public void setDataStore(final InMemoryDOMDataStore store) {
+ setNotificationManager(store.getDataChangeListenerNotificationManager());
+ }
}
Assert.assertEquals(mockListener, proxy.getInstance());
}
- @SuppressWarnings("unchecked")
@Test(timeout=10000)
public void testSuccessfulRegistration() {
new JavaTestKit(getSystem()) {{
}};
}
- @SuppressWarnings("unchecked")
@Test
public void testCloseBeforeRegistration() {
new JavaTestKit(getSystem()) {{
package org.opendaylight.controller.cluster.datastore;
+import static org.junit.Assert.assertEquals;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.testkit.JavaTestKit;
-import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import static org.junit.Assert.assertEquals;
-
public class DataChangeListenerRegistrationTest extends AbstractActorTest {
- private static ListeningExecutorService storeExecutor = MoreExecutors.listeningDecorator(MoreExecutors.sameThreadExecutor());
-
- private static final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", storeExecutor,
- MoreExecutors.sameThreadExecutor());
+ private static final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
static {
store.onGlobalContextUpdated(TestModel.createTestContext());
final String out = new ExpectMsg<String>(duration("1 seconds"), "match hint") {
// do not put code outside this method, will run afterwards
@Override
- protected String match(Object in) {
+ protected String match(final Object in) {
if (in.getClass().equals(CloseDataChangeListenerRegistrationReply.SERIALIZABLE_CLASS)) {
return "match";
} else {
private AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> noOpDataChangeListener(){
return new AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>() {
@Override
- public void onDataChanged(AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
+ public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
}
};
import scala.concurrent.Future;
import scala.concurrent.duration.FiniteDuration;
-
public class ShardTest extends AbstractActorTest {
private static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
*/
@Test
public void testInMemoryDataStoreRestore() throws ReadFailedException {
- InMemoryDOMDataStore store = new InMemoryDOMDataStore("test", MoreExecutors.listeningDecorator(
- MoreExecutors.sameThreadExecutor()), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore store = new InMemoryDOMDataStore("test", MoreExecutors.sameThreadExecutor());
store.onGlobalContextUpdated(SCHEMA_CONTEXT);
NormalizedNode<?, ?> actual = readStore(store);
assertEquals(expected, actual);
-
}
@Test
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;
* @author Basheeruddin Ahmed <syedbahm@cisco.com>
*/
public class ShardTransactionFailureTest extends AbstractActorTest {
- private static ListeningExecutorService storeExecutor =
- MoreExecutors.listeningDecorator(MoreExecutors.sameThreadExecutor());
-
private static final InMemoryDOMDataStore store =
- new InMemoryDOMDataStore("OPER", storeExecutor,
- MoreExecutors.sameThreadExecutor());
+ new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
private static final SchemaContext testSchemaContext =
TestModel.createTestContext();
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 scala.concurrent.duration.Duration;
public class ShardTransactionTest extends AbstractActorTest {
- private static ListeningExecutorService storeExecutor =
- MoreExecutors.listeningDecorator(MoreExecutors.sameThreadExecutor());
-
private static final InMemoryDOMDataStore store =
- new InMemoryDOMDataStore("OPER", storeExecutor, MoreExecutors.sameThreadExecutor());
+ new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
private static final SchemaContext testSchemaContext = TestModel.createTestContext();
}
- @SuppressWarnings("unchecked")
@Test
public void testOnReceiveCloseTransaction() throws Exception {
new JavaTestKit(getSystem()) {{
}
}
- @SuppressWarnings("unchecked")
@Test
public void testReady() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
verifyCohortFutures(proxy, getSystem().actorSelection(actorRef.path()));
}
- @SuppressWarnings("unchecked")
@Test
public void testReadyForwardCompatibility() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE, 0);
eq(actorRef.path().toString()));
}
- @SuppressWarnings("unchecked")
@Test
public void testReadyWithRecordingOperationFailure() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
MergeDataReply.SERIALIZABLE_CLASS, TestException.class);
}
- @SuppressWarnings("unchecked")
@Test
public void testReadyWithReplyFailure() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
verifyCohortFutures(proxy, PrimaryNotFoundException.class);
}
- @SuppressWarnings("unchecked")
@Test
public void testReadyWithInvalidReplyMessageType() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
assertTrue("Invalid identifier: " + id, id.toString().startsWith(memberName));
}
- @SuppressWarnings("unchecked")
@Test
public void testClose() throws Exception{
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
@Before
public void setUp(){
- store = new InMemoryDOMDataStore("test", MoreExecutors.sameThreadExecutor(),
- MoreExecutors.sameThreadExecutor());
+ store = new InMemoryDOMDataStore("test", MoreExecutors.sameThreadExecutor());
store.onGlobalContextUpdated(TestModel.createTestContext());
}
- protected void commitTransaction(DOMStoreWriteTransaction transaction){
+ protected void commitTransaction(final DOMStoreWriteTransaction transaction){
DOMStoreThreePhaseCommitCohort cohort = transaction.ready();
cohort.preCommit();
cohort.commit();
}
- protected Optional<NormalizedNode<?,?>> readData(YangInstanceIdentifier path) throws Exception{
+ protected Optional<NormalizedNode<?,?>> readData(final YangInstanceIdentifier path) throws Exception{
DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
ListenableFuture<Optional<NormalizedNode<?, ?>>> future = transaction.read(path);
return future.get();
org.opendaylight.controller.sal.dom.broker.osgi,
org.opendaylight.controller.sal.dom.broker.util,
org.opendaylight.controller.config.yang.md.sal.dom.impl,
+ org.opendaylight.controller.config.yang.md.sal.dom.pingpong,
org.opendaylight.controller.config.yang.md.sal.dom.statistics,\
org.opendaylight.controller.md.sal.dom.broker.impl,
org.opendaylight.controller.md.sal.dom.broker.impl.*,
org.opendaylight.yangtools.yang.util,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.dom.impl.rev131028.*</Private-Package>
+ org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.dom.impl.rev131028.*,
+ org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.dom.pingpong.rev141107.*
+ </Private-Package>
<Import-Package>*</Import-Package>
</instructions>
</configuration>
--- /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.config.yang.md.sal.dom.pingpong;
+
+import org.opendaylight.controller.config.api.DependencyResolver;
+import org.opendaylight.controller.config.api.ModuleIdentifier;
+import org.opendaylight.controller.md.sal.dom.broker.impl.PingPongDataBroker;
+
+public class PingpongDataBrokerModule extends AbstractPingpongDataBrokerModule {
+ public PingpongDataBrokerModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver) {
+ super(identifier, dependencyResolver);
+ }
+
+ public PingpongDataBrokerModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver, final PingpongDataBrokerModule oldModule, final java.lang.AutoCloseable oldInstance) {
+ super(identifier, dependencyResolver, oldModule, oldInstance);
+ }
+
+ @Override
+ public java.lang.AutoCloseable createInstance() {
+ return new PingPongDataBroker(getDataBrokerDependency());
+ }
+}
--- /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.config.yang.md.sal.dom.pingpong;
+
+public class PingpongDataBrokerModuleFactory extends AbstractPingpongDataBrokerModuleFactory {
+
+}
import org.opendaylight.controller.config.yang.md.sal.dom.impl.Transactions;
import org.opendaylight.controller.sal.dom.broker.DataBrokerImpl;
+@Deprecated
public class DomBrokerRuntimeMXBeanImpl implements
DomBrokerImplRuntimeMXBean {
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.broker.impl;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.Iterables;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
+import org.opendaylight.yangtools.util.DurationStatisticsTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Implementation of blocking three-phase commit-coordination tasks without
+ * support of cancellation.
+ */
+final class CommitCoordinationTask implements Callable<Void> {
+ private static enum Phase {
+ canCommit,
+ preCommit,
+ doCommit,
+ };
+
+ private static final Logger LOG = LoggerFactory.getLogger(CommitCoordinationTask.class);
+ private final Iterable<DOMStoreThreePhaseCommitCohort> cohorts;
+ private final DurationStatisticsTracker commitStatTracker;
+ private final DOMDataWriteTransaction tx;
+ private final int cohortSize;
+
+ public CommitCoordinationTask(final DOMDataWriteTransaction transaction,
+ final Iterable<DOMStoreThreePhaseCommitCohort> cohorts,
+ final DurationStatisticsTracker commitStatTracker) {
+ this.tx = Preconditions.checkNotNull(transaction, "transaction must not be null");
+ this.cohorts = Preconditions.checkNotNull(cohorts, "cohorts must not be null");
+ this.commitStatTracker = commitStatTracker;
+ this.cohortSize = Iterables.size(cohorts);
+ }
+
+ @Override
+ public Void call() throws TransactionCommitFailedException {
+ final long startTime = commitStatTracker != null ? System.nanoTime() : 0;
+
+ Phase phase = Phase.canCommit;
+
+ try {
+ LOG.debug("Transaction {}: canCommit Started", tx.getIdentifier());
+ canCommitBlocking();
+
+ phase = Phase.preCommit;
+ LOG.debug("Transaction {}: preCommit Started", tx.getIdentifier());
+ preCommitBlocking();
+
+ phase = Phase.doCommit;
+ LOG.debug("Transaction {}: doCommit Started", tx.getIdentifier());
+ commitBlocking();
+
+ LOG.debug("Transaction {}: doCommit completed", tx.getIdentifier());
+ return null;
+ } catch (TransactionCommitFailedException e) {
+ LOG.warn("Tx: {} Error during phase {}, starting Abort", tx.getIdentifier(), phase, e);
+ abortBlocking(e);
+ throw e;
+ } finally {
+ if (commitStatTracker != null) {
+ commitStatTracker.addDuration(System.nanoTime() - startTime);
+ }
+ }
+ }
+
+ /**
+ *
+ * Invokes canCommit on underlying cohorts and blocks till
+ * all results are returned.
+ *
+ * Valid state transition is from SUBMITTED to CAN_COMMIT,
+ * if currentPhase is not SUBMITTED throws IllegalStateException.
+ *
+ * @throws TransactionCommitFailedException
+ * If one of cohorts failed can Commit
+ *
+ */
+ private void canCommitBlocking() throws TransactionCommitFailedException {
+ for (ListenableFuture<?> canCommit : canCommitAll()) {
+ try {
+ final Boolean result = (Boolean)canCommit.get();
+ if (result == null || !result) {
+ throw new TransactionCommitFailedException("Can Commit failed, no detailed cause available.");
+ }
+ } catch (InterruptedException | ExecutionException e) {
+ throw TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER.apply(e);
+ }
+ }
+ }
+
+ /**
+ *
+ * Invokes canCommit on underlying cohorts and returns composite future
+ * which will contains {@link Boolean#TRUE} only and only if
+ * all cohorts returned true.
+ *
+ * Valid state transition is from SUBMITTED to CAN_COMMIT,
+ * if currentPhase is not SUBMITTED throws IllegalStateException.
+ *
+ * @return List of all cohorts futures from can commit phase.
+ *
+ */
+ private ListenableFuture<?>[] canCommitAll() {
+ final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohortSize];
+ int i = 0;
+ for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
+ ops[i++] = cohort.canCommit();
+ }
+ return ops;
+ }
+
+ /**
+ *
+ * Invokes preCommit on underlying cohorts and blocks till
+ * all results are returned.
+ *
+ * Valid state transition is from CAN_COMMIT to PRE_COMMIT, if current
+ * state is not CAN_COMMIT
+ * throws IllegalStateException.
+ *
+ * @throws TransactionCommitFailedException
+ * If one of cohorts failed preCommit
+ *
+ */
+ private void preCommitBlocking() throws TransactionCommitFailedException {
+ final ListenableFuture<?>[] preCommitFutures = preCommitAll();
+ try {
+ for(ListenableFuture<?> future : preCommitFutures) {
+ future.get();
+ }
+ } catch (InterruptedException | ExecutionException e) {
+ throw TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER.apply(e);
+ }
+ }
+
+ /**
+ *
+ * Invokes preCommit on underlying cohorts and returns future
+ * which will complete once all preCommit on cohorts completed or
+ * failed.
+ *
+ *
+ * Valid state transition is from CAN_COMMIT to PRE_COMMIT, if current
+ * state is not CAN_COMMIT
+ * throws IllegalStateException.
+ *
+ * @return List of all cohorts futures from can commit phase.
+ *
+ */
+ private ListenableFuture<?>[] preCommitAll() {
+ final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohortSize];
+ int i = 0;
+ for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
+ ops[i++] = cohort.preCommit();
+ }
+ return ops;
+ }
+
+ /**
+ *
+ * Invokes commit on underlying cohorts and blocks till
+ * all results are returned.
+ *
+ * Valid state transition is from PRE_COMMIT to COMMIT, if not throws
+ * IllegalStateException.
+ *
+ * @throws TransactionCommitFailedException
+ * If one of cohorts failed preCommit
+ *
+ */
+ private void commitBlocking() throws TransactionCommitFailedException {
+ final ListenableFuture<?>[] commitFutures = commitAll();
+ try {
+ for(ListenableFuture<?> future : commitFutures) {
+ future.get();
+ }
+ } catch (InterruptedException | ExecutionException e) {
+ throw TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER.apply(e);
+ }
+ }
+
+ /**
+ *
+ * Invokes commit on underlying cohorts and returns future which
+ * completes
+ * once all commits on cohorts are completed.
+ *
+ * Valid state transition is from PRE_COMMIT to COMMIT, if not throws
+ * IllegalStateException
+ *
+ * @return List of all cohorts futures from can commit phase.
+ */
+ private ListenableFuture<?>[] commitAll() {
+ final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohortSize];
+ int i = 0;
+ for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
+ ops[i++] = cohort.commit();
+ }
+ return ops;
+ }
+
+ /**
+ * Aborts transaction.
+ *
+ * Invokes {@link DOMStoreThreePhaseCommitCohort#abort()} on all
+ * cohorts, blocks
+ * for all results. If any of the abort failed throws
+ * IllegalStateException,
+ * which will contains originalCause as suppressed Exception.
+ *
+ * If aborts we're successful throws supplied exception
+ *
+ * @param originalCause
+ * Exception which should be used to fail transaction for
+ * consumers of transaction
+ * future and listeners of transaction failure.
+ * @param phase phase in which the problem ensued
+ * @throws TransactionCommitFailedException
+ * on invocation of this method.
+ * originalCa
+ * @throws IllegalStateException
+ * if abort failed.
+ */
+ private void abortBlocking(final TransactionCommitFailedException originalCause) throws TransactionCommitFailedException {
+ Exception cause = originalCause;
+ try {
+ abortAsyncAll().get();
+ } catch (InterruptedException | ExecutionException e) {
+ LOG.error("Tx: {} Error during Abort.", tx.getIdentifier(), e);
+ cause = new IllegalStateException("Abort failed.", e);
+ cause.addSuppressed(e);
+ }
+ Throwables.propagateIfPossible(cause, TransactionCommitFailedException.class);
+ }
+
+ /**
+ * Invokes abort on underlying cohorts and returns future which
+ * completes once all abort on cohorts are completed.
+ *
+ * @return Future which will complete once all cohorts completed
+ * abort.
+ */
+ private ListenableFuture<Void> abortAsyncAll() {
+
+ final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohortSize];
+ int i = 0;
+ for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
+ ops[i++] = cohort.abort();
+ }
+
+ /*
+ * We are returning all futures as list, not only succeeded ones in
+ * order to fail composite future if any of them failed.
+ * See Futures.allAsList for this description.
+ */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ ListenableFuture<Void> compositeResult = (ListenableFuture) Futures.allAsList(ops);
+ return compositeResult;
+ }
+}
package org.opendaylight.controller.md.sal.dom.broker.impl;
import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
return MappingCheckedFuture.create(commitFuture,
TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
}
-
- /**
- *
- * Phase of 3PC commit
- *
- * Represents phase of 3PC Commit
- *
- *
- */
- private static enum CommitPhase {
- /**
- *
- * Commit Coordination Task is submitted for executing
- *
- */
- SUBMITTED,
- /**
- * Commit Coordination Task is in can commit phase of 3PC
- *
- */
- CAN_COMMIT,
- /**
- * Commit Coordination Task is in pre-commit phase of 3PC
- *
- */
- PRE_COMMIT,
- /**
- * Commit Coordination Task is in commit phase of 3PC
- *
- */
- COMMIT,
- /**
- * Commit Coordination Task is in abort phase of 3PC
- *
- */
- ABORT
- }
-
- /**
- * Implementation of blocking three-phase commit-coordination tasks without
- * support of cancellation.
- */
- private static final class CommitCoordinationTask implements Callable<Void> {
- private static final AtomicReferenceFieldUpdater<CommitCoordinationTask, CommitPhase> PHASE_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(CommitCoordinationTask.class, CommitPhase.class, "currentPhase");
- private final DOMDataWriteTransaction tx;
- private final Iterable<DOMStoreThreePhaseCommitCohort> cohorts;
- private final DurationStatisticsTracker commitStatTracker;
- private final int cohortSize;
- private volatile CommitPhase currentPhase = CommitPhase.SUBMITTED;
-
- public CommitCoordinationTask(final DOMDataWriteTransaction transaction,
- final Iterable<DOMStoreThreePhaseCommitCohort> cohorts,
- final DurationStatisticsTracker commitStatsTracker) {
- this.tx = Preconditions.checkNotNull(transaction, "transaction must not be null");
- this.cohorts = Preconditions.checkNotNull(cohorts, "cohorts must not be null");
- this.commitStatTracker = commitStatsTracker;
- this.cohortSize = Iterables.size(cohorts);
- }
-
- @Override
- public Void call() throws TransactionCommitFailedException {
- final long startTime = commitStatTracker != null ? System.nanoTime() : 0;
-
- try {
- canCommitBlocking();
- preCommitBlocking();
- commitBlocking();
- return null;
- } catch (TransactionCommitFailedException e) {
- final CommitPhase phase = currentPhase;
- LOG.warn("Tx: {} Error during phase {}, starting Abort", tx.getIdentifier(), phase, e);
- abortBlocking(e, phase);
- throw e;
- } finally {
- if (commitStatTracker != null) {
- commitStatTracker.addDuration(System.nanoTime() - startTime);
- }
- }
- }
-
- /**
- *
- * Invokes canCommit on underlying cohorts and blocks till
- * all results are returned.
- *
- * Valid state transition is from SUBMITTED to CAN_COMMIT,
- * if currentPhase is not SUBMITTED throws IllegalStateException.
- *
- * @throws TransactionCommitFailedException
- * If one of cohorts failed can Commit
- *
- */
- private void canCommitBlocking() throws TransactionCommitFailedException {
- for (ListenableFuture<?> canCommit : canCommitAll()) {
- try {
- final Boolean result = (Boolean)canCommit.get();
- if (result == null || !result) {
- throw new TransactionCommitFailedException("Can Commit failed, no detailed cause available.");
- }
- } catch (InterruptedException | ExecutionException e) {
- throw TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER.apply(e);
- }
- }
- }
-
- /**
- *
- * Invokes canCommit on underlying cohorts and returns composite future
- * which will contains {@link Boolean#TRUE} only and only if
- * all cohorts returned true.
- *
- * Valid state transition is from SUBMITTED to CAN_COMMIT,
- * if currentPhase is not SUBMITTED throws IllegalStateException.
- *
- * @return List of all cohorts futures from can commit phase.
- *
- */
- private ListenableFuture<?>[] canCommitAll() {
- changeStateFrom(CommitPhase.SUBMITTED, CommitPhase.CAN_COMMIT);
-
- final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohortSize];
- int i = 0;
- for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
- ops[i++] = cohort.canCommit();
- }
- return ops;
- }
-
- /**
- *
- * Invokes preCommit on underlying cohorts and blocks till
- * all results are returned.
- *
- * Valid state transition is from CAN_COMMIT to PRE_COMMIT, if current
- * state is not CAN_COMMIT
- * throws IllegalStateException.
- *
- * @throws TransactionCommitFailedException
- * If one of cohorts failed preCommit
- *
- */
- private void preCommitBlocking() throws TransactionCommitFailedException {
- final ListenableFuture<?>[] preCommitFutures = preCommitAll();
- try {
- for(ListenableFuture<?> future : preCommitFutures) {
- future.get();
- }
- } catch (InterruptedException | ExecutionException e) {
- throw TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER.apply(e);
- }
- }
-
- /**
- *
- * Invokes preCommit on underlying cohorts and returns future
- * which will complete once all preCommit on cohorts completed or
- * failed.
- *
- *
- * Valid state transition is from CAN_COMMIT to PRE_COMMIT, if current
- * state is not CAN_COMMIT
- * throws IllegalStateException.
- *
- * @return List of all cohorts futures from can commit phase.
- *
- */
- private ListenableFuture<?>[] preCommitAll() {
- changeStateFrom(CommitPhase.CAN_COMMIT, CommitPhase.PRE_COMMIT);
-
- final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohortSize];
- int i = 0;
- for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
- ops[i++] = cohort.preCommit();
- }
- return ops;
- }
-
- /**
- *
- * Invokes commit on underlying cohorts and blocks till
- * all results are returned.
- *
- * Valid state transition is from PRE_COMMIT to COMMIT, if not throws
- * IllegalStateException.
- *
- * @throws TransactionCommitFailedException
- * If one of cohorts failed preCommit
- *
- */
- private void commitBlocking() throws TransactionCommitFailedException {
- final ListenableFuture<?>[] commitFutures = commitAll();
- try {
- for(ListenableFuture<?> future : commitFutures) {
- future.get();
- }
- } catch (InterruptedException | ExecutionException e) {
- throw TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER.apply(e);
- }
- }
-
- /**
- *
- * Invokes commit on underlying cohorts and returns future which
- * completes
- * once all commits on cohorts are completed.
- *
- * Valid state transition is from PRE_COMMIT to COMMIT, if not throws
- * IllegalStateException
- *
- * @return List of all cohorts futures from can commit phase.
- *
- */
- private ListenableFuture<?>[] commitAll() {
- changeStateFrom(CommitPhase.PRE_COMMIT, CommitPhase.COMMIT);
-
- final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohortSize];
- int i = 0;
- for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
- ops[i++] = cohort.commit();
- }
- return ops;
- }
-
- /**
- * Aborts transaction.
- *
- * Invokes {@link DOMStoreThreePhaseCommitCohort#abort()} on all
- * cohorts, blocks
- * for all results. If any of the abort failed throws
- * IllegalStateException,
- * which will contains originalCause as suppressed Exception.
- *
- * If aborts we're successful throws supplied exception
- *
- * @param originalCause
- * Exception which should be used to fail transaction for
- * consumers of transaction
- * future and listeners of transaction failure.
- * @param phase phase in which the problem ensued
- * @throws TransactionCommitFailedException
- * on invocation of this method.
- * originalCa
- * @throws IllegalStateException
- * if abort failed.
- */
- private void abortBlocking(final TransactionCommitFailedException originalCause, final CommitPhase phase)
- throws TransactionCommitFailedException {
- LOG.warn("Tx: {} Error during phase {}, starting Abort", tx.getIdentifier(), phase, originalCause);
- Exception cause = originalCause;
- try {
- abortAsyncAll(phase).get();
- } catch (InterruptedException | ExecutionException e) {
- LOG.error("Tx: {} Error during Abort.", tx.getIdentifier(), e);
- cause = new IllegalStateException("Abort failed.", e);
- cause.addSuppressed(e);
- }
- Throwables.propagateIfPossible(cause, TransactionCommitFailedException.class);
- }
-
- /**
- * Invokes abort on underlying cohorts and returns future which
- * completes once all abort on cohorts are completed.
- *
- * @param phase phase in which the problem ensued
- * @return Future which will complete once all cohorts completed
- * abort.
- */
- private ListenableFuture<Void> abortAsyncAll(final CommitPhase phase) {
- changeStateFrom(phase, CommitPhase.ABORT);
-
- final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohortSize];
- int i = 0;
- for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
- ops[i++] = cohort.abort();
- }
-
- /*
- * We are returning all futures as list, not only succeeded ones in
- * order to fail composite future if any of them failed.
- * See Futures.allAsList for this description.
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- ListenableFuture<Void> compositeResult = (ListenableFuture) Futures.allAsList(ops);
- return compositeResult;
- }
-
- /**
- * Change phase / state of transaction from expected value to new value
- *
- * This method checks state and updates state to new state of
- * of this task if current state equals expected state.
- * If expected state and current state are different raises
- * IllegalStateException
- * which means there is probably bug in implementation of commit
- * coordination.
- *
- * If transition is successful, it logs transition on DEBUG level.
- *
- * @param currentExpected
- * Required phase for change of state
- * @param newState
- * New Phase which will be entered by transaction.
- * @throws IllegalStateException
- * If currentState of task does not match expected state
- */
- private void changeStateFrom(final CommitPhase currentExpected, final CommitPhase newState) {
- final boolean success = PHASE_UPDATER.compareAndSet(this, currentExpected, newState);
- Preconditions.checkState(success, "Invalid state transition: Tx: %s expected: %s current: %s target: %s",
- tx.getIdentifier(), currentExpected, currentPhase, newState);
-
- LOG.debug("Transaction {}: Phase {} Started", tx.getIdentifier(), newState);
- };
- }
-
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.broker.impl;
+
+import com.google.common.base.Preconditions;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.spi.ForwardingDOMDataBroker;
+
+/**
+ * An implementation of a {@link DOMDataBroker}, which forwards most requests to a delegate.
+ *
+ * Its interpretation of the API contract is somewhat looser, specifically it does not
+ * guarantee transaction ordering between transactions allocated directly from the broker
+ * and its transaction chains.
+ */
+public final class PingPongDataBroker extends ForwardingDOMDataBroker implements AutoCloseable {
+ private final DOMDataBroker delegate;
+
+ /**
+ * Instantiate a new broker, backed by the the specified delegate
+ * {@link DOMDataBroker}.
+ *
+ * @param delegate Backend broker, may not be null.
+ */
+ public PingPongDataBroker(final @Nonnull DOMDataBroker delegate) {
+ this.delegate = Preconditions.checkNotNull(delegate);
+ }
+
+ @Override
+ protected DOMDataBroker delegate() {
+ return delegate;
+ }
+
+ @Override
+ public PingPongTransactionChain createTransactionChain(final TransactionChainListener listener) {
+ return new PingPongTransactionChain(delegate, listener);
+ }
+
+ @Override
+ public void close() {
+ // TODO Auto-generated method stub
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.broker.impl;
+
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.AbstractCheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+
+/**
+ * A {@link Future} used to report the status of an future {@link java.util.concurrent.Future}.
+ */
+final class PingPongFuture extends AbstractCheckedFuture<Void, TransactionCommitFailedException> {
+ protected PingPongFuture(final ListenableFuture<Void> delegate) {
+ super(delegate);
+ }
+
+ @Override
+ protected TransactionCommitFailedException mapException(final Exception e) {
+ Preconditions.checkArgument(e instanceof TransactionCommitFailedException);
+ return (TransactionCommitFailedException) e;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.broker.impl;
+
+import com.google.common.base.Objects;
+import com.google.common.base.Objects.ToStringHelper;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.common.impl.service.AbstractDataTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+/**
+ * Transaction context. Tracks the relationship with the backend transaction.
+ * We never leak this class to the user and have it implement the {@link FutureCallback}
+ * interface so we have a simple way of propagating the result.
+ */
+final class PingPongTransaction implements FutureCallback<Void> {
+ private final CheckedFuture<Void, TransactionCommitFailedException> submitFuture;
+ private final ListenableFuture<RpcResult<TransactionStatus>> commitFuture;
+ private final DOMDataReadWriteTransaction delegate;
+ private final SettableFuture<Void> future;
+ private DOMDataReadWriteTransaction frontendTransaction;
+
+ PingPongTransaction(final DOMDataReadWriteTransaction delegate) {
+ this.delegate = Preconditions.checkNotNull(delegate);
+ future = SettableFuture.create();
+ submitFuture = new PingPongFuture(future);
+ commitFuture = AbstractDataTransaction.convertToLegacyCommitFuture(submitFuture);
+ }
+
+ DOMDataReadWriteTransaction getTransaction() {
+ return delegate;
+ }
+
+ DOMDataReadWriteTransaction getFrontendTransaction() {
+ return frontendTransaction;
+ }
+
+ CheckedFuture<Void, TransactionCommitFailedException> getSubmitFuture() {
+ return submitFuture;
+ }
+
+ ListenableFuture<RpcResult<TransactionStatus>> getCommitFuture() {
+ return commitFuture;
+ }
+
+ @Override
+ public void onSuccess(final Void result) {
+ future.set(result);
+ }
+
+ @Override
+ public void onFailure(final Throwable t) {
+ future.setException(t);
+ }
+
+ void recordFrontendTransaction(final DOMDataReadWriteTransaction tx) {
+ if (frontendTransaction != null) {
+ frontendTransaction = tx;
+ }
+ }
+
+ @Override
+ public String toString() {
+ return addToStringAttributes(Objects.toStringHelper(this)).toString();
+ }
+
+ protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
+ return toStringHelper.add("delegate", delegate);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.broker.impl;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import javax.annotation.concurrent.GuardedBy;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
+import org.opendaylight.controller.md.sal.dom.spi.ForwardingDOMDataReadWriteTransaction;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An implementation of {@link DOMTransactionChain}, which has a very specific
+ * behavior, which some users may find surprising. If keeps the general
+ * intent of the contract, but it makes sure there are never more than two
+ * transactions allocated at any given time: one of them is being committed,
+ * and while that is happening, the other one acts as the scratch pad. Once
+ * the committing transaction completes successfully, the scratch transaction
+ * is enqueued as soon as it is ready.
+ *
+ * This mode of operation means that there is no inherent isolation between
+ * the front-end transactions and transactions cannot be reasonably cancelled.
+ *
+ * It furthermore means that the transactions returned by {@link #newReadOnlyTransaction()}
+ * counts as an outstanding transaction and the user may not allocate multiple
+ * read-only transactions at the same time.
+ */
+public final class PingPongTransactionChain implements DOMTransactionChain {
+ private static final Logger LOG = LoggerFactory.getLogger(PingPongTransactionChain.class);
+ private final DOMTransactionChain delegate;
+
+ @GuardedBy("this")
+ private PingPongTransaction bufferTransaction;
+ @GuardedBy("this")
+ private PingPongTransaction inflightTransaction;
+ @GuardedBy("this")
+ private boolean haveLocked;
+ @GuardedBy("this")
+ private boolean failed;
+
+ PingPongTransactionChain(final DOMDataBroker broker, final TransactionChainListener listener) {
+ this.delegate = broker.createTransactionChain(new TransactionChainListener() {
+ @Override
+ public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
+ LOG.debug("Delegate chain {} reported failure in {}", chain, transaction, cause);
+
+ final DOMDataReadWriteTransaction frontend;
+ if (inflightTransaction == null) {
+ LOG.warn("Transaction chain {} failed with no pending transactions", chain);
+ frontend = null;
+ } else {
+ frontend = inflightTransaction.getFrontendTransaction();
+ }
+
+ listener.onTransactionChainFailed(PingPongTransactionChain.this, frontend , cause);
+ delegateFailed();
+ }
+
+ @Override
+ public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
+ listener.onTransactionChainSuccessful(PingPongTransactionChain.this);
+ }
+ });
+ }
+
+ private synchronized void delegateFailed() {
+ failed = true;
+ if (!haveLocked) {
+ processBuffer();
+ }
+ }
+
+ private synchronized PingPongTransaction allocateTransaction() {
+ Preconditions.checkState(!haveLocked, "Attempted to start a transaction while a previous one is still outstanding");
+ Preconditions.checkState(!failed, "Attempted to use a failed chain");
+
+ if (bufferTransaction == null) {
+ bufferTransaction = new PingPongTransaction(delegate.newReadWriteTransaction());
+ }
+
+ haveLocked = true;
+ return bufferTransaction;
+ }
+
+ @GuardedBy("this")
+ private void processBuffer() {
+ final PingPongTransaction tx = bufferTransaction;
+
+ if (tx != null) {
+ if (failed) {
+ LOG.debug("Cancelling transaction {}", tx);
+ tx.getTransaction().cancel();
+ bufferTransaction = null;
+ return;
+ }
+
+ LOG.debug("Submitting transaction {}", tx);
+ final CheckedFuture<Void, ?> f = tx.getTransaction().submit();
+ bufferTransaction = null;
+ inflightTransaction = tx;
+
+ Futures.addCallback(f, new FutureCallback<Void>() {
+ @Override
+ public void onSuccess(final Void result) {
+ transactionSuccessful(tx, result);
+ }
+
+ @Override
+ public void onFailure(final Throwable t) {
+ transactionFailed(tx, t);
+ }
+ });
+ }
+ }
+
+ private void transactionSuccessful(final PingPongTransaction tx, final Void result) {
+ LOG.debug("Transaction {} completed successfully", tx);
+
+ synchronized (this) {
+ Preconditions.checkState(inflightTransaction == tx, "Successful transaction %s while %s was submitted", tx, inflightTransaction);
+ inflightTransaction = null;
+
+ if (!haveLocked) {
+ processBuffer();
+ }
+ }
+
+ // Can run unsynchronized
+ tx.onSuccess(result);
+ }
+
+ private void transactionFailed(final PingPongTransaction tx, final Throwable t) {
+ LOG.debug("Transaction {} failed", tx, t);
+
+ synchronized (this) {
+ Preconditions.checkState(inflightTransaction == tx, "Failed transaction %s while %s was submitted", tx, inflightTransaction);
+ inflightTransaction = null;
+ }
+
+ tx.onFailure(t);
+ }
+
+ private synchronized void readyTransaction(final PingPongTransaction tx) {
+ Preconditions.checkState(haveLocked, "Attempted to submit transaction while it is not outstanding");
+ Preconditions.checkState(bufferTransaction == tx, "Attempted to submit transaction %s while we have %s", tx, bufferTransaction);
+
+ haveLocked = false;
+ LOG.debug("Transaction {} unlocked", bufferTransaction);
+
+ if (inflightTransaction == null) {
+ processBuffer();
+ }
+ }
+
+ @Override
+ public synchronized void close() {
+ Preconditions.checkState(!haveLocked, "Attempted to close chain while a transaction is outstanding");
+ processBuffer();
+ delegate.close();
+ }
+
+ @Override
+ public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
+ final PingPongTransaction tx = allocateTransaction();
+
+ return new DOMDataReadOnlyTransaction() {
+ @Override
+ public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
+ return tx.getTransaction().read(store, path);
+ }
+
+ @Override
+ public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
+ return tx.getTransaction().exists(store, path);
+ }
+
+ @Override
+ public Object getIdentifier() {
+ return tx.getTransaction().getIdentifier();
+ }
+
+ @Override
+ public void close() {
+ readyTransaction(tx);
+ }
+ };
+ }
+
+ @Override
+ public DOMDataReadWriteTransaction newReadWriteTransaction() {
+ final PingPongTransaction tx = allocateTransaction();
+ final DOMDataReadWriteTransaction ret = new ForwardingDOMDataReadWriteTransaction() {
+ @Override
+ protected DOMDataReadWriteTransaction delegate() {
+ return tx.getTransaction();
+ }
+
+ @Override
+ public CheckedFuture<Void, TransactionCommitFailedException> submit() {
+ readyTransaction(tx);
+ return tx.getSubmitFuture();
+ }
+
+ @Override
+ public ListenableFuture<RpcResult<TransactionStatus>> commit() {
+ readyTransaction(tx);
+ return tx.getCommitFuture();
+ }
+
+ @Override
+ public boolean cancel() {
+ throw new UnsupportedOperationException("Transaction cancellation is not supported");
+ }
+ };
+
+ tx.recordFrontendTransaction(ret);
+ return ret;
+ }
+
+ @Override
+ public DOMDataWriteTransaction newWriteOnlyTransaction() {
+ return newReadWriteTransaction();
+ }
+}
package org.opendaylight.controller.md.sal.dom.broker.impl.compat;
import javax.annotation.concurrent.ThreadSafe;
-
import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandlerRegistration;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+@Deprecated
@ThreadSafe
public class BackwardsCompatibleDataBroker implements DataProviderService {
package org.opendaylight.controller.md.sal.dom.broker.impl.compat;
import static com.google.common.base.Preconditions.checkNotNull;
-
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
-
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.impl.service.AbstractDataTransaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.ListenableFuture;
-
-public abstract class BackwardsCompatibleTransaction<T extends DOMDataReadTransaction> implements
-DataModificationTransaction, Delegator<T> {
+@Deprecated
+public abstract class BackwardsCompatibleTransaction<T extends DOMDataReadTransaction> implements DataModificationTransaction, Delegator<T> {
private static final Logger LOG = LoggerFactory.getLogger(BackwardsCompatibleTransaction.class);
*/
package org.opendaylight.controller.md.sal.dom.broker.impl.compat;
+import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import com.google.common.collect.Maps;
-
-public abstract class TranslatingDataChangeEvent implements
-DataChangeEvent<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> {
+@Deprecated
+public abstract class TranslatingDataChangeEvent implements DataChangeEvent<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> {
private TranslatingDataChangeEvent() {
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+@Deprecated
abstract class TranslatingListenerInvoker implements AutoCloseable, DOMDataChangeListener, Delegator<DataChangeListener> {
private final DataChangeListener delegate;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.JdkFutureAdapters;
import com.google.common.util.concurrent.ListenableFuture;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
import org.opendaylight.controller.sal.core.api.notify.NotificationPublishService;
import org.opendaylight.controller.sal.dom.broker.impl.NotificationRouterImpl;
import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
import org.opendaylight.controller.sal.dom.broker.spi.NotificationRouter;
import org.opendaylight.controller.sal.dom.broker.util.ProxySchemaContext;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-import javax.annotation.Nullable;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ExecutionException;
-
+@Deprecated
public class BackwardsCompatibleMountPoint implements MountProvisionInstance, SchemaContextProvider, SchemaService {
private final DataProviderService dataReader;
class ReadWrapper implements DataReader<YangInstanceIdentifier, CompositeNode> {
private YangInstanceIdentifier shortenPath(final YangInstanceIdentifier path) {
- YangInstanceIdentifier ret = null;
- if(mountPath.contains(path)) {
- final List<PathArgument> newArgs = path.getPath().subList(mountPath.getPath().size(), path.getPath().size());
- ret = YangInstanceIdentifier.create(newArgs);
+ if (!mountPath.contains(path)) {
+ return null;
}
- return ret;
+ return YangInstanceIdentifier.create(Iterables.skip(path.getPathArguments(), Iterables.size(mountPath.getPathArguments())));
}
@Override
return Futures.immediateCheckedFuture(normalizedNodeOptional);
}
- @Override public CheckedFuture<Boolean, ReadFailedException> exists(LogicalDatastoreType store,
- YangInstanceIdentifier path) {
+ @Override public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
try {
return Futures.immediateCheckedFuture(read(store, path).get().isPresent());
return new BackwardsCompatibleReadTransaction(dataReader, dataNormalizer).read(store, path);
}
- @Override public CheckedFuture<Boolean, ReadFailedException> exists(LogicalDatastoreType store,
- YangInstanceIdentifier path) {
+ @Override public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
try {
return Futures.immediateCheckedFuture(read(store, path).get().isPresent());
import org.opendaylight.yangtools.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+@Deprecated
public class BackwardsCompatibleMountPointManager implements MountProvisionService, MountProvisionListener {
private final ListenerRegistry<MountProvisionListener> listeners = ListenerRegistry.create();
import com.google.common.util.concurrent.MoreExecutors;
+@Deprecated
public class DataBrokerImpl extends AbstractDataBroker<YangInstanceIdentifier, CompositeNode, DataChangeListener> implements
DataProviderService, AutoCloseable {
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+@Deprecated
public class DataTransactionImpl extends AbstractDataTransaction<YangInstanceIdentifier, CompositeNode>
implements DataModificationTransaction {
private final ListenerRegistry<DataTransactionListener> listeners = new ListenerRegistry<DataTransactionListener>();
package org.opendaylight.controller.sal.dom.broker;
import static com.google.common.base.Preconditions.checkState;
-
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
-
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
-
import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
import org.opendaylight.yangtools.yang.parser.repo.URLSchemaContextResolver;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
*/
package org.opendaylight.controller.sal.dom.broker;
-import java.util.List;
+import com.google.common.collect.Iterables;
+import com.google.common.util.concurrent.ListenableFuture;
import java.util.Set;
-
import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandlerRegistration;
import org.opendaylight.controller.sal.core.api.notify.NotificationListener;
import org.opendaylight.controller.sal.dom.broker.impl.NotificationRouterImpl;
import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
import org.opendaylight.controller.sal.dom.broker.spi.NotificationRouter;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
-import com.google.common.util.concurrent.ListenableFuture;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
@Deprecated
public class MountPointImpl implements MountProvisionInstance, SchemaContextProvider {
class ReadWrapper implements DataReader<YangInstanceIdentifier, CompositeNode> {
private YangInstanceIdentifier shortenPath(final YangInstanceIdentifier path) {
- YangInstanceIdentifier ret = null;
- if(mountPath.contains(path)) {
- List<PathArgument> newArgs = path.getPath().subList(mountPath.getPath().size(), path.getPath().size());
- ret = YangInstanceIdentifier.create(newArgs);
+ if (!mountPath.contains(path)) {
+ return null;
}
- return ret;
+
+ return YangInstanceIdentifier.create(Iterables.skip(path.getPathArguments(), Iterables.size(mountPath.getPathArguments())));
}
@Override
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class DataReaderRouter extends
-AbstractDataReadRouter<YangInstanceIdentifier, CompositeNode> {
+@Deprecated
+public class DataReaderRouter extends AbstractDataReadRouter<YangInstanceIdentifier, CompositeNode> {
private final static Logger LOG = LoggerFactory
.getLogger(DataReaderRouter.class);
private final static URI NETCONF_NAMESPACE = URI
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+@Deprecated
public class DataStoreStatsWrapper implements Delegator<DataStore>, DataStore {
private final DataStore delegate;
package org.opendaylight.controller.sal.dom.broker.impl;
import static com.google.common.base.Preconditions.checkState;
-
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
-
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
-
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
import org.opendaylight.controller.md.sal.common.api.data.DataModification;
import org.opendaylight.controller.md.sal.common.api.data.DataReader;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class SchemaAwareDataStoreAdapter extends AbstractLockableDelegator<DataStore> implements //
-DataStore, //
-SchemaContextListener, //
-AutoCloseable {
+@Deprecated
+public class SchemaAwareDataStoreAdapter extends AbstractLockableDelegator<DataStore> implements DataStore, SchemaContextListener, AutoCloseable {
private final static Logger LOG = LoggerFactory.getLogger(SchemaAwareDataStoreAdapter.class);
public int compare(final Entry<YangInstanceIdentifier, CompositeNode> o1, final Entry<YangInstanceIdentifier, CompositeNode> o2) {
YangInstanceIdentifier o1Key = o1.getKey();
YangInstanceIdentifier o2Key = o2.getKey();
- return Integer.compare(o1Key.getPath().size(), o2Key.getPath().size());
+ return Integer.compare(Iterables.size(o1Key.getPathArguments()), Iterables.size(o2Key.getPathArguments()));
}
};
childNodes.addAll(original.getValue());
qname = original.getNodeType();
} else {
- qname = path.getPath().get(path.getPath().size() - 1).getNodeType();
+ qname = path.getLastPathArgument().getNodeType();
}
FluentIterable<YangInstanceIdentifier> directChildren = FluentIterable.from(getStoredConfigurationPaths())
@Override
public boolean apply(final YangInstanceIdentifier input) {
if (path.contains(input)) {
- int nesting = input.getPath().size() - path.getPath().size();
+ int nesting = Iterables.size(input.getPathArguments()) - Iterables.size(path.getPathArguments());
if (nesting == 1) {
return true;
}
childNodes.addAll(original.getValue());
qname = original.getNodeType();
} else {
- qname = path.getPath().get(path.getPath().size() - 1).getNodeType();
+ qname = path.getLastPathArgument().getNodeType();
}
FluentIterable<YangInstanceIdentifier> directChildren = FluentIterable.from(getStoredOperationalPaths())
@Override
public boolean apply(final YangInstanceIdentifier input) {
if (path.contains(input)) {
- int nesting = input.getPath().size() - path.getPath().size();
+ int nesting = Iterables.size(input.getPathArguments()) - Iterables.size(path.getPathArguments());
if (nesting == 1) {
return true;
}
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
-
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-
import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.yangtools.concepts.Delegator;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
public class SchemaContextProviders {
- public static final SchemaContextProvider fromSchemaService(SchemaService schemaService) {
+ public static final SchemaContextProvider fromSchemaService(final SchemaService schemaService) {
if (schemaService instanceof SchemaContextProvider) {
return (SchemaContextProvider) schemaService;
}
private final SchemaService service;
- public SchemaServiceAdapter(SchemaService service) {
+ public SchemaServiceAdapter(final SchemaService service) {
super();
this.service = service;
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.osgi.framework.ServiceReference;
+@Deprecated
public class DataBrokerServiceProxy extends AbstractBrokerServiceProxy<DataBrokerService> implements DataBrokerService {
public DataBrokerServiceProxy(ServiceReference<DataBrokerService> ref, DataBrokerService delegate) {
public DataModificationTransaction beginTransaction() {
return getDelegate().beginTransaction();
}
-
-
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.osgi.framework.ServiceReference;
-public class DataProviderServiceProxy extends AbstractBrokerServiceProxy<DataProviderService> implements
- DataProviderService {
+@Deprecated
+public class DataProviderServiceProxy extends AbstractBrokerServiceProxy<DataProviderService> implements DataProviderService {
- public DataProviderServiceProxy(ServiceReference<DataProviderService> ref, DataProviderService delegate) {
+ public DataProviderServiceProxy(final ServiceReference<DataProviderService> ref, final DataProviderService delegate) {
super(ref, delegate);
}
- public ListenerRegistration<DataChangeListener> registerDataChangeListener(YangInstanceIdentifier path,
- DataChangeListener listener) {
+ @Override
+ public ListenerRegistration<DataChangeListener> registerDataChangeListener(final YangInstanceIdentifier path,
+ final DataChangeListener listener) {
return addRegistration(getDelegate().registerDataChangeListener(path, listener));
}
- public CompositeNode readConfigurationData(YangInstanceIdentifier path) {
+ @Override
+ public CompositeNode readConfigurationData(final YangInstanceIdentifier path) {
return getDelegate().readConfigurationData(path);
}
- public CompositeNode readOperationalData(YangInstanceIdentifier path) {
+ @Override
+ public CompositeNode readOperationalData(final YangInstanceIdentifier path) {
return getDelegate().readOperationalData(path);
}
+ @Override
public DataModificationTransaction beginTransaction() {
return getDelegate().beginTransaction();
}
@Override
- public void addRefresher(DataStoreIdentifier store, DataRefresher refresher) {
+ public void addRefresher(final DataStoreIdentifier store, final DataRefresher refresher) {
getDelegate().addRefresher(store, refresher);
}
@Override
- public void addValidator(DataStoreIdentifier store, DataValidator validator) {
+ public void addValidator(final DataStoreIdentifier store, final DataValidator validator) {
getDelegate().addValidator(store, validator);
}
@Override
public Registration registerCommitHandler(
- YangInstanceIdentifier path, DataCommitHandler<YangInstanceIdentifier, CompositeNode> commitHandler) {
+ final YangInstanceIdentifier path, final DataCommitHandler<YangInstanceIdentifier, CompositeNode> commitHandler) {
return addRegistration(getDelegate().registerCommitHandler(path, commitHandler));
}
@Override
public Registration registerConfigurationReader(
- YangInstanceIdentifier path, DataReader<YangInstanceIdentifier, CompositeNode> reader) {
+ final YangInstanceIdentifier path, final DataReader<YangInstanceIdentifier, CompositeNode> reader) {
return addRegistration(getDelegate().registerConfigurationReader(path, reader));
}
@Override
public Registration registerOperationalReader(
- YangInstanceIdentifier path, DataReader<YangInstanceIdentifier, CompositeNode> reader) {
+ final YangInstanceIdentifier path, final DataReader<YangInstanceIdentifier, CompositeNode> reader) {
return addRegistration(getDelegate().registerOperationalReader(path, reader));
}
@Override
- public void removeRefresher(DataStoreIdentifier store, DataRefresher refresher) {
+ public void removeRefresher(final DataStoreIdentifier store, final DataRefresher refresher) {
getDelegate().removeRefresher(store, refresher);
}
@Override
- public void removeValidator(DataStoreIdentifier store, DataValidator validator) {
+ public void removeValidator(final DataStoreIdentifier store, final DataValidator validator) {
getDelegate().removeValidator(store, validator);
}
@Override
public ListenerRegistration<RegistrationListener<DataCommitHandlerRegistration<YangInstanceIdentifier, CompositeNode>>> registerCommitHandlerListener(
- RegistrationListener<DataCommitHandlerRegistration<YangInstanceIdentifier, CompositeNode>> commitHandlerListener) {
+ final RegistrationListener<DataCommitHandlerRegistration<YangInstanceIdentifier, CompositeNode>> commitHandlerListener) {
return addRegistration(getDelegate().registerCommitHandlerListener(commitHandlerListener));
}
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.osgi.framework.ServiceReference;
+@Deprecated
public class MountProviderServiceProxy extends AbstractBrokerServiceProxy<MountProvisionService> implements MountProvisionService{
return ((T) _createProxyImpl);
}
+ @Deprecated
private static Object _createProxyImpl(final ServiceReference<?> ref,
final DataBrokerService service) {
((ServiceReference<DataBrokerService>) ref), service);
}
+ @Deprecated
private static Object _createProxyImpl(final ServiceReference<?> ref,
final DataProviderService service) {
((ServiceReference<NotificationService>) ref), service);
}
+ @Deprecated
private static Object _createProxyImpl(final ServiceReference<?> ref,
final MountProvisionService service) {
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+@Deprecated
public class YangDataOperations {
public static CompositeNode merge(final DataSchemaNode schema,
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+@Deprecated
public final class YangDataUtils {
private YangDataUtils() {
--- /dev/null
+module opendaylight-pingpong-broker {
+ yang-version 1;
+ namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:pingpong";
+ prefix "pingpong";
+
+ import config { prefix config; revision-date 2013-04-05; }
+ import opendaylight-md-sal-dom {prefix sal;}
+ import opendaylight-md-sal-common {prefix common;}
+ import opendaylight-config-dom-datastore {prefix config-dom-store-spi;}
+ import opendaylight-operational-dom-datastore {prefix operational-dom-store-spi;}
+
+ description
+ "Service definition for Ping-Pong DOM broker";
+
+ revision "2014-11-07" {
+ description
+ "Initial revision";
+ }
+
+ identity pingpong-data-broker {
+ base config:module-type;
+ config:provided-service sal:dom-async-data-broker;
+ }
+
+ augment "/config:modules/config:module/config:configuration" {
+ case pingpong-data-broker {
+ when "/config:modules/config:module/config:type = 'pingpong-data-broker'";
+
+ container data-broker {
+ uses config:service-ref {
+ refine type {
+ mandatory true;
+ config:required-identity sal:dom-async-data-broker;
+ }
+ }
+ }
+ }
+ }
+}
import static org.junit.Assert.assertTrue;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-
public class DOMBrokerPerformanceTest {
private static final Logger log = LoggerFactory.getLogger(DOMBrokerPerformanceTest.class);
@Before
public void setupStore() {
- InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
- InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
schemaContext = TestModel.createTestContext();
operStore.onGlobalContextUpdated(schemaContext);
public void setupStore() {
InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ MoreExecutors.sameThreadExecutor());
InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ MoreExecutors.sameThreadExecutor());
schemaContext = TestModel.createTestContext();
operStore.onGlobalContextUpdated(schemaContext);
import static org.junit.Assert.fail;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-
public class DOMTransactionChainTest {
private SchemaContext schemaContext;
@Before
public void setupStore() {
- InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
- InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
schemaContext = TestModel.createTestContext();
operStore.onGlobalContextUpdated(schemaContext);
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@Deprecated
public class BackwardsCompatibleMountPointManagerTest {
private static final Logger log = LoggerFactory.getLogger(BackwardsCompatibleMountPointManagerTest.class);
import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction;
import org.opendaylight.controller.sal.core.api.data.DataProviderService;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
return result;
} else if (Map.class.isAssignableFrom(o.getClass())) {
- Map map = (Map) o;
+ Map<?, ?> map = (Map<?, ?>) o;
for (Object oo : map.values()) {
addToResult(result, execute(oo));
}
result.add(oo);
}
} else if (Map.class.isAssignableFrom(o.getClass())) {
- Map map = (Map) o;
+ Map<?, ?> map = (Map<?, ?>) o;
for (Object oo : map.values()) {
result.add(oo);
}
public static final int TYPE_METADATA_REPLY = 7;
private JDBCResultSet rs = null;
- private Map record = null;
+ private Map<String, Object> record = null;
private int rsID = -1;
private Exception err = null;
private XSQLBluePrint bluePrint = null;
this.rsID = rs.getID();
}
- public JDBCCommand(Map _record, int _rsID) {
+ public JDBCCommand(Map<String, Object> _record, int _rsID) {
this.record = _record;
this.rsID = _rsID;
this.type = TYPE_QUERY_RECORD;
return this.rs;
}
- public Map getRecord() {
+ public Map<String, Object> getRecord() {
return this.record;
}
private List<XSQLBluePrintNode> tablesInQuery = new ArrayList<XSQLBluePrintNode>();
private Map<String, XSQLBluePrintNode> tablesInQueryMap = new ConcurrentHashMap<String, XSQLBluePrintNode>();
private List<XSQLColumn> fieldsInQuery = new ArrayList<XSQLColumn>();
- private transient LinkedList<Map> records = new LinkedList<Map>();
- private transient Map currentRecord = null;
+ private transient LinkedList<Map<String, Object>> records = new LinkedList<>();
+ private transient Map<String, Object> currentRecord = null;
private boolean finished = false;
private int id = 0;
private static Integer nextID = new Integer(0);
}
}
- public int isObjectFitCriteria(Map objValues, String tableName) {
+ public int isObjectFitCriteria(Map<String, Object> objValues, String tableName) {
Map<XSQLColumn, List<XSQLCriteria>> tblCriteria = criteria
.get(tableName);
if (tblCriteria == null) {
return this.records.size();
}
- public void addRecord(Map r) {
+ public void addRecord(Map<String, Object> r) {
synchronized (this) {
if (records == null) {
- records = new LinkedList<Map>();
+ records = new LinkedList<>();
}
records.add(r);
this.notifyAll();
}
public void addRecord(ArrayList<?> hierarchy) {
- Map rec = new HashMap();
+ Map<String, Object> rec = new HashMap<>();
for (int i = hierarchy.size() - 1; i >= 0; i--) {
Object element = hierarchy.get(i);
for (XSQLColumn c : fieldsInQuery) {
public boolean next() {
this.currentRecord = null;
if (records == null) {
- records = new LinkedList<Map>();
+ records = new LinkedList<>();
}
while (!finished || records.size() > 0) {
synchronized (this) {
return false;
}
- public Map getCurrent() {
+ public Map<String, Object> getCurrent() {
return this.currentRecord;
}
private void createRecord(Object data, XSQLBluePrintNode node) {
- Map rec = new HashMap();
+ Map<String, Object> rec = new HashMap<>();
for (XSQLColumn c : this.fieldsInQuery) {
if (c.getTableName().equals(node.getBluePrintNodeName())) {
try {
}
public static class Record {
- public Map data = new HashMap();
+ public Map<String, Object> data = new HashMap<>();
public Object element = null;
- public Map getRecord() {
+ public Map<String, Object> getRecord() {
return this.data;
}
}
- private Map collectColumnValues(Object node, XSQLBluePrintNode bpn) {
- Map subChildren = XSQLODLUtils.getChildren(node);
- Map result = new HashMap();
+ private Map<String, Object> collectColumnValues(Object node, XSQLBluePrintNode bpn) {
+ Map<?, ?> subChildren = XSQLODLUtils.getChildren(node);
+ Map<String, Object> result = new HashMap<>();
for (Object stc : subChildren.values()) {
if (stc.getClass().getName().endsWith("ImmutableAugmentationNode")) {
- Map values = XSQLODLUtils.getChildren(stc);
+ Map<?, ?> values = XSQLODLUtils.getChildren(stc);
for (Object key : values.keySet()) {
Object val = values.get(key);
if (val.getClass().getName().endsWith("ImmutableLeafNode")) {
}
private void addToData(Record rec, XSQLBluePrintNode bpn,
- XSQLBluePrint bluePrint, Map fullRecord) {
+ XSQLBluePrint bluePrint, Map<String, Object> fullRecord) {
XSQLBluePrintNode eNodes[] = bluePrint
.getBluePrintNodeByODLTableName(XSQLODLUtils
.getNodeIdentiofier(rec.element));
.getBluePrintNodeName());
if (this.criteria.containsKey(bluePrintNode.getBluePrintNodeName())
|| bpn != null) {
- Map<?, ?> allKeyValues = collectColumnValues(element, bpn);
+ Map<String, Object> allKeyValues = collectColumnValues(element, bpn);
if (!(isObjectFitCriteria(allKeyValues,
bpn.getBluePrintNodeName()) == 1)) {
return EMPTY_RESULT;
}
boolean isObjectInCriteria = true;
if (bpn != null) {
- Map allKeyValues = collectColumnValues(rec.element, bpn);
+ Map<String, Object> allKeyValues = collectColumnValues(rec.element, bpn);
if ((isObjectFitCriteria(allKeyValues,
bpn.getBluePrintNodeName()) == 1)) {
addToData(rec, bpn, bluePrint, allKeyValues);
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
-
import org.opendaylight.controller.md.sal.dom.xsql.XSQLAdapter;
import org.opendaylight.controller.md.sal.dom.xsql.XSQLBluePrint;
import org.opendaylight.controller.md.sal.dom.xsql.XSQLBluePrintNode;
}
rs.getFields().addAll(entry.getValue().getFields());
while (entry.getValue().next()) {
- Map rec = entry.getValue().getCurrent();
- Map newRec = new HashMap();
+ Map<String, Object> rec = entry.getValue().getCurrent();
+ Map<String, Object> newRec = new HashMap<>();
newRec.putAll(rec);
rs.addRecord(newRec);
}
rs.getFields().addAll(columnOrder);
for (Map.Entry<String, JDBCResultSet> entry : rs.getSubQueries().entrySet()) {
while (entry.getValue().next()) {
- Map rec = entry.getValue().getCurrent();
- Map newRec = new HashMap();
- for (Iterator<?> iter = rec.entrySet().iterator(); iter.hasNext();) {
- Map.Entry e = (Map.Entry) iter.next();
- String key = (String) e.getKey();
+ Map<String, Object> rec = entry.getValue().getCurrent();
+ Map<String, Object> newRec = new HashMap<>();
+ for (Map.Entry<String, Object> e : rec.entrySet()) {
Object value = e.getValue();
- String logicalKey = origNameToName.get(key);
+ String logicalKey = origNameToName.get(e.getKey());
if (value != null && logicalKey != null) {
newRec.put(logicalKey, value);
}
getMaxDataChangeExecutorQueueSize(), getMaxDataChangeListenerQueueSize(),
getMaxDataStoreExecutorQueueSize()));
- InMemoryDataStoreStats statsBean = new InMemoryDataStoreStats("InMemoryConfigDataStore",
- dataStore.getDataChangeListenerNotificationManager(), dataStore.getDomStoreExecutor());
-
+ InMemoryDataStoreStats statsBean = new InMemoryDataStoreStats("InMemoryConfigDataStore", dataStore);
dataStore.setCloseable(statsBean);
return dataStore;
getMaxDataStoreExecutorQueueSize()));
- InMemoryDataStoreStats statsBean = new InMemoryDataStoreStats("InMemoryOperationalDataStore",
- dataStore.getDataChangeListenerNotificationManager(), dataStore.getDomStoreExecutor());
+ InMemoryDataStoreStats statsBean = new InMemoryDataStoreStats("InMemoryOperationalDataStore", dataStore);
dataStore.setCloseable(statsBean);
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class InMemoryDOMDataStore extends TransactionReadyPrototype implements DOMStore, Identifiable<String>, SchemaContextListener, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(InMemoryDOMDataStore.class);
private static final ListenableFuture<Void> SUCCESSFUL_FUTURE = Futures.immediateFuture(null);
+ private static final ListenableFuture<Boolean> CAN_COMMIT_FUTURE = Futures.immediateFuture(Boolean.TRUE);
private static final Invoker<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> DCL_NOTIFICATION_MGR_INVOKER =
new Invoker<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent>() {
private final QueuedNotificationManager<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> dataChangeListenerNotificationManager;
private final ExecutorService dataChangeListenerExecutor;
- private final ListeningExecutorService commitExecutor;
private final boolean debugTransactions;
private final String name;
private volatile AutoCloseable closeable;
- public InMemoryDOMDataStore(final String name, final ListeningExecutorService commitExecutor,
- final ExecutorService dataChangeListenerExecutor) {
- this(name, commitExecutor, dataChangeListenerExecutor,
- InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_LISTENER_QUEUE_SIZE, false);
+ public InMemoryDOMDataStore(final String name, final ExecutorService dataChangeListenerExecutor) {
+ this(name, dataChangeListenerExecutor, InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_LISTENER_QUEUE_SIZE, false);
}
- public InMemoryDOMDataStore(final String name, final ListeningExecutorService commitExecutor,
- final ExecutorService dataChangeListenerExecutor, final int maxDataChangeListenerQueueSize,
- final boolean debugTransactions) {
+ public InMemoryDOMDataStore(final String name, final ExecutorService dataChangeListenerExecutor,
+ final int maxDataChangeListenerQueueSize, final boolean debugTransactions) {
this.name = Preconditions.checkNotNull(name);
- this.commitExecutor = Preconditions.checkNotNull(commitExecutor);
this.dataChangeListenerExecutor = Preconditions.checkNotNull(dataChangeListenerExecutor);
this.debugTransactions = debugTransactions;
return dataChangeListenerNotificationManager;
}
- public ExecutorService getDomStoreExecutor() {
- return commitExecutor;
- }
-
@Override
public final String getIdentifier() {
return name;
@Override
public void close() {
- ExecutorServiceUtil.tryGracefulShutdown(commitExecutor, 30, TimeUnit.SECONDS);
ExecutorServiceUtil.tryGracefulShutdown(dataChangeListenerExecutor, 30, TimeUnit.SECONDS);
if(closeable != null) {
@Override
public ListenableFuture<Boolean> canCommit() {
- return commitExecutor.submit(new Callable<Boolean>() {
- @Override
- public Boolean call() throws TransactionCommitFailedException {
- try {
- dataTree.validate(modification);
- LOG.debug("Store Transaction: {} can be committed", transaction.getIdentifier());
- return true;
- } catch (ConflictingModificationAppliedException e) {
- LOG.warn("Store Tx: {} Conflicting modification for {}.", transaction.getIdentifier(),
- e.getPath());
- transaction.warnDebugContext(LOG);
- throw new OptimisticLockFailedException("Optimistic lock failed.",e);
- } catch (DataValidationFailedException e) {
- LOG.warn("Store Tx: {} Data Precondition failed for {}.", transaction.getIdentifier(),
- e.getPath(), e);
- transaction.warnDebugContext(LOG);
- throw new TransactionCommitFailedException("Data did not pass validation.",e);
- }
- }
- });
+ try {
+ dataTree.validate(modification);
+ LOG.debug("Store Transaction: {} can be committed", transaction.getIdentifier());
+ return CAN_COMMIT_FUTURE;
+ } catch (ConflictingModificationAppliedException e) {
+ LOG.warn("Store Tx: {} Conflicting modification for {}.", transaction.getIdentifier(),
+ e.getPath());
+ transaction.warnDebugContext(LOG);
+ return Futures.immediateFailedFuture(new OptimisticLockFailedException("Optimistic lock failed.", e));
+ } catch (DataValidationFailedException e) {
+ LOG.warn("Store Tx: {} Data Precondition failed for {}.", transaction.getIdentifier(),
+ e.getPath(), e);
+ transaction.warnDebugContext(LOG);
+ return Futures.immediateFailedFuture(new TransactionCommitFailedException("Data did not pass validation.", e));
+ } catch (Exception e) {
+ LOG.warn("Unexpected failure in validation phase", e);
+ return Futures.immediateFailedFuture(e);
+ }
}
@Override
public ListenableFuture<Void> preCommit() {
- return commitExecutor.submit(new Callable<Void>() {
- @Override
- public Void call() {
- candidate = dataTree.prepare(modification);
- listenerResolver = ResolveDataChangeEventsTask.create(candidate, listenerTree);
- return null;
- }
- });
+ try {
+ candidate = dataTree.prepare(modification);
+ listenerResolver = ResolveDataChangeEventsTask.create(candidate, listenerTree);
+ return SUCCESSFUL_FUTURE;
+ } catch (Exception e) {
+ LOG.warn("Unexpected failure in pre-commit phase", e);
+ return Futures.immediateFailedFuture(e);
+ }
}
@Override
*/
package org.opendaylight.controller.md.sal.dom.store.impl;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.ExecutorService;
import javax.annotation.Nullable;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
ExecutorService dataChangeListenerExecutor = SpecialExecutors.newBlockingBoundedFastThreadPool(
dclExecutorMaxPoolSize, dclExecutorMaxQueueSize, name + "-DCL" );
- final ListeningExecutorService commitExecutor = MoreExecutors.sameThreadExecutor();
- final InMemoryDOMDataStore dataStore = new InMemoryDOMDataStore(name,
- commitExecutor, dataChangeListenerExecutor,
+ final InMemoryDOMDataStore dataStore = new InMemoryDOMDataStore(name, dataChangeListenerExecutor,
actualProperties.getMaxDataChangeListenerQueueSize(), debugTransactions);
if (schemaService != null) {
package org.opendaylight.controller.md.sal.dom.store.impl.jmx;
-import java.util.concurrent.ExecutorService;
import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
import org.opendaylight.controller.md.sal.common.util.jmx.QueuedNotificationManagerMXBeanImpl;
import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStatsMXBeanImpl;
+import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager;
/**
public class InMemoryDataStoreStats implements AutoCloseable {
private final AbstractMXBean notificationExecutorStatsBean;
- private final AbstractMXBean dataStoreExecutorStatsBean;
private final QueuedNotificationManagerMXBeanImpl notificationManagerStatsBean;
- public InMemoryDataStoreStats(final String mBeanType, final QueuedNotificationManager<?, ?> manager,
- final ExecutorService dataStoreExecutor) {
+ public InMemoryDataStoreStats(final String mBeanType, final QueuedNotificationManager<?, ?> manager) {
notificationManagerStatsBean = new QueuedNotificationManagerMXBeanImpl(manager,
"notification-manager", mBeanType, null);
if (notificationExecutorStatsBean != null) {
notificationExecutorStatsBean.registerMBean();
}
+ }
- dataStoreExecutorStatsBean = ThreadExecutorStatsMXBeanImpl.create(dataStoreExecutor,
- "data-store-executor", mBeanType, null);
- if (dataStoreExecutorStatsBean != null) {
- dataStoreExecutorStatsBean.registerMBean();
- }
+ public InMemoryDataStoreStats(final String name, final InMemoryDOMDataStore dataStore) {
+ this(name, dataStore.getDataChangeListenerNotificationManager());
}
@Override
notificationExecutorStatsBean.unregisterMBean();
}
- if(dataStoreExecutorStatsBean != null) {
- dataStoreExecutorStatsBean.unregisterMBean();
- }
-
if(notificationManagerStatsBean != null) {
notificationManagerStatsBean.unregisterMBean();
}
*/
package org.opendaylight.controller.md.sal.dom.store.impl;
-import com.google.common.util.concurrent.MoreExecutors;
-
import java.util.Collection;
import java.util.Map;
-
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
dclExecutorService = new TestDCLExecutorService(
SpecialExecutors.newBlockingBoundedFastThreadPool(1, 10, "DCL" ));
- datastore = new InMemoryDOMDataStore("TEST",
- MoreExecutors.sameThreadExecutor(), dclExecutorService );
+ datastore = new InMemoryDOMDataStore("TEST", dclExecutorService);
datastore.onGlobalContextUpdated(schemaContext);
}
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
-
import java.util.concurrent.ExecutionException;
-
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@Before
public void setupStore() {
- domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.sameThreadExecutor(),
- MoreExecutors.sameThreadExecutor());
+ domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.sameThreadExecutor());
schemaContext = TestModel.createTestContext();
domStore.onGlobalContextUpdated(schemaContext);
}
package org.opendaylight.controller.md.sal.dom.store.impl;
import static org.junit.Assert.assertNotNull;
-
+import com.google.common.base.Throwables;
+import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.ExecutionException;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import com.google.common.base.Throwables;
-import com.google.common.util.concurrent.MoreExecutors;
-
public class SchemaUpdateForTransactionTest {
private static final YangInstanceIdentifier TOP_PATH = YangInstanceIdentifier.of(Top.QNAME);
@Before
public void setupStore() {
- domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.sameThreadExecutor(),
- MoreExecutors.sameThreadExecutor());
+ domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.sameThreadExecutor());
loadSchemas(RockTheHouseInput.class);
}
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME;
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_TARGET_QNAME;
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.ROLLBACK_ON_ERROR_OPTION;
-
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.Collections;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
final Optional<CompositeNode> lastChildOverride) {
Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath);
- List<YangInstanceIdentifier.PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
-
// Create deepest edit element with expected edit operation
- CompositeNode previous = getDeepestEditElement(reversedPath.get(0), operation, lastChildOverride);
+ CompositeNode previous = getDeepestEditElement(dataPath.getLastPathArgument(), operation, lastChildOverride);
+ Iterator<PathArgument> it = dataPath.getReversePathArguments().iterator();
// Remove already processed deepest child
- reversedPath = Lists.newArrayList(reversedPath);
- reversedPath.remove(0);
+ it.next();
// Create edit structure in reversed order
- for (final YangInstanceIdentifier.PathArgument arg : reversedPath) {
+ while (it.hasNext()) {
+ final YangInstanceIdentifier.PathArgument arg = it.next();
final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
builder.setQName(arg.getNodeType());
*/
package org.opendaylight.controller.sal.connect.netconf.util;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Sets;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
import javax.annotation.Nullable;
-
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Sets;
-
public class NetconfMessageTransformUtil {
public static final String MESSAGE_ID_ATTR = "message-id";
public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version");
public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace");
- public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
- public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
- public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
- public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
- public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
- public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
- static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, null, null));
- public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
- public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
- public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
- public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
- public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
- public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
- public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
- public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
- public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
- public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
- public static QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
- public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
- public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
- public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
- public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
-
- public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
+ public static final URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
+ public static final QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
+ public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
+ public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
+ public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
+ public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
+ static final List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, null, null));
+ public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
+ public static final CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
+ public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
+ public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
+ public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
+ public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
+ public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
+ public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
+ public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
+ public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
+ public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
+ public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
+ public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
+ public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
+ public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
+
+ public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
.create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
- public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
+ public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
- public static URI NETCONF_CANDIDATE_URI = URI
+ public static final URI NETCONF_CANDIDATE_URI = URI
.create("urn:ietf:params:netconf:capability:candidate:1.0");
// Discard changes message
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
-
import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import java.io.IOException;
assertEquals(400, post(uri, MediaType.APPLICATION_JSON, ""));
}
- private void mockInvokeRpc(CompositeNode result, boolean sucessful, Collection<RpcError> errors) {
+ private void mockInvokeRpc(final CompositeNode result, final boolean sucessful, final Collection<RpcError> errors) {
DummyRpcResult.Builder<CompositeNode> builder = new DummyRpcResult.Builder<CompositeNode>().result(result)
.isSuccessful(sucessful);
Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
}
- private void mockInvokeRpc(CompositeNode result, boolean sucessful) {
+ private void mockInvokeRpc(final CompositeNode result, final boolean sucessful) {
mockInvokeRpc(result, sucessful, Collections.<RpcError> emptyList());
}
assertEquals(204, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface));
verify(brokerFacade).commitConfigurationDataPost(instanceIdCaptor.capture(), compNodeCaptor.capture());
String identifier = "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces]";
- assertEquals(identifier, instanceIdCaptor.getValue().getPath().toString());
+ assertEquals(identifier, ImmutableList.copyOf(instanceIdCaptor.getValue().getPathArguments()).toString());
String URI_2 = "/config/test-interface:interfaces";
assertEquals(204, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData));
verify(brokerFacade, times(2))
.commitConfigurationDataPost(instanceIdCaptor.capture(), compNodeCaptor.capture());
identifier = "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces, (urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)block]";
- assertEquals(identifier, instanceIdCaptor.getValue().getPath().toString());
+ assertEquals(identifier, ImmutableList.copyOf(instanceIdCaptor.getValue().getPathArguments()).toString());
}
@Test
restconfImpl.setControllerContext(controllerContext);
}
- private int post(String uri, String mediaType, String data) {
+ private int post(final String uri, final String mediaType, final String data) {
return target(uri).request(mediaType).post(Entity.entity(data, mediaType)).getStatus();
}
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.io.FileNotFoundException;
import java.util.Set;
.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class/student/name");
assertEquals(
"[(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)class, (urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)student[{(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)name=name}]]",
- instanceIdentifier.getInstanceIdentifier().getPath().toString());
+ ImmutableList.copyOf(instanceIdentifier.getInstanceIdentifier().getPathArguments()).toString());
}
@Test
exception.expect(RestconfDocumentedException.class);
controllerContext.setMountService(null);
- InstanceIdentifierContext instanceIdentifier = controllerContext
- .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class/student/name");
+ controllerContext.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class/student/name");
}
@Test
initMountService(false);
exception.expect(RestconfDocumentedException.class);
- InstanceIdentifierContext instanceIdentifier = controllerContext
- .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class");
+ controllerContext.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class");
}
public void initMountService(final boolean withSchema) {
package org.opendaylight.controller.sal.restconf.impl.test;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.net.URISyntaxException;
-import java.util.List;
+import java.util.Iterator;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSchemaLoader {
verifyLeafListPredicate(cnSn);
}
- private void verifyLeafListPredicate(CompositeNode cnSn) throws URISyntaxException {
+ private void verifyLeafListPredicate(final CompositeNode cnSn) throws URISyntaxException {
SimpleNode<?> lf11 = getSnWithInstanceIdentifierWhenLeafList(cnSn);
Object value = lf11.getValue();
assertTrue(value instanceof YangInstanceIdentifier);
YangInstanceIdentifier instanceIdentifier = (YangInstanceIdentifier) value;
- List<PathArgument> pathArguments = instanceIdentifier.getPath();
- assertEquals(3, pathArguments.size());
+ Iterator<PathArgument> it = instanceIdentifier.getPathArguments().iterator();
String revisionDate = "2014-01-17";
- assertEquals(TestUtils.buildQName("cont", "instance:identifier:module", revisionDate), pathArguments.get(0)
- .getNodeType());
- assertEquals(TestUtils.buildQName("cont1", "instance:identifier:module", revisionDate), pathArguments.get(1)
- .getNodeType());
- assertEquals(TestUtils.buildQName("lflst11", "augment:module:leaf:list", "2014-01-27"), pathArguments.get(2)
- .getNodeType());
- assertTrue(pathArguments.get(2) instanceof NodeWithValue);
- assertEquals("lflst11_1", ((NodeWithValue) pathArguments.get(2)).getValue());
+ assertEquals(TestUtils.buildQName("cont", "instance:identifier:module", revisionDate), it.next().getNodeType());
+ assertEquals(TestUtils.buildQName("cont1", "instance:identifier:module", revisionDate), it.next().getNodeType());
+
+ PathArgument arg = it.next();
+ assertFalse(it.hasNext());
+ assertEquals(TestUtils.buildQName("lflst11", "augment:module:leaf:list", "2014-01-27"), arg.getNodeType());
+
+ assertTrue(arg instanceof NodeWithValue);
+ assertEquals("lflst11_1", ((NodeWithValue) arg).getValue());
}
- private void verifyListPredicate(CompositeNode cnSn) throws URISyntaxException {
+ private void verifyListPredicate(final CompositeNode cnSn) throws URISyntaxException {
SimpleNode<?> lf111 = getSnWithInstanceIdentifierWhenList(cnSn);
Object value = lf111.getValue();
assertTrue(value instanceof YangInstanceIdentifier);
YangInstanceIdentifier instanceIdentifier = (YangInstanceIdentifier) value;
- List<PathArgument> pathArguments = instanceIdentifier.getPath();
- assertEquals(4, pathArguments.size());
+ Iterator<PathArgument> it = instanceIdentifier.getPathArguments().iterator();
String revisionDate = "2014-01-17";
- assertEquals(TestUtils.buildQName("cont", "instance:identifier:module", revisionDate), pathArguments.get(0)
- .getNodeType());
- assertEquals(TestUtils.buildQName("cont1", "instance:identifier:module", revisionDate), pathArguments.get(1)
- .getNodeType());
- assertEquals(TestUtils.buildQName("lst11", "augment:module", revisionDate), pathArguments.get(2).getNodeType());
- assertEquals(TestUtils.buildQName("lf112", "augment:augment:module", revisionDate), pathArguments.get(3)
- .getNodeType());
-
- assertTrue(pathArguments.get(2) instanceof NodeIdentifierWithPredicates);
- Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArguments.get(2)).getKeyValues();
+ assertEquals(TestUtils.buildQName("cont", "instance:identifier:module", revisionDate), it.next().getNodeType());
+ assertEquals(TestUtils.buildQName("cont1", "instance:identifier:module", revisionDate), it.next().getNodeType());
+
+ PathArgument arg = it.next();
+ assertEquals(TestUtils.buildQName("lst11", "augment:module", revisionDate), arg.getNodeType());
+ assertEquals(TestUtils.buildQName("lf112", "augment:augment:module", revisionDate), it.next().getNodeType());
+ assertFalse(it.hasNext());
+
+ assertTrue(arg instanceof NodeIdentifierWithPredicates);
+ Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) arg).getKeyValues();
assertEquals(2, predicates.size());
assertEquals("value1", predicates.get(TestUtils.buildQName("keyvalue111", "augment:module", revisionDate)));
assertEquals("value2", predicates.get(TestUtils.buildQName("keyvalue112", "augment:module", revisionDate)));
}
- private SimpleNode<?> getSnWithInstanceIdentifierWhenList(CompositeNode cnSn) throws URISyntaxException {
+ private SimpleNode<?> getSnWithInstanceIdentifierWhenList(final CompositeNode cnSn) throws URISyntaxException {
CompositeNode cont1 = cnSn.getFirstCompositeByName(TestUtils.buildQName("cont1", "instance:identifier:module",
"2014-01-17"));
assertNotNull(cont1);
return lf111;
}
- private SimpleNode<?> getSnWithInstanceIdentifierWhenLeafList(CompositeNode cnSn) throws URISyntaxException {
+ private SimpleNode<?> getSnWithInstanceIdentifierWhenLeafList(final CompositeNode cnSn) throws URISyntaxException {
CompositeNode cont1 = cnSn.getFirstCompositeByName(TestUtils.buildQName("cont1", "instance:identifier:module",
"2014-01-17"));
assertNotNull(cont1);
<artifactId>yang-parser-impl</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-maven-plugin-spi</artifactId>
+ </dependency>
+
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<instructions>
<Bundle-Name>MD SAL Rest Api Doc Generator</Bundle-Name>
- <Import-Package>*,
- com.sun.jersey.spi.container.servlet, org.eclipse.jetty.servlets</Import-Package>
+ <Import-Package>!org.apache.maven.plugin.logging,
+ !org.apache.maven.project,
+ !org.opendaylight.yangtools.yang2sources.spi,
+ *,
+ com.sun.jersey.spi.container.servlet, org.eclipse.jetty.servlets
+ </Import-Package>
<Bundle-Activator>org.opendaylight.controller.sal.rest.doc.DocProvider</Bundle-Activator>
<Web-ContextPath>/apidoc</Web-ContextPath>
</instructions>
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.rest.doc.impl;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
+import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration;
+import org.opendaylight.controller.sal.rest.doc.swagger.Resource;
+import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
+
+import javax.ws.rs.core.UriInfo;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * This class gathers all yang defined {@link Module}s and generates Swagger compliant documentation.
+ */
+public class StaticDocGenerator extends ApiDocGenerator implements CodeGenerator {
+
+ private static final String DEFAULT_OUTPUT_BASE_DIR_PATH = "target" + File.separator + "generated-resources"
+ + File.separator + "swagger-api-documentation";
+
+ private static Logger _logger = LoggerFactory.getLogger(ApiDocGenerator.class);
+
+ private MavenProject mavenProject;
+ private File projectBaseDir;
+ private Map<String, String> additionalConfig;
+ private File resourceBaseDir;
+ private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
+
+ /**
+ *
+ * @param context
+ * @param outputDir
+ * @param yangModules
+ * @return
+ * @throws IOException
+ */
+ @Override
+ public Collection<File> generateSources(SchemaContext context, File outputDir, Set<Module> yangModules) throws IOException {
+ List<File> result = new ArrayList<>();
+
+ // Create Base Directory
+ final File outputBaseDir;
+ if (outputDir == null) {
+ outputBaseDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH);
+ }
+ else outputBaseDir = outputDir;
+ outputBaseDir.mkdirs();
+
+ // Create Resources directory
+ File resourcesDir = new File(outputBaseDir, "resources");
+ resourcesDir.mkdirs();
+
+ // Create JS file
+ File resourcesJsFile = new File(outputBaseDir, "resources.js");
+ resourcesJsFile.createNewFile();
+ BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resourcesJsFile));
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+
+ // Write resource listing to JS file
+ ResourceList resourceList = super.getResourceListing(null, context, "");
+ String resourceListJson = mapper.writeValueAsString(resourceList);
+ resourceListJson = resourceListJson.replace("\'", "\\\'").replace("\\n", "\\\\n");
+ bufferedWriter.write("function getSpec() {\n\treturn \'" + resourceListJson + "\';\n}\n\n");
+
+ // Write resources/APIs to JS file and to disk
+ bufferedWriter.write("function jsonFor(resource) {\n\tswitch(resource) {\n");
+ for (Resource resource : resourceList.getApis()) {
+ int revisionIndex = resource.getPath().indexOf('(');
+ String name = resource.getPath().substring(0, revisionIndex);
+ String revision = resource.getPath().substring(revisionIndex + 1, resource.getPath().length() - 1);
+ ApiDeclaration apiDeclaration = super.getApiDeclaration(name, revision, null, context, "");
+ String json = mapper.writeValueAsString(apiDeclaration);
+ // Manually insert models because org.json.JSONObject cannot be serialized by ObjectMapper
+ json = json.replace("\"models\":{}", "\"models\":" + apiDeclaration.getModels().toString().replace("\\\"", "\""));
+ // Escape single quotes and new lines
+ json = json.replace("\'", "\\\'").replace("\\n", "\\\\n");
+ bufferedWriter.write("\t\tcase \"" + name + "(" + revision + ")\": return \'" + json + "\';\n");
+
+ File resourceFile = new File(resourcesDir, name + "(" + revision + ").json");
+ BufferedWriter resourceFileWriter = new BufferedWriter(new FileWriter(resourceFile));
+ resourceFileWriter.write(json);
+ resourceFileWriter.close();
+ result.add(resourceFile);
+ }
+ bufferedWriter.write("\t}\n\treturn \"\";\n}");
+ bufferedWriter.close();
+
+ result.add(resourcesJsFile);
+ return result;
+ }
+
+ @Override
+ protected String generatePath(UriInfo uriInfo, String name, String revision) {
+ if (uriInfo == null) {
+ return name + "(" + revision + ")";
+ }
+ return super.generatePath(uriInfo, name, revision);
+ }
+
+ @Override
+ protected String createBasePathFromUriInfo(UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return RESTCONF_CONTEXT_ROOT;
+ }
+ return super.createBasePathFromUriInfo(uriInfo);
+ }
+
+ @Override
+ public void setLog(Log log) {
+ }
+
+ @Override
+ public void setAdditionalConfig(Map<String, String> additionalConfig) {
+ this.additionalConfig = additionalConfig;
+ }
+
+ @Override
+ public void setResourceBaseDir(File resourceBaseDir) {
+ this.resourceBaseDir = resourceBaseDir;
+ }
+
+ @Override
+ public void setMavenProject(MavenProject mavenProject) {
+ this.mavenProject = mavenProject;
+ this.projectBaseDir = mavenProject.getBasedir();
+ }
+}
--- /dev/null
+This component offers Swagger documentation of the RestConf APIs.
+
+This Swagger documentation can be accessed in two ways:
+I. Running server
+Open a browser and go to http://<host>:8181/apidoc/explorer/index.html
+
+II. Static documentation generation
+By adding a reference to the StaticDocGenerator class in any pom.xml,
+static documentation will be generated. This static documentation will
+document all the RestConf APIs for the YANG files in that artifact and
+all the YANG files in that artifact's dependencies.
+
+In order to generate static documentation for all resources,
+this should be placed in a downstream project.
+
+Below is what you would add to the <plugins> section under <build>.
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <version>2.8</version>
+ <executions>
+ <execution>
+ <id>unpack-static-documentation</id>
+ <goals>
+ <goal>unpack-dependencies</goal>
+ </goals>
+ <phase>generate-resources</phase>
+ <configuration>
+ <outputDirectory>${project.build.directory}/generated-resources/swagger-api-documentation</outputDirectory>
+ <includeArtifactIds>sal-rest-docgen</includeArtifactIds>
+ <includes>**/explorer/css/**/*, **/explorer/images/**/*, **/explorer/lib/**/*, **/explorer/static/**/*,</includes>
+ <excludeTransitive>true</excludeTransitive>
+ <ignorePermissions>false</ignorePermissions>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-maven-plugin</artifactId>
+ <version>${yangtools.version}</version>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>maven-sal-api-gen-plugin</artifactId>
+ <version>${yangtools.version}</version>
+ <type>jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-binding</artifactId>
+ <version>${yangtools.version}</version>
+ <type>jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-rest-docgen</artifactId>
+ <version>${mdsal.version}</version>
+ <type>jar</type>
+ </dependency>
+ </dependencies>
+ <executions>
+ <execution>
+ <goals>
+ <goal>generate-sources</goal>
+ </goals>
+ <configuration>
+ <yangFilesRootDir>src</yangFilesRootDir>
+ <codeGenerators>
+ <generator>
+ <codeGeneratorClass>org.opendaylight.controller.sal.rest.doc.impl.StaticDocGenerator</codeGeneratorClass>
+ <outputBaseDir>${project.build.directory}/generated-resources/swagger-api-documentation/explorer/static</outputBaseDir>
+ </generator>
+ </codeGenerators>
+ <inspectDependencies>true</inspectDependencies>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
--- /dev/null
+/* latin */
+@font-face {
+ font-family: 'Droid Sans';
+ font-style: normal;
+ font-weight: 400;
+ src: local('Droid Sans'), local('DroidSans'), url(http://fonts.gstatic.com/s/droidsans/v6/s-BiyweUPV0v-yRb-cjciAsYbbCjybiHxArTLjt7FRU.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
+}
+/* latin */
+@font-face {
+ font-family: 'Droid Sans';
+ font-style: normal;
+ font-weight: 700;
+ src: local('Droid Sans Bold'), local('DroidSans-Bold'), url(http://fonts.gstatic.com/s/droidsans/v6/EFpQQyG9GqCrobXxL-KRMX9tREKe1lLHLCwOC24WjMs.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
+}
\ No newline at end of file
--- /dev/null
+<!DOCTYPE html>
+<html>
+<head>
+ <title>RestConf Documentation</title>
+ <link href='fonts.css'
+ rel='stylesheet' type='text/css' /> <!--original location: //fonts.googleapis.com/css?family=Droid+Sans:400,700 -->
+ <link href='../css/highlight.default.css' media='screen' rel='stylesheet'
+ type='text/css' />
+ <link href='../css/screen.css' media='screen' rel='stylesheet'
+ type='text/css' />
+ <link rel="stylesheet" type="text/css" href="opendaylight.css">
+ <link rel="stylesheet" type="text/css"
+ href="../css/ui-lightness/jquery-ui-1.10.4.custom.min.css">
+ <script type="text/javascript" src="../lib/shred.bundle.js"></script>
+ <script src='../lib/jquery-1.8.0.min.js' type='text/javascript'></script>
+ <script src='../lib/jquery-ui-1.11.0.min.js' type="text/javascript"></script>
+ <script src='../lib/jquery.slideto.min.js' type='text/javascript'></script>
+ <script src='../lib/jquery.wiggle.min.js' type='text/javascript'></script>
+ <script src='../lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
+ <script src='../lib/handlebars-1.0.0.js' type='text/javascript'></script>
+ <script src='../lib/underscore-min.js' type='text/javascript'></script>
+ <script src='../lib/backbone-min.js' type='text/javascript'></script>
+ <script src='swagger.js' type='text/javascript'></script>
+ <script src='swagger-ui.js' type='text/javascript'></script>
+ <script src='../lib/odl/list_mounts.js' type='text/javascript'></script>
+ <script src='../lib/highlight.7.3.pack.js' type='text/javascript'></script>
+ <script src='../lib/odl/swagger.js' type='text/javascript'></script>
+ <script src='resources.js' type='text/javascript'></script>
+
+ <script type="text/javascript">
+
+ //reloads the swagger UI documentation for the specified mount.
+ var loadMount = function(mountIndex, mountPath) {
+ $("#message").empty();
+ $("#message").append( "<p>Loading...</p>" );
+ loadSwagger("/apidoc/apis/mounts/" + mountIndex,
+ "swagger-ui-container");
+ $("#message").empty();
+ $("#message").append( "<h2><b>Showing mount points for " + mountPath + "</b></h2>");
+ }
+
+ //clears the swagger UI and adds text prompting use to select a mount point.
+ var selectAMount = function(string) {
+ $("#swagger-ui-container").empty();
+ $("#message").empty();
+ $("#message").append("<p>Select a mount point.</p>");
+ }
+
+ //loads the root swagger documenation (which comes from RestConf)
+ var loadRootSwagger = function() {
+ $("#message").empty();
+ loadSwagger("/apidoc/apis", "swagger-ui-container");
+ }
+
+ //main method to initialize the mount list / swagger docs / tabs on page load
+ $(function() {
+ $("#tabs").tabs();
+
+ loadMountList($("#mountlist"));
+
+ loadRootSwagger();
+ });
+ </script>
+</head>
+
+<body>
+<div>
+ <!-- style="background-color: #FCA000;" -->
+ <div class="swagger-ui-wrap ui-tabs">
+ <table>
+ <tr>
+ <td><img src="../images/logo_small.png" /></td>
+ <td><h1 width="100%">OpenDaylight RestConf API
+ Documentation</h1></td>
+ </tr>
+ </table>
+ </div>
+</div>
+
+<div class="navbar-inner">
+ <div class="brand"></div>
+</div>
+
+<!-- defines the div shells which represent the jquery tabs -->
+<div id="tabs" class="swagger-ui-wrap">
+ <ul>
+ <li><a href="#Controller" onclick="loadRootSwagger()">Controller
+ Resources</a></li>
+ </ul>
+
+ <div id="Controller">
+ <div>
+ <h3>Below are the list of APIs supported by the Controller.</h3>
+ </div>
+ </div>
+</div>
+
+<div class="swagger-ui-wrap"><hr/></div>
+
+<!-- messages -->
+<div id="message" class="swagger-ui-wrap"></div>
+
+<!-- the swagger is always loaded in this div -->
+<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
+
+<div id="message-bar" class="swagger-ui-wrap"> </div>
+</body>
+
+</html>
--- /dev/null
+.fuelux [class^="icon-"],
+.fuelux [class*=" icon-"] {
+ display: inline-block;
+ width: 14px;
+ height: 14px;
+ margin-top: 1px;
+ *margin-right: .3em;
+ line-height: 14px;
+ vertical-align: text-top;
+ background-position: 14px 14px;
+ background-repeat: no-repeat;
+}
+
+.fuelux .icon-white,
+.fuelux .nav-pills > .active > a > [class^="icon-"],
+.fuelux .nav-pills > .active > a > [class*=" icon-"],
+.fuelux .nav-list > .active > a > [class^="icon-"],
+.fuelux .nav-list > .active > a > [class*=" icon-"],
+.fuelux .navbar-inverse .nav > .active > a > [class^="icon-"],
+.fuelux .navbar-inverse .nav > .active > a > [class*=" icon-"],
+.fuelux .dropdown-menu > li > a:hover > [class^="icon-"],
+.fuelux .dropdown-menu > li > a:focus > [class^="icon-"],
+.fuelux .dropdown-menu > li > a:hover > [class*=" icon-"],
+.fuelux .dropdown-menu > li > a:focus > [class*=" icon-"],
+.fuelux .dropdown-menu > .active > a > [class^="icon-"],
+.fuelux .dropdown-menu > .active > a > [class*=" icon-"],
+.fuelux .dropdown-submenu:hover > a > [class^="icon-"],
+.fuelux .dropdown-submenu:focus > a > [class^="icon-"],
+.fuelux .dropdown-submenu:hover > a > [class*=" icon-"],
+.fuelux .dropdown-submenu:focus > a > [class*=" icon-"] {
+}
+
+.fuelux .icon-search {
+ background:url('../img/search.png') 0 0 no-repeat;
+ height: 16px;
+ line-height: 16px;
+ width: 16px;
+}
+.fuelux .icon-remove {
+ background:url('../img/searchremove.png') 0 0 no-repeat;
+ height: 16px;
+ line-height: 16px;
+ width: 16px;
+}
+
+.fuelux .icon-chevron-up {
+ background:url('../img/sort_up.png') 0 0 no-repeat;
+ height: 16px;
+ line-height: 16px;
+ width: 16px;
+}
+
+.fuelux .icon-chevron-down {
+ background:url('../img/sort_down.png') 0 0 no-repeat;
+ height: 16px;
+ line-height: 16px;
+ width: 16px;
+}
+
+.fuelux .icon-chevron-left {
+ background:url('../img/nextpageleft.png') 0 0 no-repeat;
+ height: 16px;
+ line-height: 16px;
+ width: 16px;
+}
+
+.fuelux .icon-chevron-right {
+ background:url('../img/nextpageright.png') 0 0 no-repeat;
+ height: 16px;
+ line-height: 16px;
+ width: 16px;
+}
+
+.fuelux .icon-chevron-right {
+ background:url('../img/nextpageright.png') 0 0 no-repeat;
+ height: 16px;
+ line-height: 16px;
+ width: 16px;
+}
+
+.tip {
+ background-color: white;
+ border: 1px solid #CCCCCC;
+ box-shadow: 2px 2px 8px #555555;
+ color: #111111;
+ font-family: Verdana,Geneva,Arial,Helvetica,sans-serif;
+ font-size: 14px;
+ opacity: 0.9;
+ padding: 7px;
+ width: 260px;
+ border-radius: 8px;
+}
--- /dev/null
+$(function() {
+
+ // Helper function for vertically aligning DOM elements
+ // http://www.seodenver.com/simple-vertical-align-plugin-for-jquery/
+ $.fn.vAlign = function() {
+ return this.each(function(i){
+ var ah = $(this).height();
+ var ph = $(this).parent().height();
+ var mh = (ph - ah) / 2;
+ $(this).css('margin-top', mh);
+ });
+ };
+
+ $.fn.stretchFormtasticInputWidthToParent = function() {
+ return this.each(function(i){
+ var p_width = $(this).closest("form").innerWidth();
+ var p_padding = parseInt($(this).closest("form").css('padding-left') ,10) + parseInt($(this).closest("form").css('padding-right'), 10);
+ var this_padding = parseInt($(this).css('padding-left'), 10) + parseInt($(this).css('padding-right'), 10);
+ $(this).css('width', p_width - p_padding - this_padding);
+ });
+ };
+
+ $('form.formtastic li.string input, form.formtastic textarea').stretchFormtasticInputWidthToParent();
+
+ // Vertically center these paragraphs
+ // Parent may need a min-height for this to work..
+ $('ul.downplayed li div.content p').vAlign();
+
+ // When a sandbox form is submitted..
+ $("form.sandbox").submit(function(){
+
+ var error_free = true;
+
+ // Cycle through the forms required inputs
+ $(this).find("input.required").each(function() {
+
+ // Remove any existing error styles from the input
+ $(this).removeClass('error');
+
+ // Tack the error style on if the input is empty..
+ if ($(this).val() == '') {
+ $(this).addClass('error');
+ $(this).wiggle();
+ error_free = false;
+ }
+
+ });
+
+ return error_free;
+ });
+
+});
+
+function clippyCopiedCallback(a) {
+ $('#api_key_copied').fadeIn().delay(1000).fadeOut();
+
+ // var b = $("#clippy_tooltip_" + a);
+ // b.length != 0 && (b.attr("title", "copied!").trigger("tipsy.reload"), setTimeout(function() {
+ // b.attr("title", "copy to clipboard")
+ // },
+ // 500))
+}
+
+// Logging function that accounts for browsers that don't have window.console
+function log() {
+ if (window.console) console.log.apply(console,arguments);
+}
+// Handle browsers that do console incorrectly (IE9 and below, see http://stackoverflow.com/a/5539378/7913)
+if (Function.prototype.bind && console && typeof console.log == "object") {
+ [
+ "log","info","warn","error","assert","dir","clear","profile","profileEnd"
+ ].forEach(function (method) {
+ console[method] = this.bind(console[method], console);
+ }, Function.prototype.call);
+}
+
+var Docs = {
+
+ shebang: function() {
+
+ // If shebang has an operation nickname in it..
+ // e.g. /docs/#!/words/get_search
+ var fragments = $.param.fragment().split('/');
+ fragments.shift(); // get rid of the bang
+
+ switch (fragments.length) {
+ case 1:
+ // Expand all operations for the resource and scroll to it
+// log('shebang resource:' + fragments[0]);
+ var dom_id = 'resource_' + fragments[0];
+
+ Docs.expandEndpointListForResource(fragments[0]);
+ $("#"+dom_id).slideto({highlight: false});
+ break;
+ case 2:
+ // Refer to the endpoint DOM element, e.g. #words_get_search
+// log('shebang endpoint: ' + fragments.join('_'));
+
+ // Expand Resource
+ Docs.expandEndpointListForResource(fragments[0]);
+ $("#"+dom_id).slideto({highlight: false});
+
+ // Expand operation
+ var li_dom_id = fragments.join('_');
+ var li_content_dom_id = li_dom_id + "_content";
+
+// log("li_dom_id " + li_dom_id);
+// log("li_content_dom_id " + li_content_dom_id);
+
+ Docs.expandOperation($('#'+li_content_dom_id));
+ $('#'+li_dom_id).slideto({highlight: false});
+ break;
+ }
+
+ },
+
+ toggleEndpointListForResource: function(resource) {
+ var elem = $('li#resource_' + Docs.escapeResourceName(resource) + ' ul.endpoints');
+ if (elem.is(':visible')) {
+ Docs.collapseEndpointListForResource(resource);
+ } else {
+ Docs.expandEndpointListForResource(resource);
+ }
+ },
+
+ // Expand resource
+ expandEndpointListForResource: function(resource) {
+ var resource = Docs.escapeResourceName(resource);
+ if (resource == '') {
+ $('.resource ul.endpoints').slideDown();
+ return;
+ }
+
+ $('li#resource_' + resource).addClass('active');
+
+ var elem = $('li#resource_' + resource + ' ul.endpoints');
+ elem.slideDown();
+ },
+
+ // Collapse resource and mark as explicitly closed
+ collapseEndpointListForResource: function(resource) {
+ var resource = Docs.escapeResourceName(resource);
+ $('li#resource_' + resource).removeClass('active');
+
+ var elem = $('li#resource_' + resource + ' ul.endpoints');
+ elem.slideUp();
+ },
+
+ expandOperationsForResource: function(resource) {
+ // Make sure the resource container is open..
+ Docs.expandEndpointListForResource(resource);
+
+ if (resource == '') {
+ $('.resource ul.endpoints li.operation div.content').slideDown();
+ return;
+ }
+
+ $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() {
+ Docs.expandOperation($(this));
+ });
+ },
+
+ collapseOperationsForResource: function(resource) {
+ // Make sure the resource container is open..
+ Docs.expandEndpointListForResource(resource);
+
+ $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() {
+ Docs.collapseOperation($(this));
+ });
+ },
+
+ escapeResourceName: function(resource) {
+ return resource.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&");
+ },
+
+ expandOperation: function(elem) {
+ elem.slideDown();
+ },
+
+ collapseOperation: function(elem) {
+ elem.slideUp();
+ }
+
+};
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['content_type'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers.each.call(depth0, depth0.produces, {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n";
+ return buffer;
+ }
+ function program2(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <option value=\"";
+ stack1 = (typeof depth0 === functionType ? depth0.apply(depth0) : depth0);
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\">";
+ stack1 = (typeof depth0 === functionType ? depth0.apply(depth0) : depth0);
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</option>\n ";
+ return buffer;
+ }
+
+ function program4(depth0,data) {
+
+
+ return "\n <option value=\"application/json\">application/json</option>\n";
+ }
+
+ buffer += "<label for=\"contentType\"></label>\n<select name=\"contentType\">\n";
+ stack1 = helpers['if'].call(depth0, depth0.produces, {hash:{},inverse:self.program(4, program4, data),fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n</select>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['main'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1, stack2;
+ buffer += "\n <div class=\"info_title\">"
+ + escapeExpression(((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.title)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1))
+ + "</div>\n <div class=\"info_description\">";
+ stack2 = ((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.description)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1);
+ if(stack2 || stack2 === 0) { buffer += stack2; }
+ buffer += "</div>\n ";
+ stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.termsOfServiceUrl), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data});
+ if(stack2 || stack2 === 0) { buffer += stack2; }
+ buffer += "\n ";
+ stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.contact), {hash:{},inverse:self.noop,fn:self.program(4, program4, data),data:data});
+ if(stack2 || stack2 === 0) { buffer += stack2; }
+ buffer += "\n ";
+ stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.license), {hash:{},inverse:self.noop,fn:self.program(6, program6, data),data:data});
+ if(stack2 || stack2 === 0) { buffer += stack2; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program2(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "<div class=\"info_tos\"><a href=\""
+ + escapeExpression(((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.termsOfServiceUrl)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1))
+ + "\">Terms of service</a></div>";
+ return buffer;
+ }
+
+ function program4(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "<div class='info_contact'><a href=\"mailto:"
+ + escapeExpression(((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.contact)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1))
+ + "\">Contact the developer</a></div>";
+ return buffer;
+ }
+
+ function program6(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "<div class='info_license'><a href='"
+ + escapeExpression(((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.licenseUrl)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1))
+ + "'>"
+ + escapeExpression(((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.license)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1))
+ + "</a></div>";
+ return buffer;
+ }
+
+ function program8(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n , <span style=\"font-variant: small-caps\">api version</span>: ";
+ if (stack1 = helpers.apiVersion) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.apiVersion; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "\n ";
+ return buffer;
+ }
+
+ buffer += "<div class='info' id='api_info'>\n ";
+ stack1 = helpers['if'].call(depth0, depth0.info, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n</div>\n<div class='container' id='resources_container'>\n <ul id='resources'>\n </ul>\n\n <div class=\"footer\">\n <br>\n <br>\n <h4 style=\"color: #999\">[ <span style=\"font-variant: small-caps\">base url</span>: ";
+ if (stack1 = helpers.basePath) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.basePath; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.apiVersion, {hash:{},inverse:self.noop,fn:self.program(8, program8, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "]</h4>\n </div>\n</div>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['operation'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <h4>Implementation Notes</h4>\n <p>";
+ if (stack1 = helpers.notes) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.notes; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</p>\n ";
+ return buffer;
+ }
+
+ function program3(depth0,data) {
+
+
+ return "\n <h4>Response Class</h4>\n <p><span class=\"model-signature\" /></p>\n <br/>\n <div class=\"response-content-type\" />\n ";
+ }
+
+ function program5(depth0,data) {
+
+
+ return "\n <h4>Parameters</h4>\n <table class='fullwidth'>\n <thead>\n <tr>\n <th style=\"width: 100px; max-width: 100px\">Parameter</th>\n <th style=\"width: 310px; max-width: 310px\">Value</th>\n <th style=\"width: 200px; max-width: 200px\">Description</th>\n <th style=\"width: 100px; max-width: 100px\">Parameter Type</th>\n <th style=\"width: 220px; max-width: 230px\">Data Type</th>\n </tr>\n </thead>\n <tbody class=\"operation-params\">\n\n </tbody>\n </table>\n ";
+ }
+
+ function program7(depth0,data) {
+
+
+ return "\n <div style='margin:0;padding:0;display:inline'></div>\n <h4>Error Status Codes</h4>\n <table class='fullwidth'>\n <thead>\n <tr>\n <th>HTTP Status Code</th>\n <th>Reason</th>\n </tr>\n </thead>\n <tbody class=\"operation-status\">\n \n </tbody>\n </table>\n ";
+ }
+
+ function program9(depth0,data) {
+
+
+ return "\n ";
+ }
+
+ function program11(depth0,data) {
+
+
+ return "\n <div class='sandbox_header'>\n <a href='#' class='response_hider' style='display:none'>Hide Response</a>\n <img alt='Throbber' class='response_throbber' src='../images/throbber.gif' style='display:none' />\n </div>\n ";
+ }
+
+ buffer += "\n <ul class='operations' >\n <li class='";
+ if (stack1 = helpers.method) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.method; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + " operation' id='";
+ if (stack1 = helpers.resourceName) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.resourceName; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.nickname) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.nickname; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.method) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.method; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.number) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.number; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'>\n <div class='heading'>\n <h3>\n <span class='http_method'>\n <a href='#!/";
+ if (stack1 = helpers.resourceName) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.resourceName; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "/";
+ if (stack1 = helpers.nickname) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.nickname; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.method) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.method; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.number) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.number; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' class=\"toggleOperation\">";
+ if (stack1 = helpers.method) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.method; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</a>\n </span>\n <span class='path'>\n <a href='#!/";
+ if (stack1 = helpers.resourceName) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.resourceName; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "/";
+ if (stack1 = helpers.nickname) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.nickname; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.method) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.method; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.number) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.number; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' class=\"toggleOperation\">";
+ if (stack1 = helpers.path) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.path; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</a>\n </span>\n </h3>\n <ul class='options'>\n <li>\n <a href='#!/";
+ if (stack1 = helpers.resourceName) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.resourceName; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "/";
+ if (stack1 = helpers.nickname) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.nickname; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.method) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.method; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.number) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.number; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' class=\"toggleOperation\">";
+ if (stack1 = helpers.summary) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.summary; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</a>\n </li>\n </ul>\n </div>\n <div class='content' id='";
+ if (stack1 = helpers.resourceName) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.resourceName; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.nickname) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.nickname; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.method) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.method; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_";
+ if (stack1 = helpers.number) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.number; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_content' style='display:none'>\n ";
+ stack1 = helpers['if'].call(depth0, depth0.notes, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.type, {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n <form accept-charset='UTF-8' class='sandbox'>\n <div style='margin:0;padding:0;display:inline'></div>\n ";
+ stack1 = helpers['if'].call(depth0, depth0.parameters, {hash:{},inverse:self.noop,fn:self.program(5, program5, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.responseMessages, {hash:{},inverse:self.noop,fn:self.program(7, program7, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isReadOnly, {hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n </form>\n <div class='response' style='display:none'>\n <h4>Request URL</h4>\n <div class='block request_url'></div>\n <h4>Response Body</h4>\n <div class='block response_body'></div>\n <h4>Response Code</h4>\n <div class='block response_code'></div>\n <h4>Response Headers</h4>\n <div class='block response_headers'></div>\n </div>\n </div>\n </li>\n </ul>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['param'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isFile, {hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program2(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <input type=\"file\" name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'/>\n <div class=\"parameter-content-type\" />\n ";
+ return buffer;
+ }
+
+ function program4(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.defaultValue, {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program5(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <textarea class='body-textarea' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'>";
+ if (stack1 = helpers.defaultValue) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.defaultValue; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</textarea>\n ";
+ return buffer;
+ }
+
+ function program7(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <textarea class='body-textarea' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'></textarea>\n <br />\n <div class=\"parameter-content-type\" />\n ";
+ return buffer;
+ }
+
+ function program9(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.defaultValue, {hash:{},inverse:self.program(12, program12, data),fn:self.program(10, program10, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program10(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <input class='parameter' minlength='0' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' placeholder='' type='text' value='";
+ if (stack1 = helpers.defaultValue) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.defaultValue; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'/>\n ";
+ return buffer;
+ }
+
+ function program12(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <input class='parameter' minlength='0' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' placeholder='' type='text' value=''/>\n ";
+ return buffer;
+ }
+
+ buffer += "<td class='code'>";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</td>\n<td>\n\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isBody, {hash:{},inverse:self.program(9, program9, data),fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n\n</td>\n<td>";
+ if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</td>\n<td>";
+ if (stack1 = helpers.paramType) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.paramType; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</td>\n<td>\n <span class=\"model-signature\"></span>\n</td>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['param_list'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, stack2, self=this, functionType="function", escapeExpression=this.escapeExpression;
+
+ function program1(depth0,data) {
+
+
+ return " multiple='multiple'";
+ }
+
+ function program3(depth0,data) {
+
+
+ return "\n ";
+ }
+
+ function program5(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.defaultValue, {hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program6(depth0,data) {
+
+
+ return "\n ";
+ }
+
+ function program8(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.allowMultiple, {hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program9(depth0,data) {
+
+
+ return "\n ";
+ }
+
+ function program11(depth0,data) {
+
+
+ return "\n <option selected=\"\" value=''></option>\n ";
+ }
+
+ function program13(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isDefault, {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program14(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <option selected=\"\" value='";
+ if (stack1 = helpers.value) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.value; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'>";
+ if (stack1 = helpers.value) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.value; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + " (default)</option>\n ";
+ return buffer;
+ }
+
+ function program16(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <option value='";
+ if (stack1 = helpers.value) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.value; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'>";
+ if (stack1 = helpers.value) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.value; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</option>\n ";
+ return buffer;
+ }
+
+ buffer += "<td class='code'>";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</td>\n<td>\n <select ";
+ stack1 = helpers['if'].call(depth0, depth0.allowMultiple, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += " class='parameter' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'>\n ";
+ stack1 = helpers['if'].call(depth0, depth0.required, {hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ stack2 = helpers.each.call(depth0, ((stack1 = depth0.allowableValues),stack1 == null || stack1 === false ? stack1 : stack1.descriptiveValues), {hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data});
+ if(stack2 || stack2 === 0) { buffer += stack2; }
+ buffer += "\n </select>\n</td>\n<td>";
+ if (stack2 = helpers.description) { stack2 = stack2.call(depth0, {hash:{},data:data}); }
+ else { stack2 = depth0.description; stack2 = typeof stack2 === functionType ? stack2.apply(depth0) : stack2; }
+ if(stack2 || stack2 === 0) { buffer += stack2; }
+ buffer += "</td>\n<td>";
+ if (stack2 = helpers.paramType) { stack2 = stack2.call(depth0, {hash:{},data:data}); }
+ else { stack2 = depth0.paramType; stack2 = typeof stack2 === functionType ? stack2.apply(depth0) : stack2; }
+ if(stack2 || stack2 === 0) { buffer += stack2; }
+ buffer += "</td>\n<td><span class=\"model-signature\"></span></td>";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['param_readonly'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <textarea class='body-textarea' readonly='readonly' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'>";
+ if (stack1 = helpers.defaultValue) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.defaultValue; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</textarea>\n ";
+ return buffer;
+ }
+
+ function program3(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.defaultValue, {hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program4(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ if (stack1 = helpers.defaultValue) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.defaultValue; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "\n ";
+ return buffer;
+ }
+
+ function program6(depth0,data) {
+
+
+ return "\n (empty)\n ";
+ }
+
+ buffer += "<td class='code'>";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</td>\n<td>\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isBody, {hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n</td>\n<td>";
+ if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</td>\n<td>";
+ if (stack1 = helpers.paramType) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.paramType; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</td>\n<td><span class=\"model-signature\"></span></td>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['param_readonly_required'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <textarea class='body-textarea' readonly='readonly' placeholder='(required)' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'>";
+ if (stack1 = helpers.defaultValue) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.defaultValue; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</textarea>\n ";
+ return buffer;
+ }
+
+ function program3(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.defaultValue, {hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program4(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ if (stack1 = helpers.defaultValue) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.defaultValue; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "\n ";
+ return buffer;
+ }
+
+ function program6(depth0,data) {
+
+
+ return "\n (empty)\n ";
+ }
+
+ buffer += "<td class='code required'>";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</td>\n<td>\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isBody, {hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n</td>\n<td>";
+ if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</td>\n<td>";
+ if (stack1 = helpers.paramType) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.paramType; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</td>\n<td><span class=\"model-signature\"></span></td>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['param_required'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isFile, {hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program2(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <input type=\"file\" name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'/>\n ";
+ return buffer;
+ }
+
+ function program4(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.defaultValue, {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program5(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <textarea class='body-textarea' placeholder='(required)' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'>";
+ if (stack1 = helpers.defaultValue) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.defaultValue; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</textarea>\n ";
+ return buffer;
+ }
+
+ function program7(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <textarea class='body-textarea' placeholder='(required)' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'></textarea>\n <br />\n <div class=\"parameter-content-type\" />\n ";
+ return buffer;
+ }
+
+ function program9(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isFile, {hash:{},inverse:self.program(12, program12, data),fn:self.program(10, program10, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program10(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <input class='parameter' class='required' type='file' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'/>\n ";
+ return buffer;
+ }
+
+ function program12(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers['if'].call(depth0, depth0.defaultValue, {hash:{},inverse:self.program(15, program15, data),fn:self.program(13, program13, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n ";
+ return buffer;
+ }
+ function program13(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <input class='parameter required' minlength='1' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' placeholder='(required)' type='text' value='";
+ if (stack1 = helpers.defaultValue) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.defaultValue; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'/>\n ";
+ return buffer;
+ }
+
+ function program15(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <input class='parameter required' minlength='1' name='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' placeholder='(required)' type='text' value=''/>\n ";
+ return buffer;
+ }
+
+ buffer += "<td class='code required'>";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</td>\n<td>\n ";
+ stack1 = helpers['if'].call(depth0, depth0.isBody, {hash:{},inverse:self.program(9, program9, data),fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n</td>\n<td>\n <strong>";
+ if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</strong>\n</td>\n<td>";
+ if (stack1 = helpers.paramType) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.paramType; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</td>\n<td><span class=\"model-signature\"></span></td>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['parameter_content_type'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers.each.call(depth0, depth0.consumes, {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n";
+ return buffer;
+ }
+ function program2(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <option value=\"";
+ stack1 = (typeof depth0 === functionType ? depth0.apply(depth0) : depth0);
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\">";
+ stack1 = (typeof depth0 === functionType ? depth0.apply(depth0) : depth0);
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</option>\n ";
+ return buffer;
+ }
+
+ function program4(depth0,data) {
+
+
+ return "\n <option value=\"application/json\">application/json</option>\n";
+ }
+
+ stack1 = helpers['if'].call(depth0, depth0.consumes, {hash:{},inverse:self.program(4, program4, data),fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n</select>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['resource'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, options, functionType="function", escapeExpression=this.escapeExpression, self=this, blockHelperMissing=helpers.blockHelperMissing;
+
+ function program1(depth0,data) {
+
+
+ return " : ";
+ }
+
+ buffer += "<div class='heading'>\n <h2>\n <a href='#!/";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' onclick=\"Docs.toggleEndpointListForResource('";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "');\">";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</a> ";
+ options = {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data};
+ if (stack1 = helpers.description) { stack1 = stack1.call(depth0, options); }
+ else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if (!helpers.description) { stack1 = blockHelperMissing.call(depth0, stack1, options); }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n </h2>\n <ul class='options'>\n <li>\n <a href='#!/";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "' id='endpointListTogger_";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'\n onclick=\"Docs.toggleEndpointListForResource('";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "');\">Show/Hide</a>\n </li>\n <li>\n <a href='#' onclick=\"Docs.collapseOperationsForResource('";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'); return false;\">\n List Operations\n </a>\n </li>\n <li>\n <a href='#' onclick=\"Docs.expandOperationsForResource('";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "'); return false;\">\n Expand Operations\n </a>\n </li>\n <li>\n <a href='";
+ stack1 = "resources/" + depth0.path + ".json";
+ buffer += escapeExpression(stack1)
+ + "'>Raw</a>\n </li>\n </ul>\n</div>\n<ul class='endpoints' id='";
+ if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "_endpoint_list' style='display:none'>\n\n</ul>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['response_content_type'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", self=this;
+
+ function program1(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n ";
+ stack1 = helpers.each.call(depth0, depth0.produces, {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n";
+ return buffer;
+ }
+ function program2(depth0,data) {
+
+ var buffer = "", stack1;
+ buffer += "\n <option value=\"";
+ stack1 = (typeof depth0 === functionType ? depth0.apply(depth0) : depth0);
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\">";
+ stack1 = (typeof depth0 === functionType ? depth0.apply(depth0) : depth0);
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</option>\n ";
+ return buffer;
+ }
+
+ function program4(depth0,data) {
+
+
+ return "\n <option value=\"application/json\">application/json</option>\n";
+ }
+
+ stack1 = helpers['if'].call(depth0, depth0.produces, {hash:{},inverse:self.program(4, program4, data),fn:self.program(1, program1, data),data:data});
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n</select>\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['signature'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;
+
+
+ buffer += "<div>\n<ul class=\"signature-nav\">\n <li><a class=\"description-link\" href=\"#\">Model</a></li>\n <li><a class=\"snippet-link\" href=\"#\">Model Schema</a></li>\n</ul>\n<div>\n\n<div class=\"signature-container\">\n <div class=\"description\">\n ";
+ if (stack1 = helpers.signature) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.signature; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "\n </div>\n\n <div class=\"snippet\">\n <pre><code>";
+ if (stack1 = helpers.sampleJSON) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.sampleJSON; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</code></pre>\n <small class=\"notice\"></small>\n </div>\n</div>\n\n";
+ return buffer;
+ });
+})();
+
+(function() {
+ var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
+ templates['status_code'] = template(function (Handlebars,depth0,helpers,partials,data) {
+ this.compilerInfo = [4,'>= 1.0.0'];
+ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
+ var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;
+
+
+ buffer += "<td width='15%' class='code'>";
+ if (stack1 = helpers.code) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.code; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ buffer += escapeExpression(stack1)
+ + "</td>\n<td>";
+ if (stack1 = helpers.message) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
+ else { stack1 = depth0.message; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
+ if(stack1 || stack1 === 0) { buffer += stack1; }
+ buffer += "</td>\n";
+ return buffer;
+ });
+})();
+
+
+
+// Generated by CoffeeScript 1.6.3
+(function() {
+ var ContentTypeView, HeaderView, MainView, OperationView, ParameterContentTypeView, ParameterView, ResourceView, ResponseContentTypeView, SignatureView, StatusCodeView, SwaggerUi, _ref, _ref1, _ref10, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9,
+ __hasProp = {}.hasOwnProperty,
+ __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
+
+ SwaggerUi = (function(_super) {
+ __extends(SwaggerUi, _super);
+
+ function SwaggerUi() {
+ _ref = SwaggerUi.__super__.constructor.apply(this, arguments);
+ return _ref;
+ }
+
+ SwaggerUi.prototype.dom_id = "swagger_ui";
+
+ SwaggerUi.prototype.options = null;
+
+ SwaggerUi.prototype.api = null;
+
+ SwaggerUi.prototype.headerView = null;
+
+ SwaggerUi.prototype.mainView = null;
+
+ SwaggerUi.prototype.initialize = function(options) {
+ var _this = this;
+ if (options == null) {
+ options = {};
+ }
+ if (options.dom_id != null) {
+ this.dom_id = options.dom_id;
+ delete options.dom_id;
+ }
+ if ($('#' + this.dom_id) == null) {
+ $('body').append('<div id="' + this.dom_id + '"></div>');
+ }
+ this.options = options;
+ this.options.success = function() {
+ return _this.render();
+ };
+ this.options.progress = function(d) {
+ return _this.showMessage(d);
+ };
+ this.options.failure = function(d) {
+ return _this.onLoadFailure(d);
+ };
+ this.headerView = new HeaderView({
+ el: $('#header')
+ });
+ return this.headerView.on('update-swagger-ui', function(data) {
+ return _this.updateSwaggerUi(data);
+ });
+ };
+
+ SwaggerUi.prototype.updateSwaggerUi = function(data) {
+ this.options.url = data.url;
+ return this.load();
+ };
+
+ SwaggerUi.prototype.load = function() {
+ var url, _ref1;
+ if ((_ref1 = this.mainView) != null) {
+ _ref1.clear();
+ }
+ url = this.options.url;
+ if (url.indexOf("http") !== 0) {
+ url = this.buildUrl(window.location.href.toString(), url);
+ }
+ this.options.url = url;
+ this.headerView.update(url);
+ this.api = new SwaggerApi(this.options);
+ this.api.build();
+ return this.api;
+ };
+
+ SwaggerUi.prototype.render = function() {
+ var _this = this;
+ this.showMessage('Finished Loading Resource Information. Rendering Swagger UI...');
+ this.mainView = new MainView({
+ model: this.api,
+ el: $('#' + this.dom_id)
+ }).render();
+ this.showMessage();
+ switch (this.options.docExpansion) {
+ case "full":
+ Docs.expandOperationsForResource('');
+ break;
+ case "list":
+ Docs.collapseOperationsForResource('');
+ }
+ if (this.options.onComplete) {
+ this.options.onComplete(this.api, this);
+ }
+ return setTimeout(function() {
+ return Docs.shebang();
+ }, 400);
+ };
+
+ SwaggerUi.prototype.buildUrl = function(base, url) {
+ var parts;
+ console.log("base is " + base);
+ parts = base.split("/");
+ base = parts[0] + "//" + parts[2];
+ if (url.indexOf("/") === 0) {
+ return base + url;
+ } else {
+ return base + "/" + url;
+ }
+ };
+
+ SwaggerUi.prototype.showMessage = function(data) {
+ if (data == null) {
+ data = '';
+ }
+ $('#message-bar').removeClass('message-fail');
+ $('#message-bar').addClass('message-success');
+ return $('#message-bar').html(data);
+ };
+
+ SwaggerUi.prototype.onLoadFailure = function(data) {
+ var val;
+ if (data == null) {
+ data = '';
+ }
+ $('#message-bar').removeClass('message-success');
+ $('#message-bar').addClass('message-fail');
+ val = $('#message-bar').html(data);
+ if (this.options.onFailure != null) {
+ this.options.onFailure(data);
+ }
+ return val;
+ };
+
+ return SwaggerUi;
+
+ })(Backbone.Router);
+
+ window.SwaggerUi = SwaggerUi;
+
+ HeaderView = (function(_super) {
+ __extends(HeaderView, _super);
+
+ function HeaderView() {
+ _ref1 = HeaderView.__super__.constructor.apply(this, arguments);
+ return _ref1;
+ }
+
+ HeaderView.prototype.events = {
+ 'click #show-pet-store-icon': 'showPetStore',
+ 'click #show-wordnik-dev-icon': 'showWordnikDev',
+ 'click #explore': 'showCustom',
+ 'keyup #input_baseUrl': 'showCustomOnKeyup',
+ 'keyup #input_apiKey': 'showCustomOnKeyup'
+ };
+
+ HeaderView.prototype.initialize = function() {};
+
+ HeaderView.prototype.showPetStore = function(e) {
+ return this.trigger('update-swagger-ui', {
+ url: "http://petstore.swagger.wordnik.com/api/api-docs"
+ });
+ };
+
+ HeaderView.prototype.showWordnikDev = function(e) {
+ return this.trigger('update-swagger-ui', {
+ url: "http://api.wordnik.com/v4/resources.json"
+ });
+ };
+
+ HeaderView.prototype.showCustomOnKeyup = function(e) {
+ if (e.keyCode === 13) {
+ return this.showCustom();
+ }
+ };
+
+ HeaderView.prototype.showCustom = function(e) {
+ if (e != null) {
+ e.preventDefault();
+ }
+ return this.trigger('update-swagger-ui', {
+ url: $('#input_baseUrl').val(),
+ apiKey: $('#input_apiKey').val()
+ });
+ };
+
+ HeaderView.prototype.update = function(url, apiKey, trigger) {
+ if (trigger == null) {
+ trigger = false;
+ }
+ $('#input_baseUrl').val(url);
+ if (trigger) {
+ return this.trigger('update-swagger-ui', {
+ url: url
+ });
+ }
+ };
+
+ return HeaderView;
+
+ })(Backbone.View);
+
+ MainView = (function(_super) {
+ __extends(MainView, _super);
+
+ function MainView() {
+ _ref2 = MainView.__super__.constructor.apply(this, arguments);
+ return _ref2;
+ }
+
+ MainView.prototype.initialize = function() {};
+
+ MainView.prototype.render = function() {
+ var resource, _i, _len, _ref3;
+ $(this.el).html(Handlebars.templates.main(this.model));
+ _ref3 = this.model.apisArray;
+ for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
+ resource = _ref3[_i];
+ this.addResource(resource);
+ }
+ return this;
+ };
+
+ MainView.prototype.addResource = function(resource) {
+ var resourceView;
+ resourceView = new ResourceView({
+ model: resource,
+ tagName: 'li',
+ id: 'resource_' + resource.name,
+ className: 'resource'
+ });
+ return $('#resources').append(resourceView.render().el);
+ };
+
+ MainView.prototype.clear = function() {
+ return $(this.el).html('');
+ };
+
+ return MainView;
+
+ })(Backbone.View);
+
+ ResourceView = (function(_super) {
+ __extends(ResourceView, _super);
+
+ function ResourceView() {
+ _ref3 = ResourceView.__super__.constructor.apply(this, arguments);
+ return _ref3;
+ }
+
+ ResourceView.prototype.initialize = function() {};
+
+ ResourceView.prototype.render = function() {
+ var operation, _i, _len, _ref4;
+ console.log(this.model.description);
+ $(this.el).html(Handlebars.templates.resource(this.model));
+ this.number = 0;
+ _ref4 = this.model.operationsArray;
+ for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
+ operation = _ref4[_i];
+ this.addOperation(operation);
+ }
+ return this;
+ };
+
+ ResourceView.prototype.addOperation = function(operation) {
+ var operationView;
+ operation.number = this.number;
+ operationView = new OperationView({
+ model: operation,
+ tagName: 'li',
+ className: 'endpoint'
+ });
+ $('.endpoints', $(this.el)).append(operationView.render().el);
+ return this.number++;
+ };
+
+ return ResourceView;
+
+ })(Backbone.View);
+
+ OperationView = (function(_super) {
+ __extends(OperationView, _super);
+
+ function OperationView() {
+ _ref4 = OperationView.__super__.constructor.apply(this, arguments);
+ return _ref4;
+ }
+
+ OperationView.prototype.invocationUrl = null;
+
+ OperationView.prototype.events = {
+ 'submit .sandbox': 'submitOperation',
+ 'click .submit': 'submitOperation',
+ 'click .response_hider': 'hideResponse',
+ 'click .toggleOperation': 'toggleOperationContent'
+ };
+
+ OperationView.prototype.initialize = function() {};
+
+ OperationView.prototype.render = function() {
+ var contentTypeModel, isMethodSubmissionSupported, param, responseContentTypeView, responseSignatureView, signatureModel, statusCode, type, _i, _j, _k, _len, _len1, _len2, _ref5, _ref6, _ref7;
+ isMethodSubmissionSupported = true;
+ if (!isMethodSubmissionSupported) {
+ this.model.isReadOnly = true;
+ }
+ $(this.el).html(Handlebars.templates.operation(this.model));
+ if (this.model.responseClassSignature && this.model.responseClassSignature !== 'string') {
+ signatureModel = {
+ sampleJSON: this.model.responseSampleJSON,
+ isParam: false,
+ signature: this.model.responseClassSignature
+ };
+ responseSignatureView = new SignatureView({
+ model: signatureModel,
+ tagName: 'div'
+ });
+ $('.model-signature', $(this.el)).append(responseSignatureView.render().el);
+ } else {
+ $('.model-signature', $(this.el)).html(this.model.type);
+ }
+ contentTypeModel = {
+ isParam: false
+ };
+ contentTypeModel.consumes = this.model.consumes;
+ contentTypeModel.produces = this.model.produces;
+ _ref5 = this.model.parameters;
+ for (_i = 0, _len = _ref5.length; _i < _len; _i++) {
+ param = _ref5[_i];
+ type = param.type || param.dataType;
+ if (type.toLowerCase() === 'file') {
+ if (!contentTypeModel.consumes) {
+ console.log("set content type ");
+ contentTypeModel.consumes = 'multipart/form-data';
+ }
+ }
+ }
+ responseContentTypeView = new ResponseContentTypeView({
+ model: contentTypeModel
+ });
+ $('.response-content-type', $(this.el)).append(responseContentTypeView.render().el);
+ _ref6 = this.model.parameters;
+ for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) {
+ param = _ref6[_j];
+ this.addParameter(param, contentTypeModel.consumes);
+ }
+ _ref7 = this.model.responseMessages;
+ for (_k = 0, _len2 = _ref7.length; _k < _len2; _k++) {
+ statusCode = _ref7[_k];
+ this.addStatusCode(statusCode);
+ }
+ return this;
+ };
+
+ OperationView.prototype.addParameter = function(param, consumes) {
+ var paramView;
+ param.consumes = consumes;
+ paramView = new ParameterView({
+ model: param,
+ tagName: 'tr',
+ readOnly: this.model.isReadOnly
+ });
+ return $('.operation-params', $(this.el)).append(paramView.render().el);
+ };
+
+ OperationView.prototype.addStatusCode = function(statusCode) {
+ var statusCodeView;
+ statusCodeView = new StatusCodeView({
+ model: statusCode,
+ tagName: 'tr'
+ });
+ return $('.operation-status', $(this.el)).append(statusCodeView.render().el);
+ };
+
+ OperationView.prototype.submitOperation = function(e) {
+ var error_free, form, isFileUpload, map, o, opts, val, _i, _j, _k, _len, _len1, _len2, _ref5, _ref6, _ref7;
+ if (e != null) {
+ e.preventDefault();
+ }
+ form = $('.sandbox', $(this.el));
+ error_free = true;
+ form.find("input.required").each(function() {
+ var _this = this;
+ $(this).removeClass("error");
+ if (jQuery.trim($(this).val()) === "") {
+ $(this).addClass("error");
+ $(this).wiggle({
+ callback: function() {
+ return $(_this).focus();
+ }
+ });
+ return error_free = false;
+ }
+ });
+ if (error_free) {
+ map = {};
+ opts = {
+ parent: this
+ };
+ isFileUpload = false;
+ _ref5 = form.find("input");
+ for (_i = 0, _len = _ref5.length; _i < _len; _i++) {
+ o = _ref5[_i];
+ if ((o.value != null) && jQuery.trim(o.value).length > 0) {
+ map[o.name] = o.value;
+ }
+ if (o.type === "file") {
+ isFileUpload = true;
+ }
+ }
+ _ref6 = form.find("textarea");
+ for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) {
+ o = _ref6[_j];
+ if ((o.value != null) && jQuery.trim(o.value).length > 0) {
+ map["body"] = o.value;
+ }
+ }
+ _ref7 = form.find("select");
+ for (_k = 0, _len2 = _ref7.length; _k < _len2; _k++) {
+ o = _ref7[_k];
+ val = this.getSelectedValue(o);
+ if ((val != null) && jQuery.trim(val).length > 0) {
+ map[o.name] = val;
+ }
+ }
+ opts.responseContentType = $("div select[name=responseContentType]", $(this.el)).val();
+ opts.requestContentType = $("div select[name=parameterContentType]", $(this.el)).val();
+ $(".response_throbber", $(this.el)).show();
+ if (isFileUpload) {
+ return this.handleFileUpload(map, form);
+ } else {
+ return this.model["do"](map, opts, this.showCompleteStatus, this.showErrorStatus, this);
+ }
+ }
+ };
+
+ OperationView.prototype.success = function(response, parent) {
+ return parent.showCompleteStatus(response);
+ };
+
+ OperationView.prototype.handleFileUpload = function(map, form) {
+ var bodyParam, headerParams, o, obj, param, _i, _j, _k, _len, _len1, _len2, _ref5, _ref6, _ref7,
+ _this = this;
+ console.log("it's a file upload");
+ _ref5 = form.serializeArray();
+ for (_i = 0, _len = _ref5.length; _i < _len; _i++) {
+ o = _ref5[_i];
+ if ((o.value != null) && jQuery.trim(o.value).length > 0) {
+ map[o.name] = o.value;
+ }
+ }
+ bodyParam = new FormData();
+ _ref6 = this.model.parameters;
+ for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) {
+ param = _ref6[_j];
+ if (param.paramType === 'form') {
+ bodyParam.append(param.name, map[param.name]);
+ }
+ }
+ headerParams = {};
+ _ref7 = this.model.parameters;
+ for (_k = 0, _len2 = _ref7.length; _k < _len2; _k++) {
+ param = _ref7[_k];
+ if (param.paramType === 'header') {
+ headerParams[param.name] = map[param.name];
+ }
+ }
+ console.log(headerParams);
+ $.each($('input[type~="file"]'), function(i, el) {
+ return bodyParam.append($(el).attr('name'), el.files[0]);
+ });
+ console.log(bodyParam);
+ this.invocationUrl = this.model.supportHeaderParams() ? (headerParams = this.model.getHeaderParams(map), this.model.urlify(map, false)) : this.model.urlify(map, true);
+ $(".request_url", $(this.el)).html("<pre>" + this.invocationUrl + "</pre>");
+ obj = {
+ type: this.model.method,
+ url: this.invocationUrl,
+ headers: headerParams,
+ data: bodyParam,
+ dataType: 'json',
+ contentType: false,
+ processData: false,
+ error: function(data, textStatus, error) {
+ return _this.showErrorStatus(_this.wrap(data), _this);
+ },
+ success: function(data) {
+ return _this.showResponse(data, _this);
+ },
+ complete: function(data) {
+ return _this.showCompleteStatus(_this.wrap(data), _this);
+ }
+ };
+ if (window.authorizations) {
+ window.authorizations.apply(obj);
+ }
+ jQuery.ajax(obj);
+ return false;
+ };
+
+ OperationView.prototype.wrap = function(data) {
+ var o,
+ _this = this;
+ o = {};
+ o.content = {};
+ o.content.data = data.responseText;
+ o.getHeaders = function() {
+ return {
+ "Content-Type": data.getResponseHeader("Content-Type")
+ };
+ };
+ o.request = {};
+ o.request.url = this.invocationUrl;
+ o.status = data.status;
+ return o;
+ };
+
+ OperationView.prototype.getSelectedValue = function(select) {
+ var opt, options, _i, _len, _ref5;
+ if (!select.multiple) {
+ return select.value;
+ } else {
+ options = [];
+ _ref5 = select.options;
+ for (_i = 0, _len = _ref5.length; _i < _len; _i++) {
+ opt = _ref5[_i];
+ if (opt.selected) {
+ options.push(opt.value);
+ }
+ }
+ if (options.length > 0) {
+ return options.join(",");
+ } else {
+ return null;
+ }
+ }
+ };
+
+ OperationView.prototype.hideResponse = function(e) {
+ if (e != null) {
+ e.preventDefault();
+ }
+ $(".response", $(this.el)).slideUp();
+ return $(".response_hider", $(this.el)).fadeOut();
+ };
+
+ OperationView.prototype.showResponse = function(response) {
+ var prettyJson;
+ prettyJson = JSON.stringify(response, null, "\t").replace(/\n/g, "<br>");
+ return $(".response_body", $(this.el)).html(escape(prettyJson));
+ };
+
+ OperationView.prototype.showErrorStatus = function(data, parent) {
+ return parent.showStatus(data);
+ };
+
+ OperationView.prototype.showCompleteStatus = function(data, parent) {
+ return parent.showStatus(data);
+ };
+
+ OperationView.prototype.formatXml = function(xml) {
+ var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
+ reg = /(>)(<)(\/*)/g;
+ wsexp = /[ ]*(.*)[ ]+\n/g;
+ contexp = /(<.+>)(.+\n)/g;
+ xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
+ pad = 0;
+ formatted = '';
+ lines = xml.split('\n');
+ indent = 0;
+ lastType = 'other';
+ transitions = {
+ 'single->single': 0,
+ 'single->closing': -1,
+ 'single->opening': 0,
+ 'single->other': 0,
+ 'closing->single': 0,
+ 'closing->closing': -1,
+ 'closing->opening': 0,
+ 'closing->other': 0,
+ 'opening->single': 1,
+ 'opening->closing': 0,
+ 'opening->opening': 1,
+ 'opening->other': 1,
+ 'other->single': 0,
+ 'other->closing': -1,
+ 'other->opening': 0,
+ 'other->other': 0
+ };
+ _fn = function(ln) {
+ var fromTo, j, key, padding, type, types, value;
+ types = {
+ single: Boolean(ln.match(/<.+\/>/)),
+ closing: Boolean(ln.match(/<\/.+>/)),
+ opening: Boolean(ln.match(/<[^!?].*>/))
+ };
+ type = ((function() {
+ var _results;
+ _results = [];
+ for (key in types) {
+ value = types[key];
+ if (value) {
+ _results.push(key);
+ }
+ }
+ return _results;
+ })())[0];
+ type = type === void 0 ? 'other' : type;
+ fromTo = lastType + '->' + type;
+ lastType = type;
+ padding = '';
+ indent += transitions[fromTo];
+ padding = ((function() {
+ var _j, _ref5, _results;
+ _results = [];
+ for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
+ _results.push(' ');
+ }
+ return _results;
+ })()).join('');
+ if (fromTo === 'opening->closing') {
+ return formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
+ } else {
+ return formatted += padding + ln + '\n';
+ }
+ };
+ for (_i = 0, _len = lines.length; _i < _len; _i++) {
+ ln = lines[_i];
+ _fn(ln);
+ }
+ return formatted;
+ };
+
+ OperationView.prototype.showStatus = function(data) {
+ var code, content, contentType, headers, pre, response_body;
+ content = data.content.data;
+ headers = data.getHeaders();
+ contentType = headers["Content-Type"];
+ if (content === void 0) {
+ code = $('<code />').text("no content");
+ pre = $('<pre class="json" />').append(code);
+ } else if (contentType.indexOf("application/json") === 0 || contentType.indexOf("application/hal+json") === 0) {
+ code = $('<code />').text(JSON.stringify(JSON.parse(content), null, 2));
+ pre = $('<pre class="json" />').append(code);
+ } else if (contentType.indexOf("application/xml") === 0) {
+ code = $('<code />').text(this.formatXml(content));
+ pre = $('<pre class="xml" />').append(code);
+ } else if (contentType.indexOf("text/html") === 0) {
+ code = $('<code />').html(content);
+ pre = $('<pre class="xml" />').append(code);
+ } else if (contentType.indexOf("image/") === 0) {
+ pre = $('<img>').attr('src', data.request.url);
+ } else {
+ code = $('<code />').text(content);
+ pre = $('<pre class="json" />').append(code);
+ }
+ response_body = pre;
+ $(".request_url", $(this.el)).html("<pre>" + data.request.url + "</pre>");
+ $(".response_code", $(this.el)).html("<pre>" + data.status + "</pre>");
+ $(".response_body", $(this.el)).html(response_body);
+ $(".response_headers", $(this.el)).html("<pre>" + JSON.stringify(data.getHeaders(), null, " ").replace(/\n/g, "<br>") + "</pre>");
+ $(".response", $(this.el)).slideDown();
+ $(".response_hider", $(this.el)).show();
+ $(".response_throbber", $(this.el)).hide();
+ return hljs.highlightBlock($('.response_body', $(this.el))[0]);
+ };
+
+ OperationView.prototype.toggleOperationContent = function() {
+ var elem;
+ elem = $('#' + Docs.escapeResourceName(this.model.resourceName) + "_" + this.model.nickname + "_" + this.model.method + "_" + this.model.number + "_content");
+ if (elem.is(':visible')) {
+ return Docs.collapseOperation(elem);
+ } else {
+ return Docs.expandOperation(elem);
+ }
+ };
+
+ return OperationView;
+
+ })(Backbone.View);
+
+ StatusCodeView = (function(_super) {
+ __extends(StatusCodeView, _super);
+
+ function StatusCodeView() {
+ _ref5 = StatusCodeView.__super__.constructor.apply(this, arguments);
+ return _ref5;
+ }
+
+ StatusCodeView.prototype.initialize = function() {};
+
+ StatusCodeView.prototype.render = function() {
+ var template;
+ template = this.template();
+ $(this.el).html(template(this.model));
+ return this;
+ };
+
+ StatusCodeView.prototype.template = function() {
+ return Handlebars.templates.status_code;
+ };
+
+ return StatusCodeView;
+
+ })(Backbone.View);
+
+ ParameterView = (function(_super) {
+ __extends(ParameterView, _super);
+
+ function ParameterView() {
+ _ref6 = ParameterView.__super__.constructor.apply(this, arguments);
+ return _ref6;
+ }
+
+ ParameterView.prototype.initialize = function() {};
+
+ ParameterView.prototype.render = function() {
+ var contentTypeModel, isParam, parameterContentTypeView, responseContentTypeView, signatureModel, signatureView, template, type;
+ type = this.model.type || this.model.dataType;
+ if (this.model.paramType === 'body') {
+ this.model.isBody = true;
+ }
+ if (type.toLowerCase() === 'file') {
+ this.model.isFile = true;
+ }
+ template = this.template();
+ $(this.el).html(template(this.model));
+ signatureModel = {
+ sampleJSON: this.model.sampleJSON,
+ isParam: true,
+ signature: this.model.signature
+ };
+ if (this.model.sampleJSON) {
+ signatureView = new SignatureView({
+ model: signatureModel,
+ tagName: 'div'
+ });
+ $('.model-signature', $(this.el)).append(signatureView.render().el);
+ } else {
+ $('.model-signature', $(this.el)).html(this.model.signature);
+ }
+ isParam = false;
+ if (this.model.isBody) {
+ isParam = true;
+ }
+ contentTypeModel = {
+ isParam: isParam
+ };
+ contentTypeModel.consumes = this.model.consumes;
+ if (isParam) {
+ parameterContentTypeView = new ParameterContentTypeView({
+ model: contentTypeModel
+ });
+ $('.parameter-content-type', $(this.el)).append(parameterContentTypeView.render().el);
+ } else {
+ responseContentTypeView = new ResponseContentTypeView({
+ model: contentTypeModel
+ });
+ $('.response-content-type', $(this.el)).append(responseContentTypeView.render().el);
+ }
+ return this;
+ };
+
+ ParameterView.prototype.template = function() {
+ if (this.model.isList) {
+ return Handlebars.templates.param_list;
+ } else {
+ if (this.options.readOnly) {
+ if (this.model.required) {
+ return Handlebars.templates.param_readonly_required;
+ } else {
+ return Handlebars.templates.param_readonly;
+ }
+ } else {
+ if (this.model.required) {
+ return Handlebars.templates.param_required;
+ } else {
+ return Handlebars.templates.param;
+ }
+ }
+ }
+ };
+
+ return ParameterView;
+
+ })(Backbone.View);
+
+ SignatureView = (function(_super) {
+ __extends(SignatureView, _super);
+
+ function SignatureView() {
+ _ref7 = SignatureView.__super__.constructor.apply(this, arguments);
+ return _ref7;
+ }
+
+ SignatureView.prototype.events = {
+ 'click a.description-link': 'switchToDescription',
+ 'click a.snippet-link': 'switchToSnippet',
+ 'mousedown .snippet': 'snippetToTextArea'
+ };
+
+ SignatureView.prototype.initialize = function() {};
+
+ SignatureView.prototype.render = function() {
+ var template;
+ template = this.template();
+ $(this.el).html(template(this.model));
+ this.switchToDescription();
+ this.isParam = this.model.isParam;
+ if (this.isParam) {
+ $('.notice', $(this.el)).text('Click to set as parameter value');
+ }
+ return this;
+ };
+
+ SignatureView.prototype.template = function() {
+ return Handlebars.templates.signature;
+ };
+
+ SignatureView.prototype.switchToDescription = function(e) {
+ if (e != null) {
+ e.preventDefault();
+ }
+ $(".snippet", $(this.el)).hide();
+ $(".description", $(this.el)).show();
+ $('.description-link', $(this.el)).addClass('selected');
+ return $('.snippet-link', $(this.el)).removeClass('selected');
+ };
+
+ SignatureView.prototype.switchToSnippet = function(e) {
+ if (e != null) {
+ e.preventDefault();
+ }
+ $(".description", $(this.el)).hide();
+ $(".snippet", $(this.el)).show();
+ $('.snippet-link', $(this.el)).addClass('selected');
+ return $('.description-link', $(this.el)).removeClass('selected');
+ };
+
+ SignatureView.prototype.snippetToTextArea = function(e) {
+ var textArea;
+ if (this.isParam) {
+ if (e != null) {
+ e.preventDefault();
+ }
+ textArea = $('textarea', $(this.el.parentNode.parentNode.parentNode));
+ if ($.trim(textArea.val()) === '') {
+ return textArea.val(this.model.sampleJSON);
+ }
+ }
+ };
+
+ return SignatureView;
+
+ })(Backbone.View);
+
+ ContentTypeView = (function(_super) {
+ __extends(ContentTypeView, _super);
+
+ function ContentTypeView() {
+ _ref8 = ContentTypeView.__super__.constructor.apply(this, arguments);
+ return _ref8;
+ }
+
+ ContentTypeView.prototype.initialize = function() {};
+
+ ContentTypeView.prototype.render = function() {
+ var template;
+ template = this.template();
+ $(this.el).html(template(this.model));
+ $('label[for=contentType]', $(this.el)).text('Response Content Type');
+ return this;
+ };
+
+ ContentTypeView.prototype.template = function() {
+ return Handlebars.templates.content_type;
+ };
+
+ return ContentTypeView;
+
+ })(Backbone.View);
+
+ ResponseContentTypeView = (function(_super) {
+ __extends(ResponseContentTypeView, _super);
+
+ function ResponseContentTypeView() {
+ _ref9 = ResponseContentTypeView.__super__.constructor.apply(this, arguments);
+ return _ref9;
+ }
+
+ ResponseContentTypeView.prototype.initialize = function() {};
+
+ ResponseContentTypeView.prototype.render = function() {
+ var template;
+ template = this.template();
+ $(this.el).html(template(this.model));
+ $('label[for=responseContentType]', $(this.el)).text('Response Content Type');
+ return this;
+ };
+
+ ResponseContentTypeView.prototype.template = function() {
+ return Handlebars.templates.response_content_type;
+ };
+
+ return ResponseContentTypeView;
+
+ })(Backbone.View);
+
+ ParameterContentTypeView = (function(_super) {
+ __extends(ParameterContentTypeView, _super);
+
+ function ParameterContentTypeView() {
+ _ref10 = ParameterContentTypeView.__super__.constructor.apply(this, arguments);
+ return _ref10;
+ }
+
+ ParameterContentTypeView.prototype.initialize = function() {};
+
+ ParameterContentTypeView.prototype.render = function() {
+ var template;
+ template = this.template();
+ $(this.el).html(template(this.model));
+ $('label[for=parameterContentType]', $(this.el)).text('Parameter content type:');
+ return this;
+ };
+
+ ParameterContentTypeView.prototype.template = function() {
+ return Handlebars.templates.parameter_content_type;
+ };
+
+ return ParameterContentTypeView;
+
+ })(Backbone.View);
+
+}).call(this);
--- /dev/null
+// Generated by CoffeeScript 1.6.3
+(function() {
+ var ApiKeyAuthorization, PasswordAuthorization, SwaggerApi, SwaggerAuthorizations, SwaggerHttp, SwaggerModel, SwaggerModelProperty, SwaggerOperation, SwaggerRequest, SwaggerResource,
+ __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
+
+ SwaggerApi = (function() {
+ SwaggerApi.prototype.url = "http://api.wordnik.com/v4/resources.json";
+
+ SwaggerApi.prototype.debug = false;
+
+ SwaggerApi.prototype.basePath = null;
+
+ SwaggerApi.prototype.authorizations = null;
+
+ SwaggerApi.prototype.authorizationScheme = null;
+
+ SwaggerApi.prototype.info = null;
+
+ function SwaggerApi(url, options) {
+ if (options == null) {
+ options = {};
+ }
+ if (url) {
+ if (url.url) {
+ options = url;
+ } else {
+ this.url = url;
+ }
+ } else {
+ options = url;
+ }
+ if (options.url != null) {
+ this.url = options.url;
+ }
+ if (options.success != null) {
+ this.success = options.success;
+ }
+ this.failure = options.failure != null ? options.failure : function() {};
+ this.progress = options.progress != null ? options.progress : function() {};
+ if (options.success != null) {
+ this.build();
+ }
+ }
+
+ SwaggerApi.prototype.build = function() {
+ var e, obj,
+ _this = this;
+ this.progress('fetching resource list: ' + this.url);
+ var response;
+ response = JSON.parse(getSpec());
+
+ _this.swaggerVersion = response.swaggerVersion;
+ if (_this.swaggerVersion === "1.2") {
+ setTimeout(function(){return _this.buildFromSpec(response);}, 500);
+ } else {
+ return setTimeout(function(){return _this.buildFrom1_1Spec(response);}, 500);
+ }
+ return this;
+ };
+
+ SwaggerApi.prototype.buildFromSpec = function(response) {
+ var api, isApi, newName, operation, res, resource, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
+ if (response.apiVersion != null) {
+ this.apiVersion = response.apiVersion;
+ }
+ this.apis = {};
+ this.apisArray = [];
+ this.produces = response.produces;
+ this.authSchemes = response.authorizations;
+ if (response.info != null) {
+ this.info = response.info;
+ }
+ isApi = false;
+ _ref = response.apis;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ api = _ref[_i];
+ if (api.operations) {
+ _ref1 = api.operations;
+ for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
+ operation = _ref1[_j];
+ isApi = true;
+ }
+ }
+ }
+ if (response.basePath) {
+ this.basePath = response.basePath;
+ } else if (this.url.indexOf('?') > 0) {
+ this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
+ } else {
+ this.basePath = this.url;
+ }
+ if (isApi) {
+ newName = response.resourcePath.replace(/\//g, '');
+ this.resourcePath = response.resourcePath;
+ res = new SwaggerResource(response, this);
+ this.apis[newName] = res;
+ this.apisArray.push(res);
+ } else {
+ _ref2 = response.apis;
+ for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
+ resource = _ref2[_k];
+ res = new SwaggerResource(resource, this);
+ this.apis[res.name] = res;
+ this.apisArray.push(res);
+ }
+ }
+ if (this.success) {
+ this.success();
+ }
+ return this;
+ };
+
+ SwaggerApi.prototype.buildFrom1_1Spec = function(response) {
+ var api, isApi, newName, operation, res, resource, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
+ console.log("This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info");
+ if (response.apiVersion != null) {
+ this.apiVersion = response.apiVersion;
+ }
+ this.apis = {};
+ this.apisArray = [];
+ this.produces = response.produces;
+ if (response.info != null) {
+ this.info = response.info;
+ }
+ isApi = false;
+ _ref = response.apis;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ api = _ref[_i];
+ if (api.operations) {
+ _ref1 = api.operations;
+ for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
+ operation = _ref1[_j];
+ isApi = true;
+ }
+ }
+ }
+ if (response.basePath) {
+ this.basePath = response.basePath;
+ } else if (this.url.indexOf('?') > 0) {
+ this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
+ } else {
+ this.basePath = this.url;
+ }
+ if (isApi) {
+ newName = response.resourcePath.replace(/\//g, '');
+ this.resourcePath = response.resourcePath;
+ res = new SwaggerResource(response, this);
+ this.apis[newName] = res;
+ this.apisArray.push(res);
+ } else {
+ _ref2 = response.apis;
+ for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
+ resource = _ref2[_k];
+ res = new SwaggerResource(resource, this);
+ this.apis[res.name] = res;
+ this.apisArray.push(res);
+ }
+ }
+ if (this.success) {
+ this.success();
+ }
+ return this;
+ };
+
+ SwaggerApi.prototype.selfReflect = function() {
+ var resource, resource_name, _ref;
+ if (this.apis == null) {
+ return false;
+ }
+ _ref = this.apis;
+ for (resource_name in _ref) {
+ resource = _ref[resource_name];
+ if (resource.ready == null) {
+ return false;
+ }
+ }
+ this.setConsolidatedModels();
+ this.ready = true;
+ if (this.success != null) {
+ return this.success();
+ }
+ };
+
+ SwaggerApi.prototype.fail = function(message) {
+ this.failure(message);
+ throw message;
+ };
+
+ SwaggerApi.prototype.setConsolidatedModels = function() {
+ var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results;
+ this.modelsArray = [];
+ this.models = {};
+ _ref = this.apis;
+ for (resource_name in _ref) {
+ resource = _ref[resource_name];
+ for (modelName in resource.models) {
+ if (this.models[modelName] == null) {
+ this.models[modelName] = resource.models[modelName];
+ this.modelsArray.push(resource.models[modelName]);
+ }
+ }
+ }
+ _ref1 = this.modelsArray;
+ _results = [];
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
+ model = _ref1[_i];
+ _results.push(model.setReferencedModels(this.models));
+ }
+ return _results;
+ };
+
+ SwaggerApi.prototype.help = function() {
+ var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2;
+ _ref = this.apis;
+ for (resource_name in _ref) {
+ resource = _ref[resource_name];
+ console.log(resource_name);
+ _ref1 = resource.operations;
+ for (operation_name in _ref1) {
+ operation = _ref1[operation_name];
+ console.log(" " + operation.nickname);
+ _ref2 = operation.parameters;
+ for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+ parameter = _ref2[_i];
+ console.log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
+ }
+ }
+ }
+ return this;
+ };
+
+ return SwaggerApi;
+
+ })();
+
+ SwaggerResource = (function() {
+ SwaggerResource.prototype.api = null;
+
+ SwaggerResource.prototype.produces = null;
+
+ SwaggerResource.prototype.consumes = null;
+
+ function SwaggerResource(resourceObj, api) {
+ var consumes, e, obj, parts, produces,
+ _this = this;
+ this.api = api;
+ this.api = this.api;
+ produces = [];
+ consumes = [];
+ this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path;
+ this.description = resourceObj.description;
+ parts = this.path.split("/");
+ this.name = parts[parts.length - 1].replace('.{format}', '');
+ this.basePath = this.api.basePath;
+ this.operations = {};
+ this.operationsArray = [];
+ this.modelsArray = [];
+ this.models = {};
+ if ((resourceObj.apis != null) && (this.api.resourcePath != null)) {
+ this.addApiDeclaration(resourceObj);
+ } else {
+ if (this.path == null) {
+ this.api.fail("SwaggerResources must have a path.");
+ }
+ if (this.path.substring(0, 4) === 'http') {
+ this.url = this.path.replace('{format}', 'json');
+ } else {
+ this.url = this.api.basePath + this.path.replace('{format}', 'json');
+ }
+ this.api.progress('fetching resource ' + this.name + ': ' + this.url);
+ var response;
+ var split = resourceObj.path.split("/");
+ var resource = split[split.length-1];
+ response = JSON.parse(jsonFor(resource));
+ setTimeout(function(){return _this.addApiDeclaration(response);}, 500);
+ }
+ }
+
+ SwaggerResource.prototype.addApiDeclaration = function(response) {
+ var endpoint, _i, _len, _ref;
+ if (response.produces != null) {
+ this.produces = response.produces;
+ }
+ if (response.consumes != null) {
+ this.consumes = response.consumes;
+ }
+ if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0) {
+ this.basePath = response.basePath;
+ }
+ this.addModels(response.models);
+ if (response.apis) {
+ _ref = response.apis;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ endpoint = _ref[_i];
+ this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
+ }
+ }
+ this.api[this.name] = this;
+ this.ready = true;
+ return this.api.selfReflect();
+ };
+
+ SwaggerResource.prototype.addModels = function(models) {
+ var model, modelName, swaggerModel, _i, _len, _ref, _results;
+ if (models != null) {
+ for (modelName in models) {
+ if (this.models[modelName] == null) {
+ swaggerModel = new SwaggerModel(modelName, models[modelName]);
+ this.modelsArray.push(swaggerModel);
+ this.models[modelName] = swaggerModel;
+ }
+ }
+ _ref = this.modelsArray;
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ model = _ref[_i];
+ _results.push(model.setReferencedModels(this.models));
+ }
+ return _results;
+ }
+ };
+
+ SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, produces) {
+ var method, o, op, r, ref, responseMessages, type, _i, _j, _len, _len1, _results;
+ if (ops) {
+ _results = [];
+ for (_i = 0, _len = ops.length; _i < _len; _i++) {
+ o = ops[_i];
+ consumes = this.consumes;
+ produces = this.produces;
+ if (o.consumes != null) {
+ consumes = o.consumes;
+ } else {
+ consumes = this.consumes;
+ }
+ if (o.produces != null) {
+ produces = o.produces;
+ } else {
+ produces = this.produces;
+ }
+ type = o.type || o.responseClass;
+ if (type === "array") {
+ ref = null;
+ if (o.items) {
+ ref = o.items["type"] || o.items["$ref"];
+ }
+ type = "array[" + ref + "]";
+ }
+ responseMessages = o.responseMessages;
+ method = o.method;
+ if (o.httpMethod) {
+ method = o.httpMethod;
+ }
+ if (o.supportedContentTypes) {
+ consumes = o.supportedContentTypes;
+ }
+ if (o.errorResponses) {
+ responseMessages = o.errorResponses;
+ for (_j = 0, _len1 = responseMessages.length; _j < _len1; _j++) {
+ r = responseMessages[_j];
+ r.message = r.reason;
+ r.reason = null;
+ }
+ }
+ o.nickname = this.sanitize(o.nickname);
+ op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces);
+ this.operations[op.nickname] = op;
+ _results.push(this.operationsArray.push(op));
+ }
+ return _results;
+ }
+ };
+
+ SwaggerResource.prototype.sanitize = function(nickname) {
+ var op;
+ op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]/g, '_');
+ op = op.replace(/((_){2,})/g, '_');
+ op = op.replace(/^(_)*/g, '');
+ op = op.replace(/([_])*$/g, '');
+ return op;
+ };
+
+ SwaggerResource.prototype.help = function() {
+ var msg, operation, operation_name, parameter, _i, _len, _ref, _ref1, _results;
+ _ref = this.operations;
+ _results = [];
+ for (operation_name in _ref) {
+ operation = _ref[operation_name];
+ msg = " " + operation.nickname;
+ _ref1 = operation.parameters;
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
+ parameter = _ref1[_i];
+ msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
+ }
+ _results.push(msg);
+ }
+ return _results;
+ };
+
+ return SwaggerResource;
+
+ })();
+
+ SwaggerModel = (function() {
+ function SwaggerModel(modelName, obj) {
+ var prop, propertyName, value;
+ this.name = obj.id != null ? obj.id : modelName;
+ this.properties = [];
+ for (propertyName in obj.properties) {
+ if (obj.required != null) {
+ for (value in obj.required) {
+ if (propertyName === obj.required[value]) {
+ obj.properties[propertyName].required = true;
+ }
+ }
+ }
+ prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]);
+ this.properties.push(prop);
+ }
+ }
+
+ SwaggerModel.prototype.setReferencedModels = function(allModels) {
+ var prop, type, _i, _len, _ref, _results;
+ _ref = this.properties;
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ prop = _ref[_i];
+ type = prop.type || prop.dataType;
+ if (allModels[type] != null) {
+ _results.push(prop.refModel = allModels[type]);
+ } else if ((prop.refDataType != null) && (allModels[prop.refDataType] != null)) {
+ _results.push(prop.refModel = allModels[prop.refDataType]);
+ } else {
+ _results.push(void 0);
+ }
+ }
+ return _results;
+ };
+
+ SwaggerModel.prototype.getMockSignature = function(modelsToIgnore) {
+ var classClose, classOpen, prop, propertiesStr, returnVal, strong, strongClose, stronger, _i, _j, _len, _len1, _ref, _ref1;
+ propertiesStr = [];
+ _ref = this.properties;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ prop = _ref[_i];
+ propertiesStr.push(prop.toString());
+ }
+ strong = '<span class="strong">';
+ stronger = '<span class="stronger">';
+ strongClose = '</span>';
+ classOpen = strong + this.name + ' {' + strongClose;
+ classClose = strong + '}' + strongClose;
+ returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
+ if (!modelsToIgnore) {
+ modelsToIgnore = [];
+ }
+ modelsToIgnore.push(this);
+ _ref1 = this.properties;
+ for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
+ prop = _ref1[_j];
+ if ((prop.refModel != null) && (modelsToIgnore.indexOf(prop.refModel)) === -1) {
+ returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
+ }
+ }
+ return returnVal;
+ };
+
+ SwaggerModel.prototype.createJSONSample = function(modelsToIgnore) {
+ var prop, result, _i, _len, _ref;
+ result = {};
+ modelsToIgnore = modelsToIgnore || [];
+ modelsToIgnore.push(this.name);
+ _ref = this.properties;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ prop = _ref[_i];
+ result[prop.name] = prop.getSampleValue(modelsToIgnore);
+ }
+ modelsToIgnore.pop(this.name);
+ return result;
+ };
+
+ return SwaggerModel;
+
+ })();
+
+ SwaggerModelProperty = (function() {
+ function SwaggerModelProperty(name, obj) {
+ this.name = name;
+ this.dataType = obj.type || obj.dataType || obj["$ref"];
+ this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
+ this.descr = obj.description;
+ this.required = obj.required;
+ if (obj.items != null) {
+ if (obj.items.type != null) {
+ this.refDataType = obj.items.type;
+ }
+ if (obj.items.$ref != null) {
+ this.refDataType = obj.items.$ref;
+ }
+ }
+ this.dataTypeWithRef = this.refDataType != null ? this.dataType + '[' + this.refDataType + ']' : this.dataType;
+ if (obj.allowableValues != null) {
+ this.valueType = obj.allowableValues.valueType;
+ this.values = obj.allowableValues.values;
+ if (this.values != null) {
+ this.valuesString = "'" + this.values.join("' or '") + "'";
+ }
+ }
+ if (obj["enum"] != null) {
+ this.valueType = "string";
+ this.values = obj["enum"];
+ if (this.values != null) {
+ this.valueString = "'" + this.values.join("' or '") + "'";
+ }
+ }
+ }
+
+ SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) {
+ var result;
+ if ((this.refModel != null) && (modelsToIgnore.indexOf(this.refModel.name) === -1)) {
+ result = this.refModel.createJSONSample(modelsToIgnore);
+ } else {
+ if (this.isCollection) {
+ result = this.refDataType;
+ } else {
+ result = this.dataType;
+ }
+ }
+ if (this.isCollection) {
+ return [result];
+ } else {
+ return result;
+ }
+ };
+
+ SwaggerModelProperty.prototype.toString = function() {
+ var req, str;
+ req = this.required ? 'propReq' : 'propOpt';
+ str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
+ if (!this.required) {
+ str += ', <span class="propOptKey">optional</span>';
+ }
+ str += ')';
+ if (this.values != null) {
+ str += " = <span class='propVals'>['" + this.values.join("' or '") + "']</span>";
+ }
+ if (this.descr != null) {
+ str += ': <span class="propDesc">' + this.descr + '</span>';
+ }
+ return str;
+ };
+
+ return SwaggerModelProperty;
+
+ })();
+
+ SwaggerOperation = (function() {
+ function SwaggerOperation(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces) {
+ var parameter, v, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _ref3,
+ _this = this;
+ this.nickname = nickname;
+ this.path = path;
+ this.method = method;
+ this.parameters = parameters != null ? parameters : [];
+ this.summary = summary;
+ this.notes = notes;
+ this.type = type;
+ this.responseMessages = responseMessages;
+ this.resource = resource;
+ this.consumes = consumes;
+ this.produces = produces;
+ this["do"] = __bind(this["do"], this);
+ if (this.nickname == null) {
+ this.resource.api.fail("SwaggerOperations must have a nickname.");
+ }
+ if (this.path == null) {
+ this.resource.api.fail("SwaggerOperation " + nickname + " is missing path.");
+ }
+ if (this.method == null) {
+ this.resource.api.fail("SwaggerOperation " + nickname + " is missing method.");
+ }
+ this.path = this.path.replace('{format}', 'json');
+ this.method = this.method.toLowerCase();
+ this.isGetMethod = this.method === "get";
+ this.resourceName = this.resource.name;
+ if (((_ref = this.type) != null ? _ref.toLowerCase() : void 0) === 'void') {
+ this.type = void 0;
+ }
+ if (this.type != null) {
+ this.responseClassSignature = this.getSignature(this.type, this.resource.models);
+ this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
+ }
+ this.responseMessages = this.responseMessages || [];
+ _ref1 = this.parameters;
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
+ parameter = _ref1[_i];
+ parameter.name = parameter.name || parameter.type || parameter.dataType;
+ type = parameter.type || parameter.dataType;
+ if (type.toLowerCase() === 'boolean') {
+ parameter.allowableValues = {};
+ parameter.allowableValues.values = ["true", "false"];
+ }
+ parameter.signature = this.getSignature(type, this.resource.models);
+ parameter.sampleJSON = this.getSampleJSON(type, this.resource.models);
+ if (parameter["enum"] != null) {
+ parameter.isList = true;
+ parameter.allowableValues = {};
+ parameter.allowableValues.descriptiveValues = [];
+ _ref2 = parameter["enum"];
+ for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
+ v = _ref2[_j];
+ if ((parameter.defaultValue != null) && parameter.defaultValue === v) {
+ parameter.allowableValues.descriptiveValues.push({
+ value: v,
+ isDefault: true
+ });
+ } else {
+ parameter.allowableValues.descriptiveValues.push({
+ value: v,
+ isDefault: false
+ });
+ }
+ }
+ }
+ if (parameter.allowableValues != null) {
+ if (parameter.allowableValues.valueType === "RANGE") {
+ parameter.isRange = true;
+ } else {
+ parameter.isList = true;
+ }
+ if (parameter.allowableValues.values != null) {
+ parameter.allowableValues.descriptiveValues = [];
+ _ref3 = parameter.allowableValues.values;
+ for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) {
+ v = _ref3[_k];
+ if ((parameter.defaultValue != null) && parameter.defaultValue === v) {
+ parameter.allowableValues.descriptiveValues.push({
+ value: v,
+ isDefault: true
+ });
+ } else {
+ parameter.allowableValues.descriptiveValues.push({
+ value: v,
+ isDefault: false
+ });
+ }
+ }
+ }
+ }
+ }
+ this.resource[this.nickname] = function(args, callback, error) {
+ return _this["do"](args, callback, error);
+ };
+ this.resource[this.nickname].help = function() {
+ return _this.help();
+ };
+ }
+
+ SwaggerOperation.prototype.isListType = function(type) {
+ if (type.indexOf('[') >= 0) {
+ return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
+ } else {
+ return void 0;
+ }
+ };
+
+ SwaggerOperation.prototype.getSignature = function(type, models) {
+ var isPrimitive, listType;
+ listType = this.isListType(type);
+ isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
+ if (isPrimitive) {
+ return type;
+ } else {
+ if (listType != null) {
+ return models[listType].getMockSignature();
+ } else {
+ return models[type].getMockSignature();
+ }
+ }
+ };
+
+ SwaggerOperation.prototype.getSampleJSON = function(type, models) {
+ var isPrimitive, listType, val;
+ listType = this.isListType(type);
+ isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
+ val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample());
+ if (val) {
+ val = listType ? [val] : val;
+ return JSON.stringify(val, null, 2);
+ }
+ };
+
+ SwaggerOperation.prototype["do"] = function(args, opts, callback, error) {
+ var key, param, params, possibleParams, req, requestContentType, responseContentType, value, _i, _len, _ref;
+ if (args == null) {
+ args = {};
+ }
+ if (opts == null) {
+ opts = {};
+ }
+ requestContentType = null;
+ responseContentType = null;
+ if ((typeof args) === "function") {
+ error = opts;
+ callback = args;
+ args = {};
+ }
+ if ((typeof opts) === "function") {
+ error = callback;
+ callback = opts;
+ }
+ if (error == null) {
+ error = function(xhr, textStatus, error) {
+ return console.log(xhr, textStatus, error);
+ };
+ }
+ if (callback == null) {
+ callback = function(data) {
+ var content;
+ content = null;
+ if (data.content != null) {
+ content = data.content.data;
+ } else {
+ content = "no data";
+ }
+ return console.log("default callback: " + content);
+ };
+ }
+ params = {};
+ params.headers = [];
+ if (args.headers != null) {
+ params.headers = args.headers;
+ delete args.headers;
+ }
+ _ref = this.parameters;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ param = _ref[_i];
+ if (param.paramType === "header") {
+ if (args[param.name]) {
+ params.headers[param.name] = args[param.name];
+ }
+ }
+ }
+ if (args.body != null) {
+ params.body = args.body;
+ delete args.body;
+ }
+ possibleParams = (function() {
+ var _j, _len1, _ref1, _results;
+ _ref1 = this.parameters;
+ _results = [];
+ for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
+ param = _ref1[_j];
+ if (param.paramType === "form" || param.paramType.toLowerCase() === "file") {
+ _results.push(param);
+ }
+ }
+ return _results;
+ }).call(this);
+ if (possibleParams) {
+ for (key in possibleParams) {
+ value = possibleParams[key];
+ if (args[value.name]) {
+ params[value.name] = args[value.name];
+ }
+ }
+ }
+ req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
+ if (opts.mock != null) {
+ return req;
+ } else {
+ return true;
+ }
+ };
+
+ SwaggerOperation.prototype.pathJson = function() {
+ return this.path.replace("{format}", "json");
+ };
+
+ SwaggerOperation.prototype.pathXml = function() {
+ return this.path.replace("{format}", "xml");
+ };
+
+ SwaggerOperation.prototype.urlify = function(args) {
+ var param, queryParams, reg, url, _i, _j, _len, _len1, _ref, _ref1;
+ url = this.resource.basePath + this.pathJson();
+ _ref = this.parameters;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ param = _ref[_i];
+ if (param.paramType === 'path') {
+ if (args[param.name]) {
+ reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
+ url = url.replace(reg, encodeURIComponent(args[param.name]));
+ delete args[param.name];
+ } else {
+ throw "" + param.name + " is a required path param.";
+ }
+ }
+ }
+ queryParams = "";
+ _ref1 = this.parameters;
+ for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
+ param = _ref1[_j];
+ if (param.paramType === 'query') {
+ if (args[param.name]) {
+ if (queryParams !== "") {
+ queryParams += "&";
+ }
+ queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
+ }
+ }
+ }
+ if ((queryParams != null) && queryParams.length > 0) {
+ url += "?" + queryParams;
+ }
+ return url;
+ };
+
+ SwaggerOperation.prototype.supportHeaderParams = function() {
+ return this.resource.api.supportHeaderParams;
+ };
+
+ SwaggerOperation.prototype.supportedSubmitMethods = function() {
+ return this.resource.api.supportedSubmitMethods;
+ };
+
+ SwaggerOperation.prototype.getQueryParams = function(args) {
+ return this.getMatchingParams(['query'], args);
+ };
+
+ SwaggerOperation.prototype.getHeaderParams = function(args) {
+ return this.getMatchingParams(['header'], args);
+ };
+
+ SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) {
+ var matchingParams, name, param, value, _i, _len, _ref, _ref1;
+ matchingParams = {};
+ _ref = this.parameters;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ param = _ref[_i];
+ if (args && args[param.name]) {
+ matchingParams[param.name] = args[param.name];
+ }
+ }
+ _ref1 = this.resource.api.headers;
+ for (name in _ref1) {
+ value = _ref1[name];
+ matchingParams[name] = value;
+ }
+ return matchingParams;
+ };
+
+ SwaggerOperation.prototype.help = function() {
+ var msg, parameter, _i, _len, _ref;
+ msg = "";
+ _ref = this.parameters;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ parameter = _ref[_i];
+ if (msg !== "") {
+ msg += "\n";
+ }
+ msg += "* " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description;
+ }
+ return msg;
+ };
+
+ return SwaggerOperation;
+
+ })();
+
+ SwaggerRequest = (function() {
+ function SwaggerRequest(type, url, params, opts, successCallback, errorCallback, operation, execution) {
+ var body, e, fields, headers, key, myHeaders, name, obj, param, parent, possibleParams, requestContentType, responseContentType, urlEncoded, value, values,
+ _this = this;
+ this.type = type;
+ this.url = url;
+ this.params = params;
+ this.opts = opts;
+ this.successCallback = successCallback;
+ this.errorCallback = errorCallback;
+ this.operation = operation;
+ this.execution = execution;
+ if (this.type == null) {
+ throw "SwaggerRequest type is required (get/post/put/delete).";
+ }
+ if (this.url == null) {
+ throw "SwaggerRequest url is required.";
+ }
+ if (this.successCallback == null) {
+ throw "SwaggerRequest successCallback is required.";
+ }
+ if (this.errorCallback == null) {
+ throw "SwaggerRequest error callback is required.";
+ }
+ if (this.operation == null) {
+ throw "SwaggerRequest operation is required.";
+ }
+ this.type = this.type.toUpperCase();
+ headers = params.headers;
+ myHeaders = {};
+ body = params.body;
+ parent = params["parent"];
+ requestContentType = "application/json";
+ if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH")) {
+ if (this.opts.requestContentType) {
+ requestContentType = this.opts.requestContentType;
+ }
+ } else {
+ if (((function() {
+ var _i, _len, _ref, _results;
+ _ref = this.operation.parameters;
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ param = _ref[_i];
+ if (param.paramType === "form") {
+ _results.push(param);
+ }
+ }
+ return _results;
+ }).call(this)).length > 0) {
+ type = param.type || param.dataType;
+ if (((function() {
+ var _i, _len, _ref, _results;
+ _ref = this.operation.parameters;
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ param = _ref[_i];
+ if (type.toLowerCase() === "file") {
+ _results.push(param);
+ }
+ }
+ return _results;
+ }).call(this)).length > 0) {
+ requestContentType = "multipart/form-data";
+ } else {
+ requestContentType = "application/x-www-form-urlencoded";
+ }
+ } else if (this.type !== "DELETE") {
+ requestContentType = null;
+ }
+ }
+ if (requestContentType && this.operation.consumes) {
+ if (this.operation.consumes.indexOf(requestContentType) === -1) {
+ console.log("server doesn't consume " + requestContentType + ", try " + JSON.stringify(this.operation.consumes));
+ if (this.requestContentType === null) {
+ requestContentType = this.operation.consumes[0];
+ }
+ }
+ }
+ responseContentType = null;
+ if (this.type === "POST" || this.type === "GET" || this.type === "PATCH") {
+ if (this.opts.responseContentType) {
+ responseContentType = this.opts.responseContentType;
+ } else {
+ responseContentType = "application/json";
+ }
+ } else {
+ responseContentType = null;
+ }
+ if (responseContentType && this.operation.produces) {
+ if (this.operation.produces.indexOf(responseContentType) === -1) {
+ console.log("server can't produce " + responseContentType);
+ }
+ }
+ if (requestContentType && requestContentType.indexOf("application/x-www-form-urlencoded") === 0) {
+ fields = {};
+ possibleParams = (function() {
+ var _i, _len, _ref, _results;
+ _ref = this.operation.parameters;
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ param = _ref[_i];
+ if (param.paramType === "form") {
+ _results.push(param);
+ }
+ }
+ return _results;
+ }).call(this);
+ values = {};
+ for (key in possibleParams) {
+ value = possibleParams[key];
+ if (this.params[value.name]) {
+ values[value.name] = this.params[value.name];
+ }
+ }
+ urlEncoded = "";
+ for (key in values) {
+ value = values[key];
+ if (urlEncoded !== "") {
+ urlEncoded += "&";
+ }
+ urlEncoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
+ }
+ body = urlEncoded;
+ }
+ for (name in headers) {
+ myHeaders[name] = headers[name];
+ }
+ if (requestContentType) {
+ myHeaders["Content-Type"] = requestContentType;
+ }
+ if (responseContentType) {
+ myHeaders["Accept"] = responseContentType;
+ }
+ if (!((headers != null) && (headers.mock != null))) {
+ obj = {
+ url: this.url,
+ method: this.type,
+ headers: myHeaders,
+ body: body,
+ on: {
+ error: function(response) {
+ return _this.errorCallback(response, _this.opts.parent);
+ },
+ redirect: function(response) {
+ return _this.successCallback(response, _this.opts.parent);
+ },
+ 307: function(response) {
+ return _this.successCallback(response, _this.opts.parent);
+ },
+ response: function(response) {
+ return _this.successCallback(response, _this.opts.parent);
+ }
+ }
+ };
+ e = {};
+ if (typeof window !== 'undefined') {
+ e = window;
+ } else {
+ e = exports;
+ }
+ e.authorizations.apply(obj);
+ if (opts.mock == null) {
+ new SwaggerHttp().execute(obj);
+ } else {
+ console.log(obj);
+ return obj;
+ }
+ }
+ }
+
+ SwaggerRequest.prototype.asCurl = function() {
+ var header_args, k, v;
+ header_args = (function() {
+ var _ref, _results;
+ _ref = this.headers;
+ _results = [];
+ for (k in _ref) {
+ v = _ref[k];
+ _results.push("--header \"" + k + ": " + v + "\"");
+ }
+ return _results;
+ }).call(this);
+ return "curl " + (header_args.join(" ")) + " " + this.url;
+ };
+
+ return SwaggerRequest;
+
+ })();
+
+ SwaggerHttp = (function() {
+ SwaggerHttp.prototype.Shred = null;
+
+ SwaggerHttp.prototype.shred = null;
+
+ SwaggerHttp.prototype.content = null;
+
+ function SwaggerHttp() {
+ var identity, toString,
+ _this = this;
+ if (typeof window !== 'undefined') {
+ this.Shred = require("./shred");
+ } else {
+ this.Shred = require("shred");
+ }
+ this.shred = new this.Shred();
+ identity = function(x) {
+ return x;
+ };
+ toString = function(x) {
+ return x.toString();
+ };
+ if (typeof window !== 'undefined') {
+ this.content = require("./shred/content");
+ this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
+ parser: identity,
+ stringify: toString
+ });
+ } else {
+ this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
+ parser: identity,
+ stringify: toString
+ });
+ }
+ }
+
+ SwaggerHttp.prototype.execute = function(obj) {
+ return this.shred.request(obj);
+ };
+
+ return SwaggerHttp;
+
+ })();
+
+ SwaggerAuthorizations = (function() {
+ SwaggerAuthorizations.prototype.authz = null;
+
+ function SwaggerAuthorizations() {
+ this.authz = {};
+ }
+
+ SwaggerAuthorizations.prototype.add = function(name, auth) {
+ this.authz[name] = auth;
+ return auth;
+ };
+
+ SwaggerAuthorizations.prototype.apply = function(obj) {
+ var key, value, _ref, _results;
+ _ref = this.authz;
+ _results = [];
+ for (key in _ref) {
+ value = _ref[key];
+ _results.push(value.apply(obj));
+ }
+ return _results;
+ };
+
+ return SwaggerAuthorizations;
+
+ })();
+
+ ApiKeyAuthorization = (function() {
+ ApiKeyAuthorization.prototype.type = null;
+
+ ApiKeyAuthorization.prototype.name = null;
+
+ ApiKeyAuthorization.prototype.value = null;
+
+ function ApiKeyAuthorization(name, value, type) {
+ this.name = name;
+ this.value = value;
+ this.type = type;
+ }
+
+ ApiKeyAuthorization.prototype.apply = function(obj) {
+ if (this.type === "query") {
+ if (obj.url.indexOf('?') > 0) {
+ obj.url = obj.url + "&" + this.name + "=" + this.value;
+ } else {
+ obj.url = obj.url + "?" + this.name + "=" + this.value;
+ }
+ return true;
+ } else if (this.type === "header") {
+ return obj.headers[this.name] = this.value;
+ }
+ };
+
+ return ApiKeyAuthorization;
+
+ })();
+
+ PasswordAuthorization = (function() {
+ PasswordAuthorization.prototype.name = null;
+
+ PasswordAuthorization.prototype.username = null;
+
+ PasswordAuthorization.prototype.password = null;
+
+ function PasswordAuthorization(name, username, password) {
+ this.name = name;
+ this.username = username;
+ this.password = password;
+ }
+
+ PasswordAuthorization.prototype.apply = function(obj) {
+ return obj.headers["Authorization"] = "Basic " + btoa(this.username + ":" + this.password);
+ };
+
+ return PasswordAuthorization;
+
+ })();
+
+ this.SwaggerApi = SwaggerApi;
+
+ this.SwaggerResource = SwaggerResource;
+
+ this.SwaggerOperation = SwaggerOperation;
+
+ this.SwaggerRequest = SwaggerRequest;
+
+ this.SwaggerModelProperty = SwaggerModelProperty;
+
+ this.ApiKeyAuthorization = ApiKeyAuthorization;
+
+ this.PasswordAuthorization = PasswordAuthorization;
+
+ this.authorizations = new SwaggerAuthorizations();
+
+}).call(this);
<name>binding-async-data-broker</name>
<binding-forwarded-data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
<dom-async-broker>
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
- <name>dom-broker</name>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-async-data-broker</type>
+ <name>inmemory-data-broker</name>
</dom-async-broker>
+ <schema-service>
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
+ <name>yang-schema-service</name>
+ </schema-service>
<binding-mapping-service>
<type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">binding:binding-dom-mapping-service</type>
<name>runtime-mapping-singleton</name>
}
public DOMStore createConfigurationDatastore() {
- InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
schemaService.registerSchemaContextListener(store);
return store;
}
public DOMStore createOperationalDatastore() {
- InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER",
- MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor());
+ InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
schemaService.registerSchemaContextListener(store);
return store;
}
package test.mock.util;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-@SuppressWarnings("deprecation")
public final class MockSchemaService implements SchemaService, SchemaContextProvider {
private SchemaContext schemaContext;
assertEquals("getInventoryNodeRef", new NodeRef(invNodeID), augmentation.getInventoryNodeRef());
}
- @SuppressWarnings("rawtypes")
@Test
public void testOnNodeConnectorUpdated() {
package org.opendaylight.controller.netconf.client;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.Promise;
import java.io.Closeable;
-
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
import org.opendaylight.protocol.framework.AbstractDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.util.Timer;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.Promise;
-
public class NetconfClientDispatcherImpl extends AbstractDispatcher<NetconfClientSession, NetconfClientSessionListener>
implements NetconfClientDispatcher, Closeable {
- private static final Logger logger = LoggerFactory.getLogger(NetconfClientDispatcherImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfClientDispatcherImpl.class);
private final Timer timer;
@Override
public Future<Void> createReconnectingClient(final NetconfReconnectingClientConfiguration clientConfiguration) {
switch (clientConfiguration.getProtocol()) {
- case TCP: return createReconnectingTcpClient(clientConfiguration);
- case SSH: return createReconnectingSshClient(clientConfiguration);
- default: throw new IllegalArgumentException("Unknown client protocol " + clientConfiguration.getProtocol());
+ case TCP:
+ return createReconnectingTcpClient(clientConfiguration);
+ case SSH:
+ return createReconnectingSshClient(clientConfiguration);
+ default:
+ throw new IllegalArgumentException("Unknown client protocol " + clientConfiguration.getProtocol());
}
}
private Future<NetconfClientSession> createTcpClient(final NetconfClientConfiguration currentConfiguration) {
- logger.debug("Creating TCP client with configuration: {}", currentConfiguration);
+ LOG.debug("Creating TCP client with configuration: {}", currentConfiguration);
return super.createClient(currentConfiguration.getAddress(), currentConfiguration.getReconnectStrategy(),
new PipelineInitializer<NetconfClientSession>() {
}
private Future<Void> createReconnectingTcpClient(final NetconfReconnectingClientConfiguration currentConfiguration) {
- logger.debug("Creating reconnecting TCP client with configuration: {}", currentConfiguration);
+ LOG.debug("Creating reconnecting TCP client with configuration: {}", currentConfiguration);
final TcpClientChannelInitializer init = new TcpClientChannelInitializer(getNegotiatorFactory(currentConfiguration),
currentConfiguration.getSessionListener());
}
private Future<NetconfClientSession> createSshClient(final NetconfClientConfiguration currentConfiguration) {
- logger.debug("Creating SSH client with configuration: {}", currentConfiguration);
+ LOG.debug("Creating SSH client with configuration: {}", currentConfiguration);
return super.createClient(currentConfiguration.getAddress(), currentConfiguration.getReconnectStrategy(),
new PipelineInitializer<NetconfClientSession>() {
}
private Future<Void> createReconnectingSshClient(final NetconfReconnectingClientConfiguration currentConfiguration) {
- logger.debug("Creating reconnecting SSH client with configuration: {}", currentConfiguration);
+ LOG.debug("Creating reconnecting SSH client with configuration: {}", currentConfiguration);
final SshClientChannelInitializer init = new SshClientChannelInitializer(currentConfiguration.getAuthHandler(),
getNegotiatorFactory(currentConfiguration), currentConfiguration.getSessionListener());
package org.opendaylight.controller.netconf.client;
import io.netty.channel.Channel;
-
import java.util.Collection;
-
import org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSession;
import org.opendaylight.controller.netconf.nettyutil.handler.NetconfEXICodec;
import org.opendaylight.controller.netconf.nettyutil.handler.NetconfEXIToMessageDecoder;
public class NetconfClientSession extends AbstractNetconfSession<NetconfClientSession, NetconfClientSessionListener> {
- private static final Logger logger = LoggerFactory.getLogger(NetconfClientSession.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSession.class);
private final Collection<String> capabilities;
/**
final Collection<String> capabilities) {
super(sessionListener, channel, sessionId);
this.capabilities = capabilities;
- logger.debug("Client Session {} created", toString());
+ LOG.debug("Client Session {} created", toString());
}
public Collection<String> getServerCapabilities() {
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
-
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Timer;
import io.netty.util.concurrent.Promise;
-
import java.util.Collection;
-
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
-
import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
public class NetconfClientSessionNegotiator extends
AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession, NetconfClientSessionListener>
{
- private static final Logger logger = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
private static final XPathExpression sessionIdXPath = XMLNetconfUtil
.compileXPath("/netconf:hello/netconf:session-id");
// If exi should be used, try to initiate exi communication
// Call negotiationSuccessFul after exi negotiation is finished successfully or not
if (shouldUseExi(netconfMessage)) {
- logger.debug("Netconf session {} should use exi.", session);
+ LOG.debug("Netconf session {} should use exi.", session);
NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage();
tryToInitiateExi(session, startExiMessage);
} else {
// Exi is not supported, release session immediately
- logger.debug("Netconf session {} isn't capable of using exi.", session);
+ LOG.debug("Netconf session {} isn't capable of using exi.", session);
negotiationSuccessful(session);
}
}
@Override
public void operationComplete(final ChannelFuture f) {
if (!f.isSuccess()) {
- logger.warn("Failed to send start-exi message {} on session {}", startExiMessage, this, f.cause());
+ LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, this, f.cause());
channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
} else {
- logger.trace("Start-exi message {} sent to socket on session {}", startExiMessage, this);
+ LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, this);
}
}
});
// Ok response to start-exi, try to add exi handlers
if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
- logger.trace("Positive response on start-exi call received on session {}", session);
+ LOG.trace("Positive response on start-exi call received on session {}", session);
try {
session.startExiCommunication(startExiMessage);
} catch (RuntimeException e) {
// Unable to add exi, continue without exi
- logger.warn("Unable to start exi communication, Communication will continue without exi on session {}", session, e);
+ LOG.warn("Unable to start exi communication, Communication will continue without exi on session {}", session, e);
}
// Error response
} else if(NetconfMessageUtil.isErrorMessage(netconfMessage)) {
- logger.warn(
+ LOG.warn(
"Error response to start-exi message {}, Communication will continue without exi on session {}",
XmlUtil.toString(netconfMessage.getDocument()), session);
// Unexpected response to start-exi, throwing message away, continue without exi
} else {
- logger.warn(
- "Unexpected response to start-exi message, should be ok, was {}, " +
- "Communication will continue without exi and response message will be thrown away on session {}",
- XmlUtil.toString(netconfMessage.getDocument()), session);
+ LOG.warn(
+ "Unexpected response to start-exi message, should be ok, was {}, ",XmlUtil.toString(netconfMessage.getDocument()),
+ "Communication will continue without exi and response message will be thrown away on session {}",
+ session);
}
negotiationSuccessful(session);
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
-
import io.netty.channel.Channel;
import io.netty.util.Timer;
import io.netty.util.concurrent.Promise;
-
import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
private final long connectionTimeoutMillis;
private final Timer timer;
private final EXIOptions options;
- private static final Logger logger = LoggerFactory.getLogger(NetconfClientSessionNegotiatorFactory.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiatorFactory.class);
public NetconfClientSessionNegotiatorFactory(Timer timer,
Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
try {
helloMessage = NetconfHelloMessage.createClientHello(CLIENT_CAPABILITIES, additionalHeader);
} catch (NetconfDocumentedException e) {
- logger.error("Unable to create client hello message with capabilities {} and additional handler {}",CLIENT_CAPABILITIES,additionalHeader);
+ LOG.error("Unable to create client hello message with capabilities {} and additional handler {}",CLIENT_CAPABILITIES,additionalHeader);
throw new IllegalStateException(e);
}
package org.opendaylight.controller.netconf.client;
+import com.google.common.base.Preconditions;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
-
import java.util.ArrayDeque;
import java.util.Queue;
-
import javax.annotation.concurrent.GuardedBy;
-
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Preconditions;
-
public class SimpleNetconfClientSessionListener implements NetconfClientSessionListener {
private static final class RequestEntry {
private final Promise<NetconfMessage> promise;
}
}
- private static final Logger logger = LoggerFactory.getLogger(SimpleNetconfClientSessionListener.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SimpleNetconfClientSessionListener.class);
@GuardedBy("this")
private final Queue<RequestEntry> requests = new ArrayDeque<>();
while (!requests.isEmpty()) {
final RequestEntry e = requests.peek();
if (e.promise.setUncancellable()) {
- logger.debug("Sending message {}", e.request);
+ LOG.debug("Sending message {}", e.request);
clientSession.sendMessage(e.request);
break;
}
- logger.debug("Message {} has been cancelled, skipping it", e.request);
+ LOG.debug("Message {} has been cancelled, skipping it", e.request);
requests.poll();
}
}
@Override
public final synchronized void onSessionUp(NetconfClientSession clientSession) {
this.clientSession = Preconditions.checkNotNull(clientSession);
- logger.debug("Client session {} went up", clientSession);
+ LOG.debug("Client session {} went up", clientSession);
dispatchRequest();
}
@Override
public final void onSessionDown(NetconfClientSession clientSession, Exception e) {
- logger.debug("Client Session {} went down unexpectedly", clientSession, e);
+ LOG.debug("Client Session {} went down unexpectedly", clientSession, e);
tearDown(e);
}
@Override
public final void onSessionTerminated(NetconfClientSession clientSession,
NetconfTerminationReason netconfTerminationReason) {
- logger.debug("Client Session {} terminated, reason: {}", clientSession,
+ LOG.debug("Client Session {} terminated, reason: {}", clientSession,
netconfTerminationReason.getErrorMessage());
tearDown(new RuntimeException(netconfTerminationReason.getErrorMessage()));
}
@Override
public synchronized void onMessage(NetconfClientSession session, NetconfMessage message) {
- logger.debug("New message arrived: {}", message);
+ LOG.debug("New message arrived: {}", message);
final RequestEntry e = requests.poll();
if (e != null) {
e.promise.setSuccess(message);
dispatchRequest();
} else {
- logger.info("Ignoring unsolicited message {}", message);
+ LOG.info("Ignoring unsolicited message {}", message);
}
}
package org.opendaylight.controller.netconf.client;
import com.google.common.base.Optional;
+import java.net.InetSocketAddress;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
-import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.protocol.framework.ReconnectStrategy;
-import java.net.InetSocketAddress;
-
public class NetconfClientConfigurationTest {
@Test
public void testNetconfClientConfiguration() throws Exception {
package org.opendaylight.controller.netconf.client;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doReturn;
+
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import io.netty.util.concurrent.GenericFutureListener;
+import java.net.InetSocketAddress;
+import java.util.concurrent.Future;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
-import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
-import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
import org.opendaylight.protocol.framework.ReconnectStrategy;
import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
-import java.net.InetSocketAddress;
-import java.util.concurrent.Future;
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doReturn;
-
public class NetconfClientDispatcherImplTest {
@Test
public void testNetconfClientDispatcherImpl() throws Exception {
package org.opendaylight.controller.netconf.client;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
import com.google.common.base.Optional;
import io.netty.channel.Channel;
import io.netty.util.HashedWheelTimer;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
public class NetconfClientSessionNegotiatorFactoryTest {
@Test
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import com.google.common.base.Optional;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
pipeline = mockChannelPipeline();
future = mockChannelFuture();
channel = mockChannel();
- System.out.println("setup done");
}
private ChannelHandler mockChannelHandler() {
package org.opendaylight.controller.netconf.client;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.mock;
+
import com.google.common.collect.Lists;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
+import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.netconf.client.NetconfClientSession;
-import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
import org.opendaylight.controller.netconf.nettyutil.handler.NetconfEXICodec;
import org.openexi.proc.common.EXIOptions;
-import java.util.Collection;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-
public class NetconfClientSessionTest {
@Mock
package org.opendaylight.controller.netconf.client;
import com.google.common.base.Optional;
+import java.net.InetSocketAddress;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
-import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
import org.opendaylight.protocol.framework.ReconnectStrategy;
import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
-import java.net.InetSocketAddress;
-
public class NetconfReconnectingClientConfigurationTest {
@Test
public void testNetconfReconnectingClientConfiguration() throws Exception {
*/
package org.opendaylight.controller.netconf.client;
-import io.netty.channel.*;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.Future;
+import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.collections.Sets;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
-import java.util.Set;
-
-import static org.junit.Assert.*;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.*;
-
public class SimpleNetconfClientSessionListenerTest {
private Channel channel;
package org.opendaylight.controller.netconf.client;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.*;
-
public class SshClientChannelInitializerTest {
@Test
public void test() throws Exception {
package org.opendaylight.controller.netconf.client;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
-import static org.mockito.Mockito.*;
-
public class TcpClientChannelInitializerTest {
@Test
public void testInitializeSessionNegotiator() throws Exception {
NetconfClientDispatcherImpl netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup, hashedWheelTimer);
LoginPassword authHandler = new LoginPassword("admin", "admin");
TestingNetconfClient client = new TestingNetconfClient("client", netconfClientDispatcher, getClientConfig("127.0.0.1", 1830, true, Optional.of(authHandler)));
- System.out.println(client.getCapabilities());
+ System.console().writer().println(client.getCapabilities());
}
private static NetconfClientConfiguration getClientConfig(String host ,int port, boolean ssh, Optional<? extends AuthenticationHandler> maybeAuthHandler) throws UnknownHostException {
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
+import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
+import org.opendaylight.controller.netconf.mapping.api.Capability;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class CapabilityProviderImpl implements CapabilityProvider {
private final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot;
private final Set<String> capabilityURIs;
- private static final Logger logger = LoggerFactory.getLogger(DefaultCommitNotificationProducer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(CapabilityProviderImpl.class);
public CapabilityProviderImpl(NetconfOperationServiceSnapshot netconfOperationServiceSnapshot) {
this.netconfOperationServiceSnapshot = netconfOperationServiceSnapshot;
for (Capability cap : caps) {
if(capabilityMap.containsKey(cap.getCapabilityUri())) {
- logger.debug("Duplicate capability {} from service {}", cap.getCapabilityUri(), netconfOperationService);
+ LOG.debug("Duplicate capability {} from service {}", cap.getCapabilityUri(), netconfOperationService);
}
capabilityMap.put(cap.getCapabilityUri(), cap);
package org.opendaylight.controller.netconf.impl;
-import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
-import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean;
-import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Element;
-
+import java.util.Set;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
-import java.util.Set;
+import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
+import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean;
+import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Element;
public class DefaultCommitNotificationProducer extends NotificationBroadcasterSupport implements
DefaultCommitOperationMXBean, AutoCloseable {
- private static final Logger logger = LoggerFactory.getLogger(DefaultCommitNotificationProducer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(DefaultCommitNotificationProducer.class);
private final MBeanServer mbeanServer;
public DefaultCommitNotificationProducer(MBeanServer mBeanServer) {
this.mbeanServer = mBeanServer;
- logger.debug("Registering to JMX under {}", on);
+ LOG.debug("Registering to JMX under {}", on);
registerMBean(this, mbeanServer, on);
}
public void sendCommitNotification(String message, Element cfgSnapshot, Set<String> capabilities) {
CommitJMXNotification notif = NetconfJMXNotification.afterCommit(this, message, cfgSnapshot, capabilities);
- logger.debug("Notification about commit {} sent", notif);
+ LOG.debug("Notification about commit {} sent", notif);
sendNotification(notif);
}
try {
mbeanServer.unregisterMBean(on);
} catch (InstanceNotFoundException | MBeanRegistrationException e) {
- logger.warn("Ignoring exception while unregistering {} as {}", this, on, e);
+ LOG.warn("Ignoring exception while unregistering {} as {}", this, on, e);
}
}
}
public final class NetconfServerSession extends AbstractNetconfSession<NetconfServerSession, NetconfServerSessionListener> implements NetconfManagementSession {
- private static final Logger logger = LoggerFactory.getLogger(NetconfServerSession.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSession.class);
private final NetconfHelloMessageAdditionalHeader header;
NetconfHelloMessageAdditionalHeader header) {
super(sessionListener, channel, sessionId);
this.header = header;
- logger.debug("Session {} created", toString());
+ LOG.debug("Session {} created", toString());
}
@Override
private Class<? extends Transport> getTransportForString(String transport) {
switch(transport) {
- case "ssh" : return NetconfSsh.class;
- case "tcp" : return NetconfTcp.class;
- default: throw new IllegalArgumentException("Unknown transport type " + transport);
+ case "ssh" :
+ return NetconfSsh.class;
+ case "tcp" :
+ return NetconfTcp.class;
+ default:
+ throw new IllegalArgumentException("Unknown transport type " + transport);
}
}
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
-
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfSessionListener;
public class NetconfServerSessionListener implements NetconfSessionListener<NetconfServerSession> {
- static final Logger logger = LoggerFactory.getLogger(NetconfServerSessionListener.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionListener.class);
private final SessionMonitoringService monitoringService;
private final NetconfOperationRouter operationRouter;
private final AutoCloseable onSessionDownCloseable;
@Override
public void onSessionDown(NetconfServerSession netconfNetconfServerSession, Exception cause) {
- logger.debug("Session {} down, reason: {}", netconfNetconfServerSession, cause.getMessage());
+ LOG.debug("Session {} down, reason: {}", netconfNetconfServerSession, cause.getMessage());
onDown(netconfNetconfServerSession);
}
try {
operationRouter.close();
} catch (Exception closingEx) {
- logger.debug("Ignoring exception while closing operationRouter", closingEx);
+ LOG.debug("Ignoring exception while closing operationRouter", closingEx);
}
try {
onSessionDownCloseable.close();
} catch(Exception ex){
- logger.debug("Ignoring exception while closing onSessionDownCloseable", ex);
+ LOG.debug("Ignoring exception while closing onSessionDownCloseable", ex);
}
}
@Override
public void onSessionTerminated(NetconfServerSession netconfNetconfServerSession,
NetconfTerminationReason netconfTerminationReason) {
- logger.debug("Session {} terminated, reason: {}", netconfNetconfServerSession,
+ LOG.debug("Session {} terminated, reason: {}", netconfNetconfServerSession,
netconfTerminationReason.getErrorMessage());
onDown(netconfNetconfServerSession);
}
// schemas
final NetconfMessage message = processDocument(netconfMessage,
session);
- logger.debug("Responding with message {}", XmlUtil.toString(message.getDocument()));
+ LOG.debug("Responding with message {}", XmlUtil.toString(message.getDocument()));
session.sendMessage(message);
if (isCloseSession(netconfMessage)) {
} catch (final RuntimeException e) {
// TODO: should send generic error or close session?
- logger.error("Unexpected exception", e);
+ LOG.error("Unexpected exception", e);
session.onIncommingRpcFail();
throw new IllegalStateException("Unable to process incoming message " + netconfMessage, e);
} catch (NetconfDocumentedException e) {
- logger.trace("Error occurred while processing message",e);
+ LOG.trace("Error occurred while processing message",e);
session.onOutgoingRpcError();
session.onIncommingRpcFail();
SendErrorExceptionUtil.sendErrorMessage(session, e, netconfMessage);
private void closeNetconfSession(NetconfServerSession session) {
// destroy NetconfOperationService
session.close();
- logger.info("Session {} closed successfully", session.getSessionId());
+ LOG.info("Session {} closed successfully", session.getSessionId());
}
}
private void checkMessageId(Node rootNode) throws NetconfDocumentedException {
- NamedNodeMap attributes = rootNode.getAttributes();
+
+ NamedNodeMap attributes = rootNode.getAttributes();
+
if(attributes.getNamedItemNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.MESSAGE_ID)!=null) {
return;
}
throw new NetconfDocumentedException("Missing attribute" + rootNode.getNodeName(),
NetconfDocumentedException.ErrorType.protocol, NetconfDocumentedException.ErrorTag.missing_attribute,
- NetconfDocumentedException.ErrorSeverity.error, ImmutableMap.of(NetconfDocumentedException.ErrorTag.missing_attribute.toString(),
- XmlNetconfConstants.MESSAGE_ID));
+ NetconfDocumentedException.ErrorSeverity.error,
+ ImmutableMap.of(NetconfDocumentedException.ErrorTag.missing_attribute.toString(),
+ XmlNetconfConstants.MESSAGE_ID));
}
private static boolean isCloseSession(final NetconfMessage incomingDocument) {
package org.opendaylight.controller.netconf.impl;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
+import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouterImpl;
import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
import io.netty.channel.local.LocalAddress;
import io.netty.util.Timer;
import io.netty.util.concurrent.Promise;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.AbstractMap;
+import java.util.Map;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfServerSessionPreferences;
import org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSessionNegotiator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.util.AbstractMap;
-import java.util.Map;
-
public class NetconfServerSessionNegotiator
extends
AbstractNetconfSessionNegotiator<NetconfServerSessionPreferences, NetconfServerSession, NetconfServerSessionListener> {
- static final Logger logger = LoggerFactory
- .getLogger(NetconfServerSessionNegotiator.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiator.class);
+
private static final String UNKNOWN = "unknown";
protected NetconfServerSessionNegotiator(
}
- logger.debug("Additional header from hello parsed as {} from {}",
+ LOG.debug("Additional header from hello parsed as {} from {}",
parsedHeader, additionalHeader);
return new NetconfServerSession(sessionListener, channel,
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
-
+import com.google.common.collect.Sets;
+import io.netty.channel.Channel;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.Promise;
import java.util.Set;
-
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfServerSessionPreferences;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
import org.opendaylight.protocol.framework.SessionNegotiatorFactory;
-
-import com.google.common.collect.Sets;
-
-import io.netty.channel.Channel;
-import io.netty.util.Timer;
-import io.netty.util.concurrent.Promise;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final long connectionTimeoutMillis;
private final DefaultCommitNotificationProducer commitNotificationProducer;
private final SessionMonitoringService monitoringService;
- private static final Logger logger = LoggerFactory.getLogger(NetconfServerSessionNegotiatorFactory.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiatorFactory.class);
private final Set<String> baseCapabilities;
// TODO too many params, refactor
proposal = new NetconfServerSessionPreferences(
createHelloMessage(sessionId, capabilityProvider), sessionId);
} catch (NetconfDocumentedException e) {
- logger.error("Unable to create hello mesage for session {} with capability provider {}", sessionId,capabilityProvider);
+ LOG.error("Unable to create hello mesage for session {} with capability provider {}", sessionId,capabilityProvider);
throw new IllegalStateException(e);
}
* See <a href="http://tools.ietf.org/html/rfc6241#section-6">rfc6241</a> for details.
*/
public class SubtreeFilter {
- private static final Logger logger = LoggerFactory.getLogger(SubtreeFilter.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class);
static Document applySubtreeFilter(Document requestDocument, Document rpcReply) throws NetconfDocumentedException {
// FIXME: rpcReply document must be reread otherwise some nodes do not inherit namespaces. (services/service)
try {
rpcReply = XmlUtil.readXmlToDocument(XmlUtil.toString(rpcReply, true));
} catch (SAXException | IOException e) {
- logger.error("Cannot transform document", e);
+ LOG.error("Cannot transform document", e);
throw new NetconfDocumentedException("Cannot transform document");
}
XmlNetconfConstants.FILTER, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
if (maybeFilter.isPresent() && (
"subtree".equals(maybeFilter.get().getAttribute("type"))||
- "subtree".equals(maybeFilter.get().getAttribute("type", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0))
- )) {
+ "subtree".equals(maybeFilter.get().getAttribute("type", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)))
+ ) {
// do
if (result == null) {
result = MatchingResult.NO_MATCH;
}
- logger.debug("Matching {} to {} resulted in {}", src, filter, result);
+ LOG.debug("Matching {} to {} resulted in {}", src, filter, result);
return result;
}
package org.opendaylight.controller.netconf.impl.mapping;
import com.google.common.base.Optional;
-
import java.util.Set;
public interface CapabilityProvider {
package org.opendaylight.controller.netconf.impl.mapping.operations;
+import com.google.common.base.Optional;
+import java.util.Collections;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Optional;
-
-import java.util.Collections;
-
public class DefaultCloseSession extends AbstractSingletonNetconfOperation {
public static final String CLOSE_SESSION = "close-session";
private final AutoCloseable sessionResources;
+ getNetconfSessionIdForReporting(), NetconfDocumentedException.ErrorType.application,
NetconfDocumentedException.ErrorTag.operation_failed,
NetconfDocumentedException.ErrorSeverity.error, Collections.singletonMap(
- NetconfDocumentedException.ErrorSeverity.error.toString(), e.getMessage()));
+ NetconfDocumentedException.ErrorSeverity.error.toString(), e.getMessage()));
}
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
package org.opendaylight.controller.netconf.impl.mapping.operations;
import com.google.common.base.Preconditions;
-
+import java.io.InputStream;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
+import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.util.mapping.AbstractNetconfOperation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import java.io.InputStream;
-
public class DefaultCommit extends AbstractNetconfOperation {
- private static final Logger logger = LoggerFactory.getLogger(DefaultCommit.class);
+ private static final Logger LOG = LoggerFactory.getLogger(DefaultCommit.class);
private static final String NOTIFY_ATTR = "notify";
"Subsequent netconf operation expected by %s", this);
if (isCommitWithoutNotification(requestMessage)) {
- logger.debug("Skipping commit notification");
+ LOG.debug("Skipping commit notification");
} else {
// Send commit notification if commit was not issued by persister
removePersisterAttributes(requestMessage);
Element cfgSnapshot = getConfigSnapshot(operationRouter);
- logger.debug("Config snapshot retrieved successfully {}", cfgSnapshot);
+ LOG.debug("Config snapshot retrieved successfully {}", cfgSnapshot);
notificationProducer.sendCommitNotification("ok", cfgSnapshot, cap.getCapabilities());
}
xmlElement = XmlElement.fromDomElementWithExpected(message.getDocumentElement(),
XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
} catch (NetconfDocumentedException e) {
- logger.trace("Commit operation is not valid due to {}",e);
+ LOG.trace("Commit operation is not valid due to ",e);
return false;
}
if (attr == null || attr.equals("")){
return false;
} else if (attr.equals(Boolean.toString(false))) {
- logger.debug("Commit operation received with notify=false attribute {}", message);
+ LOG.debug("Commit operation received with notify=false attribute {}", message);
return true;
} else {
return false;
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
-
+import java.util.Map;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import java.util.Map;
-
public final class DefaultGetSchema extends AbstractLastNetconfOperation {
public static final String GET_SCHEMA = "get-schema";
public static final String IDENTIFIER = "identifier";
public static final String VERSION = "version";
- private static final Logger logger = LoggerFactory.getLogger(DefaultGetSchema.class);
+ private static final Logger LOG = LoggerFactory.getLogger(DefaultGetSchema.class);
private final CapabilityProvider cap;
public DefaultGetSchema(CapabilityProvider cap, String netconfSessionIdForReporting) {
} catch (IllegalStateException e) {
Map<String, String> errorInfo = Maps.newHashMap();
errorInfo.put(entry.identifier, e.getMessage());
- logger.warn("Rpc error: {}", NetconfDocumentedException.ErrorTag.operation_failed, e);
+ LOG.warn("Rpc error: {}", NetconfDocumentedException.ErrorTag.operation_failed, e);
throw new NetconfDocumentedException(e.getMessage(), NetconfDocumentedException.ErrorType.application,
NetconfDocumentedException.ErrorTag.operation_failed,
NetconfDocumentedException.ErrorSeverity.error, errorInfo);
Element getSchemaResult;
getSchemaResult = XmlUtil.createTextElement(document, XmlNetconfConstants.DATA_KEY, schema,
Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING));
- logger.trace("{} operation successful", GET_SCHEMA);
+ LOG.trace("{} operation successful", GET_SCHEMA);
return getSchemaResult;
}
try {
identifierElement = getSchemaElement.getOnlyChildElementWithSameNamespace(IDENTIFIER);
} catch (MissingNameSpaceException e) {
- logger.trace("Can't get identifier element as only child element with same namespace due to {}",e);
+ LOG.trace("Can't get identifier element as only child element with same namespace due to ",e);
throw NetconfDocumentedException.wrap(e);
}
identifier = identifierElement.getTextContent();
import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
public class DefaultStartExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation {
public static final String START_EXI = "start-exi";
- private static final Logger logger = LoggerFactory.getLogger(DefaultStartExi.class);
+ private static final Logger LOG = LoggerFactory.getLogger(DefaultStartExi.class);
private NetconfServerSession netconfSession;
public DefaultStartExi(String netconfSessionIdForReporting) {
@Override
public Document handle(Document message,
NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
- logger.debug("Received start-exi message {} ", XmlUtil.toString(message));
+ LOG.debug("Received start-exi message {} ", XmlUtil.toString(message));
try {
netconfSession.startExiCommunication(new NetconfMessage(message));
@Override
protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
- logger.trace("{} operation successful", START_EXI);
+ LOG.trace("{} operation successful", START_EXI);
return getSchemaResult;
}
public static final String STOP_EXI = "stop-exi";
private NetconfServerSession netconfSession;
- private static final Logger logger = LoggerFactory
- .getLogger(DefaultStartExi.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(DefaultStopExi.class);
public DefaultStopExi(String netconfSessionIdForReporting) {
super(netconfSessionIdForReporting);
@Override
protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
- logger.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement));
+ LOG.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement));
netconfSession.stopExiCommunication();
Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
- logger.trace("{} operation successful", STOP_EXI);
+ LOG.trace("{} operation successful", STOP_EXI);
return getSchemaResult;
}
public class NetconfImplActivator implements BundleActivator {
- private static final Logger logger = LoggerFactory.getLogger(NetconfImplActivator.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfImplActivator.class);
private NetconfOperationServiceFactoryTracker factoriesTracker;
private DefaultCommitNotificationProducer commitNot;
NetconfServerDispatcher dispatch = new NetconfServerDispatcher(serverChannelInitializer, eventLoopGroup, eventLoopGroup);
LocalAddress address = NetconfConfigUtil.getNetconfLocalAddress();
- logger.trace("Starting local netconf server at {}", address);
+ LOG.trace("Starting local netconf server at {}", address);
dispatch.createLocalServer(address);
context.registerService(NetconfOperationProvider.class, factoriesListener, null);
@Override
public void stop(final BundleContext context) {
- logger.info("Shutting down netconf because YangStoreService service was removed");
+ LOG.info("Shutting down netconf because YangStoreService service was removed");
commitNot.close();
eventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS);
public class NetconfMonitoringServiceImpl implements NetconfMonitoringService, SessionMonitoringService {
- private static final Logger logger = LoggerFactory.getLogger(NetconfMonitoringServiceImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfMonitoringServiceImpl.class);
private final Set<NetconfManagementSession> sessions = new ConcurrentSet<>();
private final NetconfOperationProvider netconfOperationProvider;
@Override
public void onSessionUp(NetconfManagementSession session) {
- logger.debug("Session {} up", session);
+ LOG.debug("Session {} up", session);
Preconditions.checkState(!sessions.contains(session), "Session %s was already added", session);
sessions.add(session);
}
@Override
public void onSessionDown(NetconfManagementSession session) {
- logger.debug("Session {} down", session);
+ LOG.debug("Session {} down", session);
Preconditions.checkState(sessions.contains(session), "Session %s not present", session);
sessions.remove(session);
}
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.Set;
+import java.util.TreeMap;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.NavigableMap;
-import java.util.Set;
-import java.util.TreeMap;
-
public class NetconfOperationRouterImpl implements NetconfOperationRouter {
- private static final Logger logger = LoggerFactory.getLogger(NetconfOperationRouterImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfOperationRouterImpl.class);
private final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot;
private Set<NetconfOperation> allNetconfOperations;
messageAsString = XmlUtil.toString(message);
netconfOperationExecution = getNetconfOperationWithHighestPriority(message, session);
} catch (IllegalArgumentException | IllegalStateException e) {
- logger.warn("Unable to handle rpc {} on session {}", messageAsString, session, e);
+ LOG.warn("Unable to handle rpc {} on session {}", messageAsString, session, e);
String errorMessage = String.format("Unable to handle rpc %s on session %s", messageAsString, session);
Map<String, String> errorInfo = Maps.newHashMap();
}
private NetconfDocumentedException handleUnexpectedEx(String s, Exception e) throws NetconfDocumentedException {
- logger.error(s, e);
+ LOG.error(s, e);
Map<String, String> info = Maps.newHashMap();
info.put(NetconfDocumentedException.ErrorSeverity.error.toString(), e.toString());
private Document executeOperationWithHighestPriority(Document message,
NetconfOperationExecution netconfOperationExecution, String messageAsString)
throws NetconfDocumentedException {
- logger.debug("Forwarding netconf message {} to {}", messageAsString, netconfOperationExecution.netconfOperation);
+ LOG.debug("Forwarding netconf message {} to {}", messageAsString, netconfOperationExecution.netconfOperation);
return netconfOperationExecution.execute(message);
}
*/
package org.opendaylight.controller.netconf.impl.osgi;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-
import java.util.HashSet;
import java.util.Set;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
public class NetconfOperationServiceFactoryListenerImpl implements NetconfOperationServiceFactoryListener,
NetconfOperationProvider {
package org.opendaylight.controller.netconf.impl.osgi;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
import org.opendaylight.controller.netconf.util.CloseableUtil;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
public class NetconfOperationServiceSnapshotImpl implements NetconfOperationServiceSnapshot {
private final Set<NetconfOperationService> services;
import com.google.common.collect.Maps;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
+import java.util.Map;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.util.messages.SendErrorExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Map;
-
-public final class
- DeserializerExceptionHandler implements ChannelHandler {
-
- private static final Logger logger = LoggerFactory.getLogger(DeserializerExceptionHandler.class);
+public final class DeserializerExceptionHandler implements ChannelHandler {
+ private static final Logger LOG = LoggerFactory.getLogger(DeserializerExceptionHandler.class);
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- logger.warn("An exception occurred during message handling", cause);
+ LOG.warn("An exception occurred during message handling", cause);
handleDeserializerException(ctx, cause);
}
package org.opendaylight.controller.netconf.impl;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
-
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.HashedWheelTimer;
import io.netty.util.concurrent.GlobalEventExecutor;
-
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
-
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
+import org.opendaylight.controller.netconf.client.TestingNetconfClient;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
-import org.opendaylight.controller.netconf.client.TestingNetconfClient;
import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
import org.opendaylight.controller.netconf.mapping.api.Capability;
@RunWith(Parameterized.class)
public class ConcurrentClientsTest {
- private static final Logger logger = LoggerFactory.getLogger(ConcurrentClientsTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ConcurrentClientsTest.class);
private static ExecutorService clientExecutor;
@Parameterized.Parameters()
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {4, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
- {1, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
- // empty set of capabilities = only base 1.0 netconf capability
- {4, TestingNetconfClientRunnable.class, Collections.emptySet()},
- {4, TestingNetconfClientRunnable.class, getOnlyExiServerCaps()},
- {4, TestingNetconfClientRunnable.class, getOnlyChunkServerCaps()},
-
- {4, BlockingClientRunnable.class, getOnlyExiServerCaps()},
- {1, BlockingClientRunnable.class, getOnlyExiServerCaps()},
+ return Arrays.asList(new Object[][]{{4, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
+ {1, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
+ // empty set of capabilities = only base 1.0 netconf capability
+ {4, TestingNetconfClientRunnable.class, Collections.emptySet()},
+ {4, TestingNetconfClientRunnable.class, getOnlyExiServerCaps()},
+ {4, TestingNetconfClientRunnable.class, getOnlyChunkServerCaps()},
+ {4, BlockingClientRunnable.class, getOnlyExiServerCaps()},
+ {1, BlockingClientRunnable.class, getOnlyExiServerCaps()},
});
}
try {
nettyGroup.shutdownGracefully().get();
} catch (InterruptedException | ExecutionException e) {
- logger.warn("Ignoring exception while cleaning up after test", e);
+ LOG.warn("Ignoring exception while cleaning up after test", e);
}
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
} catch (ExecutionException e) {
- logger.error("Thread for testing client failed", e);
+ LOG.error("Thread for testing client failed", e);
fail("Client failed: " + e.getMessage());
}
}
@Override
public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
try {
- logger.info("Handling netconf message from test {}", XmlUtil.toString(requestMessage));
+ LOG.info("Handling netconf message from test {}", XmlUtil.toString(requestMessage));
counter.getAndIncrement();
return XmlUtil.readXmlToDocument("<test/>");
} catch (Exception e) {
while (sb.toString().endsWith("]]>]]>") == false) {
sb.append((char) inFromServer.read());
}
- logger.info(sb.toString());
+ LOG.info(sb.toString());
outToServer.write(IOUtils.toByteArray(clientHello));
outToServer.write("]]>]]>".getBytes());
while (sb.toString().endsWith("]]>]]>") == false) {
sb.append((char) inFromServer.read());
}
- logger.info(sb.toString());
+ LOG.info(sb.toString());
clientSocket.close();
}
}
final TestingNetconfClient netconfClient =
new TestingNetconfClient(Thread.currentThread().getName(), netconfClientDispatcher, getClientConfig());
long sessionId = netconfClient.getSessionId();
- logger.info("Client with session id {}: hello exchanged", sessionId);
+ LOG.info("Client with session id {}: hello exchanged", sessionId);
final NetconfMessage getMessage = XmlFileLoader
.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
NetconfMessage result = netconfClient.sendRequest(getMessage).get();
- logger.info("Client with session id {}: got result {}", sessionId, result);
+ LOG.info("Client with session id {}: got result {}", sessionId, result);
Preconditions.checkState(NetconfMessageUtil.isErrorMessage(result) == false,
"Received error response: " + XmlUtil.toString(result.getDocument()) + " to request: "
+ XmlUtil.toString(getMessage.getDocument()));
netconfClient.close();
- logger.info("Client with session id {}: ended", sessionId);
+ LOG.info("Client with session id {}: ended", sessionId);
} catch (final Exception e) {
throw new IllegalStateException(Thread.currentThread().getName(), e);
}
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.HashedWheelTimer;
+import java.lang.management.ManagementFactory;
+import java.net.InetSocketAddress;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
-import java.lang.management.ManagementFactory;
-import java.net.InetSocketAddress;
-
public class NetconfDispatcherImplTest {
private EventLoopGroup nettyGroup;
package org.opendaylight.controller.netconf.impl;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.doNothing;
+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 com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
-import org.opendaylight.controller.netconf.impl.NetconfServerSession;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionListener;
import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
import org.opendaylight.controller.netconf.mapping.api.Capability;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.*;
-
public class NetconfMonitoringServiceImplTest {
private NetconfMonitoringServiceImpl service;
@RunWith(value = Parameterized.class)
public class SubtreeFilterTest {
- private static final Logger logger = LoggerFactory.getLogger(SubtreeFilterTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilterTest.class);
private final int directoryIndex;
Document preFilterDocument = getDocument("pre-filter.xml");
Document postFilterDocument = getDocument("post-filter.xml");
Document actualPostFilterDocument = SubtreeFilter.applySubtreeFilter(requestDocument, preFilterDocument);
- logger.info("Actual document: {}", XmlUtil.toString(actualPostFilterDocument));
+ LOG.info("Actual document: {}", XmlUtil.toString(actualPostFilterDocument));
Diff diff = XMLUnit.compareXML(postFilterDocument, actualPostFilterDocument);
assertTrue(diff.toString(), diff.similar());
package org.opendaylight.controller.netconf.impl.mapping.operations;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+
import org.junit.Test;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
public class DefaultCloseSessionTest {
@Test
package org.opendaylight.controller.netconf.impl.mapping.operations;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anySetOf;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import static org.mockito.Mockito.*;
-
public class DefaultCommitTest {
private NetconfOperationChainedExecution operation;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+
import com.google.common.base.Optional;
import org.junit.Before;
import org.junit.Test;
package org.opendaylight.controller.netconf.impl.mapping.operations;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.*;
-
public class DefaultStopExiTest {
@Test
public void testHandleWithNoSubsequentOperations() throws Exception {
package org.opendaylight.controller.netconf.impl.osgi;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import java.util.Arrays;
import java.util.Dictionary;
import org.junit.Before;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
public class NetconfImplActivatorTest {
@Mock
package org.opendaylight.controller.netconf.impl.osgi;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceReference;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.*;
-
public class NetconfOperationServiceFactoryTrackerTest {
@Mock
package org.opendaylight.controller.netconf.impl.util;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyObject;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import org.junit.Before;
import org.junit.Test;
-import static org.mockito.Mockito.*;
-
public class DeserializerExceptionHandlerTest {
private DeserializerExceptionHandler handler;
public static final String LOOPBACK_ADDRESS = "127.0.0.1";
public static final int SERVER_CONNECTION_TIMEOUT_MILLIS = 5000;
- static ModuleFactory[] FACTORIES = { new TestImplModuleFactory(),
- new DepTestImplModuleFactory(), new NetconfTestImplModuleFactory(),
- new IdentityTestModuleFactory(), new MultipleDependenciesModuleFactory() };
+ static ModuleFactory[] FACTORIES = {new TestImplModuleFactory(),
+ new DepTestImplModuleFactory(),
+ new NetconfTestImplModuleFactory(),
+ new IdentityTestModuleFactory(),
+ new MultipleDependenciesModuleFactory() };
private EventLoopGroup nettyThreadgroup;
private HashedWheelTimer hashedWheelTimer;
return TCP_ADDRESS;
}
- static SessionMonitoringService getNetconfMonitoringListenerService(final Logger logger, final NetconfMonitoringServiceImpl monitor) {
+ static SessionMonitoringService getNetconfMonitoringListenerService(final Logger LOG, final NetconfMonitoringServiceImpl monitor) {
return new SessionMonitoringService() {
@Override
public void onSessionUp(final NetconfManagementSession session) {
- logger.debug("Management session up {}", session);
+ LOG.debug("Management session up {}", session);
monitor.onSessionUp(session);
}
@Override
public void onSessionDown(final NetconfManagementSession session) {
- logger.debug("Management session down {}", session);
+ LOG.debug("Management session down {}", session);
monitor.onSessionDown(session);
}
};
*/
package org.opendaylight.controller.netconf.it;
+import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
-
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
-import com.google.common.base.Preconditions;
-
public final class SSLUtil {
private SSLUtil() {}
package org.opendaylight.controller.netconf.mapping.api;
import com.google.common.base.Optional;
-
import java.util.List;
/**
public class Get extends AbstractNetconfOperation {
- private static final Logger logger = LoggerFactory.getLogger(Get.class);
+ private static final Logger LOG = LoggerFactory.getLogger(Get.class);
private final NetconfMonitoringService netconfMonitor;
public Get(final NetconfMonitoringService netconfMonitor) {
return innerResult;
} catch (final RuntimeException e) {
final String errorMessage = "Get operation for netconf-state subtree failed";
- logger.warn(errorMessage, e);
+ LOG.warn(errorMessage, e);
throw new NetconfDocumentedException(errorMessage, NetconfDocumentedException.ErrorType.application,
NetconfDocumentedException.ErrorTag.operation_failed,
public class NetconfMonitoringActivator implements BundleActivator {
- private static final Logger logger = LoggerFactory.getLogger(NetconfMonitoringActivator.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfMonitoringActivator.class);
private NetconfMonitoringServiceTracker monitor;
try {
monitor.close();
} catch (Exception e) {
- logger.warn("Ignoring exception while closing {}", monitor, e);
+ LOG.warn("Ignoring exception while closing {}", monitor, e);
}
}
}
public class NetconfMonitoringServiceTracker extends ServiceTracker<NetconfMonitoringService, NetconfMonitoringService> {
- private static final Logger logger = LoggerFactory.getLogger(NetconfMonitoringServiceTracker.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfMonitoringServiceTracker.class);
private ServiceRegistration<NetconfOperationServiceFactory> reg;
try {
reg.unregister();
} catch (final Exception e) {
- logger.warn("Ignoring exception while unregistering {}", reg, e);
+ LOG.warn("Ignoring exception while unregistering {}", reg, e);
}
}
}
*/
package org.opendaylight.controller.netconf.monitoring.xml;
-import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.dom.DOMResult;
+import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
public class JaxBSerializer {
res = new DOMResult();
marshaller.marshal(monitoringModel, res);
} catch (final JAXBException e) {
- throw new RuntimeException("Unable to serialize netconf state " + monitoringModel, e);
+ throw new RuntimeException("Unable to serialize netconf state " + monitoringModel, e);
}
return ((Document)res.getNode()).getDocumentElement();
}
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Collections2;
+import java.util.Collection;
import javax.annotation.Nonnull;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
-
import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlElement;
-import java.util.Collection;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
final class MonitoringSchema {
*/
package org.opendaylight.controller.netconf.monitoring.xml.model;
+import com.google.common.base.Joiner;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
-
-import com.google.common.base.Joiner;
import org.opendaylight.controller.netconf.monitoring.MonitoringConstants;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.Session1;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
+import java.util.Collection;
+import javax.annotation.Nullable;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.monitoring.MonitoringConstants;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
-import javax.annotation.Nullable;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.util.Collection;
-
@XmlRootElement(name = MonitoringConstants.NETCONF_MONITORING_XML_ROOT_ELEMENT)
public final class NetconfState {
)
package org.opendaylight.controller.netconf.monitoring.xml.model;
-import org.opendaylight.controller.netconf.monitoring.MonitoringConstants;
-
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
-import javax.xml.bind.annotation.XmlSchema;
\ No newline at end of file
+import javax.xml.bind.annotation.XmlSchema;
+import org.opendaylight.controller.netconf.monitoring.MonitoringConstants;
\ No newline at end of file
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;
package org.opendaylight.controller.netconf.monitoring.osgi;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+
import com.google.common.base.Optional;
import org.junit.Test;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.monitoring.MonitoringConstants;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-
public class NetconfMonitoringOperationServiceTest {
@Test
public void testGetters() throws Exception {
package org.opendaylight.controller.netconf.monitoring.osgi;
import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import java.util.Hashtable;
import org.junit.Before;
import org.junit.Test;