</properties>
<dependencies>
+ <!-- Java -->
<dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>features-yangtools</artifactId>
+ <groupId>org.json</groupId>
+ <artifactId>json</artifactId>
+ </dependency>
+
+ <!-- Google -->
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ </dependency>
+
+ <!-- Jackson -->
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.datatype</groupId>
+ <artifactId>jackson-datatype-json-org</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.module</groupId>
+ <artifactId>jackson-module-jaxb-annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.jaxrs</groupId>
+ <artifactId>jackson-jaxrs-base</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.jaxrs</groupId>
+ <artifactId>jackson-jaxrs-json-provider</artifactId>
+ </dependency>
+
+ <!-- Jersey -->
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-server</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-servlet</artifactId>
+ </dependency>
+
+ <!-- Netty -->
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-buffer</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-codec</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-codec-http</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-common</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-handler</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-transport</artifactId>
+ </dependency>
+
+ <!-- OpenDaylight -->
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>features-akka</artifactId>
+ <version>${commons.opendaylight.version}</version>
<classifier>features</classifier>
<type>xml</type>
</dependency>
<classifier>features</classifier>
<type>xml</type>
</dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>features-akka</artifactId>
- <version>${commons.opendaylight.version}</version>
- <classifier>features</classifier>
+ <artifactId>md-sal-config</artifactId>
+ <version>${mdsal.version}</version>
<type>xml</type>
+ <classifier>config</classifier>
</dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-core-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-core-api</artifactId>
+ <artifactId>sal-akka-raft</artifactId>
+ <version>${mdsal.version}</version>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-broker-impl</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-dom-xsql</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-karaf-xsql</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-dom-xsql-config</artifactId>
- <classifier>config</classifier>
- <type>xml</type>
- </dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-binding-api</artifactId>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-connector-api</artifactId>
</dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-inmemory-datastore</artifactId>
+ <artifactId>sal-dom-xsql</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>md-sal-config</artifactId>
- <version>${mdsal.version}</version>
- <type>xml</type>
+ <artifactId>sal-dom-xsql-config</artifactId>
<classifier>config</classifier>
+ <type>xml</type>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-distributed-datastore</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-remoterpc-connector</artifactId>
- </dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-clustering-commons</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-akka-raft</artifactId>
- <version>${mdsal.version}</version>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-clustering-config</artifactId>
<type>xml</type>
<classifier>config</classifier>
</dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-netconf-connector</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller.model</groupId>
- <artifactId>model-inventory</artifactId>
+ <artifactId>sal-distributed-datastore</artifactId>
</dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-config-dispatcher</artifactId>
+ <artifactId>sal-inmemory-datastore</artifactId>
</dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-connector-config</artifactId>
- <version>${netconf.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
+ <artifactId>sal-netconf-connector</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-rest-connector</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-core</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-server</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-servlet</artifactId>
- </dependency>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-buffer</artifactId>
- </dependency>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-codec</artifactId>
- </dependency>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-codec-http</artifactId>
- </dependency>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-common</artifactId>
- </dependency>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-handler</artifactId>
+ <artifactId>sal-remote</artifactId>
</dependency>
<dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-transport</artifactId>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-remoterpc-connector</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-remote</artifactId>
+ <artifactId>sal-rest-connector</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<classifier>config</classifier>
</dependency>
<dependency>
- <groupId>org.opendaylight.controller.samples</groupId>
- <artifactId>sample-toaster</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller.samples</groupId>
- <artifactId>sample-toaster-provider</artifactId>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-rest-docgen</artifactId>
</dependency>
+
<dependency>
- <groupId>org.opendaylight.controller.samples</groupId>
- <artifactId>sample-toaster-consumer</artifactId>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-config-dispatcher</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.controller.samples</groupId>
- <artifactId>toaster-config</artifactId>
- <version>${mdsal.version}</version>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-connector-config</artifactId>
+ <version>${netconf.version}</version>
<type>xml</type>
<classifier>config</classifier>
</dependency>
+
<dependency>
- <groupId>org.opendaylight.controller.samples</groupId>
- <artifactId>clustering-it-model</artifactId>
- <version>${mdsal.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller.samples</groupId>
- <artifactId>clustering-it-provider</artifactId>
- <version>${mdsal.version}</version>
+ <groupId>org.opendaylight.controller.model</groupId>
+ <artifactId>model-inventory</artifactId>
</dependency>
+
<dependency>
<groupId>org.opendaylight.controller.samples</groupId>
<artifactId>clustering-it-config</artifactId>
<artifactId>clustering-it-config</artifactId>
<version>${mdsal.version}</version>
<type>xml</type>
- <classifier>testmoduleshardconf</classifier>
+ <classifier>testmoduleconf</classifier>
</dependency>
<dependency>
<groupId>org.opendaylight.controller.samples</groupId>
<artifactId>clustering-it-config</artifactId>
<version>${mdsal.version}</version>
<type>xml</type>
- <classifier>testmoduleconf</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-rest-docgen</artifactId>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
+ <classifier>testmoduleshardconf</classifier>
</dependency>
<dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>clustering-it-model</artifactId>
+ <version>${mdsal.version}</version>
</dependency>
<dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>clustering-it-provider</artifactId>
+ <version>${mdsal.version}</version>
</dependency>
+
+ <!-- toaster -->
<dependency>
- <groupId>com.fasterxml.jackson.datatype</groupId>
- <artifactId>jackson-datatype-json-org</artifactId>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>sample-toaster</artifactId>
</dependency>
<dependency>
- <groupId>com.fasterxml.jackson.module</groupId>
- <artifactId>jackson-module-jaxb-annotations</artifactId>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>sample-toaster-consumer</artifactId>
</dependency>
<dependency>
- <groupId>com.fasterxml.jackson.jaxrs</groupId>
- <artifactId>jackson-jaxrs-base</artifactId>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>sample-toaster-provider</artifactId>
</dependency>
<dependency>
- <groupId>com.fasterxml.jackson.jaxrs</groupId>
- <artifactId>jackson-jaxrs-json-provider</artifactId>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>toaster-config</artifactId>
+ <version>${mdsal.version}</version>
+ <type>xml</type>
+ <classifier>config</classifier>
</dependency>
+
+ <!-- yang -->
<dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>features-yangtools</artifactId>
+ <classifier>features</classifier>
+ <type>xml</type>
</dependency>
+
<!-- test to validate features.xml -->
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-rest-docgen</artifactId>
+ <artifactId>sal-rest-docgen-maven</artifactId>
<version>${mdsal.version}</version>
<type>jar</type>
</dependency>
<yangFilesRootDir>src</yangFilesRootDir>
<codeGenerators>
<generator>
- <codeGeneratorClass>org.opendaylight.controller.sal.rest.doc.impl.StaticDocGenerator</codeGeneratorClass>
+ <codeGeneratorClass>org.opendaylight.controller.sal.rest.doc.maven.StaticDocGenerator</codeGeneratorClass>
<outputBaseDir>${project.build.directory}/generated-resources/swagger-api-documentation/explorer/static</outputBaseDir>
</generator>
</codeGenerators>
return null;
}
for (String cacheName : manager.getCacheNames()) {
- if (!manager.isRunning(cacheName)) continue;
+ if (!manager.isRunning(cacheName)) {
+ continue;
+ }
if (cacheName.startsWith("{" + containerName + "}_")) {
String[] res = cacheName.split("[{}]");
if (res.length >= 4 && res[1].equals(containerName)
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
IPHostId other = (IPHostId) obj;
if (ipAddress == null) {
- if (other.ipAddress != null)
+ if (other.ipAddress != null) {
return false;
- } else if (!ipAddress.equals(other.ipAddress))
+ }
+ } else if (!ipAddress.equals(other.ipAddress)) {
return false;
+ }
return true;
}
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
IPMacHostId other = (IPMacHostId) obj;
if (ipAddress == null) {
- if (other.ipAddress != null)
+ if (other.ipAddress != null) {
return false;
- } else if (!ipAddress.equals(other.ipAddress))
+ }
+ } else if (!ipAddress.equals(other.ipAddress)) {
return false;
+ }
if (macAddr == null) {
- if (other.macAddr != null)
+ if (other.macAddr != null) {
return false;
- } else if (!macAddr.equals(other.macAddr))
+ }
+ } else if (!macAddr.equals(other.macAddr)) {
return false;
+ }
return true;
}
@Override
public HostNodeConnector call() throws Exception {
HostNodeConnector h = hostTracker.hostFind(trackedHost);
- if (h != null)
+ if (h != null) {
return h;
+ }
hostTracker.setCallableOnPendingARP(trackedHost, this);
Thread.sleep(2000); // wait 2sec to see if the host responds
return hostTracker.hostQuery(trackedHost);
@Override
protected void configureGlobalInstance(Component c, Object imp) {
- if (!imp.equals(BundleScanServiceImpl.class)) return;
+ if (!imp.equals(BundleScanServiceImpl.class)) {
+ return;
+ }
// export service
c.setInterface(
new String[] { IBundleScanService.class.getName() },
}
private boolean matches(Pattern pattern, Set<String> values) {
- if (pattern == null) return true;
+ if (pattern == null) {
+ return true;
+ }
//LOGGER.debug("Matching: {} {}", pattern.toString(), values);
for (String s : values) {
- if (pattern.matcher(s).find()) return true;
+ if (pattern.matcher(s).find()) {
+ return true;
+ }
}
return false;
}
Bundle initBundle, Set<String> excludes)
{
for (BundleInfo other : bundlesToScan) {
- if (other.getId() == target.getId()) continue;
+ if (other.getId() == target.getId()) {
+ continue;
+ }
if (target.isDependantOn(other)) {
if (!visited.contains(other)) {
classes.addAll(BundleScanner.loadClasses(
private boolean isDependantOn(BundleInfo other) {
for (String pkg : importPkgs) {
- if (other.exportPkgs.contains(pkg)) return true;
+ if (other.exportPkgs.contains(pkg)) {
+ return true;
+ }
}
return false;
}
public List<BundleInfo> getDependencies(Collection<BundleInfo> bundles) {
List<BundleInfo> result = new ArrayList<BundleInfo>();
for(BundleInfo bundle : bundles) {
- if (isDependantOn(bundle)) result.add(bundle);
+ if (isDependantOn(bundle)) {
+ result.add(bundle);
+ }
}
return result;
}
private static Set<String> parsePackages(String packageString) {
- if (packageString == null) return Collections.emptySet();
+ if (packageString == null) {
+ return Collections.emptySet();
+ }
String[] packages = packageString.split(",");
Set<String> result = new HashSet<String>();
for (int i=0; i<packages.length; i++) {
boolean includeDependentBundleClasses)
{
BundleInfo info = bundleAnnotations.get(context.getBundle().getBundleId());
- if (info == null) return Collections.emptyList();
+ if (info == null) {
+ return Collections.emptyList();
+ }
Pattern pattern = mergePatterns(annotations, false);
List<Class<?>> result = null;
if (includeDependentBundleClasses) {
StringBuilder errors = new StringBuilder();
for (String name : annotatedClasses) {
try {
- if (excludes != null && excludes.contains(name)) continue;
+ if (excludes != null && excludes.contains(name)) {
+ continue;
+ }
result.add(initBundle.loadClass(name));
} catch (ClassNotFoundException e) {
errors.append(name).append(", ");
if (c.endsWith("*")) {
c = c.substring(0, c.length() - 1);
}
- if (regex.length() > 0) regex.append("|");
+ if (regex.length() > 0) {
+ regex.append("|");
+ }
regex.append("^");
if (convert2signature) {
regex.append("L").append(c.replaceAll("\\.", "/"));
}
private void validate(List<Class<?>> classes) {
- if (classes == null || classes.size() == 0) return;
+ if (classes == null || classes.size() == 0) {
+ return;
+ }
Map<String,String> names = new HashMap<String,String>();
StringBuilder conflictsMsg = new StringBuilder();
for (Class<?> c : classes) {
XmlRootElement root = c.getAnnotation(XmlRootElement.class);
- if (root == null) continue;
+ if (root == null) {
+ continue;
+ }
String rootName = root.name();
if ("##default".equals(rootName)) {
String clsName = c.getSimpleName();
}
@Context
public void setSecurityContext(SecurityContext context) {
- if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
+ if (context != null && context.getUserPrincipal() != null) {
+ username = context.getUserPrincipal().getName();
+ }
}
protected String getUserName() {
return username;
@Context
public void setSecurityContext(SecurityContext context) {
- if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
+ if (context != null && context.getUserPrincipal() != null) {
+ username = context.getUserPrincipal().getName();
+ }
}
protected String getUserName() {
@Context
public void setSecurityContext(SecurityContext context) {
- if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
+ if (context != null && context.getUserPrincipal() != null) {
+ username = context.getUserPrincipal().getName();
+ }
}
protected String getUserName() {
return username;
@Context
public void setSecurityContext(SecurityContext context) {
- if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
+ if (context != null && context.getUserPrincipal() != null) {
+ username = context.getUserPrincipal().getName();
+ }
}
protected String getUserName() {
return username;
}
@Context
public void setSecurityContext(SecurityContext context) {
- if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
+ if (context != null && context.getUserPrincipal() != null) {
+ username = context.getUserPrincipal().getName();
+ }
}
protected String getUserName() {
import org.opendaylight.controller.sal.utils.INodeFactory;
import org.opendaylight.controller.sal.core.Node;
-public class StubNodeFactory implements INodeFactory
- {
- void init() {
- }
+public class StubNodeFactory implements INodeFactory {
+ void init() {
+ }
- /**
- * Function called by the dependency manager when at least one dependency
- * become unsatisfied or when the component is shutting down because for
- * example bundle is being stopped.
- *
- */
- void destroy() {
- }
+ /**
+ * Function called by the dependency manager when at least one dependency
+ * become unsatisfied or when the component is shutting down because for
+ * example bundle is being stopped.
+ *
+ */
+ void destroy() {
+ }
- /**
- * Function called by dependency manager after "init ()" is called and after
- * the services provided by the class are registered in the service registry
- *
- */
- void start() {
- }
+ /**
+ * Function called by dependency manager after "init ()" is called and after
+ * the services provided by the class are registered in the service registry
+ *
+ */
+ void start() {
+ }
- /**
- * Function called by the dependency manager before the services exported by
- * the component are unregistered, this will be followed by a "destroy ()"
- * calls
- *
- */
- void stop() {
- }
+ /**
+ * Function called by the dependency manager before the services exported by
+ * the component are unregistered, this will be followed by a "destroy ()"
+ * calls
+ *
+ */
+ void stop() {
+ }
- public Node fromString(String nodeType, String nodeId){
- if(nodeType.equals("STUB"))
- try{
- return new Node("STUB", Integer.parseInt(nodeId));
- } catch(ConstructionException e)
- {
- return null;
- }
- return null;
- }
+ public Node fromString(String nodeType, String nodeId){
+ if(nodeType.equals("STUB")) {
+ try {
+ return new Node("STUB", Integer.parseInt(nodeId));
+ } catch(ConstructionException e) {
+ return null;
+ }
+ }
+ return null;
+ }
}
@Override
public ConnectionLocality getLocalityStatus(Node node) {
- if (this.connectionListener == null) return ConnectionLocality.NOT_CONNECTED;
+ if (this.connectionListener == null) {
+ return ConnectionLocality.NOT_CONNECTED;
+ }
return connectionListener.getLocalityStatus(node);
}
@Override
public Status disconnect(Node node) {
IPluginInConnectionService s = pluginService.get(node.getType());
- if (s != null) return s.disconnect(node);
+ if (s != null) {
+ return s.disconnect(node);
+ }
return new Status(StatusCode.NOTFOUND);
}
@Override
public boolean memberExists(String name, String poolName) {
- if(this.pools.containsKey(poolName)){
- if(this.pools.get(poolName).getMember(name) != null )
+ if (this.pools.containsKey(poolName)) {
+ if (this.pools.get(poolName).getMember(name) != null) {
return true;
+ }
}
return false;
}
@Override
- public boolean memberExists(String name, String memberIP,String poolName){
- if(!this.pools.containsKey(poolName))
+ public boolean memberExists(String name, String memberIP,String poolName) {
+ if (!this.pools.containsKey(poolName)) {
return false;
+ }
return this.pools.get(poolName).poolMemberExists(new PoolMember(name, memberIP, poolName));
}
* requires
*/
public String getContainerName() {
- if (containerName == null)
+ if (containerName == null) {
return GlobalConstants.DEFAULT.toString();
+ }
return containerName;
}
private String checkPasswordRecovery() {
final String fileDescription = "Default Network Administrator password recovery file";
File recoveryFile = new File(UserManager.RECOVERY_FILE);
- if (!recoveryFile.exists()) return null;
+ if (!recoveryFile.exists()) {
+ return null;
+ }
// read the recovery file
String pwd = null;
try {
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>clustering.services</artifactId>
javax.servlet.resources,
javax.xml.parsers,
javax.xml.transform,
+ org.apache.commons.io,
org.apache.commons.logging,
org.apache.taglibs.standard.functions,
org.apache.taglibs.standard.resources,
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013, 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,
package org.opendaylight.controller.web;
import java.io.FileInputStream;
+import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
+import org.apache.commons.io.IOUtils;
import org.opendaylight.controller.configuration.IConfigurationContainerService;
import org.opendaylight.controller.configuration.IConfigurationService;
import org.opendaylight.controller.containermanager.IContainerAuthorization;
@ResponseBody
public String getVersion(HttpServletRequest request, @PathVariable("property") String property) {
Properties prop = new Properties();
+ FileInputStream propertiesFile = null;
try {
- prop.load(new FileInputStream("version.properties"));
+ propertiesFile = new FileInputStream("version.properties");
+ prop.load(propertiesFile);
return prop.getProperty(property+".version");
- } catch (Exception e) {
+ } catch (IOException e) {
+ // TODO: We should be logging the exception here
+ // "Failed to open version.properties."
return null;
+ } finally {
+ IOUtils.closeQuietly(propertiesFile);
}
}
@RequestMapping(value = "web.json")
int value = 0;
for (int i = 0; i < length; i++) {
value = array[i];
- if (value < 0)
+ if (value < 0) {
value += 256;
+ }
ret = ret
| (long) ((long) value << ((length - i - 1) * NetUtils.NumBitsInAByte));
}
for (int i = startOffset; i < array.length; i++) {
value = array[i];
- if (value < 0)
+ if (value < 0) {
value += 256;
+ }
ret = ret
| (long) ((long) value << ((array.length - i - 1) * NetUtils.NumBitsInAByte));
}
}
} else {
for (i = 0; i < numBytes; i++) {
- if (i != 0)
+ if (i != 0) {
InputLSBbits = (inputdata[i - 1] & getLSBMask(extraOffsetBits));
+ }
InputMSBbits = (byte) (inputdata[i] & (getMSBMask(NetUtils.NumBitsInAByte
- extraOffsetBits)));
InputMSBbits = (InputMSBbits >= 0) ? InputMSBbits
InputMSBbits = InputLSBbits = 0;
}
if (RestBits < (NetUtils.NumBitsInAByte - extraOffsetBits)) {
- if (numBytes != 0)
+ if (numBytes != 0) {
InputLSBbits = (inputdata[i - 1] & getLSBMask(extraOffsetBits));
+ }
InputMSBbits = (byte) (inputdata[i] & (getMSBMask(RestBits)));
InputMSBbits = (InputMSBbits >= 0) ? InputMSBbits
: InputMSBbits + 256;
data[startByteOffset + i] = (byte) ((data[startByteOffset + i])
| (InputLSBbits << (NetUtils.NumBitsInAByte - extraOffsetBits)) | (InputMSBbits >> extraOffsetBits));
} else if (RestBits == (NetUtils.NumBitsInAByte - extraOffsetBits)) {
- if (numBytes != 0)
+ if (numBytes != 0) {
InputLSBbits = (inputdata[i - 1] & getLSBMask(extraOffsetBits));
+ }
InputMSBbits = (byte) (inputdata[i] & (getMSBMask(NetUtils.NumBitsInAByte
- extraOffsetBits)));
InputMSBbits = (InputMSBbits >= 0) ? InputMSBbits
data[startByteOffset + i] = (byte) (data[startByteOffset + i]
| (InputLSBbits << (NetUtils.NumBitsInAByte - extraOffsetBits)) | (InputMSBbits >> extraOffsetBits));
} else {
- if (numBytes != 0)
+ if (numBytes != 0) {
InputLSBbits = (inputdata[i - 1] & getLSBMask(extraOffsetBits));
+ }
InputMSBbits = (byte) (inputdata[i] & (getMSBMask(NetUtils.NumBitsInAByte
- extraOffsetBits)));
InputMSBbits = (InputMSBbits >= 0) ? InputMSBbits
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
DataLinkAddress other = (DataLinkAddress) obj;
if (name == null) {
- if (other.name != null)
+ if (other.name != null) {
return false;
- } else if (!name.equals(other.name))
+ }
+ } else if (!name.equals(other.name)) {
return false;
+ }
return true;
}
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (!super.equals(obj))
+ }
+ if (!super.equals(obj)) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
EthernetAddress other = (EthernetAddress) obj;
- if (!Arrays.equals(macAddress, other.macAddress))
+ if (!Arrays.equals(macAddress, other.macAddress)) {
return false;
+ }
return true;
}
public final void channelInactive(final ChannelHandlerContext ctx) {
LOG.debug("Channel {} inactive.", ctx.channel());
endOfInput();
+ try {
+ // Forward channel inactive event, all handlers in pipeline might be interested in the event e.g. close channel handler of reconnect promise
+ super.channelInactive(ctx);
+ } catch (final Exception e) {
+ throw new RuntimeException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
+ }
}
@Override
pending = this.dispatcher.createClient(this.address, cs, b, new AbstractDispatcher.PipelineInitializer<S>() {
@Override
public void initializeChannel(final SocketChannel channel, final Promise<S> promise) {
- // add closed channel handler
- // This handler has to be added before initializer.initializeChannel is called
- // Initializer might add some handlers using addFirst e.g. AsyncSshHandler and in that case
- // closed channel handler is before the handler that invokes channel inactive event
- channel.pipeline().addFirst(new ClosedChannelHandler(ReconnectPromise.this));
-
initializer.initializeChannel(channel, promise);
+ // add closed channel handler
+ // This handler has to be added as last channel handler and the channel inactive event has to be caught by it
+ // Handlers in front of it can react to channelInactive event, but have to forward the event or the reconnect will not work
+ // This handler is last so all handlers in front of it can handle channel inactive (to e.g. resource cleanup) before a new connection is started
+ channel.pipeline().addLast(new ClosedChannelHandler(ReconnectPromise.this));
}
});
}
@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
- // Pass info about disconnect further and then reconnect
- super.channelInactive(ctx);
-
+ // This is the ultimate channel inactive handler, not forwarding
if (promise.isCancelled()) {
return;
}
LOG.debug("Storage file does not exist, creating empty file");
try {
boolean result = storage.createNewFile();
- if (result == false)
+ if (result == false) {
throw new RuntimeException("Unable to create storage file " + storage);
+ }
} catch (IOException e) {
throw new RuntimeException("Unable to create storage file " + storage, e);
}
}
public static Config fromXml(File from) {
- if(isEmpty(from))
+ if(isEmpty(from)) {
return new Config();
+ }
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
@Override
public void close() throws IOException {
- if (reg != null)
+ if (reg != null) {
reg.close();
+ }
unregisterFromLogback();
}
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
-
import java.util.Set;
import java.util.concurrent.TimeUnit;
-
import org.opendaylight.controller.config.api.JmxAttributeValidationException;
/**
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.DeadEvent;
import com.google.common.eventbus.Subscribe;
-
import java.io.Closeable;
import java.io.IOException;
-
import org.opendaylight.controller.config.threadpool.ThreadPool;
import org.opendaylight.controller.config.yang.threadpool.impl.AsyncEventBusRuntimeMXBean;
import org.opendaylight.controller.config.yang.threadpool.impl.AsyncEventBusRuntimeRegistration;
package org.opendaylight.controller.config.threadpool.util;
+import com.google.common.eventbus.DeadEvent;
+import com.google.common.eventbus.EventBus;
+import com.google.common.eventbus.Subscribe;
import java.io.Closeable;
-
import org.opendaylight.controller.config.yang.threadpool.impl.EventBusRuntimeMXBean;
import org.opendaylight.controller.config.yang.threadpool.impl.EventBusRuntimeRegistration;
import org.opendaylight.controller.config.yang.threadpool.impl.EventBusRuntimeRegistrator;
-import com.google.common.eventbus.DeadEvent;
-import com.google.common.eventbus.EventBus;
-import com.google.common.eventbus.Subscribe;
-
/**
* Closeable {@link EventBus}.
*/
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
-
import org.opendaylight.controller.config.threadpool.ThreadPool;
/**
package org.opendaylight.controller.config.threadpool.util;
+import com.google.common.base.Optional;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-
import org.opendaylight.controller.config.threadpool.ThreadPool;
-import com.google.common.base.Optional;
-
/**
* Implementation of {@link ThreadPool} using flexible number of threads wraps
* {@link ExecutorService}.
package org.opendaylight.controller.config.threadpool.util;
+import com.google.common.base.Preconditions;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
-
import javax.annotation.concurrent.ThreadSafe;
-import com.google.common.base.Preconditions;
-
/**
* Implementation of {@link ThreadFactory}.
*/
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
-
import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
/**
import com.google.common.base.Optional;
import java.util.concurrent.TimeUnit;
-
import org.opendaylight.controller.config.api.JmxAttributeValidationException;
import org.opendaylight.controller.config.threadpool.util.FlexibleThreadPoolWrapper;
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.ConflictingVersionException;
*/
package org.opendaylight.controller.config.threadpool.eventbus;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.ObjectName;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
import org.opendaylight.controller.config.yang.threadpool.impl.EventBusModuleFactory;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
public class SyncEventBusConfigBeanTest extends AbstractConfigTest {
private EventBusModuleFactory factory;
import org.slf4j.LoggerFactory;
public class FixedThreadPoolConfigBeanTest extends AbstractConfigTest {
- private static final Logger logger = LoggerFactory.getLogger(FixedThreadPoolConfigBeanTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(FixedThreadPoolConfigBeanTest.class);
private FixedThreadPoolModuleFactory factory;
private final String nameInstance = "fixedInstance";
result++;
}
}
- logger.info("Current threads {}", names);
+ LOG.info("Current threads {}", names);
return result;
}
import static org.mockito.Mockito.mock;
import java.util.concurrent.ExecutorService;
-
import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.manager.impl.AbstractMockedModule;
*/
package org.opendaylight.controller.config.threadpool.flexible;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.ObjectName;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.yang.threadpool.impl.flexible.FlexibleThreadPoolModuleFactory;
import org.opendaylight.controller.config.yang.threadpool.impl.flexible.FlexibleThreadPoolModuleMXBean;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
public class FlexibleThreadPoolConfigBeanTest extends AbstractConfigTest {
private FlexibleThreadPoolModuleFactory flexibleFactory;
import java.io.Closeable;
import java.io.IOException;
-
import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.spi.Module;
*/
package org.opendaylight.controller.config.threadpool.scheduled;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
import com.google.common.util.concurrent.ListenableFutureTask;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import javax.management.ObjectName;
import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.manager.impl.AbstractMockedModule;
import org.opendaylight.controller.config.yang.threadpool.ScheduledThreadPoolServiceInterface;
import org.opendaylight.controller.config.yang.threadpool.impl.scheduled.ScheduledThreadPoolModuleMXBean;
-import javax.management.ObjectName;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Matchers.anyLong;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
public class TestingScheduledThreadPoolModule extends AbstractMockedModule implements
ScheduledThreadPoolServiceInterface, Module, ScheduledThreadPoolModuleMXBean {
*/
package org.opendaylight.controller.config.yangjmxgenerator.it;
+import static org.junit.Assert.fail;
+
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.ObjectName;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
import org.opendaylight.controller.config.yang.test.impl.TestImplModuleMXBean;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-
-import static org.junit.Assert.fail;
-
@Ignore
// ietf beans are not JMX compliant beans:
// Do not know how to make a
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
final class CodeWriter {
- private static final Logger LOGGER = LoggerFactory.getLogger(CodeWriter.class);
+ private static final Logger LOG = LoggerFactory.getLogger(CodeWriter.class);
private static final Optional<String> COPYRIGHT = StringUtil.loadCopyright();
public File writeSie(ServiceInterfaceEntry sie, File outputBaseDir) {
} catch (Exception e) {
String message = "An error occurred during Service interface generating, sie:"
+ sie.getTypeName() + ", " + sie.getFullyQualifiedName();
- LOGGER.error(message, e);
+ LOG.error(message, e);
throw new RuntimeException(message, e);
}
}
} catch (Exception e) {
String message = "An error occurred during Module generating, mbe:"
+ mbe.getJavaNamePrefix();
- LOGGER.error(message, e);
+ LOG.error(message, e);
throw new RuntimeException(message, e);
}
}
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+import java.io.File;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.StaticLoggerBinder;
-import java.io.File;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
/**
* This class interfaces with yang-maven-plugin. Gets parsed yang modules in
* {@link SchemaContext}, and parameters form the plugin configuration, and
private PackageTranslator packageTranslator;
private final CodeWriter codeWriter;
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(JMXGenerator.class);
private Map<String, String> namespaceToPackageMapping;
private File resourceBaseDir;
fullyQualifiedNamesOfFactories.toString());
} catch (IOException e) {
String message = "Cannot write to " + serviceLoaderFile;
- LOGGER.error(message);
+ LOG.error(message);
throw new RuntimeException(message, e);
}
}
@Override
public void setAdditionalConfig(Map<String, String> additionalCfg) {
- if (LOGGER != null) {
- LOGGER.debug(getClass().getCanonicalName(),
+ if (LOG != null) {
+ LOG.debug(getClass().getCanonicalName(),
": Additional configuration received: ",
additionalCfg.toString());
}
public void setMavenProject(MavenProject project) {
this.projectBaseDir = project.getBasedir();
- if (LOGGER != null)
- LOGGER.debug(getClass().getCanonicalName(), " project base dir: ",
+ if (LOG != null) {
+ LOG.debug(getClass().getCanonicalName(), " project base dir: ",
projectBaseDir);
+ }
}
@VisibleForTesting
}
}
if (undeletedFiles.isEmpty() == false) {
- LOGGER.error(
+ LOG.error(
"Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
undeletedFiles);
}
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
import com.google.common.collect.Lists;
+import java.util.Collections;
+import java.util.List;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-import java.util.Collections;
-import java.util.List;
-
public class AbstractFactoryTemplate extends GeneralClassTemplate {
private static final List<String> IMPLEMENTED_IFCS = Lists
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
+import java.util.Collections;
+import java.util.List;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.TypeDeclaration;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-import java.util.Collections;
-import java.util.List;
-
public abstract class AbstractFtlTemplate implements FtlTemplate {
private final String packageName;
private final List<Field> fields;
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
+import java.util.Collections;
+import java.util.List;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.ModuleField;
-import java.util.Collections;
-import java.util.List;
-
public class AbstractModuleTemplate extends GeneralClassTemplate {
private final List<ModuleField> moduleFields;
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
import com.google.common.base.Optional;
+import java.util.List;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Method;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.TypeDeclaration;
-import java.util.List;
-
public interface FtlTemplate {
Header getHeader();
import java.util.Collections;
import java.util.List;
-
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
}
static List<String> checkCardinality(List<String> extendedClass) {
- if (extendedClass.size() > 1)
+ if (extendedClass.size() > 1) {
throw new IllegalArgumentException(
"Class cannot have more than one super " + "class");
+ }
return extendedClass;
}
import java.util.Collections;
import java.util.List;
-
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDeclaration;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.opendaylight.controller.config.api.runtime.HierarchicalRuntimeBeanRegistration;
import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.Lists;
-
public class RuntimeRegistratorFtlTemplate extends GeneralClassTemplate {
private RuntimeRegistratorFtlTemplate(RuntimeBeanEntry runtimeBeanEntry,
// TODO header
super(null, runtimeBeanEntry.getPackageName(), name, Collections
.<String> emptyList(), Arrays.asList(Closeable.class
- .getCanonicalName()), fields, methods);
+ .getCanonicalName()), fields, methods);
}
public static RuntimeBeanEntry findRoot(
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
import com.google.common.collect.Lists;
+import java.util.Collections;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-import java.util.Collections;
-
public class StubFactoryTemplate extends GeneralClassTemplate {
public StubFactoryTemplate(Header header, String packageName, String name,
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import javax.management.openmbean.SimpleType;
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.controller.config.api.IdentityAttributeRef;
import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import javax.management.openmbean.SimpleType;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
public class TemplateFactory {
/**
Lists.<MethodDeclaration> newArrayList());
sieTemplate.setJavadoc(sie.getNullableDescription());
- if (sie.getNullableDescription() != null)
+ if (sie.getNullableDescription() != null) {
sieTemplate.getAnnotations().add(
Annotation.createDescriptionAnnotation(sie
.getNullableDescription()));
+ }
sieTemplate.getAnnotations().addAll(Annotation.createSieAnnotations(sie));
return sieTemplate;
attrProcessor.getMethods(), generateRuntime,
registratorFullyQualifiedName);
- if (mbe.getNullableDescription() != null)
+ if (mbe.getNullableDescription() != null) {
abstractModuleTemplate.getAnnotations().add(
Annotation.createDescriptionAnnotation(mbe
.getNullableDescription()));
+ }
return abstractModuleTemplate;
}
private static boolean needsDepResolver(AttributeIfc value) {
- if(value instanceof TOAttribute)
+ if(value instanceof TOAttribute) {
return true;
+ }
if(value instanceof ListAttribute) {
AttributeIfc innerAttribute = ((ListAttribute) value).getInnerAttribute();
return needsDepResolver(innerAttribute);
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
-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 org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
-import org.opendaylight.yangtools.yang.common.QName;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+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 org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
+import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
+import org.opendaylight.yangtools.yang.common.QName;
public class Annotation {
final String name;
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-import com.google.common.collect.Lists;
+import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.common.collect.Lists;
import java.util.List;
-import static com.google.common.base.Preconditions.checkNotNull;
-
public class Field {
private final String type;
private final String name;
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator;
-
import java.util.Date;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator;
public class HeaderSerializer {
private static final String GENERATOR_CLASS = JMXGenerator.class.getCanonicalName();
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.Dependency;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import org.opendaylight.controller.config.yangjmxgenerator.attribute.Dependency;
public class ModuleField extends Field {
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
-
import java.util.List;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
public class TypeDeclaration {
private final String type, name;
}
// add logger:
- b.addToBody(getLogger(abstractFQN));
+ b.addToBody(getLoggerDefinition(abstractFQN));
b.addToBody("//attributes start");
for(ModuleField moduleField: moduleFields) {
return result;
}
- private static String getLogger(FullyQualifiedName fqn) {
+ private static String getLoggerDefinition(FullyQualifiedName fqn) {
return format("private static final %s logger = %s.getLogger(%s.class);",
Logger.class.getCanonicalName(), LoggerFactory.class.getCanonicalName(), fqn);
}
package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory;
+import com.google.common.base.Joiner;
+import com.google.common.base.Optional;
import java.util.LinkedHashMap;
-
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.JavaFileInputBuilder;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
-import com.google.common.base.Joiner;
-import com.google.common.base.Optional;
-
public class ConcreteModuleGeneratedObjectFactory {
public GeneratedObject toGeneratedObject(ModuleMXBeanEntry mbe, Optional<String> copyright, Optional<String> header) {
package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+import static com.google.common.base.Preconditions.checkNotNull;
+
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import static com.google.common.base.Preconditions.checkNotNull;
-
public class FullyQualifiedName {
private final String packageName;
package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+import static com.google.common.base.Preconditions.checkNotNull;
+
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
-import org.apache.commons.io.FileUtils;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
-
import java.io.File;
import java.io.IOException;
import java.util.Map.Entry;
-
-import static com.google.common.base.Preconditions.checkNotNull;
+import org.apache.commons.io.FileUtils;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
public class GeneratedObject {
package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+import static org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil.prefixAndJoin;
+
import com.google.common.base.Optional;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
-import static org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil.prefixAndJoin;
-
public class GeneratedObjectBuilder {
private final JavaFileInput input;
package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
import com.google.common.base.Optional;
-
import java.util.List;
public interface JavaFileInput {
package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
+import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.common.base.Optional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-
-import static com.google.common.base.Preconditions.checkNotNull;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
public class JavaFileInputBuilder {
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
+import java.util.List;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.List;
-import java.util.regex.Pattern;
-
public class StringUtil {
- private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
+ private static final Logger LOG = LoggerFactory.getLogger(StringUtil.class);
/**
* @param list of strings to be joined by ','
return Optional.of(IOUtils.toString(in));
}
} catch (IOException e) {
- logger.warn("Cannot load copyright.txt", e);
+ LOG.warn("Cannot load copyright.txt", e);
}
*/
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
+import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.opendaylight.controller.config.yangjmxgenerator.AbstractYangTest;
-import java.io.File;
-
public abstract class AbstractGeneratorTest extends AbstractYangTest {
private static final File GENERATOR_OUTPUT_PATH_ROOT = new File(
"target/testgen");
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import com.google.common.collect.Sets;
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants;
import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslatorTest;
-import com.google.common.collect.Sets;
-
public class JMXGeneratorFileNamesValidationTest extends JMXGeneratorTest {
@Test
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
import static org.junit.Assert.assertEquals;
+
import java.io.File;
import org.junit.Test;
private static class SieASTVisitor extends ASTVisitor {
protected String packageName, descriptionAnotValue, sieAnnotValue,
- sieAnnotOsgiRegistrationType, type, extnds, javadoc;
+ sieAnnotOsgiRegistrationType, type, extnds, javadoc;
protected Map<String, String> methodDescriptions = Maps.newHashMap();
@Override
import java.util.Collection;
import java.util.List;
import java.util.Map;
-
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntryTest;
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
import com.google.common.collect.Maps;
+import java.util.Collections;
+import java.util.Map;
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import java.util.Collections;
-import java.util.Map;
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
public class ModuleMXBeanEntryTemplatesTest {
@Test
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Map;
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeRegistratorTest;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.RuntimeRegistratorFtlTemplate;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Map;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
public class RuntimeRegistratorFtlFileTest extends RuntimeRegistratorTest {
@Test
package org.opendaylight.controller.config.yangjmxgenerator.plugin.module;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
import net.sourceforge.pmd.lang.Parser;
import net.sourceforge.pmd.lang.ParserOptions;
import net.sourceforge.pmd.lang.ast.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
public class AbstractGeneratedObjectTest extends AbstractGeneratorTest {
- private static final Logger logger = LoggerFactory.getLogger(AbstractGeneratedObjectTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractGeneratedObjectTest.class);
protected void assertHasMethodNamed(Node c, String method) {
assertTrue(c.hasDescendantMatchingXPath("//MethodDeclaration[MethodDeclarator[@Image='" +
protected Node parse(File dstFile) throws IOException {
assertNotNull(dstFile);
- logger.debug(FileUtils.readFileToString(dstFile));
+ LOG.debug(FileUtils.readFileToString(dstFile));
Parser parser = new Java17Parser(new ParserOptions());
return parser.parse(dstFile.toString(), new FileReader(dstFile));
}
package org.opendaylight.controller.config.yangjmxgenerator.plugin.module.abs;
import com.google.common.base.Optional;
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Map.Entry;
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.module.AbstractGeneratedObjectTest;
import org.opendaylight.yangtools.yang.common.QName;
-import java.io.File;
-import java.io.IOException;
-import java.util.Map;
-import java.util.Map.Entry;
-
public class AbsModuleGeneratedObjectFactoryTest extends AbstractGeneratedObjectTest {
@Test
package org.opendaylight.controller.config.yangjmxgenerator.plugin.module.concrete;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
import com.google.common.base.Optional;
+import java.io.File;
+import java.util.Map.Entry;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.module.AbstractGeneratedObjectTest;
-import java.io.File;
-import java.util.Map.Entry;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
public class ConcreteModuleGeneratedObjectFactoryTest extends AbstractGeneratedObjectTest {
@Test
package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-
-import java.io.IOException;
-
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import java.io.IOException;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
+
public class StringUtilTest {
@Test
public void testPrefixAndJoin() {
@Test
public void testFormatting() {
{
- String input = " \tpack;\n" +
+ String input = " \tpack;\n" +
"class Bar{ \n" +
" method() {\n" +
" body\n" +
"}\n" +
" }";
- String expected = "pack;\n" +
+ String expected = "pack;\n" +
"class Bar{\n" +
" method() {\n" +
" body\n" +
" }\n" +
"}\n";
- assertEquals(expected, StringUtil.formatJavaSource(input));
+ assertEquals(expected, StringUtil.formatJavaSource(input));
}
{
String input = "{\n" +
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import javax.annotation.Nullable;
-
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AbstractDependencyAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
return this;
}
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(ModuleMXBeanEntryBuilder.class);
// TODO: the XPath should be parsed by code generator IMO
public Map<String, ModuleMXBeanEntry> build() {
- LOGGER.debug("Generating ModuleMXBeans of {} to package {}",
+ LOG.debug("Generating ModuleMXBeans of {} to package {}",
currentModule.getNamespace(), packageName);
String configModulePrefix;
checkAttributeNamesUniqueness(uniqueGeneratedClassesNames, result);
checkUnaugumentedIdentities(unaugmentedModuleIdentities);
- LOGGER.debug("Number of ModuleMXBeans to be generated: {}", result.size());
+ LOG.debug("Number of ModuleMXBeans to be generated: {}", result.size());
return result;
}
private static void checkUnaugumentedIdentities(final Map<String, IdentitySchemaNode> unaugmentedModuleIdentities) {
if (unaugmentedModuleIdentities.size() > 0) {
- LOGGER.warn("Augmentation not found for all currentModule identities: {}",
+ LOG.warn("Augmentation not found for all currentModule identities: {}",
unaugmentedModuleIdentities.keySet());
}
}
+ identityLocalName);
} else {
moduleIdentities.put(identityLocalName, id);
- LOGGER.debug("Found identity {}", identityLocalName);
+ LOG.debug("Found identity {}", identityLocalName);
}
// validation check on unknown schema nodes
boolean providedServiceWasSet = false;
HAS_CHILDREN_AND_QNAME dataNodeContainer = getDataNodeContainer(choiceCaseNode);
if (EXPECTED_CONFIGURATION_AUGMENTATION_SCHEMA_PATH.equals(augmentation.getTargetPath())) {
- LOGGER.debug("Parsing configuration of {}", moduleLocalNameFromXPath);
+ LOG.debug("Parsing configuration of {}", moduleLocalNameFromXPath);
yangToAttributes = fillConfiguration(dataNodeContainer, currentModule, typeProviderWrapper, qNamesToSIEs,
schemaContext, packageName);
checkUniqueAttributesWithGeneratedClass(uniqueGeneratedClassesNames, when.getQName(), yangToAttributes);
} else if (EXPECTED_STATE_AUGMENTATION_SCHEMA_PATH.equals(augmentation.getTargetPath())) {
- LOGGER.debug("Parsing state of {}", moduleLocalNameFromXPath);
+ LOG.debug("Parsing state of {}", moduleLocalNameFromXPath);
try {
runtimeBeans = fillRuntimeBeans(dataNodeContainer, currentModule, typeProviderWrapper, packageName,
moduleLocalNameFromXPath, javaNamePrefix);
" both state and configuration");
} else {
ModuleMXBeanEntry.ModuleMXBeanEntryInitial initial = new ModuleMXBeanEntry.ModuleMXBeanEntryInitialBuilder()
- .setIdSchemaNode(moduleIdentity).setPackageName(packageName).setJavaNamePrefix(javaNamePrefix)
- .setNamespace(currentModule.getNamespace().toString()).setqName(ModuleUtil.getQName(currentModule))
- .build();
+ .setIdSchemaNode(moduleIdentity).setPackageName(packageName).setJavaNamePrefix(javaNamePrefix)
+ .setNamespace(currentModule.getNamespace().toString()).setqName(ModuleUtil.getQName(currentModule))
+ .build();
// construct ModuleMXBeanEntry
ModuleMXBeanEntry moduleMXBeanEntry = new ModuleMXBeanEntry(initial, yangToAttributes, providedServices,
import java.util.Map;
import java.util.Map.Entry;
-
import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
import org.opendaylight.yangtools.yang.model.api.Module;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
-
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
*/
package org.opendaylight.controller.config.yangjmxgenerator;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static java.lang.String.format;
+import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.SERVICE_TYPE_Q_NAME;
+
import com.google.common.base.Optional;
import java.util.ArrayList;
import java.util.HashMap;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static com.google.common.base.Preconditions.checkNotNull;
-import static java.lang.String.format;
-import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.SERVICE_TYPE_Q_NAME;
/**
* Represents identity derived from {@link ConfigConstants#SERVICE_TYPE_Q_NAME}.
* </p>
*/
public class ServiceInterfaceEntry extends AbstractEntry {
- private static final Logger LOGGER = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(ServiceInterfaceEntry.class);
private static final String CLASS_NAME_SUFFIX = "ServiceInterface";
*/
public static Map<QName, ServiceInterfaceEntry> create(Module currentModule,
String packageName,Map<IdentitySchemaNode, ServiceInterfaceEntry> definedSEItracker) {
- LOGGER.debug("Generating ServiceInterfaces from {} to package {}",
+ LOG.debug("Generating ServiceInterfaces from {} to package {}",
currentModule.getNamespace(), packageName);
Map<IdentitySchemaNode, ServiceInterfaceEntry> identitiesToSIs = new HashMap<>();
int lastSize = notVisited.size() + 1;
while (!notVisited.isEmpty()) {
if (notVisited.size() == lastSize) {
- LOGGER.debug(
+ LOG.debug(
"Following identities will be ignored while generating ServiceInterfaces, as they are not derived from {} : {}",
SERVICE_TYPE_Q_NAME, notVisited);
break;
for (ServiceInterfaceEntry sie : identitiesToSIs.values()) {
resultMap.put(sie.getQName(), sie);
}
- LOGGER.debug("Number of ServiceInterfaces to be generated: {}",
+ LOG.debug("Number of ServiceInterfaces to be generated: {}",
resultMap.size());
return resultMap;
}
public abstract class AbstractAttribute implements AttributeIfc {
private final String attributeYangName, upperCaseCammelCase,
- lowerCaseCammelCase;
+ lowerCaseCammelCase;
protected final DataSchemaNode node;
private static String getLocalName(DataSchemaNode attrNode) {
@Override
public boolean equals(Object o) {
- if (this == o)
+ if (this == o) {
return true;
- if (o == null || getClass() != o.getClass())
+ }
+ if (o == null || getClass() != o.getClass()) {
return false;
+ }
Dependency that = (Dependency) o;
- if (mandatory != that.mandatory)
+ if (mandatory != that.mandatory) {
return false;
- if (!sie.equals(that.sie))
+ }
+ if (!sie.equals(that.sie)) {
return false;
+ }
return true;
}
*/
package org.opendaylight.controller.config.yangjmxgenerator.attribute;
+import javax.management.ObjectName;
+import javax.management.openmbean.SimpleType;
import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
import org.opendaylight.yangtools.binding.generator.util.Types;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import javax.management.ObjectName;
-import javax.management.openmbean.SimpleType;
-
public class DependencyAttribute extends AbstractDependencyAttribute {
package org.opendaylight.controller.config.yangjmxgenerator.attribute;
import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import java.util.List;
+import javax.management.openmbean.ArrayType;
+import javax.management.openmbean.CompositeType;
+import javax.management.openmbean.OpenDataException;
+import javax.management.openmbean.OpenType;
+import javax.management.openmbean.SimpleType;
import org.opendaylight.controller.config.api.IdentityAttributeRef;
import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import java.util.Arrays;
-import java.util.List;
-
public class JavaAttribute extends AbstractAttribute implements TypedAttribute {
public static final String DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION = "valueOfArtificialUnionProperty";
return simpleType;
}
- private OpenType<?> getCompositeType(Type baseType, TypeDefinition<?> baseTypeDefinition) {
+ private OpenType<?> getCompositeType(Type baseType, TypeDefinition<?> baseTypeDefinition) {
SimpleType<?> innerItemType = SimpleTypeResolver.getSimpleType(baseType);
String innerItemName = typeProviderWrapper.getJMXParamForBaseType(baseTypeDefinition);
// TODO verify
private boolean isPrimitive(String innerTypeFullyQName) {
- if (innerTypeFullyQName.contains("."))
+ if (innerTypeFullyQName.contains(".")) {
return false;
+ }
return true;
}
*/
package org.opendaylight.controller.config.yangjmxgenerator.attribute;
+import java.util.List;
+import javax.management.openmbean.ArrayType;
+import javax.management.openmbean.OpenDataException;
+import javax.management.openmbean.OpenType;
import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
import org.opendaylight.yangtools.binding.generator.util.Types;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import java.util.List;
-
public class ListAttribute extends AbstractAttribute implements TypedAttribute {
private final String nullableDescription, nullableDefault;
*/
package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.yangtools.binding.generator.util.Types;
-import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
+import java.util.List;
import javax.management.ObjectName;
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
-import java.util.List;
+import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
+import org.opendaylight.yangtools.binding.generator.util.Types;
+import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
public class ListDependenciesAttribute extends AbstractDependencyAttribute {
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
-import org.opendaylight.yangtools.sal.binding.model.api.Type;
-
-import javax.management.openmbean.SimpleType;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.Map;
+import javax.management.openmbean.SimpleType;
+import org.opendaylight.yangtools.sal.binding.model.api.Type;
public class SimpleTypeResolver {
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import javax.management.openmbean.CompositeType;
+import javax.management.openmbean.OpenDataException;
+import javax.management.openmbean.OpenType;
import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
public class TOAttribute extends AbstractAttribute implements TypedAttribute {
private final String nullableDescription, nullableDefault;
public static String getFullyQualifiedName(String packageName,
String className) {
- if (packageName.isEmpty())
+ if (packageName.isEmpty()) {
return className;
+ }
return packageName + "." + className;
}
}
*/
package org.opendaylight.controller.config.yangjmxgenerator;
-import static org.junit.Assert.assertNotNull;
import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import com.google.common.base.Preconditions;
protected Map<String, Module> namesToModules; // are module names globally
// unique?
protected Module configModule, rpcContextModule, threadsModule,
- threadsJavaModule, bgpListenerJavaModule, ietfInetTypesModule,
- jmxModule, jmxImplModule, testFilesModule, testFiles1Module;
+ threadsJavaModule, bgpListenerJavaModule, ietfInetTypesModule,
+ jmxModule, jmxImplModule, testFilesModule, testFiles1Module;
public static final String EVENTBUS_MXB_NAME = "eventbus";
public static final String ASYNC_EVENTBUS_MXB_NAME = "async-eventbus";
protected Map<String /* identity local name */, ModuleMXBeanEntry> loadThreadsJava(Map<QName, ServiceInterfaceEntry> modulesToSIEs, String packageName) {
Map<String /* identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
.create(threadsJavaModule, modulesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl
- (context)), packageName);
+ (context)), packageName);
Assert.assertNotNull(namesToMBEs);
Set<String> expectedMXBeanNames = Sets.newHashSet(EVENTBUS_MXB_NAME,
ASYNC_EVENTBUS_MXB_NAME, THREADFACTORY_NAMING_MXB_NAME,
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import com.google.common.base.Preconditions;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.NameConflictException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Preconditions;
-
public class ModuleMXBeanEntryNameConflictTest extends AbstractYangTest {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOG = LoggerFactory
.getLogger(ModuleMXBeanEntryNameConflictTest.class);
public static final String PACKAGE_NAME = "pack2";
Module testedModule = loadYangs(yangFile, moduleName);
try {
- logger.debug("Testing {}", yangFile);
+ LOG.debug("Testing {}", yangFile);
ModuleMXBeanEntry.create(testedModule,
new HashMap<QName, ServiceInterfaceEntry>(), context,
new TypeProviderWrapper(new TypeProviderImpl(context)),
import static org.mockito.Mockito.mock;
import com.google.common.collect.Sets;
-
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
-
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.SimpleType;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import com.google.common.collect.Maps;
import java.net.URI;
import java.util.Map;
-
import org.junit.Test;
import org.opendaylight.yangtools.yang.model.api.Module;
-import com.google.common.collect.Maps;
-
public class PackageTranslatorTest {
public static final String EXPECTED_PACKAGE_PREFIX = "org.opendaylight.controller.config";
import java.util.HashSet;
import java.util.List;
import java.util.Map;
-
import javax.management.openmbean.SimpleType;
-
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.MODULE_TYPE_Q_NAME;
import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.SERVICE_TYPE_Q_NAME;
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableMap;
-
public class SchemaContextTest extends AbstractYangTest {
IdentitySchemaNode findIdentityByQName(Module module, QName qName) {
Map<String /* identity name */, Optional<QName>> expectedIdentitiesToBases = new HashMap<String, Optional<QName>>(){
private static final long serialVersionUID = 1L;
- {
- put(ModuleMXBeanEntryTest.EVENTBUS_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- put(ModuleMXBeanEntryTest.ASYNC_EVENTBUS_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- put(ModuleMXBeanEntryTest.THREADFACTORY_NAMING_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- put(ModuleMXBeanEntryTest.THREADPOOL_DYNAMIC_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- put("thread-rpc-context", Optional.<QName>absent());
- put(ModuleMXBeanEntryTest.THREADPOOL_REGISTRY_IMPL_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- }};
+ {
+ put(ModuleMXBeanEntryTest.EVENTBUS_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
+ put(ModuleMXBeanEntryTest.ASYNC_EVENTBUS_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
+ put(ModuleMXBeanEntryTest.THREADFACTORY_NAMING_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
+ put(ModuleMXBeanEntryTest.THREADPOOL_DYNAMIC_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
+ put("thread-rpc-context", Optional.<QName>absent());
+ put(ModuleMXBeanEntryTest.THREADPOOL_REGISTRY_IMPL_NAME, Optional.of(MODULE_TYPE_Q_NAME));
+ }
+ };
assertAllIdentitiesAreExpected(threadsJavaModule,
expectedIdentitiesToBases);
import static org.junit.Assert.assertThat;
import com.google.common.collect.Sets;
-
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
+import com.google.common.base.Preconditions;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
-
import org.opendaylight.yangtools.yang.model.api.Module;
-import com.google.common.base.Preconditions;
-
public class YangModelSearchUtils {
public static Map<String, Module> mapModulesByNames(
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import com.google.common.collect.Lists;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
-
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants;
import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntryTest;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import com.google.common.collect.Lists;
-
public class UnknownExtensionTest extends ServiceInterfaceEntryTest {
@Test
*/
package org.opendaylight.controller.config.yang.test.plugin;
+import java.io.File;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
-import java.io.File;
-
/**
* Delete all Module/ModuleFactory sources
*
}
File sourceDirectory = new File(directory.getPath() + Util.replaceDots(".org.opendaylight.controller.config.yang.test.impl"));
if (sourceDirectory == null || !sourceDirectory.exists()) {
- super.getLog().error("Source directory does not exists " + sourceDirectory.getPath());
+ super.getLog().error(String.format("Source directory does not exists %s", sourceDirectory.getPath()));
}
File[] sourceFiles = sourceDirectory.listFiles();
for (File sourceFile: sourceFiles) {
if(sourceFile.getName().endsWith("Module.java") || sourceFile.getName().endsWith("ModuleFactory.java")) {
- super.getLog().debug("Source file deleted: " + sourceFile.getName());
+ super.getLog().debug(String.format("Source file deleted: %s", sourceFile.getName()));
sourceFile.delete();
}
}
*/
package org.opendaylight.controller.config.yang.test.plugin;
+import java.io.File;
+import java.io.IOException;
+import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
-import java.io.File;
-import java.io.IOException;
-import java.util.regex.Pattern;
-
/**
* Add implementation code from stub.txt
*
}
File sourceDirectory = new File(directory.getPath() + Util.replaceDots(".org.opendaylight.controller.config.yang.test.impl"));
if (!sourceDirectory.exists()) {
- super.getLog().error("Source directory does not exists " + sourceDirectory.getPath());
+ super.getLog().error(String.format("Source directory does not exists %s", sourceDirectory.getPath()));
}
File[] sourceFiles = sourceDirectory.listFiles();
try {
sourceContent = FileUtils.readFileToString(sourceFile);
} catch (IOException e) {
- getLog().error("Cannot read " + sourceFile.getAbsolutePath(), e);
+ getLog().error(String.format("Cannot read %s", sourceFile.getAbsolutePath()), e);
continue;
}
if (sourceFile.getName().endsWith("Module.java") || sourceFile.getName().endsWith("ModuleFactory.java")) {
try {
stubContent = FileUtils.readFileToString(stubFile);
} catch (IOException e) {
- getLog().error("Cannot read " + stubFile.getAbsolutePath(), e);
+ getLog().error(String.format("Cannot read %s", stubFile.getAbsolutePath()), e);
}
if (stubContent != null) {
sourceContent = rewriteStub(sourceContent, stubContent);
try {
FileUtils.write(sourceFile, sourceContent);
} catch (IOException e) {
- getLog().error("Cannot write " + sourceFile.getAbsolutePath(), e);
+ getLog().error(String.format("Cannot write %s", sourceFile.getAbsolutePath()), e);
}
}
*/
package org.opendaylight.controller.config.yang.test.impl;
-import com.google.common.collect.Lists;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+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.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.ObjectName;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.api.IdentityAttributeRef;
import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
public class NetconfTestImplModuleTest extends AbstractConfigTest {
public static final String TESTING_DEP_PREFIX = "testing-dep";
<artifactId>sal-rest-docgen</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-rest-docgen-maven</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<!-- Toaster -->
<dependency>
<!-- Documentation -->
<module>sal-rest-docgen</module>
+ <module>sal-rest-docgen-maven</module>
<module>sal-akka-raft</module>
package org.opendaylight.controller.sal.binding.codegen.impl;
import static org.opendaylight.controller.sal.binding.codegen.RuntimeCodeHelper.setRoutingTable;
-
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-
+import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-
public class RpcRouterCodegenInstance<T extends RpcService> implements //
RpcRouter<T>, RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
return new DefaultRpcImplementationRegistration(service);
}
- private class RoutedRpcRegistrationImpl extends AbstractObjectRegistration<T> implements RoutedRpcRegistration<T> {
+ private final class RoutedRpcRegistrationImpl extends AbstractObjectRegistration<T> implements RoutedRpcRegistration<T> {
+ /*
+ * FIXME: retaining this collection is not completely efficient. We really should be storing
+ * a reference to this registration, as a particular listener may be registered multiple
+ * times -- and then this goes kaboom in various aspects.
+ */
+ @GuardedBy("this")
+ private final Collection<Class<? extends BaseIdentity>> contexts = new ArrayList<>(1);
public RoutedRpcRegistrationImpl(final T instance) {
super(instance);
}
@Override
- public void registerPath(final Class<? extends BaseIdentity> context, final InstanceIdentifier<?> path) {
+ public synchronized void registerPath(final Class<? extends BaseIdentity> context, final InstanceIdentifier<?> path) {
+ if (isClosed()) {
+ LOG.debug("Closed registration of {} ignoring new path {}", getInstance(), path);
+ return;
+ }
+
routingTables.get(context).updateRoute(path, getInstance());
+ contexts.add(context);
}
@Override
- public void unregisterPath(final Class<? extends BaseIdentity> context, final InstanceIdentifier<?> path) {
+ public synchronized void unregisterPath(final Class<? extends BaseIdentity> context, final InstanceIdentifier<?> path) {
+ if (isClosed()) {
+ LOG.debug("Closed unregistration of {} ignoring new path {}", getInstance(), path);
+ return;
+ }
+
routingTables.get(context).removeRoute(path, getInstance());
+ contexts.remove(context);
}
+ @Deprecated
@Override
public void registerInstance(final Class<? extends BaseIdentity> context, final InstanceIdentifier<?> instance) {
registerPath(context, instance);
}
+ @Deprecated
@Override
public void unregisterInstance(final Class<? extends BaseIdentity> context, final InstanceIdentifier<?> instance) {
unregisterPath(context, instance);
}
@Override
- protected void removeRegistration() {
-
+ protected synchronized void removeRegistration() {
+ for (Class<? extends BaseIdentity> ctx : contexts) {
+ routingTables.get(ctx).removeAllReferences(getInstance());
+ }
+ contexts.clear();
}
}
- private class DefaultRpcImplementationRegistration extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
+ private final class DefaultRpcImplementationRegistration extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
protected DefaultRpcImplementationRegistration(final T instance) {
package org.opendaylight.controller.sal.binding.codegen.impl;
import java.util.Collections;
+import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-class RpcRoutingTableImpl<C extends BaseIdentity, S extends RpcService> //
-implements //
+final class RpcRoutingTableImpl<C extends BaseIdentity, S extends RpcService> implements
Mutable, //
RpcRoutingTable<C, S>, //
RouteChangePublisher<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
private RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> listener;
private S defaultRoute;
- public RpcRoutingTableImpl(String routerName,Class<C> contextType, Class<S> serviceType) {
+ public RpcRoutingTableImpl(final String routerName,final Class<C> contextType, final Class<S> serviceType) {
super();
this.routerName = routerName;
this.serviceType = serviceType;
}
@Override
- public void setDefaultRoute(S target) {
+ public void setDefaultRoute(final S target) {
defaultRoute = target;
}
@Override
public <L extends RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>>> ListenerRegistration<L> registerRouteChangeListener(
- L listener) {
+ final L listener) {
return new SingletonListenerRegistration<L>(listener);
}
@Override
@SuppressWarnings("unchecked")
- public void updateRoute(InstanceIdentifier<?> path, S service) {
+ public void updateRoute(final InstanceIdentifier<?> path, final S service) {
S previous = this.routes.put(path, service);
LOGGER.debug("Route {} updated to {} in routing table {}",path,service,this);
@Override
@SuppressWarnings("unchecked")
- public void removeRoute(InstanceIdentifier<?> path) {
+ public void removeRoute(final InstanceIdentifier<?> path) {
S previous = this.routes.remove(path);
LOGGER.debug("Route {} to {} removed in routing table {}",path,previous,this);
@SuppressWarnings("rawtypes")
}
}
- public void removeRoute(InstanceIdentifier<?> path, S service) {
+ void removeRoute(final InstanceIdentifier<?> path, final S service) {
@SuppressWarnings("rawtypes")
RouteChangeListener listenerCapture = listener;
if (routes.remove(path, service) && listenerCapture != null) {
}
@Override
- public S getRoute(InstanceIdentifier<?> nodeInstance) {
+ public S getRoute(final InstanceIdentifier<?> nodeInstance) {
S route = routes.get(nodeInstance);
if (route != null) {
return route;
return unmodifiableRoutes;
}
- protected void removeAllReferences(S service) {
-
+ void removeAllReferences(final S service) {
+ // FIXME: replace this via properly-synchronized BiMap (or something)
+ final Iterator<S> it = routes.values().iterator();
+ while (it.hasNext()) {
+ final S s = it.next();
+ if (service.equals(s)) {
+ it.remove();
+ }
+ }
}
-
-
@Override
public String toString() {
return "RpcRoutingTableImpl [router=" + routerName + ", service=" + serviceType.getSimpleName() + ", context="
+ contextType.getSimpleName() + "]";
}
-
-
private class SingletonListenerRegistration<L extends RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>>> extends
AbstractObjectRegistration<L>
implements ListenerRegistration<L> {
- public SingletonListenerRegistration(L instance) {
+ public SingletonListenerRegistration(final L instance) {
super(instance);
listener = instance;
}
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
-
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
-
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;
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.impl.codec.BindingIndependentMappingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final RpcProviderRegistry baRpcRegistry;
private final RpcProviderRegistryImpl baRpcRegistryImpl;
- private final Function<InstanceIdentifier<?>, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier> toDOMInstanceIdentifier;
+ private final Function<InstanceIdentifier<?>, YangInstanceIdentifier> toDOMInstanceIdentifier;
private final static Method EQUALS_METHOD;
this.rpcServiceType = new WeakReference<Class<? extends RpcService>>(service);
this.supportedRpcs = mappingService.getRpcQNamesFor(service);
- toDOMInstanceIdentifier = new Function<InstanceIdentifier<?>, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier>() {
-
+ this.toDOMInstanceIdentifier = new Function<InstanceIdentifier<?>, YangInstanceIdentifier>() {
@Override
- public org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier apply(final InstanceIdentifier<?> input) {
+ public YangInstanceIdentifier apply(final InstanceIdentifier<?> input) {
return mappingService.toDataDom(input);
}
};
public void registerPaths(final Class<? extends BaseIdentity> context,
final Class<? extends RpcService> service, final Set<InstanceIdentifier<?>> set) {
QName ctx = BindingReflections.findQName(context);
- for (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier path : FluentIterable.from(set).transform(
+ for (YangInstanceIdentifier path : FluentIterable.from(set).transform(
toDOMInstanceIdentifier)) {
for (org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration reg : registrations) {
reg.registerPath(ctx, path);
public void removePaths(final Class<? extends BaseIdentity> context, final Class<? extends RpcService> service,
final Set<InstanceIdentifier<?>> set) {
QName ctx = BindingReflections.findQName(context);
- for (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier path : FluentIterable.from(set).transform(
+ for (YangInstanceIdentifier path : FluentIterable.from(set).transform(
toDOMInstanceIdentifier)) {
for (org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration reg : registrations) {
reg.unregisterPath(ctx, path);
package org.opendaylight.controller.sal.binding.impl.connect.dom;
+import com.google.common.base.Optional;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.WeakHashMap;
-
import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import com.google.common.base.Optional;
-
/**
* Manager responsible for instantiating forwarders responsible for
* forwarding of RPC invocations from DOM Broker to Binding Aware Broker
@Override
public void onRouteChange(final RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> change) {
- for (Map.Entry<RpcContextIdentifier, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements().entrySet()) {
- bindingRoutesAdded(entry);
+ // Process removals first
+ for (Entry<RpcContextIdentifier, Set<InstanceIdentifier<?>>> entry : change.getRemovals().entrySet()) {
+ final Class<? extends BaseIdentity> context = entry.getKey().getRoutingContext();
+ if (context != null) {
+ final Class<? extends RpcService> service = entry.getKey().getRpcService();
+ getRpcForwarder(service, context).removePaths(context, service, entry.getValue());
+ }
}
- }
- private void bindingRoutesAdded(final Map.Entry<RpcContextIdentifier, Set<InstanceIdentifier<?>>> entry) {
- Class<? extends BaseIdentity> context = entry.getKey().getRoutingContext();
- Class<? extends RpcService> service = entry.getKey().getRpcService();
- if (context != null) {
- getRpcForwarder(service, context).registerPaths(context, service, entry.getValue());
+ for (Entry<RpcContextIdentifier, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements().entrySet()) {
+ final Class<? extends BaseIdentity> context = entry.getKey().getRoutingContext();
+ if (context != null) {
+ final Class<? extends RpcService> service = entry.getKey().getRpcService();
+ getRpcForwarder(service, context).registerPaths(context, service, entry.getValue());
+ }
}
}
</parent>
<artifactId>sal-clustering-commons</artifactId>
-
<packaging>bundle</packaging>
- <dependencies>
-
+ <dependencies>
+ <!-- Java -->
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-actor_${scala.version}</artifactId>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
</dependency>
-
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-cluster_${scala.version}</artifactId>
+ <groupId>xmlunit</groupId>
+ <artifactId>xmlunit</artifactId>
</dependency>
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-persistence-experimental_${scala.version}</artifactId>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
</dependency>
-
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-remote_${scala.version}</artifactId>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
</dependency>
+ <!-- Apache -->
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-testkit_${scala.version}</artifactId>
+ <groupId>commons-lang</groupId>
+ <artifactId>commons-lang</artifactId>
</dependency>
-
+ <!-- Akka -->
<dependency>
- <groupId>org.scala-lang</groupId>
- <artifactId>scala-library</artifactId>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-actor_${scala.version}</artifactId>
</dependency>
-
-
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-slf4j_${scala.version}</artifactId>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-cluster_${scala.version}</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-osgi_${scala.version}</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-persistence-experimental_${scala.version}</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-remote_${scala.version}</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-slf4j_${scala.version}</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-testkit_${scala.version}</artifactId>
</dependency>
+ <!-- Codahale -->
+ <dependency>
+ <groupId>com.codahale.metrics</groupId>
+ <artifactId>metrics-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.codahale.metrics</groupId>
+ <artifactId>metrics-graphite</artifactId>
+ </dependency>
+ <!-- Google -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<artifactId>protobuf-java</artifactId>
<version>2.5.0</version>
</dependency>
+
+ <!-- Scala -->
<dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
+ <groupId>org.scala-lang</groupId>
+ <artifactId>scala-library</artifactId>
+ </dependency>
+
+ <!-- OpenDaylight -->
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-util</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-model-util</artifactId>
</dependency>
-
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-parser-impl</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-util</artifactId>
- </dependency>
-
- <dependency>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-binding</artifactId>
- </dependency>
-
-
- <dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-osgi_${scala.version}</artifactId>
- </dependency>
- <dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-actor_${scala.version}</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-parser-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.google.code.findbugs</groupId>
- <artifactId>jsr305</artifactId>
- </dependency>
- <dependency>
- <groupId>com.codahale.metrics</groupId>
- <artifactId>metrics-core</artifactId>
- </dependency>
- <dependency>
- <groupId>com.codahale.metrics</groupId>
- <artifactId>metrics-graphite</artifactId>
- </dependency>
</dependencies>
- <build>
+ <build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
}
private final void checkMutable() {
- if (!NEW.equals(this.getStatus()))
+ if (!NEW.equals(this.getStatus())) {
throw new IllegalStateException("Transaction was already submitted");
+ }
}
@Override
}
RouteChangeImpl<?, ?> other = (RouteChangeImpl<?, ?>) obj;
if (announcement == null) {
- if (other.announcement != null)
+ if (other.announcement != null) {
return false;
- } else if (!announcement.equals(other.announcement))
+ }
+ } else if (!announcement.equals(other.announcement)) {
return false;
+ }
if (removal == null) {
if (other.removal != null) {
return false;
}
- } else if (!removal.equals(other.removal))
+ } else if (!removal.equals(other.removal)) {
return false;
+ }
return true;
}
}
*/
@SuppressWarnings("unchecked")
public static <T> T checkInstanceOf(Object value, Class<T> type) {
- if(!type.isInstance(value))
+ if(!type.isInstance(value)) {
throw new IllegalArgumentException(String.format("Value %s is not of type %s", value, type));
+ }
return (T) value;
}
}
<packaging>bundle</packaging>
<dependencies>
+ <!-- Java -->
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
</dependency>
+ <!-- Akka -->
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_${scala.version}</artifactId>
</dependency>
-
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-cluster_${scala.version}</artifactId>
</dependency>
-
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-osgi_${scala.version}</artifactId>
+ </dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-persistence-experimental_${scala.version}</artifactId>
</dependency>
-
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-remote_${scala.version}</artifactId>
</dependency>
-
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-slf4j_${scala.version}</artifactId>
+ </dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-testkit_${scala.version}</artifactId>
</dependency>
+ <!-- Codahale -->
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-slf4j_${scala.version}</artifactId>
+ <groupId>com.codahale.metrics</groupId>
+ <artifactId>metrics-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.codahale.metrics</groupId>
+ <artifactId>metrics-graphite</artifactId>
</dependency>
+ <!-- Google -->
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-osgi_${scala.version}</artifactId>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
- <!-- SAL Dependencies -->
+ <!-- Scala -->
+ <dependency>
+ <groupId>org.scala-lang</groupId>
+ <artifactId>scala-library</artifactId>
+ </dependency>
+ <!-- OpenDaylight -->
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>config-api</artifactId>
</dependency>
-
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft</artifactId>
+ <version>1.2.0-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-binding-api</artifactId>
</dependency>
-
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-binding-config</artifactId>
</dependency>
-
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-api</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-impl</artifactId>
- </dependency>
-
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-inmemory-datastore</artifactId>
+ <artifactId>sal-clustering-commons</artifactId>
</dependency>
-
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-common-api</artifactId>
</dependency>
-
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-common-util</artifactId>
</dependency>
-
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-core-spi</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-inmemory-datastore</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>concepts</artifactId>
</dependency>
-
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-binding</artifactId>
</dependency>
-
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-common</artifactId>
</dependency>
-
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-api</artifactId>
</dependency>
-
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.scala-lang</groupId>
- <artifactId>scala-library</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-clustering-commons</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-akka-raft</artifactId>
- <version>1.2.0-SNAPSHOT</version>
- </dependency>
-
- <dependency>
- <groupId>com.codahale.metrics</groupId>
- <artifactId>metrics-core</artifactId>
- </dependency>
-
- <dependency>
- <groupId>com.codahale.metrics</groupId>
- <artifactId>metrics-graphite</artifactId>
- </dependency>
- <!-- Test Dependencies -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-impl</artifactId>
</dependency>
-
</dependencies>
<build>
<plugins>
-
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
return new BrokerImpl(router, services);
}
+ @Deprecated
private DataProviderService createLegacyDataService(final DataStore legacyStore, final SchemaService schemaService) {
YangInstanceIdentifier rootPath = YangInstanceIdentifier.builder().toInstance();
DataBrokerImpl dataService = new DataBrokerImpl();
String odlTableName) {
Map<String, XSQLBluePrintNode> map = this.odlNameToBluePrint
.get(odlTableName);
- if (map == null)
+ if (map == null) {
return null;
+ }
return map.values().toArray(new XSQLBluePrintNode[map.size()]);
}
XSQLBluePrintNode other = (XSQLBluePrintNode) obj;
if (odlNode != null) {
return getBluePrintNodeName().equals(other.getBluePrintNodeName());
- } else if (this.odlTableName == null && other.odlTableName != null)
+ } else if (this.odlTableName == null && other.odlTableName != null) {
return false;
- if (this.odlTableName != null && other.odlTableName == null)
+ }
+ if (this.odlTableName != null && other.odlTableName == null) {
return false;
- else
+ }
+ else {
return this.odlTableName.equals(other.odlTableName);
+ }
}
@Override
}
private void init() throws Exception {
- if (addr.startsWith("http://"))
+ if (addr.startsWith("http://")) {
addr = addr.substring(7);
+ }
System.err.print("Address is:" + addr);
socket = new Socket(addr, 40004);
try {
}
public JDBCResultSet addSubQuery(String _sql,String logicalName) {
- if(subQueries == null)
+ if (subQueries == null) {
subQueries = new HashMap<String,JDBCResultSet>();
+ }
JDBCResultSet rs = new JDBCResultSet(_sql);
this.subQueries.put(logicalName,rs);
return rs;
}
public Map<String,JDBCResultSet> getSubQueries() {
- if(this.subQueries==null)
+ if (this.subQueries==null) {
this.subQueries = new HashMap<>();
+ }
return this.subQueries;
}
for (Object child : children) {
String odlNodeName = XSQLODLUtils.getNodeIdentiofier(child);
- if (odlNodeName == null)
+ if (odlNodeName == null) {
continue;
+ }
XSQLBluePrintNode eNodes[] = bluePrint
.getBluePrintNodeByODLTableName(odlNodeName);
- if (eNodes == null)
+ if (eNodes == null) {
continue;
+ }
boolean match = false;
for (XSQLBluePrintNode enode : eNodes) {
}
}
- if (!match)
+ if (!match) {
continue;
+ }
if (child.getClass().getName().endsWith("ImmutableContainerNode")) {
result.add(child);
for (XSQLBluePrintNode eNode : eNodes) {
bpn = this.tablesInQueryMap.get(eNode
.getBluePrintNodeName());
- if (bpn != null)
+ if (bpn != null) {
break;
+ }
}
boolean isObjectInCriteria = true;
if (bpn != null) {
if (isObjectInCriteria) {
if (root) {
- if (!rec.data.isEmpty())
+ if (!rec.data.isEmpty()) {
addRecord(rec.data);
+ }
} else {
result.add(rec);
}
int braketCount = 0;
int endSubQuery = startSubQuery;
do {
- if (sql.charAt(endSubQuery) == '(')
+ if (sql.charAt(endSubQuery) == '(') {
braketCount++;
- else if (sql.charAt(endSubQuery) == ')')
+ }
+ else if (sql.charAt(endSubQuery) == ')') {
braketCount--;
+ }
endSubQuery++;
} while (braketCount > 0 || endSubQuery == sql.length());
String subQuerySQL = sql.substring(startSubQuery + 1,endSubQuery - 1);
whereTo = order;
}
- if(whereTo==-1)
+ if(whereTo==-1) {
whereTo=lowSQL.length();
+ }
String whereStatement = rs.getSQL().substring(where + 5, whereTo)
.trim();
LOG.warn("Store Tx: {} Data Precondition failed for {}.", transaction.getIdentifier(),
e.getPath(), e);
transaction.warnDebugContext(LOG);
+
+ // For debugging purposes, allow dumping of the modification. Coupled with the above
+ // precondition log, it should allow us to understand what went on.
+ LOG.trace("Store Tx: {} modifications: {} tree: {}", modification, dataTree);
+
return Futures.immediateFailedFuture(new TransactionCommitFailedException("Data did not pass validation.", e));
} catch (Exception e) {
LOG.warn("Unexpected failure in validation phase", e);
@Override
public boolean equals(final Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
final RemoteYangSchema that = (RemoteYangSchema) o;
- if (!qname.equals(that.qname)) return false;
+ if (!qname.equals(that.qname)) {
+ return false;
+ }
return true;
}
final ReadWriteTransaction transaction = dataService.newReadWriteTransaction();
logger.trace("{}: Update device state transaction {} merging operational data started.", id, transaction.getIdentifier());
- transaction.merge(LogicalDatastoreType.OPERATIONAL, id.getBindingPath(), data);
+ transaction.put(LogicalDatastoreType.OPERATIONAL, id.getBindingPath(), data);
logger.trace("{}: Update device state transaction {} merging operational data ended.", id, transaction.getIdentifier());
commitTransaction(transaction, "update");
final Node nodeWithId = getNodeWithId(id);
logger.trace("{}: Init device state transaction {} putting if absent operational data started.", id, transaction.getIdentifier());
- transaction.merge(LogicalDatastoreType.OPERATIONAL, path, nodeWithId);
+ transaction.put(LogicalDatastoreType.OPERATIONAL, path, nodeWithId);
logger.trace("{}: Init device state transaction {} putting operational data ended.", id, transaction.getIdentifier());
logger.trace("{}: Init device state transaction {} putting if absent config data started.", id, transaction.getIdentifier());
- transaction.merge(LogicalDatastoreType.CONFIGURATION, path, nodeWithId);
+ transaction.put(LogicalDatastoreType.CONFIGURATION, path, nodeWithId);
logger.trace("{}: Init device state transaction {} putting config data ended.", id, transaction.getIdentifier());
commitTransaction(transaction, "init");
@Override
public boolean equals(final Object o) {
- if (this == o) return true;
- if (!(o instanceof RemoteDeviceId)) return false;
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof RemoteDeviceId)) {
+ return false;
+ }
final RemoteDeviceId that = (RemoteDeviceId) o;
- if (!name.equals(that.name)) return false;
- if (!bindingPath.equals(that.bindingPath)) return false;
+ if (!name.equals(that.name)) {
+ return false;
+ }
+ if (!bindingPath.equals(that.bindingPath)) {
+ return false;
+ }
return true;
}
import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.ERROR_TAG_QNAME;
import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.ERROR_TYPE_QNAME;
import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.NAMESPACE;
-
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
private final static Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
+ private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
@Context
private HttpHeaders headers;
private Transformer createTransformer() throws TransformerFactoryConfigurationError,
TransformerConfigurationException {
- TransformerFactory tf = TransformerFactory.newInstance();
- Transformer transformer = tf.newTransformer();
+ Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-parent</artifactId>
+ <version>1.2.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>sal-rest-docgen-maven</artifactId>
+ <packaging>jar</packaging>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-rest-docgen</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-maven-plugin-spi</artifactId>
+ </dependency>
+ </dependencies>
+</project>
* 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;
+package org.opendaylight.controller.sal.rest.doc.maven;
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;
+import javax.ws.rs.core.UriInfo;
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
+import org.opendaylight.controller.sal.rest.doc.impl.ApiDocGenerator;
+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.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* This class gathers all yang defined {@link Module}s and generates Swagger compliant documentation.
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 static final 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");
/**
*
* @throws IOException
*/
@Override
- public Collection<File> generateSources(SchemaContext context, File outputDir, Set<Module> yangModules) throws IOException {
+ public Collection<File> generateSources(final SchemaContext context, final File outputDir, final 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;
}
- else outputBaseDir = outputDir;
outputBaseDir.mkdirs();
// Create Resources directory
}
@Override
- protected String generatePath(UriInfo uriInfo, String name, String revision) {
+ protected String generatePath(final UriInfo uriInfo, final String name, final String revision) {
if (uriInfo == null) {
return name + "(" + revision + ")";
}
}
@Override
- protected String createBasePathFromUriInfo(UriInfo uriInfo) {
+ protected String createBasePathFromUriInfo(final UriInfo uriInfo) {
if (uriInfo == null) {
return RESTCONF_CONTEXT_ROOT;
}
}
@Override
- public void setLog(Log log) {
+ public void setLog(final Log log) {
}
@Override
- public void setAdditionalConfig(Map<String, String> additionalConfig) {
+ public void setAdditionalConfig(final Map<String, String> additionalConfig) {
this.additionalConfig = additionalConfig;
}
@Override
- public void setResourceBaseDir(File resourceBaseDir) {
+ public void setResourceBaseDir(final File resourceBaseDir) {
this.resourceBaseDir = resourceBaseDir;
}
@Override
- public void setMavenProject(MavenProject mavenProject) {
+ public void setMavenProject(final MavenProject mavenProject) {
this.mavenProject = mavenProject;
this.projectBaseDir = mavenProject.getBasedir();
}
<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>
@Override
public void stop(BundleContext context) throws Exception {
- if (brokerServiceTracker != null)
+ if (brokerServiceTracker != null) {
brokerServiceTracker.close();
+ }
- if (session != null)
+ if (session != null) {
session.close();
+ }
synchronized (toClose) {
for (AutoCloseable close : toClose) {
@Override
public void modifiedService(ServiceReference<Broker> reference, Broker service) {
- if (session != null)
+ if (session != null) {
session.close();
+ }
Broker broker = bundleContext.getService(reference);
session = broker.registerProvider(this, bundleContext);
if (statsFlow == storedFlow) {
return true;
}
- if (storedFlow == null && statsFlow != null) return false;
- if (statsFlow == null && storedFlow != null) return false;
+ if (storedFlow == null && statsFlow != null) {
+ return false;
+ }
+ if (statsFlow == null && storedFlow != null) {
+ return false;
+ }
if (storedFlow.getEthernetMatch() == null) {
if (statsFlow.getEthernetMatch() != null) {
return false;
public synchronized ObjectName getOrCreateTransaction() {
Optional<ObjectName> ta = getTransaction();
- if (ta.isPresent())
+ if (ta.isPresent()) {
return ta.get();
+ }
transaction = configRegistryClient.beginConfig();
allOpenedTransactions.add(transaction);
return transaction;
@Parameterized.Parameters(name = "{index}: parsed({0}) contains moduleName:{1} and instanceName:{2}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
- // With namespaces
- { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']",
- new HashMap<>(ImmutableMap.of("listener-state", "127.0.0.1"))},
- { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']",
- null},
+ // With namespaces
+ { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']",
+ new HashMap<>(ImmutableMap.of("listener-state", "127.0.0.1"))},
+ { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']",
+ null},
- // Without namespaces
- { "/modules/module[name=instanceName][type=moduleType]", null},
- { "/modules/module[type=moduleType][name='instanceName']", null},
- { "/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null},
- { "/modules/module[type=moduleType and name=instanceName]", null},
- { "/modules/module[name=\"instanceName\" and type=moduleType]", null},
- { "/modules/module[type=\"moduleType\" and name=instanceName]", null},
- { "/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null},
+ // Without namespaces
+ { "/modules/module[name=instanceName][type=moduleType]", null},
+ { "/modules/module[type=moduleType][name='instanceName']", null},
+ { "/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null},
+ { "/modules/module[type=moduleType and name=instanceName]", null},
+ { "/modules/module[name=\"instanceName\" and type=moduleType]", null},
+ { "/modules/module[type=\"moduleType\" and name=instanceName]", null},
+ { "/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null},
- // With inner beans
- { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]", Collections.singletonMap("inner", "b")},
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=b]", Collections.singletonMap("inner", "b")},
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']", Collections.singletonMap("inner", "b")},
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]", Collections.singletonMap("inner", "b")},
+ // With inner beans
+ { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]", Collections.singletonMap("inner", "b")},
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=b]", Collections.singletonMap("inner", "b")},
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']", Collections.singletonMap("inner", "b")},
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]", Collections.singletonMap("inner", "b")},
- { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]",
- new HashMap<>(ImmutableMap.of("inner", "a", "inner2", "b"))
- },
+ { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]",
+ new HashMap<>(ImmutableMap.of("inner", "a", "inner2", "b"))
+ },
});
}
import java.util.Date;
import java.util.Map;
import java.util.Set;
+import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
-import org.hamcrest.CoreMatchers;
import org.opendaylight.controller.config.api.LookupRegistry;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.yangtools.yang.common.QName;
@Override
public void handleNotification(final Notification notification, final Object handback) {
- if (!(notification instanceof NetconfJMXNotification))
+ if (!(notification instanceof NetconfJMXNotification)) {
return;
+ }
// Socket should not be closed at this point
// Activator unregisters this as JMX listener before close is called
synchronized (autoCloseables) {
autoCloseables.add(jmxNotificationHandler);
}
- /*
- * We have completed initial configuration. At this point
- * it is good idea to perform garbage collection to prune
- * any garbage we have accumulated during startup.
- */
- LOG.debug("Running post-initialization garbage collection...");
- System.gc();
- LOG.debug("Post-initialization garbage collection completed.");
- LOG.debug("ConfigPusher has pushed configs {}, gc completed", configs);
- }
- catch (NetconfDocumentedException e) {
+
+ LOG.debug("ConfigPusher has pushed configs {}", configs);
+ } catch (NetconfDocumentedException e) {
LOG.error("Error pushing configs {}",configs);
throw new IllegalStateException(e);
}
private final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot;
private final CapabilityProvider capabilityProvider;
- public NetconfServerSessionListenerFactory(DefaultCommitNotificationProducer commitNotifier,
- SessionMonitoringService monitor,
- NetconfOperationServiceSnapshot netconfOperationServiceSnapshot,
- CapabilityProvider capabilityProvider) {
+ public NetconfServerSessionListenerFactory(final DefaultCommitNotificationProducer commitNotifier,
+ final SessionMonitoringService monitor,
+ final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot,
+ final CapabilityProvider capabilityProvider) {
this.commitNotifier = commitNotifier;
this.monitor = monitor;
@Override
public NetconfServerSessionListener getSessionListener() {
- NetconfOperationRouter operationRouter = NetconfOperationRouterImpl.createOperationRouter(
- netconfOperationServiceSnapshot, capabilityProvider, commitNotifier);
+ NetconfOperationRouter operationRouter = new NetconfOperationRouterImpl(netconfOperationServiceSnapshot, capabilityProvider, commitNotifier);
return new NetconfServerSessionListener(operationRouter, monitor, netconfOperationServiceSnapshot);
}
}
AbstractNetconfSessionNegotiator<NetconfServerSessionPreferences, NetconfServerSession, NetconfServerSessionListener> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiator.class);
-
+
private static final String UNKNOWN = "unknown";
protected NetconfServerSessionNegotiator(
package org.opendaylight.controller.netconf.impl.osgi;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
+import java.util.Collection;
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 LOG = LoggerFactory.getLogger(NetconfOperationRouterImpl.class);
-
private final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot;
- private Set<NetconfOperation> allNetconfOperations;
-
- private NetconfOperationRouterImpl(final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot) {
- this.netconfOperationServiceSnapshot = netconfOperationServiceSnapshot;
- }
-
- private synchronized void initNetconfOperations(final Set<NetconfOperation> allOperations) {
- allNetconfOperations = allOperations;
- }
+ private final Collection<NetconfOperation> allNetconfOperations;
- /**
- * Factory method to produce instance of NetconfOperationRouter
- */
- public static NetconfOperationRouter createOperationRouter(final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot,
- final CapabilityProvider capabilityProvider, final DefaultCommitNotificationProducer commitNotifier) {
- NetconfOperationRouterImpl router = new NetconfOperationRouterImpl(netconfOperationServiceSnapshot);
-
- Preconditions.checkNotNull(netconfOperationServiceSnapshot);
- Preconditions.checkNotNull(capabilityProvider);
+ public NetconfOperationRouterImpl(final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot, final CapabilityProvider capabilityProvider,
+ final DefaultCommitNotificationProducer commitNotifier) {
+ this.netconfOperationServiceSnapshot = Preconditions.checkNotNull(netconfOperationServiceSnapshot);
final String sessionId = netconfOperationServiceSnapshot.getNetconfSessionIdForReporting();
- final Set<NetconfOperation> defaultNetconfOperations = Sets.newHashSet();
- defaultNetconfOperations.add(new DefaultGetSchema(capabilityProvider, sessionId));
- defaultNetconfOperations.add(new DefaultCloseSession(sessionId, router));
- defaultNetconfOperations.add(new DefaultStartExi(sessionId));
- defaultNetconfOperations.add(new DefaultStopExi(sessionId));
- defaultNetconfOperations.add(new DefaultCommit(commitNotifier, capabilityProvider, sessionId, router));
-
- router.initNetconfOperations(getAllNetconfOperations(defaultNetconfOperations, netconfOperationServiceSnapshot));
-
- return router;
- }
-
- private static Set<NetconfOperation> getAllNetconfOperations(final Set<NetconfOperation> defaultNetconfOperations,
- final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot) {
- Set<NetconfOperation> result = new HashSet<>();
- result.addAll(defaultNetconfOperations);
+ final Set<NetconfOperation> ops = new HashSet<>();
+ ops.add(new DefaultGetSchema(capabilityProvider, sessionId));
+ ops.add(new DefaultCloseSession(sessionId, this));
+ ops.add(new DefaultStartExi(sessionId));
+ ops.add(new DefaultStopExi(sessionId));
+ ops.add(new DefaultCommit(commitNotifier, capabilityProvider, sessionId, this));
for (NetconfOperationService netconfOperationService : netconfOperationServiceSnapshot.getServices()) {
- final Set<NetconfOperation> netOpsFromService = netconfOperationService.getNetconfOperations();
- for (NetconfOperation netconfOperation : netOpsFromService) {
- Preconditions.checkState(!result.contains(netconfOperation),
+ for (NetconfOperation netconfOperation : netconfOperationService.getNetconfOperations()) {
+ Preconditions.checkState(!ops.contains(netconfOperation),
"Netconf operation %s already present", netconfOperation);
- result.add(netconfOperation);
+ ops.add(netconfOperation);
}
}
- return Collections.unmodifiableSet(result);
+
+ allNetconfOperations = ImmutableSet.copyOf(ops);
}
@Override
- public synchronized Document onNetconfMessage(final Document message,
- final NetconfServerSession session) throws NetconfDocumentedException {
+ public Document onNetconfMessage(final Document message, final NetconfServerSession session) throws NetconfDocumentedException {
Preconditions.checkNotNull(allNetconfOperations, "Operation router was not initialized properly");
- NetconfOperationExecution netconfOperationExecution;
-
- String messageAsString = "";
+ final NetconfOperationExecution netconfOperationExecution;
try {
- messageAsString = XmlUtil.toString(message);
netconfOperationExecution = getNetconfOperationWithHighestPriority(message, session);
} catch (IllegalArgumentException | IllegalStateException e) {
+ final String messageAsString = XmlUtil.toString(message);
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();
-
- NetconfDocumentedException.ErrorTag tag;
+ final NetconfDocumentedException.ErrorTag tag;
if (e instanceof IllegalArgumentException) {
- errorInfo.put(NetconfDocumentedException.ErrorTag.operation_not_supported.toString(), e.getMessage());
tag = NetconfDocumentedException.ErrorTag.operation_not_supported;
} else {
- errorInfo.put(NetconfDocumentedException.ErrorTag.operation_failed.toString(), e.getMessage());
tag = NetconfDocumentedException.ErrorTag.operation_failed;
}
- throw new NetconfDocumentedException(errorMessage, e, NetconfDocumentedException.ErrorType.application,
- tag, NetconfDocumentedException.ErrorSeverity.error, errorInfo);
+ throw new NetconfDocumentedException(
+ String.format("Unable to handle rpc %s on session %s", messageAsString, session),
+ e, NetconfDocumentedException.ErrorType.application,
+ tag, NetconfDocumentedException.ErrorSeverity.error,
+ Collections.singletonMap(tag.toString(), e.getMessage()));
} catch (RuntimeException e) {
throw handleUnexpectedEx("Unexpected exception during netconf operation sort", e);
}
try {
- return executeOperationWithHighestPriority(message, netconfOperationExecution, messageAsString);
+ return executeOperationWithHighestPriority(message, netconfOperationExecution);
} catch (RuntimeException e) {
throw handleUnexpectedEx("Unexpected exception during netconf operation execution", e);
}
netconfOperationServiceSnapshot.close();
}
- private NetconfDocumentedException handleUnexpectedEx(final String s, final Exception e) throws NetconfDocumentedException {
- LOG.error(s, e);
-
- Map<String, String> info = Maps.newHashMap();
- info.put(NetconfDocumentedException.ErrorSeverity.error.toString(), e.toString());
+ private static NetconfDocumentedException handleUnexpectedEx(final String s, final Exception e) throws NetconfDocumentedException {
+ LOG.error("{}", s, e);
return new NetconfDocumentedException("Unexpected error",
NetconfDocumentedException.ErrorType.application,
NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error, info);
+ NetconfDocumentedException.ErrorSeverity.error,
+ Collections.singletonMap(NetconfDocumentedException.ErrorSeverity.error.toString(), e.toString()));
}
private Document executeOperationWithHighestPriority(final Document message,
- final NetconfOperationExecution netconfOperationExecution, final String messageAsString)
+ final NetconfOperationExecution netconfOperationExecution)
throws NetconfDocumentedException {
- LOG.debug("Forwarding netconf message {} to {}", messageAsString, netconfOperationExecution.netconfOperation);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Forwarding netconf message {} to {}", XmlUtil.toString(message), netconfOperationExecution.netconfOperation);
+ }
+
return netconfOperationExecution.execute(message);
}
NetconfServerSessionListener sessionListener = mock(NetconfServerSessionListener.class);
Channel channel = mock(Channel.class);
+ doReturn("mockChannel").when(channel).toString();
NetconfHelloMessageAdditionalHeader header = new NetconfHelloMessageAdditionalHeader("name", "addr", "2", "tcp", "id");
NetconfServerSession sm = new NetconfServerSession(sessionListener, channel, 10, header);
doNothing().when(sessionListener).onSessionUp(any(NetconfServerSession.class));
package org.opendaylight.controller.netconf.impl;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
import io.netty.channel.local.LocalAddress;
+import java.net.InetSocketAddress;
import org.apache.sshd.common.SshdSocketAddress;
import org.junit.Test;
-import java.net.InetSocketAddress;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
public class NetconfServerSessionNegotiatorTest {
@Test
DefaultStopExi exi = new DefaultStopExi("");
Document doc = XmlUtil.newDocument();
Channel channel = mock(Channel.class);
+ doReturn("mockChannel").when(channel).toString();
ChannelPipeline pipeline = mock(ChannelPipeline.class);
doReturn(pipeline).when(channel).pipeline();
ChannelHandler channelHandler = mock(ChannelHandler.class);
import io.netty.channel.local.LocalAddress;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
-import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Files;
public static final String USERNAME = "user";
public static final String PASSWORD = "pwd";
- private File sshKeyPair;
private SshProxyServer sshProxyServer;
private ExecutorService nioExec;
@Before
public void setUp() throws Exception {
- sshKeyPair = Files.createTempFile("sshKeyPair", ".pem").toFile();
- sshKeyPair.deleteOnExit();
nioExec = Executors.newFixedThreadPool(1);
clientGroup = new NioEventLoopGroup();
minaTimerEx = Executors.newScheduledThreadPool(1);
.setBindingAddress(TLS_ADDRESS)
.setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress())
.setAuthenticator(new PasswordAuthenticator() {
- @Override
- public boolean authenticate(final String username, final String password, final ServerSession session) {
- return true;
- }
- })
- .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString()))
+ @Override
+ public boolean authenticate(final String username, final String password, final ServerSession session) {
+ return true;
+ }
+ }
+ )
+ .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
.setIdleTimeout(Integer.MAX_VALUE)
.createSshProxyServerConfiguration());
}
ServiceReference<?>[] refs = new ServiceReference[2];
doReturn(Arrays.asList(refs)).when(context).getServiceReferences(any(Class.class), anyString());
doReturn(refs).when(context).getServiceReferences(anyString(), anyString());
+ doNothing().when(context).removeServiceListener(any(ServiceListener.class));
}
@Test
public String toString() {
final StringBuffer sb = new StringBuffer(getClass().getSimpleName() + "{");
sb.append("sessionId=").append(sessionId);
+ sb.append(", channel=").append(channel);
sb.append('}');
return sb.toString();
}
package org.opendaylight.controller.netconf.nettyutil.handler;
+import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
-import org.opendaylight.controller.netconf.util.messages.NetconfMessageHeader;
public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
public static final int DEFAULT_CHUNK_SIZE = 8192;
this(DEFAULT_CHUNK_SIZE);
}
- public ChunkedFramingMechanismEncoder(int chunkSize) {
- Preconditions.checkArgument(chunkSize > MIN_CHUNK_SIZE);
- Preconditions.checkArgument(chunkSize < MAX_CHUNK_SIZE);
+ public ChunkedFramingMechanismEncoder(final int chunkSize) {
+ Preconditions.checkArgument(chunkSize >= MIN_CHUNK_SIZE && chunkSize <= MAX_CHUNK_SIZE, "Unsupported chunk size %s", chunkSize);
this.chunkSize = chunkSize;
}
}
@Override
- protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
- while (msg.readableBytes() > chunkSize) {
- ByteBuf chunk = Unpooled.buffer(chunkSize);
- chunk.writeBytes(createChunkHeader(chunkSize));
- chunk.writeBytes(msg.readBytes(chunkSize));
- ctx.write(chunk);
- }
- out.writeBytes(createChunkHeader(msg.readableBytes()));
- out.writeBytes(msg.readBytes(msg.readableBytes()));
- out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
- }
+ protected void encode(final ChannelHandlerContext ctx, final ByteBuf msg, final ByteBuf out) {
+ do {
+ final int xfer = Math.min(chunkSize, msg.readableBytes());
+
+ out.writeBytes(NetconfMessageConstants.START_OF_CHUNK);
+ out.writeBytes(String.valueOf(xfer).getBytes(Charsets.US_ASCII));
+ out.writeByte('\n');
- private ByteBuf createChunkHeader(int chunkSize) {
- return Unpooled.wrappedBuffer(NetconfMessageHeader.toBytes(chunkSize));
+ out.writeBytes(msg, xfer);
+ } while (msg.isReadable());
+
+ out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
}
}
import java.io.InputStream;
import java.util.List;
import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder {
private static final Logger LOG = LoggerFactory.getLogger(NetconfEXIToMessageDecoder.class);
+ private static final SAXTransformerFactory FACTORY = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
private final NetconfEXICodec codec;
}
final EXIReader r = codec.getReader();
-
- final SAXTransformerFactory transformerFactory
- = (SAXTransformerFactory) TransformerFactory.newInstance();
- final TransformerHandler handler = transformerFactory.newTransformerHandler();
+ final TransformerHandler handler = FACTORY.newTransformerHandler();
r.setContentHandler(handler);
final DOMResult domResult = new DOMResult();
import io.netty.handler.codec.MessageToByteEncoder;
import java.io.IOException;
import java.io.OutputStream;
-import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
-import javax.xml.transform.sax.SAXTransformerFactory;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.openexi.proc.common.EXIOptionsException;
import org.openexi.sax.Transmogrifier;
import org.slf4j.LoggerFactory;
public final class NetconfMessageToEXIEncoder extends MessageToByteEncoder<NetconfMessage> {
-
private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToEXIEncoder.class);
-
- private static final SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
private final NetconfEXICodec codec;
public NetconfMessageToEXIEncoder(final NetconfEXICodec codec) {
final Transmogrifier transmogrifier = codec.getTransmogrifier();
transmogrifier.setOutputStream(os);
- final Transformer transformer = saxTransformerFactory.newTransformer();
- transformer.transform(new DOMSource(msg.getDocument()), new SAXResult(transmogrifier.getSAXTransmogrifier()));
+ ThreadLocalTransformers.getDefaultTransformer().transform(new DOMSource(msg.getDocument()), new SAXResult(transmogrifier.getSAXTransmogrifier()));
}
}
}
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.opendaylight.controller.netconf.api.NetconfMessage;
public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMessage> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToXMLEncoder.class);
- private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
private final Optional<String> clientId;
this(Optional.<String>absent());
}
- public NetconfMessageToXMLEncoder(Optional<String> clientId) {
+ public NetconfMessageToXMLEncoder(final Optional<String> clientId) {
this.clientId = clientId;
}
@Override
@VisibleForTesting
- public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws IOException, TransformerException {
+ public void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws IOException, TransformerException {
LOG.trace("Sent to encode : {}", msg);
if (clientId.isPresent()) {
}
try (OutputStream os = new ByteBufOutputStream(out)) {
- Transformer transformer = FACTORY.newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
-
// Wrap OutputStreamWriter with BufferedWriter as suggested in javadoc for OutputStreamWriter
StreamResult result = new StreamResult(new BufferedWriter(new OutputStreamWriter(os)));
DOMSource source = new DOMSource(msg.getDocument());
- transformer.transform(source, result);
+ ThreadLocalTransformers.getPrettyTransformer().transform(source, result);
}
}
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.nettyutil.handler;
+
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+
+/**
+ * Utility class for cached thread-local transformers. This class exists mostly for use by handlers.
+ */
+final class ThreadLocalTransformers {
+ private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
+
+ private static final ThreadLocal<Transformer> DEFAULT_TRANSFORMER = new ThreadLocal<Transformer>() {
+ @Override
+ protected Transformer initialValue() {
+ try {
+ return FACTORY.newTransformer();
+ } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
+ throw new IllegalStateException("Unexpected error while instantiating a Transformer", e);
+ }
+ };
+
+ @Override
+ public void set(final Transformer value) {
+ throw new UnsupportedOperationException();
+ };
+ };
+
+ private static final ThreadLocal<Transformer> PRETTY_TRANSFORMER = new ThreadLocal<Transformer>() {
+ @Override
+ protected Transformer initialValue() {
+ final Transformer ret;
+
+ try {
+ ret = FACTORY.newTransformer();
+ } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
+ throw new IllegalStateException("Unexpected error while instantiating a Transformer", e);
+ }
+
+ ret.setOutputProperty(OutputKeys.INDENT, "yes");
+ ret.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ return ret;
+ };
+
+ @Override
+ public void set(final Transformer value) {
+ throw new UnsupportedOperationException();
+ };
+ };
+
+ private ThreadLocalTransformers() {
+ throw new UnsupportedOperationException("Utility class");
+ }
+
+ /**
+ * Get the transformer with default configuration.
+ *
+ * @return A transformer with default configuration based on the default implementation.
+ */
+ public static Transformer getDefaultTransformer() {
+ return DEFAULT_TRANSFORMER.get();
+ }
+
+ /**
+ * Get the transformer with default configuration, but with automatic indentation
+ * and the XML declaration removed.
+ *
+ * @return A transformer with human-friendly configuration.
+ */
+ public static Transformer getPrettyTransformer() {
+ return PRETTY_TRANSFORMER.get();
+ }
+}
@Override
public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
+ LOG.debug("XXX session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
this.connectPromise = promise;
startSsh(ctx, remoteAddress);
}
@Override
public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
- // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
- // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
- // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
- try {
- super.disconnect(ctx, ctx.newPromise());
- } catch (final Exception e) {
- LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
- }
+ LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise);
- if(sshReadAsyncListener != null) {
- sshReadAsyncListener.close();
+ // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
+ if(connectPromise.isSuccess()) {
+ ctx.fireChannelInactive();
}
if(sshWriteAsyncHandler != null) {
sshWriteAsyncHandler.close();
}
+ if(sshReadAsyncListener != null) {
+ sshReadAsyncListener.close();
+ }
+
if(session!= null && !session.isClosed() && !session.isClosing()) {
session.close(false).addListener(new SshFutureListener<CloseFuture>() {
@Override
});
}
- // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
- if(connectPromise.isSuccess()) {
- ctx.fireChannelInactive();
+ // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
+ // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
+ // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
+ try {
+ // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
+ super.disconnect(ctx, ctx.newPromise());
+ } catch (final Exception e) {
+ LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
}
channel = null;
-
promise.setSuccess();
LOG.debug("SSH session closed on channel: {}", ctx.channel());
}
doReturn(mock(ChannelFuture.class)).when(channel).writeAndFlush(any(NetconfMessage.class));
doReturn(pipeline).when(channel).pipeline();
+ doReturn("mockChannel").when(channel).toString();
doReturn(mock(ChannelFuture.class)).when(channel).close();
doReturn(null).when(pipeline).replace(anyString(), anyString(), any(ChannelHandler.class));
package org.opendaylight.controller.netconf.nettyutil.handler;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.doAnswer;
-import com.google.common.collect.Lists;
+import static org.junit.Assert.assertTrue;
+import com.google.common.base.Charsets;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
-import java.util.List;
+import java.nio.ByteBuffer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
public class ChunkedFramingMechanismEncoderTest {
@Test
public void testEncode() throws Exception {
- final List<ByteBuf> chunks = Lists.newArrayList();
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- chunks.add((ByteBuf) invocation.getArguments()[0]);
- return null;
- }
- }).when(ctx).write(anyObject());
-
final ChunkedFramingMechanismEncoder encoder = new ChunkedFramingMechanismEncoder(chunkSize);
final int lastChunkSize = 20;
final ByteBuf src = Unpooled.wrappedBuffer(getByteArray(chunkSize * 4 + lastChunkSize));
final ByteBuf destination = Unpooled.buffer();
encoder.encode(ctx, src, destination);
- assertEquals(4, chunks.size());
- final int framingSize = "#256\n".getBytes().length + 1/* new line at end */;
+ assertEquals(1077, destination.readableBytes());
- for (final ByteBuf chunk : chunks) {
- assertEquals(chunkSize + framingSize, chunk.readableBytes());
- }
+ byte[] buf = new byte[destination.readableBytes()];
+ destination.readBytes(buf);
+ String s = Charsets.US_ASCII.decode(ByteBuffer.wrap(buf)).toString();
- final int lastFramingSize = "#20\n".length() + NetconfMessageConstants.END_OF_CHUNK.length + 1/* new line at end */;
- assertEquals(lastChunkSize + lastFramingSize, destination.readableBytes());
+ assertTrue(s.startsWith("\n#256\na"));
+ assertTrue(s.endsWith("\n#20\naaaaaaaaaaaaaaaaaaaa\n##\n"));
}
private byte[] getByteArray(final int size) {
public static final int MAX_HEADER_LENGTH = 13;
+ public static final byte[] START_OF_CHUNK = "\n#".getBytes(Charsets.UTF_8);
public static final byte[] END_OF_CHUNK = "\n##\n".getBytes(Charsets.UTF_8);
}
package org.opendaylight.controller.netconf.util.xml;
+import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
public final class XMLNetconfUtil {
+ private static final XPathFactory FACTORY = XPathFactory.newInstance();
+ private static final NamespaceContext NS_CONTEXT = new HardcodedNamespaceResolver("netconf",
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- private XMLNetconfUtil() {}
+ private XMLNetconfUtil() {
+ throw new UnsupportedOperationException("Utility class");
+ }
- public static XPathExpression compileXPath(String xPath) {
- final XPathFactory xPathfactory = XPathFactory.newInstance();
- final XPath xpath = xPathfactory.newXPath();
- xpath.setNamespaceContext(new HardcodedNamespaceResolver("netconf",
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ public static XPathExpression compileXPath(final String xPath) {
+ final XPath xpath = FACTORY.newXPath();
+ xpath.setNamespaceContext(NS_CONTEXT);
try {
return xpath.compile(xPath);
} catch (final XPathExpressionException e) {
public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
- private static final DocumentBuilderFactory BUILDERFACTORY;
+ private static final DocumentBuilderFactory BUILDER_FACTORY;
+ private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
+ private static final SchemaFactory SCHEMA_FACTORY = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
static {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setCoalescing(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setIgnoringComments(true);
- BUILDERFACTORY = factory;
+ BUILDER_FACTORY = factory;
}
- private XmlUtil() {}
+ private XmlUtil() {
+ throw new UnsupportedOperationException("Utility class");
+ }
- public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
+ public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
Document doc = readXmlToDocument(xmlContent);
return doc.getDocumentElement();
}
- public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
+ public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
Document doc = readXmlToDocument(xmlContent);
return doc.getDocumentElement();
}
- public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
+ public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
}
// TODO improve exceptions throwing
// along with XmlElement
- public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
+ public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
DocumentBuilder dBuilder;
try {
- dBuilder = BUILDERFACTORY.newDocumentBuilder();
+ dBuilder = BUILDER_FACTORY.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new IllegalStateException("Failed to parse XML document", e);
}
return doc;
}
- public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
+ public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
}
public static Document newDocument() {
try {
- DocumentBuilder builder = BUILDERFACTORY.newDocumentBuilder();
+ DocumentBuilder builder = BUILDER_FACTORY.newDocumentBuilder();
return builder.newDocument();
} catch (ParserConfigurationException e) {
throw new IllegalStateException("Failed to create document", e);
}
}
- public static Element createElement(final Document document, String qName, Optional<String> namespaceURI) {
+ public static Element createElement(final Document document, final String qName, final Optional<String> namespaceURI) {
if(namespaceURI.isPresent()) {
final Element element = document.createElementNS(namespaceURI.get(), qName);
String name = XMLNS_ATTRIBUTE_KEY;
return document.createElement(qName);
}
- public static Element createTextElement(Document document, String qName, String content, Optional<String> namespaceURI) {
+ public static Element createTextElement(final Document document, final String qName, final String content, final Optional<String> namespaceURI) {
Element typeElement = createElement(document, qName, namespaceURI);
typeElement.appendChild(document.createTextNode(content));
return typeElement;
}
- public static Element createTextElementWithNamespacedContent(Document document, String qName, String prefix,
- String namespace, String contentWithoutPrefix) {
+ public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
+ final String namespace, final String contentWithoutPrefix) {
return createTextElementWithNamespacedContent(document, qName, prefix, namespace, contentWithoutPrefix, Optional.<String>absent());
}
- public static Element createTextElementWithNamespacedContent(Document document, String qName, String prefix,
- String namespace, String contentWithoutPrefix, Optional<String> namespaceURI) {
+ public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
+ final String namespace, final String contentWithoutPrefix, final Optional<String> namespaceURI) {
String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
Element element = createTextElement(document, qName, content, namespaceURI);
return element;
}
- public static String createPrefixedValue(String prefix, String value) {
+ public static String createPrefixedValue(final String prefix, final String value) {
return prefix + ":" + value;
}
- public static String toString(Document document) {
+ public static String toString(final Document document) {
return toString(document.getDocumentElement());
}
- public static String toString(Element xml) {
+ public static String toString(final Element xml) {
return toString(xml, false);
}
- public static String toString(XmlElement xmlElement) {
+ public static String toString(final XmlElement xmlElement) {
return toString(xmlElement.getDomElement(), false);
}
- public static String toString(Element xml, boolean addXmlDeclaration) {
+ public static String toString(final Element xml, final boolean addXmlDeclaration) {
try {
- Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
}
}
- public static String toString(Document doc, boolean addXmlDeclaration) {
+ public static String toString(final Document doc, final boolean addXmlDeclaration) {
return toString(doc.getDocumentElement(), addXmlDeclaration);
}
- public static Schema loadSchema(InputStream... fromStreams) {
+ public static Schema loadSchema(final InputStream... fromStreams) {
Source[] sources = new Source[fromStreams.length];
int i = 0;
for (InputStream stream : fromStreams) {
sources[i++] = new StreamSource(stream);
}
- final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
- return schemaFactory.newSchema(sources);
+ return SCHEMA_FACTORY.newSchema(sources);
} catch (SAXException e) {
throw new IllegalStateException("Failed to instantiate XML schema", e);
}
}
- public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
+ public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
try {
return expr.evaluate(rootNode, returnType);
} catch (XPathExpressionException e) {
}
}
- public static Document createDocumentCopy(Document original) {
+ public static Document createDocumentCopy(final Document original) {
final Document copiedDocument = newDocument();
final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
copiedDocument.appendChild(copiedRoot);
*/
package org.opendaylight.controller.netconf.util;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import static org.hamcrest.CoreMatchers.containsString;
import org.junit.Test;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<failsOnError>false</failsOnError>
- <failOnViolation>false</failOnViolation>
+ <failOnViolation>true</failOnViolation>
<configLocation>checkstyle-logging.xml</configLocation>
<consoleOutput>true</consoleOutput>
<includeTestSourceDirectory>true</includeTestSourceDirectory>