ReportBuilder.scala 5.47 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, BiopetJavaCommandLineFunction, 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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

  val builder: ReportBuilder

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

  var outputDir: File = _

  var args: Map[String, String] = Map()

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

  override def commandLine: String = {
    super.commandLine +
      required("--summary", summaryFile) +
      required("--outputDir", outputDir) +
      args.map(x => required(x._1, x._2)).mkString
  }
}

39
40
trait ReportBuilder extends ToolCommand {

41
  case class Args(summary: File = null, outputDir: File = null, pageArgs: Map[String, String] = Map()) extends AbstractArgs
42
43

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

  private var setSummary: Summary = _

  final def summary = setSummary

  def pageArgs: Map[String, Any] = Map()

Peter van 't Hof's avatar
Peter van 't Hof committed
61
62
63
  private var done = 0
  private var total = 0

64
65
66
67
68
69
70
71
72
  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")

73
74
    logger.info("Copy Base files")

Peter van 't Hof's avatar
Peter van 't Hof committed
75
    // Static files that will be copied to the output folder, then file is added to [resourceDir] it's need to be added here also
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    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) {
92
      IoUtils.copyStreamToFile(getClass.getResourceAsStream(resourceDir + resource), new File(extOutputDir, resource), true)
93
    }
94

Peter van 't Hof's avatar
Peter van 't Hof committed
95
    logger.info("Parsing summary")
96
97
    setSummary = new Summary(cmdArgs.summary)

Peter van 't Hof's avatar
Peter van 't Hof committed
98
99
100
    total = countPages(indexPage)
    logger.info(total + " pages to be generated")

Peter van 't Hof's avatar
Peter van 't Hof committed
101
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
102
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
103
104
      args = pageArgs ++ cmdArgs.pageArgs ++
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage))
105

Peter van 't Hof's avatar
Peter van 't Hof committed
106
    logger.info(jobs + " Done")
107
108
109
110
111
112
  }

  def indexPage: ReportPage

  def reportName: String

Peter van 't Hof's avatar
Peter van 't Hof committed
113
114
115
116
  def countPages(page: ReportPage): Int = {
    page.subPages.map(x => countPages(x._2)).fold(1)(_ + _)
  }

117
118
119
120
  def generatePage(summary: Summary,
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
121
                   args: Map[String, Any] = Map()): Int = {
122

Peter van 't Hof's avatar
Peter van 't Hof committed
123
124
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
125
126
127
128
129
130
131
    val rootPath = "./" + Array.fill(path.size)("../").mkString("")
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
132

133
134
135
136
137
    // 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
138
139
140
141
    val output = ReportBuilder.renderTemplate("/nl/lumc/sasc/biopet/core/report/main.ssp",
      pageArgs ++ Map("args" -> pageArgs))

    val file = new File(pageOutputDir, "index.html")
142
143
144
145
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
146
147
    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
148
    jobs.fold(0)(_ + _) + 1
149
150
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
151
152
153
154
155

object ReportBuilder {

  protected val engine = new TemplateEngine()

156
157
  private var templateCache: Map[String, File] = Map()

Peter van 't Hof's avatar
Peter van 't Hof committed
158
159
160
161
162
163
164
  /**
   * 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 = {
165
166
167
168
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
      case _ => {
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
169
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
170
171
172
173
174
175
        templateCache += location -> tempFile
        tempFile
      }
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
176
}