Extent report logs for Test Steps is not working - extentreports

I have a TestNG test that has multiple methods. The extent report works in the main class but when I try to write logs for the other methods I am getting null pointer exception. All the tutorials point to writing logs in the main method but not to the other methods. I have been struggling to find a solution for this for a week now. Can somebody help me please ? Thanks
My code is some thing like this
#Test
public void TestOne()
{
extentTest = extent.startTest("TestOne");
Login.LoginToClient();
Access.AccessMainPage();
-
-
}
Public void LoginToClient()
{
***How can write an extent report log here for example - "Enter Username"
driver.findElement(By.id("username")).SendKeys(username)
-
-
}
The following is written in the main test
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#AfterMethod
public void tearDown(ITestResult result) throws IOException {
if(result.getStatus()==ITestResult.FAILURE){
//to add name in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getName());
//to add error/exception in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getThrowable());
String screenshotPath = Screenshots.getScreenshot(driver, result.getName());
//to add screenshot in extent report
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath));
}
else if(result.getStatus()==ITestResult.SKIP){
extentTest.log(LogStatus.SKIP, "Test Case SKIPPED IS " + result.getName());
}
else if(result.getStatus()==ITestResult.SUCCESS){
extentTest.log(LogStatus.PASS, "Test Case PASSED IS " + result.getName());
}
extent.endTest(extentTest);
}
My Full code is here
package yellowfin.bi.test;
import java.awt.AWTException;
import java.io.IOException;
import java.lang.reflect.Method;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import y.bi.create.reports.charts.ContentMenuButton;
import y.bi.create.reports.charts.ReportChartBuilder;
import y.bi.create.reports.charts.ReportFormattingPage;
import y.bi.create.reports.charts.ViewForReport;
import y.bi.login.loginPage;
import y.bi.logout.Logout;
import y.bi.screenshots.Screenshots;
import y.bi.utils.Printscreen;
import y.bi.utils.BrowserFactory;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ReportFormatting {
private EventFiringWebDriver driver;
private loginPage login;
private Logout logout;
private ContentMenuButton createContentMenuButton;
private ViewForReport reportView;
private ReportChartBuilder createChart;
Printscreen ps;
private ReportFormattingPage reportFormattingPage;
public ExtentReports extent;
public ExtentTest logger;
#BeforeSuite(enabled = true)
public void setUpTheTest() {
driver = (EventFiringWebDriver) BrowserFactory.selectBrowser("chrome");
}
#Parameters({ "yellowfinURL" })
#BeforeTest(enabled = true)
public void instantiatePages(String url) {
driver.get(url);
login = new loginPage(driver);
logout = new Logout(driver);
createContentMenuButton = new ContentMenuButton(driver);
reportView = new ViewForReport(driver);
createChart = new ReportChartBuilder(driver);
ps = new Printscreen(driver);
reportFormattingPage = new ReportFormattingPage(driver);
}
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#AfterMethod(alwaysRun=true)
public void TearDown_AM(ITestResult result) throws IOException
{
System.out.println("#After Method");
try
{
if(result.getStatus()==ITestResult.FAILURE)
{
String screenshotPath = Screenshots.getScreenshot(driver, result.getName());
String image= logger.addScreenCapture(screenshotPath);
System.out.println(image);
String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
logger.log(LogStatus.FAIL, TestCaseName + logger.addScreenCapture(screenshotPath));
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success");
}
else if(result.getStatus()==ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
}
extent.endTest(logger);
extent.flush();
}
catch(Throwable t)
{
logger.log(LogStatus.ERROR,t.fillInStackTrace());
}
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "fontType" ,"fontSize"})
#Test(testName = "validateDataSection", enabled = true, groups = {"Report Formatting : Data"}, alwaysRun = true, priority=1)
public void ValidateDataSection(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String ftype, String fsize) {
logger = extent.startTest("ValidateDataSection");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Checks the style "Font Type, Font Size, Bold Italic"
reportFormattingPage.DataSection(ftype,fsize);
// Access Row Highlight
reportFormattingPage.RowHighlight();
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "headerFontType", "headerFontSize", "borderWidth"})
#Test(testName = "Validate Column & Row Headings and Border", enabled = false, groups = {"Report Formatting : Column & Row Headings and Border"}, alwaysRun = true, priority=1)
public void ValidateColumnandRowHeadingsandBorder(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String headerFontType, String headerFontSize, String borderWidth) {
logger = extent.startTest("ValidateColumnandRowHeadingsandBorder");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
// validates the column and Row headings
reportFormattingPage.ColumnAndRowHandling(headerFontType, headerFontSize);
// Validates the border
reportFormattingPage.Border(borderWidth);
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "displayTitleFontType", "displayTitleFontSize", "displayDescFontType", "displayDescFontSize"})
#Test(testName = "Validate Title and Description", enabled = false, groups = {"Report Formatting : Title and Description"}, alwaysRun = true, priority=1)
public void ValidateTitleandDescription(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String displayTitleFontType, String displayTitleFontSize, String displayDescFontType, String displayDescFontSize) {
logger = extent.startTest("ValidateTitleandDescription");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Validates Title and Description
reportFormattingPage.TitleAndDescription(displayTitleFontType,displayTitleFontSize,displayDescFontType,displayDescFontSize);
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "displayTitleFontType", "displayTitleFontSize", "displayDescFontType", "displayDescFontSize"})
#Test(testName = "Validate header / Footer and Table sort", enabled = false, groups = {"Report Formatting : header / Footer and Table sort"}, alwaysRun = true, priority=1)
public void ValidateHeaderFooterandTableSort(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String displayTitleFontType, String displayTitleFontSize, String displayDescFontType, String displayDescFontSize) {
logger = extent.startTest("ValidateHeaderFooterandTableSort");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Validates Header and Footer page
reportFormattingPage.HeaderAndFooter();
//Validates Table sort
reportFormattingPage.TableSort();
logout.performLogout();
}
#AfterTest
public void endReport(){
extent.flush();
extent.close();
driver.quit();
}
}
import java.awt.Robot;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.BeforeTest;
import org.testng.asserts.SoftAssert;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import yellowfin.bi.screenshots.Screenshots;
public class ReportFormattingPage {
static WebDriver driver;
static long d = 2000;
String xpathElements="//div[#class='toggleSwitchSliderInner']";
String workingDir = System.getProperty("user.dir");
ReportFormat rf = new ReportFormat();
SoftAssert sa= new SoftAssert();
Screenshots screenshot = new Screenshots();
public ExtentReports extent;
public ExtentTest logger;
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#SuppressWarnings("static-access")
public ReportFormattingPage(WebDriver driver) {
this.driver = driver;
}
public void DataSection(String FontType, String FontSize)
{
try {
logger = extent.startTest("ValidateDataSection");
//Click on Report Format
logger.log(LogStatus.INFO, "Access Report Format Button");
rf.accessReportFormat(driver);
//Click on the Toggle switch
driver.findElement(By.cssSelector("div.toggleSwitchSliderInner")).click();
Thread.sleep(d);
//Select the font type
new Select(driver.findElement(By.cssSelector("div.fontDropDown > div.styledSelect.customSelect > select"))).selectByVisibleText(FontType);
Thread.sleep(d);
//Select the font size
driver.findElement(By.cssSelector("input.broadcastInput")).clear();
driver.findElement(By.cssSelector("input.broadcastInput")).sendKeys(FontSize);
//Click on Bold
driver.findElement(By.cssSelector("div.fontStyleOptions > div > img")).click();
Thread.sleep(d);
//Select italic and underline
driver.findElement(By.xpath("//img[#src='images/format_italic.png']")).click();
driver.findElement(By.xpath("//img[#src='images/format_underline.png']")).click();
//Changing the color of the text
driver.findElement(By.xpath("//div[#class='sp-preview-inner']")).click();
rf.dragAndDrop(driver);
driver.findElement(By.xpath("(//span[#id='chooseColourText'])")).click();
//Row shading Default
driver.findElement(By.xpath("//td[contains(text(), 'Default')]")).click();
// Row Shading Alternative ------------------------------------------------------------
driver.findElement(By.xpath("//td[contains(text(), 'Alternating')]")).click();
//click on the Alternate Row Color
driver.findElement(By.xpath("(//div[contains(text(), 'Define a color to be applied to every second row in the table.')]//following::div[#class='backboneColourPicker'])[1]")).click();
//Select the color
driver.findElement(By.xpath("(//span[#style='background-color:rgb(143, 80, 157);'])[3]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowShadingAlternative");
//Click on Report Format
rf.accessReportFormat(driver);
//RowShading none ------------------------------------------------------------------------------------
driver.findElement(By.xpath("//td[contains(text(), 'None')]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
screenshot.captureScreenShot(driver, "RowShadingNone");
//Click on Report Format
rf.accessReportFormat(driver);
rf.clickCloseAndAccessDesignPage(driver);
//Assertions
rf.DataSectionAssertions(driver);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowShadingDefault");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void RowHighlight()
{
try {
//Click on Report Format
rf.accessReportFormat(driver);
// Click on the toggle switch for the Row Highlight field
driver.findElement(By.cssSelector("div.controlContainer > div.toggleSwitchSlider > div.toggleSwitchSliderInner")).click();
// Click on Row Highlight color
driver.findElement(By.cssSelector("div.sp-preview-inner.no-colour")).click();
// Select the color
driver.findElement(By.xpath("(//span[#style='background-color:rgb(124, 187, 0);'])[3]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
Robot robot = new Robot();
robot.mouseMove(200,600);
robot.delay(1500);
robot.mouseMove(200,900);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowHighlight");
}
catch (Exception e) {
e.printStackTrace();
}
}

Please check these links for the answer:
How to print logs by using ExtentReports listener in java?
https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/EmailableReporter2.java
If you have a Reporting Class say which Listens to the TestNG Listner and have ExtentReport code implemented in it you can get the TestCase Steps using Reporter Object
please see below.
Note that Reporter .log of TestNG does not have any definition for Type of Log like INFO, FATAL etc.. It just adds the Log Message.
Test case:
public class TC_1 extends BaseClass{
#Test (priority=0)
public void addNotes() throws Exception
{
if (super.search("VALUE"))
{
logger.info("Search is Successful");
Reporter.log("Search is Successful");
Assert.assertTrue(true);
}
}
Reporting:
public class Reporting extends TestListenerAdapter
{
public ExtentHtmlReporter htmlReporter;
public ExtentReports extent;
public ExtentTest logger;
public void onStart(ITestContext testContext)
{
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());//time stamp
String repName="Test-Report-"+timeStamp+".html";
htmlReporter=new ExtentHtmlReporter(System.getProperty("user.dir")+ "/test-output/"+repName);//specify location of the report
htmlReporter.loadXMLConfig(System.getProperty("user.dir")+ "/extent-config.xml");
extent=new ExtentReports();
extent.attachReporter(htmlReporter);
htmlReporter.config().setDocumentTitle("Test Project");
htmlReporter.config().setReportName("Functional Test Automation Report");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
public void onTestSuccess(ITestResult tr)
{
logger=extent.createTest(tr.getName());
logger.log(Status.PASS,MarkupHelper.createLabel(tr.getName(),ExtentColor.GREEN));
List<String> reporterMessages = Reporter.getOutput(tr);
for (int i = 0; i < reporterMessages.size(); i++)
{
System.out.println(reporterMessages.get(i));
logger.info(reporterMessages.get(i));
}
}
}

Firstly, I recommend to use Version 3 instead of Version 2,
As I can see in your Code, You have define Test definition but there is no such logs for that method in which you wants to generate,
Please Refer as Following, to generate logs:
You can use same way in any method,
extentTest.log(LogStatus.INFO, "Test Case Details");
Here object of ExtentTest need to declare as Class variable, So you can access it anywhere within class.
If you wants to create different Test section for Login.LoginToClient(); method, you can define it like:
Public void LoginToClient()
{
extentTest = extent.startTest("Login Test");
driver.findElement(By.id("username")).SendKeys(username);
extentTest.log(LogStatus.INFO, "User Name: " +username);
}
Hope it will works as you want to generate.

Related

Extent Report showing only one test case result when executing cucumber scripts in parallel using Cucable plugin

I have to generate Extent Report from all executed test scripts. I am running scripts in parallel. When I use TestNG or Selenium Grid for parallel execution, in those implementation, Extent Reports are getting generated perfectly covering each executed test scripts. But when I run scripts in parallel using Cucable Plugin, Extent report gets generated but would have only 1 test case report if 2 test cases were there in execution.
I am using Cucumber (Selenium), Junit Suite Runner, Cucable Plugin
I verified Extent Report code is thread safe. So not sure, why only in case of Cucable Plugin, Extent report gets only 1 test case. Someone told me, In case of testNG, testNG itself provides additional thread safe mechanism which helps internally to have all executed test cases in report.
ExtentTestManager.java
package com.jacksparrow.automation.extent.listeners;
import java.io.IOException;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.Markup;
import com.aventstack.extentreports.markuputils.MarkupHelper;
public class ExtentTestManager {
public static ThreadLocal<ExtentTest> testReport = new ThreadLocal<ExtentTest>();
static ExtentReports extent = ExtentManager.getReporter();
public static synchronized ExtentTest getTest() {
return testReport.get();
}
public static synchronized void setTest(ExtentTest tst)
{
testReport.set(tst);
}
public static synchronized void logInfo(String message) {
testReport.get().info(message);
}
public static synchronized void logPass(String message) {
testReport.get().pass(message);
}
public static synchronized void scenarioPass() {
String passLogg = "SCENARIO PASSED";
Markup m = MarkupHelper.createLabel(passLogg, ExtentColor.GREEN);
testReport.get().log(Status.PASS, m);
}
public static synchronized void logFail(String message) {
testReport.get().fail(message);
}
public static synchronized boolean addScreenShotsOnFailure() {
ExtentManager.captureScreenshot();
try {
testReport.get().fail("<b>" + "<font color=" + "red>" + "Screenshot of failure" + "</font>" + "</b>",
MediaEntityBuilder.createScreenCaptureFromPath(ExtentManager.screenshotName).build());
} catch (IOException e) {
}
String failureLogg = "SCENARIO FAILED";
Markup m = MarkupHelper.createLabel(failureLogg, ExtentColor.RED);
testReport.get().log(Status.FAIL, m);
return true;
}
public static synchronized boolean addScreenShots() {
ExtentManager.captureScreenshot();
try {
testReport.get().info(("<b>" + "<font color=" + "green>" + "Screenshot" + "</font>" + "</b>"),
MediaEntityBuilder.createScreenCaptureFromPath(ExtentManager.screenshotName).build());
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public static synchronized ExtentTest startTest(String testName) {
return startTest(testName, "");
}
public static synchronized ExtentTest startTest(String testName, String desc) {
ExtentTest test = extent.createTest(testName, desc);
testReport.set(test);
return test;
}
}
ExtentManager.java
package com.jacksparrow.automation.extent.listeners;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import com.jacksparrow.automation.utilities.DriverManager;
import com.aventstack.extentreports.AnalysisStrategy;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentManager {
static ExtentReports extent;
static Date d = new Date();
static String fileName = "Extent_" + d.toString().replace(":", "_").replace(" ", "_") + ".html";
public synchronized static ExtentReports getReporter() {
if (extent == null) {
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"/target/extent-report/"+fileName);
htmlReporter.loadXMLConfig(".\\src\\test\\resources\\extent-config.xml");
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(fileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(fileName);
//htmlReporter.setAppendExisting(true);
extent = new ExtentReports();
extent.setAnalysisStrategy(AnalysisStrategy.TEST);
extent.attachReporter(htmlReporter);
extent.setSystemInfo("Automation Analyst", "Robin Tyagi");
extent.setSystemInfo("Organization", "Way2Automation");
extent.setSystemInfo("Build no", "W2A-1234");
}
return extent;
}
public static String screenshotPath;
public static String screenshotName;
static int i=0;
public static void captureScreenshot() {
i = i + 1;
File scrFile = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.FILE);
Date d = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("E dd MMM HH:mm:ss z yyyy");
String strDate = formatter.format(d);
screenshotName = strDate.replace(":", "_").replace(" ", "_") + "_"+i+".jpg";
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/extent-report/" + screenshotName));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createExtentReportDirectory() {
File file = new File(System.getProperty("user.dir") + "/target/extent-report/");
if (!file.exists()) {
if (file.mkdir()) {
} else {
}
}
}
}
Please help me to understand what could be the correct thought in order to generate Extent Report having summary of all executed test scripts when Cucable Plugin is used for achieving parallel execution in Cucumber (Selenium)
After migrating to cucumber 4.0, I am able to generate single consolidated extent report. Thank you.

How to use extent reports for individual steps

How can we use extent report logs for individual steps. My main test is as follows
#Test(testName = "Validate SinglePage and Multiple Page", enabled = true, priority = 1, groups = {"Section Formatting"})
public void SingleSection(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String SecItem1, String SecItem2, String DispStyle, String fType) throws InterruptedException {
extentTest = extent.startTest("SingleSection");
extentTest.log(LogStatus.INFO, "Login to the system");
login.loginToTenant(username, password);
extentTest.log(LogStatus.INFO, "Access the content menu");
// select view from content menu button
createContentMenuButton.setContentMenuButton();
extentTest.log(LogStatus.INFO, "Select the view");
// choose view
reportView.selectView(viewName);
extentTest.log(LogStatus.INFO, "Create the report");
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
extentTest.log(LogStatus.INFO, "Add fields to sections");
// Adds fields to sections
sections.dragAndDropToSections(SecItem1, SecItem2);
For example If I want to put steps for one of the methods ex- loginToTenant, the system throughs null value exception error.
the code for the method loginToTenant is as follows
public class loginPage extends ConfigReader {
WebDriver driver;
public ExtentReports extent;
public ExtentTest extentTest;
public loginPage(WebDriver driver) {
this.driver = driver;
}
// locators for login page
By userName = By.name("email");
By password = By.name("password");
By submitButton = By.id("logonButton");
By licenseWarning = By.partialLinkText("Click Here To Continue");
By plusButton = By.className("create-menu-container");
By banner = By.className("i4sidenav_width");
By logout = By.id("logoffBtn");
/**
* perform login to yellowfin and verify successful login
*
* #param uName
* #param passwd
* #return
*/
public String loginToTenant(String uName, String passwd) {
String loginmsg = null;
long d = 1000;
try {
extentTest.log(LogStatus.INFO, "Login to the system"); //I am getting an error on this line with null pointer exception
driver.findElement(userName).clear();
driver.findElement(userName).sendKeys(uName);
driver.findElement(password).clear();
driver.findElement(password).sendKeys(passwd);
driver.findElement(submitButton).click();
If you wants to create individual steps for loginToTenant method, you can create extentReport in loginPage class similarly. And it will create individual steps for it.

Error parsing data org.json.JSONException: Value Pin of type java.lang.String cannot be converted to JSONObject

I am relatively new to android programming and I have been facing this problem. I am currently working on Interfacing android with Arduino and controlling device with an app. I am facing a problem in this part of the Front End where I have switches which would send POST request with some string as parameter. But I keep getting this error. I did search the internet first for the answer but no one seems to have any problems related to throwing exceptions as " Value Pin of type". The code for the Front End java and PHP is posted below. Thank you for your help.
changeState.php
<?php
//load and connect to MySQL database stuff
require("config.php");
if (!empty($_POST)) {
$status = $_POST['status'];
//initial query
$query = "INSERT INTO status ( leaf_id, state ) VALUES ( :pinNumber, :pinState ) ";
//Update query
$stageOne = explode(',',$status);
for($i=0;$i<sizeof($stageOne);$i++) {
$pinNumber=$pinState="0";
$stageTwo = explode('-',$stageOne[$i]);
$pinNumber = $stageTwo[0];
$pinState = $stageTwo[1];
echo "Pin number : ".$pinNumber."</br>";
echo "Pin state : ".$pinState."</br>";
//execute query
$query_params = array(
':pinNumber' => $pinNumber,
':pinState' => $pinState
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute( $query_params );
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't add post!";
die(json_encode($response));
}
}
$response["success"] = 1;
$response["message"] = "State Change Successfully Added!";
echo json_encode($response);
} else {
?>
<h1>Waiting for user Interation</h1>
<form action="changeState.php" method="post">
Status:<br />
<input type="text" name="status" placeholder="Change status" />
<br /><br />
</form>
<?php
}
?>
controlFrontEnd.java
package com.thulung.bathiama;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class controlFrontEnd extends Activity implements OnClickListener{
boolean outlet1_status = false;
boolean outlet2_status = false;
boolean outlet3_status = false;
boolean outlet4_status = false;
boolean outlet5_status = false;
boolean outlet6_status = false;
private ImageView outlet1;
private ImageView outlet2;
private ImageView outlet3;
private ImageView outlet4;
private ImageView outlet5;
private ImageView outlet6;
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String STATECHANGE_URL = "http://192.168.1.102/Test/BathiAma/bathiama/changeState.php";
private ProgressDialog pDialog;
private JSONParser jsonParser = new JSONParser();
String DebugOutletMessage = new String("Status Message");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttons);
outlet1 = (ImageView)findViewById(R.id.outlet1);
outlet2 = (ImageView)findViewById(R.id.outlet2);
outlet3 = (ImageView)findViewById(R.id.outlet3);
outlet4 = (ImageView)findViewById(R.id.outlet4);
outlet5 = (ImageView)findViewById(R.id.outlet5);
outlet6 = (ImageView)findViewById(R.id.outlet6);
outlet1.setOnClickListener(this);
outlet2.setOnClickListener(this);
outlet3.setOnClickListener(this);
outlet4.setOnClickListener(this);
outlet5.setOnClickListener(this);
outlet6.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.outlet1:
if(!outlet1_status)
outlet1.setImageResource(R.drawable.on);
else
outlet1.setImageResource(R.drawable.off);
outlet1_status=!outlet1_status;
break;
case R.id.outlet2:
//Toast.makeText(getApplicationContext(), "Outlet 2 pressed", Toast.LENGTH_LONG).show();
if(!outlet2_status)
outlet2.setImageResource(R.drawable.on);
else
outlet2.setImageResource(R.drawable.off);
outlet2_status=!outlet2_status;
break;
case R.id.outlet3:
//Toast.makeText(getApplicationContext(), "Outlet 3 pressed", Toast.LENGTH_LONG).show();
if(!outlet3_status)
outlet3.setImageResource(R.drawable.on);
else
outlet3.setImageResource(R.drawable.off);
outlet3_status=!outlet3_status;
break;
case R.id.outlet4:
//Toast.makeText(getApplicationContext(), "Outlet 4 pressed", Toast.LENGTH_LONG).show();
if(!outlet4_status)
outlet4.setImageResource(R.drawable.on);
else
outlet4.setImageResource(R.drawable.off);
outlet4_status=!outlet4_status;
break;
case R.id.outlet5:
//Toast.makeText(getApplicationContext(), "Outlet 5 pressed", Toast.LENGTH_LONG).show();
if(!outlet5_status)
outlet5.setImageResource(R.drawable.on);
else
outlet5.setImageResource(R.drawable.off);
outlet5_status=!outlet5_status;
break;
case R.id.outlet6:
//Toast.makeText(getApplicationContext(), "Outlet 6 pressed", Toast.LENGTH_LONG).show();
if(!outlet6_status)
outlet6.setImageResource(R.drawable.on);
else
outlet6.setImageResource(R.drawable.off);
outlet6_status=!outlet6_status;
break;
default:
break;
}
String state1 = booleanToString(outlet1_status);
String state2 = booleanToString(outlet2_status);
String state3 = booleanToString(outlet3_status);
String state4 = booleanToString(outlet4_status);
String state5 = booleanToString(outlet5_status);
String state6 = booleanToString(outlet6_status);
//building parameter to Send for storing in db
String stateOfMachine = "2-"+state1+","+"3-"+state2+","+"4-"+state3+","+"5-"+state4+","+"6-"+state5+","+"7-"+state6;
new changeSwitchState().execute(stateOfMachine);
}
class changeSwitchState extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(controlFrontEnd.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
JSONObject json = null;
String stateOfMachine = args[0];
Log.d("to Parse - Control Front End",stateOfMachine);
//Retrieving Saved Username Data:
//SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(controlFrontEnd.this);
//String post_username = sp.getString("username", "anon");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("status", stateOfMachine));
Log.d("request!", "starting");
//Posting user data to script
json = jsonParser.makeHttpRequest(
STATECHANGE_URL, "POST", params);
// full json response
Log.d("Change Status attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Status Changed!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Status Change Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(controlFrontEnd.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
public String booleanToString(boolean logic){
if(logic)
return "1";
else
return "0";
}
}
I solved this issue. The error was in the php data echo-ed. If you encounter such error, be sure that you are not sending rubbish i.e. plain text to receiver.

crawler4j compile error with class CrawlConfig - VariableDeclaratorId Expected

The code will not compile. I changed the JRE to 1.7. The compiler does not highlight the class in Eclipse and the CrawlConfig appears to fail in the compiler. The class should be run from the command line in Linux.
Any ideas?
Compiler Error -
Description Resource Path Location Type
Syntax error on token "crawlStorageFolder", VariableDeclaratorId expected after this token zeocrawler.java /zeowebcrawler/src/main/java/com/example line 95 Java Problem
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.WebURL;
public class Controller {
String crawlStorageFolder = "/data/crawl/root";
int numberOfCrawlers = 7;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("http://www.senym.com");
controller.addSeed("http://www.merrows.co.uk");
controller.addSeed("http://www.zeoic.com");
controller.start(MyCrawler.class, numberOfCrawlers);
}
public URLConnection connectURL(String strURL) {
URLConnection conn =null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
int test = 0;
}catch(MalformedURLException e) {
System.out.println("Please input a valid URL");
}catch(IOException ioe) {
System.out.println("Can not connect to the URL");
}
return conn;
}
public static void updatelongurl()
{
// System.out.println("Short URL: "+ shortURL);
// urlConn = connectURL(shortURL);
// urlConn.getHeaderFields();
// System.out.println("Original URL: "+ urlConn.getURL());
/* connectURL - This function will take a valid url and return a
URL object representing the url address. */
}
public class MyCrawler extends WebCrawler {
private Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g"
+ "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf"
+ "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether
* the given url should be crawled or not (based on your
* crawling logic).
*/
#Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
#Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
}
}
This is a pretty strange error since the code seems to be clean. Try to start eclipse with the -clean option on command line.
Change
String crawlStorageFolder = "/data/crawl/root";
to
String crawlStorageFolder = "./data/crawl/root";
i.e. add a leading .

Not getting value in midlet from servlet

I'm trying to send data from a midlet to a servlet and recieve back a response from the servlet but I don't get any value in response. I've tried to print it on command window and it seems to be null yet I expect only two values "ok" or "error". Please help me check the code and let me know what I should do to get the response right on the midlet. My code is below:
import javax.microedition.midlet.*;//midlet class package import
import javax.microedition.lcdui.*;//package for ui and commands
import javax.microedition.io.*;//
import java.io.*;
/**
* #author k'owino
*/
//Defining the midlet class
public class MvsMidlet extends MIDlet implements CommandListener {
private boolean midletPaused = false;//variable for paused state of midlet
//defining variables
private Display display;// Reference to Display object
private Form welForm;
private Form vCode;//vote code
private StringItem welStr;
private TextField phoneField;
private StringItem phoneError;
private Command quitCmd;
private Command contCmd;
//constructor of the midlet
public MvsMidlet() {
display = Display.getDisplay(this);//creating the display object
welForm = new Form("THE MVS");//instantiating welForm object
welStr = new StringItem("", "Welcome to the MVS, Busitema's mobile voter."
+ "Please enter the your phone number below");//instantiating welStr string item
phoneError = new StringItem("", "");//intantiating phone error string item
phoneField = new TextField("Phone number e.g 0789834141", "", 10, 3);//phone number field object
quitCmd = new Command("Quit", Command.EXIT, 0);//creating quit command object
contCmd = new Command("Continue", Command.OK, 0);//creating continue command object
welForm.append(welStr);//adding welcome string item to form
welForm.append(phoneField);//adding phone field to form
welForm.append(phoneError);//adding phone error string item to form
welForm.addCommand(contCmd);//adding continue command
welForm.addCommand(quitCmd);//adding quit command
welForm.setCommandListener(this);
display.setCurrent(welForm);
}
//start application method definition
public void startApp() {
}
//pause application method definition
public void pauseApp() {
}
//destroy application method definition
public void destroyApp(boolean unconditional) {
}
//Command action method definition
public void commandAction(Command c, Displayable d) {
if (d == welForm) {
if (c == quitCmd) {
exitMidlet();//call to exit midlet
} else {//if the command is contCmd
//place a waiting activity indicator
System.out.println("ken de man");
Thread t = new Thread() {
public void run() {
try {
//method to connect to server
sendPhone();
} catch (Exception e) {
}//end of catch
}//end of ru()
};//end of thread
t.start();//starting the thread
}//end of else
}//end of first if
}//end of command action
//defining method to exit midlet
public void exitMidlet() {
display.setCurrent(null);
destroyApp(true);
notifyDestroyed();
}//end of exitMidlet()
//defining sendPhone method
public void sendPhone() throws IOException {
System.out.println("ken de man");//check
HttpConnection http = null;//HttpConnection variable
OutputStream oStrm = null;//OutputStream variable
InputStream iStrm = null;//InputStream variable
String url = "http://localhost:8084/MvsWeb/CheckPhone";//server url
try {
http = (HttpConnection) Connector.open(url);//opening connection
System.out.println("connection made");//checking code
oStrm = http.openOutputStream();//opening output stream
http.setRequestMethod(HttpConnection.POST);//setting request type
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//setting content type
byte data[] = ("phone=" + phoneField.getString()).getBytes();
oStrm.write(data);
iStrm = http.openInputStream();//openning input stream
if (http.getResponseCode() == HttpConnection.HTTP_OK) {
int length = (int) http.getLength();
String str;
if (length != -1) {
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
} else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) {
bStrm.write(ch);
}
str = new String(bStrm.toByteArray());
bStrm.close();
}
System.out.println("de man");
System.out.println(str);
if (str.equals("ok")) {
//change to vcode form
} else {
//add error message to phone_error stingItem
}
}
} catch (Exception e) {
}
}
}//end of class definition
//servlet
import java.io.*;//package for io classes
import javax.servlet.ServletException;//package for servlet exception classes
import javax.servlet.http.*;
import java.sql.*;//package for sql classes
/**
*
* #author k'owino
*/
public class CheckPhone extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//declaring variables
PrintWriter pw;//PrintWriter object
String pnum;//phone parameter sent from client
Connection con = null;//connection variable
String dbDriver = "com.jdbc.mysql.Driver";//the database driver
String dbUrl = "jdbc:mysql://localhost/mvs_db";//the database url
String dbUser = "root";//database user
String dbPwd = "";//database password
PreparedStatement pstmt = null;//Prepared statement variable
String query = "select * from student where stud_phone = ?;";
ResultSet rs = null;//resultset variable
String dbPhone=null;//phone from database
//getting the "phone" parameter sent from client
pnum = req.getParameter("phone");//getting the "phone" parameter sent from client
System.out.println(pnum);
//setting the content type of the response
res.setContentType("text/html");
//creating a PrintWriter object
pw = res.getWriter();
pw.println("ken");
try{//trying to load the database driver and establish a connection to the database
Class.forName(dbDriver).newInstance();//loading the database driver
con = DriverManager.getConnection(dbUrl,dbUser,dbPwd);//establishing a connection to the database
System.out.println("connection established");
}
catch(Exception e){
}
//trying to query the database
try{
pstmt = con.prepareStatement(query);//preparing a statement
pstmt.setString(1, pnum);//setting the input parameter
rs = pstmt.executeQuery();//executing the query assigning to the resultset object
//extracring data from the resultset
while(rs.next()){
dbPhone = rs.getString("stud_phone");//getting the phone number from database
}//end of while
if(pnum.equals(dbPhone)){
pw.print("ok");
pw.close();
}
else{
pw.print("error");
pw.close();
}
}
catch(Exception e){
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Resources