How to parse xml using groovy - groovy

I'm new to groovy xml parsing. I'm trying to parse the below xml file
<font face=Tahoma size=2>
Team,<br/><br/> Please find below the test summary details for the 'Test' execution.<br/><br/><b><U>Transaction Summary Table:</U></b><br/><br/>
<table border=1 CELLPADDING =3 style='font-family:Tahoma;font-size:12'>
<tr>
<b>
<th bgcolor=#C0C0C0> TransactionName </th>
<th bgcolor=#C0C0C0> AverageLatency </th>
<th bgcolor=#C0C0C0> MinimumLatency </th>
<th bgcolor=#C0C0C0> MaximumLatency </th>
<th bgcolor=#C0C0C0> AverageElapsedTime </th>
<th bgcolor=#C0C0C0> MinimumElapsedTime </th>
<th bgcolor=#C0C0C0> MaximumElapsedTime </th>
<th bgcolor=#C0C0C0> TotalCount </th>
<th bgcolor=#C0C0C0> PassPercentage </th>
</b>
</tr>
<tr>
<td>1 /aumentum/</td>
<td>
<center>1648.0</center>
</td>
<td>
<center>1240</center>
</td>
<td>
<center>2900</center>
</td>
<td>
<center>1907.0</center>
</td>
<td>
<center>1495</center>
</td>
<td>
<center>3140</center>
</td>
<td>
<center>45</center>
</td>
<td>
<center>100.0</center>
</td>
</tr>
<tr>
<td>T01_Aumentum_Home</td>
<td>
<center>6.0</center>
</td>
<td>
<center>1</center>
</td>
<td>
<center>10</center>
</td>
<td>
<center>1956.0</center>
</td>
<td>
<center>1490</center>
</td>
<td>
<center>3806</center>
</td>
<td>
<center>213</center>
</td>
<td>
<center>0.0</center>
</td>
</tr>
</tbody>
</table>
<br/><br/>Thanks,<br/>Performance Team.
</font>
<br/><br/>
Expected Result:
[{
"transaction name":"1 /aumentum/",
"AverageLatency ":"1648.0",
"Minimum latency":"1240",
"MaximumLatency ":"2900",
"AverageElapsedTime":"1907.0",
"MinimumElapsedTime":"1495",
"MaximumElapsedTime":"3140",
"TotalCount":"45",
"PassPercentage":"100.0"
},
{
"transaction name": "1 /aumentum/",
"AverageLatency ":"1648.0",
"Minimum latency":"1240",
"MaximumLatency ":"2900",
"AverageElapsedTime":"1907.0",
"MinimumElapsedTime":"1495",
"MaximumElapsedTime":"3140",
"TotalCount":"45",
"PassPercentage":"100.0"
}]
i have got the first children using values using docParser.getElementsByTag("tr").first()
Here is the error I get:
Exception thrown
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at org.jsoup.select.Elements.get(Elements.java:519)
at org.jsoup.nodes.Element.child(Element.java:174)
at org.jsoup.nodes.Element$child$0.call(Unknown Source)
at CommonUtils.parseLRHTMLReport(jmeteragent.groovy:304)
at CommonUtils$parseLRHTMLReport.call(Unknown Source)
Here is what I have done so far:
def transactiondetails12 = null
def iterator12 = 0
int count1 = 0
def violcounts = 0
def violations = null;
tmpElement = docParser.getElementsByTag("tr").first()
println tmpElement.children()
// tmpElement= tmpElement.child(0)
// println "#########tmpElement#########:" +tmpElement
for (element in tmpElement.children()) {
if (iterator12 == 0) {
// transactiondetails1 = "<table border=1 CELLPADDING =3 style='font-family:Tahoma;font-size:12'><tr><b><th bgcolor=#C0C0C0>" +
element.child(0).text().trim() + "</th><th bgcolor=#C0C0C0>" + element.child(2).text().trim() + "</th><th bgcolor=#C0C0C0>" +
element.child(3).text().trim() + "</th><th bgcolor=#C0C0C0>" + element.child(4).text().trim() + "</th></b></tr>"
iterator12 = 1;
count1++;
// println "nqwlieufrh 2938ry `9p23dhWCDNJ p3fu89 Q2390RUD"+transactiondetails1
} else {
count1++;
if (count1 <= 5) {
// println "iterator1iterator1iterator1iterator1"+iterator1++
transactiondetails12 = transactiondetails12 + "<tr><td>" + element.child(0).text().trim() + "</td><td><center>" +
element.child(2).text().trim() + "</center></td><td><center>" +
element.child(3).text().trim() + "</center></td><td><center>" +
element.child(4).text().trim()
println "transactiondetails12" + transactiondetails12
// println "3215463654156436212315465123011482145634217225445622341"+element.child(4).text().trim()
String violation1 = element.child(1).text()
// violation=Integer.valueOf(violation1)
// violation=Integer.parseInt(violation1)
// if(violation1>=0)
if (violation1.length() > 0) {
violcounts++
}
}
}
}
I have no idea how to map the tmpElement.children() values. Any advise on this would be helpful. Thanks in advance.

The sample you have provided uses jsoup library that is useful for HTML DOM manipulation. The solution to your problem is to use correct selectors to extract the data.
Consider following example:
def headers = docParser.select("tr > th").collect { it.text() }
def result = []
docParser.select("tr:has(td)").each { tr ->
def obj = [:]
tr.select("td").eachWithIndex { Element td, int i ->
obj[headers[i]] = td.text()
}
result << obj
}
println JsonOutput.prettyPrint(JsonOutput.toJson(result))
docParser.select("tr > th").collect { it.text() } collects table headers and stores them as an ordered List<String>
docParser.select("tr:has(td)") selects all rows (excluding table header) with data
tr.select("td").eachWithIndex iterates inside each row, collects the data and associates it with header by index i
the last line displays desired output to console
Output:
[
{
"TransactionName": "1 /aumentum/",
"AverageLatency": "1648.0",
"MinimumLatency": "1240",
"MaximumLatency": "2900",
"AverageElapsedTime": "1907.0",
"MinimumElapsedTime": "1495",
"MaximumElapsedTime": "3140",
"TotalCount": "45",
"PassPercentage": "100.0"
},
{
"TransactionName": "T01_Aumentum_Home",
"AverageLatency": "6.0",
"MinimumLatency": "1",
"MaximumLatency": "10",
"AverageElapsedTime": "1956.0",
"MinimumElapsedTime": "1490",
"MaximumElapsedTime": "3806",
"TotalCount": "213",
"PassPercentage": "0.0"
}
]
And here you can find full Groovy script I've used for experimenting with your example: https://gist.github.com/wololock/651a536dff4e104ebba0eef69d4ac3ea
I hope it helps.

Related

How do I make automatic height row based on content in the maatwebsite version 3 laravel excel?

I had search reference and the reference say to try like this :
<?php
...
class ReportExport implements ShouldAutoSize, FromView, WithColumnFormatting, WithEvents
{
...
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
...
$event->sheet->getDelegate()->getRowDimension(37)->setRowHeight(-1);
$event->sheet->getDelegate()->getStyle('R37:Z37')->getAlignment()->setWrapText(true);
},
];
}
}
I try like that, but the result like this :
Should the height of row automatic added based content/text. But it does not added
How can I solve this problem?
Update :
Seems this script : $event->sheet->getDelegate()->getRowDimension(37)->setRowHeight(-1); is not working in the table
I tried the script outside the table, it worked. So the script only work outside table tag
My table like this :
<table>
....
#php ($group = 'A')
#php ($number = 0)
#foreach($values as $item)
#if($number==0 || $group!=$item['group'])
<tr>
<td colspan="9">Kelompok {{$item['group']}}</td>
<td colspan="2"></td>
<td colspan="3"></td>
<td colspan="3"></td>
<td colspan="9"></td>
<td colspan="2"></td>
<td colspan="3"></td>
<td colspan="3"></td>
<td colspan="9"></td>
</tr>
#php ($number = 0)
#endif
<tr>
<td style="text-align:center;" colspan="2">{{++$number}}</td>
<td colspan="7">{{$item['lesson_name']}}</td>
<td style="text-align:center;" colspan="2">{{$item['kb_pengetahuan']}}</td>
<td style="text-align:center;" colspan="3">{{$item['nilai_pengetahuan']}}</td>
<td style="text-align:center;" colspan="3">{{$item['predikat_pengetahuan']}}</td>
<td colspan="9">{{$item['deskripsi_pengetahuan']}}</td>
<td style="text-align:center;" colspan="2">{{$item['kb_keterampilan']}}</td>
<td style="text-align:center;" colspan="3">{{$item['nilai_keterampilan']}}</td>
<td style="text-align:center;" colspan="3">{{$item['predikat_keterampilan']}}</td>
<td colspan="9">{{$item['deskripsi_keterampilan']}}</td>
</tr>
#php ($group = $item['group'])
#endforeach
</table>
Please help me. I need support for PhpSpreadsheet functionality
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
...
$event->sheet->getDelegate()
->getStyle('R37:Z37')
->applyFromArray([ 'alignment' => ['wrapText' => true]])
},
];
}

