How to use Pdf class of org.openqa.selenium package

Best Selenium code snippet using org.openqa.selenium.Pdf

Source:SeleniumDownloadHelperTest.java Github

copy

Full Screen

...32 private WebDriver driver;33 // Server testdata34 private static String baseUrl;35 private static String indexPage = "";36 private static String testPdf = "SeleniumDownloadHelper.pdf";37 private File testPdfFile;38 private static File serverBaseFolder = new File("src/test/resources/testServer");39 private byte[] referenceContent;40 private static Server server;41 @BeforeClass42 public static void setUpClass() throws Exception {43 Server server = new Server(0);44 ResourceHandler resource_handler = new ResourceHandler();45 resource_handler.setDirectoriesListed(true);46 resource_handler.setResourceBase(serverBaseFolder.toString());47 HandlerList handlers = new HandlerList();48 handlers.setHandlers(new Handler[]{resource_handler});49 server.setHandler(handlers);50 server.start();51 baseUrl = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/";52 }53 @AfterClass54 public static void tearDownClass() throws Exception {55 if (server != null) {56 server.stop();57 }58 }59 @Before60 public void setUpFiles() throws Exception {61 testPdfFile = new File(serverBaseFolder + "/" + testPdf);62 referenceContent = FileUtils.readFileToByteArray(testPdfFile);63 }64 @After65 public void tearDownTestDriver() throws Exception {66 if (driver != null)67 driver.quit();68 }69 @Test70 @Ignore("Known to fail")71 public void testGetFileFromUrlHtmlUnit() throws Exception {72 driver = new HtmlUnitDriver(true);73 invokeGetFileDataFromUrl();74 invokeGetFileFromUrl();75 }76 @Test77 public void testGetFileFromUrlChrome() throws Exception {78 //TODO put this into pom profiles which are OS specific or build helper lib like phantomjs has79 System.setProperty("webdriver.chrome.driver", "driver/chromedriver");80 driver = new ChromeDriver();81 invokeGetFileDataFromUrl();82 invokeGetFileFromUrl();83 }84 @Test85 @TargetOS(family = "mac")86 public void testGetFileFromUrlSafari() throws Exception {87 driver = new SafariDriver();88 invokeGetFileDataFromUrl();89 invokeGetFileFromUrl();90 }91 @Test92 public void testGetFileFromUrlFireFox() throws Exception {93 driver = new FirefoxDriver();94 invokeGetFileDataFromUrl();95 invokeGetFileFromUrl();96 }97 @Test98 @TargetOS(family = "windows")99 public void testGetFileFromUrlInternetExplorer() throws Exception {100 //TODO Fetch latest binaries and make arch specific profiles101 driver = new InternetExplorerDriver();102 invokeGetFileDataFromUrl();103 invokeGetFileFromUrl();104 }105 @Test106 public void testGetFileFromUrlPhantomJS() throws Exception {107 // See http://blog.anthavio.net/2014/04/phantomjs-embedder-for-selenium.html108 File phantomjs = Phanbedder.unpack();109 DesiredCapabilities dcaps = new DesiredCapabilities();110 dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, phantomjs.getAbsolutePath());111 driver = new PhantomJSDriver(dcaps);112 invokeGetFileDataFromUrl();113 invokeGetFileFromUrl();114 }115 private void invokeGetFileDataFromUrl() throws Exception {116 driver.get(baseUrl + indexPage);117 SeleniumDownloadHelper sdlh = new SeleniumDownloadHelper(driver);118 FileData testFileData = sdlh.getFileFromUrlRaw(new URL(baseUrl + testPdf));119 Assert.assertArrayEquals("Raw data is correct", referenceContent, testFileData.getData());120 Assert.assertTrue("Guessed name from URL is correct", testPdf.equals(testFileData.getGuessedFilename()));121 }122 private void invokeGetFileFromUrl() throws Exception {123 driver.get(baseUrl + indexPage);124 SeleniumDownloadHelper sdlh = new SeleniumDownloadHelper(driver);125 File tmpFile = File.createTempFile("testfile", ".pdf");126 tmpFile.deleteOnExit();127 File dlFile = sdlh.getFileFromUrl(new URL(baseUrl + testPdf), tmpFile);128 Assert.assertTrue("File content is correct", FileUtils.contentEquals(testPdfFile, dlFile));129 }130}...

