Sunday, March 31, 2019

Dr Jordan B Peterson

Are you alive? That means you're all in, so you might as well play your most magnificent game. Ask yourself today: how much good can I do, or what's the best thing I can do? This is one of the ways to justify existence.
Orient yourself to the highest possible good that you can conceive and commit to it. You're way more powerful than you think.

Wednesday, March 27, 2019

Log4j2

log4j2.properties


 name=PropertiesConfig  
 property.filename = logs  
 appenders = console, file  
 appender.console.type = Console  
 appender.console.name = STDOUT  
 appender.console.layout.type = PatternLayout  
 appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n  
 appender.file.type = File  
 appender.file.name = LOGFILE  
 appender.file.fileName=${filename}/myLogs.log  
 appender.file.layout.type=PatternLayout  
 appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n  
 loggers=file  
 logger.file.name=kavoor  
 logger.file.level = debug  
 logger.file.appenderRefs = file  
 logger.file.appenderRef.file.ref = LOGFILE  
 rootLogger.level = debug  
 rootLogger.appenderRefs = stdout  
 rootLogger.appenderRef.stdout.ref = STDOUT  


SampleTest.java


 package kavoor;  
 import org.apache.logging.log4j.LogManager;  
 import org.apache.logging.log4j.Logger;  
 public class LoggerSample {  
      private static Logger logger = LogManager.getLogger(LoggerSample.class);  
      public static void main(String[] args) {  
           logger.info("Info");  
           logger.warn("Warn");  
           logger.debug("Debug");  
           logger.error("Error");  
           logger.fatal("Fatal");  
      }  
 }  


Mylogs.log


 [INFO ] 2019-03-27 15:55:06.748 [main] LoggerSample - Info  
 [WARN ] 2019-03-27 15:55:06.751 [main] LoggerSample - Warn  
 [DEBUG] 2019-03-27 15:55:06.751 [main] LoggerSample - Debug  
 [ERROR] 2019-03-27 15:55:06.751 [main] LoggerSample - Error  
 [FATAL] 2019-03-27 15:55:06.751 [main] LoggerSample - Fatal  




Tuesday, March 26, 2019

8 Ways to Become a Better Coder


It’s time to get serious about improving your programming skills. Let’s do it!
That’s an easy career improvement goal to give oneself, but “become a kick-ass programmer” is not a simple goal. For one thing, saying, “I want to get better” assumes that you recognize what “better” looks like. Plus, too many people aim for improvement without any sense of how to get there.
So let me share eight actionable guidelines that can act as a flowchart to improving your programming skills. These tidbits of wisdom are gathered from 35 years in the computer industry, many of which were spent as a lowly grasshopper at the feet of some of the people who defined and documented it.
1. Remind yourself how much you have to learn
The first step in learning something is recognizing that you don’t know it. That sounds obvious, but experienced programmers remember how long it took to overcome this personal assumption. Too many computer science students graduate with an arrogant “I know best” bravado, a robust certainty that they know everything and the intense need to prove it to every new work colleague. In other words: Your “I know what I’m doing!” attitude can get in the way of learning anything new.

2. Stop trying to prove yourself right

To become great—not just good—you have to learn from experience. But be careful, experience can teach us to repeat poor behavior and to create bad habits. We’ve all encountered programmers with eight years of experience … the same year of experience, repeated eight times. To avoid that syndrome, look at everything you do and ask yourself, “How can I make this better?”
Novice software developers (and too many experienced ones) look at their code to admire its wonderfulness. They write tests to prove that their code works instead of trying to make it fail. Truly great programmers actively look for where they’re wrong—because they know that eventually users will find the defects they missed.

3. “The code works” isn’t where you stop; it’s where you start

Yes, your first step is always to write quality software that fulfills the spec. Average programmers quit at that point and move on to the next thing.
But to stop once it’s “done” is like taking a snapshot and expecting it to be a work of art. Great programmers know that the first iteration is just the first iteration. It works— congratulations!—but you aren’t done. Now, make it better.
Part of that process is defining what “better” means. Is it valuable to make it faster? Easier to document? More reusable? More reliable? The answer varies with each application, but the process doesn’t.

4. Write it three times

