private static final Logger LOG = LoggerFactory.getLogger(JMXGenerator.class);
private static final Pattern NAMESPACE_MAPPING_PATTERN = Pattern.compile("(.+)" + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
- private PackageTranslator packageTranslator;
private final CodeWriter codeWriter;
private Map<String, String> namespaceToPackageMapping;
private File resourceBaseDir;
.checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(),
"No namespace to package mapping provided in additionalConfiguration");
- packageTranslator = new PackageTranslator(namespaceToPackageMapping);
+ PackageTranslator packageTranslator = new PackageTranslator(namespaceToPackageMapping);
if (!outputBaseDir.exists()) {
outputBaseDir.mkdirs();
for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
.entrySet()) {
// merge value into qNamesToSIEs
- if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
- qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
- } else {
+ if (qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue()) != null) {
throw new IllegalStateException(
- "Cannot add two SIE with same qname "
+ "Cannot add two SIE with same qname "
+ sieEntry.getValue());
}
}
Files.write(fullyQualifiedNamesOfFactories.toString(), serviceLoaderFile, StandardCharsets.UTF_8);
} catch (IOException e) {
String message = "Cannot write to " + serviceLoaderFile;
- LOG.error(message);
+ LOG.error(message, e);
throw new RuntimeException(message, e);
}
}
@VisibleForTesting
static File concatFolders(final File projectBaseDir, final String... folderNames) {
- StringBuilder b = new StringBuilder();
- for (String folder : folderNames) {
- b.append(folder);
- b.append(File.separator);
+ File result = projectBaseDir;
+ for (String folder: folderNames) {
+ result = new File(result, folder);
}
- return new File(projectBaseDir, b.toString());
+ return result;
}
@Override
private boolean extractModuleFactoryBoolean(
final Map<String, String> additionalCfg) {
String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
- if (bool == null) {
- return true;
- }
- if ("false".equals(bool)) {
- return false;
- }
- return true;
+ return !"false".equals(bool);
}
private static Map<String, String> extractNamespaceMapping(
if (files.contains(file)) {
List<File> undeletedFiles = Lists.newArrayList();
for (File presentFile : files) {
- if (presentFile.delete() == false) {
+ if (!presentFile.delete()) {
undeletedFiles.add(presentFile);
}
}
- if (undeletedFiles.isEmpty() == false) {
+ if (!undeletedFiles.isEmpty()) {
LOG.error(
"Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
undeletedFiles);
Optional<String> getMaybeJavadoc();
- public List<Annotation> getAnnotations();
+ List<Annotation> getAnnotations();
TypeDeclaration getTypeDeclaration();
- public String getFullyQualifiedName();
+ String getFullyQualifiedName();
- public List<Field> getFields();
+ List<Field> getFields();
List<? extends Method> getMethods();
import com.google.common.collect.Lists;
import java.io.Closeable;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
String name, List<Field> fields, List<MethodDefinition> methods) {
// TODO header
super(null, runtimeBeanEntry.getPackageName(), name, Collections
- .<String> emptyList(), Arrays.asList(Closeable.class
- .getCanonicalName()), fields, methods);
+ .<String> emptyList(), Collections.singletonList(Closeable.class
+ .getCanonicalName()), fields, methods);
}
public static RuntimeBeanEntry findRoot(
private static String constructConstructorBody(
List<Field> constructorParameters) {
- StringBuffer constructorBody = new StringBuffer();
+ StringBuilder constructorBody = new StringBuilder();
for (Field field : constructorParameters) {
constructorBody.append("this.");
constructorBody.append(field.getName());
StringBuilder registerBody = new StringBuilder();
registerBody.append(format("%s %s = this.%s.registerRoot(%s);\n",
HierarchicalRuntimeBeanRegistration.class
- .getCanonicalName(), hierachchicalRegistration
+ .getCanonicalName(), hierachicalRegistration
.getName(), rootRuntimeBeanRegistratorField
.getName(), rbParameter.getName()));
registerBody.append(format("return new %s(%s);\n",
rootFtlFile.getFullyQualifiedName(),
- hierachchicalRegistration.getName()));
+ hierachicalRegistration.getName()));
MethodDefinition registerMethod = new MethodDefinition(
childRegistratorFQN, "register",
- Arrays.asList(rbParameter), registerBody.toString());
+ Collections.singletonList(rbParameter), registerBody.toString());
methods.add(registerMethod);
}
// TODO add header
GeneralClassTemplate registrator = new GeneralClassTemplate(null,
rootRB.getPackageName(), registratorName,
- Collections.<String> emptyList(), Arrays.asList(Closeable.class
- .getCanonicalName()), constructorParameters, methods);
+ Collections.<String> emptyList(), Collections.singletonList(Closeable.class
+ .getCanonicalName()), constructorParameters, methods);
- checkState(RuntimeRegistratorFtlTemplates.containsKey(registrator
- .getTypeDeclaration().getName()) == false, "Name conflict: "
+ checkState(!RuntimeRegistratorFtlTemplates.containsKey(registrator
+ .getTypeDeclaration().getName()), "Name conflict: "
+ registrator.getTypeDeclaration().getName());
Map<String, FtlTemplate> result = new HashMap<>();
result.putAll(RuntimeRegistratorFtlTemplates);
return result;
}
- private static Field hierachchicalRegistration = new Field(
+ private static Field hierachicalRegistration = new Field(
Lists.newArrayList("final"),
HierarchicalRuntimeBeanRegistration.class.getCanonicalName(),
"registration");
Set<String> currentOccupiedKeys = new HashSet<>(occupiedKeys);
currentOccupiedKeys.add(parent.getJavaNamePrefix());
- Field registratorsMapField = new Field(Arrays.asList("final"),
+ Field registratorsMapField = new Field(Collections.singletonList("final"),
TypeHelper.getGenericType(Map.class, String.class,
AtomicInteger.class), "unkeyedMap", "new "
+ TypeHelper.getGenericType(HashMap.class,
body.append(format("String value = %s;\n", value));
body.append(format("%s r = %s.register(key, value, bean);\n",
HierarchicalRuntimeBeanRegistration.class
- .getCanonicalName(), hierachchicalRegistration
+ .getCanonicalName(), hierachicalRegistration
.getName()));
body.append(format("return new %s(r);",
childRegistrator.getFullyQualifiedName()));
Field param = new Field(Lists.newArrayList("final"),
child.getJavaNameOfRuntimeMXBean(), "bean");
MethodDefinition register = new MethodDefinition(
- Arrays.asList("synchronized"),
+ Collections.singletonList("synchronized"),
childRegistrator.getFullyQualifiedName(), "register",
- Arrays.asList(param), Collections.<String> emptyList(),
+ Collections.singletonList(param), Collections.<String> emptyList(),
Collections.<Annotation> emptyList(), body.toString());
methods.add(register);
// create parent registration
String createdName = getJavaNameOfRuntimeRegistration(parent.getJavaNamePrefix());
- List<Field> constructorParameters = Arrays
- .asList(hierachchicalRegistration);
+ List<Field> constructorParameters = Collections.singletonList(hierachicalRegistration);
String constructorBody = constructConstructorBody(constructorParameters);
MethodDefinition constructor = MethodDefinition.createConstructor(
createdName, constructorParameters, constructorBody);
- MethodDefinition closeRegistrator = createCloseMethodToCloseField(hierachchicalRegistration);
+ MethodDefinition closeRegistrator = createCloseMethodToCloseField(hierachicalRegistration);
methods.add(closeRegistrator);
methods.add(constructor);
List<Field> privateFields = Lists.newArrayList(registratorsMapField);
LinkedHashMap<String, RuntimeRegistratorFtlTemplate> result = new LinkedHashMap<>();
result.put(created.getTypeDeclaration().getName(), created);
- checkState(unorderedResult.containsKey(created.getTypeDeclaration()
- .getName()) == false, "Naming conflict: "
+ checkState(!unorderedResult.containsKey(created.getTypeDeclaration()
+ .getName()), "Naming conflict: "
+ created.getTypeDeclaration().getName());
result.putAll(unorderedResult);
return result;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
{ // create GeneralInterfaceFtlFile for runtime MXBean. Attributes will
// be transformed to getter methods
String mxBeanTypeName = entry.getJavaNameOfRuntimeMXBean();
- List<String> extendedInterfaces = Arrays.asList(RuntimeBean.class
+ List<String> extendedInterfaces = Collections.singletonList(RuntimeBean.class
.getCanonicalName());
List<MethodDeclaration> methods = new ArrayList<>();
public static AbstractFactoryTemplate abstractFactoryTemplateFromMbe(
final ModuleMXBeanEntry mbe) {
AbstractFactoryAttributesProcessor attrProcessor = new AbstractFactoryAttributesProcessor();
- attrProcessor.processAttributes(mbe.getAttributes(),
- mbe.getPackageName());
+ attrProcessor.processAttributes(mbe.getAttributes());
boolean generateRuntime = false;
String registratorFullyQualifiedName = null;
if (mbe.getRuntimeBeans() != null
- && mbe.getRuntimeBeans().isEmpty() == false) {
+ && !mbe.getRuntimeBeans().isEmpty()) {
generateRuntime = true;
RuntimeBeanEntry rootEntry = RuntimeRegistratorFtlTemplate
.findRoot(mbe.getRuntimeBeans());
continue;
}
- Preconditions.checkState(yangPropertiesToTypesMap.containsKey(returnType.getAttributeYangName()) == false,
+ Preconditions.checkState(!yangPropertiesToTypesMap.containsKey(returnType.getAttributeYangName()),
"Duplicate TO %s for %s", returnType.getAttributeYangName(), rbe);
yangPropertiesToTypesMap.put(returnType.getAttributeYangName(), returnType);
}
private MethodDefinition getEquals(final Map<String, AttributeIfc> attrs) {
final StringBuilder equalsBodyBuilder = new StringBuilder(
- " if (this == o) return true;\n" +
- " if (o == null || getClass() != o.getClass()) return false;\n");
+ " if (this == o) { return true; }\n" +
+ " if (o == null || getClass() != o.getClass()) { return false; }\n");
equalsBodyBuilder.append(String.format(
" final %s that = (%s) o;\n", name, name));
for (AttributeIfc s : attrs.values()) {
private final List<Field> fields = Lists.newArrayList();
- void processAttributes(final Map<String, AttributeIfc> attributes,
- final String packageName) {
- for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
- String type;
- String nullableDefaultWrapped = null;
- AttributeIfc attributeIfc = attrEntry.getValue();
-
+ void processAttributes(final Map<String, AttributeIfc> attributes) {
+ for (AttributeIfc attributeIfc : attributes.values()) {
if (attributeIfc instanceof TypedAttribute) {
TypedAttribute typedAttribute = (TypedAttribute) attributeIfc;
- type = serializeType(typedAttribute.getType());
+ String type = serializeType(typedAttribute.getType());
+
+ fields.add(new Field(type, attributeIfc
+ .getUpperCaseCammelCase(), null));
} else {
throw new UnsupportedOperationException(
"Attribute not supported: "
+ attributeIfc.getClass());
}
-
- fields.add(new Field(type, attributeIfc
- .getUpperCaseCammelCase(), nullableDefaultWrapped));
}
}
* "List<String>" for input parameters List.class, String.class
*/
static String getGenericType(Class<?> type, Class<?>... parameters) {
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
sb.append(type.getCanonicalName());
if (parameters.length > 0) {
sb.append("<");
if (constr.isPublic()) {
build.append("public ");
}
- build.append(constr.getTypeName() + " ");
+ build.append(constr.getTypeName());
build.append("() {");
build.append("\n");
build.append(" ");
StringBuilder build = new StringBuilder();
build.append("private ");
for (String mod : field.getModifiers()) {
- build.append(mod + " ");
+ build.append(mod).append(" ");
}
- build.append(field.getType() + " ");
+ build.append(field.getType()).append(" ");
build.append(field.getName());
if (field.getDefinition() != null) {
- build.append(" = " + field.getDefinition());
+ build.append(" = ").append(field.getDefinition());
}
build.append(";");
build.append("\n");
package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
import java.util.Date;
+
import org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator;
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();
+ return "Generated file" + "\n" +
+ "\n" +
+ "Generated from: " +
+ "yang module name: " + header.getYangModuleName() +
+ " yang module local name: " + header.getYangModuleLocalName() + "\n" +
+ "Generated by: " + GENERATOR_CLASS + "\n" +
+ "Generated at: " + new Date() + "\n" +
+ "\n" +
+ "Do not modify this file unless it is present under src/main directory ";
}
}
build.append(" " + "public ");
for (String mod : method.getModifiers()) {
- build.append(mod + " ");
+ build.append(mod).append(" ");
}
- build.append(method.getReturnType() + " ");
+ build.append(method.getReturnType()).append(" ");
- build.append(method.getName() + "(");
+ build.append(method.getName()).append("(");
+ boolean firstParam = true;
for (Field param : method.getParameters()) {
+ if (!firstParam) {
+ build.append(", ");
+ }
for (String mod : param.getModifiers()) {
- build.append(mod + " ");
+ build.append(mod).append(" ");
}
- 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(')');
+ build.append(param.getType()).append(" ");
+ build.append(param.getName());
+ firstParam = false;
}
+ build.append(")");
if (method instanceof MethodDeclaration) {
build.append(";");
build.append("\n");
} else if (method instanceof MethodDefinition) {
- if (!((MethodDefinition) method).getThrowsExceptions()
- .isEmpty()) {
+ MethodDefinition definition = (MethodDefinition) method;
+ if (!definition.getThrowsExceptions().isEmpty()) {
build.append(" throws ");
}
- for (String ex : ((MethodDefinition) method)
- .getThrowsExceptions()) {
- build.append(ex + " ");
+ for (String ex : definition.getThrowsExceptions()) {
+ build.append(ex).append(" ");
}
build.append(" {");
build.append("\n");
build.append(" ");
- build.append(((MethodDefinition) method).getBody());
+ build.append(definition.getBody());
build.append("\n");
build.append(" ");
build.append("}");
public static String toString(ModuleField moduleField) {
StringBuilder builder = new StringBuilder();
builder.append(" ");
- builder.append("public static final "
- + JmxAttribute.class.getCanonicalName() + " "
- + moduleField.getName() + "JmxAttribute = new "
- + JmxAttribute.class.getCanonicalName() + "(\""
- + moduleField.getAttributeName() + "\");");
+ builder.append("public static final ");
+ builder.append(JmxAttribute.class.getCanonicalName());
+ builder.append(" ");
+ builder.append(moduleField.getName());
+ builder.append("JmxAttribute = new ");
+ builder.append(JmxAttribute.class.getCanonicalName());
+ builder.append("(\"");
+ builder.append(moduleField.getAttributeName());
+ builder.append("\");");
builder.append("\n");
builder.append(" private ");
for (String mod : moduleField.getModifiers()) {
- builder.append(mod + " ");
+ builder.append(mod).append(" ");
}
- builder.append(moduleField.getType() + " ");
+ builder.append(moduleField.getType()).append(" ");
builder.append(moduleField.getName());
if (moduleField.getNullableDefault() != null) {
- builder.append(" = " + moduleField.getNullableDefault());
+ builder.append(" = ").append(moduleField.getNullableDefault());
}
builder.append(";");
if (moduleField.isDependent()) {
String comment = moduleField.getDependency().isMandatory() ? "mandatory"
: "optional";
- builder.append(" // " + comment);
+ builder.append(" // ").append(comment);
}
builder.append("\n");
"throw new UnsupportedOperationException(\"Class reloading is not supported\");\n"+
"}\n", moduleFQN, DynamicMBeanWithInstance.class.getCanonicalName()));
+ // TODO The generic specifier in HashSet<> isn't necessary, but the Eclipse AST parser used in the unit tests doesn't support this
b.addToBody(format("\n"+
"@Override\n"+
"public java.util.Set<%s> getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory dependencyResolverFactory, %s bundleContext) {\n"+
- "return new java.util.HashSet<%s>();\n"+
- "}\n", moduleFQN, BUNDLE_CONTEXT, moduleFQN));
+ "return new java.util.HashSet<%1$s>();\n"+
+ "}\n", moduleFQN, BUNDLE_CONTEXT));
return new GeneratedObjectBuilder(b.build()).toGeneratedObject();
}
format("public %s createModule(String instanceName, %s dependencyResolver, %s old, %s bundleContext) throws Exception {\n",
Module.class.getCanonicalName(), DependencyResolver.class.getCanonicalName(),
DynamicMBeanWithInstance.class.getCanonicalName(), BUNDLE_CONTEXT)+
- format("%s oldModule = null;\n",moduleFQN)+
+ format("%s oldModule;\n",moduleFQN)+
"try {\n"+
format("oldModule = (%s) old.getModule();\n",moduleFQN)+
"} catch(Exception e) {\n"+
private static String getServiceIfcsInitialization(List<FullyQualifiedName> providedServices) {
String generic = format("Class<? extends %s>", AbstractServiceInterface.class.getCanonicalName());
- String result = format("static {\n"+
- "java.util.Set<%1$s> serviceIfcs2 = new java.util.HashSet<%1$s>();\n", generic);
+ String result = "static {\n";
+ if (!providedServices.isEmpty()) {
+ // TODO The generic specifier in HashSet<> isn't necessary, but the Eclipse AST parser used in the unit tests doesn't support this
+ result += format("java.util.Set<%1$s> serviceIfcs2 = new java.util.HashSet<%1$s>();\n", generic);
- for(FullyQualifiedName fqn: providedServices) {
- result += format("serviceIfcs2.add(%s.class);\n", fqn);
+ for(FullyQualifiedName fqn: providedServices) {
+ result += format("serviceIfcs2.add(%s.class);\n", fqn);
+ }
+
+ result += "serviceIfcs = java.util.Collections.unmodifiableSet(serviceIfcs2);\n";
+ } else {
+ result += "serviceIfcs = java.util.Collections.emptySet();\n";
}
- result += "serviceIfcs = java.util.Collections.unmodifiableSet(serviceIfcs2);\n"+
- "}\n";
+ result += "}\n";
// add isModuleImplementingServiceInterface and getImplementedServiceIntefaces methods
return "\n"+
"@Override\n"+
"public boolean equals(Object o) {\n"+
- "if (this == o) return true;\n"+
- "if (o == null || getClass() != o.getClass()) return false;\n"+
+ "if (this == o) { return true; }\n"+
+ "if (o == null || getClass() != o.getClass()) { return false; }\n"+
format("%s that = (%1$s) o;\n", abstractFQN.getTypeName())+
"return identifier.equals(that.identifier);\n"+
"}\n"+
for (ModuleField moduleField : moduleFields) {
result += format(
- "if (java.util.Objects.deepEquals(%s, other.%1$s) == false) {\n"+
+ "if (!java.util.Objects.deepEquals(%s, other.%1$s)) {\n"+
"return false;\n"+
"}\n", moduleField.getName());
// parameters
stringBuilder.append(Joiner.on(", ").withKeyValueSeparator(" ").join(parameters));
stringBuilder.append(") {\n");
- if (parameters.isEmpty() == false) {
+ if (!parameters.isEmpty()) {
stringBuilder.append("super(");
stringBuilder.append(Joiner.on(", ").join(parameters.values()));
stringBuilder.append(");\n");
content.append(maybeAddComment(input.getCopyright()));
content.append(maybeAddComment(input.getHeader()));
- if (input.getFQN().getPackageName().isEmpty() == false) {
+ if (!input.getFQN().getPackageName().isEmpty()) {
content.append("package ");
content.append(input.getFQN().getPackageName());
content.append(";\n");
int basicIndent = 4;
StringBuilder sb = new StringBuilder();
- int intends = 0, empty = 0;
+ int indents = 0, empty = 0;
for (String line : split) {
- intends -= StringUtils.countMatches(line, "}");
- if (intends < 0) {
- intends = 0;
+ indents -= StringUtils.countMatches(line, "}");
+ if (indents < 0) {
+ indents = 0;
}
- if (line.isEmpty() == false) {
- sb.append(Strings.repeat(" ", basicIndent * intends));
+ if (!line.isEmpty()) {
+ sb.append(Strings.repeat(" ", basicIndent * indents));
sb.append(line);
sb.append("\n");
empty = 0;
sb.append("\n");
}
}
- intends += StringUtils.countMatches(line, "{");
+ indents += StringUtils.countMatches(line, "{");
}
return ensureEndsWithSingleNewLine(sb.toString());
}