alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (DocumentationHandler.scala)

This example Play Framework source code file (DocumentationHandler.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

anyref, api, filerepository, http, lib, library, memoise, none, option, play, play framework, r, resource, some, string, t

The DocumentationHandler.scala Play Framework example source code

/*
 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
 */
package play.docs

import play.api.mvc._
import play.api.http.Status
import play.api.http.HeaderNames
import play.api.libs.iteratee.Enumerator
import play.api.libs.iteratee.Enumeratee
import play.core.{ PlayVersion, BuildDocHandler }
import play.doc.{ FileRepository, PlayDoc, RenderedPage }
import org.apache.commons.io.IOUtils

/**
 * Used by the DocumentationApplication class to handle requests for Play documentation.
 * Documentation is located in the given repository - either a JAR file or directly from
 * the filesystem.
 */
class DocumentationHandler(repo: FileRepository, apiRepo: FileRepository) extends BuildDocHandler {

  def this(repo: FileRepository) = this(repo, repo)

  val markdownRenderer = new PlayDoc(repo, repo, "resources", PlayVersion.current)

  val locator: String => String = new Memoise(name =>
    repo.findFileWithName(name).orElse(apiRepo.findFileWithName(name)).getOrElse(name)
  )

  // Method without Scala types. Required by BuildDocHandler to allow communication
  // between code compiled by different versions of Scala
  override def maybeHandleDocRequest(request: AnyRef): AnyRef = {
    this.maybeHandleDocRequest(request.asInstanceOf[RequestHeader])
  }

  /**
   * Handle the given request if it is a request for documentation content.
   */
  def maybeHandleDocRequest(request: RequestHeader): Option[Result] = {

    // Assumes caller consumes result, closing entry
    def sendFileInline(repo: FileRepository, path: String): Option[Result] = {
      import play.api.libs.concurrent.Execution.Implicits.defaultContext
      repo.handleFile(path) { handle =>
        Result(
          ResponseHeader(Status.OK, Map(
            HeaderNames.CONTENT_LENGTH -> handle.size.toString,
            HeaderNames.CONTENT_TYPE -> play.api.libs.MimeTypes.forFileName(handle.name).getOrElse(play.api.http.ContentTypes.BINARY)
          )),
          Enumerator.fromStream(handle.is) &> Enumeratee.onIterateeDone(handle.close)
        )
      }
    }

    import play.api.mvc.Results._

    val documentation = """/@documentation/?""".r
    val book = """/@documentation/Book""".r
    val apiDoc = """/@documentation/api/(.*)""".r
    val wikiResource = """/@documentation/resources/(.*)""".r
    val wikiPage = """/@documentation/([^/]*)""".r

    request.path match {

      case documentation() => {

        Some {
          Redirect("/@documentation/Home")
        }

      }

      case book() => {

        Some {
          repo.loadFile("manual/book/Book") { is =>
            val lines = IOUtils.toString(is).split('\n').toSeq.map(_.trim)
            Ok(views.html.play20.book(lines))
          }.getOrElse(NotFound("Resource not found [Book]"))
        }

      }

      case apiDoc(page) => {

        Some {
          sendFileInline(apiRepo, "api/" + page).getOrElse(NotFound(views.html.play20.manual(page, None, None, locator)))
        }

      }

      case wikiResource(path) => {

        Some {
          sendFileInline(repo, path).orElse(sendFileInline(apiRepo, path)).getOrElse(NotFound("Resource not found [" + path + "]"))
        }

      }

      case wikiPage(page) => {

        Some {
          markdownRenderer.renderPage(page) match {
            case None => NotFound(views.html.play20.manual(page, None, None, locator))
            case Some(RenderedPage(mainPage, None, _)) => Ok(views.html.play20.manual(page, Some(mainPage), None, locator))
            case Some(RenderedPage(mainPage, Some(sidebar), _)) => Ok(views.html.play20.manual(page, Some(mainPage), Some(sidebar), locator))
          }
        }
      }
      case _ => None
    }
  }
}

/**
 * Memoise a function.
 */
class Memoise[-T, +R](f: T => R) extends (T => R) {
  private[this] val cache = scala.collection.mutable.Map.empty[T, R]
  def apply(v: T): R = synchronized { cache.getOrElseUpdate(v, f(v)) }
}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework DocumentationHandler.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.