public Result view(Context context) {

    Group group = context.getAttribute("group", Group.class);

    Map<Integer, GoogleTargetSummary> summaryByTagetId = new HashMap<>();
    Map<Integer, List<Integer>> scoreHistoryByTagetId = new HashMap<>();

    Run lastRun = baseDB.run.findLast(group.getModule(), RunDB.STATUSES_DONE, null);
    if (lastRun != null) {
      List<GoogleTargetSummary> summaries = googleDB.targetSummary.list(lastRun.getId());
      for (GoogleTargetSummary summary : summaries) {
        if (summary != null) {
          summaryByTagetId.put(summary.getTargetId(), summary);
          List<Integer> scoreHistory =
              googleDB.targetSummary.listScoreHistory(group.getId(), summary.getTargetId(), 30);
          int missingScore = 30 - scoreHistory.size();
          for (int i = 0; i < missingScore; i++) {
            scoreHistory.add(0, 0);
          }
          scoreHistoryByTagetId.put(summary.getTargetId(), scoreHistory);
        }
      }
    }

    return Results.ok()
        .render("events", baseDB.event.list(group, null, null))
        .render("default", googleDB.options.get())
        .render("searchesSize", context.getAttribute("searches", List.class).size())
        .render("targets", context.getAttribute("targets"))
        .render("summaries", summaryByTagetId)
        .render("histories", scoreHistoryByTagetId);
  }
  public Result debug(Context context) {

    return Results.ok()
    //            .render("f_warning",msg.get("test.translate", context,
    // Optional.absent(),12l).or(""))
    ;
  }
  public Result test(@Param("query") String query) throws SQLException {
    long _start = System.currentTimeMillis();

    HikariDataSource hds = null;
    if (ds instanceof HikariDataSource) {
      hds = (HikariDataSource) ds;
    } else {
      hds = ((P6DataSource) ds).unwrap(HikariDataSource.class);
    }

    if (query != null) {
      //            try(Connection con = DriverManager.getConnection(hds.getJdbcUrl()); Statement
      // stmt = con.createStatement() ){
      try (Connection con = ds.getConnection();
          Statement stmt = con.createStatement()) {
        stmt.execute(query);
      }
    }

    String duration = DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start);

    LOG.info(duration);

    return Results.ok().text().render(duration);
  }
  @FilterWith({XSRFFilter.class, AdminFilter.class})
  public Result exportSearches(Context context, @Params("id[]") String[] ids) {
    FlashScope flash = context.getFlashScope();
    Group group = context.getAttribute("group", Group.class);

    if (ids == null || ids.length == 0) {
      flash.error("error.noSearchSelected");
      return Results.redirect(
          router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }

    List<GoogleSearch> searches = new ArrayList<>();
    for (String id : ids) {
      GoogleSearch search = null;
      try {
        search = getSearch(context, Integer.parseInt(id));
      } catch (Exception ex) {
        search = null;
      }

      if (search == null) {
        flash.error("error.invalidSearch");
        return Results.redirect(
            router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
      }

      searches.add(search);
    }

    StringBuilder builder = new StringBuilder();
    for (GoogleSearch search : searches) {
      builder.append(StringEscapeUtils.escapeCsv(search.getKeyword())).append(",");
      builder.append(search.getTld() != null ? search.getTld() : "com").append(",");
      builder.append(search.getDatacenter() != null ? search.getDatacenter() : "").append(",");
      builder
          .append(
              search.getDevice() != null
                  ? (search.getDevice() == GoogleDevice.DESKTOP ? "desktop" : "mobile")
                  : "")
          .append(",");
      builder
          .append(StringEscapeUtils.escapeCsv(search.getLocal() != null ? search.getLocal() : ""))
          .append(",");
      builder
          .append(
              StringEscapeUtils.escapeCsv(
                  search.getCustomParameters() != null ? search.getCustomParameters() : ""))
          .append("\n");
    }

    return Results.ok().text().render(builder.toString());
  }
  public Result jsonSearches(Context context) {
    List<GoogleSearch> searches = context.getAttribute("searches", List.class);
    if (searches.isEmpty()) {
      return Results.json().renderRaw("[]");
    }

    return Results.ok()
        .json()
        .render(
            (Context context0, Result result) -> {
              PrintWriter writer = null;
              OutputStream os = null;
              try {

                String acceptEncoding = context0.getHeader("Accept-Encoding");
                if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                  result.addHeader("Content-Encoding", "gzip");
                }

                ResponseStreams response = context0.finalizeHeaders(result);
                os = response.getOutputStream();
                if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                  os = new GZIPOutputStream(os);
                }

                writer = new PrintWriter(os);
                writer.append("[");
                for (int i = 0; i < searches.size(); i++) {
                  GoogleSearch search = searches.get(i);
                  writer.append("{");
                  writer.append("\"id\":").append(Integer.toString(search.getId())).append(",");
                  writer
                      .append("\"keyword\":\"")
                      .append(StringEscapeUtils.escapeJson(search.getKeyword()))
                      .append("\",");
                  writer
                      .append("\"tld\":\"")
                      .append(
                          search.getTld() == null
                              ? ""
                              : StringEscapeUtils.escapeJson(search.getTld()))
                      .append("\",");
                  writer
                      .append("\"device\":\"")
                      .append(SMARTPHONE.equals(search.getDevice()) ? 'M' : 'D')
                      .append("\",");
                  writer
                      .append("\"local\":\"")
                      .append(
                          search.getLocal() == null
                              ? ""
                              : StringEscapeUtils.escapeJson(search.getLocal()))
                      .append("\",");
                  writer
                      .append("\"datacenter\":\"")
                      .append(
                          search.getDatacenter() == null
                              ? ""
                              : StringEscapeUtils.escapeJson(search.getDatacenter()))
                      .append("\",");
                  writer
                      .append("\"custom\":\"")
                      .append(
                          search.getCustomParameters() == null
                              ? ""
                              : StringEscapeUtils.escapeJson(search.getCustomParameters()))
                      .append("\"");
                  writer.append("}");
                  if (i != searches.size() - 1) {
                    writer.append(",");
                  }
                }
                writer.append("]");

              } catch (Exception ex) {
                LOG.warn("HTTP error", ex);
              } finally {
                if (os != null) {
                  try {
                    writer.close();
                    os.close();
                  } catch (Exception ex) {
                  }
                }
              }
            });
  }
 public Result settings() {
   return Results.ok().render("options", googleDB.options.get());
 }
 @FilterWith(XSRFFilter.class)
 public Result dummyPost() {
   return Results.ok().text().render("dummyPost");
 }
 public Result shutdown() {
   System.exit(0);
   return Results.ok();
 }