Good programmers write software that works. Great ones write software that works exceedingly well. That rarely happens on the first try. The best software usually is written three times:
  1. First, you write the software to prove to yourself (or a client) that the solution is possible. Others may not recognize that this is just a proof-of-concept, but you do.
  2. The second time, you make it work.
  3. The third time, you make it work right.
This level of work may not be obvious when you look at the work of the best developers. Everything they do seems so brilliant, but what you don’t see is that even rock-star developers probably threw out the first and second versions before showing their software to anyone else. Throwing away code and starting over can be a powerful way to include “make it better” into your personal workflow.
If nothing else, “Write it three times” teaches you how many ways there are to approach a problem. And it prevents you from getting stuck in a rut.

5. Read code. Read lots of code

You probably expected me to lead with this advice, and indeed it’s both the most common and the most valuable suggestion for improving programming skills. What is less evident are the reasons that reading others’ code is so important.
When you read others’ code, you see how someone else solved a programming problem. But don’t treat it as literature; think of it as a lesson and a challenge. To get better, ask yourself:
  • How would I have written that block of code? What would you do differently, now that you’ve seen another solution?
  • What did I learn? How can I apply that technique to code I wrote in the past? (“I’d never have thought to use recursive descent there…”).
  • How would I improve this code? And if it’s an open source project where you are confident you have a better solution, do it!
  • Write code in the author’s style. Practicing this helps you get into the head of the person who wrote the software, which can improve your empathy.
Don’t just idly think about these steps. Write out your answers, whether in a personal journal, a blog, in a code review process, or a community forum with other developers. Just as explaining a problem to a friend can help you sort out the solution, writing down and sharing your analysis can help you understand why you react to another person’s code in a given way. It’s all part of that introspection I mentioned earlier, helping you to dispassionately judge your own strengths and weaknesses.
Warning: It’s easy to read a lot of code without becoming a great programmer, just as a wannabe writer can read great literature without improving her own prose. Plenty of developers look at open source or other software to “find an answer” and, most likely, to copy and paste code that appears to solve a similar problem. Doing that can actually make you a worse programmer, since you are blindly accepting others’ wisdom without examining it. (Plus, it may be buggier than a summer picnic, but because you didn’t take the time to understand it, you’ll never recognize that you just imported a bug-factory.)
6. Write code, and not just as assignments
Working on personal programming projects has many advantages. For one, it gives you a way to learn tools and technologies that aren’t available at your current job, but which make you more marketable for the next one. Whether you contribute to an open source project or take on pro-bono work for a local community organization, you’ll gain tech skills and self-confidence. (Plus, your personal projects demonstrate to would-be employers that you’re a self-starter who never stops learning.)
Another advantage of writing code for fun is that it forces you to figure things out on your own. You can’t leave the hard stuff to someone else, so it keeps you from asking for help too soon.
Pro tip: Don’t choose only personal projects where you never fail. You need to fail! But you do probably don’t want to fail at work or when you have a deadline.
7. Work one-on-one with other developers any way you can
It helps to listen to other people. That might mean pair programming, or going to a hackathon, or joining a programming user group (such as the Vermont Coders Connection). When you contribute to an open source project, pay attention to the feedback you get from users and from other developers. What commonalities do you see in their criticism?
You might be lucky enough to find a personal mentor whom you can trust to guide you in everything from coding techniques to career decisions. Don’t waste these opportunities.

8. Learn techniques, not tools

Programming languages, tools, and methodologies come and go. That’s why it pays to get as much experience as you can with as many languages and frameworks as possible. Focus on the programming fundamentals, because the basics never change; pay more attention to architecture than to programming. If you feel certain that there’s only one right way to do something, it’s probably time for a reality check. Dogma can hamper your ability to learn new things, and make you slow to adapt to change.
I could keep going, but a key tenet of self-improvement is knowing when to stop.

Saturday, March 23, 2019

ITestListener in TestNG Selenium




Test file

 package learning;  
 import org.testng.Assert;  
 import org.testng.annotations.Listeners;  
 import org.testng.annotations.Test;  
 @Listeners(MyListeners.class)  
 public class ListenerExample {  
      @Test  
      public void testToFail() {  
           Assert.assertTrue(false);  
      }  
      public void testToPass(){  
           Assert.assertTrue(true);  
      }  
 }  


