【Java】JFreeChart实现过滤日志画图

【背景】平时都是拿python来画个折线图的,这次自动化的项目需要用java,通过JFreeChart想着也做一份。
(其实完全可以java调用python脚本出图,毕竟用java画图少、图形单一)

【逻辑】

  1. 传log路径,获取关键字的值的列表:
    public void FilterLogValue(String logurl, String startTime, String endTime)

  2. 根据文件名称上的时间戳选择符合指定区间内的log:
    public List SelectLog(String logdir, String stratTime, String endTime)

  3. 画图参数修改:
    public JFreeChart createChart(CategoryDataset categoryDateset, String title, String X, String Y)

  4. JFreeChart画图步骤:
    public void DrewPic(CategoryDataset dataset, String title, String X, String Y)

JFreeChart freeChart = createChart(dataset, title, X, Y);
        ChartPanel chartf = new ChartPanel(freeChart, true);
        JFrame jf = new JFrame();
        jf.add(chartf, BorderLayout.WEST);
        jf.setVisible(false);
        jf.setSize(1400, 600);
        jf.setLocationRelativeTo(null);

【代码】

import org.apache.commons.io.FileUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

public class DrewPic {
    private List<Double> A_RTT_value = new ArrayList<>();
    private List<Double> A_loss_value = new ArrayList<>();
    private List<Double> A_table_target_bitrate_value = new ArrayList<>();

    public void FilterLogValue(String logurl, String startTime, String endTime) throws ParseException {
        String line;
        Date sTime = stringTimeToDateTime(startTime);
        Date eTime = stringTimeToDateTime(endTime);
        try (BufferedReader br = new BufferedReader(new FileReader(logurl))) {
            while ((line = br.readLine()) != null) {
                if (line.contains("CST") && line.contains("INFO")) {
                    String str = line.substring(0, 23);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
                    Date t = sdf.parse(str);
                    if (t.after(sTime)) {
                    }   
                    if (t.after(eTime)) {
                        break;
                    }
                    }
                }
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void DeleteLog(String logdir) throws IOException {
        File file = new File(logdir);
        FileUtils.cleanDirectory(file);
    }
		
    public List<String> SelectLog(String logdir, String stratTime, String endTime) throws ParseException, IOException {
        Date sTime = stringTimeToDateTime(stratTime);
        Date eTime = stringTimeToDateTime(endTime);
        File file = new File(logdir);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().contains("webrtc") || files[i].getName().contains("RoomsServiceHost")) {
                    targetLogList.add(logdir + files[i].getName());
                }
            }
        } else {
            if (file.getName().contains("webrtc") || file.getName().contains("RoomsServiceHost")) {
                targetLogList.add(logdir + file.getName());
            }
        }

