关于jfreechart的几个知识点

关于jfreechart的几个知识点

1、文件生成
 系统临时目录的获取

System.getProperty("java.io.tmpdir")

 
 随机文件名产生

//第一个参数为前缀,第二个为后缀
File.createTempFile("jfreechart", "jpeg");

 
2、图片的自动删除

参考:

http://hi.baidu.com/qingcao_xiaohei/blog/item/aaeebd518599f410377abe1a.html

http://hi.baidu.com/paulau/blog/item/760d9634e2fbd849241f1468.html

主要是

Session代表客户的会话过程,客户登录时,往Session中传入一个对象,即可跟踪客户的会话。在Servlet中,传入Session的对象如果是一个实现HttpSessionBindingListener接口的对象(方便起见,此对象称为监听器),则在传入的时候(即调用HttpSession对象的setAttribute方法的时候)和移去的时候(即调用HttpSession对象的removeAttribute方法的时候或Session Time out的时候)Session对象会自动调用监听器的valueBound和valueUnbound方法(这是HttpSessionBindingListener接口中的方法)。

3、jfreechart源码

DisplayChart.java

package org.jfree.chart.servlet;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DisplayChart extends HttpServlet
{
  public void init()
    throws ServletException
  {
  }

  public void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    HttpSession session = request.getSession();
    String filename = request.getParameter("filename");
    if (filename == null) {
      throw new ServletException("Parameter 'filename' must be supplied");
    }

    filename = ServletUtilities.searchReplace(filename, "..", "");

    File file = new File(System.getProperty("java.io.tmpdir"), filename);
    if (!(file.exists())) {
      throw new ServletException("File '" + file.getAbsolutePath() + "' does not exist");
    }

    boolean isChartInUserList = false;
    ChartDeleter chartDeleter = (ChartDeleter)session.getAttribute("JFreeChart_Deleter");

    if (chartDeleter != null) {
      isChartInUserList = chartDeleter.isChartAvailable(filename);
    }

    boolean isChartPublic = false;
    if ((filename.length() >= 6) && 
      (filename.substring(0, 6).equals("public"))) {
      isChartPublic = true;
    }

    boolean isOneTimeChart = false;
    if (filename.startsWith(ServletUtilities.getTempOneTimeFilePrefix())) {
      isOneTimeChart = true;
    }

    if ((isChartInUserList) || (isChartPublic) || (isOneTimeChart))
    {
      ServletUtilities.sendTempFile(file, response);
      if (isOneTimeChart)
        file.delete();
    }
    else
    {
      throw new ServletException("Chart image not found");
    }
  }
}

 ServletUtilities.java

package org.jfree.chart.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;

public class ServletUtilities
{
  private static String tempFilePrefix = "jfreechart-";
  private static String tempOneTimeFilePrefix = "jfreechart-onetime-";

  public static String getTempFilePrefix()
  {
    return tempFilePrefix;
  }

  public static void setTempFilePrefix(String prefix)
  {
    if (prefix == null)
      throw new IllegalArgumentException("Null 'prefix' argument.");

    tempFilePrefix = prefix;
  }

  public static String getTempOneTimeFilePrefix()
  {
    return tempOneTimeFilePrefix;
  }

  public static void setTempOneTimeFilePrefix(String prefix)
  {
    if (prefix == null)
      throw new IllegalArgumentException("Null 'prefix' argument.");

    tempOneTimeFilePrefix = prefix;
  }

  public static String saveChartAsPNG(JFreeChart chart, int width, int height, HttpSession session)
    throws IOException
  {
    return saveChartAsPNG(chart, width, height, null, session);
  }

  public static String saveChartAsPNG(JFreeChart chart, int width, int height, ChartRenderingInfo info, HttpSession session)
    throws IOException
  {
    if (chart == null)
      throw new IllegalArgumentException("Null 'chart' argument.");

    createTempDir();
    String prefix = tempFilePrefix;
    if (session == null)
      prefix = tempOneTimeFilePrefix;

    File tempFile = File.createTempFile(prefix, ".png", new File(System.getProperty("java.io.tmpdir")));

    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null)
      registerChartForDeletion(tempFile, session);

