javax.script package: How to import JavaScript files? - javax.script

I'm using javax.script package for running external JavaScript files within Java application.
How can I import one JavaScript file into another JavaScript file, without using Java code?

When you say without using java code, I am not completely sure what you mean, but this is a pure javascript that works (although it is calling java):
importPackage(java.io);
function loadJs(name, user) {
println("Loading " + name);
var f = new File(name);
var br = new BufferedReader(new FileReader(f));
var line = null;
var script = "";
while((line = br.readLine())!=null) {
script += line;
}
println(script);
eval(script);
hello(user);
}
...proivided, of course, that I have the file named (say c:/temp/hellouser.js) with something like:
function hello(name) { print('Hello, ' + name); }
I tested the script using a groovy script:
import javax.script.*;
sem = new ScriptEngineManager();
engine = sem.getEngineByExtension("js");
script1 = """
importPackage(java.io);
function loadJs(name, user) {
println("Loading " + name);
var f = new File(name);
var br = new BufferedReader(new FileReader(f));
var line = null;
var script = "";
while((line = br.readLine())!=null) {
script += line;
}
println(script);
eval(script);
hello(user);
}
""";
engine.eval(script1);
Object obj = engine.get("obj");
Invocable inv = (Invocable) engine;
inv.invokeFunction("loadJs", "c:/temp/hellouser.js", "Nicholas");
and the output was:
Loading c:/temp/hellouser.js
function hello(name) { print('Hello, ' + name); }
Hello, Nicholas
I hope this is approximately what you were looking for....
=========================== UPDATE ===========================
Here's a cleaned up version that extends the Rhino script engine factory (because the engine itself is final):
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import com.sun.script.javascript.RhinoScriptEngineFactory;
/**
* <p>Title: LoadEnabledRhinoEngineFactory</p>
* <p>Description: Adding a loadJs function to the standard JS engine</p>
* <p>Company: Helios Development Group LLC</p>
* #author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>org.helios.apmrouter.js.LoadEnabledRhinoEngineFactory</code></p>
*/
public class LoadEnabledRhinoEngineFactory extends RhinoScriptEngineFactory {
/** The load script source */
public static final String LOAD_JS =
"importPackage(java.io); " +
"var script = ''; " +
"var ctx = null; " +
"function loadScript(name) { " +
"var f = new File(name); " +
"var br = new BufferedReader(new FileReader(f)); " +
"var line = null; " +
"while((line = br.readLine())!=null) { " +
" script += line; " +
"} " +
"_e_ngine.eval(script);" +
"} ";
/**
* {#inheritDoc}
* #see com.sun.script.javascript.RhinoScriptEngineFactory#getScriptEngine()
*/
#Override
public ScriptEngine getScriptEngine() {
ScriptEngine se = super.getScriptEngine();
Bindings b = se.createBindings();
b.put("_e_ngine", se);
se.setBindings(b, ScriptContext.GLOBAL_SCOPE);
try {
se.eval(LOAD_JS);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
return se;
}
Now, loadScript(fileName) is part of the engine and you can cleanly call it with JS like:
loadScript('c:/temp/hellouser.js');
hello('Nicholas');"
or as I tested in Java:
ScriptEngine se = new LoadEnabledRhinoEngineFactory().getScriptEngine();
try {
se.eval("loadScript('c:/temp/hellouser.js'); hello('Nicholas');");
} catch (Exception e) {
e.printStackTrace(System.err);
}
Cheers.

Related

Can't search the same word again in Lucene search

I'm new to Lucene so i downloaded an example from http://www.lucenetutorial.com/sample-apps/textfileindexer-java.html .
The code currently works, however, I think I am not correctly making use of Lucene. I can search a word (ex : is student) for the first time, but after that (still in the loop), if i search the same word, it will return an exception. (java.lang.NullPointerException)
Please help me fix it.
Here's my problem
Here's the code
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import java.io.*;
import java.util.ArrayList;
public class TextFileIndexer {
private static StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
private IndexWriter writer;
private ArrayList<File> queue = new ArrayList<File>();
public static void main(String[] args) throws IOException {
System.out.println("Enter the path where the index will be created: (e.g. /tmp/index or c:\temp\index)");
String indexLocation = null;
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String s = br.readLine();
TextFileIndexer indexer = null;
try {
indexLocation = s;
indexer = new TextFileIndexer(s);
} catch (Exception ex) {
System.out.println("Cannot create index..." + ex.getMessage());
System.exit(-1);
}
while (!s.equalsIgnoreCase("q")) {
try {
System.out.println("Enter the full path to add into the index (q=quit): (e.g. /home/ron/mydir or c:\Users\ron\mydir)");
System.out.println("[Acceptable file types: .xml, .html, .html, .txt]");
s = br.readLine();
if (s.equalsIgnoreCase("q")) {
break;
}
indexer.indexFileOrDirectory(s);
} catch (Exception e) {
System.out.println("Error indexing " + s + " : " + e.getMessage());
}
}
indexer.closeIndex();
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexLocation)));
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(5, true);
s = "";
while (!s.equalsIgnoreCase("q")) {
try {
System.out.println("Enter the search query (q=quit):");
s = br.readLine();
if (s.equalsIgnoreCase("q")) {
break;
}
Query q = new QueryParser(Version.LUCENE_40, "contents", analyzer).parse(s);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// 4. display results
System.out.println("Found " + hits.length + " hits.");
for(int i=0;i<hits.length;++i) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i + 1) + ". " + d.get("path") + " score=" + hits[i].score);
}
} catch (Exception e) {
System.out.println("Error searching " + s + " : " + e.getMessage());
}
}
}
/**
* Constructor
* #param indexDir the name of the folder in which the index should be created
* #throws java.io.IOException when exception creating index.
*/
TextFileIndexer(String indexDir) throws IOException {
FSDirectory dir = FSDirectory.open(new File(indexDir));
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
writer = new IndexWriter(dir, config);
}
/**
* Indexes a file or directory
* #param fileName the name of a text file or a folder we wish to add to the index
* #throws java.io.IOException when exception
*/
public void indexFileOrDirectory(String fileName) throws IOException {
addFiles(new File(fileName));
int originalNumDocs = writer.numDocs();
for (File f : queue) {
FileReader fr = null;
try {
Document doc = new Document();
fr = new FileReader(f);
doc.add(new TextField("contents", fr));
doc.add(new StringField("path", f.getPath(), Field.Store.YES));
doc.add(new StringField("filename", f.getName(), Field.Store.YES));
writer.addDocument(doc);
System.out.println("Added: " + f);
} catch (Exception e) {
System.out.println("Could not add: " + f);
} finally {
fr.close();
}
}
int newNumDocs = writer.numDocs();
System.out.println("");
System.out.println("************************");
System.out.println((newNumDocs - originalNumDocs) + " documents added.");
System.out.println("************************");
queue.clear();
}
private void addFiles(File file) {
if (!file.exists()) {
System.out.println(file + " does not exist.");
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
addFiles(f);
}
} else {
String filename = file.getName().toLowerCase();
if (filename.endsWith(".htm") || filename.endsWith(".html") ||
filename.endsWith(".xml") || filename.endsWith(".txt")) {
queue.add(file);
} else {
System.out.println("Skipped " + filename);
}
}
}
public void closeIndex() throws IOException {
writer.close();
}
}
p/s: English is not my mother tongue so please ignore my grammar or word mistake.
I have checked your code. Simply you must instantiate the TopScoreDocCollector in the cycle before the method search. Below a snippet of your code with the comments where I changed the code:
...
//REMOVE AND INSTANTIATE IN THE CYCLE! TopScoreDocCollector collector = TopScoreDocCollector.create ( 5, true );
s = "";
while ( !s.equalsIgnoreCase ( "q" ) ) {
try {
System.out.println ( "Enter the search query (q=quit):" );
s = br.readLine ();
if ( s.equalsIgnoreCase ( "q" ) ) {
break;
}
// INTANTIATE HERE!!!
TopScoreDocCollector collector = TopScoreDocCollector.create ( 5, true );
Query q = new QueryParser ( Version.LUCENE_40, "contents", analyzer ).parse ( s );
searcher.search ( q, collector );
...
Otherwise you can use another signature of the method search and remove definitely the explicit instance of TopScoreDocCollector. For example:
TopDocs topDocs = searcher.search ( q, 5);
ScoreDoc[] hits = topDocs.scoreDocs;
I think you can solve your problem.

Run Multiple test cases with multiple test data sheet

I need help in selenium. I am trying to run multiple test cases with multiple test data sheets with TestNG and Data Provider concept. But I am having issue in running the test data. If I return array in Test, after getting the test data from sheet then starting from the one row of test cases again so it always run 1st row of the Data driven function.
If I return at the end of the DataDriven then last row will print the value in Test rest would get overnight.
Please let me know what I have to do to run the my test cases. I am attaching the code and Test cases and Test data sheet.
Test Cases & test data sheet
package testCases;
import java.util.Properties;
import operation.ReadObject;
import operation.UIOperation;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Iterator;
import java.lang.reflect.Method;
import excelExportAndFileIO.ReadExcelFile;
public class Test1 {
private static final Boolean True = null;
//WebDriver webdriver = null;
public static WebDriver driver;
private Cell Cell;
private Cell TCCellValue;
/* #BeforeSuite
public static void firefoxSetUp() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#AfterSuite
public static void closeFirefox(){
driver.quit();
}*/
#Test(dataProvider = "hybridData")
public void Permittee_Registration(String Status, String TC, String Module1, String Module2 ) { //String Status, String TCName, String TCDesc) throws Exception {
System.out.println("Status:"+Status +" ; TC:"+TC + " ; Module1:"+Module1 + " ; Module2:"+Module2);
}
// Call the test data sheet ----- PR = Permittee Registration
#Test(dataProvider = "hybridData")
public void PR_Applicant_Information(String TestCase, String URL, String objPermittee, String objPR, String PR_TITLE, String objLegal_Entity_Type, String Permittee_Legal_Name, String EIN ) {
System.out.println("PR_Applicant_Information Test");
if (TestCase!=null){
System.out.println("");
System.out.println("TestCase:"+TestCase + " ; PR_Applicant_Information URL:"+URL + " ; objPermittee: "+objPermittee + " ; objPR: " +objPR + " ; PR_TITLE: " +PR_TITLE + " ; objLegal_Entity_Type: " +objLegal_Entity_Type + " ; Permittee_Legal_Name: " + " ; EIN: " +EIN + "; dd: dd") ;
}
}
#Test(dataProvider = "hybridData")
public void PR_Choose_Qualification(String TC, String URL){
if (TC!=null){
System.out.println("");
System.out.println("PR_Choose_Qualification TC:"+TC + " ; URL: "+ URL);
}
}
#DataProvider(name = "hybridData")
public Iterator[] loginData(Method method) {
//System.out.println("Hybrid");
String TCName="";
Object[][] result = null;
Object[][] testData = new String[10][10];
Object[][] arrayObject = getExcelData(("user.dir") + "\\TestCaseSheet.xlsx", "TestCases_Modules",TCName);
//K=Row and L=Column
for (int k=0; k < arrayObject.length; k++){
int colCount=arrayObject[k].length;
//System.out.println("Column=arrayObject[k].length:"+arrayObject[k].length);
if ("YES".equals(arrayObject[k][0])){
//System.out.println("arrayObject[k][L]:"+arrayObject[k][L]+" ; K="+k+" ; L="+L);
//System.out.println("arrayObject[k][0]----:"+arrayObject[k][0] +" ; K = "+k );
for (int L=0; L< colCount ; L++){
//"Permittee_Registration"
//System.out.println("Permittee_Registration"+arrayObject[k][2]);
if ((arrayObject[k][L] !=null) && ((String)arrayObject[k][L]).indexOf(",") > 0) {
String[] pr = ((String)arrayObject[k][L] ).split(",");
//System.out.println("pr:"+pr.length + " ; PRValue:"+pr[0]);
for (int prN=0; prN < pr.length; prN++ ){
//System.out.println("for (int prN=0; prN < pr.length; prN++ )");
//pr=Applicant_Information
TCName=(String) arrayObject[k][1]; //fetching the Test Case Name
//System.out.println("TCName:"+TCName + " ; equals(pr[prN]) = "+equals(pr[prN]) + " ; pr.length="+pr.length + " ; pr[prN]="+ pr[prN]);
if ("Applicant_Information".equals(pr[prN])){
System.out.println("if (Applicant_Information.equals(pr[prN]))"+pr[prN] + " ; pr.length="+pr.length );
if (method.getName().equals("PR_Applicant_Information")) {
System.out.println("Applicant_Information Moni before calling excel sheet function:"+" ; result.length"+result.length);
//result = getExcelData(("user.dir") + "\\TestCaseSheet.xlsx", "Applicant_Information",TCName);
result = getExcelData(("user.dir") + "\\TestCaseSheet.xlsx", pr[prN] ,TCName);
//AI(result);
//System.out.println("Applicant_Information Moni afte calling excel sheet function:"+" ; result.length"+result.length);
//return result;
};
}
else if ("Choose_Qualification".equals(pr[prN])){
if (method.getName().equals("PR_Choose_Qualification")) {
//System.out.println("Choose_Qualification Moni before calling excel sheet function:"+pr[prN] +" ; result.length"+result.length);
result = getExcelData(("user.dir") + "\\TestCaseSheet.xlsx", "Choose_Qualification",TCName);
System.out.println("Choose_Qualification Moni after calling excel sheet function:"+pr[prN] +" ; result.length"+result.length);
};
}
}
//return result;
}
}
}
}
return result;
}
public void AI(Object result){
System.out.println("resultAI:"+result);
}
/**
* #param File
* Name
* #param Sheet
* Name
* #return
*/
public String[][] getExcelData(String fileName, String sheetName, String TCName) {
//public List<String> getExcelData(String fileName, String sheetName, String TCName) {
String[][] arrayExcelData = null;
int a=0;
int b=0;
try {
ReadExcelFile file = new ReadExcelFile();
// UIOperation operation = new UIOperation(driver);
// Read keyword sheet
Sheet testCaseSheet = file.readExcel(System.getProperty("user.dir") + "\\", "TestCaseSheet.xlsx", sheetName);
// Find number of rows in excel file
int rowCount = testCaseSheet.getLastRowNum() - testCaseSheet.getFirstRowNum();
int coulmnCount = testCaseSheet.getRow(0).getLastCellNum();
int firstCoulmnCount = testCaseSheet.getRow(0).getFirstCellNum();
arrayExcelData=new String[rowCount+1][coulmnCount];
//System.out.println("rowCount:"+rowCount);
//System.out.println("coulmnCount:"+coulmnCount);
//Looping the row
for (int i = testCaseSheet.getFirstRowNum(); i < (testCaseSheet.getLastRowNum()+1) ; i++) {
// Loop over all the rows
//Row row=testCaseSheet.getRow(i + 1);
int j;
if ("" != (TCName)){
//Object TCCellValues = null;
}
for (j = firstCoulmnCount; j < coulmnCount ; j++) {
Cell = testCaseSheet.getRow(i).getCell(j);
//System.out.println("TCName in recurring function :"+TCName);
//System.out.println("Cell:"+Cell);
//if TCName is equal to particular row then pick only that cell data.
TCCellValue = testCaseSheet.getRow(i).getCell(0);
String TCCellValues = TCCellValue.getStringCellValue();
//System.out.println("if ( != (TCCellValue)): " +TCCellValue + " ; TCName=" + TCName + " ; i="+i);
String CellData="";
//System.out.println("Cell inside:"+Cell);
if (Cell!=null){
CellData = Cell.getStringCellValue();
//System.out.println(i+":"+CellData);
}
if (TCName.equals("")||(TCName.equals(TCCellValues))){
arrayExcelData[i][j]=CellData;
//System.out.println("arrayExcelData[i][j]=CellData;"+CellData + " ; i="+i +" ; j="+j + " ; TCName="+TCName + " ; a="+a +" ; b="+b );
}
}
}
} catch (Exception e) {
System.out.println("Error " + e);
}
//System.out.println("Stop_arrayExcelData:");
return arrayExcelData;
//return new List<String>{{arrayExcelData}};
}
}

ArrayList Double

Im getting this error
java.lang.NumberFormatException: Invalid double: "-20.528899,"
im using a webservice to get latitude and longitude from bd, and show in a map.
I am not able to pass the latitude and longitude values to list
i am saving lat and long at the same column in db, so this field should be "lat, long" eg "-20.528899, -47.438933" and i need to parse this in the list...can i do this?
public List<Localizacoes> buscarLocalizacoes(){
List<Localizacoes> lista = new ArrayList<Localizacoes>();
SoapObject buscarLocalizacoes = new SoapObject(NAMESPACE, BUSCAR);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(buscarLocalizacoes);
envelope.implicitTypes = true;
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call("uri:" + BUSCAR, envelope);
Vector<SoapObject> resposta = (Vector<SoapObject>) envelope.getResponse();
for (SoapObject soapObject : resposta){
Localizacoes loc = new Localizacoes();
loc.setId(Integer.parseInt(soapObject.getProperty("id").toString()));
loc.setNome(soapObject.getProperty("nome").toString());
loc.setDescricao(soapObject.getProperty("descricao").toString());
loc.setPosicao(soapObject.getProperty("posicao").toString()); // error in this line
lista.add(loc);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return lista;
}
activity
dao = new LocalizacoesDAO(context);
List<Localizacoes> lista = dao.buscarLocalizacoes();
Log.d("Teste Buscar", lista.toString());
public void setPosicao(LatLng poLatLng) {
this.poLatLng = poLatLng;
this.posicao = String.valueOf(poLatLng.latitude) + " " + String.valueOf(poLatLng.longitude);
}
public void setPosicao(String posicao) {
this.posicao = posicao;
String[] pos = posicao.split(" ");
this.poLatLng = new LatLng(Double.valueOf(pos[0]), Double.valueOf(pos[1]));
}
can anyone help me pls?
Change the following line in your setPosicao(String) method
String[] pos = posicao.split(" ");
INTO
String[] pos = posicao.split(", ");
(Since you have a ',' and a ' ' in the string)

To Get the VM Created Date

I am new to the VMWare Sdk Programming,i have a requirement to get the Virtual Machine (VM) Deployed date.
I have written the below code to get the other required details.
package com.vmware.vim25.mo.samples;
import java.net.URL;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;
public class HelloVM {
public static void main(String[] args) throws Exception
{
long start = System.currentTimeMillis();
int i;
ServiceInstance si = new ServiceInstance(new URL("https://bgl-clvs-vc.bgl.com/sdk"), "sbibi", "sibi_123", true);
long end = System.currentTimeMillis();
System.out.println("time taken:" + (end-start));
Folder rootFolder = si.getRootFolder();
String name = rootFolder.getName();
System.out.println("root:" + name);
ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
System.out.println("No oF vm:" + mes.length);
if(mes==null || mes.length ==0)
{
return;
}
for(i=0;i<mes.length; i++){
VirtualMachine vm = (VirtualMachine) mes[i];
VirtualMachineConfigInfo vminfo = vm.getConfig();
VirtualMachineCapability vmc = vm.getCapability();
vm.getResourcePool();
System.out.println("VM Name " + vm.getName());
System.out.println("GuestOS: " + vminfo.getGuestFullName());
System.out.println("Multiple snapshot supported: " + vmc.isMultipleSnapshotsSupported());
System.out.println("Summary: " + vminfo.getDatastoreUrl());
}
si.getServerConnection().logout();
}
}
Can anyone help me how I can get the VM created date?
I have found the Vm Creation Date using the below codes.
EventFilterSpecByUsername uFilter =
new EventFilterSpecByUsername();
uFilter.setSystemUser(false);
uFilter.setUserList(new String[] {"administrator"});
Event[] events = evtMgr.queryEvents(efs);
// print each of the events
for(int i=0; events!=null && i<events.length; i++)
{
System.out.println("\nEvent #" + i);
printEvent(events[i]);
}
/**
* Only print an event as Event type.
*/
static void printEvent(Event evt)
{
String typeName = evt.getClass().getName();
int lastDot = typeName.lastIndexOf('.');
if(lastDot != -1)
{
typeName = typeName.substring(lastDot+1);
}
System.out.println("Time:" + evt.getCreatedTime().getTime());
}
Hope this code might help others.
private DateTime GetVMCreatedDate(VirtualMachine vm)
{
var date = DateTime. Now;
var userName = new EventFilterSpecByUsername ();
userName . SystemUser = false;
var filter = new EventFilterSpec ();
filter . UserName = userName;
filter . EventTypeId = ( new String [] { "VmCreatedEvent" , "VmBeingDeployedEvent" ,"VmRegisteredEvent" , "VmClonedEvent" });
var collector = vm .GetEntityOnlyEventsCollectorView(filter);
foreach (Event e in collector . ReadNextEvents(1 ))
{
Console .WriteLine(e . GetType(). ToString() + " :" + e. CreatedTime);
date = e. CreatedTime;
}
Console .WriteLine( "---------------------------------------------------" );
return date;
}

Customizing summary section of TestNG emailable report

TestNG generates an emailable report. I have seen that this report can be customized by using Listeners. But could not get what i wanted. My requirement is to include extra details in the summary section of this report. I want to be able to add may be a new table or extra columns to show the environment details of the test execution.
Trying to attach a screenshot but apparently missing something and it does not come up.
That is what I have on my framework. I'll try to explain it (sorry my English)
Copy ReporterListenerAdapter.java and rename as MyReporterListenerAdapter.java, put it on your java project (/listener folder for example)
public class MyReporterListenerAdapter implements IReporter {
public void generateReport(List<XmlSuite> xml, List<ISuite> suites, String outdir) {}
}
Next, copy ReporterListener.java and rename as MyReporterListener.java
Too much code to paste here, but on createWriter function change the report name. For example: "emailable-MyFramework-report".
MyReporterListener.java
public class MyReporterListener extends MyReporterListenerAdapter {
private static final Logger L = Logger.getLogger(MyReporterListener.class);
// ~ Instance fields ------------------------------------------------------
private PrintWriter m_out;
private int m_row;
private Integer m_testIndex;
private int m_methodIndex;
private Scanner scanner;
// ~ Methods --------------------------------------------------------------
/** Creates summary of the run */
#Override
public void generateReport(List<XmlSuite> xml, List<ISuite> suites,
String outdir) {
try {
m_out = createWriter(outdir);
} catch (IOException e) {
L.error("output file", e);
return;
}
startHtml(m_out);
generateSuiteSummaryReport(suites);
generateMethodSummaryReport(suites);
generateMethodDetailReport(suites);
endHtml(m_out);
m_out.flush();
m_out.close();
}
protected PrintWriter createWriter(String outdir) throws IOException {
java.util.Date now = new Date();
new File(outdir).mkdirs();
return new PrintWriter(new BufferedWriter(new FileWriter(new File(
outdir, "emailable-FON-report"
+ DateFunctions.dateToDayAndTimeForFileName(now)
+ ".html"))));
}
/**
* Creates a table showing the highlights of each test method with links to
* the method details
*/
protected void generateMethodSummaryReport(List<ISuite> suites) {
m_methodIndex = 0;
startResultSummaryTable("methodOverview");
int testIndex = 1;
for (ISuite suite : suites) {
if (suites.size() > 1) {
titleRow(suite.getName(), 5);
}
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
ITestContext testContext = r2.getTestContext();
String testName = testContext.getName();
m_testIndex = testIndex;
resultSummary(suite, testContext.getFailedConfigurations(),
testName, "failed", " (configuration methods)");
resultSummary(suite, testContext.getFailedTests(), testName,
"failed", "");
resultSummary(suite, testContext.getSkippedConfigurations(),
testName, "skipped", " (configuration methods)");
resultSummary(suite, testContext.getSkippedTests(), testName,
"skipped", "");
resultSummary(suite, testContext.getPassedTests(), testName,
"passed", "");
testIndex++;
}
}
m_out.println("</table>");
}
/** Creates a section showing known results for each method */
protected void generateMethodDetailReport(List<ISuite> suites) {
m_methodIndex = 0;
for (ISuite suite : suites) {
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
ITestContext testContext = r2.getTestContext();
if (r.values().size() > 0) {
m_out.println("<h1>" + testContext.getName() + "</h1>");
}
resultDetail(testContext.getFailedConfigurations());
resultDetail(testContext.getFailedTests());
resultDetail(testContext.getSkippedConfigurations());
resultDetail(testContext.getSkippedTests());
resultDetail(testContext.getPassedTests());
}
}
}
/**
* #param tests
*/
private void resultSummary(ISuite suite, IResultMap tests, String testname,
String style, String details) {
if (tests.getAllResults().size() > 0) {
StringBuffer buff = new StringBuffer();
String lastClassName = "";
int mq = 0;
int cq = 0;
for (ITestNGMethod method : getMethodSet(tests, suite)) {
m_row += 1;
m_methodIndex += 1;
ITestClass testClass = method.getTestClass();
String className = testClass.getName();
if (mq == 0) {
String id = (m_testIndex == null ? null : "t"
+ Integer.toString(m_testIndex));
titleRow(testname + " — " + style + details, 5, id);
m_testIndex = null;
}
if (!className.equalsIgnoreCase(lastClassName)) {
if (mq > 0) {
cq += 1;
m_out.print("<tr class=\"" + style
+ (cq % 2 == 0 ? "even" : "odd") + "\">"
+ "<td");
if (mq > 1) {
m_out.print(" rowspan=\"" + mq + "\"");
}
m_out.println(">" + lastClassName + "</td>" + buff);
}
mq = 0;
buff.setLength(0);
lastClassName = className;
}
Set<ITestResult> resultSet = tests.getResults(method);
long end = Long.MIN_VALUE;
long start = Long.MAX_VALUE;
for (ITestResult testResult : tests.getResults(method)) {
if (testResult.getEndMillis() > end) {
end = testResult.getEndMillis();
}
if (testResult.getStartMillis() < start) {
start = testResult.getStartMillis();
}
}
mq += 1;
if (mq > 1) {
buff.append("<tr class=\"" + style
+ (cq % 2 == 0 ? "odd" : "even") + "\">");
}
String description = method.getDescription();
String testInstanceName = resultSet
.toArray(new ITestResult[] {})[0].getTestName();
buff.append("<td><a href=\"#m"
+ m_methodIndex
+ "\">"
+ qualifiedName(method)
+ " "
+ (description != null && description.length() > 0 ? "(\""
+ description + "\")"
: "")
+ "</a>"
+ (null == testInstanceName ? "" : "<br>("
+ testInstanceName + ")") + "</td>"
+ "<td class=\"numi\">" + resultSet.size() + "</td>"
+ "<td>" + start + "</td>" + "<td class=\"numi\">"
+ (end - start) + "</td>" + "</tr>");
}
if (mq > 0) {
cq += 1;
m_out.print("<tr class=\"" + style
+ (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td");
if (mq > 1) {
m_out.print(" rowspan=\"" + mq + "\"");
}
m_out.println(">" + lastClassName + "</td>" + buff);
}
}
}
/** Starts and defines columns result summary table */
private void startResultSummaryTable(String style) {
tableStart(style, "summary");
m_out.println("<tr><th>Class</th>"
+ "<th>Method</th><th># of<br/>Scenarios</th><th>Start</th><th>Time<br/>(ms)</th></tr>");
m_row = 0;
}
private String qualifiedName(ITestNGMethod method) {
StringBuilder addon = new StringBuilder();
String[] groups = method.getGroups();
int length = groups.length;
if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) {
addon.append("(");
for (int i = 0; i < length; i++) {
if (i > 0) {
addon.append(", ");
}
addon.append(groups[i]);
}
addon.append(")");
}
return "<b>" + method.getMethodName() + "</b> " + addon;
}
private void resultDetail(IResultMap tests) {
for (ITestResult result : tests.getAllResults()) {
ITestNGMethod method = result.getMethod();
m_methodIndex++;
String cname = method.getTestClass().getName();
m_out.println("<h2 id=\"m" + m_methodIndex + "\">" + cname + ":"
+ method.getMethodName() + "</h2>");
Set<ITestResult> resultSet = tests.getResults(method);
generateForResult(result, method, resultSet.size());
m_out.println("<p class=\"totop\">back to summary</p>");
}
}
/**
* Write the first line of the stack trace
*
* #param tests
*/
private void getShortException(IResultMap tests) {
for (ITestResult result : tests.getAllResults()) {
m_methodIndex++;
Throwable exception = result.getThrowable();
List<String> msgs = Reporter.getOutput(result);
boolean hasReporterOutput = msgs.size() > 0;
boolean hasThrowable = exception != null;
if (hasThrowable) {
boolean wantsMinimalOutput = result.getStatus() == ITestResult.SUCCESS;
if (hasReporterOutput) {
m_out.print("<h3>"
+ (wantsMinimalOutput ? "Expected Exception"
: "Failure") + "</h3>");
}
// Getting first line of the stack trace
String str = Utils.stackTrace(exception, true)[0];
scanner = new Scanner(str);
String firstLine = scanner.nextLine();
m_out.println(firstLine);
}
}
}
/**
* Write all parameters
*
* #param tests
*/
private void getParameters(IResultMap tests) {
for (ITestResult result : tests.getAllResults()) {
m_methodIndex++;
Object[] parameters = result.getParameters();
boolean hasParameters = parameters != null && parameters.length > 0;
if (hasParameters) {
for (Object p : parameters) {
m_out.println(Utils.escapeHtml(Utils.toString(p)) + " | ");
}
}
}
}
private void generateForResult(ITestResult ans, ITestNGMethod method,
int resultSetSize) {
Object[] parameters = ans.getParameters();
boolean hasParameters = parameters != null && parameters.length > 0;
if (hasParameters) {
tableStart("result", null);
m_out.print("<tr class=\"param\">");
for (int x = 1; x <= parameters.length; x++) {
m_out.print("<th>Param." + x + "</th>");
}
m_out.println("</tr>");
m_out.print("<tr class=\"param stripe\">");
for (Object p : parameters) {
m_out.println("<td>" + Utils.escapeHtml(Utils.toString(p))
+ "</td>");
}
m_out.println("</tr>");
}
List<String> msgs = Reporter.getOutput(ans);
boolean hasReporterOutput = msgs.size() > 0;
Throwable exception = ans.getThrowable();
boolean hasThrowable = exception != null;
if (hasReporterOutput || hasThrowable) {
if (hasParameters) {
m_out.print("<tr><td");
if (parameters.length > 1) {
m_out.print(" colspan=\"" + parameters.length + "\"");
}
m_out.println(">");
} else {
m_out.println("<div>");
}
if (hasReporterOutput) {
if (hasThrowable) {
m_out.println("<h3>Test Messages</h3>");
}
for (String line : msgs) {
m_out.println(line + "<br/>");
}
}
if (hasThrowable) {
boolean wantsMinimalOutput = ans.getStatus() == ITestResult.SUCCESS;
if (hasReporterOutput) {
m_out.println("<h3>"
+ (wantsMinimalOutput ? "Expected Exception"
: "Failure") + "</h3>");
}
generateExceptionReport(exception, method);
}
if (hasParameters) {
m_out.println("</td></tr>");
} else {
m_out.println("</div>");
}
}
if (hasParameters) {
m_out.println("</table>");
}
}
protected void generateExceptionReport(Throwable exception,
ITestNGMethod method) {
m_out.print("<div class=\"stacktrace\">");
m_out.print(Utils.stackTrace(exception, true)[0]);
m_out.println("</div>");
}
/**
* Since the methods will be sorted chronologically, we want to return the
* ITestNGMethod from the invoked methods.
*/
private Collection<ITestNGMethod> getMethodSet(IResultMap tests,
ISuite suite) {
List<IInvokedMethod> r = Lists.newArrayList();
List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods();
for (IInvokedMethod im : invokedMethods) {
if (tests.getAllMethods().contains(im.getTestMethod())) {
r.add(im);
}
}
Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new TestSorter());
List<ITestNGMethod> result = Lists.newArrayList();
// Add all the invoked methods
for (IInvokedMethod m : r) {
result.add(m.getTestMethod());
}
// Add all the methods that weren't invoked (e.g. skipped) that we
// haven't added yet
for (ITestNGMethod m : tests.getAllMethods()) {
if (!result.contains(m)) {
result.add(m);
}
}
return result;
}
#SuppressWarnings("unused")
public void generateSuiteSummaryReport(List<ISuite> suites) {
tableStart("testOverview", null);
m_out.print("<tr>");
tableColumnStart("Test");
tableColumnStart("Methods<br/>Passed");
tableColumnStart("Scenarios<br/>Passed");
tableColumnStart("# skipped");
tableColumnStart("# failed");
tableColumnStart("Error messages");
tableColumnStart("Parameters");
tableColumnStart("Start<br/>Time");
tableColumnStart("End<br/>Time");
tableColumnStart("Total<br/>Time");
tableColumnStart("Included<br/>Groups");
tableColumnStart("Excluded<br/>Groups");
m_out.println("</tr>");
NumberFormat formatter = new DecimalFormat("#,##0.0");
int qty_tests = 0;
int qty_pass_m = 0;
int qty_pass_s = 0;
int qty_skip = 0;
int qty_fail = 0;
long time_start = Long.MAX_VALUE;
long time_end = Long.MIN_VALUE;
m_testIndex = 1;
for (ISuite suite : suites) {
if (suites.size() > 1) {
titleRow(suite.getName(), 8);
}
Map<String, ISuiteResult> tests = suite.getResults();
for (ISuiteResult r : tests.values()) {
qty_tests += 1;
ITestContext overview = r.getTestContext();
startSummaryRow(overview.getName());
int q = getMethodSet(overview.getPassedTests(), suite).size();
qty_pass_m += q;
summaryCell(q, Integer.MAX_VALUE);
q = overview.getPassedTests().size();
qty_pass_s += q;
summaryCell(q, Integer.MAX_VALUE);
q = getMethodSet(overview.getSkippedTests(), suite).size();
qty_skip += q;
summaryCell(q, 0);
q = getMethodSet(overview.getFailedTests(), suite).size();
qty_fail += q;
summaryCell(q, 0);
// NEW
// Insert error found
m_out.print("<td class=\"numi" + (true ? "" : "_attn") + "\">");
getShortException(overview.getFailedTests());
getShortException(overview.getSkippedTests());
m_out.println("</td>");
// NEW
// Add parameters for each test case (failed or passed)
m_out.print("<td class=\"numi" + (true ? "" : "_attn") + "\">");
// Write OS and Browser
// m_out.println(suite.getParameter("os").substring(0, 3) +
// " | "
// + suite.getParameter("browser").substring(0, 3) + " | ");
getParameters(overview.getFailedTests());
getParameters(overview.getPassedTests());
getParameters(overview.getSkippedTests());
m_out.println("</td>");
// NEW
summaryCell(
DateFunctions.dateToDayAndTime(overview.getStartDate()),
true);
m_out.println("</td>");
summaryCell(
DateFunctions.dateToDayAndTime(overview.getEndDate()),
true);
m_out.println("</td>");
time_start = Math.min(overview.getStartDate().getTime(),
time_start);
time_end = Math.max(overview.getEndDate().getTime(), time_end);
summaryCell(
formatter.format((overview.getEndDate().getTime() - overview
.getStartDate().getTime()) / 1000.)
+ " seconds", true);
summaryCell(overview.getIncludedGroups());
summaryCell(overview.getExcludedGroups());
m_out.println("</tr>");
m_testIndex++;
}
}
if (qty_tests > 1) {
m_out.println("<tr class=\"total\"><td>Total</td>");
summaryCell(qty_pass_m, Integer.MAX_VALUE);
summaryCell(qty_pass_s, Integer.MAX_VALUE);
summaryCell(qty_skip, 0);
summaryCell(qty_fail, 0);
summaryCell(" ", true);
summaryCell(" ", true);
summaryCell(" ", true);
summaryCell(" ", true);
summaryCell(
formatter.format(((time_end - time_start) / 1000.) / 60.)
+ " minutes", true);
m_out.println("<td colspan=\"3\"> </td></tr>");
}
m_out.println("</table>");
}
private void summaryCell(String[] val) {
StringBuffer b = new StringBuffer();
for (String v : val) {
b.append(v + " ");
}
summaryCell(b.toString(), true);
}
private void summaryCell(String v, boolean isgood) {
m_out.print("<td class=\"numi" + (isgood ? "" : "_attn") + "\">" + v
+ "</td>");
}
private void startSummaryRow(String label) {
m_row += 1;
m_out.print("<tr"
+ (m_row % 2 == 0 ? " class=\"stripe\"" : "")
+ "><td style=\"text-align:left;padding-right:2em\"><a href=\"#t"
+ m_testIndex + "\">" + label + "</a>" + "</td>");
}
private void summaryCell(int v, int maxexpected) {
summaryCell(String.valueOf(v), v <= maxexpected);
}
private void tableStart(String cssclass, String id) {
m_out.println("<table cellspacing=\"0\" cellpadding=\"0\""
+ (cssclass != null ? " class=\"" + cssclass + "\""
: " style=\"padding-bottom:2em\"")
+ (id != null ? " id=\"" + id + "\"" : "") + ">");
m_row = 0;
}
private void tableColumnStart(String label) {
m_out.print("<th>" + label + "</th>");
}
private void titleRow(String label, int cq) {
titleRow(label, cq, null);
}
private void titleRow(String label, int cq, String id) {
m_out.print("<tr");
if (id != null) {
m_out.print(" id=\"" + id + "\"");
}
m_out.println("><th colspan=\"" + cq + "\">" + label + "</th></tr>");
m_row = 0;
}
/** Starts HTML stream */
protected void startHtml(PrintWriter out) {
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
out.println("<head>");
out.println("<title>Hector Flores - TestNG Report</title>");
out.println("<style type=\"text/css\">");
out.println("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}");
out.println("td,th {border:1px solid #009;padding:.25em .5em}");
out.println(".result th {vertical-align:bottom}");
out.println(".param th {padding-left:1em;padding-right:1em}");
out.println(".param td {padding-left:.5em;padding-right:2em}");
out.println(".stripe td,.stripe th {background-color: #E6EBF9}");
out.println(".numi,.numi_attn {text-align:right}");
out.println(".total td {font-weight:bold}");
out.println(".passedodd td {background-color: #0A0}");
out.println(".passedeven td {background-color: #3F3}");
out.println(".skippedodd td {background-color: #CCC}");
out.println(".skippedodd td {background-color: #DDD}");
out.println(".failedodd td,.numi_attn {background-color: #F33}");
out.println(".failedeven td,.stripe .numi_attn {background-color: #D00}");
out.println(".stacktrace {white-space:pre;font-family:monospace}");
out.println(".totop {font-size:85%;text-align:center;border-bottom:2px solid #000}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
}
/** Finishes HTML stream */
protected void endHtml(PrintWriter out) {
out.println("<center> Report customized by Hector Flores [hectorfb#gmail.com] </center>");
out.println("</body></html>");
}
// ~ Inner Classes --------------------------------------------------------
/** Arranges methods by classname and method name */
private class TestSorter implements Comparator<IInvokedMethod> {
// ~ Methods
// -------------------------------------------------------------
/** Arranges methods by classname and method name */
#Override
public int compare(IInvokedMethod o1, IInvokedMethod o2) {
// System.out.println("Comparing " + o1.getMethodName() + " " +
// o1.getDate()
// + " and " + o2.getMethodName() + " " + o2.getDate());
return (int) (o1.getDate() - o2.getDate());
// int r = ((T) o1).getTestClass().getName().compareTo(((T)
// o2).getTestClass().getName());
// if (r == 0) {
// r = ((T) o1).getMethodName().compareTo(((T) o2).getMethodName());
// }
// return r;
}
}
}
With those steps you already have your listener ready to listen.
How to call it?
If you use testng.xml add the following lines:
<listeners>
<listener class-name='[your_class_path].MyReporterListener'/>
</listeners>
If you run your tests from a java class, add the following lines:
private final static MyReporterListener frl = new MyReporterListener();
TestNG testng = new TestNG();
testng.addListener(frl);
With those steps, when you execute your tests you'll have two emailable reports, customized and original.
Now it's time to pimp your report.
In my case I had to add error messages, parameters and times (start and end), because it's very useful if you want to paste on an excel file.
My customized report:
You have to mainly modify generateSuiteSummaryReport(List suites) function.
Play with that and ask me if you have any problem.
Make a you CSS and embed it in EmailableReporter.class. This class file can be found in TestNG folder> org.testNg.reporters> EmailableReporter.class.
There you can edit the Style of the TestNG report HTML file which starts with
protected void startHtml(PrintWriter out)
Better you can use extent report html reporting library jar file. However i am using extentreport1.4.jar jar file. So you will get summary details at right corner of your report
Using the above code, I am facing the below null pointer issue, HTML report works fine when fewer tests are included in testng.xml, but when I include more tests, the HTML report does not get generated and the below exception is thrown
[TestNG] Reporter report.MyListener#60e07aed failed
java.lang.NullPointerException: Cannot invoke "String.length()" because "s" is null
at java.base/java.io.StringReader.<init>(StringReader.java:51)
at java.base/java.util.Scanner.<init>(Scanner.java:766)
at report.MyListener.getShortException(MyListener.java:294)
at report.MyListener.generateSuiteSummaryReport(MyListener.java:473)
at report.MyListener.generateReport(MyListener.java:72)
at org.testng.TestNG.generateReports(TestNG.java:1093)
at org.testng.TestNG.run(TestNG.java:1036)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
To fix the above added a null check to avoid Null Pointer at line 295
if(str!=null) {
scanner = new Scanner(str);
String firstLine = scanner.nextLine()+"<br>";
m_out.println(firstLine);
}