Ngrinder Source Analysis: Detailed report page data display

Source: Internet
Author: User
Tags json readline
0. Background

When you look at the Ngrinder Detail Report page, you will show performance data results and timing diagrams, how are these internally implemented? This article will analyze the source code, give you a clear understanding. 1. Source Code Analysis

When you ask for http://ip/perftest/{testid}/detail_report; When viewing the detailed report page, the controller side forwards the request to the Perftest/detail_report template (ngrinder-controller/src/main/webapp/web-inf/ftl/perftest/ DETAIL_REPORT.FTL):

/**
 * Get The detailed perf test report.
 *
 * @param model
 * @param ID    Test ID
 * @return perftest/detail_report
 *
 * return to Detail_ REPORT.FTL
 */
@SuppressWarnings ("mvcpathvariableinspection")
@RequestMapping (value = {"/{id}/ Detail_report ",/** for backward compatibility */"/{id}/report "}) public
String GetReport (Modelmap model, @ Pathvariable ("id") long ID) {
    model.addattribute ("Test", Perftestservice.getone (ID));
    Model.addattribute ("Plugins", Perftestservice.getavailablereportplugins (ID));
    return "Perftest/detail_report";
}

Model.addattribute ("Test", Perftestservice.getone (ID));

Modelmap: Building a map of the model data to the front end

AddAttribute: Add a property for the specified name

Perftestservice.getone (ID): Gets the Perftest (performance statistics model) instance under the corresponding test ID

DETAIL_REPORT.FTL can get perftest member variable values based on test DETAIL_REPORT.FTL The data presentation in the template is divided into two parts:

1-1. First part: DB data

DB:H2, File save path:/root/.ngrinder/db

DETAIL_REPORT.FTL Local code example:

<tr>
    <th>< @spring. Message "perfTest.report.totalVusers"/></th>
    <td>< Strong>${test.vuserperagent * test.agentcount}</strong></td>
</tr>

Test.vuserperagent is based on the Perftestservice.getone (ID), obtains the Perftest instance from the DB, the front-end directly shows the member variable value. 2-2. Part II: Document Data

The second part is labeled Detail_panel; the default is Perfmenu

JS script:

