summaryrefslogtreecommitdiffstats
path: root/configgen/src/main/scala/com/yahoo/config/codegen/JavaClassBuilder.scala
blob: c346338e5437fe4035cfb2183d036c50a684de90 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen

import java.io.{FileNotFoundException, FileOutputStream, PrintStream, File}
import ConfigGenerator.{indentCode, createClassName}
import util.Random
import scala.collection.JavaConversions._

/**
 * Builds one Java class based on the given CNode tree.
 *
 * @author gjoranv
 * @author tonytv
 */
class JavaClassBuilder(
                        root: InnerCNode,
                        nd: NormalizedDefinition,
                        destDir: File)
  extends ClassBuilder
{
  import JavaClassBuilder._

  val javaPackage = PackagePrefix + root.getNamespace
  val className = createClassName(root.getName)

  override def createConfigClasses() {
    try {
      val outFile = new File(getDestPath(destDir, root.getNamespace), className + ".java")
      val out = new PrintStream(new FileOutputStream(outFile))
      out.print(getConfigClass(className))
      System.err.println(outFile.getPath + " successfully written.")
    }
    catch {
      case e: FileNotFoundException => {
        throw new CodegenRuntimeException(e)
      }
    }
  }

  def getConfigClass(className:String): String = {
    val ret = new StringBuilder

    ret.append(getHeader).append("\n\n")
    ret.append(getRootClassDeclaration(root, className)).append("\n\n")
    ret.append(indentCode(Indentation, getFrameworkCode(className))).append("\n\n")
    ret.append(ConfigGenerator.generateContent(Indentation, root)).append("\n")
    ret.append("}\n")

    ret.toString()
  }

  private def getHeader: String = {
    <code>
      |/**
      | * This file is generated from a config definition file.
      | * ------------   D O   N O T   E D I T !   ------------
      | */
      |
      |package {javaPackage};
      |
      |import java.util.*;
      |import java.nio.file.Path;
      |import edu.umd.cs.findbugs.annotations.NonNull;
      |{getImportFrameworkClasses(root.getNamespace)}
    </code>.text.stripMargin.trim
  }

  private def getImportFrameworkClasses(namespace: String): String = {
    if (namespace != CNode.DEFAULT_NAMESPACE)
      "import " + PackagePrefix + CNode.DEFAULT_NAMESPACE + ".*;\n"
    else
      ""
  }

  // TODO: remove the extra comment line " *" if root.getCommentBlock is empty
  private def getRootClassDeclaration(root:InnerCNode, className: String): String = {
      <code>
       |/**
       | * This class represents the root node of {root.getFullName}
       | *
       |{root.getCommentBlock(" *")} */
       |public final class {className} extends ConfigInstance {{
       |
       |  public final static String CONFIG_DEF_MD5 = "{root.getMd5}";
       |  public final static String CONFIG_DEF_NAME = "{root.getName}";
       |  public final static String CONFIG_DEF_NAMESPACE = "{root.getNamespace}";
       |  public final static String CONFIG_DEF_VERSION = "{root.getVersion}";
       |  public final static String[] CONFIG_DEF_SCHEMA = {{
       |{indentCode(Indentation * 2, getDefSchema)}
       |  }};
       |
       |  public static String getDefMd5()       {{ return CONFIG_DEF_MD5; }}
       |  public static String getDefName()      {{ return CONFIG_DEF_NAME; }}
       |  public static String getDefNamespace() {{ return CONFIG_DEF_NAMESPACE; }}
       |  public static String getDefVersion()   {{ return CONFIG_DEF_VERSION; }}
      </code>.text.stripMargin.trim
  }

  private def getDefSchema: String = {
    nd.getNormalizedContent.map { line =>
      "\"" +
        line.replace("\"", "\\\"") +
        "\""
    }.mkString(",\n")
  }

  private def getFrameworkCode(className: String): String = {
     getProducerBase
  }

  private def getProducerBase = {
    """
      |public interface Producer extends ConfigInstance.Producer {
      |  void getConfig(Builder builder);
      |}
    """.stripMargin.trim
  }
}


object JavaClassBuilder {
  private val PackagePrefix: String = System.getProperty("config.packagePrefix", "com.yahoo.")

  val Indentation = "  "

  /**
   * Returns a name that can be safely used as a local variable in the generated config class
   * for the given node. The name will be based on the given basis string, but the basis itself is
   * not a possible return value.
   *
   * @param node The node to find a unused symbol name for.
   * @param basis The basis for the generated symbol name.
   * @return A name that is not used in the given config node.
   */
  def createUniqueSymbol(node: CNode, basis: String) = {

    def getCandidate(cnt: Int) = {
      if (cnt < basis.length())
        basis.substring(0, cnt)
      else
        ReservedWords.INTERNAL_PREFIX + basis + Random.nextInt().abs
    }

    def getUsedSymbols: Set[String] = {
      (node.getChildren map (child => child.getName)).toSet
    }

    // TODO: refactoring potential
    val usedSymbols = getUsedSymbols
    var count = 1
    var candidate = getCandidate(count)
    while (usedSymbols contains(candidate)) {
      count += 1
      candidate = getCandidate(count)
    }
    candidate
  }

  /**
   * @param rootDir  The root directory for the destination path.
   * @param namespace  The namespace from the def file
   * @return the destination path for the generated config file, including the given rootDir.
   */
  private def getDestPath(rootDir: File, namespace: String): File = {
    var dir: File = rootDir
    val subDirs: Array[String] = (PackagePrefix + namespace).split("""\.""")
    for (subDir <- subDirs) {
      dir = new File(dir, subDir)
      if (!dir.isDirectory && !dir.mkdir) throw new CodegenRuntimeException("Could not create " + dir.getPath)
    }
    dir
  }
}