Full Screen

Full Screen

Source:ExportPdfPage.java Github

copy

Full Screen

...28 * and methods that handle the interaction with said page.29 * @author omar30 *31 */32public class ExportPdfPage {33 34 private WebDriver driver;35 36 private String downloadFileNamePath;37 38 /**39 * Constructs a new ExportPdfPage object, using the driver created in <class>com.wikipedia.tests.Page</class>40 * It also initializes its web elements 41 * @param driver WebDriver used to run the tests.42 */43 44 public ExportPdfPage(WebDriver driver) {45 this.driver = driver;46 PageFactory.initElements(this.driver, this);47 }48 49 /* Web Element declaration section*/50 51 @FindBy(how = How.CSS, using = "#plugin")52 WebElement pdfObj;53 54 /**55 * it downloads the pdf depending on which browser is running. On Chrome, a ExportPDF page56 * appears, meanwhile internet explorer shows a small dialog showing options.57 */58 59 public void downloadPdf() {60 61 if(driver instanceof ChromeDriver) {62 63 try {64 Thread.sleep(Properties.TIMEOUT/10);65 } catch (InterruptedException e1) {66 // TODO Auto-generated catch block67 e1.printStackTrace();68 System.out.println(e1);69 }70 71 // Create object of Robot class72 Robot robotObject;73 try {74 robotObject = new Robot();75 com.framework.util.KeyboardKeys kk = new KeyboardKeys();76 Thread.sleep(Properties.KEYSTROKE_WAIT);77 robotObject.keyPress(KeyEvent.VK_CONTROL);78 robotObject.keyRelease(KeyEvent.VK_S);79 Thread.sleep(Properties.KEYSTROKE_WAIT);80 robotObject.keyPress(KeyEvent.VK_S);81 robotObject.keyRelease(KeyEvent.VK_CONTROL);82 Thread.sleep(Properties.TIMEOUT/2);83 84 Date now = new java.util.Date();85 String currTime = new SimpleDateFormat(Properties.TIMESTAMP_FORMAT).format(new Date());86 downloadFileNamePath = Properties.PDF_SAVE_PATH + Properties.PDF_FILENAME + Properties.FILENAME_SEPARATOR + currTime + Properties.PDF_FILE_EXTENSION;87 for(int i = 0; i < downloadFileNamePath.length(); i++) {88 89 kk.keyPress(downloadFileNamePath.charAt(i));90 } 91 robotObject.keyPress(KeyEvent.VK_ENTER);92 Thread.sleep(Properties.KEYSTROKE_WAIT/10);93 robotObject.keyRelease(KeyEvent.VK_ENTER);94 Thread.sleep(Properties.TIMEOUT/2);95 } catch (AWTException e) {96 System.out.println(e);97 e.printStackTrace();98 } catch (InterruptedException e) {99 System.out.println(e);100 e.printStackTrace();101 }102 }103 else if(driver instanceof InternetExplorerDriver) {104 //Todo click the save as dialog and redirect file to save file path.105 }106 else if(driver instanceof FirefoxDriver){107 //Todo click the save as dialog and redirect file to save file path.108 }109 110 }111 /**112 * Indicates whether the browser is currently at this page.113 * @return boolean, true if currently at the ExportPdfPage marked by the pdf object, 114 * false otherwise115 */ 116 public boolean isAt() {117 // TODO Auto-generated method stub118 return pdfObj.isDisplayed();119 }120 121 public boolean fileHasDownloaded() {122 File file;123 for(int i = 0; i < (int) Properties.TIMEOUT; i++) {124 try {125 126 file = new File(downloadFileNamePath);127 if(!file.exists()) {...

Full Screen

Full Screen

Source:FileDownloadPDF.java Github

copy

Full Screen

1package SeleniumConcepts;2import java.util.HashMap;3import org.openqa.selenium.By;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.edge.EdgeDriver;8import org.openqa.selenium.edge.EdgeOptions;9import org.openqa.selenium.firefox.FirefoxDriver;10import org.openqa.selenium.firefox.FirefoxOptions;11import org.openqa.selenium.firefox.FirefoxProfile;12import org.testng.annotations.AfterMethod;13import org.testng.annotations.BeforeMethod;14import org.testng.annotations.Test;15import io.github.bonigarcia.wdm.WebDriverManager;16public class FileDownloadPDF {17 WebDriver driver;18 19 @BeforeMethod20 public void setup() {21 String location = System.getProperty("user.dir")+"\\downloads\\";22 23//chrome24/* HashMap pref = new HashMap();25 pref.put("plugins.always_open_pdf_externally", true); //for pdf26 pref.put("download.default_directory", location);27 ChromeOptions options = new ChromeOptions();28 options.setExperimentalOption("prefs", pref);29 30 WebDriverManager.chromedriver().setup();31 driver = new ChromeDriver(options); 32 driver.manage().window().maximize();*/33 34//Edge35/* HashMap pref = new HashMap();36 pref.put("plugins.always_open_pdf_externally", true); //for pdf37 pref.put("download.default_directory", location);38 EdgeOptions options = new EdgeOptions();39 options.setExperimentalOption("prefs", pref);40 41 WebDriverManager.edgedriver().setup();42 driver = new EdgeDriver(options);43 driver.manage().window().maximize(); */44 45//Firefox46 FirefoxProfile profile = new FirefoxProfile();47 profile.setPreference("pdfjs.disabled", true);48 profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword");49 profile.setPreference("browser.download.folderList", 2);50 profile.setPreference("browser.download.dir", location);51 52 FirefoxOptions options = new FirefoxOptions();53 options.setProfile(profile);54 55 WebDriverManager.firefoxdriver().setup();56 driver = new FirefoxDriver(options);57 driver.manage().window().maximize();58 }59 60 @Test61 public void downloadFile() {62 driver.get("https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/");63 driver.findElement(By.xpath("//tbody/tr[1]/td[5]/a[1]")).click();64 // driver.switchTo().alert().dismiss();65 }66 @AfterMethod67 public void tearDown() {68 //driver.quit();69 }70}...

Full Screen

Full Screen

Source:DownloadPdfFile.java Github

copy

Full Screen

...14import org.openqa.selenium.firefox.FirefoxProfile;1516import io.github.bonigarcia.wdm.WebDriverManager;1718public class DownloadPdfFile {1920 public static void main(String[] args) {21 String location=System.getProperty("user.dir")+"\\Downloads\\";22 23 HashMap preferences=new HashMap();24 preferences.put("plugins.always_open_pdf_externally", true); //for pdf download25 preferences.put("download.default_directory", location);26 27 //Chrome28 /*ChromeOptions options=new ChromeOptions();29 options.setExperimentalOption("prefs",preferences);30 31 WebDriverManager.chromedriver().setup();32 WebDriver driver=new ChromeDriver(options);*/ ...

Full Screen

Full Screen

Source:PdfImage.java Github

copy

Full Screen

...19import com.itextpdf.text.Document;20import com.itextpdf.text.DocumentException;21import com.itextpdf.text.Image;22import com.itextpdf.text.Paragraph;23import com.itextpdf.text.pdf.PdfWriter;2425public class PdfImage {2627 static WebDriver driver;28 static Document document;29 public static void main(String[] args) throws DocumentException, MalformedURLException, IOException {30 // TODO Auto-generated method stub31 System.setProperty("webdriver.chrome.driver", "C:\\jars\\chromedriver.exe");32 document = new Document();33 PdfWriter.getInstance(document, new FileOutputStream("C:\\img\\Report.pdf"));34 document.open();35 driver=new ChromeDriver();36 driver.get("https://www.google.com/");37 WebElement e1=driver.findElement(By.name("q"));38 JavascriptExecutor jse=(JavascriptExecutor)(driver); 39 jse.executeScript("arguments[0].setAttribute('style','background: yellow; border: 2px solid red;');", e1);40 takeScreenShot("Before entering");41 e1.sendKeys("sachin");42 takeScreenShot("After Entering");43 document.close();44 45 System.out.println("Done");46 }47 public static void takeScreenShot(String step) throws IOException, DocumentException ...

Full Screen

Full Screen

Source:DownloadPDF.java Github

copy

Full Screen

1package others;23import java.util.HashMap;45import org.openqa.selenium.Keys;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.chrome.ChromeDriver;8import org.openqa.selenium.chrome.ChromeOptions;9import org.openqa.selenium.interactions.Actions;10import org.openqa.selenium.remote.RemoteWebDriver;11import org.testng.annotations.Test;1213public class DownloadPDF {14 RemoteWebDriver driver;15 ChromeOptions options;16 String downloadFilepath = "K:\\";17 HashMap<String, Object> prefs;18 Actions builder;19 @Test20 public void pdf() {21 options = new ChromeOptions();22 prefs = new HashMap<String, Object>(); // To put preferences using "prefs" (KeyWord)23 prefs.put("download.default_directory", downloadFilepath); //To set path24 prefs.put("safebrowsing.enabled", "false"); // To disable security check (keep or Cancel)25 prefs.put("plugins.always_open_pdf_externally", true);26 options.setExperimentalOption("prefs", prefs); // Adding preferences to ChromeOptions27 options.addArguments("--disable-extensions"); //to disable window browser28 driver = new ChromeDriver(options);29 driver.manage().window().maximize();30 driver.get("http://enos.itcollege.ee/~jpoial/allalaadimised/reading/");31 WebElement pdf = driver.findElementByLinkText("Advanced-java.pdf");32 pdf.click();33 }34 public void openInNewTab(WebElement ele) {35 builder = new Actions(driver);36 builder.sendKeys(ele,Keys.CONTROL).click().perform();37 }38 ...

Full Screen

Full Screen

Source:PDFViewerHelper.java Github

copy

Full Screen

...10 * @author Syed A. Zawad11 *12 */13public class PDFViewerHelper {14 @FindBy(css = "iframe.embedPdf")15 private WebElement pdfContainer;16 private WebDriver driver;17 public PDFViewerHelper(WebDriver driver) {18 this.driver = driver;19 UiHelper.waitForSpinnerEnd(driver.findElement(By.cssSelector("div.spinner")), 30);20 }21 public void printFrames() {22 driver.switchTo().frame(0);23 WebElement input = driver.findElement(By.id("pageNumber"));24 System.out.println("Page Number " + input.getAttribute("value"));25 driver.switchTo().parentFrame();26 }27 public void goToPageNumber(String pageNumber) {28 driver.switchTo().frame(0);...

Full Screen

Full Screen

Source:itextConvertHtmlToPdf.java Github

copy

Full Screen

1import com.itextpdf.text.Document;2import com.itextpdf.text.DocumentException;3import com.itextpdf.text.pdf.PdfWriter;4import com.itextpdf.tool.xml.XMLWorkerHelper;5import java.io.FileInputStream;6import java.io.FileNotFoundException;7import java.io.FileOutputStream;8import java.io.IOException;9import java.io.File;10import java.io.IOException;11import org.apache.commons.io.FileUtils;12import org.openqa.selenium.By;13import org.openqa.selenium.Dimension;14import org.openqa.selenium.Keys;15import org.openqa.selenium.OutputType;16import org.openqa.selenium.Point;17import org.openqa.selenium.TakesScreenshot;18import org.openqa.selenium.WebDriver;19import org.openqa.selenium.WebElement;20import org.openqa.selenium.phantomjs.PhantomJSDriver;21public class itextConvertHtmlToPdf {22 public static void main(String[] args) throws IOException, DocumentException {23 Document document = new Document();24 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdfFiles/pdfFile.pdf"));25 document.open();26 XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("test1.html"));27 document.close();28 System.out.println( "Ваш PDF файл - Создан!" );29 }30}...

Full Screen

Full Screen

Pdf

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.support.ui.ExpectedConditions;6import org.openqa.selenium.support.ui.WebDriverWait;7import org.openqa.selenium.support.ui.Select;8import org.openqa.selenium.JavascriptExecutor;9import org.openqa.selenium.Keys;10import org.openqa.selenium.interactions.Actions;11import java.util.concurrent.TimeUnit;12import java.util.List;13import java.util.ArrayList;14import java.util.Iterator;15import java.util.Collections;16import java.util.Set;17import java.util.HashMap;18import java.util.Map;19import java.util.Map.Entry;20import java.util.TreeMap;21import java.util.stream.Collectors;22import java.util.stream.Stream;23import java.util.Arrays;24import java.util.Random;25import java.util.Date;26import java.text.SimpleDateFormat;27import java.io.File;28import java.io.IOException;29import java.io.FileWriter;30import java.io.BufferedWriter;31import java.io.PrintWriter;32import java.io.BufferedReader;33import java.io.FileReader;34import java.util.regex.Matcher;35import java.util.regex.Pattern;36import org.apache.commons.io.FileUtils;37import org.apache.commons.lang3.StringUtils;38import org.apache.commons.lang3.RandomStringUtils;39import org.apache.commons.lang3.RandomUtils;40import org.apache.commons.lang3.time.StopWatch;41import org.apache.commons.lang3.time.DateUtils;42import org.apache.commons.lang3.time.DateFormatUtils;43import org.apache.commons.lang3.ArrayUtils;44import org.apache.commons.lang3.SystemUtils;45import org.apache.commons.lang3.builder.ToStringBuilder;46import org.apache.commons.lang3.builder.ToStringStyle;47import org.apache.commons.lang3.exception.ExceptionUtils;48import org.apache.commons.lang3.math.NumberUtils;49import org.apache.commons.lang3.tuple.ImmutablePair;50import org.apache.commons.lang3.tuple.Pair;51import org.apache.poi.xssf.usermodel.XSSFWorkbook;52import org.apache.poi.ss.usermodel.Workbook;53import org.apache.poi.ss.usermodel.Sheet;54import org.apache.poi.ss.usermodel.Cell;55import org.apache.poi.ss.usermodel.Row;56import org.apache.poi.ss.usermodel.DataFormatter;57import org.apache.poi.ss.usermodel.FormulaEvaluator;58import org.apache.poi.ss.usermodel.CellType;59import org.apache.poi.ss.usermodel.CellStyle;60import org.apache.poi.ss.usermodel.Font;61import org.apache.poi.ss.usermodel.IndexedColors;62import org.apache.poi.ss.util.CellRangeAddress;63import org.apache.poi.ss.util.CellReference;64import org.apache.poi.ss.util.WorkbookUtil;65import org.apache.poi.ss.util.CellAddress;66import org.apache.poi.ss.util.RegionUtil;

Full Screen

Full Screen

Pdf

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By; 2import org.openqa.selenium.WebDriver; 3import org.openqa.selenium.WebElement; 4import org.openqa.selenium.chrome.ChromeDriver; 5import org.openqa.selenium.chrome.ChromeOptions; 6import org.openqa.selenium.support.ui.ExpectedConditions; 7import org.openqa.selenium.support.ui.WebDriverWait;8import java.io.File; 9import java.io.IOException; 10import java.util.HashMap; 11import java.util.Map;12public class PdfDownload { 13public static void main(String[] args) throws IOException { 14System.setProperty(“webdriver.chrome.driver”, “C:\\Users\\shah\\Downloads\\chromedriver_win32\\chromedriver.exe”); 15ChromeOptions options = new ChromeOptions(); 16Map<String, Object> prefs = new HashMap<String, Object>(); 17prefs.put(“profile.default_content_settings.popups”, 0); 18prefs.put(“download.default_directory”, “C:\\Users\\shah\\Downloads”); 19options.setExperimentalOption(“prefs”, prefs); 20WebDriver driver = new ChromeDriver(options); 21download.click(); 22WebDriverWait wait = new WebDriverWait(driver,30); 23pdf.click(); 24File file = new File(“C:\\Users\\shah\\Downloads\\Selenium-Java-3.141.59.pdf”); 25if(file.exists()) 26{ 27System.out.println(“File downloaded successfully”); 28} 29{ 30System.out.println(“File not downloaded”); 31} 32driver.close(); 33} 34}

Full Screen

Full Screen

Pdf

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.chrome.ChromeOptions;6import org.openqa.selenium.remote.RemoteWebDriver;7import org.openqa.selenium.support.events.EventFiringWebDriver;8import java.io.File;9import java.io.IOException;10import java.util.HashMap;11import java.util.Map;12import java.util.concurrent.TimeUnit;13public class Pdf {14 public static void main(String[] args) throws IOException {15 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");16 ChromeOptions options = new ChromeOptions();17 Map<String, Object> prefs = new HashMap<String, Object>();18 prefs.put("plugins.always_open_pdf_externally", true);19 prefs.put("download.default_directory", "C:\\Users\\Admin\\Downloads");20 options.setExperimentalOption("prefs", prefs);21 WebDriver driver = new ChromeDriver(options);22 driver.manage().window().maximize();23 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);24 System.out.println("Title of the page is " + driver.getTitle());25 driver.close();26 }27}28Your name to display (optional):29Your name to display (optional):30public class DownloadFile {31 public static void main(String[] args) {32 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");33 ChromeOptions options = new ChromeOptions();34 Map<String, Object> prefs = new HashMap<String, Object>();35 prefs.put("plugins.always_open_pdf_externally", true);36 prefs.put("download.default_directory", "C:\\Users\\Admin\\Downloads");37 options.setExperimentalOption("prefs", prefs);38 WebDriver driver = new ChromeDriver(options);39 driver.manage().window().maximize();

Full Screen

Full Screen

Pdf

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.pdf.Pdf;6import java.io.File;7import java.io.IOException;8import java.nio.file.Files;9import java.nio.file.Path;10import java.nio.file.Paths;11import java.util.List;12public class PDF {13 public static void main(String[] args) throws IOException {14 System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\IdeaProjects\\Selenium\\chromedriver.exe");15 WebDriver driver = new ChromeDriver();16 driver.manage().window().maximize();17 WebElement element = driver.findElement(By.tagName("pdf-viewer"));18 String fileLocation = element.getAttribute("file");19 File file = new File(fileLocation);20 Pdf pdf = new Pdf(file);21 int totalNumberOfPages = pdf.getNumberOfPages();22 System.out.println("Total number of pages in the pdf is " + totalNumberOfPages);23 String textFromPdf = pdf.getText();24 System.out.println("Text from the pdf is " + textFromPdf);25 for (int i = 1; i <= totalNumberOfPages; i++) {26 String textFromPdfPageByPage = pdf.getText(i);27 System.out.println("Text from the pdf page by page is " + textFromPdfPageByPage);28 }29 List<WebElement> allLinks = pdf.getLinks();30 System.out.println("List of all the links present in the pdf " + allLinks);31 List<WebElement> allImages = pdf.getImages();32 System.out.println("List of all the images present in the pdf " + allImages);33 List<WebElement> allForms = pdf.getForms();34 System.out.println("List of all the forms present in the pdf " + allForms);

Full Screen

Full Screen

Pdf

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.firefox.FirefoxDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.By;5import org.openqa.selenium.support.ui.ExpectedConditions;6import org.openqa.selenium.support.ui.WebDriverWait;7import org.openqa.selenium.support.ui.Select;8import org.openqa.selenium.NoSuchElementException;9import org.openqa.selenium.TimeoutException;10import org.openqa.selenium.JavascriptExecutor;11import org.openqa.selenium.StaleElementReferenceException;12import org.openqa.selenium.WebDriverException;13import org.openqa.selenium.Keys;14import org.openqa.selenium.Alert;15import org.openqa.selenium.NoAlertPresentException;16import org.openqa.selenium.UnhandledAlertException;17import org.openqa.selenium.remote.UnreachableBrowserException;18import org.openqa.selenium.remote.RemoteWebDriver;19import org.openqa.selenium.remote.DesiredCapabilities;20import org.openqa.selenium.remote.SessionNotFoundException;21import org.openqa.selenium.support.ui.FluentWait;22import org.openqa.selenium.support.ui.Wait;23import org.openqa.selenium.support.ui.ExpectedConditions;24import org.openqa.selenium.support.ui.WebDriverWait;25import org.openqa.selenium.support.ui.Select;26import org.openqa.selenium.support

Full Screen

Full Screen
copy
1try {23 HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();4 con.setRequestMethod("HEAD");5 con.setConnectTimeout(5000); //set timeout to 5 seconds6 return (con.getResponseCode() == HttpURLConnection.HTTP_OK);78} catch (java.net.SocketTimeoutException e) {9 return false;10} catch (java.io.IOException e) {11 return false;12}13
Full Screen
copy
1 private CloseableHttpClient createHttpClient()2 {3 CloseableHttpClient httpClient;4 CommonHelperFunctions helperFunctions = new CommonHelperFunctions();5 PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();6 cm.setMaxTotal(306);7 cm.setDefaultMaxPerRoute(108);8 RequestConfig requestConfig = RequestConfig.custom()9 .setConnectTimeout(15000)10 .setSocketTimeout(15000).build();11 httpClient = HttpClients.custom()12 .setConnectionManager(cm)13 .setDefaultRequestConfig(requestConfig).build();14 return httpClient;15 }16
Full Screen
copy
1import org.apache.commons.httpclient.HttpClient;2import org.apache.commons.httpclient.methods.EntityEnclosingMethod;3import org.apache.commons.httpclient.methods.PostMethod;4import org.apache.commons.httpclient.methods.multipart.FilePart;5import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;6import org.apache.commons.httpclient.methods.multipart.Part;7import java.io.File;8import java.io.IOException;9import java.util.Arrays;10import java.util.List;11import java.util.concurrent.*;1213/**14 * @author Jeff Kirby15 * @since <pre>Jun 17, 2011</pre>16 */17public class Example {1819 private static final String SITE = "http://some.website.com/upload";20 private static final int TIME_OUT_SECS = 5;2122 // upload a file and return the response as a string23 public String post(File file) throws IOException, InterruptedException {24 final Part[] multiPart = { new FilePart("file", file.getName(), file) };25 final EntityEnclosingMethod post = new PostMethod(SITE);26 post.setRequestEntity(new MultipartRequestEntity(multiPart, post.getParams()));27 final ExecutorService executor = Executors.newSingleThreadExecutor();28 final List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(new KillableHttpClient(post)), TIME_OUT_SECS, TimeUnit.SECONDS);29 executor.shutdown();30 if(futures.get(0).isCancelled()) {31 throw new IOException(SITE + " has timed out. It has taken more than " + TIME_OUT_SECS + " seconds to respond");32 }33 return post.getResponseBodyAsString();34 }3536 private static class KillableHttpClient implements Callable<Integer> {3738 private final EntityEnclosingMethod post;3940 private KillableHttpClient(EntityEnclosingMethod post) {41 this.post = post;42 }4344 public Integer call() throws Exception {45 return new HttpClient().executeMethod(post);46 }47 }48}49
Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in Pdf

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful