int orderingIdx = 0;
for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
+ logger.trace("Registering {}", moduleIdentifier);
ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
.get(moduleIdentifier);
if (entry == null) {
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
+import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
/**
try {
logger.debug("About to commit {} in transaction {}",
name, getTransactionIdentifier());
- module.getInstance();
+ AutoCloseable instance = module.getInstance();
+ checkNotNull(instance, "Instance is null:{} in transaction {}", name, getTransactionIdentifier());
} catch (Exception e) {
logger.error("Commit failed on {} in transaction {}", name,
getTransactionIdentifier(), e);
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>config-subsystem</artifactId>
<artifactId>binding-type-provider</artifactId>
</dependency>
+ <dependency>
+ <groupId>net.sourceforge.pmd</groupId>
+ <artifactId>pmd</artifactId>
+ <version>5.1.0</version>
+ <scope>test</scope>
+ </dependency>
+
+
<dependency>
<groupId>org.eclipse.jdt</groupId>
<artifactId>core</artifactId>
</dependency>
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- <version>2.3.20</version>
- </dependency>
-
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-api</artifactId>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>org.codehaus.gmaven.runtime</groupId>
+ <artifactId>gmaven-runtime-2.0</artifactId>
+ <version>1.5</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.sonatype.gossip</groupId>
+ <artifactId>gossip</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
</dependencies>
<build>
<plugins>
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.1</version>
+ <configuration>
+ <compilerId>groovy-eclipse-compiler</compilerId>
+ <verbose>false</verbose>
+ </configuration>
+ <dependencies>
+ <dependency>
+ <groupId>org.codehaus.groovy</groupId>
+ <artifactId>groovy-eclipse-compiler</artifactId>
+ <version>2.8.0-01</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.codehaus.groovy</groupId>
+ <artifactId>groovy-eclipse-batch</artifactId>
+ <version>2.1.8-01</version>
+ </dependency>
+ </dependencies>
</plugin>
+
</plugins>
</build>
</project>
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
+import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
+import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.GeneralClassTemplate;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.GeneralInterfaceTemplate;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.RuntimeRegistratorFtlTemplate;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.StubFactoryTemplate;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.AbsFactoryGeneratedObjectFactory;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.AbsModuleGeneratedObjectFactory;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.ConcreteModuleGeneratedObjectFactory;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.GenericGeneratedObjectFactory;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
+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;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
+final class CodeWriter {
+
+ private static final Logger logger = LoggerFactory.getLogger(CodeWriter.class);
+ private static final Optional<String> copyright = StringUtil.loadCopyright();
+
+ public File writeSie(ServiceInterfaceEntry sie, File outputBaseDir) {
+ try {
+ GeneralInterfaceTemplate generalInterfaceTemplate = TemplateFactory.serviceInterfaceFromSie(sie);
+ GeneratedObject go = new GenericGeneratedObjectFactory().toGeneratedObject(generalInterfaceTemplate, copyright);
+ return go.persist(outputBaseDir).get().getValue();
+ } catch (Exception e) {
+ String message = "An error occurred during Service interface generating, sie:"
+ + sie.getTypeName() + ", " + sie.getFullyQualifiedName();
+ logger.error(message, e);
+ throw new RuntimeException(message, e);
+ }
+ }
+
+ public List<File> writeMbe(ModuleMXBeanEntry mbe, File targetBaseDir,
+ File mainBaseDir) {
+ try {
+ List<File> generatedFiles = Lists.newArrayList();
+
+
+ Map<GeneratedObject, Boolean /*overwrite*/> gos = new HashMap<>();
+
+ // generate mx interface and abstract factory
+
+ // TOs
+ Map<String,GeneralClassTemplate> tosFromMbe = TemplateFactory.tOsFromMbe(mbe);
+ for(GeneralClassTemplate template: tosFromMbe.values()) {
+ gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(template, copyright), true);
+ }
+
+ // MXBean interface
+ GeneralInterfaceTemplate ifcTemplate = TemplateFactory.mXBeanInterfaceTemplateFromMbe(mbe);
+ gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(ifcTemplate, copyright), true);
+
+
+ // generate abstract factory
+ gos.put(new AbsFactoryGeneratedObjectFactory().toGeneratedObject(mbe, copyright), true);
+
+ // generate abstract module
+ gos.put(new AbsModuleGeneratedObjectFactory().toGeneratedObject(mbe, copyright), true);
+
+ // generate concrete factory
+ StubFactoryTemplate concreteFactory = TemplateFactory.stubFactoryTemplateFromMbe(mbe);
+ gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(concreteFactory, copyright), false);
+
+
+ // generate concrete module
+
+ gos.put(new ConcreteModuleGeneratedObjectFactory().toGeneratedObject(mbe, copyright, Optional.<String>absent()), false);
+
+ // write runtime bean MXBeans and registrators
+ List<FtlTemplate> allFtlFiles = getRuntimeBeanFtlTemplates(mbe.getRuntimeBeans());
+ for(FtlTemplate template: allFtlFiles) {
+ gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(template, copyright), true);
+ }
+
+ generatedFiles.addAll(persistGeneratedObjects(targetBaseDir, mainBaseDir, gos));
+
+ // purge nulls
+ for (Iterator<File> it = generatedFiles.iterator(); it.hasNext(); ) {
+ if (it.next() == null) {
+ it.remove();
+ }
+ }
+
+ return generatedFiles;
+
+ } catch (Exception e) {
+ String message = "An error occurred during Module generating, mbe:"
+ + mbe.getJavaNamePrefix();
+ logger.error(message, e);
+ throw new RuntimeException(message, e);
+ }
+ }
-public interface CodeWriter {
+ private List<File> persistGeneratedObjects(File targetBaseDir, File mainBaseDir, Map<GeneratedObject, Boolean> gos) throws IOException {
+ List<File> generatedFiles = new ArrayList<>();
+ for (Entry<GeneratedObject, Boolean> entry : gos.entrySet()) {
+ boolean overwrite = entry.getValue();
+ File dst;
+ if (overwrite) {
+ dst = targetBaseDir;
+ } else {
+ dst = mainBaseDir;
+ }
+ Optional<Entry<FullyQualifiedName, File>> maybePersistEntry = entry.getKey().persist(dst, overwrite);
- File writeSie(ServiceInterfaceEntry sie, File targetBaseDir);
+ if (maybePersistEntry.isPresent()) {
+ generatedFiles.add(maybePersistEntry.get().getValue());
+ }
+ }
+ return generatedFiles;
+ }
- List<File> writeMbe(ModuleMXBeanEntry mbe, File targetBaseDir,
- File mainBaseDir, File resourceBaseDir);
+ private List<FtlTemplate> getRuntimeBeanFtlTemplates(Collection<RuntimeBeanEntry> runtimeBeans) {
+ if (runtimeBeans.isEmpty()) {
+ return Collections.emptyList();
+ }
+ List<FtlTemplate> allFtlFiles = new ArrayList<>();
+ { // registrators
+ Map<String, FtlTemplate> registratorNamesToFtls = RuntimeRegistratorFtlTemplate
+ .create(RuntimeRegistratorFtlTemplate.findRoot(runtimeBeans));
+ allFtlFiles.addAll(registratorNamesToFtls.values());
+ }
+ { // TOs, MXBean interfaces
+ for (RuntimeBeanEntry runtimeBeanEntry : runtimeBeans) {
+ Collection<FtlTemplate> ftlFiles = TemplateFactory
+ .getTOAndMXInterfaceFtlFiles(runtimeBeanEntry)
+ .values();
+ allFtlFiles.addAll(ftlFiles);
+ }
+ }
+ return allFtlFiles;
+ }
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlFilePersister;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.RuntimeRegistratorFtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Lists;
-
-final class FreeMarkerCodeWriterImpl implements CodeWriter {
-
- private static final Logger logger = LoggerFactory
- .getLogger(FreeMarkerCodeWriterImpl.class);
-
- private final FtlFilePersister ftlFilePersister = new FtlFilePersister();
-
- public FreeMarkerCodeWriterImpl() {
- }
-
- @Override
- public File writeSie(ServiceInterfaceEntry sie, File outputBaseDir) {
- try {
- Collection<FtlTemplate> values = TemplateFactory.getFtlTemplates(
- sie).values();
- return ftlFilePersister.persist(values, outputBaseDir, true).get(0);
- } catch (Exception e) {
- String message = "An error occurred during Service interface generating, sie:"
- + sie.getTypeName() + ", " + sie.getFullyQualifiedName();
- logger.error(message, e);
- throw new RuntimeException(message, e);
- }
- }
-
- @Override
- public List<File> writeMbe(ModuleMXBeanEntry mbe, File targetBaseDir,
- File mainBaseDir, File resourceBaseDir) {
- try {
- List<File> generatedFiles = Lists.newArrayList();
-
- generatedFiles.addAll(ftlFilePersister.persist(TemplateFactory
- .getFtlTemplates(mbe).values(), targetBaseDir, true));
- generatedFiles.addAll(ftlFilePersister.persist(TemplateFactory
- .getFtlStubTemplates(mbe).values(), mainBaseDir, false));
-
- // write runtime bean MXBeans and registrators
- Collection<RuntimeBeanEntry> runtimeBeans = mbe.getRuntimeBeans();
- if (runtimeBeans.size() > 0) {
- List<FtlTemplate> allFtlFiles = new ArrayList<>();
- { // registrators
- Map<String, FtlTemplate> registratorNamesToFtls = RuntimeRegistratorFtlTemplate
- .create(RuntimeRegistratorFtlTemplate.findRoot(runtimeBeans));
-
- allFtlFiles.addAll(registratorNamesToFtls.values());
- }
- { // TOs, MXBean interfaces
- for (RuntimeBeanEntry runtimeBeanEntry : runtimeBeans) {
- Collection<FtlTemplate> ftlFiles = TemplateFactory
- .getTOAndMXInterfaceFtlFiles(runtimeBeanEntry)
- .values();
- allFtlFiles.addAll(ftlFiles);
- }
- }
- boolean overwrite = true;
-
- FtlFilePersister ftlFilePersister = new FtlFilePersister();
- List<File> persisted = ftlFilePersister.persist(allFtlFiles,
- targetBaseDir, overwrite);
- // FIXME: check for intersection
- generatedFiles.addAll(persisted);
- }
-
- // purge nulls
- for (Iterator<File> it = generatedFiles.iterator(); it.hasNext();) {
- if (it.next() == null) {
- it.remove();
- }
- }
-
- return generatedFiles;
-
- } catch (Exception e) {
- String message = "An error occurred during Module generating, mbe:"
- + mbe.getJavaNamePrefix();
- logger.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 boolean generateModuleFactoryFile = true;
public JMXGenerator() {
- this.codeWriter = new FreeMarkerCodeWriterImpl();
+ this.codeWriter = new CodeWriter();
}
public JMXGenerator(CodeWriter codeWriter) {
ModuleMXBeanEntry mbe = mbeEntry.getValue();
try {
List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir,
- mainBaseDir, resourceBaseDir);
+ mainBaseDir);
generatedFiles.addFile(files1);
} catch (Exception e) {
throw new RuntimeException(
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
import com.google.common.collect.Lists;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
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.osgi.framework.BundleContext;
import java.util.Collections;
import java.util.List;
-/**
- *
- */
public class AbstractFactoryTemplate extends GeneralClassTemplate {
private static final List<String> implementedIfcs = Lists
.newArrayList(ModuleFactory.class.getCanonicalName());
- private final String globallyUniqueName, moduleInstanceType;
- private final List<String> providedServices;
- private final ModuleMXBeanEntry mbe;
-
public AbstractFactoryTemplate(Header header, String packageName,
- String abstractFactoryName, String globallyUniqueName,
- String moduleInstanceType, List<Field> fields,
- List<String> providedServices, ModuleMXBeanEntry mbe) {
+ String abstractFactoryName,
+ List<Field> fields) {
super(header, packageName, abstractFactoryName, Collections
.<String> emptyList(), implementedIfcs, fields, Collections
.<MethodDefinition> emptyList(), true, false, Collections
.<Constructor> emptyList());
- this.globallyUniqueName = globallyUniqueName;
- this.moduleInstanceType = moduleInstanceType;
- this.providedServices = providedServices;
- this.mbe = mbe;
- }
-
- public String getGloballyUniqueName() {
- return globallyUniqueName;
- }
-
- public String getInstanceType() {
- return AutoCloseable.class.getCanonicalName();
- }
-
- public String getModuleNameType() {
- return ModuleIdentifier.class.getCanonicalName();
- }
-
- public String getModuleInstanceType() {
- return moduleInstanceType;
- }
-
- public String getAbstractServiceInterfaceType() {
- return AbstractServiceInterface.class.getCanonicalName();
- }
-
- public List<String> getProvidedServices() {
- return providedServices;
- }
-
- public String getModuleType() {
- return Module.class.getCanonicalName();
- }
-
- public String getDependencyResolverType() {
- return DependencyResolver.class.getCanonicalName();
- }
-
- public String getDynamicMBeanWithInstanceType() {
- return DynamicMBeanWithInstance.class.getCanonicalName();
- }
-
- public String getBundleContextType() {
- return BundleContext.class.getCanonicalName();
- }
-
- @Override
- public String getFtlTempleteLocation() {
- return "factory_abs_template.ftl";
- }
-
- public ModuleMXBeanEntry getMbe() {
- return mbe;
}
}
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-import java.io.File;
-import java.util.List;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
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.Header;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Method;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.TypeDeclaration;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-import com.google.common.collect.Lists;
+import java.util.Collections;
+import java.util.List;
public abstract class AbstractFtlTemplate implements FtlTemplate {
private final String packageName;
return header;
}
+ @Override
+ public Optional<String> getHeaderString() {
+ if (header == null) {
+ return Optional.absent();
+ } else {
+ return Optional.of(header.toString());
+ }
+ }
+
@Override
public String getFullyQualifiedName() {
return FullyQualifiedNameHelper.getFullyQualifiedName(getPackageName(),
return typeDeclaration;
}
+
@Override
- public String getJavadoc() {
- return javadoc;
+ public Optional<String> getMaybeJavadoc() {
+ if (javadoc == null) {
+ return Optional.absent();
+ } else {
+ return Optional.of(javadoc);
+ }
}
public void setJavadoc(String javadoc) {
return methods;
}
- @Override
- public File getRelativeFile() {
- return new File(packageName.replace(".", File.separator),
- getTypeDeclaration().getName() + ".java");
- }
@Override
- public String getFtlTempleteLocation() {
- return "abstract_ftl_file.ftl";
+ public List<Constructor> getConstructors() {
+ return Collections.emptyList();
}
@Override
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-import java.util.Collections;
-import java.util.List;
-
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
-import org.opendaylight.controller.config.spi.Module;
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 org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-/**
- *
- */
+import java.util.Collections;
+import java.util.List;
+
public class AbstractModuleTemplate extends GeneralClassTemplate {
private final List<ModuleField> moduleFields;
return moduleFields;
}
- public String getInstanceType() {
- return AutoCloseable.class.getCanonicalName();
- }
-
- public String getModuleNameType() {
- return ModuleIdentifier.class.getCanonicalName();
- }
-
- public String getAbstractServiceInterfaceType() {
- return AbstractServiceInterface.class.getCanonicalName();
- }
-
- public String getModuleType() {
- return Module.class.getCanonicalName();
- }
-
public String getRegistratorType() {
return registratorType;
}
return runtime;
}
- public String getDependencyResolverType() {
- return DependencyResolver.class.getCanonicalName();
- }
-
- public String getDynamicMBeanWithInstanceType() {
- return DynamicMBeanWithInstance.class.getCanonicalName();
- }
-
- public String getRootRuntimeRegistratorType() {
- return RootRuntimeBeanRegistrator.class.getCanonicalName();
- }
-
- @Override
- public String getFtlTempleteLocation() {
- return "module_abs_template_new.ftl";
- }
-
- public String getLoggerType() {
- return Logger.class.getCanonicalName();
- }
-
- public String getLoggerFactoryType() {
- return LoggerFactory.class.getCanonicalName();
- }
-
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import com.google.common.annotations.VisibleForTesting;
-import freemarker.template.Configuration;
-import freemarker.template.Template;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.AnnotationsDirective;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.ConstructorsDirective;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.FieldsDirectiveProg;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.HeaderDirective;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.JavadocDirective;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.MethodsDirective;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.ModuleFieldsDirective;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.TypeDeclarationDirective;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives.UnimplementedExceptionDirective;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.Writer;
-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 java.util.regex.Pattern;
-
-public class FtlFilePersister {
- private static final Logger logger = LoggerFactory
- .getLogger(FtlFilePersister.class);
-
- private static final Pattern TRAILING_WHITESPACES = Pattern.compile(" +$", Pattern.MULTILINE);
-
- @VisibleForTesting
- public Map<FtlTemplate, String> serializeFtls(
- Collection<? extends FtlTemplate> ftlFiles) {
- Map<FtlTemplate, String> result = new HashMap<>();
- for (FtlTemplate ftlFile : ftlFiles) {
-
- try (Writer writer = new StringWriter()) {
- Template template = getCfg().getTemplate(
- ftlFile.getFtlTempleteLocation());
- try {
- template.process(ftlFile, writer);
- } catch (Exception e) {
- throw new IllegalStateException(
- "Template error while generating " + ftlFile, e);
- }
- String fileContent = writer.toString();
- // remove trailing spaces
- fileContent = TRAILING_WHITESPACES.matcher(fileContent).replaceAll("");
- result.put(ftlFile, fileContent);
- } catch (IOException e) {
- throw new IllegalStateException(
- "Exception while processing template", e);
- }
- }
-
- return result;
- }
-
- public List<File> persist(Collection<? extends FtlTemplate> ftlFiles,
- File dstFolder, boolean overwrite) throws IOException {
- Map<FtlTemplate, String> ftlFileStringMap = serializeFtls(ftlFiles);
- List<File> result = new ArrayList<>();
- for (Entry<FtlTemplate, String> entry : ftlFileStringMap.entrySet()) {
- FtlTemplate ftlFile = entry.getKey();
- File targetFile = new File(dstFolder, ftlFile.getRelativeFile()
- .getPath());
- File pathToFile = targetFile.getParentFile();
- if (pathToFile.exists() == false) {
- pathToFile.mkdirs();
- }
- if (targetFile.exists() && overwrite == false) {
- logger.trace("Skipping {} since it already exists", targetFile);
- } else {
- try (Writer fileWriter = new FileWriter(targetFile)) {
- fileWriter.write(entry.getValue());
- }
- logger.trace("{}: File {} generated successfully",
- JMXGenerator.class.getCanonicalName(), targetFile);
- result.add(targetFile);
- }
- }
- return result;
- }
-
- private Configuration getCfg() {
- Configuration cfg = new Configuration();
- cfg.setClassForTemplateLoading(getClass(), "/freeMarker/");
- cfg.setSharedVariable("javadocD", new JavadocDirective());
- cfg.setSharedVariable("annotationsD", new AnnotationsDirective());
- cfg.setSharedVariable("typeDeclarationD",
- new TypeDeclarationDirective());
- cfg.setSharedVariable("constructorsD", new ConstructorsDirective());
- cfg.setSharedVariable("fieldsD", new FieldsDirectiveProg());
- cfg.setSharedVariable("moduleFieldsD", new ModuleFieldsDirective());
- cfg.setSharedVariable("methodsD", new MethodsDirective());
- cfg.setSharedVariable("headerD", new HeaderDirective());
- cfg.setSharedVariable("unimplementedExceptionD",
- new UnimplementedExceptionDirective());
- return cfg;
- }
-
-}
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-import java.io.File;
-import java.util.List;
-
+import com.google.common.base.Optional;
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.Header;
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();
+ Optional<String> getHeaderString();
String getPackageName();
- String getJavadoc();
+ Optional<String> getMaybeJavadoc();
public List<Annotation> getAnnotations();
List<? extends Method> getMethods();
- /**
- * @return relative path to file to be created.
- */
- public File getRelativeFile();
-
- /**
- *
- * @return ftl template location
- */
- public String getFtlTempleteLocation();
+ List<Constructor> getConstructors();
}
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-import java.util.Collections;
-
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
+import com.google.common.collect.Lists;
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 com.google.common.collect.Lists;
+import java.util.Collections;
public class StubFactoryTemplate extends GeneralClassTemplate {
- private final String moduleInstanceType;
-
public StubFactoryTemplate(Header header, String packageName, String name,
- String extendedClass, String moduleInstanceType) {
+ String extendedClass) {
super(header, packageName, name, Lists.newArrayList(extendedClass),
Collections.<String> emptyList(), Collections
.<Field> emptyList(), Collections
.<MethodDefinition> emptyList());
- this.moduleInstanceType = moduleInstanceType;
- }
-
- public String getModuleInstanceType() {
- return moduleInstanceType;
}
- public String getDynamicMBeanWithInstanceType() {
- return DynamicMBeanWithInstance.class.getCanonicalName();
- }
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import java.util.Collections;
-
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
-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 com.google.common.collect.Lists;
-
-/**
- *
- */
-public class StubModuleTemplate extends GeneralClassTemplate {
-
- private final String extendedClass;
-
- public StubModuleTemplate(Header header, String packageName,
- String stubModuleName, String extendedClass) {
- super(header, packageName, stubModuleName, Lists
- .newArrayList(extendedClass), Collections.<String> emptyList(),
- Collections.<Field> emptyList(), Collections
- .<MethodDefinition> emptyList(), false, true,
- Collections.<Constructor> emptyList());
- this.extendedClass = extendedClass;
- }
-
- public String getExtendedClass() {
- return extendedClass;
- }
-
- public String getInstanceType() {
- return AutoCloseable.class.getCanonicalName();
- }
-
- public String getModuleNameType() {
- return ModuleIdentifier.class.getCanonicalName();
- }
-
- public String getAbstractServiceInterfaceType() {
- return AbstractServiceInterface.class.getCanonicalName();
- }
-
- public String getModuleType() {
- return Module.class.getCanonicalName();
- }
-
- public String getDependencyResolverType() {
- return DependencyResolver.class.getCanonicalName();
- }
-
- public String getDynamicMBeanWithInstanceType() {
- return DynamicMBeanWithInstance.class.getCanonicalName();
- }
-
- @Override
- public String getFtlTempleteLocation() {
- return "module_stub_template.ftl";
- }
-}
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-import com.google.common.base.Function;
import com.google.common.base.Preconditions;
-import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
import javax.management.openmbean.SimpleType;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class TemplateFactory {
- public static Map<String, FtlTemplate> getFtlTemplates(
- ModuleMXBeanEntry entry) {
- Map<String, FtlTemplate> result = new HashMap<>();
-
- result.putAll(TemplateFactory.tOsFromMbe(entry));
-
- // IFC
- result.put(entry.getMXBeanInterfaceName() + ".java",
- TemplateFactory.mXBeanInterfaceTemplateFromMbe(entry));
-
- // ABS fact
- result.put(entry.getAbstractFactoryName() + ".java",
- TemplateFactory.abstractFactoryTemplateFromMbe(entry));
-
- // ABS module
- result.put(entry.getAbstractModuleName() + ".java",
- TemplateFactory.abstractModuleTemplateFromMbe(entry));
-
- return result;
- }
-
- public static Map<String, FtlTemplate> getFtlStubTemplates(
- ModuleMXBeanEntry entry) {
- Map<String, FtlTemplate> result = new HashMap<>();
- // STUB fact
- result.put(entry.getStubFactoryName() + ".java",
- TemplateFactory.stubFactoryTemplateFromMbe(entry));
-
- result.put(entry.getStubModuleName() + ".java",
- TemplateFactory.stubModuleTemplateFromMbe(entry));
- return result;
- }
-
- public static Map<String, FtlTemplate> getFtlTemplates(
- ServiceInterfaceEntry entry) {
-
- Map<String, FtlTemplate> result = new HashMap<>();
- result.put(entry.getTypeName() + ".java",
- TemplateFactory.serviceInterfaceFromSie(entry));
-
- return result;
- }
-
/**
* Get map of file name as key, FtlFile instance representing runtime mx
* bean as value that should be persisted from this instance.
return serializeType(type, false);
}
- private static boolean isIdentityRefType(Type type) {
- return type instanceof IdentityrefTypeDefinition;
- }
-
-
private static String getReturnType(AttributeIfc attributeIfc) {
String returnType;
if (attributeIfc instanceof TypedAttribute) {
attrProcessor.processAttributes(mbe.getAttributes(),
mbe.getPackageName());
- Collection<String> transformed = Collections2.transform(mbe
- .getProvidedServices().keySet(),
- new Function<String, String>() {
- @Override
- public String apply(String input) {
- return input + ".class";
- }
- });
return new AbstractFactoryTemplate(getHeaderFromEntry(mbe),
mbe.getPackageName(), mbe.getAbstractFactoryName(),
- mbe.getGloballyUniqueName(), mbe.getFullyQualifiedName(mbe
- .getStubModuleName()), attrProcessor.getFields(),
- Lists.newArrayList(transformed), mbe);
+ attrProcessor.getFields()
+ );
}
public static AbstractModuleTemplate abstractModuleTemplateFromMbe(
ModuleMXBeanEntry mbe) {
- AbstractModuleAttributesProcessor attrProcessor = new AbstractModuleAttributesProcessor();
- attrProcessor.processAttributes(mbe.getAttributes(),
- mbe.getPackageName());
+ AbstractModuleAttributesProcessor attrProcessor = new AbstractModuleAttributesProcessor(mbe.getAttributes());
List<ModuleField> moduleFields = attrProcessor.getModuleFields();
List<String> implementedIfcs = Lists.newArrayList(
ModuleMXBeanEntry mbe) {
return new StubFactoryTemplate(getHeaderFromEntry(mbe),
mbe.getPackageName(), mbe.getStubFactoryName(),
- mbe.getFullyQualifiedName(mbe.getAbstractFactoryName()),
- mbe.getStubModuleName());
- }
-
- public static StubModuleTemplate stubModuleTemplateFromMbe(
- ModuleMXBeanEntry mbe) {
- return new StubModuleTemplate(getHeaderFromEntry(mbe),
- mbe.getPackageName(), mbe.getStubModuleName(),
- mbe.getFullyQualifiedName(mbe.getAbstractModuleName()));
+ mbe.getFullyQualifiedName(mbe.getAbstractFactoryName())
+ );
}
public static GeneralInterfaceTemplate mXBeanInterfaceTemplateFromMbe(
}
private static class AbstractModuleAttributesProcessor {
+ private static class Holder {
+ private final List<ModuleField> moduleFields;
+ private final List<MethodDefinition> methods;
+
+ private Holder(List<ModuleField> moduleFields, List<MethodDefinition> methods) {
+ this.moduleFields = Collections.unmodifiableList(moduleFields);
+ this.methods = Collections.unmodifiableList(methods);
+ }
+ }
- private final List<ModuleField> moduleFields = Lists.newArrayList();
- private final List<MethodDefinition> methods = Lists.newArrayList();
+ private final Holder holder;
- void processAttributes(Map<String, AttributeIfc> attributes,
- String packageName) {
+
+ private AbstractModuleAttributesProcessor(Map<String, AttributeIfc> attributes) {
+ this.holder = processAttributes(attributes);
+ }
+
+ private static Holder processAttributes(Map<String, AttributeIfc> attributes) {
+ List<ModuleField> moduleFields = new ArrayList<>();
+ List<MethodDefinition> methods = new ArrayList<>();
for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
String type, nullableDefaultWrapped = null;
AttributeIfc attributeIfc = attrEntry.getValue();
String varName = BindingGeneratorUtil
.parseToValidParamName(attrEntry.getKey());
-
+ {
ModuleField field;
if (isIdentity) {
nullableDefaultWrapped, isDependency, dependency, isListOfDependencies, needsDepResolver);
}
moduleFields.add(field);
-
+ }
String getterName = "get"
+ attributeIfc.getUpperCaseCammelCase();
MethodDefinition getter = new MethodDefinition(type,
methods.add(setter);
}
+ return new Holder(moduleFields, methods);
}
List<ModuleField> getModuleFields() {
- return moduleFields;
+ return holder.moduleFields;
}
List<MethodDefinition> getMethods() {
- return methods;
+ return holder.methods;
}
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation.Parameter;
-
-import com.google.common.collect.Lists;
-
-import freemarker.core.Environment;
-import freemarker.template.SimpleSequence;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add annotations to freemarker template.
- */
-public class AnnotationsDirective implements TemplateDirectiveModel {
-
- private static final String OBJECT = "object";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
- Object object = params.get(OBJECT);
- List<Annotation> annotations = Lists.newArrayList();
-
- if (object != null) {
- if (object instanceof SimpleSequence)
- annotations = ((SimpleSequence) object).toList();
- else if (object instanceof FtlTemplate) {
- annotations = ((FtlTemplate) object).getAnnotations();
- } else
- throw new IllegalArgumentException(
- "Object must be a SimpleSequence or instance of "
- + FtlTemplate.class + "but was "
- + object.getClass());
- }
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder();
- writeAnnotations(annotations, build, "");
-
- if (!annotations.isEmpty())
- out.write(build.toString().toCharArray());
- }
-
- static void writeAnnotations(List<Annotation> annotations,
- StringBuilder build, String linePrefix) {
- for (Annotation annotation : annotations) {
- build.append(linePrefix + "@");
- build.append(annotation.getName());
- if (!annotation.getParams().isEmpty()) {
- build.append("(");
- for (Parameter param : annotation.getParams()) {
- build.append(param.getKey());
- build.append(" = ");
- build.append(fixString(param.getValue()));
- build.append(", ");
- }
- build.setCharAt(build.length() - 2, ')');
- }
- build.append(System.lineSeparator());
- }
- }
-
- private static String fixString(String value) {
- // TODO replace with compress single line if possible
- return value.replaceAll("\\r\\n|\\r|\\n", " ").replaceAll(" +", " ");
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.GeneralClassTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
-
-import com.google.common.collect.Lists;
-
-import freemarker.core.Environment;
-import freemarker.template.SimpleSequence;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add annotations to freemarker template.
- */
-public class ConstructorsDirective implements TemplateDirectiveModel {
-
- private static final String OBJECT = "object";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
- Object object = params.get(OBJECT);
- List<Constructor> constructors = Lists.newArrayList();
-
- if (object != null) {
- if (object instanceof SimpleSequence)
- constructors = ((SimpleSequence) object).toList();
- else if (object instanceof GeneralClassTemplate) {
- constructors = ((GeneralClassTemplate) object)
- .getConstructors();
- } else
- throw new IllegalArgumentException(
- "Object must be a SimpleSequence or instance of "
- + GeneralClassTemplate.class + "but was "
- + object.getClass());
- }
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder();
- for (Constructor constr : constructors) {
- build.append(" ");
- if (constr.isPublic())
- build.append("public ");
- build.append(constr.getTypeName() + " ");
- build.append("() {");
- build.append(System.lineSeparator());
- build.append(" ");
- build.append(" ");
- build.append(constr.getBody());
- build.append(System.lineSeparator());
- build.append(" ");
- build.append("}");
- build.append(System.lineSeparator());
- build.append(System.lineSeparator());
- }
-
- if (!constructors.isEmpty())
- out.write(build.toString().toCharArray());
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-
-import com.google.common.collect.Lists;
-
-import freemarker.core.Environment;
-import freemarker.template.SimpleSequence;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add fields to freemarker template.
- */
-public class FieldsDirectiveProg implements TemplateDirectiveModel {
-
- private static final String OBJECT = "object";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
- Object object = params.get(OBJECT);
- List<Field> fields = Lists.newArrayList();
-
- if (object != null) {
- if (object instanceof SimpleSequence)
- fields = ((SimpleSequence) object).toList();
- else if (object instanceof FtlTemplate) {
- fields = ((FtlTemplate) object).getFields();
- } else
- throw new IllegalArgumentException(
- "Object must be a SimpleSequence or instance of "
- + FtlTemplate.class + "but was "
- + object.getClass());
- }
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder();
- for (Field field : fields) {
- build.append(" private ");
- for (String mod : field.getModifiers()) {
- build.append(mod + " ");
- }
- build.append(field.getType() + " ");
- build.append(field.getName());
- if (field.getDefinition() != null)
- build.append(" = " + field.getDefinition());
- build.append(";");
- build.append(System.lineSeparator());
- }
-
- if (!fields.isEmpty())
- out.write(build.toString().toCharArray());
- }
-
- // String templateStr = "Hello ${user}";
- // Template t = new Template("name", new StringReader(templateStr), new
- // Configuration());
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.Writer;
-import java.util.Map;
-
-import com.google.common.collect.Maps;
-
-import freemarker.core.Environment;
-import freemarker.template.Configuration;
-import freemarker.template.Template;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add fields to freemarker template.
- */
-public class FieldsDirectiveTemplate implements TemplateDirectiveModel {
-
- private static final String OBJECT = "object";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
- Object object = params.get(OBJECT);
-
- // TODO check type
-
- String templateStr = " <#list fields as field>"
- + "private <#if field.final==true>final </#if> <#if field.static==true>static </#if>"
- + "${field.type} ${field.name}<#if field.definition??> = ${field.definition}</#if>;"
- + System.lineSeparator() + " </#list>";
- Template t = new Template("name", new StringReader(templateStr),
- new Configuration());
-
- try {
- Map<String, Object> map = Maps.newHashMap();
- map.put("fields", object);
- Writer out = env.getOut();
- t.process(map, out);
- } catch (TemplateException e) {
- throw new IllegalStateException(
- "Template error while generating fields" + e);
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Date;
-import java.util.Map;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-
-import com.google.common.base.Preconditions;
-
-import freemarker.core.Environment;
-import freemarker.ext.beans.StringModel;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add annotations to freemarker template.
- */
-public class HeaderDirective implements TemplateDirectiveModel {
-
- private static final String GENERATOR_CLASS = JMXGenerator.class
- .getCanonicalName();
- private static final String OBJECT = "header";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
-
- // FIXME do not allow null header
- // Preconditions.checkNotNull(object, "Null type declaration");
- Object object = params.get(OBJECT);
- Header header = null;
- if (object != null) {
- object = ((StringModel) object).getWrappedObject();
- Preconditions.checkArgument(object instanceof Header,
- "Template header should be instance of " + Header.class
- + " but was " + object.getClass());
-
- header = (Header) object;
- }
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder();
- build.append("/**");
- build.append(System.lineSeparator());
- build.append("* ");
- build.append("Generated file");
- build.append(System.lineSeparator());
- build.append(System.lineSeparator());
- build.append("* ");
- build.append("Generated from: ");
- build.append(header != null ? header.toString() : "");
- build.append(System.lineSeparator());
- build.append("* ");
- build.append("Generated by: " + GENERATOR_CLASS);
- build.append(System.lineSeparator());
- build.append("* ");
- build.append("Generated at: " + new Date());
- build.append(System.lineSeparator());
- build.append("* ");
- build.append(System.lineSeparator());
- build.append("* ");
- build.append("Do not modify this file unless it is present under src/main directory ");
- build.append(System.lineSeparator());
- build.append("*/");
- build.append(System.lineSeparator());
-
- out.write(build.toString().toCharArray());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Map;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-
-import freemarker.core.Environment;
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add javadoc to freemarker template as String.
- */
-public class JavadocDirective implements TemplateDirectiveModel {
-
- private static final String OBJECT = "object";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
- Object object = params.get(OBJECT);
- String javadoc = "";
-
- if (object != null) {
- if (object instanceof SimpleScalar)
- javadoc = ((SimpleScalar) object).getAsString();
- else if (object instanceof FtlTemplate) {
- javadoc = ((FtlTemplate) object).getJavadoc();
- } else
- throw new IllegalArgumentException(
- "Object must be a String or instance of "
- + FtlTemplate.class + "but was "
- + object.getClass());
- }
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder();
- writeJavadoc(build, javadoc, "");
- out.write(build.toString().toCharArray());
- }
-
- static void writeJavadoc(StringBuilder build, String javadoc,
- String linePrefix) {
- build.append(linePrefix + "/**");
- build.append(System.lineSeparator());
- build.append(linePrefix + "* ");
- build.append(javadoc == null ? "" : javadoc);
- build.append(System.lineSeparator());
- build.append(linePrefix + "*/");
- build.append(System.lineSeparator());
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-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.MethodDeclaration;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-
-import com.google.common.collect.Lists;
-
-import freemarker.core.Environment;
-import freemarker.template.SimpleSequence;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add annotations to freemarker template.
- */
-public class MethodsDirective implements TemplateDirectiveModel {
-
- private static final String OBJECT = "object";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
- Object object = params.get(OBJECT);
- List<? extends Method> methods = Lists.newArrayList();
-
- if (object != null) {
- if (object instanceof SimpleSequence)
- methods = ((SimpleSequence) object).toList();
- else if (object instanceof FtlTemplate) {
- methods = ((FtlTemplate) object).getMethods();
- } else
- throw new IllegalArgumentException(
- "Object must be a SimpleSequence or instance of "
- + FtlTemplate.class + "but was "
- + object.getClass());
- }
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder();
- for (Method method : methods) {
- if (method.getJavadoc() != null)
- JavadocDirective.writeJavadoc(build, method.getJavadoc(), " ");
-
- if (!method.getAnnotations().isEmpty()) {
- AnnotationsDirective.writeAnnotations(method.getAnnotations(),
- build, " ");
- }
-
- build.append(" " + "public ");
- for (String mod : method.getModifiers()) {
- build.append(mod + " ");
- }
- build.append(method.getReturnType() + " ");
-
- build.append(method.getName() + "(");
- for (Field param : method.getParameters()) {
- for (String mod : param.getModifiers()) {
- build.append(mod + " ");
- }
- build.append(param.getType() + " ");
- build.append(param.getName() + ", ");
- }
- if (method.getParameters().isEmpty())
- build.append(")");
- else {
- build.deleteCharAt(build.length() - 1);
- build.deleteCharAt(build.length() - 1);
- build.append(')');
- }
-
- if (method instanceof MethodDeclaration) {
- build.append(";");
- build.append(System.lineSeparator());
- } else if (method instanceof MethodDefinition) {
- if (!((MethodDefinition) method).getThrowsExceptions()
- .isEmpty())
- build.append(" throws ");
- for (String ex : ((MethodDefinition) method)
- .getThrowsExceptions()) {
- build.append(ex + " ");
- }
- build.append(" {");
- build.append(System.lineSeparator());
- build.append(" ");
- build.append(((MethodDefinition) method).getBody());
- build.append(System.lineSeparator());
- build.append(" ");
- build.append("}");
- build.append(System.lineSeparator());
- }
- build.append(System.lineSeparator());
-
- }
-
- if (!methods.isEmpty())
- out.write(build.toString().toCharArray());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.controller.config.api.JmxAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.AbstractModuleTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.ModuleField;
-
-import com.google.common.collect.Lists;
-
-import freemarker.core.Environment;
-import freemarker.template.SimpleSequence;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add annotations to freemarker template.
- */
-public class ModuleFieldsDirective implements TemplateDirectiveModel {
-
- private static final String OBJECT = "moduleFields";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
- Object object = params.get(OBJECT);
- List<ModuleField> fields = Lists.newArrayList();
-
- if (object != null) {
- if (object instanceof SimpleSequence)
- fields = ((SimpleSequence) object).toList();
- else if (object instanceof AbstractModuleTemplate) {
- fields = ((AbstractModuleTemplate) object).getModuleFields();
- } else
- throw new IllegalArgumentException(
- "Object must be a SimpleSequence or instance of "
- + AbstractModuleTemplate.class + "but was "
- + object.getClass());
- }
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder();
- for (ModuleField field : fields) {
- build.append(" ");
- build.append("protected final "
- + JmxAttribute.class.getCanonicalName() + " "
- + field.getName() + "JmxAttribute = new "
- + JmxAttribute.class.getCanonicalName() + "(\""
- + field.getAttributeName() + "\");");
- build.append(System.lineSeparator());
-
- build.append(" private ");
- for (String mod : field.getModifiers()) {
- build.append(mod + " ");
- }
- build.append(field.getType() + " ");
- build.append(field.getName());
- if (field.getNullableDefault() != null)
- build.append(" = " + field.getNullableDefault());
- build.append(";");
-
- if (field.isDependent()) {
- String comment = field.getDependency().isMandatory() ? "mandatory"
- : "optional";
- build.append(" // " + comment);
- }
- build.append(System.lineSeparator());
-
- build.append(System.lineSeparator());
-
- }
-
- if (!fields.isEmpty())
- out.write(build.toString().toCharArray());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Collection;
-import java.util.Map;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.TypeDeclaration;
-
-import com.google.common.base.Preconditions;
-
-import freemarker.core.Environment;
-import freemarker.ext.beans.StringModel;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add type declaration to freemarker template.
- */
-public class TypeDeclarationDirective implements TemplateDirectiveModel {
-
- private static final String OBJECT = "object";
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
- Object object = params.get(OBJECT);
- Preconditions.checkNotNull(object, "Null type declaration");
-
- object = ((StringModel) object).getWrappedObject();
- Preconditions.checkArgument(
- object instanceof TypeDeclaration,
- "Type declaration should be instance of "
- + TypeDeclaration.class + " but was "
- + object.getClass());
-
- TypeDeclaration type = (TypeDeclaration) object;
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder("public ");
- if (type.isAbstract())
- build.append("abstract ");
- if (type.isFinal())
- build.append("final ");
- build.append(type.getType() + " ");
- build.append(type.getName() + " ");
-
- generateExtendOrImplement(build, "extends", type.getExtended());
-
- generateExtendOrImplement(build, "implements", type.getImplemented());
-
- build.append(System.lineSeparator());
- out.write(build.toString().toCharArray());
- }
-
- private void generateExtendOrImplement(StringBuilder build, String prefix,
- Collection<String> elements) {
- if (elements.isEmpty())
- return;
-
- build.append(prefix + " ");
-
- for (String extended : elements) {
- build.append(extended);
- build.append(", ");
- }
- build.deleteCharAt(build.length() - 1);
- build.deleteCharAt(build.length() - 1);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Map;
-
-import freemarker.core.Environment;
-import freemarker.template.TemplateDirectiveBody;
-import freemarker.template.TemplateDirectiveModel;
-import freemarker.template.TemplateException;
-import freemarker.template.TemplateModel;
-
-/**
- * Add annotations to freemarker template.
- */
-public class UnimplementedExceptionDirective implements TemplateDirectiveModel {
-
- @Override
- public void execute(Environment env, Map params, TemplateModel[] loopVars,
- TemplateDirectiveBody body) throws TemplateException, IOException {
-
- Writer out = env.getOut();
- StringBuilder build = new StringBuilder();
- build.append(" ");
- build.append("throw new "
- + UnsupportedOperationException.class.getCanonicalName()
- + "(\"Unimplemented stub method\");");
- build.append(System.lineSeparator());
-
- out.write(build.toString().toCharArray());
- }
-}
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
+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.yangtools.yang.binding.annotations.ModuleQName;
import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
+import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
+import org.opendaylight.yangtools.yang.common.QName;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
+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;
public class Annotation {
final String name;
return params;
}
+ public static Annotation createFromMap(Class<?> annotationClass, Map<String, String> parameters) {
+ List<Parameter> parameterList = new ArrayList<>();
+ for(Entry<String, String> entry: parameters.entrySet()) {
+ parameterList.add(new Parameter(entry.getKey(), entry.getValue()));
+ }
+ return new Annotation(annotationClass.getCanonicalName(), parameterList);
+ }
+
public static Annotation createDescriptionAnnotation(String description) {
Preconditions.checkNotNull(description,
"Cannot create annotation from null description");
Lists.newArrayList(new Parameter("value", q(description))));
}
+ public static Annotation createModuleQNameANnotation(QName qName) {
+ Map<String, String> parameters = new HashMap<>();
+ parameters.put("namespace", q(qName.getNamespace().toString()));
+ parameters.put("revision", q(qName.getFormattedRevision()));
+ parameters.put("name", q(qName.getLocalName()));
+ return Annotation.createFromMap(ModuleQName.class, parameters);
+ }
+
public static Collection<Annotation> createSieAnnotations(ServiceInterfaceEntry sie){
String exportedClassName = sie.getExportedOsgiClassName();
private static final String quote = "\"";
- private static String q(String nullableDescription) {
+ public static String q(String nullableDescription) {
return nullableDescription == null ? null : quote + nullableDescription
+ quote;
}
}
}
+ @Override
+ public String toString() {
+ return AnnotationSerializer.toString(this);
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
+
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation.Parameter;
+
+class AnnotationSerializer {
+
+ static String toString(Annotation annotation) {
+ StringBuilder builder = new StringBuilder();
+ builder.append("@");
+ builder.append(annotation.getName());
+ if (!annotation.getParams().isEmpty()) {
+ builder.append("(");
+ for (Parameter param : annotation.getParams()) {
+ builder.append(param.getKey());
+ builder.append(" = ");
+ builder.append(fixString(param.getValue()));
+ builder.append(", ");
+ }
+ builder.setCharAt(builder.length() - 2, ')');
+ }
+ builder.append("\n");
+ return builder.toString();
+ }
+
+ private static String fixString(String value) {
+ // TODO replace with compress single line if possible
+ return value.replaceAll("\\r\\n|\\r|\\n", " ").replaceAll(" +", " ");
+ }
+
+}
return isPublic;
}
+ @Override
+ public String toString() {
+ return ConstructorSerializer.toString(this);
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
+
+public class ConstructorSerializer {
+
+ public static String toString(Constructor constr) {
+ StringBuilder build = new StringBuilder();
+ build.append(" ");
+ if (constr.isPublic()) {
+ build.append("public ");
+ }
+ build.append(constr.getTypeName() + " ");
+ build.append("() {");
+ build.append("\n");
+ build.append(" ");
+ build.append(" ");
+ build.append(constr.getBody());
+ build.append("\n");
+ build.append(" ");
+ build.append("}");
+ build.append("\n");
+ build.append("\n");
+ return build.toString();
+ }
+}
import java.util.List;
+import static com.google.common.base.Preconditions.checkNotNull;
+
public class Field {
private final String type;
private final String name;
}
public Field(List<String> modifiers, String type, String name,
- String definition, boolean needsDepResolver) {
- this.modifiers = modifiers;
- this.type = type;
- this.name = name;
- this.definition = definition;
+ String nullableDefinition, boolean needsDepResolver) {
+ this.modifiers = checkNotNull(modifiers);
+ this.type = checkNotNull(type);
+ this.name = checkNotNull(name);
+ this.definition = nullableDefinition;
this.needsDepResolver = needsDepResolver;
}
return type;
}
+ public String getGenericInnerType() {
+ return type.substring(type.indexOf("<") + 1, type.indexOf(">"));
+ }
+
public List<String> getModifiers() {
return modifiers;
}
public boolean isArray() {
return type.endsWith("[]");
}
+
+ @Override
+ public String toString() {
+ return FieldSerializer.toString(this);
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
+
+public class FieldSerializer {
+
+ public static String toString(Field field) {
+ StringBuilder build = new StringBuilder();
+ build.append("private ");
+ for (String mod : field.getModifiers()) {
+ build.append(mod + " ");
+ }
+ build.append(field.getType() + " ");
+ build.append(field.getName());
+ if (field.getDefinition() != null) {
+ build.append(" = " + field.getDefinition());
+ }
+ build.append(";");
+ build.append("\n");
+ return build.toString();
+ }
+}
@Override
public String toString() {
- return "yang module name: " + yangModuleName + " "
- + " yang module local name: " + yangModuleLocalName;
+ return HeaderSerializer.toString(this);
}
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
+
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator;
+
+import java.util.Date;
+
+public class HeaderSerializer {
+ private static final String GENERATOR_CLASS = JMXGenerator.class.getCanonicalName();
+
+ public static String toString(Header header) {
+ StringBuilder build = new StringBuilder();
+
+
+ build.append("Generated file");
+ build.append("\n");
+ build.append("\n");
+ build.append("Generated from: ");
+ //build.append(header.toString());
+
+ build.append("yang module name: ");
+ build.append(header.getYangModuleName());
+ build.append(" yang module local name: ");
+ build.append(header.getYangModuleLocalName());
+
+ build.append("\n");
+ build.append("Generated by: " + GENERATOR_CLASS);
+ build.append("\n");
+ build.append("Generated at: " + new Date());
+ build.append("\n");
+ build.append("\n");
+ build.append("Do not modify this file unless it is present under src/main directory ");
+
+ return build.toString();
+ }
+
+}
public List<String> getModifiers() {
return Collections.emptyList();
}
+
+ @Override
+ public String toString() {
+ return MethodSerializer.toString(this);
+ }
}
public List<String> getModifiers() {
return modifiers;
}
+
+ @Override
+ public String toString() {
+ return MethodSerializer.toString(this);
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
+
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
+
+class MethodSerializer {
+
+ static String toString(Method method) {
+ StringBuilder build = new StringBuilder();
+ if (method.getJavadoc() != null) {
+ build.append(StringUtil.writeComment(method.getJavadoc(), true));
+ }
+
+ for(Annotation a: method.getAnnotations()) {
+ build.append(a);
+ }
+
+ build.append(" " + "public ");
+ for (String mod : method.getModifiers()) {
+ build.append(mod + " ");
+ }
+ build.append(method.getReturnType() + " ");
+
+ build.append(method.getName() + "(");
+ for (Field param : method.getParameters()) {
+ for (String mod : param.getModifiers()) {
+ build.append(mod + " ");
+ }
+ build.append(param.getType() + " ");
+ build.append(param.getName() + ", ");
+ }
+ if (method.getParameters().isEmpty()) {
+ build.append(")");
+ } else {
+ build.deleteCharAt(build.length() - 1);
+ build.deleteCharAt(build.length() - 1);
+ build.append(')');
+ }
+
+ if (method instanceof MethodDeclaration) {
+ build.append(";");
+ build.append("\n");
+ } else if (method instanceof MethodDefinition) {
+ if (!((MethodDefinition) method).getThrowsExceptions()
+ .isEmpty()) {
+ build.append(" throws ");
+ }
+ for (String ex : ((MethodDefinition) method)
+ .getThrowsExceptions()) {
+ build.append(ex + " ");
+ }
+ build.append(" {");
+ build.append("\n");
+ build.append(" ");
+ build.append(((MethodDefinition) method).getBody());
+ build.append("\n");
+ build.append(" ");
+ build.append("}");
+ build.append("\n");
+ }
+ build.append("\n");
+ return build.toString();
+ }
+}
return false;
}
+ @Override
+ public String toString() {
+ return ModuleFieldSerializer.toString(this);
+ }
+
public Dependency getDependency() {
return dependency;
}
return attributeName;
}
+
+ public boolean isList() {
+ return getType().startsWith("java.util.List");
+ }
+
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
+
+import org.opendaylight.controller.config.api.JmxAttribute;
+
+public class ModuleFieldSerializer {
+
+
+ public static String toString(ModuleField moduleField) {
+ StringBuilder builder = new StringBuilder();
+ builder.append(" ");
+ builder.append("protected final "
+ + JmxAttribute.class.getCanonicalName() + " "
+ + moduleField.getName() + "JmxAttribute = new "
+ + JmxAttribute.class.getCanonicalName() + "(\""
+ + moduleField.getAttributeName() + "\");");
+ builder.append("\n");
+
+ builder.append(" private ");
+ for (String mod : moduleField.getModifiers()) {
+ builder.append(mod + " ");
+ }
+ builder.append(moduleField.getType() + " ");
+ builder.append(moduleField.getName());
+ if (moduleField.getNullableDefault() != null) {
+ builder.append(" = " + moduleField.getNullableDefault());
+ }
+ builder.append(";");
+
+ if (moduleField.isDependent()) {
+ String comment = moduleField.getDependency().isMandatory() ? "mandatory"
+ : "optional";
+ builder.append(" // " + comment);
+ }
+ builder.append("\n");
+
+ builder.append("\n");
+
+ return builder.toString();
+ }
+}
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
+
import java.util.List;
public class TypeDeclaration {
return implemented;
}
+ public TypeName toTypeName() {
+ if ("interface".equals(type)) {
+ return TypeName.interfaceType;
+ } else if ("class".equals(type)) {
+ if (isAbstract) {
+ return TypeName.absClassType;
+ } else if (isFinal) {
+ return TypeName.finalClassType;
+ } else {
+ return TypeName.classType;
+ }
+ } else if ("enum".equals(type)) {
+ return TypeName.enumType;
+ } else {
+ throw new IllegalStateException("Type not supported: " + type);
+ }
+ }
+
@Override
public String toString() {
return "TypeDeclaration{" + "type='" + type + '\'' + ", name='" + name
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory
+import com.google.common.base.Optional
+import org.opendaylight.controller.config.api.DependencyResolver
+import org.opendaylight.controller.config.api.DynamicMBeanWithInstance
+import org.opendaylight.controller.config.api.ModuleIdentifier
+import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface
+import org.opendaylight.controller.config.api.annotations.Description
+import org.opendaylight.controller.config.spi.Module
+import org.opendaylight.controller.config.spi.ModuleFactory
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.AbstractFactoryTemplate
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.*
+import org.opendaylight.yangtools.yang.common.QName
+import org.osgi.framework.BundleContext
+
+public class AbsFactoryGeneratedObjectFactory {
+
+ public GeneratedObject toGeneratedObject(ModuleMXBeanEntry mbe, Optional<String> copyright) {
+ FullyQualifiedName absFactoryFQN = new FullyQualifiedName(mbe.packageName, mbe.abstractFactoryName)
+ FullyQualifiedName moduleFQN = new FullyQualifiedName(mbe.packageName, mbe.stubModuleName)
+ Optional<String> classJavaDoc = Optional.fromNullable(mbe.getNullableDescription())
+
+ AbstractFactoryTemplate abstractFactoryTemplate = TemplateFactory.abstractFactoryTemplateFromMbe(mbe)
+ Optional<String> header = abstractFactoryTemplate.headerString;
+ List<FullyQualifiedName> providedServices = mbe.providedServices.keySet().collect {
+ FullyQualifiedName.fromString(it)
+ }
+
+
+ return toGeneratedObject(absFactoryFQN, copyright,
+ header, classJavaDoc, mbe.yangModuleQName,
+ mbe.globallyUniqueName,
+ providedServices,
+ moduleFQN,
+ abstractFactoryTemplate.fields)
+ }
+
+ public GeneratedObject toGeneratedObject(FullyQualifiedName absFactoryFQN, Optional<String> copyright,
+ Optional<String> header, Optional<String> classJavaDoc, QName yangModuleQName,
+ String globallyUniqueName,
+ List<FullyQualifiedName> providedServices,
+ FullyQualifiedName moduleFQN,
+ List<Field> moduleFields) {
+ JavaFileInputBuilder b = new JavaFileInputBuilder()
+ Annotation moduleQNameAnnotation = Annotation.createModuleQNameANnotation(yangModuleQName)
+ b.addClassAnnotation(moduleQNameAnnotation)
+
+ b.setFqn(absFactoryFQN)
+ b.setTypeName(TypeName.absClassType)
+
+ b.setCopyright(copyright);
+ b.setHeader(header);
+ b.setClassJavaDoc(classJavaDoc);
+ b.addImplementsFQN(new FullyQualifiedName(ModuleFactory))
+ if (classJavaDoc.isPresent()) {
+ b.addClassAnnotation("@${Description.canonicalName}(value=\"${classJavaDoc.get()}\")")
+ }
+
+ b.addToBody("public static final java.lang.String NAME = \"${globallyUniqueName}\";")
+ b.addToBody("private static final java.util.Set<Class<? extends ${AbstractServiceInterface.canonicalName}>> serviceIfcs;")
+
+ b.addToBody("@Override\n public final String getImplementationName() { \n return NAME; \n}")
+
+ b.addToBody(getServiceIfcsInitialization(providedServices))
+
+ // createModule
+ b.addToBody("""
+ @Override
+ public ${Module.canonicalName} createModule(String instanceName, ${DependencyResolver.canonicalName} dependencyResolver, ${BundleContext.canonicalName} bundleContext) {
+ return instantiateModule(instanceName, dependencyResolver, bundleContext);
+ }
+ """)
+
+ b.addToBody(getCreateModule(moduleFQN, moduleFields))
+
+ b.addToBody("""
+ public ${moduleFQN} instantiateModule(String instanceName, ${DependencyResolver.canonicalName} dependencyResolver, ${moduleFQN} oldModule, ${AutoCloseable.canonicalName} oldInstance, ${BundleContext.canonicalName} bundleContext) {
+ return new ${moduleFQN}(new ${ModuleIdentifier.canonicalName}(NAME, instanceName), dependencyResolver, oldModule, oldInstance);
+ }
+ """)
+
+ b.addToBody("""
+ public ${moduleFQN} instantiateModule(String instanceName, ${DependencyResolver.canonicalName} dependencyResolver, ${BundleContext.canonicalName} bundleContext) {
+ return new ${moduleFQN}(new ${ModuleIdentifier.canonicalName}(NAME, instanceName), dependencyResolver);
+ }
+ """)
+
+ b.addToBody("""
+ public ${moduleFQN} handleChangedClass(${DynamicMBeanWithInstance.canonicalName} old) throws Exception {
+ throw new UnsupportedOperationException("Class reloading is not supported");
+ }
+ """)
+
+ b.addToBody("""
+ @Override
+ public java.util.Set<${moduleFQN}> getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory dependencyResolverFactory, ${BundleContext.canonicalName} bundleContext) {
+ return new java.util.HashSet<${moduleFQN}>();
+ }
+ """)
+
+ return new GeneratedObjectBuilder(b.build()).toGeneratedObject()
+ }
+
+ private static String getCreateModule(FullyQualifiedName moduleFQN, List<Field> moduleFields) {
+ String result = """
+ @Override
+ public ${Module.canonicalName} createModule(String instanceName, ${DependencyResolver.canonicalName} dependencyResolver, ${DynamicMBeanWithInstance.canonicalName} old, ${BundleContext.canonicalName} bundleContext) throws Exception {
+ ${moduleFQN} oldModule = null;
+ try {
+ oldModule = (${moduleFQN}) old.getModule();
+ } catch(Exception e) {
+ return handleChangedClass(old);
+ }
+ ${moduleFQN} module = instantiateModule(instanceName, dependencyResolver, oldModule, old.getInstance(), bundleContext);
+ """
+ result += moduleFields.collect{"module.set${it.name}(oldModule.get${it.name}());"}.join("\n")
+ result += """
+ return module;
+ }
+ """
+ return result
+ }
+
+ private static String getServiceIfcsInitialization(List<FullyQualifiedName> providedServices) {
+ String generic = "Class<? extends ${AbstractServiceInterface.canonicalName}>"
+
+ String result = """static {
+ java.util.Set<${generic}> serviceIfcs2 = new java.util.HashSet<${generic}>();
+ """
+ result += providedServices.collect{"serviceIfcs2.add(${it}.class);"}.join("\n")
+ result += """serviceIfcs = java.util.Collections.unmodifiableSet(serviceIfcs2);
+ }
+ """
+
+ // add isModuleImplementingServiceInterface and getImplementedServiceIntefaces methods
+
+ result += """
+ @Override
+ public final boolean isModuleImplementingServiceInterface(Class<? extends ${AbstractServiceInterface.canonicalName}> serviceInterface) {
+ for (Class<?> ifc: serviceIfcs) {
+ if (serviceInterface.isAssignableFrom(ifc)){
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public java.util.Set<Class<? extends ${AbstractServiceInterface.canonicalName}>> getImplementedServiceIntefaces() {
+ return serviceIfcs;
+ }
+ """
+
+ return result
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory
+import com.google.common.base.Optional
+import org.opendaylight.controller.config.api.DependencyResolver
+import org.opendaylight.controller.config.api.ModuleIdentifier
+import org.opendaylight.controller.config.api.annotations.Description
+import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.AbstractModuleTemplate
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.IdentityRefModuleField
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Method
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.ModuleField
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.*
+import org.opendaylight.yangtools.yang.common.QName
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+public class AbsModuleGeneratedObjectFactory {
+
+ public GeneratedObject toGeneratedObject(ModuleMXBeanEntry mbe, Optional<String> copyright) {
+ FullyQualifiedName abstractFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getAbstractModuleName())
+ Optional<String> classJavaDoc = Optional.fromNullable(mbe.getNullableDescription())
+ AbstractModuleTemplate abstractModuleTemplate = TemplateFactory.abstractModuleTemplateFromMbe(mbe)
+ Optional<String> header = abstractModuleTemplate.headerString;
+ List<FullyQualifiedName> implementedInterfaces = abstractModuleTemplate.getTypeDeclaration().getImplemented().collect {
+ FullyQualifiedName.fromString(it)
+ }
+ Optional<FullyQualifiedName> maybeRegistratorType
+ if (abstractModuleTemplate.isRuntime()) {
+ maybeRegistratorType = Optional.of(FullyQualifiedName.fromString(abstractModuleTemplate.getRegistratorType()))
+ } else {
+ maybeRegistratorType = Optional.absent()
+ }
+
+ return toGeneratedObject(abstractFQN, copyright, header, classJavaDoc, implementedInterfaces,
+ abstractModuleTemplate.getModuleFields(), maybeRegistratorType, abstractModuleTemplate.getMethods(),
+ mbe.yangModuleQName
+ )
+ }
+
+ public GeneratedObject toGeneratedObject(FullyQualifiedName abstractFQN,
+ Optional<String> copyright,
+ Optional<String> header,
+ Optional<String> classJavaDoc,
+ List<FullyQualifiedName> implementedInterfaces,
+ List<ModuleField> moduleFields,
+ Optional<FullyQualifiedName> maybeRegistratorType,
+ List<Method> methods,
+ QName yangModuleQName) {
+ JavaFileInputBuilder b = new JavaFileInputBuilder()
+
+ Annotation moduleQNameAnnotation = Annotation.createModuleQNameANnotation(yangModuleQName)
+ b.addClassAnnotation(moduleQNameAnnotation)
+
+ b.setFqn(abstractFQN)
+ b.setTypeName(TypeName.absClassType)
+
+ b.setCopyright(copyright);
+ b.setHeader(header);
+ b.setClassJavaDoc(classJavaDoc);
+ implementedInterfaces.each { b.addImplementsFQN(it) }
+ if (classJavaDoc.isPresent()) {
+ b.addClassAnnotation("@${Description.canonicalName}(value=\"${classJavaDoc.get()}\")")
+ }
+
+ // add logger:
+ b.addToBody(getLogger(abstractFQN));
+
+ b.addToBody("//attributes start");
+
+ b.addToBody(moduleFields.collect { it.toString() }.join("\n"))
+
+ b.addToBody("//attributes end");
+
+
+ b.addToBody(getCommonFields(abstractFQN));
+
+
+ b.addToBody(getNewConstructor(abstractFQN))
+ b.addToBody(getCopyFromOldConstructor(abstractFQN))
+
+ b.addToBody(getRuntimeRegistratorCode(maybeRegistratorType))
+ b.addToBody(getValidationMethods(moduleFields))
+
+ b.addToBody(getCachesOfResolvedDependencies(moduleFields))
+ b.addToBody(getCachesOfResolvedIdentityRefs(moduleFields))
+ b.addToBody(getGetInstance(moduleFields))
+ b.addToBody(getReuseLogic(moduleFields, abstractFQN))
+ b.addToBody(getEqualsAndHashCode(abstractFQN))
+
+ b.addToBody(getMethods(methods))
+
+ return new GeneratedObjectBuilder(b.build()).toGeneratedObject()
+ }
+
+ private static String getMethods(List<Method> methods) {
+ String result = """
+ // getters and setters
+ """
+ result += methods.collect{it.toString()}.join("\n")
+ return result
+ }
+
+ private static String getEqualsAndHashCode(FullyQualifiedName abstractFQN) {
+ return """
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ ${abstractFQN.typeName} that = (${abstractFQN.typeName}) o;
+ return identifier.equals(that.identifier);
+ }
+
+ @Override
+ public int hashCode() {
+ return identifier.hashCode();
+ }
+ """
+ }
+
+ private static String getReuseLogic(List<ModuleField> moduleFields, FullyQualifiedName abstractFQN) {
+ String result = """
+ public boolean canReuseInstance(${abstractFQN.typeName} oldModule){
+ // allow reusing of old instance if no parameters was changed
+ return isSame(oldModule);
+ }
+
+ public ${AutoCloseable.canonicalName} reuseInstance(${AutoCloseable.canonicalName} oldInstance){
+ // implement if instance reuse should be supported. Override canReuseInstance to change the criteria.
+ return oldInstance;
+ }
+ """
+ // isSame method that detects changed fields
+ result += """
+ public boolean isSame(${abstractFQN.typeName} other) {
+ if (other == null) {
+ throw new IllegalArgumentException("Parameter 'other' is null");
+ }
+ """
+ // loop through fields, do deep equals on each field
+ result += moduleFields.collect { field ->
+ if (field.isListOfDependencies()) {
+ return """
+ if (${field.name}Dependency.equals(other.${field.name}Dependency) == false) {
+ return false;
+ }
+ for (int idx = 0; idx < ${field.name}Dependency.size(); idx++) {
+ if (${field.name}Dependency.get(idx) != other.${field.name}Dependency.get(idx)) {
+ return false;
+ }
+ }
+ """
+ } else if (field.isDependent()) {
+ return """
+ if (${field.name}Dependency != other.${field.name}Dependency) { // reference to dependency must be same
+ return false;
+ }
+ """
+ } else {
+ return """
+ if (java.util.Objects.deepEquals(${field.name}, other.${field.name}) == false) {
+ return false;
+ }
+ """
+ }
+ }.join("\n")
+
+
+ result += """
+ return true;
+ }
+ """
+
+ return result
+ }
+
+ private static String getGetInstance(List<ModuleField> moduleFields) {
+ String result = """
+ @Override
+ public final ${AutoCloseable.canonicalName} getInstance() {
+ if(instance==null) {
+ """
+ // create instance start
+
+ // loop through dependent fields, use dependency resolver to instantiate dependencies. Do it in loop in case field represents list of dependencies.
+ Map<ModuleField, String> resolveDependenciesMap = moduleFields.findAll {
+ it.isDependent()
+ }.collectEntries { ModuleField field ->
+ [field, field.isList() ?
+ """
+ ${field.name}Dependency = new java.util.ArrayList<${field.dependency.sie.exportedOsgiClassName}>();
+ for(javax.management.ObjectName dep : ${field.name}) {
+ ${field.name}Dependency.add(dependencyResolver.resolveInstance(${
+ field.dependency.sie.exportedOsgiClassName
+ }.class, dep, ${field.name}JmxAttribute));
+ }
+ """
+ :
+ """
+ ${field.name}Dependency = dependencyResolver.resolveInstance(${
+ field.dependency.sie.exportedOsgiClassName
+ }.class, ${field.name}, ${field.name}JmxAttribute);
+ """
+ ]
+ }
+ // wrap each field resolvation statement with if !=null when dependency is not mandatory
+ def wrapWithNullCheckClosure = {Map<ModuleField, String> map, predicate -> map.collect { ModuleField key, String value ->
+ predicate(key) ? """
+ if(${key.name}!=null) {
+ ${value}
+ }
+ """ : value
+ }.join("\n")
+ }
+
+ result += wrapWithNullCheckClosure(resolveDependenciesMap, {ModuleField key ->
+ key.getDependency().isMandatory() == false} )
+
+ // add code to inject dependency resolver to fields that support it
+ Map<ModuleField, String> injectDepsMap = moduleFields.findAll { it.needsDepResolver }.collectEntries { field ->
+ if (field.isList()) {
+ return [field,"""
+ for(${field.genericInnerType} candidate : ${field.name}) {
+ candidate.injectDependencyResolver(dependencyResolver);
+ }
+ """]
+ } else {
+ return [field, "${field.name}.injectDependencyResolver(dependencyResolver);"]
+ }
+ }
+
+ result += wrapWithNullCheckClosure(injectDepsMap, {true})
+
+ // identity refs need to be injected with dependencyResolver and base class
+ Map<ModuleField, String> resolveIdentityMap = moduleFields.findAll { it.isIdentityRef() }.collectEntries { IdentityRefModuleField field ->
+ [field,
+ "set${field.attributeName}(${field.name}.resolveIdentity(dependencyResolver, ${field.identityBaseClass}.class));"]
+ }
+
+ result += wrapWithNullCheckClosure(resolveIdentityMap, {true})
+
+ // create instance end: reuse and recreate logic
+ result += """
+ if(oldInstance!=null && canReuseInstance(oldModule)) {
+ instance = reuseInstance(oldInstance);
+ } else {
+ if(oldInstance!=null) {
+ try {
+ oldInstance.close();
+ } catch(Exception e) {
+ logger.error("An error occurred while closing old instance " + oldInstance, e);
+ }
+ }
+ instance = createInstance();
+ if (instance == null) {
+ throw new IllegalStateException("Error in createInstance - null is not allowed as return value");
+ }
+ }
+ }
+ return instance;
+ }
+ public abstract ${AutoCloseable.canonicalName} createInstance();
+ """
+ return result
+ }
+
+ private static String getCommonFields(FullyQualifiedName abstractFQN) {
+ return """
+ private final ${abstractFQN.typeName} oldModule;
+ private final ${AutoCloseable.canonicalName} oldInstance;
+ private ${AutoCloseable.canonicalName} instance;
+ private final ${DependencyResolver.canonicalName} dependencyResolver;
+ private final ${ModuleIdentifier.canonicalName} identifier;
+ @Override
+ public ${ModuleIdentifier.canonicalName} getIdentifier() {
+ return identifier;
+ }
+ """
+ }
+
+ private static String getCachesOfResolvedIdentityRefs(List<ModuleField> moduleFields) {
+ return moduleFields.findAll { it.isIdentityRef() }.collect { IdentityRefModuleField field ->
+ "private ${field.identityClassType} ${field.identityClassName};"
+ }.join("\n")
+ }
+
+ private static String getCachesOfResolvedDependencies(List<ModuleField> moduleFields) {
+ return moduleFields.findAll { it.dependent }.collect { field ->
+ if (field.isList()) {
+ return """
+ private java.util.List<${field.dependency.sie.exportedOsgiClassName}> ${
+ field.name
+ }Dependency = new java.util.ArrayList<${field.dependency.sie.exportedOsgiClassName}>();
+ protected final java.util.List<${field.dependency.sie.exportedOsgiClassName}> get${
+ field.attributeName
+ }Dependency(){
+ return ${field.name}Dependency;
+ }
+ """
+ } else {
+ return """
+ private ${field.dependency.sie.exportedOsgiClassName} ${field.name}Dependency;
+ protected final ${field.dependency.sie.exportedOsgiClassName} get${field.attributeName}Dependency(){
+ return ${field.name}Dependency;
+ }
+ """
+ }
+ }.join("\n")
+ }
+
+ private static String getRuntimeRegistratorCode(Optional<FullyQualifiedName> maybeRegistratorType) {
+ if (maybeRegistratorType.isPresent()) {
+ String registratorType = maybeRegistratorType.get()
+
+ return """
+ private ${registratorType} rootRuntimeBeanRegistratorWrapper;
+
+ public ${registratorType} getRootRuntimeBeanRegistratorWrapper(){
+ return rootRuntimeBeanRegistratorWrapper;
+ }
+
+ @Override
+ public void setRuntimeBeanRegistrator(${RootRuntimeBeanRegistrator.canonicalName} rootRuntimeRegistrator){
+ this.rootRuntimeBeanRegistratorWrapper = new ${registratorType}(rootRuntimeRegistrator);
+ }
+ """
+ } else {
+ return ""
+ }
+ }
+
+ private static String getValidationMethods(List<ModuleField> moduleFields) {
+ String result = """
+ @Override
+ public void validate() {
+ """
+ // validate each mandatory dependency
+ List<String> lines = moduleFields.findAll{(it.dependent && it.dependency.mandatory)}.collect { field ->
+ if (field.isList()) {
+ return "" +
+ "for(javax.management.ObjectName dep : ${field.name}) {\n" +
+ " dependencyResolver.validateDependency(${field.dependency.sie.fullyQualifiedName}.class, dep, ${field.name}JmxAttribute);\n" +
+ "}\n"
+ } else {
+ return "dependencyResolver.validateDependency(${field.dependency.sie.fullyQualifiedName}.class, ${field.name}, ${field.name}JmxAttribute);"
+ }
+ }
+ result += lines.findAll { it.isEmpty() == false }.join("\n")
+ result += """
+ customValidation();
+ }
+
+ protected void customValidation(){
+ }
+ """
+ return result
+ }
+
+ private static String getLogger(FullyQualifiedName fqn) {
+ return "private static final ${Logger.canonicalName} logger = ${LoggerFactory.canonicalName}.getLogger(${fqn.toString()}.class);"
+ }
+
+ // assumes that each parameter name corresponds to an field in this class, constructs lines setting this.field = field;
+ private static String getConstructorStart(FullyQualifiedName fqn,
+ LinkedHashMap<String, String> parameters, String after) {
+ return "public ${fqn.typeName}(" +
+ parameters.collect { it.key + " " + it.value }.join(",") +
+ ") {\n" +
+ parameters.values().collect { "this.${it}=${it};\n" }.join() +
+ after +
+ "}\n"
+ }
+
+ private static String getNewConstructor(FullyQualifiedName abstractFQN) {
+ LinkedHashMap<String, String> parameters = [
+ (ModuleIdentifier.canonicalName): "identifier",
+ (DependencyResolver.canonicalName): "dependencyResolver"
+ ]
+ String setToNulls = ["oldInstance", "oldModule"].collect { "this.${it}=null;\n" }.join()
+ return getConstructorStart(abstractFQN, parameters, setToNulls)
+ }
+
+ private static String getCopyFromOldConstructor(FullyQualifiedName abstractFQN) {
+ LinkedHashMap<String, String> parameters = [
+ (ModuleIdentifier.canonicalName): "identifier",
+ (DependencyResolver.canonicalName): "dependencyResolver",
+ (abstractFQN.typeName): "oldModule",
+ (AutoCloseable.canonicalName): "oldInstance"
+ ]
+ return getConstructorStart(abstractFQN, parameters, "")
+ }
+}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Optional;
+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.FullyQualifiedName;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObjectBuilder;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.JavaFileInputBuilder;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
+
+import java.util.LinkedHashMap;
+
+public class ConcreteModuleGeneratedObjectFactory {
+
+ public GeneratedObject toGeneratedObject(ModuleMXBeanEntry mbe, Optional<String> copyright, Optional<String> header) {
+ FullyQualifiedName concreteFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getStubModuleName());
+ FullyQualifiedName abstractFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getAbstractModuleName());
+ Optional<String> classJavaDoc = Optional.fromNullable(mbe.getNullableDescription());
+ return toGeneratedObject(concreteFQN, abstractFQN, copyright, header, classJavaDoc);
+ }
+
+ GeneratedObject toGeneratedObject(FullyQualifiedName concreteFQN,
+ FullyQualifiedName abstractFQN,
+ Optional<String> copyright,
+ Optional<String> header,
+ Optional<String> classJavaDoc) {
+ // there are two constructors and two methods
+ JavaFileInputBuilder builder = new JavaFileInputBuilder();
+ builder.setTypeName(TypeName.classType);
+ builder.setFqn(concreteFQN);
+ builder.addExtendsFQN(abstractFQN);
+
+ builder.setCopyright(copyright);
+ builder.setHeader(header);
+ builder.setClassJavaDoc(classJavaDoc);
+
+ builder.addToBody(getNewCtor(concreteFQN));
+ builder.addToBody(getCopyCtor(concreteFQN));
+ builder.addToBody(getCustomValidationStub());
+ builder.addToBody(getCreateInstanceStub());
+
+ return new GeneratedObjectBuilder(builder.build()).toGeneratedObject();
+ }
+
+ private static String getNewCtor(FullyQualifiedName fqn) {
+ LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>(){
+ {
+ put(ModuleIdentifier.class.getCanonicalName(), "identifier");
+ put(DependencyResolver.class.getCanonicalName(), "dependencyResolver");
+ }
+ };
+ StringBuilder stringBuilder = getCtor(fqn, parameters);
+ return stringBuilder.toString();
+ }
+
+ private static StringBuilder getCtor(FullyQualifiedName fqn , LinkedHashMap<String, String> parameters) {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append("public ").append(fqn.getTypeName()).append("(");
+ // parameters
+ stringBuilder.append(Joiner.on(", ").withKeyValueSeparator(" ").join(parameters));
+ stringBuilder.append(") {\n");
+ if (parameters.isEmpty() == false) {
+ stringBuilder.append("super(");
+ stringBuilder.append(Joiner.on(", ").join(parameters.values()));
+ stringBuilder.append(");\n");
+ }
+ stringBuilder.append("}");
+ return stringBuilder;
+ }
+
+ private static String getCopyCtor(final FullyQualifiedName fqn) {
+ LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>(){
+ {
+ put(ModuleIdentifier.class.getCanonicalName(), "identifier");
+ put(DependencyResolver.class.getCanonicalName(), "dependencyResolver");
+ put(fqn.toString(), "oldModule");
+ put(AutoCloseable.class.getCanonicalName(), "oldInstance");
+ }
+ };
+ StringBuilder stringBuilder = getCtor(fqn, parameters);
+ return stringBuilder.toString();
+ }
+
+ private static String getCustomValidationStub() {
+ return "@Override\n" +
+ "public void customValidation() {\n" +
+ "// add custom validation form module attributes here.\n" +
+ "}";
+ }
+
+ private static String getCreateInstanceStub() {
+ return "@Override\n" +
+ "public " + AutoCloseable.class.getCanonicalName() + " createInstance() {\n" +
+ "// TODO:implement\n" +
+ "throw new " + UnsupportedOperationException.class.getCanonicalName() + "();\n"+
+ "}";
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory
+
+import com.google.common.base.Optional
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObjectBuilder
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.JavaFileInputBuilder
+
+public class GenericGeneratedObjectFactory {
+
+ public GeneratedObject toGeneratedObject(FtlTemplate template, Optional<String> copyright) {
+ JavaFileInputBuilder b = new JavaFileInputBuilder();
+ b.setHeader(template.headerString)
+ b.setFqn(new FullyQualifiedName(template.packageName, template.typeDeclaration.name))
+ b.setClassJavaDoc(template.maybeJavadoc)
+ template.annotations.each { b.addClassAnnotation(it) }
+ // type declaration
+ template.typeDeclaration.extended.each { b.addExtendsFQN(FullyQualifiedName.fromString(it)) }
+ template.typeDeclaration.implemented.each { b.addImplementsFQN(FullyQualifiedName.fromString(it)) }
+ b.setCopyright(copyright);
+ b.setTypeName(template.typeDeclaration.toTypeName())
+ // fields
+ template.fields.each { b.addToBody(it.toString()) }
+ // constructors
+ template.constructors.each { b.addToBody(it.toString()) }
+ // methods
+ template.methods.each { b.addToBody(it.toString()) }
+
+ return new GeneratedObjectBuilder(b.build()).toGeneratedObject();
+ }
+}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+
+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;
+ private final String typeName;
+
+ public FullyQualifiedName(String packageName, String typeName) {
+ this.packageName = checkNotNull(packageName);
+ this.typeName = checkNotNull(typeName);
+ }
+
+ public FullyQualifiedName(Class<?> clazz) {
+ this(clazz.getPackage().getName(), clazz.getSimpleName());
+ }
+
+ public static FullyQualifiedName fromString(String fqn) {
+ Matcher m = Pattern.compile("(.*)\\.([^\\.]+)$").matcher(fqn);
+ if (m.matches()) {
+ return new FullyQualifiedName(m.group(1), m.group(2));
+ } else {
+ return new FullyQualifiedName("", fqn);
+ }
+ }
+
+ public String getPackageName() {
+ return packageName;
+ }
+
+ public String getTypeName() {
+ return typeName;
+ }
+
+ public File toFile(File srcDirectory) {
+ String directory = packageName.replace(".", File.separator);
+ return new File(srcDirectory, directory + File.separator + typeName + ".java");
+ }
+
+
+ @Override
+ public String toString() {
+ if (packageName.isEmpty()){
+ return typeName;
+ }
+ return packageName + "." + typeName;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ FullyQualifiedName that = (FullyQualifiedName) o;
+
+ if (!packageName.equals(that.packageName)) {
+ return false;
+ }
+ if (!typeName.equals(that.typeName)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = packageName.hashCode();
+ result = 31 * result + typeName.hashCode();
+ return result;
+ }
+}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+
+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;
+
+public class GeneratedObject {
+
+ private final FullyQualifiedName fqn;
+ private final String content;
+
+ public GeneratedObject(FullyQualifiedName fqn, String content) {
+ this.fqn = checkNotNull(fqn);
+ this.content = StringUtil.formatJavaSource(checkNotNull(content));
+ }
+
+ public FullyQualifiedName getFQN(){
+ return fqn;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public Optional<Entry<FullyQualifiedName,File>> persist(File srcDirectory, boolean overwrite) throws IOException {
+ File dstFile = fqn.toFile(srcDirectory);
+ if (overwrite == true || dstFile.exists() == false) {
+ FileUtils.write(dstFile, content);
+ return Optional.of(Maps.immutableEntry(fqn, dstFile));
+ } else {
+ return Optional.absent();
+ }
+ }
+
+ public Optional<Entry<FullyQualifiedName,File>> persist(File srcDirectory) throws IOException {
+ return persist(srcDirectory, true);
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "fqn=" + fqn +
+ '}';
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ GeneratedObject that = (GeneratedObject) o;
+
+ if (!fqn.equals(that.fqn)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return fqn.hashCode();
+ }
+}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+
+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;
+
+ public GeneratedObjectBuilder(JavaFileInput input) {
+ this.input = input;
+ }
+
+
+ public GeneratedObject toGeneratedObject() {
+ FullyQualifiedName fqn = input.getFQN();
+ StringBuilder content = new StringBuilder();
+
+
+ content.append(maybeAddComment(input.getCopyright()));
+ content.append(maybeAddComment(input.getHeader()));
+
+ if (input.getFQN().getPackageName().isEmpty() == false) {
+ content.append("package ");
+ content.append(input.getFQN().getPackageName());
+ content.append(";\n");
+ }
+ content.append(maybeAddComment(input.getClassJavaDoc(), true));
+
+ for (String classAnnotation : input.getClassAnnotations()) {
+ content.append(classAnnotation);
+ content.append("\n");
+ }
+
+ content.append("public ");
+ content.append(input.getType());
+ content.append(" ");
+ content.append(input.getFQN().getTypeName());
+ content.append(prefixAndJoin(input.getExtends(), "extends"));
+ content.append(prefixAndJoin(input.getImplements(), "implements"));
+ content.append(" {\n");
+
+ for (String method : input.getBodyElements()) {
+ content.append(method);
+ content.append("\n");
+ }
+
+ content.append("\n}\n");
+
+ return new GeneratedObject(fqn, content.toString());
+ }
+
+ private static String maybeAddComment(Optional<String> comment) {
+ return maybeAddComment(comment, false);
+ }
+
+ private static String maybeAddComment(Optional<String> comment, boolean isJavadoc) {
+
+ if (comment.isPresent()) {
+ String input = comment.get();
+ return StringUtil.writeComment(input, isJavadoc);
+ } else {
+ return "";
+ }
+ }
+
+}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+
+import com.google.common.base.Optional;
+
+import java.util.List;
+
+public interface JavaFileInput {
+
+ FullyQualifiedName getFQN();
+
+ Optional<String> getCopyright();
+
+ Optional<String> getHeader();
+
+ TypeName getType();
+
+ Optional<String> getClassJavaDoc();
+
+ List<String> getClassAnnotations();
+
+ List<FullyQualifiedName> getExtends();
+
+ List<FullyQualifiedName> getImplements();
+
+ List<String> getBodyElements();
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+
+import com.google.common.base.Optional;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+public class JavaFileInputBuilder {
+
+ private Optional<String> copyright = Optional.absent(), header = Optional.absent(), classJavaDoc = Optional.absent();
+
+ private TypeName typeName = TypeName.classType;
+
+ private FullyQualifiedName fqn;
+
+ private final List<String> classAnnotations = new ArrayList<>();
+
+ private final List<FullyQualifiedName> extendsFQNs = new ArrayList<>();
+
+ private final List<FullyQualifiedName> implementsFQNs = new ArrayList<>();
+
+ private final List<String> bodyElements = new ArrayList<>();
+
+ public void addToBody(String element) {
+ bodyElements.add(element + "\n");
+ }
+
+ public void addClassAnnotation(Annotation annotation) {
+ addClassAnnotation(annotation.toString());
+ }
+
+ public void addClassAnnotation(String annotation) {
+ classAnnotations.add(checkNotNull(annotation));
+ }
+
+ public void addExtendsFQN(FullyQualifiedName fqn) {
+ extendsFQNs.add(fqn);
+ }
+
+ public void addImplementsFQN(FullyQualifiedName fqn) {
+ implementsFQNs.add(fqn);
+ }
+
+ public Optional<String> getCopyright() {
+ return copyright;
+ }
+
+ public void setCopyright(Optional<String> copyright) {
+ this.copyright = checkNotNull(copyright);
+ }
+
+ public Optional<String> getHeader() {
+ return header;
+ }
+
+ public void setHeader(Optional<String> header) {
+ this.header = checkNotNull(header);
+ }
+
+
+ public Optional<String> getClassJavaDoc() {
+ return classJavaDoc;
+ }
+
+ public void setClassJavaDoc(Optional<String> classJavaDoc) {
+ this.classJavaDoc = checkNotNull(classJavaDoc);
+ }
+
+
+ public FullyQualifiedName getFqn() {
+ return fqn;
+ }
+
+ public void setFqn(FullyQualifiedName fqn) {
+ this.fqn = fqn;
+ }
+
+ public List<FullyQualifiedName> getExtendsFQNs() {
+ return extendsFQNs;
+ }
+
+
+ public List<FullyQualifiedName> getImplementsFQNs() {
+ return implementsFQNs;
+ }
+
+
+ public TypeName getTypeName() {
+ return typeName;
+ }
+
+ public void setTypeName(TypeName typeName) {
+ this.typeName = typeName;
+ }
+
+
+ public JavaFileInput build() {
+ checkNotNull(copyright);
+ checkNotNull(header);
+ checkNotNull(classJavaDoc);
+ checkNotNull(typeName);
+ checkNotNull(fqn);
+
+ return new JavaFileInput() {
+
+ @Override
+ public FullyQualifiedName getFQN() {
+ return fqn;
+ }
+
+ @Override
+ public Optional<String> getCopyright() {
+ return copyright;
+ }
+
+ @Override
+ public Optional<String> getHeader() {
+ return header;
+ }
+
+ @Override
+ public Optional<String> getClassJavaDoc() {
+ return classJavaDoc;
+ }
+
+ @Override
+ public TypeName getType() {
+ return typeName;
+ }
+
+ @Override
+ public List<FullyQualifiedName> getExtends() {
+ return Collections.unmodifiableList(extendsFQNs);
+ }
+
+ @Override
+ public List<FullyQualifiedName> getImplements() {
+ return Collections.unmodifiableList(implementsFQNs);
+ }
+
+ @Override
+ public List<String> getClassAnnotations() {
+ return Collections.unmodifiableList(classAnnotations);
+ }
+
+ @Override
+ public List<String> getBodyElements() {
+ return Collections.unmodifiableList(bodyElements);
+ }
+ };
+ }
+}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
+
+public enum TypeName {
+
+ classType("class"), interfaceType("interface"), enumType("enum"), absClassType("abstract class"), finalClassType("final class");
+
+ private final String value;
+
+ TypeName(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return value;
+ }
+}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Optional;
+import com.google.common.base.Splitter;
+import com.google.common.base.Strings;
+import org.apache.commons.io.IOUtils;
+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.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import java.util.regex.Pattern;
+
+public class StringUtil {
+ private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
+
+ /**
+ * @param list of strings to be joined by ','
+ * @param prefix e.g. 'extends' or 'implements'
+ */
+ public static String prefixAndJoin(List<FullyQualifiedName> list, String prefix) {
+ if (list.isEmpty()) {
+ return "";
+ }
+ Joiner joiner = Joiner.on(",");
+ return " " + prefix + " " + joiner.join(list);
+ }
+
+ public static String addAsterixAtEachLineStart(String input) {
+ String s = Pattern.compile("^", Pattern.MULTILINE).matcher(input).replaceAll("* ");
+ // remove trailing spaces
+ s = Pattern.compile("\\s+$", Pattern.MULTILINE).matcher(s).replaceAll("");
+ s = ensureEndsWithSingleNewLine(s);
+ return s;
+ }
+
+ private static String ensureEndsWithSingleNewLine(String s) {
+ // .split Only trailing empty strings are skipped.
+ String[] split = s.split("\n");
+ s = Joiner.on("\n").join(split);
+ s = s + "\n";
+ return s;
+ }
+
+ public static String writeComment(String input, boolean isJavadoc) {
+ StringBuilder content = new StringBuilder();
+ content.append("/*");
+ if (isJavadoc) {
+ content.append("*");
+ }
+ content.append("\n");
+
+ content.append(addAsterixAtEachLineStart(input));
+ content.append("*/\n");
+ return content.toString();
+ }
+
+
+ public static Optional<String> loadCopyright() {
+ try (InputStream in = StringUtil.class.getResourceAsStream("/copyright.txt")) {
+ if (in != null) {
+ return Optional.of(IOUtils.toString(in));
+ }
+ } catch (IOException e) {
+ logger.warn("Cannot load copyright.txt", e);
+ }
+ return Optional.absent();
+ }
+
+ public static String formatJavaSource(String input) {
+ Iterable<String> split = Splitter.on("\n").trimResults().split(input);
+
+ int basicIndent = 4;
+ StringBuilder sb = new StringBuilder();
+ int intends = 0, empty = 0;
+ for (String line : split) {
+ intends -= StringUtils.countMatches(line, "}");
+ if (intends < 0) {
+ intends = 0;
+ }
+ if (line.isEmpty() == false) {
+ sb.append(Strings.repeat(" ", basicIndent * intends));
+ sb.append(line);
+ sb.append("\n");
+ empty = 0;
+ } else {
+ empty++; // one empty line is allowed
+ if (empty < 2) {
+ sb.append("\n");
+ }
+ }
+ intends += StringUtils.countMatches(line, "{");
+ }
+ return ensureEndsWithSingleNewLine(sb.toString());
+ }
+
+}
--- /dev/null
+Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+
+This program and the accompanying materials are made available under the
+terms of the Eclipse Public License v1.0 which accompanies this distribution,
+and is available at http://www.eclipse.org/legal/epl-v10.html
+++ /dev/null
-<@headerD header=header/>
-package ${packageName};
-
-<@javadocD object=javadoc/>
-<@annotationsD object=annotations/>
-<#-- class/interface -->
-<@typeDeclarationD object=typeDeclaration/>
-{
-
-<@constructorsD object=constructors>
-</@constructorsD>
-<@fieldsD object=fields/>
-
-<@methodsD object=methods/>
-}
+++ /dev/null
-<@headerD header=header/>
-package ${packageName};
-
-<@javadocD object=javadoc/>
-@org.opendaylight.yangtools.yang.binding.annotations.ModuleQName(namespace="${mbe.getYangModuleQName().getNamespace().toString()}",revision="${mbe.getYangModuleQName().getFormattedRevision()}",name="${mbe.getYangModuleQName().getLocalName()}")
-<@typeDeclarationD object=typeDeclaration/>
-{
-
- public static final java.lang.String NAME = "${globallyUniqueName}";
- private static final java.util.Set<Class<? extends ${abstractServiceInterfaceType}>> serviceIfcs;
- <#if providedServices??>
- static {
- java.util.Set<Class<? extends ${abstractServiceInterfaceType}>> serviceIfcs2 = new java.util.HashSet<Class<? extends ${abstractServiceInterfaceType}>>();
- <#list providedServices as refId>
- serviceIfcs2.add(${refId});
- </#list>
- serviceIfcs = java.util.Collections.unmodifiableSet(serviceIfcs2);
- }
- </#if>
-
- @Override
- public final boolean isModuleImplementingServiceInterface(Class<? extends ${abstractServiceInterfaceType}> serviceInterface) {
- for (Class<?> ifc: serviceIfcs) {
- if (serviceInterface.isAssignableFrom(ifc)){
- return true;
- }
- }
- return false;
- }
-
- @Override
- public java.util.Set<Class<? extends ${abstractServiceInterfaceType}>> getImplementedServiceIntefaces() {
- return serviceIfcs;
- }
-
-
- @Override
- public ${moduleType} createModule(String instanceName, ${dependencyResolverType} dependencyResolver, ${bundleContextType} bundleContext) {
- return instantiateModule(instanceName, dependencyResolver, bundleContext);
- }
-
- @Override
- public ${moduleType} createModule(String instanceName, ${dependencyResolverType} dependencyResolver, ${dynamicMBeanWithInstanceType} old, ${bundleContextType} bundleContext) throws Exception {
- ${moduleInstanceType} oldModule = null;
- try {
- oldModule = (${moduleInstanceType}) old.getModule();
- } catch(Exception e) {
- return handleChangedClass(old);
- }
- ${moduleInstanceType} module = instantiateModule(instanceName, dependencyResolver, oldModule, old.getInstance(), bundleContext);
-
- <#list fields as attr>
- module.set${attr.name}(oldModule.get${attr.name}());
- </#list>
-
- return module;
- }
-
- public ${moduleInstanceType} instantiateModule(String instanceName, ${dependencyResolverType} dependencyResolver, ${moduleInstanceType} oldModule, ${instanceType} oldInstance, ${bundleContextType} bundleContext) {
- return new ${moduleInstanceType}(new ${moduleNameType}(NAME, instanceName), dependencyResolver, oldModule, oldInstance);
- }
-
- public ${moduleInstanceType} instantiateModule(String instanceName, ${dependencyResolverType} dependencyResolver, ${bundleContextType} bundleContext) {
- return new ${moduleInstanceType}(new ${moduleNameType}(NAME, instanceName), dependencyResolver);
- }
-
- @Override
- public final String getImplementationName() {
- return NAME;
- }
-
-
- public ${moduleInstanceType} handleChangedClass(${dynamicMBeanWithInstanceType} old) throws Exception {
- throw new UnsupportedOperationException("Class reloading is not supported");
- }
-
- @Override
- public java.util.Set<${moduleInstanceType}> getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory dependencyResolverFactory, ${bundleContextType} bundleContext) {
- return new java.util.HashSet<${moduleInstanceType}>();
- }
-
-}
+++ /dev/null
-<@headerD header=header/>
-package ${packageName};
-
-<@javadocD object=javadoc/>
-<@annotationsD object=annotations/>
-<@typeDeclarationD object=typeDeclaration/>
-{
- // attributes
- <@moduleFieldsD moduleFields=moduleFields/>
- //attributes end
-
- private static final ${loggerType} logger = ${loggerFactoryType}.getLogger(${typeDeclaration.name}.class);
-
- private final ${typeDeclaration.name} oldModule;
- private final ${instanceType} oldInstance;
- private ${instanceType} instance;
- private final ${dependencyResolverType} dependencyResolver;
- private final ${moduleNameType} identifier;
- <#if runtime=true>
- private ${registratorType} rootRuntimeBeanRegistratorWrapper;
- </#if>
-
- public ${typeDeclaration.name}(${moduleNameType} identifier, ${dependencyResolverType} dependencyResolver) {
- this.identifier = identifier;
- this.dependencyResolver = dependencyResolver;
- this.oldInstance = null;
- this.oldModule = null;
- }
-
- public ${typeDeclaration.name}(${moduleNameType} identifier, ${dependencyResolverType} dependencyResolver, ${typeDeclaration.name} oldModule, ${instanceType} oldInstance) {
- this.identifier = identifier;
- this.dependencyResolver = dependencyResolver;
- this.oldInstance = oldInstance;
- this.oldModule = oldModule;
- }
-
- // getters and setters exported into MXBean
- <@methodsD object=methods/>
-
- <#if runtime=true>
- public ${registratorType} getRootRuntimeBeanRegistratorWrapper(){
- return rootRuntimeBeanRegistratorWrapper;
- }
-
- @Override
- public void setRuntimeBeanRegistrator(${rootRuntimeRegistratorType} rootRuntimeRegistrator){
- this.rootRuntimeBeanRegistratorWrapper = new ${registratorType}(rootRuntimeRegistrator);
- }
- </#if>
-
- @Override
- public void validate(){
- <#list moduleFields as field>
- <#if field.dependent==true && field.dependency.mandatory==true>
- <#if field.type?starts_with("java.util.List")>
- for(javax.management.ObjectName dep : ${field.name}) {
- dependencyResolver.validateDependency(${field.dependency.sie.fullyQualifiedName}.class, dep, ${field.name}JmxAttribute);
- }
- <#else>
- dependencyResolver.validateDependency(${field.dependency.sie.fullyQualifiedName}.class, ${field.name}, ${field.name}JmxAttribute);
- </#if>
- </#if>
- </#list>
- customValidation();
- }
-
- protected void customValidation(){
-
- }
-
- // caches of resolved dependencies
- <#list moduleFields as field>
- <#if field.dependent==true>
- <#if field.type?starts_with("java.util.List")>
- private java.util.List<${field.dependency.sie.exportedOsgiClassName}> ${field.name}Dependency = new java.util.ArrayList<${field.dependency.sie.exportedOsgiClassName}>();
- protected final java.util.List<${field.dependency.sie.exportedOsgiClassName}> get${field.attributeName}Dependency(){
- return ${field.name}Dependency;
- }
- <#else>
- private ${field.dependency.sie.exportedOsgiClassName} ${field.name}Dependency;
- protected final ${field.dependency.sie.exportedOsgiClassName} get${field.attributeName}Dependency(){
- return ${field.name}Dependency;
- }
- </#if>
- </#if>
- </#list>
-
- // caches of resolved IdentityRefs
- <#list moduleFields as field>
- <#if field.identityRef==true>
- private ${field.identityClassType} ${field.identityClassName};
- </#if>
- </#list>
-
- @Override
- public final ${instanceType} getInstance(){
- if(instance==null) {
-
- <#list moduleFields as field>
- <#if field.dependent==true>
- <#if field.dependency.mandatory==false>
- if(${field.name}!=null) {
- </#if>
-
- <#if field.type?starts_with("java.util.List")>
- ${field.name}Dependency = new java.util.ArrayList<${field.dependency.sie.exportedOsgiClassName}>();
- for(javax.management.ObjectName dep : ${field.name}) {
- ${field.name}Dependency.add(dependencyResolver.resolveInstance(${field.dependency.sie.exportedOsgiClassName}.class, dep, ${field.name}JmxAttribute));
- }
- <#else>
- ${field.name}Dependency = dependencyResolver.resolveInstance(${field.dependency.sie.exportedOsgiClassName}.class, ${field.name}, ${field.name}JmxAttribute);
- </#if>
-
- <#if field.dependency.mandatory==false>
- }
- </#if>
- </#if>
-
- <#if field.needsDepResolver==true>
- if(${field.name} != null) {
- <#if field.type?starts_with("java.util.List")>
- for(${field.type?substring(field.type?index_of("<") + 1, field.type?index_of(">"))} candidate : ${field.name}) {
- candidate.injectDependencyResolver(dependencyResolver);
- }
- <#else>
- ${field.name}.injectDependencyResolver(dependencyResolver);
- </#if>
- }
- </#if>
-
- <#if field.identityRef==true>
- if(${field.name} != null) {
- set${field.attributeName}(${field.name}.resolveIdentity(dependencyResolver, ${field.identityBaseClass}.class));
- }
- </#if>
- </#list>
-
- if(oldInstance!=null && canReuseInstance(oldModule)) {
- instance = reuseInstance(oldInstance);
- } else {
- if(oldInstance!=null) {
- try {
- oldInstance.close();
- } catch(Exception e) {
- logger.error("An error occurred while closing old instance " + oldInstance, e);
- }
- }
- instance = createInstance();
- }
- }
- return instance;
- }
-
- @Override
- public ${moduleNameType} getIdentifier() {
- return identifier;
- }
-
- public boolean canReuseInstance(${typeDeclaration.name} oldModule){
- // allow reusing of old instance if no parameters was changed
- return isSame(oldModule);
- }
-
- public ${instanceType} reuseInstance(${instanceType} oldInstance){
- // implement if instance reuse should be supported. Override canReuseInstance to change the criteria.
- return oldInstance;
- }
-
- public abstract ${instanceType} createInstance();
-
- public boolean isSame(${typeDeclaration.name} other) {
- if (other == null) {
- throw new IllegalArgumentException("Parameter 'other' is null");
- }
- <#list moduleFields as field>
- <#if field.dependent==true && field.listOfDependencies == false>
- if (${field.name}Dependency != other.${field.name}Dependency) { // reference to dependency must be same
- return false;
- }
- <#elseif field.listOfDependencies>
- if (${field.name}Dependency.equals(other.${field.name}Dependency) == false) {
- return false;
- }
- for (int idx = 0; idx < ${field.name}Dependency.size(); idx++) {
- if (${field.name}Dependency.get(idx) != other.${field.name}Dependency.get(idx)) {
- return false;
- }
- }
- <#else>
- if (${field.name} == null) {
- if (other.${field.name} != null) {
- return false;
- }
- } else if
- <#if field.array == false>
- (${field.name}.equals(other.${field.name}) == false)
- <#else>
- (java.util.Arrays.equals(${field.name},other.${field.name}) == false)
- </#if>
- {
- return false;
- }
- </#if>
- </#list>
-
- return true;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- ${typeDeclaration.name} that = (${typeDeclaration.name}) o;
-
- return identifier.equals(that.identifier);
- }
-
- @Override
- public int hashCode() {
- return identifier.hashCode();
- }
-}
+++ /dev/null
-<@headerD header=header/>
-package ${packageName};
-
-<@javadocD object=javadoc/>
-<@typeDeclarationD object=typeDeclaration/> {
-
- public ${typeDeclaration.name}(${moduleNameType} identifier, ${dependencyResolverType} dependencyResolver) {
- super(identifier, dependencyResolver);
- }
-
- public ${typeDeclaration.name}(${moduleNameType} identifier, ${dependencyResolverType} dependencyResolver,
- ${typeDeclaration.name} oldModule, ${instanceType} oldInstance) {
-
- super(identifier, dependencyResolver, oldModule, oldInstance);
- }
-
- @Override
- protected void customValidation(){
- // Add custom validation for module attributes here.
- }
-
- @Override
- public ${instanceType} createInstance() {
- //TODO:implement
- <@unimplementedExceptionD/>
- }
-}
*/
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");
+ JMXGenerator.NAMESPACE_TO_PACKAGE_DIVIDER
+ PackageTranslatorTest.EXPECTED_PACKAGE_PREFIX);
map.put(JMXGenerator.MODULE_FACTORY_FILE_BOOLEAN, "false");
- jmxGenerator = new JMXGenerator(new FreeMarkerCodeWriterImpl());
+ jmxGenerator = new JMXGenerator(new CodeWriter());
jmxGenerator.setAdditionalConfig(map);
File targetDir = new File(generatorOutputPath, "target");
generatedResourcesDir = new File(targetDir, "generated-resources");
assertNotNull(template);
}
- private ModuleMXBeanEntry mockMbe(String packageName) {
+ public static ModuleMXBeanEntry mockMbe(String packageName) {
ModuleMXBeanEntry mbe = mock(ModuleMXBeanEntry.class);
Map<String, AttributeIfc> a = Maps.newHashMap();
JavaAttribute attr = mockJavaAttr();
return mbe;
}
- private JavaAttribute mockJavaAttr() {
+ public static JavaAttribute mockJavaAttr() {
JavaAttribute attr = mock(JavaAttribute.class);
Type typeA = mock(Type.class);
doReturn("package").when(typeA).getName();
*/
package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.internal.matchers.StringContains.containsString;
-
-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.FtlFilePersister;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.RuntimeRegistratorFtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FormattingUtil;
+
+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 {
- private final FtlFilePersister ftlFilePersister = new FtlFilePersister();
@Test
public void testRootWithoutAnything() {
FtlTemplate rootFtlFile = createdFtls.get(rootRegistratorName);
assertNotNull(rootFtlFile);
- Map<FtlTemplate, String> serializedFtls = ftlFilePersister
- .serializeFtls(createdFtls.values());
- assertThat(serializedFtls.size(), is(2));
+ assertThat(createdFtls.values().size(), is(2));
}
@Test
Map<String, FtlTemplate> createdFtls = RuntimeRegistratorFtlTemplate
.create(rootRB);
- Map<FtlTemplate, String> serializedFtls = ftlFilePersister
- .serializeFtls(createdFtls.values());
- assertThat(serializedFtls.size(), is(4));
-
- assertThat(
- findRegistrationOutput(createdFtls, grandChildRB,
- serializedFtls), not(containsString(" register(")));
-
- FtlTemplate registrator = createdFtls.get(RuntimeRegistratorFtlTemplate
- .getJavaNameOfRuntimeRegistrator(rootRB));
- FormattingUtil.cleanUpEmptyLinesAndIndent(serializedFtls
- .get(registrator));
-
+ assertThat(createdFtls.values().size(), is(4));
}
-
- private String findRegistrationOutput(Map<String, FtlTemplate> createdFtls,
- RuntimeBeanEntry rb, Map<FtlTemplate, String> serializedFtls) {
- RuntimeRegistratorFtlTemplate rbFtlFile = (RuntimeRegistratorFtlTemplate) createdFtls
- .get(RuntimeRegistratorFtlTemplate.getJavaNameOfRuntimeRegistration(rb.getJavaNamePrefix()));
- assertNotNull(rbFtlFile);
- String unformatted = serializedFtls.get(rbFtlFile);
- assertNotNull(unformatted);
- return FormattingUtil.cleanUpEmptyLinesAndIndent(unformatted);
- }
-
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDeclaration;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FormattingUtil;
-
-import com.google.common.collect.Lists;
-
-public class FtlFilePersisterTest {
- private final FtlFilePersister tested = new FtlFilePersister();
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void testGeneralInterface() {
- String packageName = "pa.cka.ge";
- String name = "GeneralClassImpl";
- List<String> extendedInterfaces = Arrays.asList("List", "Set");
- List<MethodDeclaration> methods = new ArrayList<>();
- methods.add(new MethodDeclaration("String", "executeOperation",
- Collections.<Field> emptyList()));
-
- List<String> mods = Lists.newArrayList();
- List<String> mods2 = Lists.newArrayList("final");
- methods.add(new MethodDeclaration("String", "executeOperation", Arrays
- .asList(new Field(mods, "int", "param1"), new Field(mods2, "long", "param2"))));
-
- GeneralInterfaceTemplate generalInterface = new GeneralInterfaceTemplate(
- null, packageName, name, extendedInterfaces, methods);
-
- Map<FtlTemplate, String> abstractFtlFileStringMap = tested
- .serializeFtls(Arrays.asList(generalInterface));
- String content = FormattingUtil
- .cleanUpEmptyLinesAndIndent(abstractFtlFileStringMap.get(generalInterface));
-
- // skip header
- content = content.substring(content.indexOf("package"));
-
- String expected = "package pa.cka.ge;\n"
- + "/**\n"
- + "*\n"
- + "*/\n"
- + "public interface GeneralClassImpl extends List, Set\n{\n"
- + "public String executeOperation();\n"
- + "public String executeOperation(int param1, final long param2);\n"
- + "}\n";
-
- assertEquals(expected, content);
- }
-
-}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.module;
+
+import net.sourceforge.pmd.lang.Parser;
+import net.sourceforge.pmd.lang.ParserOptions;
+import net.sourceforge.pmd.lang.ast.Node;
+import net.sourceforge.pmd.lang.java.Java17Parser;
+import org.apache.commons.io.FileUtils;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.AbstractGeneratorTest;
+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);
+
+ protected void assertHasMethodNamed(Node c, String method) {
+ assertTrue(c.hasDescendantMatchingXPath("//MethodDeclaration[MethodDeclarator[@Image='" +
+ method +
+ "']]"));
+ }
+
+ protected Node parse(File dstFile) throws IOException {
+ assertNotNull(dstFile);
+ logger.debug(FileUtils.readFileToString(dstFile));
+ Parser parser = new Java17Parser(new ParserOptions());
+ return parser.parse(dstFile.toString(), new FileReader(dstFile));
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.module.abs;
+
+import com.google.common.base.Optional;
+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.gofactory.AbsModuleGeneratedObjectFactory;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
+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
+ public void test() throws IOException {
+ Map<QName,ServiceInterfaceEntry> serviceInterfaceEntryMap = loadThreadsServiceInterfaceEntries("packages.sis");
+ Map<String, ModuleMXBeanEntry> namesToMBEs = loadThreadsJava(serviceInterfaceEntryMap, "packages.pack2");
+ ModuleMXBeanEntry dynamicThreadPool = namesToMBEs.get(THREADPOOL_DYNAMIC_MXB_NAME);
+ parseGeneratedFile(dynamicThreadPool);
+
+ }
+
+ private void parseGeneratedFile(ModuleMXBeanEntry moduleMXBeanEntry) throws IOException {
+ Optional<String> copyright = Optional.absent();
+ GeneratedObject generatedObject = new AbsModuleGeneratedObjectFactory().toGeneratedObject(moduleMXBeanEntry, copyright);
+ Entry<FullyQualifiedName,File> entry = generatedObject.persist(generatorOutputPath).get();
+
+ File dstFile = entry.getValue();
+ parse(dstFile);
+ }
+}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.module.concrete;
+
+import com.google.common.base.Optional;
+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.junit.Test;
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.ConcreteModuleGeneratedObjectFactory;
+import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
+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
+ public void test() throws Exception {
+ FullyQualifiedName fqn = new FullyQualifiedName("foo.bar", "Baz");
+ FullyQualifiedName abstractFQN = new FullyQualifiedName("foo.bar", "AbstractBaz");
+ String nullableDescription = null;
+
+ ModuleMXBeanEntry moduleMXBeanEntry = mockModuleMXBeanEntry(fqn, abstractFQN, nullableDescription);
+ Optional<String> copyright = Optional.absent();
+ Optional<String> header = Optional.absent();
+ GeneratedObject go = new ConcreteModuleGeneratedObjectFactory().toGeneratedObject(moduleMXBeanEntry, copyright, header);
+ Entry<FullyQualifiedName, File> entry = go.persist(generatorOutputPath).get();
+
+ File dstFile = entry.getValue();
+ Node c = parse(dstFile);
+ assertEquals(fqn.getPackageName(), ((ASTCompilationUnit) c).getPackageDeclaration().getPackageNameImage());
+ assertEquals(fqn.getTypeName(), c.getFirstDescendantOfType(ASTClassOrInterfaceDeclaration.class).getImage());
+ assertHasMethodNamed(c, "customValidation");
+ assertHasMethodNamed(c, "createInstance");
+ }
+
+ static ModuleMXBeanEntry mockModuleMXBeanEntry(FullyQualifiedName fqn, FullyQualifiedName abstractFQN, String nullableDescription) {
+ ModuleMXBeanEntry mock = mock(ModuleMXBeanEntry.class);
+ assertEquals(fqn.getPackageName(), abstractFQN.getPackageName());
+ doReturn(fqn.getPackageName()).when(mock).getPackageName();
+ doReturn(fqn.getTypeName()).when(mock).getStubModuleName();
+ doReturn(nullableDescription).when(mock).getNullableDescription();
+ doReturn(abstractFQN.getTypeName()).when(mock).getAbstractModuleName();
+ return mock;
+ }
+}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
-
-import java.util.Scanner;
-
-public class FormattingUtil {
-
- public static String cleanUpEmptyLinesAndIndent(String input) {
- StringBuffer output = new StringBuffer();
- Scanner scanner = new Scanner(input);
- while (scanner.hasNextLine()) {
- String line = scanner.nextLine();
- line = line.replaceAll("\t", " ");
- while (line.contains(" ")) {
- line = line.replaceAll(" ", " ");
- }
- line = line.trim();
- if (line.length() > 0) {
- output.append(line);
- output.append("\n");
- }
- }
-
- return output.toString();
- }
-}
--- /dev/null
+package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
+
+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;
+
+public class StringUtilTest {
+ @Test
+ public void testPrefixAndJoin() {
+ assertEquals(" extends p1.Foo,Bar", StringUtil.prefixAndJoin(asList(
+ new FullyQualifiedName("p1", "Foo"), new FullyQualifiedName("", "Bar")), "extends"));
+ }
+
+ @Test
+ public void testAddAsterixAtEachLineStart() {
+ String input = "foo \nbar";
+ String expectedOutput = "* foo\n* bar\n";
+ assertEquals(expectedOutput, StringUtil.addAsterixAtEachLineStart(input));
+ }
+
+ @Test
+ public void testCopyright() throws IOException {
+ assertTrue(StringUtil.loadCopyright().isPresent());
+ }
+
+ @Test
+ public void testFormatting() {
+ {
+ String input = " \tpack;\n" +
+ "class Bar{ \n" +
+ " method() {\n" +
+ " body\n" +
+ "}\n" +
+ " }";
+ String expected = "pack;\n" +
+ "class Bar{\n" +
+ " method() {\n" +
+ " body\n" +
+ " }\n" +
+ "}\n";
+ assertEquals(expected, StringUtil.formatJavaSource(input));
+ }
+ {
+ String input = "{\n" +
+ "bar\n" +
+ "}\n" +
+ "\n\nbaz\n\n\n\n";
+ String expected = "{\n" +
+ " bar\n" +
+ "}\n\n" +
+ "baz\n";
+ assertEquals(expected, StringUtil.formatJavaSource(input));
+ }
+ }
+}
*/
package org.opendaylight.controller.config.yangjmxgenerator;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.format;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+import org.junit.Assert;
import org.junit.Before;
import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.YangModelSearchUtils;
+import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
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.SchemaContext;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import com.google.common.base.Preconditions;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.format;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
public abstract class AbstractYangTest {
protected SchemaContext context;
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";
+ public static final String THREADFACTORY_NAMING_MXB_NAME = "threadfactory-naming";
+ public static final String THREADPOOL_DYNAMIC_MXB_NAME = "threadpool-dynamic";
+ public static final String THREADPOOL_REGISTRY_IMPL_NAME = "threadpool-registry-impl";
+
+ public static final String BGP_LISTENER_IMPL_MXB_NAME = "bgp-listener-impl";
+
@Before
public void loadYangFiles() throws Exception {
List<InputStream> yangISs = new ArrayList<>();
}
return result;
}
+
+ protected Map<QName, ServiceInterfaceEntry> loadThreadsServiceInterfaceEntries(String packageName) {
+ Map<IdentitySchemaNode, ServiceInterfaceEntry> identitiesToSIs = new HashMap<>();
+ return ServiceInterfaceEntry.create(threadsModule, packageName,identitiesToSIs);
+ }
+
+ 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);
+ Assert.assertNotNull(namesToMBEs);
+ Set<String> expectedMXBeanNames = Sets.newHashSet(EVENTBUS_MXB_NAME,
+ ASYNC_EVENTBUS_MXB_NAME, THREADFACTORY_NAMING_MXB_NAME,
+ THREADPOOL_DYNAMIC_MXB_NAME, THREADPOOL_REGISTRY_IMPL_NAME);
+ assertThat(namesToMBEs.keySet(), is(expectedMXBeanNames));
+ return namesToMBEs;
+ }
+
}
package org.opendaylight.controller.config.yangjmxgenerator;
import com.google.common.collect.Sets;
-import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.mockito.Mockito.mock;
public class ModuleMXBeanEntryTest extends AbstractYangTest {
- public static final String EVENTBUS_MXB_NAME = "eventbus";
- public static final String ASYNC_EVENTBUS_MXB_NAME = "async-eventbus";
- public static final String THREADFACTORY_NAMING_MXB_NAME = "threadfactory-naming";
- public static final String THREADPOOL_DYNAMIC_MXB_NAME = "threadpool-dynamic";
- public static final String THREADPOOL_REGISTRY_IMPL_NAME = "threadpool-registry-impl";
-
- public static final String BGP_LISTENER_IMPL_MXB_NAME = "bgp-listener-impl";
public static final String PACKAGE_NAME = "pack2";
protected Map<QName, ServiceInterfaceEntry> modulesToSIEs;
- protected Map<String /* identity local name */, ModuleMXBeanEntry> loadThreadsJava() {
- Map<String /* identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
- .create(threadsJavaModule, modulesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl
- (context)), PACKAGE_NAME);
- assertNotNull(namesToMBEs);
- Set<String> expectedMXBeanNames = Sets.newHashSet(EVENTBUS_MXB_NAME,
- ASYNC_EVENTBUS_MXB_NAME, THREADFACTORY_NAMING_MXB_NAME,
- THREADPOOL_DYNAMIC_MXB_NAME, THREADPOOL_REGISTRY_IMPL_NAME);
- assertThat(namesToMBEs.keySet(), is(expectedMXBeanNames));
- return namesToMBEs;
- }
@Before
public void setUp() {
- Map<IdentitySchemaNode, ServiceInterfaceEntry> identitiesToSIs = new HashMap<>();
- modulesToSIEs = ServiceInterfaceEntry.create(threadsModule,
- "packages.sis",identitiesToSIs);
+ modulesToSIEs = loadThreadsServiceInterfaceEntries("packages.sis");
+ }
+
+
+ protected Map<String /* identity local name */, ModuleMXBeanEntry> loadThreadsJava() {
+ return loadThreadsJava(modulesToSIEs, PACKAGE_NAME);
}
@Test
<artifactId>maven-plugin-api</artifactId>
<version>3.0.5</version>
</dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
</dependencies>
</project>
\ No newline at end of file
*/
package org.opendaylight.controller.config.yang.test.plugin;
+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.BufferedReader;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
+import java.util.regex.Pattern;
/**
* Add implementation code from stub.txt
if (!sourceDirectory.exists()) {
super.getLog().error("Source directory does not exists " + sourceDirectory.getPath());
}
- String header = "";
- try {
- header = Util.loadHeader();
- } catch (IOException e) {
- super.getLog().error("Header.txt not found.");
- }
+
File[] sourceFiles = sourceDirectory.listFiles();
for (File sourceFile: sourceFiles) {
if(sourceFile.getName().endsWith("Module.java") || sourceFile.getName().endsWith("ModuleFactory.java")) {
File stubFile = new File(sourceFile.getPath().replace(".java", "Stub.txt"));
- String stubLines = null;
- try {
- if (stubFile.exists()) {
- stubLines = Util.loadStubFile(stubFile.getPath());
- }
-
- InputStream javaIn = new FileInputStream(sourceFile.getPath());
- BufferedReader javaBuf = new BufferedReader(new InputStreamReader(javaIn));
- StringBuffer output = new StringBuffer();
- String line = javaBuf.readLine();
- boolean writeLine = false;
- while ((line = javaBuf.readLine()) != null) {
- if(!writeLine && line.contains("*/")) {
- line = header;
- writeLine = true;
- } else {
- if (line.contains("TODO")) {
- writeLine = false;
- } else {
- if (stubLines != null && line.contains("throw new")) {
- line = stubLines.toString();
- writeLine = true;
- }
- }
- }
- if(writeLine) {
- output.append(line).append(System.lineSeparator());
- }
+ if (stubFile.exists()) {
+ try {
+ rewrite(sourceFile, FileUtils.readFileToString(stubFile));
+ } catch (IOException e) {
+ getLog().error("Error while reading/writing to files.", e);
}
- javaBuf.close();
-
- OutputStream javaOut = new FileOutputStream(sourceFile.getPath());
- javaOut.write(output.toString().getBytes());
- javaOut.close();
- } catch (IOException e) {
- getLog().error("Error while reading/writing to files.", e);
}
-
}
}
}
+
+ private static void rewrite(File sourceFile, String replaceTODOWith) throws IOException {
+ String source = FileUtils.readFileToString(sourceFile);
+ String target = Pattern.compile("^.*TODO.*\n.*throw new java.lang.UnsupportedOperationException.*$", Pattern.MULTILINE).matcher(source).replaceFirst(replaceTODOWith);
+ FileUtils.write(sourceFile, target);
+ }
}
package org.opendaylight.controller.config.yang.test.plugin;
-import java.io.BufferedReader;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
import java.util.regex.Matcher;
public class Util {
path = path.replace(".", Matcher.quoteReplacement(File.separator));
return path;
}
-
- public static String loadHeader() throws IOException {
- StringBuffer header = new StringBuffer();
- InputStream headIn = Util.class.getClassLoader().getResourceAsStream("Header.txt");
- BufferedReader headBuf = new BufferedReader(new InputStreamReader(headIn));
- String line = null;
- while ((line = headBuf.readLine()) != null) {
- header.append(line).append(System.lineSeparator());
- }
- headBuf.close();
- return header.toString();
- }
-
- public static String loadStubFile(String fileName) throws IOException {
- InputStream stubIn = new FileInputStream(fileName);
- BufferedReader stubBuf = new BufferedReader(new InputStreamReader(stubIn));
-
- StringBuffer stubLines = new StringBuffer();
- String stubLine = null;
- while ((stubLine = stubBuf.readLine()) != null) {
- stubLines.append(stubLine).append(System.lineSeparator());
- }
- stubBuf.close();
- return stubLines.toString();
- }
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
\ No newline at end of file
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
</plugin>
+
<plugin>
<groupId>org.opendaylight.controller</groupId>
<artifactId>yang-test-plugin</artifactId>
<execution>
<goals>
<goal>delete-sources</goal>
+
<goal>process-sources</goal>
</goals>
</execution>
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.impl;
-
-/**
+* 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
*/
-public final class DepTestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractDepTestImplModule
- {
-
+package org.opendaylight.controller.config.yang.test.impl;
+public class DepTestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractDepTestImplModule {
public DepTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
- public DepTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
- DepTestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
-
+ public DepTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.test.impl.DepTestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
@Override
- protected void customValidation(){
- // Add custom validation for module attributes here.
+ public void customValidation() {
+ // add custom validation form module attributes here.
}
@Override
};
}
+
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.impl;
-
-/**
+* 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
*/
-public class DepTestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractDepTestImplModuleFactory
-{
-
+/*
+* Generated file
+*
+* Generated from: yang module name: config-test-impl yang module local name: impl-dep
+* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
+* Generated at: Mon Mar 17 14:04:38 CET 2014
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.test.impl;
+public class DepTestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractDepTestImplModuleFactory {
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.impl;
-
-/**
+* 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
*/
-public final class IdentityTestModule extends org.opendaylight.controller.config.yang.test.impl.AbstractIdentityTestModule
- {
-
+package org.opendaylight.controller.config.yang.test.impl;
+public class IdentityTestModule extends org.opendaylight.controller.config.yang.test.impl.AbstractIdentityTestModule {
public IdentityTestModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
- public IdentityTestModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
- IdentityTestModule oldModule, java.lang.AutoCloseable oldInstance) {
-
+ public IdentityTestModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.test.impl.IdentityTestModule oldModule, java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
@Override
- protected void customValidation(){
- // Add custom validation for module attributes here.
+ public void customValidation() {
+ // add custom validation form module attributes here.
}
@Override
};
}
+
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.impl;
-
-/**
+* 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
*/
-public class IdentityTestModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractIdentityTestModuleFactory
-{
-
+/*
+* Generated file
+*
+* Generated from: yang module name: config-test-impl yang module local name: impl-identity-test
+* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
+* Generated at: Mon Mar 17 14:04:38 CET 2014
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.test.impl;
+public class IdentityTestModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractIdentityTestModuleFactory {
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.impl;
-
-/**
+* 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
*/
-public final class NetconfTestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractNetconfTestImplModule
- {
-
+package org.opendaylight.controller.config.yang.test.impl;
+public class NetconfTestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractNetconfTestImplModule {
public NetconfTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
- public NetconfTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
- NetconfTestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
-
+ public NetconfTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
@Override
- protected void customValidation(){
- // Add custom validation for module attributes here.
+ public void customValidation() {
+ // add custom validation form module attributes here.
}
@Override
return NetconfTestImplModuleUtil.registerRuntimeBeans(this);
}
+
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.impl;
-
-/**
+* 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
*/
-public class NetconfTestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractNetconfTestImplModuleFactory
-{
-
+/*
+* Generated file
+*
+* Generated from: yang module name: config-test-impl yang module local name: impl-netconf
+* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
+* Generated at: Mon Mar 17 14:04:38 CET 2014
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.test.impl;
+public class NetconfTestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractNetconfTestImplModuleFactory {
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.impl;
-
-/**
+* 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
*/
-public final class TestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractTestImplModule
- {
-
+package org.opendaylight.controller.config.yang.test.impl;
+public class TestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractTestImplModule {
public TestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
- public TestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
- TestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
-
+ public TestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.test.impl.TestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
@Override
- protected void customValidation(){
- // Add custom validation for module attributes here.
+ public void customValidation() {
+ // add custom validation form module attributes here.
}
@Override
};
}
+
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.impl;
-
-/**
+* 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
*/
-public class TestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractTestImplModuleFactory
-{
-
+/*
+* Generated file
+*
+* Generated from: yang module name: config-test-impl yang module local name: impl
+* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
+* Generated at: Mon Mar 17 14:04:38 CET 2014
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.test.impl;
+public class TestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractTestImplModuleFactory {
}