Listener class

 package learning;  
 import org.testng.ITestContext;  
 import org.testng.ITestListener;  
 import org.testng.ITestResult;  
 import org.testng.SkipException;  
 public class MyListeners implements ITestListener {  
      @Override  
      public void onTestStart(ITestResult result) {  
           System.out.println("Test started " + result);  
      }  
      @Override  
      public void onTestSuccess(ITestResult result) {  
           System.out.println("This test passed " + result);  
      }  
      @Override  
      public void onTestFailure(ITestResult result) {  
           System.out.println("This test failed " + result);  
      }  
      @Override  
      public void onTestSkipped(ITestResult result) {  
           System.out.println("Test is Skipped " + result);  
           throw new SkipException("Skipping this exception");  
      }  
      @Override  
      public void onTestFailedButWithinSuccessPercentage(ITestResult result) {  
      }  
      @Override  
      public void onStart(ITestContext context) {  
           System.out.println("Test started");  
      }  
      @Override  
      public void onFinish(ITestContext context) {  
           System.out.println("Test finnished");  
      }  
 }  


TestNG.xml

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite">  
      <listeners>  
           <listener class-name="learning.MyListeners" />  
      </listeners>  
      <test name="Test">  
           <classes>  
                <class name="learning.HilightExample" />  
           </classes>  
      </test> <!-- Test -->  
 </suite> <!-- Suite -->  

Friday, March 22, 2019

Highlight elements in Selenium Webdriver



 package learning;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 public class Hightlight {  
      public static void hilightElement(WebElement element, WebDriver driver) {  
           for (int i = 0; i < 2; i++) {  
                JavascriptExecutor js = (JavascriptExecutor) driver;  
                js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');",  
                          element);  
           }  
      }  
 }  


 package learning;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.testng.annotations.Test;  
 public class HilightExample {  
      @Test  
      public void showIt() {  
           System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.get("https://www.flipkart.com/");  
           WebElement element = driver.findElement(By.className("_2zrpKA"));  
           Hightlight.hilightElement(element, driver);  
           element.sendKeys("hulagabal@gmail.com");  
      }  
 }  

Tuesday, March 12, 2019

Data provider in TestNG

 package muttu.test;  
 import org.testng.annotations.DataProvider;  
 import org.testng.annotations.Test;  
 public class DataProviderDemo {  
      @DataProvider(name = "LoginDeatls")  
      public Object[][] getUserDetails() {  
           return new Object[][] { { "uName1", "pwd1" }, { "uName2", "pwd2" } };  
      }  
      @Test(dataProvider = "LoginDeatls")  
      public void Login(String name, String password) {  
           System.out.println(name);  
           System.out.println(password);  
      }  
 }  

Run failed test cases in Java


Create a class that fails test case


 package testNG;  
 import org.testng.Assert;  
 import org.testng.annotations.Test;  
 public class TestFailClass {  
      @Test(retryAnalyzer=MyRetry.class)  
      public void failMethod(){  
           System.out.println("FAILED CLASS");  
           Assert.assertTrue(false);  
      }  
 }  

Create a class that re-runs the failed test cases

 package testNG;  
 import java.util.ArrayList;  
 import java.util.List;  
 import org.testng.TestNG;  
 public class RunFailed {  
      public static void main(String[] args) {  
           TestNG testRunner = new TestNG();  
           List<String> failedXmls = new ArrayList<String>();  
           //Enter the full path for the 'test-faailed.xml' file  
           failedXmls.add("C:/Users/Mutturaj.h/workspace/hulagabal/test-output/testng-failed.xml");  
           testRunner.setTestSuites(failedXmls);  
           testRunner.run();  
      }  
 }  

Retry failed test cases TestNG in Java


Create test cases which fails

 package testNG;  
 import org.testng.Assert;  
 import org.testng.annotations.Test;  
 public class TestFailClass {  
      @Test(retryAnalyzer=MyRetry.class)  
      public void failMethod(){  
           Assert.fail("Test failed");  
      }  
 }  

