How to use CustomAuthenticator method of com.qaprosoft.carina.core.foundation.report.ReportContext class

Best Carina code snippet using com.qaprosoft.carina.core.foundation.report.ReportContext.CustomAuthenticator

Source:ReportContext.java Github

copy

Full Screen

...307 String username = getField(url, 1);308 String password = getField(url, 2);309 310 if (!username.isEmpty() && !password.isEmpty()) {311 Authenticator.setDefault(new CustomAuthenticator(username, password));312 } 313 if (checkArtifactUsingHttp(url, username, password)) {314 try {315 FileUtils.copyURLToFile(new URL(url), file);316 LOGGER.debug("Successfully downloaded artifact: {}", name);317 } catch (IOException e) {318 LOGGER.error("Artifact: " + url + " wasn't downloaded to " + path, e);319 }320 } else {321 Assert.fail("Unable to find artifact: " + name);322 }323 // publish as test artifact to Zebrunner Reporting324 Artifact.attachToTest(name, file); 325 return file;326 }327 /**328 * check if artifact exists using http329 * 330 * @param url String331 * @param username String332 * @param password String333 * @return boolean334 */335 private static boolean checkArtifactUsingHttp(String url, String username, String password) {336 try {337 HttpURLConnection.setFollowRedirects(false);338 // note : you may also need339 // HttpURLConnection.setInstanceFollowRedirects(false)340 HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();341 con.setRequestMethod("HEAD");342 if (!username.isEmpty() && !password.isEmpty()) {343 String usernameColonPassword = username + ":" + password;344 String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());345 con.addRequestProperty("Authorization", basicAuthPayload);346 }347 return (con.getResponseCode() == HttpURLConnection.HTTP_OK);348 } catch (Exception e) {349 LOGGER.debug("Artifact doesn't exist: " + url, e);350 return false;351 }352 }353 /**354 * get username or password from url355 * 356 * @param url String357 * @param position int358 * @return String359 */360 private static String getField(String url, int position) {361 Pattern pattern = Pattern.compile(".*:\\/\\/(.*):(.*)@");362 Matcher matcher = pattern.matcher(url);363 return matcher.find() ? matcher.group(position) : "";364 }365 366 /**367 * Generate file in artifacts location and register in Zebrunner Reporting368 * 369 * @param name String370 * @param source InputStream371 */ 372 public static void saveArtifact(String name, InputStream source) throws IOException {373 File artifact = new File(String.format("%s/%s", getArtifactsFolder(), name));374 artifact.createNewFile();375 FileUtils.writeByteArrayToFile(artifact, IOUtils.toByteArray(source));376 377 Artifact.attachToTest(name, IOUtils.toByteArray(source));378 }379 /**380 * Copy file into artifacts location and register in Zebrunner Reporting381 * @param source File382 */ 383 public static void saveArtifact(File source) throws IOException {384 File artifact = new File(String.format("%s/%s", getArtifactsFolder(), source.getName()));385 artifact.createNewFile();386 FileUtils.copyFile(source, artifact);387 388 Artifact.attachToTest(source.getName(), artifact);389 } 390 /**391 * generate url for artifact by name392 * 393 * @param driver WebDriver394 * @param name String395 * @return String396 */397 private static String getUrl(WebDriver driver, String name) {398 String seleniumHost = Configuration.getSeleniumUrl().replace("wd/hub", "download/");399 WebDriver drv = (driver instanceof EventFiringWebDriver) ? ((EventFiringWebDriver) driver).getWrappedDriver() : driver;400 String sessionId = ((RemoteWebDriver) drv).getSessionId().toString();401 String url = seleniumHost + sessionId + "/" + name;402 LOGGER.debug("url: " + url);403 return url;404 }405 private static void stopThreadLogAppender() {406 try {407 LoggerContext loggerContext = (LoggerContext) LogManager.getContext(true);408 ThreadLogAppender appender = loggerContext.getConfiguration().getAppender("ThreadLogAppender");;409 if (appender != null) {410 appender.stop();411 }412 } catch (Exception e) {413 LOGGER.error("Exception while closing thread log appender.", e);414 }415 }416 private static File renameTestDir(String test) {417 File testDir = testDirectory.get();418 initIsCustomTestDir();419 if (testDir != null && !isCustomTestDirName.get()) {420 File newTestDir = new File(String.format("%s/%s", getBaseDir(), test.replaceAll("[^a-zA-Z0-9.-]", "_")));421 if (!newTestDir.exists()) {422 boolean isRenamed = false;423 int retry = 5;424 while (!isRenamed && retry > 0) {425 // close ThreadLogAppender resources before renaming426 stopThreadLogAppender();427 isRenamed = testDir.renameTo(newTestDir);428 if (!isRenamed) {429 CommonUtils.pause(1);430 System.err.println("renaming failed to '" + newTestDir + "'");431 }432 retry--;433 }434 435 if (isRenamed) {436 testDirectory.set(newTestDir);437 System.out.println("Test directory renamed to '" + newTestDir + "'");438 }439 }440 } else {441 LOGGER.error("Unexpected case with absence of test.log for '" + test + "'");442 }443 return testDir;444 }445 private static void initIsCustomTestDir() {446 if (isCustomTestDirName.get() == null) {447 isCustomTestDirName.set(Boolean.FALSE);448 }449 ;450 }451 /**452 * Removes emailable html report and oldest screenshots directories according to history size defined in config.453 */454 private static void removeOldReports() {455 File baseDir = new File(String.format("%s/%s", System.getProperty("user.dir"),456 Configuration.get(Parameter.PROJECT_REPORT_DIRECTORY)));457 if (baseDir.exists()) {458 // remove old emailable report459 File reportFile = new File(String.format("%s/%s/%s", System.getProperty("user.dir"),460 Configuration.get(Parameter.PROJECT_REPORT_DIRECTORY), SpecialKeywords.HTML_REPORT));461 if (reportFile.exists()) {462 reportFile.delete();463 }464 List<File> files = FileManager.getFilesInDir(baseDir);465 List<File> screenshotFolders = new ArrayList<File>();466 for (File file : files) {467 if (file.isDirectory() && !file.getName().startsWith(".")) {468 screenshotFolders.add(file);469 }470 }471 int maxHistory = Configuration.getInt(Parameter.MAX_SCREENSHOOT_HISTORY);472 if (maxHistory > 0 && screenshotFolders.size() + 1 > maxHistory) {473 Comparator<File> comp = new Comparator<File>() {474 @Override475 public int compare(File file1, File file2) {476 return file2.getName().compareTo(file1.getName());477 }478 };479 Collections.sort(screenshotFolders, comp);480 for (int i = maxHistory - 1; i < screenshotFolders.size(); i++) {481 if (screenshotFolders.get(i).getName().equals("gallery-lib")) {482 continue;483 }484 try {485 FileUtils.deleteDirectory(screenshotFolders.get(i));486 } catch (IOException e) {487 System.out.println((e + "\n" + e.getMessage()));488 }489 }490 }491 }492 }493 public static void generateHtmlReport(String content) {494 String emailableReport = SpecialKeywords.HTML_REPORT;495 File reportFile = new File(String.format("%s/%s/%s", System.getProperty("user.dir"),496 Configuration.get(Parameter.PROJECT_REPORT_DIRECTORY), emailableReport));497 File reportFileToBaseDir = new File(String.format("%s/%s", getBaseDir(), emailableReport));498 try (FileWriter reportFileWriter = new FileWriter(reportFile.getAbsoluteFile());499 BufferedWriter reportBufferedWriter = new BufferedWriter(reportFileWriter);500 FileWriter baseDirFileWriter = new FileWriter(reportFileToBaseDir.getAbsolutePath());501 BufferedWriter baseDirBufferedWriter = new BufferedWriter(baseDirFileWriter)) {502 createNewFileIfNotExists(reportFile);503 reportBufferedWriter.write(content);504 createNewFileIfNotExists(reportFileToBaseDir);505 baseDirBufferedWriter.write(content);506 } catch (IOException e) {507 LOGGER.error("generateHtmlReport failure", e);508 }509 }510 private static void createNewFileIfNotExists(File file) throws IOException {511 if (!file.exists()) {512 boolean isCreated = file.createNewFile();513 if (!isCreated) {514 throw new RuntimeException("File not created: " + file.getAbsolutePath());515 }516 }517 }518 /**519 * Returns URL for test artifacts folder.520 * 521 * @return - URL for test screenshot folder.522 */523 public static String getTestArtifactsLink() {524 String link = "";525 if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) {526 link = String.format("%s/%d/artifacts", Configuration.get(Parameter.REPORT_URL), rootID);527 } else {528 link = String.format("file://%s/artifacts", getBaseDirAbsolutePath());529 }530 return link;531 }532 /**533 * Returns URL for test screenshot folder.534 * 535 * @return - URL for test screenshot folder.536 */537 public static String getTestScreenshotsLink() {538 String link = "";539 try {540 if (FileUtils.listFiles(ReportContext.getTestDir(), new String[] { "png" }, false).isEmpty()) {541 // no png screenshot files at all542 return link;543 }544 } catch (Exception e) {545 LOGGER.error("Exception during report directory scanning", e);546 }547 548 String test = testDirectory.get().getName().replaceAll("[^a-zA-Z0-9.-]", "_");549 550 if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) {551 link = String.format("%s/%d/%s/report.html", Configuration.get(Parameter.REPORT_URL), rootID, test);552 } else {553 link = String.format("file://%s/%s/report.html", getBaseDirAbsolutePath(), test);554 }555 return link;556 }557 /**558 * Returns URL for test log.559 * @return - URL to test log folder.560 */561 public static String getTestLogLink() {562 String link = "";563 File testLogFile = new File(ReportContext.getTestDir() + "/" + "test.log");564 if (!testLogFile.exists()) {565 // no test.log file at all566 return link;567 }568 String test = testDirectory.get().getName().replaceAll("[^a-zA-Z0-9.-]", "_");569 if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) {570 link = String.format("%s/%d/%s/test.log", Configuration.get(Parameter.REPORT_URL), rootID, test);571 } else {572 link = String.format("file://%s/%s/test.log", getBaseDirAbsolutePath(), test);573 }574 return link;575 }576 /**577 * Returns URL for cucumber report.578 * 579 * @return - URL to test log folder.580 */581 public static String getCucumberReportLink() {582 String folder = SpecialKeywords.CUCUMBER_REPORT_FOLDER;583 String subFolder = SpecialKeywords.CUCUMBER_REPORT_SUBFOLDER;584 String fileName = SpecialKeywords.CUCUMBER_REPORT_FILE_NAME;585 String link = "";586 if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) {587 // remove report url and make link relative588 // link = String.format("./%d/report.html", rootID);589 String report_url = Configuration.get(Parameter.REPORT_URL);590 if (report_url.contains("n/a")) {591 LOGGER.error("Contains n/a. Replace it.");592 report_url = report_url.replace("n/a", "");593 }594 link = String.format("%s/%d/%s/%s/%s", report_url, rootID, folder, subFolder, fileName);595 } else {596 link = String.format("file://%s/%s/%s/%s", getBaseDirAbsolutePath(), folder, subFolder, fileName);597 }598 return link;599 }600 /**601 * Saves screenshot.602 * 603 * @param screenshot - {@link BufferedImage} file to save604 * 605 * @return - screenshot name.606 */607 public static String saveScreenshot(BufferedImage screenshot) {608 long now = System.currentTimeMillis();609 executor.execute(new ImageSaverTask(screenshot, String.format("%s/%d.png", getTestDir().getAbsolutePath(), now),610 Configuration.getInt(Parameter.BIG_SCREEN_WIDTH), Configuration.getInt(Parameter.BIG_SCREEN_HEIGHT)));611 return String.format("%d.png", now);612 }613 /**614 * Asynchronous image saver task.615 */616 private static class ImageSaverTask implements Runnable {617 private BufferedImage image;618 private String path;619 private Integer width;620 private Integer height;621 public ImageSaverTask(BufferedImage image, String path, Integer width, Integer height) {622 this.image = image;623 this.path = path;624 this.width = width;625 this.height = height;626 }627 @Override628 public void run() {629 try {630 if (width > 0 && height > 0) {631 BufferedImage resizedImage = Scalr.resize(image, Scalr.Method.BALANCED, Scalr.Mode.FIT_TO_WIDTH, width, height,632 Scalr.OP_ANTIALIAS);633 if (resizedImage.getHeight() > height) {634 resizedImage = Scalr.crop(resizedImage, resizedImage.getWidth(), height);635 }636 ImageIO.write(resizedImage, "PNG", new File(path));637 } else {638 ImageIO.write(image, "PNG", new File(path));639 }640 } catch (Exception e) {641 LOGGER.error("Unable to save screenshot: " + e.getMessage());642 }643 }644 }645 private static void copyGalleryLib() {646 File reportsRootDir = new File(System.getProperty("user.dir") + "/" + Configuration.get(Parameter.PROJECT_REPORT_DIRECTORY));647 if (!new File(reportsRootDir.getAbsolutePath() + "/gallery-lib").exists()) {648 try {649 InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(GALLERY_ZIP);650 if (is == null) {651 System.out.println("Unable to find in classpath: " + GALLERY_ZIP);652 return;653 }654 ZipManager.copyInputStream(is, new BufferedOutputStream(new FileOutputStream(reportsRootDir.getAbsolutePath() + "/"655 + GALLERY_ZIP)));656 ZipManager.unzip(reportsRootDir.getAbsolutePath() + "/" + GALLERY_ZIP, reportsRootDir.getAbsolutePath());657 File zip = new File(reportsRootDir.getAbsolutePath() + "/" + GALLERY_ZIP);658 zip.delete();659 } catch (Exception e) {660 System.out.println("Unable to copyGalleryLib! " + e);661 }662 }663 }664 public static void generateTestReport() {665 File testDir = testDirectory.get();666 try {667 List<File> images = FileManager.getFilesInDir(testDir);668 List<String> imgNames = new ArrayList<String>();669 for (File image : images) {670 imgNames.add(image.getName());671 }672 imgNames.remove("test.log");673 imgNames.remove("sql.log");674 if (imgNames.size() == 0)675 return;676 Collections.sort(imgNames);677 StringBuilder report = new StringBuilder();678 for (int i = 0; i < imgNames.size(); i++) {679 // convert toString680 String image = R.REPORT.get("image");681 image = image.replace("${image}", imgNames.get(i));682 String title = getScreenshotComment(imgNames.get(i));683 if (title == null) {684 title = "";685 }686 image = image.replace("${title}", StringUtils.substring(title, 0, MAX_IMAGE_TITLE));687 report.append(image);688 }689 // String wholeReport = R.REPORT.get("container").replace("${images}", report.toString());690 String wholeReport = R.REPORT.get("container").replace("${images}", report.toString());691 wholeReport = wholeReport.replace("${title}", TITLE);692 String folder = testDir.getAbsolutePath();693 FileManager.createFileWithContent(folder + REPORT_NAME, wholeReport);694 } catch (Exception e) {695 LOGGER.error("generateTestReport failure", e);696 }697 }698 /**699 * Stores comment for screenshot.700 *701 * @param screenId screenId id702 * @param msg message703 * 704 */705 public static void addScreenshotComment(String screenId, String msg) {706 if (!StringUtils.isEmpty(screenId)) {707 screenSteps.put(screenId, msg);708 }709 }710 /**711 * Return comment for screenshot.712 * 713 * @param screenId Screen Id714 * 715 * @return screenshot comment716 */717 public static String getScreenshotComment(String screenId) {718 String comment = "";719 if (screenSteps.containsKey(screenId))720 comment = screenSteps.get(screenId);721 return comment;722 }723 private static String getBaseDirAbsolutePath() {724 if (baseDirectory != null) {725 return baseDirectory.getAbsolutePath();726 }727 return null;728 }729 730 // Converting InputStream to String731 private static String readStream(InputStream in) {732 BufferedReader reader = null;733 StringBuffer response = new StringBuffer();734 try {735 reader = new BufferedReader(new InputStreamReader(in));736 String line = "";737 while ((line = reader.readLine()) != null) {738 response.append(line);739 }740 } catch (IOException e) {741 // do noting742 } finally {743 if (reader != null) {744 try {745 reader.close();746 } catch (IOException e) {747 // do nothing748 }749 }750 }751 return response.toString();752 }753 754 public static class CustomAuthenticator extends Authenticator {755 String username;756 String password;757 public CustomAuthenticator(String username, String password) {758 this.username = username;759 this.password = password;760 }761 protected PasswordAuthentication getPasswordAuthentication() {762 return new PasswordAuthentication(username, password.toCharArray());763 }764 } 765}...

