<commit_before>package org.fusesource.scalate.jersey

import java.io.OutputStream
import java.net.MalformedURLException
import javax.servlet.ServletContext
import com.sun.jersey.api.view.Viewable
import com.sun.jersey.spi.template.ViewProcessor
import com.sun.jersey.server.impl.container.servlet.RequestDispatcherWrapper
import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import com.sun.jersey.api.core.{HttpContext, ResourceConfig}
import org.fusesource.scalate.util.Logging
import com.sun.jersey.api.container.ContainerException
import org.fusesource.scalate.TemplateEngine
import java.lang.{String, Class}
import javax.ws.rs.core.{MultivaluedMap, MediaType, Context}
import java.lang.annotation.Annotation
import java.lang.reflect.Type
import org.fusesource.scalate.servlet.{ServletTemplateEngine, ServletHelper, TemplateEngineServlet}
import org.fusesource.scalate.support.ResourceLoader
import javax.ws.rs.ext.{Provider, MessageBodyWriter, MessageBodyReader}
import javax.ws.rs.Produces

/**
 * A template provider for <a href="https://jersey.dev.java.net/">Jersey</a> using Scalate templates
 * to produce HTML of an object.
 *
 * @version $Revision : 1.1 $
 */
@Provider
class ScalateTemplateProvider(@Context resourceConfig: ResourceConfig) extends MessageBodyWriter[AnyRef] with Logging {

  @Context
  var servletContext: ServletContext = _
  @Context
  var request: HttpServletRequest = _
  @Context
  var response: HttpServletResponse = _

  var templateDirectories = List("/WEB-INF", "")

  def resolve(loader:ResourceLoader, argType:Class[_]):String = {
    val argBase = argType.getName.replace('.','/')

    templateDirectories.foreach { dir =>
      TemplateEngine.templateTypes.foreach { types =>
        val path = dir + "/" + argBase + "." + types
        if( loader.exists(path) ) {
          return path
        }
      }
    }
    null
  }

  def getSize(arg: AnyRef, argType : Class[_], genericType: Type, annotations: Array[Annotation], mediaType: MediaType) = -1L

  def isWriteable(argType: Class[_], genericType: Type, annotations: Array[Annotation], mediaType: MediaType) = {
    if(mediaType.getType == "text" && mediaType.getSubtype == "html") {
      val servlet = TemplateEngineServlet()
      val path = resolve(servlet.templateEngine.resourceLoader, argType)
      path != null
    } else {
      false
    }
  }

  def writeTo(arg:AnyRef, argType:Class[_], genericType: Type, annotations: Array[Annotation], media: MediaType, headers: MultivaluedMap[String, AnyRef], out: OutputStream) = {
    // Ensure headers are committed
    out.flush()

    val servlet = TemplateEngineServlet()
    val path = resolve(servlet.templateEngine.resourceLoader, argType)
    path != null

    request.setAttribute("it", arg)

    try {
      servlet.render(path, request, response)
    } catch {
      case e: Exception =>
        // lets forward to the error handler
        var notFound = true
        for (uri <- ServletHelper.errorUris() if notFound) {
          if (servletContext.getResource(uri) != null) {

            // we need to expose all the errors property here...
            request.setAttribute("javax.servlet.error.exception", e)
            request.setAttribute("javax.servlet.error.exception_type", e.getClass)
            request.setAttribute("javax.servlet.error.message", e.getMessage)
            request.setAttribute("javax.servlet.error.request_uri", request.getRequestURI)
            request.setAttribute("javax.servlet.error.servlet_name", request.getServerName)

            // TODO how to get the status code???
            val status = 500<commit_msg>implicitly bind the object and also put the uri info in the attribute map.<commit_after>package org.fusesource.scalate.jersey

import java.io.OutputStream
import java.net.MalformedURLException
import javax.servlet.ServletContext
import com.sun.jersey.api.view.Viewable
import com.sun.jersey.spi.template.ViewProcessor
import com.sun.jersey.server.impl.container.servlet.RequestDispatcherWrapper
import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import com.sun.jersey.api.core.{HttpContext, ResourceConfig}
import org.fusesource.scalate.util.Logging
import com.sun.jersey.api.container.ContainerException
import java.lang.{String, Class}
import java.lang.annotation.Annotation
import java.lang.reflect.Type
import org.fusesource.scalate.support.ResourceLoader
import javax.ws.rs.ext.{Provider, MessageBodyWriter, MessageBodyReader}
import javax.ws.rs.Produces
import org.fusesource.scalate.servlet.{ServletRenderContext, ServletTemplateEngine, ServletHelper, TemplateEngineServlet}
import javax.ws.rs.core.{UriInfo, MultivaluedMap, MediaType, Context}
import org.fusesource.scalate.{Binding, TemplateEngine}

/**
 * A template provider for <a href="https://jersey.dev.java.net/">Jersey</a> using Scalate templates
 * to produce HTML of an object.
 *
 * @version $Revision : 1.1 $
 */
@Provider
class ScalateTemplateProvider extends MessageBodyWriter[AnyRef] with Logging {

  @Context
  var servletContext: ServletContext = _
  @Context
  var request: HttpServletRequest = _
  @Context
  var response: HttpServletResponse = _
  @Context
  var uriInfo:UriInfo = _

  var templateDirectories = List("/WEB-INF", "")

  def resolve(loader:ResourceLoader, argType:Class[_]):String = {
    val argBase = argType.getName.replace('.','/')

    templateDirectories.foreach { dir =>
      TemplateEngine.templateTypes.foreach { types =>
        val path = dir + "/" + argBase + "." + types
        if( loader.exists(path) ) {
          return path
        }
      }
    }
    null
  }

  def getSize(arg: AnyRef, argType : Class[_], genericType: Type, annotations: Array[Annotation], mediaType: MediaType) = -1L

  def isWriteable(argType: Class[_], genericType: Type, annotations: Array[Annotation], mediaType: MediaType) = {
    if(mediaType.getType == "text" && mediaType.getSubtype == "html") {
      val servlet = TemplateEngineServlet()
      val path = resolve(servlet.templateEngine.resourceLoader, argType)
      path != null
    } else {
      false
    }
  }

  def writeTo(arg:AnyRef, argType:Class[_], genericType: Type, annotations: Array[Annotation], media: MediaType, headers: MultivaluedMap[String, AnyRef], out: OutputStream) = {
    // Ensure headers are committed
    out.flush()

    val servlet = TemplateEngineServlet()
    val path = resolve(servlet.templateEngine.resourceLoader, argType)

    try {

      assert(path != null)

      request.setAttribute("uri_info", uriInfo)
      request.setAttribute("it", arg)

      val context = new ServletRenderContext(servlet.templateEngine, request, response, servletContext)
      context.include(path, true, List(Binding("it", argType.getName, false, None, "val",  true )))


    } catch {
      case e: Exception =>
        // lets forward to the error handler
        var notFound = true
        for (uri <- ServletHelper.errorUris() if notFound) {
          if (servletContext.getResource(uri) != null) {

            // we need to expose all the errors property here...
            request.setAttribute("javax.servlet.error.exception", e)
            request.setAttribute("javax.servlet.error.exception_type", e.getClass)
            request.setAttribute("javax.servlet.error.message", e.getMessage)
            request.setAttribute("javax.servlet.error.request_uri", request.getRequestURI)
            request.setAttribute("javax.servlet.error.servlet_name", request.getServerName)

            // TODO how to get the status code???
            val status = 500
{'fraction_non_alphanumeric': 0.11127263116162284, 'fraction_numerical': 0.0015858332232060262, 'mean_word_length': 3.76274386406545, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3320586', 'n_tokens_mistral': 2159, 'n_tokens_neox': 2132, 'n_words': 492}