Get tr having specific th value from the table having an id using Xpath

I am using python3.6 with XPath library. Crawling inside the table gives me an empty list. And need to crawl to specific th.
My tr contents are dynamically generated. I need to crawl to tr which has a specific th value. Example In HTML code, the Rank appears in the second tr but it can appear in anywhere in tr. It doesn't have a specific index. Need to get the href from the tr having the Rank th.
My html file:
<tbody>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">
Product Number
</th>
<td class="a-size-base">
B003NR57BY
</td>
</tr>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">
Rank
</th>
<td>
<span>
<span>#3 in Computer Mice</span>
<br>
</span>
</td>
</tr>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">
Created Date
</th>
<td class="a-size-base">
June 7, 2010
</td>
</tr>
</tbody>
</table>
Python code:
listings_details = parser.xpath(XPATH_PRODUCT_DETAILS)
for row in listings_details:
th = row.xpath("./th/text()")
if th[0].strip() == 'Rank':
categories = row.xpath("./td/span/span//text()")
qid_url= row.xpath("./td/span/span//#href")
I expect the output to be
Rank: 3,
url : /gp/bestsellers/pc/11036491/ref=pd_zg_hrsr_pc_1_1_last,
category: Computer Mice
Need to get the href from the tr having the Rank th.
Use:
/table/tbody/tr[normalize-space(th)='Rank']/td//a/#href
Note: this works for your provided fragment (now well-formed). You need to add later a context for selecting the table element.
<table>
<tbody>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">Product Number</th>
<td class="a-size-base">B003NR57BY</td>
</tr>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">Rank</th>
<td>
<span>
<span>#3 in
Computer Mice
</span>
<br/>
</span>
</td>
</tr>
<tr>
<th class="a-color-secondary a-size-base prodDetSectionEntry">Created Date</th>
<td class="a-size-base">June 7, 2010</td>
</tr>
</tbody>
</table>
Test in http://www.xpathtester.com/xpath/53808ee94dfbc5b38f12791cf857ffb9

Jquery datatable not working for first row in colspan

I tried to bind dynamically partial view its working but for jquery
datatable against first row what I specified below its not working.
#model IEnumerable<PurModelClass>
<table id="stock-audit-table" class="table table-striped table-bordered dt-responsive nowrap">
<thead>
<tr>
#*<th>Purchase From</th>
<th>Purchase Date</th>*#
<th>Item Name</th>
<th>Qty</th>
<th>Unit</th>
<th>Cost</th>
<th>Net Amount</th>
<th>Discount</th>
<th>Vat</th>
<th>Gross</th>
</tr>
</thead>
<tbody id="stock-audit-tbody">
#foreach (var item in Model)
{
<tr><td colspan="8">Invoice No: #item.PurInvNo Inv Date: #($"{#item.PurDate:MMM-dd-yyyy}") Vendor: #item.VendorName </td></tr>
foreach (var detail in item.PurDetails)
{
<tr>
<td>#detail.StockName</td>
<td>#detail.PurQty</td>
<td>#detail.UnitName</td>
<td>#detail.UnitPrice</td>
<td>#detail.Total</td>
<td>#detail.Discount</td>
<td>#detail.VAT</td>
<td>#detail.NetAmount</td>
</tr>
}
}
</tbody>
<tfoot>
</tfoot>
</table>
This the datatable script, is there any way to implement jquery datatable by demanding specific row with colspan properties.
<script type="text/javascript">
$(document)
.ready(function() {
$('#stock-audit-table').DataTable({
"autoWidth": false,
"order": [[0, "desc"]]
});
}
);
</script>
Try the rowGroup extension. You can use startRender and endRender to customize the summary data
$('#stock-audit-table').DataTable({
"autoWidth": false,
"order": [[0, "desc"]],
"rowGroup": {
dataSrc: 0,
startRender: function(groupName){
return $('<tr/>').append("<td colspan="8">TODO put data here</td>");
}
}
});
<tbody id="stock-audit-tbody">
#foreach (var item in Model)
{
foreach (var detail in item.PurDetails)
{
<tr>
<td>
<!-- Define a key to be referenced by the
'datasrc' property in dataTables -->
#item.GroupName
</td>
<td>#detail.StockName</td>
<td>#detail.PurQty</td>
<td>#detail.UnitName</td>
<td>#detail.UnitPrice</td>
<td>#detail.Total</td>
<td>#detail.Discount</td>
<td>#detail.VAT</td>
<td>#detail.NetAmount</td>
</tr>
}
}
</tbody>

Iterating Hashmap in jsp and Showing Data in Dynamically Generated Table

I am having hashmap in jsp.
I want to print all the values that hashmap contains in a table. The table should generated dynamically and after 3 columns next values should be displayed in next row and so on..Using jstl or any tag library.
So if hashmap contains 6 values then HTML generated should be:
<table>
<tr>
<td> val1 </td>
<td> val2 </td>
<td> val3 </td>
</tr>
<tr>
<td> val1 </td>
<td> val2 </td>
<td> val3 </td>
</tr>
</table>
If hashmap contains 8 values then HTML generated should be:
<table>
<tr>
<td> val1 </td>
<td> val2 </td>
<td> val3 </td>
</tr>
<tr>
<td> val4 </td>
<td> val5 </td>
<td> val6 </td>
</tr>
<tr>
<td> val7 </td>
<td> val8 </td>
</tr>
</table>
So as per number of values the number of rows should get added to table. How do I do that in jsp... either using jstl tags or any custom tag library?
Simply add the following java code in your jsp
<table>
<%
int count=0;
Iterator itr = yourMap.iterator();
while(itr.hasNext()) {
String key = itr.next();
if(count ==0) {
%>
<tr>
<% } %>
<td><% =yourMap.get(key) %></td>
<%
count ++;
if(count ==3 ) {
count =0;
%>
</tr>
<%>
}
</table>
Here I am assuing your map is <String,String> and please import relevant classes for map and iterator. Any JSP tutorial can tell you how o do that

change color value with colorpicker

How do I change the bgcolor of 'colorId'. I tried the code below and I want the bgcolor to change in the value 'val'. But from then on I m doing something wrong.
<script type="text/javascript">
function updatevariable(elm) {
val = elm;
var divElement = document.getElementById(colorId);
divElement.bgcolor = val;
}
</script>
<table width="150" border="0" cellspacing="1" cellpading="0" align="center">
<tr>
<td bgcolor="#190707" onclick="updatevariable(this.bgColor)"> </td>
<td bgcolor="#fa5858" onclick="updatevariable(this.bgColor)"> </td>
<td bgcolor="#F4FA58" onclick="updatevariable(this.bgColor)"> </td>
<td bgcolor="#00FF00" onclick="updatevariable(this.bgColor)"> </td>
<td bgcolor="#fbefef" onclick="updatevariable(this.bgColor)"> </td>
</tr>
<tr>
<td id='colorId' bgcolor="#F4FA58"> </td>
</tr>
</table>
If you switch to jQuery you can do this in stead:
function updatevariable(elm){
var val = elm;
$('#colorId').css('background-color', val);
}
Just found your bugs. Use code below and it would work.
function updatevariable(elm) {
var val = elm;
var divElement = document.getElementById("colorId");
divElement.setAttribute("bgcolor", val);
}

Resources