        // 获取每个目标的log的名称上的时间
        for (int k = 0; k < targetLogList.size(); k++) {
            String logurl = targetLogList.get(k);
            File f = new File(logurl);
            String time = getTargetTimeName(f);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
            Date tt = sdf.parse(time);
            // 判断含webrtc的log在时间区间内
            if (tt.after(sTime) && tt.before(eTime)) {
                FilterLogValue(logurl, stratTime, endTime);
            }
        }
        return targetLogList;
    }

    public String getTargetTimeName(File file) throws ParseException {
        String timeName = "";
        if (file.getName().contains("webrtc")) {
            String yearStr = file.getName().split("-webrtc")[0];
            String y = yearStr.substring(0, 4);
            String M = yearStr.substring(5, 7);
            String d = yearStr.substring(8, 10);

            String H = yearStr.substring(11, 13);
            String m = yearStr.substring(13, 15);
            String s = yearStr.substring(15, 17);
            String SSS = yearStr.substring(18, 21);
            timeName = y + "-" + M + "-" + d + " " + H + ":" + m + ":" + s + "." + SSS;
        }
        if (file.getName().contains("RoomsServiceHost")) {
            String yearStr = file.getName().split("RoomsServiceHost-")[1].split("_")[0];
            String timeStr = file.getName().split("_")[1].split("_pid")[0];

            String y = yearStr.substring(0, 4);
            String M = yearStr.substring(4, 6);
            String d = yearStr.substring(6, 8);

            String H = timeStr.substring(0, 2);
            String m = timeStr.substring(2, 4);
            String s = timeStr.substring(4, 6);
            String SSS = timeStr.substring(6, 9);
            timeName = y + "-" + M + "-" + d + " " + H + ":" + m + ":" + s + "." + SSS;
        }
        return timeName;
    }

    public Date stringTimeToDateTime(String timeStr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
        Date dateTime = sdf.parse(timeStr);
        return dateTime;
    }

    public void DrewLogPicBaAudio() {
        CategoryDataset dataset = createDataSetAudio();
        DrewPic(dataset, "[BA] Audio", "", "");
    }

   
    public JFreeChart createChart(CategoryDataset categoryDateset, String title, String X, String Y) {

        // 创建JFreeChart对象:ChartFactory.createLineChart
        JFreeChart jfreechart = ChartFactory.createLineChart(title, // 标题
                X,         //categoryAxisLabel (category轴,横轴,X轴标签)
                Y,      // valueAxisLabel(value轴,纵轴,Y轴的标签)
                categoryDateset,  //Dataset
                PlotOrientation.VERTICAL, true, // legend
                true,          //Tooltips
                true);        //URLs

        // 使用CategoryPlot设置各种参数。
        CategoryPlot plot = (CategoryPlot) jfreechart.getPlot();

        // 背景色 透明度
        plot.setBackgroundAlpha(0.5f);

        // 前景色 透明度
        plot.setForegroundAlpha(1.0f);

        // 其他设置 参考 CategoryPlot类
        LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        renderer.setBaseShapesVisible(true); // series 点(即数据点)可见
        renderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见
        renderer.setUseSeriesOffset(true); // 设置偏移量
        renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(false); //秒点数据

        SimpleDateFormat formatter = new SimpleDateFormat("HH-mm-ss-SSS");
        Date date = new Date(System.currentTimeMillis());
        saveAsFile(jfreechart, "/Users/mickey.mei/Desktop/" + formatter.format(date) + ".png", 600, 400);

        return jfreechart;
    }

    public void saveAsFile(JFreeChart jfreechart, String outputPath, int weight, int height) {
        FileOutputStream out = null;
        try {
            File outFile = new File(outputPath);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            out = new FileOutputStream(outputPath);
            // 保存为PNG
            ChartUtilities.writeChartAsPNG(out, jfreechart, weight, height);
            // 保存为JPEG
            // ChartUtilities.writeChartAsJPEG(out, chart, weight, height);
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // do nothing
                }
            }
        }
    }

    public CategoryDataset createDataSetAudio() {
        String[] rowKeys = {"rtt", "loss", "bitrate"};
        String[] colKeys = new String[A_RTT_value.size()];
        for (int i = 0; i < A_RTT_value.size(); i++) {
            colKeys[i] = String.valueOf(i);
        }
        double[] colData1 = new double[A_RTT_value.size()];
        for (int j = 0; j < A_RTT_value.size(); j++) {
            colData1[j] = A_RTT_value.get(j);
        }

        double[] colData2 = new double[A_RTT_value.size()];
        for (int j = 0; j < A_RTT_value.size(); j++) {
            colData2[j] = A_loss_value.get(j);
        }

        double[] colData3 = new double[A_RTT_value.size()];
        for (int j = 0; j < A_RTT_value.size(); j++) {
            colData3[j] = A_table_target_bitrate_value.get(j);
        }

        double[][] data = new double[rowKeys.length][colKeys.length];
        data[0] = colData1;
        data[1] = colData2;
        data[2] = colData3;
        return DatasetUtilities.createCategoryDataset(rowKeys, colKeys, data);
    }

    public void DrewPic(CategoryDataset dataset, String title, String X, String Y) {
        JFreeChart freeChart = createChart(dataset, title, X, Y);
        ChartPanel chartf = new ChartPanel(freeChart, true);
        JFrame jf = new JFrame();
        jf.add(chartf, BorderLayout.WEST);
        jf.setVisible(false);
        jf.setSize(1400, 600);
        jf.setLocationRelativeTo(null);
    }

}

你可能感兴趣的:(java,java,开发语言)