Webdriver is Not able to read element-Null Pointer exception.. - java

I am Trying to Automate a Test sequence of Login - Booking - Cancellation.
Till Booking its Fine , But moment it Reaches Cancellation, It throws a java lang Null-Pointer Exp.
I rechecked and My locators(xpath) is correct(xpath-Checker) and I am Trying to getText() the Ticket Number and proceed to cancellation.
Problem is whenever WebDriver is reaching the Booking confirmation Page , which Loads after a While, it Fails and Returns Null Pointer Exp..
It may be a Loading Issue which is handled or I am messed up with my Java Concept...
Please Help !! anyone...
public class StackOverflow {
public static WebDriver driver;
public static Properties p;
public static FileInputStream f ;
#Test
public void loginTest() {
System.out.println("Enter Login");
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver = new FirefoxDriver();
driver.get("https://in3.seatseller.travel/");
driver.manage().window().maximize();
try{
driver.findElement(By.name(p.getProperty("login.username.textfield"))).sendKeys("UserName");
driver.findElement(By.name(p.getProperty("login.password.textfield"))).sendKeys("Password");
WebElement ele =driver.findElement(By.id(p.getProperty("login.signin.button")));
ele.click();
}
catch (Exception e) {
}
}
#Test (dependsOnMethods={"loginTest"})
public void booking() throws InterruptedException{
System.out.println("Enter Booking");
// Type Bangalore on Source Field..
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebDriverWait wait2 = new WebDriverWait(driver, 30);
wait2.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(p.getProperty("oneapp.source.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys("Bangalore");
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys(Keys.TAB);
Thread.sleep(900L);
// Type Mysore on Destination Field
WebDriverWait wait1 = new WebDriverWait(driver, 30);
wait1.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.destination.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.destination.textfield"))).sendKeys("Tirupathi");
driver.findElement(By.xpath(p.getProperty("oneapp.destination.textfield"))).sendKeys(Keys.TAB);
}
#Test (dependsOnMethods={"booking"})
public void cancellation() throws InterruptedException{
System.out.println("Enter Cancellation");
WebDriverWait wait4 = new WebDriverWait(driver, 60);
Thread.sleep(9000);
/*Facing Null Pointer Exp Here */
wait4.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(p.getProperty("oneapp.congratulations.text"))));
wait4.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.congratulations.text"))));
Thread.sleep(9000);
/*Facing Null Pointer Exp Here */
WebElement ticket =driver.findElement(By.xpath(p.getProperty("oneapp.ticket.text")));
/*Want to getText() Ticket Number to cancel*/
String ticket1 = ticket.getText();
System.out.println(ticket1);
driver.findElement(By.xpath(p.getProperty("oneapp.leftNavCancel.link "))).click();
WebDriverWait wait1 = new WebDriverWait(driver, 30);
wait1.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.phoneNumber.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.phoneNumber.textfield"))).sendKeys(TIN1);
driver.findElement(By.xpath(p.getProperty("oneapp.search.button"))).click();
driver.findElement(By.xpath(p.getProperty("oneapp.cancel.button"))).click();
}
}

