ReportBuilder.scala 6.58 KB
Newer Older
1
2
package nl.lumc.sasc.biopet.core.report

3
import java.io._
4

5
import nl.lumc.sasc.biopet.core.{ ToolCommandFuntion, ToolCommand }
6
import nl.lumc.sasc.biopet.core.summary.Summary
7
import org.broadinstitute.gatk.utils.commandline.Input
8
import org.fusesource.scalate.{ TemplateSource, TemplateEngine }
9
import nl.lumc.sasc.biopet.utils.IoUtils
10
11
12
13

/**
 * Created by pjvan_thof on 3/27/15.
 */
14
trait ReportBuilderExtension extends ToolCommandFuntion {
15

16
  /** Report builder object */
17
18
19
20
21
  val builder: ReportBuilder

  @Input(required = true)
  var summaryFile: File = _

22
  /** OutputDir for the report  */
23
24
  var outputDir: File = _

25
  /** Arguments that are passed on the commandline */
26
27
28
29
30
31
32
33
  var args: Map[String, String] = Map()

  override def beforeGraph: Unit = {
    super.beforeGraph
    jobOutputFile = new File(outputDir, ".report.log.out")
    javaMainClass = builder.getClass.getName.takeWhile(_ != '$')
  }

34
  /** Command to generate the report */
35
36
37
38
39
40
41
42
  override def commandLine: String = {
    super.commandLine +
      required("--summary", summaryFile) +
      required("--outputDir", outputDir) +
      args.map(x => required(x._1, x._2)).mkString
  }
}

43
44
trait ReportBuilder extends ToolCommand {

45
  case class Args(summary: File = null, outputDir: File = null, pageArgs: Map[String, String] = Map()) extends AbstractArgs
46
47

  class OptParser extends AbstractOptParser {
48
    opt[File]('s', "summary") required () maxOccurs 1 valueName "<file>" action { (x, c) =>
49
50
      c.copy(summary = x)
    }
51
    opt[File]('o', "outputDir") required () maxOccurs 1 valueName "<file>" action { (x, c) =>
52
53
      c.copy(outputDir = x)
    }
54
55
56
    opt[Map[String, String]]('a', "args") action { (x, c) =>
      c.copy(pageArgs = c.pageArgs ++ x)
    }
57
58
  }

59
  /** summary object internaly */
60
61
  private var setSummary: Summary = _

62
  /** Retrival of summary, read only */
63
64
  final def summary = setSummary

65
  /** default args that are passed to all page withing the report */
66
67
  def pageArgs: Map[String, Any] = Map()

Peter van 't Hof's avatar
Peter van 't Hof committed
68
69
70
  private var done = 0
  private var total = 0

71
  /** Main function to for building the report */
72
73
74
75
76
77
78
79
80
  def main(args: Array[String]): Unit = {
    logger.info("Start")

    val argsParser = new OptParser
    val cmdArgs: Args = argsParser.parse(args, Args()) getOrElse sys.exit(1)

    require(cmdArgs.outputDir.exists(), "Output dir does not exist")
    require(cmdArgs.outputDir.isDirectory, "Output dir is not a directory")

81
82
    logger.info("Copy Base files")

Peter van 't Hof's avatar
Peter van 't Hof committed
83
    // Static files that will be copied to the output folder, then file is added to [resourceDir] it's need to be added here also
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
    val extOutputDir: File = new File(cmdArgs.outputDir, "ext")
    val resourceDir: String = "/nl/lumc/sasc/biopet/core/report/ext/"
    val extFiles = List(
      "css/bootstrap_dashboard.css",
      "css/bootstrap.min.css",
      "css/bootstrap-theme.min.css",
      "css/sortable-theme-bootstrap.css",
      "js/jquery.min.js",
      "js/sortable.min.js",
      "js/bootstrap.min.js",
      "fonts/glyphicons-halflings-regular.woff",
      "fonts/glyphicons-halflings-regular.ttf",
      "fonts/glyphicons-halflings-regular.woff2"
    )

    for (resource <- extFiles.par) {
100
      IoUtils.copyStreamToFile(getClass.getResourceAsStream(resourceDir + resource), new File(extOutputDir, resource), true)
101
    }
102

Peter van 't Hof's avatar
Peter van 't Hof committed
103
    logger.info("Parsing summary")
104
105
    setSummary = new Summary(cmdArgs.summary)

106
    total = ReportBuilder.countPages(indexPage)
Peter van 't Hof's avatar
Peter van 't Hof committed
107
108
    logger.info(total + " pages to be generated")

Peter van 't Hof's avatar
Peter van 't Hof committed
109
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
110
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
111
112
      args = pageArgs ++ cmdArgs.pageArgs ++
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage))
113

Peter van 't Hof's avatar
Peter van 't Hof committed
114
    logger.info(jobs + " Done")
115
116
  }

117
  /** This must be implemented, this will be the root page of the report */
118
119
  def indexPage: ReportPage

120
  /** This must be implemented, this will because the title of the report */
121
122
  def reportName: String

123
124
125
126
127
128
129
130
131
  /**
   * This method will render the page and the subpages recursivly
   * @param summary The summary object
   * @param page Page to render
   * @param outputDir Root output dir of the report
   * @param path Path from root to current page
   * @param args Args to add to this sub page, are args from current page are passed automaticly
   * @return Number of pages including all subpages that are rendered
   */
132
133
134
135
  def generatePage(summary: Summary,
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
136
                   args: Map[String, Any] = Map()): Int = {
137

Peter van 't Hof's avatar
Peter van 't Hof committed
138
139
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
140
141
142
143
144
145
146
    val rootPath = "./" + Array.fill(path.size)("../").mkString("")
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
147

148
149
150
151
152
    // Generating subpages
    val jobs = for ((name, subPage) <- page.subPages.par) yield {
      generatePage(summary, subPage, outputDir, path ::: name :: Nil, pageArgs)
    }

Peter van 't Hof's avatar
Peter van 't Hof committed
153
154
155
156
    val output = ReportBuilder.renderTemplate("/nl/lumc/sasc/biopet/core/report/main.ssp",
      pageArgs ++ Map("args" -> pageArgs))

    val file = new File(pageOutputDir, "index.html")
157
158
159
160
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
161
162
    done += 1
    if (done % 100 == 0) logger.info(done + " Done, " + (done.toDouble / total * 100) + "%")
Peter van 't Hof's avatar
Peter van 't Hof committed
163
    jobs.fold(0)(_ + _) + 1
164
165
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
166
167
168

object ReportBuilder {

169
  /** Single template render engine, this will have a cache for all compile templates */
Peter van 't Hof's avatar
Peter van 't Hof committed
170
171
  protected val engine = new TemplateEngine()

172
  /** Cache of temp file for templates from the classpath / jar */
173
174
  private var templateCache: Map[String, File] = Map()

175
176
177
178
179
  /** This will give the total number of pages including all nested pages */
  def countPages(page: ReportPage): Int = {
    page.subPages.map(x => countPages(x._2)).fold(1)(_ + _)
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
180
181
182
183
184
185
186
  /**
   * This method will render a template that is located in the classpath / jar
   * @param location location in the classpath / jar
   * @param args Additional arguments, not required
   * @return Rendered result of template
   */
  def renderTemplate(location: String, args: Map[String, Any] = Map()): String = {
187
188
189
190
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
      case _ => {
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
191
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
192
193
194
195
196
197
        templateCache += location -> tempFile
        tempFile
      }
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
198
}