示例#1
0
  /**
   * Sends the given message as a PNG image. <strong>This method will block</strong> while image is
   * being generated. It's only recommended for cases where we want to report an error back to the
   * user and the user's browser expects a PNG image. Don't abuse it.
   *
   * @param status The status of the request (e.g. 200 OK or 404 Not Found).
   * @param msg The message to send as an image.
   * @param max_age The expiration time of this entity, in seconds. This is not a timestamp, it's
   *     how old the resource is allowed to be in the client cache. See RFC 2616 section 14.9 for
   *     more information. Use 0 to disable caching.
   */
  public void sendAsPNG(final HttpResponseStatus status, final String msg, final int max_age) {
    try {
      final long now = System.currentTimeMillis() / 1000;
      Plot plot = new Plot(now - 1, now);
      HashMap<String, String> params = new HashMap<String, String>(1);
      StringBuilder buf = new StringBuilder(1 + msg.length() + 18);

      buf.append('"');
      escapeJson(msg, buf);
      buf.append("\" at graph 0.02,0.97");
      params.put("label", buf.toString());
      buf = null;
      plot.setParams(params);
      params = null;
      final String basepath =
          RpcHandler.getDirectoryFromSystemProp("tsd.http.cachedir")
              + Integer.toHexString(msg.hashCode());
      GraphHandler.runGnuplot(this, basepath, plot);
      plot = null;
      sendFile(status, basepath + ".png", max_age);
    } catch (Exception e) {
      getQueryString().remove("png"); // Avoid recursion.
      internalError(
          new RuntimeException(
              "Failed to generate a PNG with the" + " following message: " + msg, e));
    }
  }