Either add Properties p=new Properties(); in your cancellation() method or mention it outside of the test methods(In the begining, you've declared public static Properties p; rather define it there like public static Properties p = new Properties();)

In first two methods you create f = new FileInputStream but in the third method you read properties without it. Did you try to read properties again?

Related

Unable to view the screenshots in extent reports In Jenkins

We are able to view the screenshots locally. When we run the job in Jenkins we are unable to view the screenshots in extent reports. We are using extent reports v2.41.2. Both the screenshot and report are in the same directory. Kindly give us a solution in order to solve it.
public static String takescreenshot(WebDriver driver, String Screenshotname) throws InterruptedException {
Thread.sleep(3000);
TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);
String timeStamp = new SimpleDateFormat("MMMdd_yyyy_hh_mmaa").format(Calendar.getInstance().getTime());
String dest = System.getProperty("user.dir")+"\\ATOM_20Report\\"+Screenshotname + "_" + timeStamp + ".png";
try {
FileUtils.copyFile(src, new File(dest));
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Failed to take screenshot: " + e.getMessage());
}
return dest;
}
public static void passTestwithsc(String Screenshotname, WebDriver driver) {
Assert.assertTrue(true);
String path = null;
try {
path = Helper.takescreenshot(driver, Screenshotname);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.log(LogStatus.PASS, logger.getDescription(),logger.addScreenCapture(path));
}

I can't mock static method using Mockito and PowerMockito

I'm having trouble mocking a static method in a third-party library. I keep receiving a null-pointer exception when running the test, but I'm not sure why that is.
Here is the class and the void method that invokes the static method I'm trying to mock "MRClientFactory.createConsumer(props)":
public class Dmaap {
Properties props = new Properties();
public Dmaap() {
}
public MRConsumerResponse createDmaapConsumer() {
System.out.println("at least made it here");
MRConsumerResponse mrConsumerResponse = null;
try {
MRConsumer mrConsumer = MRClientFactory.createConsumer(props);
System.out.println("made it here.");
mrConsumerResponse = mrConsumer.fetchWithReturnConsumerResponse();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mrConsumerResponse;
}
}
Below is the test that keeps returning a null-pointer exception. The specific line where the null-pointer is being generated is: MRClientFactory.createConsumer(Mockito.any(Properties.class));
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.vismark.PowerMock.*")
public class DmaapTest {
#Test
public void testCreateDmaapConsumer() {
try {
Properties props = new Properties();
PowerMockito.mockStatic(MRClientFactory.class);
PowerMockito.doNothing().when(MRClientFactory.class);
MRClientFactory.createConsumer(Mockito.any(Properties.class));
//MRClientFactory.createConsumer(props);
Dmaap serverMatchCtrl = new Dmaap();
Dmaap serverMatchCtrlSpy = spy(serverMatchCtrl);
serverMatchCtrlSpy.createDmaapConsumer();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please follow this example carefully: https://github.com/powermock/powermock/wiki/MockStatic
Especially you are missing a
#PrepareForTest(Dmaap.class)
…to denote the class which does the static call.

How can I change try catch exception to WebDriverWait

I am trying to login and search records based on date selected from a calendar. I have used try catch exception after each step. I need to replace try catch with WebDriverWait. But the problem is that I have fields on the page which are getting identified by id or XPath. So I am not getting a way out how to implement WebDriverWait instead of try catch. Can anyone help me out? Below is my code structure with details.
public class Login {
public static WebDriver driver;
String username = "username";
String password = "password";
String baseurl = "http://mybusiness.com/login.aspx";
public class Details {
#Test(priority = 0)
public void loginpage() {
//WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.chrome.driver","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
capabilities.setCapability("chrome.binary","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get(baseurl);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement password = driver.findElement(By.id("Password"));
password.sendKeys(password);
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement button = driver.findElement(By.id("ButtonClick"));
button.click();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
// Selecting a date from date picker
#Test(priority = 1)
public void RecordSearch() {
WebElement calendar = driver.findElement(By.id("CalendarId"));
calendar.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement month = driver.findElement(By.xpath("XPath"));
month.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement day = driver.findElement(By.xpath("XPath"));
day.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement submit = driver.findElement(By.id("Submit"));
submit.click();
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
driver.close();
}
I would have thought you'd be better off adding an implicit wait, e.g. once you've setup your driver object add the following line:
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
A simple example would take your code
try
{
Thread.sleep(10000); // 1000 milliseconds is one second.
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
and change it to
String username = "username123";
WebDriverWait wait = new WebDriverWait(driver, 10); // 10 seconds
WebElement usernameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("UserName")));
usernameField.sendKeys(username);
Once you have defined wait, you can reuse it over and over and it will have the same attributes, e.g. 10 sec wait time.
String password = "abc123";
WebElement passwordField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Password")));
passwordField.sendKeys(password);
NOTE: I noticed that you were using username.sendKeys(username);. I'm assuming/hoping this isn't actual code since .sendKeys() takes a String and you have username defined as a WebElement. I fixed it in my code and named the two differently.
There is WebDriverWait functionality in selenium, you can set explicit wait. You are using selenium webdriver, then it is far better to use WebDriverWait for waiting purpose to element. follow below code
protected WebElement waitForPresent(final String locator, long timeout) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement ele = null;
try {
ele = wait.until(ExpectedConditions
.presenceOfElementLocated(locator));
} catch (Exception e) {
throw e;
}
return ele;
}
protected WebElement waitForNotPresent(final String locator, long timeout) {
timeout = timeout * 1000;
long startTime = System.currentTimeMillis();
WebElement ele = null;
while ((System.currentTimeMillis() - startTime) < timeout) {
try {
ele = findElement(locator);
Thread.sleep(1000);
} catch (Exception e) {
break;
}
}
return ele;
}
Whenever you require wait for element present, call waitForPresent method with expected parameters.
If you explore little, you can find different types of WebDriverWait. One of the most common is WebDriver.wait(timeinmilliseconds).
and for example, others are,
webDriver.waituntil (Expectedconditions)...
wait.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
WebElement button = driver.findElement(By.className("sel"));
String enabled = button.getText();
return enabled.contains(city);
}
});
or for example
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("froexample_username_txtbox")));
PS : define private final WebDriverWait wait;
It may be more useful if you are not sure about implict timewait value.(be being specific about events and results)

ObjectMapper append file JSON

Trying to learn about Jackson some, so I'm writing a simple program that reads a file/creates one to store some JSON in it. From the Jackson website I figured out how to read and write from the file, but in the case of my rudimentary program, i'd like to append as well. I'm basically trying to store a list of shopping lists. There is a shopping list object which has store name, amd items for that store.
The trouble is that I cannot figure a way to append another entry to the end of the file (in JSON format). Here is what I am working with so far, you can ignore the first bit it's just a silly console scanner asking for input:
public class JacksonExample {
static ObjectMapper mapper = new ObjectMapper();
static File file = new File("C:/Users/stephen.protzman/Desktop/user.json");
static List<ShoppingList> master = new ArrayList<ShoppingList>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("[ 1 ] Add a new shopping list");
System.out.println("[ 2 ] View all shopping lists");
System.out.println("[ 3 ] Save all shopping lists");
int choice = Integer.parseInt(in.nextLine());
switch (choice) {
case 1:
getNewList();
case 2:
display();
case 3:
running = false;
}
}
in.close();
}
public static void getNewList() {
boolean more = true;
String store, temp;
List<String> items = new ArrayList<String>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the store: ");
store = s.nextLine();
System.out.println("Enter each item [If done type 'DONE'] :");
while (more) {
temp = s.nextLine();
if (temp != null) {
if (temp.toUpperCase().equals("DONE")) {
more = false;
} else {
items.add(temp);
}
}
}
save(store, items);
s.close();
}
public static void display() {
try {
ShoppingList list = mapper.readValue(file, ShoppingList.class);
System.out.println(mapper.defaultPrettyPrintingWriter()
.writeValueAsString(list));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void save(String store, List<String> items) {
//load in old one
try {
ShoppingList list = mapper.readValue(file, ShoppingList.class);
System.out.println(mapper.defaultPrettyPrintingWriter()
.writeValueAsString(list));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//add to end of older list
ShoppingList tempList = new ShoppingList();
tempList.setStore(store);
tempList.setItems(items);
master.add(tempList);
try {
mapper.writeValue(file, master);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want to keep using ObjectMapper (considering im trying to learn Jackson) I just havent found a way to append yet is all. Any ideas?
To append content, you need to use Streaming API to create JsonGenerator; and then you can give this generator to ObjectMapper to write to. So something like:
JsonGenerator g = mapper.getFactory().createGenerator(outputStream);
mapper.writeValue(g, valueToWrite);
// and more
g.close();
Below method can be used to write objects into a json file in append mode. it first reads your existing json file and adds new java objects to JSON file.
public static void appendWriteToJson() {
ObjectMapper mapper = new ObjectMapper();
try {
// Object to JSON in file
JsonDaoImpl js = new JsonDaoImpl();
URL resourceUrl = js.getClass().getResource("/data/actionbean.json");
System.out.println(resourceUrl);
File file = new File(resourceUrl.toURI());
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); // append mode file writer
mapper.writeValue(out, DummyBeanObject);
} catch (Exception e) {
e.printStackTrace();
}
}

Delete all index data/files in disk using Apache Lucene?

How can I flush/delete/erase all the index files/data in the disk using Apache Lucene.This is my code so far and still I can't remove index files.Please help me out...
Test:
public class Test {
private static final String INDEX_DIR = "/home/amila/Lucene/REST/indexing";
public static void main(String[] args) {
try {
ContentIndexer contentIndexer = new ContentIndexer(INDEX_DIR);
contentIndexer.flushDisk();
System.out.println("Flushed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
ContentIndexer:
public class ContentIndexer {
private IndexWriter writer;
public ContentIndexer(String indexDir) throws IOException {
// create the index
if (writer == null) {
writer = new IndexWriter(FSDirectory.open(new File(indexDir)),
new IndexWriterConfig(Version.LUCENE_36,
new StandardAnalyzer(Version.LUCENE_36)));
}
}
public void flushDisk() {
try {
writer.deleteAll();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Edited -- Updated Answer
public class Test {
private static final String INDEX_DIR = "/home/amila/Lucene/REST/indexing";
public static void main(String[] args) {
try {
IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_36,
new StandardAnalyzer(Version.LUCENE_36));
conf.setOpenMode(OpenMode.CREATE);
Directory directory = FSDirectory.open(new File(INDEX_DIR));
IndexWriter indexWriter = new IndexWriter(directory, conf);
indexWriter.deleteAll();
indexWriter.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The simplest way is to open IndexWriter with a CREATE mode (via indexWriterConfig.setOpenMode(...)). This removes all existing index files in the given directory.
For older versions IndexWriter constructor also has a special boolean create flag which does the same thing.
You can use two options :
You can call the delete all method of the writer
indexWriter.DeleteAll();
You can create a new indexWriter with the create flag set to true ( open mode= created)
new IndexWriter(_luceneDirectory, _analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);

Categories

Resources