Full Screen

Full Screen

CustomAuthenticator

Using AI Code Generation

copy

Full Screen

1CustomAuthenticator authenticator = new CustomAuthenticator();2authenticator.setCredentials();3authenticator.setCredentials();4authenticator.setCredentials();5authenticator.setCredentials();6authenticator.setCredentials();7authenticator.setCredentials();8authenticator.setCredentials();9authenticator.setCredentials();10authenticator.setCredentials();11authenticator.setCredentials();

Full Screen

Full Screen

CustomAuthenticator

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.report.ReportContext;2import com.qaprosoft.carina.core.foundation.report.ReportContext.CustomAuthenticator;3public class CustomAuthenticatorExample {4 public static void main(String[] args) {5 ReportContext.setCustomAuthenticator(new CustomAuthenticator() {6 public String getAuthenticator() {7 return "customAuthenticator";8 }9 public String getAuthenticatorValue() {10 return "customAuthenticatorValue";11 }12 });13 ReportContext.unsetCustomAuthenticator();14 }15}16import com.qaprosoft.carina.core.foundation.report.ReportContext;17import com.qaprosoft.carina.core.foundation.report.ReportContext.CustomAuthenticator;18public class CustomAuthenticatorExample {19 public static void main(String[] args) {20 ReportContext.setCustomAuthenticator(new CustomAuthenticator() {21 public String getAuthenticator() {22 return "customAuthenticator";23 }24 public String getAuthenticatorValue() {25 return "customAuthenticatorValue";26 }27 });28 ReportContext.unsetCustomAuthenticator();29 }30}31import com.qaprosoft.carina.core.foundation.report.ReportContext;32import com.qaprosoft.carina.core.foundation.report.ReportContext.CustomAuthenticator;33public class CustomAuthenticatorExample {34 public static void main(String[] args) {35 ReportContext.setCustomAuthenticator(new CustomAuthenticator() {36 public String getAuthenticator() {37 return "customAuthenticator";38 }39 public String getAuthenticatorValue() {40 return "customAuthenticatorValue";41 }42 });43 ReportContext.unsetCustomAuthenticator();44 }45}46import com.qaprosoft.carina.core.foundation.report.ReportContext;47import com.qaprosoft.carina.core.foundation.report.ReportContext.CustomAuth

Full Screen

Full Screen

CustomAuthenticator

Using AI Code Generation

copy

Full Screen

1List<String> credentials = ReportContext.getCustomAuthenticator().getCredentials();2for (String credential : credentials) {3 ReportContext.getCustomAuthenticator().addCredential(credential);4}5List<String> credentials = ReportContext.getCustomAuthenticator().getCredentials();6for (String credential : credentials) {7 ReportContext.getCustomAuthenticator().addCredential(credential);8}9List<String> credentials = ReportContext.getCustomAuthenticator().getCredentials();10for (String credential : credentials) {11 ReportContext.getCustomAuthenticator().addCredential(credential);12}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful