<commit_before>/*
 * Copyright 2012 Twitter Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.twitter.zipkin.web

import com.codahale.jerkson.Json
import com.twitter.finatra.{Response, Controller, View, Request}
import com.twitter.logging.Logger
import com.twitter.util.Future
import com.twitter.zipkin.adapter.{JsonQueryAdapter, ThriftQueryAdapter}
import com.twitter.zipkin.gen
import com.twitter.zipkin.config.ZipkinWebConfig
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.Calendar
import com.twitter.zipkin.common.json.JsonTraceSummary

/**
 * Application that handles ZipkinWeb routes
 * @param config ZipkinWebConfig
 * @param client Thrift client to ZipkinQuery
 */
class App(config: ZipkinWebConfig, client: gen.ZipkinQuery.FinagledClient) extends Controller(config.statsReceiver) {

  val log = Logger.get()
  val dateFormat = new SimpleDateFormat("MM-dd-yyyy")
  val timeFormat = new SimpleDateFormat("HH:mm:ss")
  def getDate = dateFormat.format(Calendar.getInstance().getTime)
  def getTime = timeFormat.format(Calendar.getInstance().getTime)

  /* Index page */
  get("/") { request =>
    /* If valid query params passed, run the query and push the data down with the page */
    val queryResults = QueryRequest(request) match {
      case None => {
        /* Not valid params, load the normal landing page */
        Future(Seq.empty[JsonTraceSummary])
      }
      case Some(qr) => {
        /* Valid params */
        query(qr, request)
      }
    }
    getServices.map { services =>
      queryResults.map { qr =>
        render.view(wrapView(new IndexView(getDate, getTime, services, qr)))
      }
    }.flatten
  }

  /* Trace page */
  get("/show/:id") { request =>
    render.view(wrapView(new ShowView(request.params("id")))).toFuture
  }

  /* Static page for render trace from JSON */
  get("/static") { request =>
    render.view(wrapView(new StaticView)).toFuture
  }

  /**
   * API: query
   * Returns query results that satisfy the request parameters in order of descending duration
   *
   * Required GET params:
   * - service_name: String
   * - end_date: date String formatted to `QueryRequest.fmt`
   *
   * Optional GET params:
   * - limit: Int, default 100
   * - span_name: String
   * - time_annotation: String
   * - annotation_key, annotation_value: String
   * - adjust_clock_skew = (true|false), default true
   */
  get("/api/query") { request =>
    query(request).map(render.json(_))
  }

  def query(request: Request): Future[Seq[JsonTraceSummary]] = {
    QueryRequest(request) match {
      case Some(qr) => query(qr, request)
      case None     => Future(Seq.empty)
    }
  }

  def query(queryRequest: QueryRequest, request: Request): Future[Seq[JsonTraceSummary]] = {
    /* Get trace ids */
    val traceIds = queryRequest match {
      case r: SpanQueryRequest => {
        client.getTraceIdsBySpanName(r.serviceName, r.spanName, r.endTimestamp, r.limit, r.order)
      }
      case r: AnnotationQueryRequest => {
        client.getTraceIdsByAnnotation(r.serviceName, r.annotation, null, r.endTimestamp, r.limit, r.order)
      }
      case r: KeyValueAnnotationQueryRequest => {
        client.getTraceIdsByAnnotation(r.serviceName, r.key, ByteBuffer.wrap(r.value.getBytes), r.endTimestamp, r.limit, r.order)
      }
      case r: ServiceQueryRequest => {
        client.getTraceIdsByServiceName(r.serviceName, r.endTimestamp, r.limit, r.order)
      }
    }
    val adjusters = getAdjusters(request)<commit_msg>Fix NPE when querying for time annotations<commit_after>/*
 * Copyright 2012 Twitter Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.twitter.zipkin.web

import com.codahale.jerkson.Json
import com.twitter.finatra.{Response, Controller, View, Request}
import com.twitter.logging.Logger
import com.twitter.util.Future
import com.twitter.zipkin.adapter.{JsonQueryAdapter, ThriftQueryAdapter}
import com.twitter.zipkin.gen
import com.twitter.zipkin.config.ZipkinWebConfig
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.Calendar
import com.twitter.zipkin.common.json.JsonTraceSummary

/**
 * Application that handles ZipkinWeb routes
 * @param config ZipkinWebConfig
 * @param client Thrift client to ZipkinQuery
 */
class App(config: ZipkinWebConfig, client: gen.ZipkinQuery.FinagledClient) extends Controller(config.statsReceiver) {

  val log = Logger.get()
  val dateFormat = new SimpleDateFormat("MM-dd-yyyy")
  val timeFormat = new SimpleDateFormat("HH:mm:ss")
  def getDate = dateFormat.format(Calendar.getInstance().getTime)
  def getTime = timeFormat.format(Calendar.getInstance().getTime)

  /* Index page */
  get("/") { request =>
    /* If valid query params passed, run the query and push the data down with the page */
    val queryResults = QueryRequest(request) match {
      case None => {
        /* Not valid params, load the normal landing page */
        Future(Seq.empty[JsonTraceSummary])
      }
      case Some(qr) => {
        /* Valid params */
        query(qr, request)
      }
    }
    getServices.map { services =>
      queryResults.map { qr =>
        render.view(wrapView(new IndexView(getDate, getTime, services, qr)))
      }
    }.flatten
  }

  /* Trace page */
  get("/show/:id") { request =>
    render.view(wrapView(new ShowView(request.params("id")))).toFuture
  }

  /* Static page for render trace from JSON */
  get("/static") { request =>
    render.view(wrapView(new StaticView)).toFuture
  }

  /**
   * API: query
   * Returns query results that satisfy the request parameters in order of descending duration
   *
   * Required GET params:
   * - service_name: String
   * - end_date: date String formatted to `QueryRequest.fmt`
   *
   * Optional GET params:
   * - limit: Int, default 100
   * - span_name: String
   * - time_annotation: String
   * - annotation_key, annotation_value: String
   * - adjust_clock_skew = (true|false), default true
   */
  get("/api/query") { request =>
    query(request).map(render.json(_))
  }

  def query(request: Request): Future[Seq[JsonTraceSummary]] = {
    QueryRequest(request) match {
      case Some(qr) => query(qr, request)
      case None     => Future(Seq.empty)
    }
  }

  def query(queryRequest: QueryRequest, request: Request): Future[Seq[JsonTraceSummary]] = {
    /* Get trace ids */
    val traceIds = queryRequest match {
      case r: SpanQueryRequest => {
        client.getTraceIdsBySpanName(r.serviceName, r.spanName, r.endTimestamp, r.limit, r.order)
      }
      case r: AnnotationQueryRequest => {
        client.getTraceIdsByAnnotation(r.serviceName, r.annotation, ByteBuffer.wrap("".getBytes), r.endTimestamp, r.limit, r.order)
      }
      case r: KeyValueAnnotationQueryRequest => {
        client.getTraceIdsByAnnotation(r.serviceName, r.key, ByteBuffer.wrap(r.value.getBytes), r.endTimestamp, r.limit, r.order)
      }
      case r: ServiceQueryRequest => {
        client.getTraceIdsByServiceName(r.serviceName, r.endTimestamp, r.limit, r.order)
      }
    }
    val adjusters = getAdjusters(request)
{'fraction_non_alphanumeric': 0.11087891825445606, 'fraction_numerical': 0.002704363859864782, 'mean_word_length': 3.390717754991905, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '5395055', 'n_tokens_mistral': 2419, 'n_tokens_neox': 2358, 'n_words': 657}