Create a retry class which implements IRetryAnalyzer interface like below which tries for 3 times

 package testNG;  
 import org.testng.IRetryAnalyzer;  
 import org.testng.ITestResult;  
 public class MyRetry implements IRetryAnalyzer {  
      private int retryCount = 0;  
      private static final int maxRetryCount = 3;  
      public boolean retry(ITestResult result) {  
           if (retryCount < maxRetryCount) {  
                retryCount++;  
                return true;  
           }  
           return false;  
      }  
 }  

Sunday, March 10, 2019

import java.text.SimpleDateFormat;
import java.util.Date;

public class MethodName {

String methodName;

public static String getName() {

return new Object() {
}.getClass().getEnclosingMethod().getName();

}

public static String dateStamp() {

return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());

}

public static void main(String[] args) {

System.out.println(dateStamp());
System.out.println(getName());

System.out.println(new Object() {
}.getClass().getEnclosingMethod().getName());
}

}

Get Name of the current executing method name

 public class MethodName {  
      public static void main(String[] args) {  
           String name = new Object() {  
           }.getClass().getEnclosingMethod().getName();  
           System.out.println(name);  
      }  
 }  

Saturday, March 9, 2019

Record video and save video by method name or any name by passing parameter

Create a class named:  SpecializedScreenRecorder.java

Paste the below code into the class

 package learning;  
 import java.awt.AWTException;  
 import java.awt.GraphicsConfiguration;  
 import java.awt.Rectangle;  
 import java.io.File;  
 import java.io.IOException;  
 import java.text.SimpleDateFormat;  
 import java.util.Date;  
 import org.monte.media.Format;  
 import org.monte.media.Registry;  
 import org.monte.screenrecorder.ScreenRecorder;  
 public class SpecializedScreenRecorder extends ScreenRecorder {  
      private String name;  
      public SpecializedScreenRecorder(GraphicsConfiguration cfg, Rectangle captureArea, Format fileFormat,  
                Format screenFormat, Format mouseFormat, Format audioFormat, File movieFolder,String name)  
                throws IOException, AWTException {  
           super(cfg, captureArea, fileFormat, screenFormat, mouseFormat, audioFormat, movieFolder);  
           this.name=name;  
      }  
      @Override  
      protected File createMovieFile(Format fileFormat) throws IOException {  
           if (!movieFolder.exists()) {  
                movieFolder.mkdirs();  
           } else if (!movieFolder.isDirectory()) {  
                throw new IOException("\"" + movieFolder + "\" is not a directory.");  
           }  
           SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");  
           return new File(movieFolder,  
                     name + "-" + dateFormat.format(new Date()) + "." + Registry.getInstance().getExtension(fileFormat));  
      }  
 }  

Create another class named: Video.java

copy below code into that

 package learning;  
 import static org.monte.media.FormatKeys.EncodingKey;  
 import static org.monte.media.FormatKeys.FrameRateKey;  
 import static org.monte.media.FormatKeys.KeyFrameIntervalKey;  
 import static org.monte.media.FormatKeys.MIME_AVI;  
 import static org.monte.media.FormatKeys.MediaTypeKey;  
 import static org.monte.media.FormatKeys.MimeTypeKey;  
 import static org.monte.media.VideoFormatKeys.CompressorNameKey;  
 import static org.monte.media.VideoFormatKeys.DepthKey;  
 import static org.monte.media.VideoFormatKeys.ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE;  
 import static org.monte.media.VideoFormatKeys.QualityKey;  
 import java.awt.Dimension;  
 import java.awt.GraphicsConfiguration;  
 import java.awt.GraphicsEnvironment;  
 import java.awt.Rectangle;  
 import java.awt.Toolkit;  
 import java.io.File;  
 import org.monte.media.Format;  
 import org.monte.media.FormatKeys.MediaType;  
 import org.monte.media.math.Rational;  
 import org.monte.screenrecorder.ScreenRecorder;  
 public class Video{  
   public static final String USER_DIR = "user.dir";  
   public static final String DOWNLOADED_FILES_FOLDER = "downloadFiles";  
   private static ScreenRecorder screenRecorder;  
   public static void startRecording(String methodName) throws Exception {  
     File file = new File(System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER);  
     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();  
     int width = screenSize.width;  
     int height = screenSize.height;  
     Rectangle captureSize = new Rectangle(0, 0, width, height);  
     GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();  
     screenRecorder = new SpecializedScreenRecorder(gc, captureSize, new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),  
         new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, DepthKey, 24, FrameRateKey,  
             Rational.valueOf(15), QualityKey, 1.0f, KeyFrameIntervalKey, 15 * 60),  
         new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black", FrameRateKey, Rational.valueOf(30)), null, file, methodName);  
     screenRecorder.start();  
   }  
   public static void stopRecording() throws Exception {  
     screenRecorder.stop();  
   }  
 }  