<div id= "Detail_panel" > </div> <#--Left, execution report, target server, PLUGINS--<script> $ (document). Ready
        Ction () {var $perfMenu = $ ("Li.perf");
        var $monitorMenu = $ ("Li.monitor");

        var $pluginMenu = $ ("Li.plugin"); $perfMenu. Click (function () {$ ("#detail_panel"). Load ("${req.getcontextpath ()}/perftest/${(test.id)? C}/detail_
            Report/perf ");
        Changactivelink ($ (this));

        }); $monitorMenu. Click (function () {$ ("#detail_panel"). Load ("${req.getcontextpath ()}/perftest/${(test.id)? C}/deta
            Il_report/monitor?targetip= "+ $ (This). attr (" IP "));
        Changactivelink ($ (this));
        }); $pluginMenu. Click (function () {$ ("#detail_panel"). Load ("${req.getcontextpath ()}/perftest/${(test.id)? C}/detai
            L_report/plugin/"+ $ (This). attr (" plugin ") +"? kind= "+ $ (This). attr (" IP "));
        Changactivelink ($ (this));

        }); $.ajaxsetup ({"Cache": false});
    $perfMenu. Click ();

    });
        function Changactivelink (obj) {$ ("li.active"). Removeclass ("active");
    Obj.addclass ("active"); } </script>

To execute a report request:
${req.getcontextpath ()}/perftest/${(test.id) c}/detail_report/perf

The corresponding controller:

/**
 * Get The detailed perf test report.
 *
 * @param ID Test ID
 * @return perftest/detail_report/perf
 *
/@SuppressWarnings ({" Mvcpathvariableinspection "," Unusedparameters "})
@RequestMapping ("/{id}/detail_report/perf ")
public String Getdetailperfreport (@PathVariable ("id") long ID) {
    return ' perftest/detail_report/perf ';

Mapping to NGRINDER-CONTROLLER/SRC/MAIN/WEBAPP/WEB-INF/FTL/PERFTEST/DETAIL_REPORT/PERF.FTL templates

<div class= "Bigchart" id= "Tps_chart" ></div>  

Note: var ajaxobj = new Ajaxobj ("/perftest/api/" + TestID + "/perf");

Go to request @requestmapping ({"/api/{id}/perf", "/api/{id}/graph"})

/** * Get The detailed report graph data for the given perf test ID.
     * This method returns the appropriate points based on the given imgwidth. * * @param ID Test ID * @param dataType which data * @param imgwidth imagewidth * @return JSON s
     Tring. */@SuppressWarnings ("Mvcpathvariableinspection") @RestAPI @RequestMapping ({"/api/{id}/perf", "/api/{id}/graph
                                           "}") public httpentity<string> getperfgraph (@PathVariable ("id") long ID, @RequestParam (required = true, DefaultValue = "") String DataType, @RequestP
        Aram (defaultvalue = "false") Boolean onlytotal, @RequestParam int imgwidth) {
        String[] Datatypes = Checknotempty (Stringutils.split (DataType, ","), "dataType argument should be provided");
    Return tojsonhttpentity (Getperfgraphdata (ID, datatypes, onlytotal, imgwidth));
 }
 Where: Getperfgraphdata (ID, datatypes, onlytotal, ImgWidth) obtains data according to the *.data file (*.data writes the collected performance data to the file under the corresponding path when you perform a performance test, Path: '/root/.ngrinder/perftest/0_999/$testid/report ') Getperfgraphdata (ID, datatypes, onlytotal, imgwidth): 
 private map<string, object> getperfgraphdata (Long ID, string[] datatypes, Boolean OnlyT
        otal, int imgwidth) {final perftest test = Perftestservice.getone (ID);
        int interval = Perftestservice.getreportdatainterval (ID, datatypes[0], imgwidth);
        map<string, object> resultmap = Maps.newhashmap (); for (String each:datatypes) {pair<arraylist<string>, arraylist<string>> tpsresult = PerfT
            Estservice.getreportdata (ID, each, onlytotal, interval);
            map<string, object> dataMap = Maps.newhashmap ();
            Datamap.put ("Labels", Tpsresult.getfirst ());
            Datamap.put ("Data", Tpsresult.getsecond ());
        Resultmap.put (Stringutils.replacechars (each, "()", ""), DataMap);
        } resultmap.put (Param_test_chart_interval, INTERVAL * Test.getsamplinginterval ());
    return resultmap; }
perftestservice.getreportdata (): 
/** * Get list that contains test report data as a string.  * * @param testid Test ID * @param key Report Key * @param onlytotal True if only total show is passed * @param Interval interval to collect data * @return list containing label and TPS Value list */public PAIR&LT;ARRAYLIST&LT;STR Ing>, arraylist<string>> getreportdata (Long TestID, String key, Boolean onlytotal, int interval) {pair&lt ; Arraylist<string&gt, arraylist<string>> Resultpair = Pair.of (New arraylist<string> (), New A
    Rraylist<string> ()); List<file> reportdatafiles = onlytotal?
    Lists.newarraylist (Getreportdatafile (TestID, key)): Getreportdatafiles (TestID, key);
        for (file file:reportdatafiles) {String buildreportname = buildreportname (key, file);
        if (Key.equals (Buildreportname)) {buildreportname = "total";
        } else {buildreportname = Buildreportname.replace ("_", ""); } ResUltpair.getfirst (). Add (Buildreportname);
    Resultpair.getsecond (). Add (Getfiledataasjson (file, interval));
} return Resultpair;

 }
//read *.data converted to son string Getfiledataasjson (file, interval): 
/** * Get The test report data as a JSON string. * * @param targetfile target file * @param interval interval to collect data * @return JSON String * /Private String Getfiledataasjson (File targetfile, int interval) {if (!targetfile.exists ()) {RE
        Turn "[]";
        } StringBuilder reportdata = new StringBuilder ("[");
        FileReader reader = null;
        BufferedReader br = null;
            try {reader = new FileReader (targetfile);
            br = new BufferedReader (reader);
            String data = Br.readline ();
            int current = 0;
                    while (Stringutils.isnotblank (data)) {if (0 = = current) {reportdata.append (data);
                Reportdata.append (",");
                } if (++current >= interval) {current = 0;
            } data = Br.readline (); } if (ReportData. CharAt (Reportdata.length ()-1) = = ', ') {Reportdata.deletecharat (Reportdata.length ()-1);
            }} catch (IOException e) {logger.error ("Report data retrieval is failed: {}", E.getmessage ());
        Logger.debug ("Trace is:", e);
            } finally {ioutils.closequietly (reader);
        ioutils.closequietly (BR);
    } return Reportdata.append ("]"). ToString ();
 }
1-3. Timing diagram Data Interface vs. *data file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.