</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>
+ <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);
public void setLastSeenTimestamp(Date lastSeenTimestamp) {
if (activeSince == null
|| (activeSince.getTime() + ACTIVITY_TIMEOUT) < lastSeenTimestamp
- .getTime())
+ .getTime()) {
this.activeSince = lastSeenTimestamp;
+ }
this.lastSeenTimestamp = lastSeenTimestamp;
}
@Override
public int hashCode() {
- if (hashCode != 0)
+ if (hashCode != 0) {
return hashCode;
+ }
final int prime = 31;
hashCode = 1;
hashCode = prime * hashCode
@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;
+ }
Entity other = (Entity) obj;
if (ipv4Address == null) {
- if (other.ipv4Address != null)
+ if (other.ipv4Address != null) {
return false;
- } else if (!ipv4Address.equals(other.ipv4Address))
+ }
+ } else if (!ipv4Address.equals(other.ipv4Address)) {
return false;
- if (macAddress != other.macAddress)
+ }
+ if (macAddress != other.macAddress) {
return false;
+ }
if (port == null) {
- if (other.port != null)
+ if (other.port != null) {
return false;
- } else if (!port.equals(other.port))
+ }
+ } else if (!port.equals(other.port)) {
return false;
+ }
if (vlan == null) {
- if (other.vlan != null)
+ if (other.vlan != null) {
return false;
- } else if (!vlan.equals(other.vlan))
+ }
+ } else if (!vlan.equals(other.vlan)) {
return false;
+ }
return true;
}
Comparable switchId = (Comparable) port.getNode().getID();
Comparable oswitchId = (Comparable) o.port.getNode().getID();
r = switchId.compareTo(oswitchId);
- if (r != 0)
+ if (r != 0) {
return r;
+ }
Comparable portId = (Comparable) port.getID();
Comparable oportId = (Comparable) o.port.getID();
@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;
+ }
SwitchPort other = (SwitchPort) obj;
- if (errorStatus != other.errorStatus)
+ if (errorStatus != other.errorStatus) {
return false;
+ }
if (port == null) {
- if (other.port != null)
+ if (other.port != null) {
return false;
- } else if (!port.equals(other.port))
+ }
+ } else if (!port.equals(other.port)) {
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;
+ }
HostNodeConnector other = (HostNodeConnector) obj;
if (nodeConnector == null) {
- if (other.nodeConnector != null)
+ if (other.nodeConnector != null) {
return false;
- } else if (!nodeConnector.equals(other.nodeConnector))
+ }
+ } else if (!nodeConnector.equals(other.nodeConnector)) {
return false;
- if (staticHost != other.staticHost)
+ }
+ if (staticHost != other.staticHost) {
return false;
- if (vlan != other.vlan)
+ }
+ if (vlan != other.vlan) {
return false;
+ }
return true;
}
EthernetAddress e = (EthernetAddress) getDataLayerAddress();
macaddr = e.getValue();
}
- if (macaddr == null)
+ if (macaddr == null) {
return false;
+ }
return !Arrays.equals(emptyArray, macaddr);
}
@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();
Object item = it.next();
for (TypeInfo child : _types.values()) {
Object val = child.retrieve(item, query, index);
- if (val != null) objects.add(val);
+ if (val != null) {
+ objects.add(val);
+ }
}
}
return objects;
@Override
public synchronized void explore() {
- if (_explored) return;
+ if (_explored) {
+ return;
+ }
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("exploring iteratable type: {} gtype: {}", _class,
_accessor.getGenericType());
@Override
public <T> Query<T> createQuery(String queryString, Class<T> type) throws QueryException {
- if (queryString == null || queryString.trim().length() == 0) return null;
+ if (queryString == null || queryString.trim().length() == 0) {
+ return null;
+ }
try {
- if (LOGGER.isDebugEnabled()) LOGGER.debug("Processing query: {}", queryString);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Processing query: {}", queryString);
+ }
// FiqlParser is a parser generated by javacc
Expression expression = FiqlParser.parse(queryString);
- if (LOGGER.isDebugEnabled()) LOGGER.debug("Query expression: {}", expression);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Query expression: {}", expression);
+ }
// create Query and return;
return new QueryImpl<T>(type, expression);
} catch (Exception ex) {
- if (LOGGER.isDebugEnabled()) LOGGER.error("Query processing failed = {}",
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.error("Query processing failed = {}",
queryString, ex);
+ }
throw new QueryException("Unable to parse query.", ex);
}
}
}
private boolean compare(Object valueToMatch, Object actualValue, OP operator) {
- if (valueToMatch == null || actualValue == null) return false;
+ if (valueToMatch == null || actualValue == null) {
+ return false;
+ }
if (ALLOW_OBJECT_STRING_COMPARE && (valueToMatch instanceof String)
&& !(actualValue instanceof String)) {
actualValue = actualValue.toString();
}
}
private Object parse(String arg, Object value) {
- if (value == null) return null;
+ if (value == null) {
+ return null;
+ }
try {
if (value instanceof String) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("retrieve: {}/{} type:{}", index, query.length, target.getClass());
}
- if (index >= query.length) return null;
+ if (index >= query.length) {
+ return null;
+ }
explore();
if (!target.getClass().equals(_class)) {
if (_class.isAssignableFrom(target.getClass())) {
}
}
TypeInfo child = getChild(query[index]);
- if (child == null) return null;
+ if (child == null) {
+ return null;
+ }
target = child.getAccessor().getValue(target);
if (index+1 == query.length) {
// match found
* Explore the type info for children.
*/
public synchronized void explore() {
- if (_explored) return;
+ if (_explored) {
+ return;
+ }
for (Class<?> c = _class; c != null; c = c.getSuperclass()) {
- if (c.equals(Object.class)) break;
+ if (c.equals(Object.class)) {
+ break;
+ }
// Currently only fields and methods annotated with JAXB annotations are
// considered as valid for search purposes.
//check methods first
for (Method m : c.getDeclaredMethods()) {
String tn = getTypeName(m, _accessType);
if (tn != null) {
- if (LOGGER.isDebugEnabled()) LOGGER.debug(
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(
"exploring type: {} name: {} method: {}",
_class.getSimpleName(), tn, m);
+ }
_types.put(tn, createTypeInfo(tn, new Accessor(m)));
}
}
for (Field f : c.getDeclaredFields()) {
String tn = getTypeName(f, _accessType);
if (tn != null) {
- if (LOGGER.isDebugEnabled()) LOGGER.debug(
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(
"exploring type: {} name: {} field: {}",
_class.getSimpleName(), tn, f);
+ }
_types.put(tn, createTypeInfo(tn, new Accessor(f)));
}
}
PropertyDescriptor[] props = info.getPropertyDescriptors();
for (PropertyDescriptor pd : props)
{
- if (m.equals(pd.getReadMethod())) return pd.getName();
+ if (m.equals(pd.getReadMethod())) {
+ return pd.getName();
+ }
}
}
catch (IntrospectionException e)
// root is always a composite type
// FIXME assert its a JAXB type
XmlRootElement root = clz.getAnnotation(XmlRootElement.class);
- if (root == null) throw new IllegalArgumentException("Not a JAXB type: " + clz);
- if (name == null) name = getRootName(clz);
+ if (root == null) {
+ throw new IllegalArgumentException("Not a JAXB type: " + clz);
+ }
+ if (name == null) {
+ name = getRootName(clz);
+ }
return new TypeInfo(name, clz, null);
}
public static String getRootName(Class<?> cls) {
XmlRootElement root = cls.getAnnotation(XmlRootElement.class);
- if (root == null) return null;
+ if (root == null) {
+ return null;
+ }
String rootName = root.name();
if (DEFAULT_NAME.equals(rootName)) {
String clsName = cls.getSimpleName();
return null;
}
}
- if (DEFAULT_NAME.equals(name)) return dflt;
+ if (DEFAULT_NAME.equals(name)) {
+ return dflt;
+ }
return name;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("retrieve collection: {}/{}", index, query.length);
}
- if (index >= query.length) return null;
+ if (index >= query.length) {
+ return null;
+ }
explore();
TypeInfo child = getChild(query[index]);
- if (child == null) return null;
+ if (child == null) {
+ return null;
+ }
if (query.length == index+1) { // skipping this node
return target;
}else { // if list of list go to next node to get value
@Override
public synchronized void explore() {
- if (_explored) return;
+ if (_explored) {
+ return;
+ }
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("exploring wrapper type: {} gtype: {}", _class,
_accessor.getGenericType());
}
@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 static void checkCondition(boolean condition, String message,
JmxAttribute jmxAttribute) throws JmxAttributeValidationException {
- if (condition == false) {
+ if (!condition) {
throw new JmxAttributeValidationException(
jmxAttribute.getAttributeName() + " " + message,
jmxAttribute);
if (quoted == null) {
throw new IllegalArgumentException("Cannot find " + SERVICE_QNAME_KEY + " in " + objectName);
}
- if (quoted.startsWith("\"") == false || quoted.endsWith("\"") == false) {
+ if (!quoted.startsWith("\"") || !quoted.endsWith("\"")) {
throw new IllegalArgumentException("Quotes not found in " + objectName);
}
String substring = quoted.substring(1);
throw new IllegalArgumentException(
"Expected ObjectName with transaction:" + inputON);
}
- if (ON_DOMAIN.equals(inputON.getDomain()) == false) {
+ if (!ON_DOMAIN.equals(inputON.getDomain())) {
throw new IllegalArgumentException("Expected different domain: "
+ inputON);
}
Map<String, String> allProperties = getAdditionalProperties(on);
Map<String, String> result = new HashMap<>();
for (Entry<String, String> entry : allProperties.entrySet()) {
- if (blacklist.contains(entry.getKey()) == false) {
+ if (!blacklist.contains(entry.getKey())) {
result.put(entry.getKey(), entry.getValue());
}
}
* {@inheritDoc}
*/
@Override
- @SuppressWarnings("PMD.AvoidCatchingThrowable")
public synchronized CommitStatus commitConfig(ObjectName transactionControllerON)
throws ConflictingVersionException, ValidationException {
final String transactionName = ObjectNameUtil
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static java.lang.String.format;
-
/**
* Contains common code for readable/rw dynamic mbean wrappers. Routes all
* requests (getAttribute, setAttribute, invoke) into the actual instance, but
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" +
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>binding-type-provider</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-util</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
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,
final String javaNamePrefix) {
return RuntimeBeanEntry.extractClassNameToRuntimeBeanMap(packageName, dataNodeContainer, moduleLocalNameFromXPath,
- typeProviderWrapper, javaNamePrefix, currentModule).values();
+ typeProviderWrapper, javaNamePrefix, currentModule, schemaContext).values();
}
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 static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
-
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
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;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.UsesNode;
+import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
/**
* Holds information about runtime bean to be generated. There are two kinds of
* lined via children so that a tree with all beans can be created.
*/
public class RuntimeBeanEntry {
+
+ private static final Function<SchemaNode, QName> QNAME_FROM_NODE = new Function<SchemaNode, QName>() {
+ @Override
+ public QName apply(final SchemaNode input) {
+ return input.getQName();
+ }
+ };
+
+ private static final Function<UnknownSchemaNode, String> UNKNOWN_NODE_TO_STRING = new Function<UnknownSchemaNode, String>() {
+ @Override
+ public String apply(final UnknownSchemaNode input) {
+ return input.getQName().getLocalName() + input.getNodeParameter();
+ }
+ };
+
private final String packageName;
private final String yangName, javaNamePrefix;
private final boolean isRoot;
public static Map<String, RuntimeBeanEntry> extractClassNameToRuntimeBeanMap(
final String packageName, final DataNodeContainer container,
final String moduleYangName, final TypeProviderWrapper typeProviderWrapper,
- final String javaNamePrefix, final Module currentModule) {
+ final String javaNamePrefix, final Module currentModule, final SchemaContext schemaContext) {
- Map<QName, Set<RpcDefinition>> identitiesToRpcs = getIdentitiesToRpcs(currentModule);
AttributesRpcsAndRuntimeBeans attributesRpcsAndRuntimeBeans = extractSubtree(
packageName, container, typeProviderWrapper, currentModule,
- identitiesToRpcs);
+ schemaContext);
Map<String, RuntimeBeanEntry> result = new HashMap<>();
List<AttributeIfc> attributes;
return result;
}
- private static Map<QName/* of identity */, Set<RpcDefinition>> getIdentitiesToRpcs(
- final Module currentModule) {
- // currently only looks for local identities (found in currentModule)
- Map<QName, Set<RpcDefinition>> result = new HashMap<>();
- for (IdentitySchemaNode identity : currentModule.getIdentities()) {
- // add all
- result.put(identity.getQName(), new HashSet<RpcDefinition>());
- }
+ private static Multimap<QName/* of identity */, RpcDefinition> getIdentitiesToRpcs(
+ final SchemaContext schemaCtx) {
+ Multimap<QName, RpcDefinition> result = HashMultimap.create();
+ for (Module currentModule : schemaCtx.getModules()) {
- for (RpcDefinition rpc : currentModule.getRpcs()) {
- ContainerSchemaNode input = rpc.getInput();
- if (input != null) {
- for (UsesNode uses : input.getUses()) {
+ // Find all identities in current module for later identity->rpc mapping
+ Set<QName> allIdentitiesInModule = Sets.newHashSet(Collections2.transform(currentModule.getIdentities(), QNAME_FROM_NODE));
- if (uses.getGroupingPath().getPath().size() != 1) {
- continue;
- }
+ for (RpcDefinition rpc : currentModule.getRpcs()) {
+ ContainerSchemaNode input = rpc.getInput();
+ if (input != null) {
+ for (UsesNode uses : input.getUses()) {
- // check grouping path
- QName qname = uses.getGroupingPath().getPath().get(0);
- if (false == qname
- .equals(ConfigConstants.RPC_CONTEXT_REF_GROUPING_QNAME)) {
- continue;
- }
+ // Check if the rpc is config rpc by looking for input argument rpc-context-ref
+ Iterator<QName> pathFromRoot = uses.getGroupingPath().getPathFromRoot().iterator();
+ if (!pathFromRoot.hasNext() ||
+ !pathFromRoot.next().equals(ConfigConstants.RPC_CONTEXT_REF_GROUPING_QNAME)) {
+ continue;
+ }
- for (SchemaNode refinedNode : uses.getRefines().values()) {
-
- for (UnknownSchemaNode unknownSchemaNode : refinedNode
- .getUnknownSchemaNodes()) {
- if (ConfigConstants.RPC_CONTEXT_INSTANCE_EXTENSION_QNAME
- .equals(unknownSchemaNode.getNodeType())) {
- String localIdentityName = unknownSchemaNode
- .getNodeParameter();
- QName identityQName = QName.create(
- currentModule.getNamespace(),
- currentModule.getRevision(),
- localIdentityName);
- Set<RpcDefinition> rpcDefinitions = result
- .get(identityQName);
- if (rpcDefinitions == null) {
- throw new IllegalArgumentException(
- "Identity referenced by rpc not found. Identity:"
- + localIdentityName + " , rpc "
- + rpc);
+ for (SchemaNode refinedNode : uses.getRefines().values()) {
+ for (UnknownSchemaNode unknownSchemaNode : refinedNode
+ .getUnknownSchemaNodes()) {
+ if (ConfigConstants.RPC_CONTEXT_INSTANCE_EXTENSION_QNAME
+ .equals(unknownSchemaNode.getNodeType())) {
+ String localIdentityName = unknownSchemaNode
+ .getNodeParameter();
+ QName identityQName = QName.create(
+ currentModule.getNamespace(),
+ currentModule.getRevision(),
+ localIdentityName);
+ Preconditions.checkArgument(allIdentitiesInModule.contains(identityQName),
+ "Identity referenced by rpc not found. Identity: %s, rpc: %s", localIdentityName, rpc);
+ result.put(identityQName, rpc);
}
- rpcDefinitions.add(rpc);
}
}
}
private static AttributesRpcsAndRuntimeBeans extractSubtree(
final String packageName, final DataNodeContainer subtree,
final TypeProviderWrapper typeProviderWrapper, final Module currentModule,
- final Map<QName, Set<RpcDefinition>> identitiesToRpcs) {
+ final SchemaContext ctx) {
+
+ Multimap<QName, RpcDefinition> identitiesToRpcs = getIdentitiesToRpcs(ctx);
List<AttributeIfc> attributes = Lists.newArrayList();
List<RuntimeBeanEntry> runtimeBeanEntries = new ArrayList<>();
ListSchemaNode listSchemaNode = (ListSchemaNode) child;
RuntimeBeanEntry hierarchicalChild = createHierarchical(
packageName, listSchemaNode, typeProviderWrapper,
- currentModule, identitiesToRpcs);
+ currentModule, ctx);
runtimeBeanEntries.add(hierarchicalChild);
} else /* ordinary list attribute */{
ListAttribute listAttribute = ListAttribute.create(
if (ConfigConstants.RPC_CONTEXT_INSTANCE_EXTENSION_QNAME
.equals(unknownSchemaNode.getNodeType())) {
String localIdentityName = unknownSchemaNode.getNodeParameter();
- QName identityQName = QName.create(currentModule.getNamespace(),
- currentModule.getRevision(), localIdentityName);
- Set<RpcDefinition> rpcDefinitions = identitiesToRpcs
- .get(identityQName);
- if (rpcDefinitions == null) {
- throw new IllegalArgumentException("Cannot find identity "
- + localIdentityName + " to be used as "
- + "context reference when resolving "
- + unknownSchemaNode);
- }
+ QName identityQName = unknownSchemaNode.isAddedByUses() ?
+ findQNameFromGrouping(subtree, ctx, unknownSchemaNode, localIdentityName) :
+ QName.create(currentModule.getNamespace(), currentModule.getRevision(), localIdentityName);
// convert RpcDefinition to Rpc
- for (RpcDefinition rpcDefinition : rpcDefinitions) {
+ for (RpcDefinition rpcDefinition : identitiesToRpcs.get(identityQName)) {
String name = TypeProviderWrapper
.findJavaParameter(rpcDefinition);
AttributeIfc returnType;
attributes, rpcs);
}
+ /**
+ * Find "proper" qname of unknown node in case it comes from a grouping
+ */
+ private static QName findQNameFromGrouping(final DataNodeContainer subtree, final SchemaContext ctx, final UnknownSchemaNode unknownSchemaNode, final String localIdentityName) {
+ QName identityQName = null;
+ for (UsesNode usesNode : subtree.getUses()) {
+ SchemaNode dataChildByName = SchemaContextUtil.findDataSchemaNode(ctx, usesNode.getGroupingPath());
+ Module m = SchemaContextUtil.findParentModule(ctx, dataChildByName);
+ List<UnknownSchemaNode> unknownSchemaNodes = dataChildByName.getUnknownSchemaNodes();
+ if(Collections2.transform(unknownSchemaNodes, UNKNOWN_NODE_TO_STRING).contains(UNKNOWN_NODE_TO_STRING.apply(unknownSchemaNode))) {
+ identityQName = QName.create(dataChildByName.getQName(), localIdentityName);
+ }
+ }
+ return identityQName;
+ }
+
private static AttributeIfc getReturnTypeAttribute(final DataSchemaNode child, final TypeProviderWrapper typeProviderWrapper,
final String packageName) {
if (child instanceof LeafSchemaNode) {
private static RuntimeBeanEntry createHierarchical(final String packageName,
final ListSchemaNode listSchemaNode,
final TypeProviderWrapper typeProviderWrapper, final Module currentModule,
- final Map<QName, Set<RpcDefinition>> identitiesToRpcs) {
+ final SchemaContext ctx) {
// supported are numeric types, strings, enums
// get all attributes
AttributesRpcsAndRuntimeBeans attributesRpcsAndRuntimeBeans = extractSubtree(
packageName, listSchemaNode, typeProviderWrapper,
- currentModule, identitiesToRpcs);
+ currentModule, ctx);
Optional<String> keyYangName;
if (listSchemaNode.getKeyDefinition().isEmpty()) {
*/
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;
.getUnknownSchemaNodes();
Map<String, RuntimeBeanEntry> runtimeBeans = RuntimeBeanEntry
.extractClassNameToRuntimeBeanMap(PACKAGE_NAME, caseNode, "test-name", new TypeProviderWrapper(new
- TypeProviderImpl(context)), "test", jmxImplModule);
+ TypeProviderImpl(context)), "test", jmxImplModule, context);
assertEquals(1, runtimeBeans.size());
RuntimeBeanEntry runtimeMXBean = runtimeBeans.get("testRuntimeMXBean");
assertTrue(runtimeMXBean.isRoot());
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.util;
import com.google.common.collect.Lists;
+import java.math.BigInteger;
import java.util.List;
import org.opendaylight.controller.config.yang.test.impl.Asdf;
import org.opendaylight.controller.config.yang.test.impl.Deep2;
return asdf;
}
+ @Override
+ public BigInteger getCommonStat() {
+ return new BigInteger("54");
+ }
+
@Override
public String noArg(final String arg1) {
return arg1.toUpperCase();
}
+ @Override
+ public Long commonRpcTwo() {
+ return 1L;
+ }
+
+ @Override
+ public String commonRpcThree() {
+ return "true";
+ }
+
+ @Override
+ public Boolean commonRpc() {
+ return true;
+ }
+
+ @Override
+ public void netconfImplRpcFromGrouping() {
+ // rpc from grouping within same yang module
+ }
+
});
for (int i = 0; i < module.getSimpleShort(); i++) {
import ietf-inet-types { prefix inet; revision-date 2010-09-24;}
import rpc-context { prefix rpcx; revision-date 2013-06-17; }
import test-types { prefix tt; revision-date 2013-11-27; }
+ import test-groups { prefix tg; revision-date 2014-12-08; }
description
"Testing IMPL";
}
}
+ grouping netconf-impl-rpc {
+ rpcx:rpc-context-instance netconf-impl-rpc-ctx;
+ }
+
+ identity netconf-impl-rpc-ctx;
+
+ rpc netconf-impl-rpc-from-grouping {
+ input {
+ uses rpcx:rpc-context-ref {
+ refine context-instance {
+ rpcx:rpc-context-instance "netconf-impl-rpc-ctx";
+ }
+ }
+ }
+ }
+
augment "/config:modules/config:module/config:state" {
case impl-netconf {
when "/config:modules/config:module/config:type = 'impl-netconf'";
// rpc
rpcx:rpc-context-instance "test-rpc";
+ // add some stats + rpc from groupings outside this module
+ uses tt:common-operational;
+ uses tg:common-operational-rpc;
+ uses netconf-impl-rpc;
+
// root runtime bean
leaf created-sessions {
type uint32;
--- /dev/null
+module test-groups {
+ yang-version 1;
+ namespace "urn:opendaylight:params:xml:ns:yang:controller:config:test:groups";
+ prefix "tg";
+
+ import rpc-context { prefix rpcx; revision-date 2013-06-17; }
+
+ description
+ "Groupings generated for testing";
+
+ revision "2014-12-08";
+
+ grouping common-operational-rpc {
+ rpcx:rpc-context-instance common-rpc-ctx;
+ rpcx:rpc-context-instance common-rpc-ctx-two;
+ }
+
+ identity common-rpc-ctx;
+ identity common-rpc-ctx-two;
+
+ rpc common-rpc {
+ input {
+ uses rpcx:rpc-context-ref {
+ refine context-instance {
+ rpcx:rpc-context-instance "common-rpc-ctx";
+ }
+ }
+ }
+
+ output {
+ leaf output {
+ type boolean;
+ }
+ }
+ }
+
+ rpc common-rpc-two {
+ input {
+ uses rpcx:rpc-context-ref {
+ refine context-instance {
+ rpcx:rpc-context-instance "common-rpc-ctx-two";
+ }
+ }
+ }
+
+ output {
+ leaf output {
+ type uint32;
+ }
+ }
+ }
+}
namespace "urn:opendaylight:params:xml:ns:yang:controller:config:test:types";
prefix "tt";
+ import rpc-context { prefix rpcx; revision-date 2013-06-17; }
+
description
"Types generated for testing";
identity test-identity2 {
base test-identity1;
}
+
+ grouping common-operational {
+ leaf common-stat {
+ type uint64;
+ }
+ // This would not work, since it clashes with identity common-rpc-ctx from test-groups
+ // Both grouping add the same unknown node "rpcx:rpc-context-instance common-rpc-ctx-three;"
+ // and we cannot match the unknown node to the grouping that added it
+ //rpcx:rpc-context-instance common-rpc-ctx-three;
+ rpcx:rpc-context-instance common-rpc-ctx-three;
+ }
+
+ //identity common-rpc-ctx;
+ identity common-rpc-ctx-three;
+
+ rpc common-rpc-three {
+ input {
+ uses rpcx:rpc-context-ref {
+ refine context-instance {
+ rpcx:rpc-context-instance "common-rpc-ctx-three";
+ }
+ }
+ }
+
+ output {
+ leaf output {
+ type string;
+ }
+ }
+ }
}
*/
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";
package org.opendaylight.controller.md.sal.dom.store.benchmark;
import java.util.concurrent.TimeUnit;
+
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
-import org.opendaylight.controller.md.sal.dom.broker.impl.DOMDataBrokerImpl;
+import org.opendaylight.controller.md.sal.dom.broker.impl.SerializedDOMDataBroker;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Measurement;
*/
public abstract class AbstractInMemoryBrokerWriteTransactionBenchmark extends AbstractInMemoryWriteTransactionBenchmark {
- protected DOMDataBrokerImpl domBroker;
+ protected SerializedDOMDataBroker domBroker;
protected void initTestNode() throws Exception {
final YangInstanceIdentifier testPath = YangInstanceIdentifier.builder(BenchmarkModel.TEST_PATH)
<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>
scheduleElection(electionDuration());
}
+ private boolean isLogEntryPresent(long index){
+ if(index == context.getReplicatedLog().getSnapshotIndex()){
+ return true;
+ }
+
+ ReplicatedLogEntry previousEntry = context.getReplicatedLog()
+ .get(index);
+
+ return previousEntry != null;
+
+ }
+
+ private long getLogEntryTerm(long index){
+ if(index == context.getReplicatedLog().getSnapshotIndex()){
+ return context.getReplicatedLog().getSnapshotTerm();
+ }
+
+ ReplicatedLogEntry previousEntry = context.getReplicatedLog()
+ .get(index);
+
+ if(previousEntry != null){
+ return previousEntry.getTerm();
+ }
+
+ return -1;
+ }
+
@Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
- AppendEntries appendEntries) {
+ AppendEntries appendEntries) {
if(appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
if(LOG.isDebugEnabled()) {
// 2. Reply false if log doesn’t contain an entry at prevLogIndex
// whose term matches prevLogTerm (§5.3)
- ReplicatedLogEntry previousEntry = context.getReplicatedLog()
- .get(appendEntries.getPrevLogIndex());
+ long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
+ boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
boolean outOfSync = true;
// First check if the logs are in sync or not
if (lastIndex() == -1
- && appendEntries.getPrevLogIndex() != -1) {
+ && appendEntries.getPrevLogIndex() != -1) {
// The follower's log is out of sync because the leader does have
// an entry at prevLogIndex and this follower has no entries in
if(LOG.isDebugEnabled()) {
LOG.debug("The followers log is empty and the senders prevLogIndex is {}",
- appendEntries.getPrevLogIndex());
+ appendEntries.getPrevLogIndex());
}
} else if (lastIndex() > -1
- && appendEntries.getPrevLogIndex() != -1
- && previousEntry == null) {
+ && appendEntries.getPrevLogIndex() != -1
+ && !prevEntryPresent) {
// The follower's log is out of sync because the Leader's
// prevLogIndex entry was not found in it's log
if(LOG.isDebugEnabled()) {
LOG.debug("The log is not empty but the prevLogIndex {} was not found in it",
- appendEntries.getPrevLogIndex());
+ appendEntries.getPrevLogIndex());
}
} else if (lastIndex() > -1
- && previousEntry != null
- && previousEntry.getTerm()!= appendEntries.getPrevLogTerm()) {
+ && prevEntryPresent
+ && prevLogTerm != appendEntries.getPrevLogTerm()) {
// The follower's log is out of sync because the Leader's
// prevLogIndex entry does exist in the follower's log but it has
// a different term in it
- if(LOG.isDebugEnabled()) {
+ if (LOG.isDebugEnabled()) {
LOG.debug(
- "Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}"
- , previousEntry.getTerm()
- , appendEntries.getPrevLogTerm());
+ "Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}"
+ , prevLogTerm
+ , appendEntries.getPrevLogTerm());
}
} else {
outOfSync = false;
// We found that the log was out of sync so just send a negative
// reply and return
if(LOG.isDebugEnabled()) {
- LOG.debug("Follower is out-of-sync, " +
+ LOG.debug("Follower ({}) is out-of-sync, " +
"so sending negative reply, lastIndex():{}, lastTerm():{}",
- lastIndex(), lastTerm()
+ context.getId(), lastIndex(), lastTerm()
);
}
sender.tell(
}};
}
+ @Test
+ public void testHandleAppendEntriesPreviousLogEntryMissing(){
+ new JavaTestKit(getSystem()) {{
+
+ MockRaftActorContext context = (MockRaftActorContext)
+ createActorContext();
+
+ // Prepare the receivers log
+ MockRaftActorContext.SimpleReplicatedLog log =
+ new MockRaftActorContext.SimpleReplicatedLog();
+ log.append(
+ new MockRaftActorContext.MockReplicatedLogEntry(1, 0, new MockRaftActorContext.MockPayload("zero")));
+ log.append(
+ new MockRaftActorContext.MockReplicatedLogEntry(1, 1, new MockRaftActorContext.MockPayload("one")));
+ log.append(
+ new MockRaftActorContext.MockReplicatedLogEntry(1, 2, new MockRaftActorContext.MockPayload("two")));
+
+ context.setReplicatedLog(log);
+
+ // Prepare the entries to be sent with AppendEntries
+ List<ReplicatedLogEntry> entries = new ArrayList<>();
+ entries.add(
+ new MockRaftActorContext.MockReplicatedLogEntry(1, 4, new MockRaftActorContext.MockPayload("two-1")));
+
+ AppendEntries appendEntries =
+ new AppendEntries(1, "leader-1", 3, 1, entries, 4);
+
+ RaftActorBehavior behavior = createBehavior(context);
+
+ // Send an unknown message so that the state of the RaftActor remains unchanged
+ RaftActorBehavior expected = behavior.handleMessage(getRef(), "unknown");
+
+ RaftActorBehavior raftBehavior =
+ behavior.handleMessage(getRef(), appendEntries);
+
+ assertEquals(expected, raftBehavior);
+
+ // Also expect an AppendEntriesReply to be sent where success is false
+ final Boolean out = new ExpectMsg<Boolean>(duration("1 seconds"),
+ "AppendEntriesReply") {
+ // do not put code outside this method, will run afterwards
+ protected Boolean match(Object in) {
+ if (in instanceof AppendEntriesReply) {
+ AppendEntriesReply reply = (AppendEntriesReply) in;
+ return reply.isSuccess();
+ } else {
+ throw noMatch();
+ }
+ }
+ }.get();
+
+ assertEquals(false, out);
+
+ }};
+
+ }
+
+ @Test
+ public void testHandleAppendAfterInstallingSnapshot(){
+ new JavaTestKit(getSystem()) {{
+
+ MockRaftActorContext context = (MockRaftActorContext)
+ createActorContext();
+
+
+ // Prepare the receivers log
+ MockRaftActorContext.SimpleReplicatedLog log =
+ new MockRaftActorContext.SimpleReplicatedLog();
+
+ // Set up a log as if it has been snapshotted
+ log.setSnapshotIndex(3);
+ log.setSnapshotTerm(1);
+
+ context.setReplicatedLog(log);
+
+ // Prepare the entries to be sent with AppendEntries
+ List<ReplicatedLogEntry> entries = new ArrayList<>();
+ entries.add(
+ new MockRaftActorContext.MockReplicatedLogEntry(1, 4, new MockRaftActorContext.MockPayload("two-1")));
+
+ AppendEntries appendEntries =
+ new AppendEntries(1, "leader-1", 3, 1, entries, 4);
+
+ RaftActorBehavior behavior = createBehavior(context);
+
+ // Send an unknown message so that the state of the RaftActor remains unchanged
+ RaftActorBehavior expected = behavior.handleMessage(getRef(), "unknown");
+
+ RaftActorBehavior raftBehavior =
+ behavior.handleMessage(getRef(), appendEntries);
+
+ assertEquals(expected, raftBehavior);
+
+ // Also expect an AppendEntriesReply to be sent where success is false
+ final Boolean out = new ExpectMsg<Boolean>(duration("1 seconds"),
+ "AppendEntriesReply") {
+ // do not put code outside this method, will run afterwards
+ protected Boolean match(Object in) {
+ if (in instanceof AppendEntriesReply) {
+ AppendEntriesReply reply = (AppendEntriesReply) in;
+ return reply.isSuccess();
+ } else {
+ throw noMatch();
+ }
+ }
+ }.get();
+
+ assertEquals(true, out);
+
+ }};
+
+ }
+
/**
* This test verifies that when InstallSnapshot is received by
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;
}
package org.opendaylight.controller.sal.binding.impl;
import static com.google.common.base.Preconditions.checkState;
-
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
-
import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Throwables;
-import com.google.common.cache.Cache;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
-import com.google.common.util.concurrent.UncheckedExecutionException;
-
public class RpcProviderRegistryImpl implements RpcProviderRegistry, RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
private RuntimeCodeGenerator rpcFactory = SingletonHolder.RPC_GENERATOR_IMPL;
}
@Override
- public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(final Class<T> type, final T implementation)
- throws IllegalStateException {
+ public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(final Class<T> type, final T implementation) {
// FIXME: This should be well documented - addRpcImplementation for
// routed RPCs
}
- private class RouteChangeForwarder<T extends RpcService> implements RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
-
+ private final class RouteChangeForwarder<T extends RpcService> implements RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
private final Class<T> type;
- public RouteChangeForwarder(final Class<T> type) {
+ RouteChangeForwarder(final Class<T> type) {
this.type = type;
}
}
}
- public static class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
-
+ private static final class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
+ private final RpcProviderRegistryImpl registry;
private final Class<T> serviceType;
- private RpcProviderRegistryImpl registry;
- public RpcProxyRegistration(final Class<T> type, final T service, final RpcProviderRegistryImpl registry) {
+ RpcProxyRegistration(final Class<T> type, final T service, final RpcProviderRegistryImpl registry) {
super(service);
+ this.registry = Preconditions.checkNotNull(registry);
this.serviceType = type;
- this.registry = registry;
}
@Override
@Override
protected void removeRegistration() {
- if (registry != null) {
- T publicProxy = registry.getRpcService(serviceType);
- RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
- if (currentDelegate == getInstance()) {
- RuntimeCodeHelper.setDelegate(publicProxy, null);
- }
- registry = null;
+ T publicProxy = registry.getRpcService(serviceType);
+ RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
+ if (currentDelegate == getInstance()) {
+ RuntimeCodeHelper.setDelegate(publicProxy, null);
}
}
}
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.Collections2;
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.controller.sal.core.api.Broker;
+import org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration;
import org.opendaylight.controller.sal.core.api.RpcImplementation;
import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
import org.opendaylight.yangtools.concepts.CompositeObjectRegistration;
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 Set<QName> supportedRpcs;
private final WeakReference<Class<? extends RpcService>> rpcServiceType;
- private Set<org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration> registrations;
+ private Set<RoutedRpcRegistration> registrations;
private final Map<QName, RpcInvocationStrategy> strategiesByQName = new HashMap<>();
private final WeakHashMap<Method, RpcInvocationStrategy> strategiesByMethod = new WeakHashMap<>();
private final RpcService proxy;
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);
}
};
final RpcProvisionRegistry biRpcRegistry, final RpcProviderRegistry baRpcRegistry, final RpcProviderRegistryImpl registryImpl) {
this(service, mappingService, biRpcRegistry, baRpcRegistry,registryImpl);
- final ImmutableSet.Builder<Broker.RoutedRpcRegistration> registrationsBuilder = ImmutableSet.builder();
+ final ImmutableSet.Builder<RoutedRpcRegistration> registrationsBuilder = ImmutableSet.builder();
try {
for (QName rpc : supportedRpcs) {
registrationsBuilder.add(biRpcRegistry.addRoutedRpcImplementation(rpc, this));
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(
- toDOMInstanceIdentifier)) {
- for (org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration reg : registrations) {
+ for (YangInstanceIdentifier path : Collections2.transform(set, toDOMInstanceIdentifier)) {
+ for (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(
- toDOMInstanceIdentifier)) {
- for (org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration reg : registrations) {
+ for (YangInstanceIdentifier path : Collections2.transform(set, toDOMInstanceIdentifier)) {
+ for (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>
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.raft.protobuff.client.messages;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.GeneratedMessage;
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.UnknownFieldSet;
+import java.io.IOException;
+import java.io.Serializable;
+import java.lang.ref.SoftReference;
+import java.util.HashMap;
+import java.util.Map;
+import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages;
+import org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CompositeModificationByteStringPayload extends Payload implements
+ Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private ByteString byteString;
+ private SoftReference<PersistentMessages.CompositeModification> modificationReference;
+ private static final Logger LOG = LoggerFactory.getLogger(CompositeModificationByteStringPayload.class);
+
+ public CompositeModificationByteStringPayload(){
+ byteString = null;
+ }
+ public CompositeModificationByteStringPayload(Object modification){
+ this(((PersistentMessages.CompositeModification) modification).toByteString());
+ this.modificationReference = new SoftReference<>((PersistentMessages.CompositeModification) modification);
+ }
+
+ private CompositeModificationByteStringPayload(ByteString byteString){
+ this.byteString = Preconditions.checkNotNull(byteString, "byteString should not be null");
+ }
+
+
+ @Override
+ public Map<GeneratedMessage.GeneratedExtension, PersistentMessages.CompositeModification> encode() {
+ Preconditions.checkState(byteString!=null);
+ Map<GeneratedMessage.GeneratedExtension, PersistentMessages.CompositeModification> map = new HashMap<>();
+ map.put(org.opendaylight.controller.protobuff.messages.shard.CompositeModificationPayload.modification,
+ getModificationInternal());
+ return map;
+ }
+
+ @Override
+ public Payload decode(
+ AppendEntriesMessages.AppendEntries.ReplicatedLogEntry.Payload payload) {
+ PersistentMessages.CompositeModification modification = payload
+ .getExtension(
+ org.opendaylight.controller.protobuff.messages.shard.CompositeModificationPayload.modification);
+
+ // The extension was put in the unknown field.
+ // This is because extensions need to be registered
+ // see org.opendaylight.controller.mdsal.CompositeModificationPayload.registerAllExtensions
+ // also see https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/ExtensionRegistry
+ // If that is not done then on the other end the extension shows up as an unknown field
+ // Need to figure out a better way to do this
+ if(payload.getUnknownFields().hasField(2)){
+ UnknownFieldSet.Field field =
+ payload.getUnknownFields().getField(2);
+
+ return new CompositeModificationByteStringPayload(field.getLengthDelimitedList().get(0));
+ }
+
+ return new CompositeModificationByteStringPayload(modification);
+ }
+
+ public Object getModification(){
+ return getModificationInternal();
+ }
+
+ private PersistentMessages.CompositeModification getModificationInternal(){
+ if(this.modificationReference != null && this.modificationReference.get() != null){
+ return this.modificationReference.get();
+ }
+ try {
+ PersistentMessages.CompositeModification compositeModification = PersistentMessages.CompositeModification.parseFrom(this.byteString);
+ this.modificationReference = new SoftReference<>(compositeModification);
+ return compositeModification;
+ } catch (InvalidProtocolBufferException e) {
+ LOG.error("Unexpected exception occurred when parsing byteString to CompositeModification", e);
+ }
+
+ return null;
+ }
+
+ public int size(){
+ return byteString.size();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream stream)
+ throws IOException {
+ byteString.writeTo(stream);
+ }
+
+ private void readObject(java.io.ObjectInputStream stream)
+ throws IOException, ClassNotFoundException {
+ byteString = ByteString.readFrom(stream);
+ }
+
+ @VisibleForTesting
+ public void clearModificationReference(){
+ if(this.modificationReference != null) {
+ this.modificationReference.clear();
+ }
+ }
+}
\ No newline at end of file
}
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.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>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-api</artifactId>
</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>
import org.opendaylight.controller.cluster.raft.RaftActor;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
+import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
cohortEntry.getCohort().preCommit().get();
Shard.this.persistData(getSender(), transactionID,
- new CompositeModificationPayload(cohortEntry.getModification().toSerializable()));
+ new CompositeModificationByteStringPayload(cohortEntry.getModification().toSerializable()));
} catch (InterruptedException | ExecutionException e) {
LOG.error(e, "An exception occurred while preCommitting transaction {}",
cohortEntry.getTransactionID());
protected void appendRecoveredLogEntry(final Payload data) {
if (data instanceof CompositeModificationPayload) {
currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
+ } else if (data instanceof CompositeModificationByteStringPayload) {
+ currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
} else {
LOG.error("Unknown state received {} during recovery", data);
}
if (data instanceof CompositeModificationPayload) {
Object modification = ((CompositeModificationPayload) data).getModification();
- if(modification == null) {
- LOG.error(
- "modification is null - this is very unexpected, clientActor = {}, identifier = {}",
- identifier, clientActor != null ? clientActor.path().toString() : null);
- } else if(clientActor == null) {
- // There's no clientActor to which to send a commit reply so we must be applying
- // replicated state from the leader.
- commitWithNewTransaction(MutableCompositeModification.fromSerializable(
- modification, schemaContext));
- } else {
- // This must be the OK to commit after replication consensus.
- finishCommit(clientActor, identifier);
- }
+ applyModificationToState(clientActor, identifier, modification);
+ } else if(data instanceof CompositeModificationByteStringPayload ){
+ Object modification = ((CompositeModificationByteStringPayload) data).getModification();
+
+ applyModificationToState(clientActor, identifier, modification);
+
} else {
LOG.error("Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
data, data.getClass().getClassLoader(),
}
+ private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
+ if(modification == null) {
+ LOG.error(
+ "modification is null - this is very unexpected, clientActor = {}, identifier = {}",
+ identifier, clientActor != null ? clientActor.path().toString() : null);
+ } else if(clientActor == null) {
+ // There's no clientActor to which to send a commit reply so we must be applying
+ // replicated state from the leader.
+ commitWithNewTransaction(MutableCompositeModification.fromSerializable(
+ modification, schemaContext));
+ } else {
+ // This must be the OK to commit after replication consensus.
+ finishCommit(clientActor, identifier);
+ }
+ }
+
private void updateJournalStats() {
ReplicatedLogEntry lastLogEntry = getLastLogEntry();
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertTrue;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.commons.lang.SerializationUtils;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.datastore.modification.Modification;
+import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
+import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
+import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
+import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
+import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
+import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class CompositeModificationByteStringPayloadTest {
+
+ private static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
+
+ @Test
+ public void testSerialization(){
+ WriteModification writeModification =
+ new WriteModification(TestModel.TEST_PATH, ImmutableNodes
+ .containerNode(TestModel.TEST_QNAME),
+ TestModel.createTestContext());
+
+ MutableCompositeModification compositeModification =
+ new MutableCompositeModification();
+
+ compositeModification.addModification(writeModification);
+
+ CompositeModificationByteStringPayload compositeModificationByteStringPayload
+ = new CompositeModificationByteStringPayload(compositeModification.toSerializable());
+
+ byte[] bytes = SerializationUtils.serialize(compositeModificationByteStringPayload);
+
+ Object deserialize = SerializationUtils.deserialize(bytes);
+
+ assertTrue(deserialize instanceof CompositeModificationByteStringPayload);
+
+ }
+
+ @Test
+ public void testAppendEntries(){
+ List<ReplicatedLogEntry> entries = new ArrayList<>();
+
+ CompositeModificationByteStringPayload payload = newByteStringPayload(
+ new WriteModification(TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
+ SCHEMA_CONTEXT));
+
+ payload.clearModificationReference();
+
+ entries.add(new ReplicatedLogImplEntry(0, 1, payload));
+
+
+ assertNotNull(new AppendEntries(10, "foobar", 10, 10, entries, 10).toSerializable());
+ }
+
+
+
+ private CompositeModificationByteStringPayload newByteStringPayload(final Modification... mods) {
+ MutableCompositeModification compMod = new MutableCompositeModification();
+ for(Modification mod: mods) {
+ compMod.addModification(mod);
+ }
+
+ return new CompositeModificationByteStringPayload(compMod.toSerializable());
+ }
+
+}
import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
+import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
SCHEMA_CONTEXT))));
- int nListEntries = 11;
+ int nListEntries = 16;
Set<Integer> listEntryKeys = new HashSet<>();
- for(int i = 1; i <= nListEntries; i++) {
+ for(int i = 1; i <= nListEntries-5; i++) {
listEntryKeys.add(Integer.valueOf(i));
YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
.nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
newPayload(mod)));
}
+ // Add some of the new CompositeModificationByteStringPayload
+ for(int i = 11; i <= nListEntries; i++) {
+ listEntryKeys.add(Integer.valueOf(i));
+ YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
+ Modification mod = new MergeModification(path,
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i),
+ SCHEMA_CONTEXT);
+ InMemoryJournal.addEntry(shardID.toString(), i, new ReplicatedLogImplEntry(i, 1,
+ newByteStringPayload(mod)));
+ }
+
+
InMemoryJournal.addEntry(shardID.toString(), nListEntries + 1,
new ApplyLogEntries(nListEntries));
return new CompositeModificationPayload(compMod.toSerializable());
}
+ private CompositeModificationByteStringPayload newByteStringPayload(final Modification... mods) {
+ MutableCompositeModification compMod = new MutableCompositeModification();
+ for(Modification mod: mods) {
+ compMod.addModification(mod);
+ }
+
+ return new CompositeModificationByteStringPayload(compMod.toSerializable());
+ }
+
+
private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(final String cohortName,
final InMemoryDOMDataStore dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
final MutableCompositeModification modification) {
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;
}
@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");
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+
factory.setNamespaceAware(true);
factory.setCoalescing(true);
factory.setIgnoringElementContentWhitespace(true);
static {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ try {
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ factory.setXIncludeAware(false);
+ factory.setExpandEntityReferences(false);
+ } catch (ParserConfigurationException e) {
+ throw new ExceptionInInitializerError(e);
+ }
factory.setNamespaceAware(true);
factory.setCoalescing(true);
factory.setIgnoringElementContentWhitespace(true);
public class XmlToCompositeNodeReader {
private final static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
+ static {
+ xmlInputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
+ }
private XMLEventReader eventReader;
public Node<?> read(InputStream entityStream) throws XMLStreamException,
--- /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;
private List<InputStream> getYangs() throws FileNotFoundException {
List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
"/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
- "/META-INF/yang/ietf-inet-types.yang");
+ "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types.yang");
final Collection<InputStream> yangDependencies = new ArrayList<>();
for (String path : paths) {
final InputStream is = Preconditions
@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);
}
static {
BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
+ try {
+ BUILDER_FACTORY.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ BUILDER_FACTORY.setXIncludeAware(false);
+ BUILDER_FACTORY.setExpandEntityReferences(false);
+ } catch (ParserConfigurationException e) {
+ throw new ExceptionInInitializerError(e);
+ }
BUILDER_FACTORY.setNamespaceAware(true);
BUILDER_FACTORY.setCoalescing(true);
BUILDER_FACTORY.setIgnoringElementContentWhitespace(true);
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;
+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
"/META-INF/yang/config-test.yang",
"/META-INF/yang/config-test-impl.yang",
"/META-INF/yang/test-types.yang",
+ "/META-INF/yang/test-groups.yang",
"/META-INF/yang/ietf-inet-types.yang");
final Collection<InputStream> yangDependencies = new ArrayList<>();
}
notificationVerifier.assertNotificationCount(2);
- notificationVerifier.assertNotificationContent(0, 0, 0, 8);
- notificationVerifier.assertNotificationContent(1, 4, 3, 8);
+ notificationVerifier.assertNotificationContent(0, 0, 0, 9);
+ notificationVerifier.assertNotificationContent(1, 4, 3, 9);
mockedAggregator.assertSnapshotCount(2);
// Capabilities are stripped for persister
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());
}
import org.openexi.proc.grammars.GrammarCache;
import org.openexi.sax.EXIReader;
import org.openexi.sax.Transmogrifier;
+import org.openexi.sax.TransmogrifierException;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
public final class NetconfEXICodec {
/**
* of the stream. This is really useful, so let's output it now.
*/
private static final boolean OUTPUT_EXI_COOKIE = true;
+ /**
+ * OpenEXI does not allow us to directly prevent resolution of external entities. In order
+ * to prevent XXE attacks, we reuse a single no-op entity resolver.
+ */
+ private static final EntityResolver ENTITY_RESOLVER = new EntityResolver() {
+ @Override
+ public InputSource resolveEntity(final String publicId, final String systemId) {
+ return new InputSource();
+ }
+ };
+
private final EXIOptions exiOptions;
public NetconfEXICodec(final EXIOptions exiOptions) {
final EXIReader r = new EXIReader();
r.setPreserveLexicalValues(exiOptions.getPreserveLexicalValues());
r.setGrammarCache(getGrammarCache());
+ r.setEntityResolver(ENTITY_RESOLVER);
return r;
}
- Transmogrifier getTransmogrifier() throws EXIOptionsException {
+ Transmogrifier getTransmogrifier() throws EXIOptionsException, TransmogrifierException {
final Transmogrifier transmogrifier = new Transmogrifier();
transmogrifier.setAlignmentType(exiOptions.getAlignmentType());
transmogrifier.setBlockSize(exiOptions.getBlockSize());
transmogrifier.setGrammarCache(getGrammarCache());
transmogrifier.setOutputCookie(OUTPUT_EXI_COOKIE);
transmogrifier.setOutputOptions(HeaderOptionsOutputType.all);
+ transmogrifier.setResolveExternalGeneralEntities(false);
return transmogrifier;
}
}
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.openexi.sax.TransmogrifierException;
import org.slf4j.Logger;
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) {
}
@Override
- protected void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws EXIOptionsException, IOException, TransformerException {
+ protected void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws EXIOptionsException, IOException, TransformerException, TransmogrifierException {
LOG.trace("Sent to encode : {}", msg);
try (final OutputStream os = new ByteBufOutputStream(out)) {
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();
+ }
+}
server = dispatcher.createLocalServer(tcpLocalAddress);
try {
final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
- sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress));
+ sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
sshWrappers.add(sshServer);
} catch (final BindException e) {
LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
return openDevices;
}
- private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress) throws IOException {
+ private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
return new SshProxyServerConfigurationBuilder()
.setBindingAddress(bindingAddress)
.setLocalAddress(tcpLocalAddress)
return true;
}
})
- .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
+ .setKeyPairProvider(keyPairProvider)
.setIdleTimeout(Integer.MAX_VALUE)
.createSshProxyServerConfiguration();
}
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();
+ try {
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ factory.setXIncludeAware(false);
+ factory.setExpandEntityReferences(false);
+ } catch (ParserConfigurationException e) {
+ throw new ExceptionInInitializerError(e);
+ }
factory.setNamespaceAware(true);
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;
}
+ @Test(expected = SAXParseException.class)
+ public void testXXEFlaw() throws Exception {
+ XmlUtil.readXmlToDocument("<!DOCTYPE foo [ \n" +
+ "<!ELEMENT foo ANY >\n" +
+ "<!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]>\n" +
+ "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
+ " <capabilities>\n" +
+ " <capability>urn:ietf:params:netconf:base:1.0 &xxe;</capability>\n" +
+ " </capabilities>\n" +
+ " </hello>]]>]]>");
+ }
+
@Test
public void testXPath() throws Exception {
final XPathExpression correctXPath = XMLNetconfUtil.compileXPath("/top/innerText");
<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>