Screen recording of a test execution in selenium using JAVA

1. Download .jar from https://www.randelshofer.ch/monte/index.html

add to your project














2.Create class and copy below code into the class


 package learning;  
 import static org.monte.media.FormatKeys.EncodingKey;  
 import static org.monte.media.FormatKeys.FrameRateKey;  
 import static org.monte.media.FormatKeys.KeyFrameIntervalKey;  
 import static org.monte.media.FormatKeys.MIME_AVI;  
 import static org.monte.media.FormatKeys.MediaTypeKey;  
 import static org.monte.media.FormatKeys.MimeTypeKey;  
 import static org.monte.media.VideoFormatKeys.CompressorNameKey;  
 import static org.monte.media.VideoFormatKeys.DepthKey;  
 import static org.monte.media.VideoFormatKeys.ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE;  
 import static org.monte.media.VideoFormatKeys.QualityKey;  
 import java.awt.AWTException;  
 import java.awt.GraphicsConfiguration;  
 import java.awt.GraphicsEnvironment;  
 import java.io.IOException;  
 import org.monte.media.Format;  
 import org.monte.media.FormatKeys.MediaType;  
 import org.monte.media.math.Rational;  
 import org.monte.screenrecorder.ScreenRecorder;  
 public class Video {  
      static ScreenRecorder screenRecorder;  
      // Method to start recording video  
      public static void startRecord() throws IOException, AWTException {  
           GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()  
                     .getDefaultConfiguration();  
           screenRecorder = new ScreenRecorder(configuration,  
                     new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),  
                     new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,  
                               CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, DepthKey, (int) 24, FrameRateKey,  
                               Rational.valueOf(15), QualityKey, 1.0f, KeyFrameIntervalKey, (int) (15 * 60)),  
                     new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black", FrameRateKey, Rational.valueOf(30)),  
                     null);  
           screenRecorder.start();  
      }  
      // Method to stop vedeo recording  
      public static void stopRecord() throws IOException {  
           screenRecorder.stop();  
      }  
 }  
3.Use it wherever you want to record

Friday, March 8, 2019

Select an Item from the drop-down in selenium webdriver

 package learning;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.support.ui.Select;  
 public class Dropdown {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://html.com/attributes/select-size/?utm_source=network%20recirc&utm_medium=Bibblio");  
           //Select dropdown by Select class  
           Select select = new Select(driver.findElement(By.xpath("//select")));  
           //select required item from the above dropdown  
           select.selectByValue("Lesser");  
      }  
 }  

Dealing with modal dialog in selenium Webdriver

 package test.test;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class ModelDialog {  
      public static void main(String[] args) throws InterruptedException {  
           System.setProperty("webdriver.chrome.driver",  
                     "C:\\Users\\Mutturaj\\Downloads\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://html.com/input-type-file/");  
           WebElement element = driver.findElement(By.xpath("//*[@id='fileupload']"));  
           JavascriptExecutor jse = (JavascriptExecutor) driver;  
           jse.executeScript("arguments[0].scrollIntoView()", element);  
           element.sendKeys("C:/Users/Mutturaj/Downloads/chromedriver_win32/chromedriver.exe");  
           System.out.println("File Uploaded");  
           // activeElement() method clicks the modal dialog  
           driver.switchTo().activeElement();  
           // Click on the button, here in out case we click on the 'Don't allow'  
           // button  
           driver.findElement(By.linkText("Don't Allow")).click();  
           driver.findElement(By.xpath("//input[@type='submit' and @value='submit']")).click();  
           System.out.println("Submitted");  
      }  
 }  