    return tempFile.getName();
  }

  public static String saveChartAsJPEG(JFreeChart chart, int width, int height, HttpSession session)
    throws IOException
  {
    return saveChartAsJPEG(chart, width, height, null, session);
  }

  public static String saveChartAsJPEG(JFreeChart chart, int width, int height, ChartRenderingInfo info, HttpSession session)
    throws IOException
  {
    if (chart == null) {
      throw new IllegalArgumentException("Null 'chart' argument.");
    }

    createTempDir();
    String prefix = tempFilePrefix;
    if (session == null)
      prefix = tempOneTimeFilePrefix;

    File tempFile = File.createTempFile(prefix, ".jpeg", new File(System.getProperty("java.io.tmpdir")));

    ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
    if (session != null)
      registerChartForDeletion(tempFile, session);

    return tempFile.getName();
  }

  protected static void createTempDir()
  {
    String tempDirName = System.getProperty("java.io.tmpdir");
    if (tempDirName == null) {
      throw new RuntimeException("Temporary directory system property (java.io.tmpdir) is null.");
    }

    File tempDir = new File(tempDirName);
    if (!(tempDir.exists()))
      tempDir.mkdirs();
  }

  protected static void registerChartForDeletion(File tempFile, HttpSession session)
  {
    if (session != null) {
      ChartDeleter chartDeleter = (ChartDeleter)session.getAttribute("JFreeChart_Deleter");

      if (chartDeleter == null) {
        chartDeleter = new ChartDeleter();
        session.setAttribute("JFreeChart_Deleter", chartDeleter);
      }
      chartDeleter.addChart(tempFile.getName());
    }
    else {
      System.out.println("Session is null - chart will not be deleted");
    }
  }

  public static void sendTempFile(String filename, HttpServletResponse response)
    throws IOException
  {
    File file = new File(System.getProperty("java.io.tmpdir"), filename);
    sendTempFile(file, response);
  }

  public static void sendTempFile(File file, HttpServletResponse response)
    throws IOException
  {
    String mimeType = null;
    String filename = file.getName();
    if (filename.length() > 5)
      if (filename.substring(filename.length() - 5, filename.length()).equals(".jpeg"))
      {
        mimeType = "image/jpeg";
      }
      else if (filename.substring(filename.length() - 4, filename.length()).equals(".png"))
      {
        mimeType = "image/png";
      }

    sendTempFile(file, response, mimeType);
  }

  public static void sendTempFile(File file, HttpServletResponse response, String mimeType)
    throws IOException
  {
    if (file.exists()) {
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

      if (mimeType != null)
        response.setHeader("Content-Type", mimeType);

      response.setHeader("Content-Length", String.valueOf(file.length()));
      SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");

      sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
      response.setHeader("Last-Modified", sdf.format(new Date(file.lastModified())));

      BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

      byte[] input = new byte[1024];
      boolean eof = false;
      while (!(eof)) {
        int length = bis.read(input);
        if (length == -1) {
          eof = true;
        }
        else
          bos.write(input, 0, length);
      }

      bos.flush();
      bis.close();
      bos.close();
    }
    else {
      throw new FileNotFoundException(file.getAbsolutePath());
    }
  }

  public static String searchReplace(String inputString, String searchString, String replaceString)
  {
    int i = inputString.indexOf(searchString);
    if (i == -1) {
      return inputString;
    }

    String r = "";
    r = r + inputString.substring(0, i) + replaceString;
    if (i + searchString.length() < inputString.length()) {
      r = r + searchReplace(inputString.substring(i + searchString.length()), searchString, replaceString);
    }

    return r;
  }
}

 

ChartDeleter.java

 

package org.jfree.chart.servlet;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class ChartDeleter
  implements HttpSessionBindingListener
{
  private List chartNames = new ArrayList();

  public void addChart(String filename)
  {
    this.chartNames.add(filename);
  }

  public boolean isChartAvailable(String filename)
  {
    return this.chartNames.contains(filename);
  }

  public void valueBound(HttpSessionBindingEvent event)
  {
  }

  public void valueUnbound(HttpSessionBindingEvent event)
  {
    Iterator iter = this.chartNames.listIterator();
    while (iter.hasNext()) {
      String filename = (String)iter.next();
      File file = new File(System.getProperty("java.io.tmpdir"), filename);

      if (file.exists())
        file.delete();
    }
  }
}

 

你可能感兴趣的:(java,servlet,jfreechart,Blog)