Handling Alert in selenium

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class AlertPopup {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver",  
                     "C:\\Users\\Mutturaj\\Downloads\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://mail.rediff.com/cgi-bin/login.cgi");  
           driver.findElement(By.name("proceed")).click();  
           Alert alert = driver.switchTo().alert();  
           System.out.println(alert.getText());  
           alert.accept();  

           // other importent methods  
           /*  
            * alert.getText() alert.dismiss(); alert.sendKeys("text");  
            */  
      }  
 }  

Implicit wait in Selenium

 package learning;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.interactions.Actions;  
 import org.openqa.selenium.support.ui.ExpectedConditions;  
 import org.openqa.selenium.support.ui.WebDriverWait;  
 public class MoveMouse {  
      public static void main(String[] args) throws Exception {  
           System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://www.spicejet.com");  
           Actions actions = new Actions(driver);  
           actions.moveToElement(driver.findElement(By.linkText("ADD-ONS"))).build().perform();  
           Thread.sleep(3000);  
           waitForVisa(driver,driver.findElement(By.linkText("Dubai Visa Services")),20);  
           driver.close();  
      }  
//Implicit wait method
      public static void waitForVisa(WebDriver driver, WebElement element,int timeout){  
           new WebDriverWait(driver,timeout).until(ExpectedConditions.elementToBeClickable(element));  
           element.click();            
      }  
 }  

Thursday, March 7, 2019

Take screenshots in selenium

 package utility;  
 import java.io.File;  
 import java.io.IOException;  
 import java.text.SimpleDateFormat;  
 import java.util.Calendar;  
 import java.util.concurrent.TimeUnit;  
 import org.apache.commons.io.FileUtils;  
 import org.openqa.selenium.OutputType;  
 import org.openqa.selenium.TakesScreenshot;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class TakeScreenshot1 {  
      //Takes screenshot method  
      public static void takepics(WebDriver driver,String filePath) throws IOException{  
           File file=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);  
           File destFile=new File(filePath);  
           FileUtils.copyFile(file, destFile);  
      }  
      public static void main(String[] args) throws IOException {  
           System.setProperty("webdriver.chrome.driver",  
                     "C:/Users/Mutturaj.h/Desktop/Soft/chromedriver_win32/chromedriver.exe");  
           //Time Stamp  
           String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());  
           //File path where screenshot is saved  
           String filePath="C:/Users/Mutturaj.h/workspace/Test/Screenshots/muttu"+""+ timeStamp+".png";  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://www.amazon.in/");  
           // takepics() method is called after page loaded  
           TakeScreenshot1.takepics(driver,filePath);  
      }  
 }  

Mouse Movement in Selenium

 package learning;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.interactions.Actions;  
 public class MoveMouse {  
      public static void main(String[] args) throws Exception {  
           System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://www.spicejet.com");  
           Actions actions = new Actions(driver);  
           actions.moveToElement(driver.findElement(By.linkText("ADD-ONS"))).build().perform();  
           Thread.sleep(3000);  
           driver.findElement(By.linkText("Dubai Visa Services")).click();  
      }  
 }  

Wednesday, March 6, 2019

Count all the links and display in Selenium Webdriver

 package learning;  
 import java.util.List;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class CountElements {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://www.facebook.com/");  
           List<WebElement> list = driver.findElements(By.tagName("a"));  
           System.out.println(list.size());  
           for (int i = 0; i < list.size(); i++) {  
                String links = list.get(i).getText();  
                System.out.println(links);  
           }  
      }  
 }  

Tuesday, March 5, 2019

Open Source Automation Testing Tools

  • Selenium
  • JMeter
  • JUnit
  • Maven
  • TestNG
  • Katalon Studio
  • SoapUI
  • Sikuli
  • Appium
  • Robotium
  • Cucumber
  • Watir
  • Canoo WebTest
  • WatiN
  • Capybara
  • Tarantula
  • Testlink
  • Windmill
  • Marathon
  • httest
  • Xmind
  • Wiremock
  • Espresso
  • FitNesse
  • Grinder
  • Tsung
  • Gatling
  • Multi-mechanize
  • Selendroid
  • KIF
  • iMacros
  • Linux Desktop Testing Tool