0% found this document useful (0 votes)
5 views

otonamcode

The document outlines a Java Spring Boot application called Otonom, which uses Selenium for web automation and processes Excel files for configuration. It includes various components such as OtonomHandler for handling file processing, BrandingService for managing branding specifications, and HttpService for making HTTP calls. The application is designed to execute automated tasks based on configurations specified in Excel files and log the process using Log4j.

Uploaded by

Anish Singh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

otonamcode

The document outlines a Java Spring Boot application called Otonom, which uses Selenium for web automation and processes Excel files for configuration. It includes various components such as OtonomHandler for handling file processing, BrandingService for managing branding specifications, and HttpService for making HTTP calls. The application is designed to execute automated tasks based on configurations specified in Excel files and log the process using Log4j.

Uploaded by

Anish Singh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 54

Start of Program:

package com.intellect.digipay.otonom;

import java.io.FileNotFoundException;

import javax.annotation.PostConstruct;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.intellect.digipay.otonom.handler.OtonomHandler;
import com.itextpdf.text.DocumentException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import io.github.bonigarcia.wdm.WebDriverManager;

@SpringBootApplication
@EnableAutoConfiguration

public class OtonomApplication {

static Logger logger = LogManager.getLogger(OtonomApplication.class);


@Autowired
OtonomHandler handle;

public static void main(String[] args) {


SpringApplication.run(OtonomApplication.class, args);

WebDriverManager.chromedriver().setup(); // Set up ChromeDriver


WebDriverManager.firefoxdriver().setup(); // Set up GeckoDriver

// String browser = "chrome";


String browser = "firefox";

WebDriver driver;
if ("firefox".equalsIgnoreCase(browser)) {
driver = new FirefoxDriver();
logger.trace("Firefox Driver Run Successfully ");
} else {
driver = new ChromeDriver();
logger.trace("Chrome Driver Run Successfully ");
}

logger.trace("this is trace message");


logger.info("this is info message");
logger.error("this is error message");
logger.warn("this is warning message");
logger.fatal("this is fatal message");
}

/*@PostConstruct
public void process() throws FileNotFoundException, DocumentException {
String inputFile = "Otonom_Config_Sanity_FTB_Cash_Position00";
ExecutorService executor = Executors.newFixedThreadPool(1);

for (int i = 1; i <= 3; i++) {


String fileName = inputFile + i + ".xlsx";
executor.submit(() -> {
try {
handle.process(fileName);
} catch (Exception e) {
logger.error("Error processing file: " + fileName,
e);
}
});
}

}
*/

@PostConstruct void process() throws FileNotFoundException,


DocumentException { //String
// inputFile="Otonom_Config_Sanity_FTB_I2I_Sweep_Tran_10St_QHDCT00";

//String inputFile="Otonom_Config_Sanity_FTB_I2I_Sweep_Tran_10St_AWS00";
String inputFile="Otonom_Config_Sanity_FTB_Cash_Position00";

for(int i=2; i<=3; i++){ handle.process(inputFile+i+".xlsx");

System.exit(1);

otonam handleer:

package com.intellect.digipay.otonom.handler;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Properties;

import org.springframework.aop.target.SimpleBeanTargetSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import com.intellect.digipay.otonom.service.LoadConfigService;
import com.intellect.digipay.otonom.service.OtonomService;
import com.intellect.digipay.otonom.service.ResultService;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.log.SysoCounter;

import Utilities.PropertyUtils;

@Component
public class OtonomHandler {
@Autowired
LoadConfigService config;
@Autowired
ResultService rs;

@Autowired
Environment environment;

@SuppressWarnings("rawtypes")

public void process(String inputfile) throws FileNotFoundException,


DocumentException {

String fileName;
String filePath;
String browser;
String driverPath;
try {

//driverPath = environment.getProperty("chrome_driver_path");
//filePath = environment.getProperty("otonom_home");
//filePath = (System.getProperty("user.dir")+"\\");
// filePath = "D:\\Otonom_New\\Otonom\\DEV_AUTOMATON_FILE\\";
//filePath = "D:\\Otonom_New\\Otonom\\SIT_Atomation_File\\";
// filePath = "D:\\Automation\\Daily_Sanity_DEV_SIT_UAT\\";
filePath = "D:\\Automation\\Otonom_new\\SANITY\\";
//filePath ="D:\\Otonom_New\\Otonom\\SCRIPT_WRITE\\";

// filePath="D:\\Otonom_New\\Otonom\\TEST_DATA\\";

//filePath = "D:\\Otonom_New\\Otonom\\SANITY\\";
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println("Enter Config sheet");
// fileName = myObj.nextLine(); // Read user input
fileName = inputfile;
System.out.println("fileName is: " + fileName); // Output user
input

// fileName = environment.getProperty("config_file_name");
browser = environment.getProperty("browser");

// browser = (System.getProperty("user.dir")+"\\Driver\\
chromedriver.exe");
driverPath = System.getProperty("user.dir") + "\\Driver\\
chromedriver.exe";
//driverPath = System.getProperty("user.dir") + "\\Driver\\
geckodriver.exe";

//change 26sep
System.setProperty("webdriver.chrome.driver", driverPath);
//System.setProperty("webdriver.gecko.driver", driverPath);

//System.out.println("driverPath::>>> " + driverPath + " filePath " + filePath


+ " fileName " + fileName+" browser " + browser);
} catch (Exception e) {
filePath = "D:\\Otonom_2.0\\Otonom";
fileName = "Otonom_sanity_sheet.xlsx";
browser = "chrome";
}

HashMap excelData = loadConfig(filePath, fileName);


HashMap resultMap = execute(excelData, filePath, browser);
writeResult(resultMap, filePath, fileName);
}

@SuppressWarnings("rawtypes")

private HashMap loadConfig(String filePath, String fileName) {


HashMap excelData = new HashMap();
// LoadConfigService config = new LoadConfigService();
try {
excelData = config.getExcelData(filePath, fileName);
} catch (IOException e) {
e.printStackTrace();
}
return excelData;
}

@SuppressWarnings("rawtypes")
private HashMap execute(HashMap mapConfig, String filePath, String browser)
throws FileNotFoundException, DocumentException {
HashMap resultMap;
OtonomService os = new OtonomService(mapConfig, filePath, browser);
resultMap = os.executeStories();
return resultMap;
}

@SuppressWarnings("rawtypes")
private void writeResult(HashMap resultMap, String filePath, String fileName)
{
// ResultService rs = new ResultService();
rs.writeResult(resultMap, filePath, fileName);
}
}

branding service:
package com.intellect.digipay.otonom.service;

import java.util.ArrayList;
import java.util.HashMap;
public class BrandingService {

private ArrayList<String> brandingHeader;


private ArrayList<ArrayList<String>> brandingList;
private ArrayList<String> brandingKeys;
private HashMap<String, String> definedBranding;
private String bv;

public BrandingService(ArrayList<ArrayList<String>> brandingList) {


this.brandingList = brandingList;
this.brandingKeys = new ArrayList<String>();

brandingHeader = (ArrayList<String>) brandingList.get(0);


for (int j = 0; j < brandingHeader.size(); j++) {
brandingKeys.add(((String) brandingHeader.get(j)).trim());
}
}

public HashMap<String, String> getBrandingSpecs(String brandingRef, String


brandingType) {
ArrayList<String> brandingWorkList;
definedBranding = new HashMap<String, String>();
for (int i = 1; i < brandingList.size(); i++) {
brandingWorkList = brandingList.get(i);
if
(brandingRef.equalsIgnoreCase((brandingWorkList.get(0)).trim()) && brandingType
.equalsIgnoreCase("check_branding_" +
(brandingWorkList.get(1)).trim().toLowerCase())) {
for (int j = 2; j < brandingWorkList.size(); j++) {
bv = (brandingWorkList.get(j)).trim();
if (bv.length() > 0)
definedBranding.put(brandingKeys.get(j), bv);
}
break;
}
}
return definedBranding;
}

httpsservice:
package com.intellect.digipay.otonom.service;

import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import com.jayway.jsonpath.JsonPath;

public class HttpService {

RestTemplate restTemplate = new RestTemplate();


private ArrayList<ArrayList<String>> httpList;

public HttpService(ArrayList<ArrayList<String>> httpList) {


this.httpList = httpList;
}

public int makeHttpCall(String callingApiCode) throws URISyntaxException {


System.out.println("-----------------------------------");
ArrayList<String> httpWorkList;
ArrayList<String> parametersList = null;
ArrayList<String> headersList = null;
URI uri;
String httpUrl = null;
String httpMethod = " ";
String httpHeaders = null;
String httpBody = " ";
int responseStatus = 0;
ResponseEntity<String> response = null;
HttpHeaders headers;
String apiCode;
String responseJsonPath = null;
String responseJsonPathValue = null;
String parameters = null;
String holder;

int semicolonPosition = callingApiCode.indexOf(";");


int semicolonPositionSecond = 0;
if (semicolonPosition < 1) {
apiCode = callingApiCode;
} else {
semicolonPositionSecond = callingApiCode.indexOf(";",
semicolonPosition + 1);
System.out.println("semicolonPositionSecond:" +
semicolonPositionSecond);
apiCode = callingApiCode.substring(0, semicolonPosition);
if (semicolonPositionSecond < 1) {
parameters = callingApiCode.substring(semicolonPosition +
1);
} else {
parameters = callingApiCode.substring(semicolonPosition +
1, semicolonPositionSecond);
responseJsonPath =
callingApiCode.substring(semicolonPositionSecond + 1).trim();
System.out.println("responseJsonPath:" + responseJsonPath);
}
parametersList = new
ArrayList<>(Arrays.asList(parameters.split(",")));
}

for (int i = 1; i < httpList.size(); i++) {


httpWorkList = httpList.get(i);
if (apiCode.equalsIgnoreCase((httpWorkList.get(0)).trim())) {
httpUrl = (httpWorkList.get(1)).trim();
httpMethod = (httpWorkList.get(2)).trim();
httpHeaders = (httpWorkList.get(3)).trim();
httpBody = (httpWorkList.get(4)).trim();
break;
}
}

if (parametersList != null) {
for (int i = 0; i < parametersList.size(); i++) {
httpBody = httpBody.replaceAll("##PARAM" + i + "##",
parametersList.get(i).trim());
}
}
httpBody = replaceKeywords(httpBody);

uri = new URI(httpUrl);


headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headersList = new ArrayList<>(Arrays.asList(httpHeaders.split(",")));
for (int i = 0; i < headersList.size(); i++) {
if (!"Content-Type"
.equalsIgnoreCase(headersList.get(i).substring(0,
headersList.get(i).indexOf(":")).trim())) {
holder = headersList.get(i);
holder = replaceKeywords(holder);
if (parametersList != null) {
for (int i1 = 0; i1 < parametersList.size(); i1++) {
holder = holder.replaceAll("##PARAM" + i1 +
"##", parametersList.get(i1).trim());
}
}
headers.add(holder.substring(0,
holder.indexOf(":")).trim(),
holder.substring(holder.indexOf(":") +
1).trim());

}
}

try {
HttpEntity<String> request = new HttpEntity<>(httpBody, headers);
System.out.println("apiCode: " + apiCode + " : request: " +
request);

if ("POST".equalsIgnoreCase(httpMethod.trim()))
response = restTemplate.exchange(uri, HttpMethod.POST,
request, String.class);
if ("GET".equalsIgnoreCase(httpMethod.trim()))
response = restTemplate.exchange(uri, HttpMethod.GET,
request, String.class);

if (null != response) {
responseStatus = response.getStatusCodeValue();
if (null != responseJsonPath &&
responseJsonPath.trim().length() > 0) {
try {
responseJsonPathValue =
JsonPath.read(response.getBody(), responseJsonPath).toString();
} catch (Exception e) {
responseJsonPathValue = "";
}
System.out.println("--> responseJsonPathValue:" +
responseJsonPathValue);
}
}
} catch (HttpClientErrorException httperr) {
responseStatus = httperr.getRawStatusCode();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("responseStatus:" + responseStatus);

System.out.println("-------------------------------------------------------------")
;
return responseStatus;
}

private String replaceKeywords(String inputString) {


String replacedString = inputString;

replacedString = replacedString.replaceAll("##TODAY_YYYYMMDD##",

LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
replacedString = replacedString.replaceAll("##TODAY_YYYY-MM-DD##",
LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-
MM-dd")));
replacedString = replacedString.replaceAll("##TODAY_DD-MMM-YYYY##",
LocalDate.now().format(DateTimeFormatter.ofPattern("dd-MMM-
yyyy")));
replacedString = replacedString.replaceAll("##TODAY_DD/MM/YYYY##",

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
replacedString = replacedString.replaceAll("##TODAY_DATE_TIME##",
LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd
HH:mm:ss.SSS").withZone(ZoneId.systemDefault())));

replacedString = replacedString.replaceAll("##YESTERDAY_YYYYMMDD##",

LocalDate.now().minus(Period.ofDays(1)).format(DateTimeFormatter.ofPattern("yyyyMMd
d")));
replacedString = replacedString.replaceAll("##YESTERDAY_YYYY-MM-DD##",
LocalDate.now().minus(Period.ofDays(1)).format(DateTimeFormatter.ofPattern("yyyy-
MM-dd")));
replacedString = replacedString.replaceAll("##YESTERDAY_DD-MMM-YYYY##",

LocalDate.now().minus(Period.ofDays(1)).format(DateTimeFormatter.ofPattern("dd-MMM-
yyyy")));
replacedString = replacedString.replaceAll("##YESTERDAY_DD/MM/YYYY##",

LocalDate.now().minus(Period.ofDays(1)).format(DateTimeFormatter.ofPattern("dd/MM/
yyyy")));
replacedString = replacedString.replaceAll("##YESTERDAY_DATE_TIME##",
LocalDateTime.now().minus(Period.ofDays(1)).format(
DateTimeFormatter.ofPattern("yyyy-MM-dd
HH:mm:ss.SSS").withZone(ZoneId.systemDefault())));

replacedString = replacedString.replaceAll("##UID##", getUID());

return replacedString;
}

public String getUID() {


Random rnd = new Random();
int number = rnd.nextInt(999999);

return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd-
HHmmss-SSS"))
+ String.format("%06d", number);
}
}

load config:
package com.intellect.digipay.otonom.service;

import org.dhatim.fastexcel.reader.ReadableWorkbook;
import org.dhatim.fastexcel.reader.Row;
import org.dhatim.fastexcel.reader.Sheet;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Optional;
import java.util.stream.Stream;

@Component
public class LoadConfigService {

@SuppressWarnings({ "rawtypes", "unchecked" })


public HashMap getExcelData(String filePath, String fileName) throws
IOException {

File f = new File(filePath + fileName);


HashMap mapExcelData = new HashMap();
ArrayList dynamicSheet;
ArrayList scopeSheet;
ArrayList storySheet;
ArrayList sketchSheet;
ArrayList routineSheet;
ArrayList brandingSheet;
ArrayList guideSheet;
ArrayList readmeSheet;

try (ReadableWorkbook wb = new ReadableWorkbook(f)) {

dynamicSheet = getSingleSheetData(0, wb);


mapExcelData.put("Dynamic", dynamicSheet);
// printSingleSheetData(dynamicSheet);

scopeSheet = getSingleSheetData(1, wb);


mapExcelData.put("Scope", scopeSheet);
// printSingleSheetData(scopeSheet);

storySheet = getSingleSheetData(2, wb);


mapExcelData.put("Story", storySheet);
// printSingleSheetData(storySheet);

sketchSheet = getSingleSheetData(3, wb);


mapExcelData.put("Sketch", sketchSheet);
// printSingleSheetData(sketchSheet);

routineSheet = getSingleSheetData(4, wb);


mapExcelData.put("Routine", routineSheet);
// printSingleSheetData(routineSheet);

brandingSheet = getSingleSheetData(5, wb);


mapExcelData.put("Branding", brandingSheet);
// printSingleSheetData(brandingSheet);

guideSheet = getSingleSheetData(6, wb);


mapExcelData.put("Guide", guideSheet);
// printSingleSheetData(guideSheet);

readmeSheet = getSingleSheetData(7, wb);


mapExcelData.put("Readme", readmeSheet);
// printSingleSheetData(readmeSheet);

guideSheet = getSingleSheetData(8, wb);


mapExcelData.put("Database", guideSheet);
// printSingleSheetData(guideSheet);

readmeSheet = getSingleSheetData(9, wb);


mapExcelData.put("Http", readmeSheet);
// printSingleSheetData(readmeSheet);
}
return mapExcelData;
}

@SuppressWarnings({ "unchecked", "rawtypes" })


public ArrayList getSingleSheetData(int sheetIndex, ReadableWorkbook wb) {
Sheet sheet = null;
Row row = null;
ArrayList listKeys = new ArrayList();
ArrayList listValues = new ArrayList();
ArrayList dataRows = new ArrayList();

try {
Optional<Sheet> optSheet = wb.getSheet(sheetIndex);
if (optSheet.isPresent()) {
sheet = optSheet.get();
}

try (Stream<Row> rows = sheet.openStream()) {


Iterator<Row> it = rows.iterator();
int i = 0;
while (it.hasNext()) {
listValues.clear();
row = it.next();
if (i == -10) { // temporarily making it -10... need
to revisit this
row.stream().forEach(cell -> {
listKeys.add(cell.getText());
});
} else { // data rows.. not any more.. this holds
header row also
if (row.getCell(0).getText().length() > 0) {
row.stream().forEach(cell ->
listValues.add(cell.getText()));
dataRows.add(listValues.clone());
}
}
i++;
}
} catch (NullPointerException en) {
ArrayList tempList = new ArrayList();
tempList.add("1"); // revisit this
dataRows.add(tempList.clone());
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return dataRows;
}

/*@SuppressWarnings("rawtypes")
public void printSingleSheetData(ArrayList sheetData) {
System.out.println(" ** ----------------");
ArrayList li2;
for (int i = 0; i < sheetData.size(); i++) {
System.out.print(" Row " + i + " ----------------");
li2 = (ArrayList) sheetData.get(i);
for (int p = 0; p < li2.size(); p++) {
System.out.print(p + " - " + li2.get(p) + " ::: ");
}
System.out.println(" ");
}
}*/
}
otonam service:
package com.intellect.digipay.otonom.service;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.env.RandomValuePropertySource;

import com.intellect.digipay.otonom.util.ItextpdfhealperUtil;
import com.itextpdf.text.DocumentException;

import Utilities.PropertyUtils;

public class OtonomService {

Logger logger = LogManager.getLogger(OtonomService.class);


SelenideService selenideService;
private HashMap<String, String> taskMap;
private String labelScope;
private String brandingScope;

@SuppressWarnings("rawtypes")
private HashMap inputConfigMap;
@SuppressWarnings("rawtypes")
private HashMap resultMap;

public ArrayList<ArrayList<String>> dynamicValuesList;


public ArrayList<ArrayList<String>> storyResultList = new
ArrayList<ArrayList<String>>();
public ArrayList<ArrayList<String>> sketchResultList = new
ArrayList<ArrayList<String>>();
public ArrayList<ArrayList<String>> routineResultList = new
ArrayList<ArrayList<String>>();

@SuppressWarnings({ "rawtypes", "unchecked" })


public OtonomService(HashMap configMap, String filePath, String browser) {
ArrayList brandingList = (ArrayList) configMap.get("Branding");
ArrayList httpList = (ArrayList) configMap.get("Http");
ArrayList databaseList = (ArrayList) configMap.get("Database");

this.inputConfigMap = configMap;
this.taskMap = new HashMap();
this.selenideService = new SelenideService(brandingList, httpList,
databaseList, filePath, browser);

ArrayList headerRow = new ArrayList();


ArrayList innerResultList;
dynamicValuesList = (ArrayList) configMap.get("Dynamic");

ArrayList scopeList = (ArrayList) configMap.get("Scope");


innerResultList = (ArrayList) scopeList.get(1); // Row-2 of Excel

ArrayList storyList = (ArrayList) configMap.get("Story");


headerRow = (ArrayList) storyList.get(0);
headerRow.add("Result_Functionality");
storyResultList.add(headerRow); // Story Header Row

ArrayList sketchList = (ArrayList) configMap.get("Sketch");


headerRow = (ArrayList) sketchList.get(0);
headerRow.add("Result_Functionality");
sketchResultList.add(headerRow); // Sketch Header Row

ArrayList routineList = (ArrayList) configMap.get("Routine");


headerRow = (ArrayList) routineList.get(0);
headerRow.add("Result_Task");
headerRow.add("Result_Expected");
headerRow.add("Result_Actual");
headerRow.add("Sketch");
headerRow.add("Routine");
headerRow.add("Flavour");
headerRow.add("Audit_Timestamp");
routineResultList.add(headerRow); // Routine Header Row

if ("Labels".equals(innerResultList.get(0))) {
this.labelScope = (String) innerResultList.get(1);
} else {
this.labelScope = "Y";
}

innerResultList = (ArrayList) scopeList.get(2); // Row-3 of Excel


if ("Branding".equals(innerResultList.get(0))) {
this.brandingScope = (String) innerResultList.get(1);
} else {
this.brandingScope = "Y";
}
}

@SuppressWarnings({ "unchecked", "rawtypes" })


public HashMap executeStories() throws FileNotFoundException,
DocumentException {

String sketchResult;
ArrayList storyWorkList = new ArrayList();
ArrayList storyData = (ArrayList) inputConfigMap.get("Story");
ArrayList localStoryResultList = null;

for (int i = 0; i < storyData.size(); i++) {


storyWorkList = (ArrayList) storyData.get(i);
localStoryResultList = (ArrayList) storyWorkList.clone();

if ("Y".equalsIgnoreCase(((String) storyWorkList.get(2)).trim())
|| "YES".equalsIgnoreCase(((String)
storyWorkList.get(2)).trim())) {

sketchResult = executeSketch(((String)
storyWorkList.get(1)).trim()); // sketch
if (!"Pass".equalsIgnoreCase(sketchResult))
storyWorkList.add("Fail");
localStoryResultList.add(sketchResult);
storyResultList.add(localStoryResultList);
}
}
resultMap = inputConfigMap;
resultMap.put("Story", storyResultList);
resultMap.put("Sketch", sketchResultList);
resultMap.put("Routine", routineResultList);
return resultMap;
}

@SuppressWarnings({ "rawtypes", "unchecked" })


private String executeSketch(String sketch) throws FileNotFoundException,
DocumentException {

String routineResult = null;


String sketchAllClear = "Pass";

ArrayList<String> sketchWorkList;
ArrayList sketchData = (ArrayList) inputConfigMap.get("Sketch");
ArrayList<String> localSketchResultList = null;

System.out.println(" ");
System.out.println("===> Executing Sketch (" + sketch + ")");
logger.info("inside OtonomService");
System.out.println(" ");
for (int i = 1; i < sketchData.size(); i++) {
sketchWorkList = (ArrayList) sketchData.get(i);
localSketchResultList = (ArrayList) sketchWorkList.clone();

if (sketch.contains(((String) sketchWorkList.get(0)).trim())) {
if ("Y".equalsIgnoreCase(((String)
sketchWorkList.get(3)).trim())
|| "YES".equalsIgnoreCase(((String)
sketchWorkList.get(3)).trim())) {

ItextpdfhealperUtil itextpdf = new


ItextpdfhealperUtil();
System.out.println("itextpdf ::::: "+itextpdf);

String Screenshot_path=System.getProperty("user.dir")
+ "\\reports";
// itextpdf.initializePDF(sketchWorkList.get(1),
PropertyUtils.getProperties().getProperty("screenshot_location"));

itextpdf.initializePDF(sketchWorkList.get(1),Screenshot_path);

// sketch, routine, flavour


try {
routineResult = executeRoutine(sketch, (String)
sketchWorkList.get(1),
(String)
sketchWorkList.get(2),itextpdf);
} catch (Exception e) {
e.printStackTrace();
}finally {
itextpdf.closePDF();
}
// routineResult = "Pass";

if (!"Pass".equalsIgnoreCase(routineResult))
sketchAllClear = "Fail";

localSketchResultList.add(routineResult);
sketchResultList.add(localSketchResultList);
}
}
}

return sketchAllClear; // configMap;


}

@SuppressWarnings({ "rawtypes", "unchecked" })


private String executeRoutine(String sketch, String routine, String flavour,
ItextpdfhealperUtil itextpdf) {
System.out.println(" => Routine (" + routine + ") & flavour (" +
flavour + ")");
System.out.println(" ");
logger.info("inside OtonomService");
HashMap taskResultMap = new HashMap();
String taskResult = "Pass";
String routineResult = "Pass";
String flavourValue;
ArrayList routineWorkList;
ArrayList localRoutineResultList = null;
ArrayList routineData = (ArrayList) inputConfigMap.get("Routine");

for (int i = 1; i < routineData.size(); i++) {


taskResultMap.clear();
routineWorkList = (ArrayList) routineData.get(i);
localRoutineResultList = (ArrayList) routineWorkList.clone();

if (routine.contains(((String) routineWorkList.get(0)).trim())) {

if (((String) routineWorkList.get(5)).startsWith("##")) {
flavourValue = getFlavourValue(flavour, (String)
routineWorkList.get(5));
} else {
flavourValue = (String) routineWorkList.get(5);
}

taskMap.put("labelScope", labelScope);
taskMap.put("brandingScope", brandingScope);
taskMap.put("routine", routine);
taskMap.put("flavour", flavour);
taskMap.put("sketch", sketch);
taskMap.put("task", (String) routineWorkList.get(1));
taskMap.put("taskType", (String) routineWorkList.get(2));
taskMap.put("xpath", (String) routineWorkList.get(3));
taskMap.put("id", (String) routineWorkList.get(4));
taskMap.put("value", flavourValue);
taskMap.put("timeout", (String) routineWorkList.get(6));
taskMap.put("externalRef", (String)
routineWorkList.get(7));
taskMap.put("externalRef1", (String)
routineWorkList.get(8));
taskMap.put("collectVariables", (String)
routineWorkList.get(9));

if (!"Ignore".equalsIgnoreCase((String)
routineWorkList.get(2))) {
taskResultMap =
this.selenideService.executeTask(taskMap,itextpdf);
taskResult = (String)
taskResultMap.get("Result_Task");
} else {
taskResult = "Pass";
taskResultMap.put("Result_Expected", " ");
taskResultMap.put("Result_Actual", " ");
}

if ("Fail".equalsIgnoreCase(taskResult) ||
"TechFail".equalsIgnoreCase(taskResult)) {
System.out.println(" Task Result Failed- " +
(String) routineWorkList.get(1));
logger.info("inside OtonomService");
routineResult = "Fail";
}

localRoutineResultList.add(taskResult);

localRoutineResultList.add(taskResultMap.get("Result_Expected"));

localRoutineResultList.add(taskResultMap.get("Result_Actual"));
localRoutineResultList.add(sketch);
localRoutineResultList.add(routine);
localRoutineResultList.add(flavour);

localRoutineResultList.add(taskResultMap.get("Result_Timestamp"));

routineResultList.add(localRoutineResultList);

}
} // loop of tasks in a routine
System.out.println(" ");
return routineResult;

@SuppressWarnings("rawtypes")
private String getFlavourValue(String flavour, String value) {
ArrayList dynamicWorkList;
for (int i = 0; i < dynamicValuesList.size(); i++) {
dynamicWorkList = (ArrayList) dynamicValuesList.get(i);
if (value.equalsIgnoreCase(((String)
dynamicWorkList.get(0)).trim())
|| value.equalsIgnoreCase("##" + ((String)
dynamicWorkList.get(0)).trim())) {
if (flavour.equalsIgnoreCase(((String)
dynamicWorkList.get(1)).trim())) {
// return ((String) dynamicWorkList.get(2)).trim();
String val = ((String)
dynamicWorkList.get(2)).trim();

SimpleDateFormat formatter = null;


Date date = new Date();
Random random = new Random();

if ("~~RANDOM_NUM~~".equals(val)) // yymmddhhmissmis
+any

// randum number betw

// 10000 and 99999


{
int min = 10000;
int max = 99999;
formatter = new
SimpleDateFormat("yyyyHHmmssSSS");
val = formatter.format(date) +
random.nextInt(max + min) + 1; // generate

// date

// with

// randum

// number
System.out.println(formatter.format(date));
}

if ("~~TODAY_YYMMDD~~".equals(val)) // generate date


with

// YYMMDD
{
formatter = new SimpleDateFormat("yymmdd");
val = formatter.format(date);
System.out.println(formatter.format(date));
}

if ("~~TODAY_DD-MM-YYYY~~".equals(val)) // generate
date

// with DD-MM-YYYY
{
formatter = new SimpleDateFormat("dd-mm-yyyy");
val = formatter.format(date);
System.out.println(formatter.format(date));
}

if ("~~TODAY_MM/dd/yyyy~~".equals(val)) // generate
date
// with MM/dd/yyyy
{
formatter = new SimpleDateFormat("MM/dd/yyyy");
val = formatter.format(date);
System.out.println(formatter.format(date));
}

if ("~~TODAY_YYYY/MM/DD~~".equals(val)) // generate
date
// with YYYY/MM/DD
{
formatter = new SimpleDateFormat("yyyy/mm/dd");
val = formatter.format(date);
System.out.println(formatter.format(date));
}

if ("~~TOMORROW_MM/dd/yyyy~~".equals(val)) //
generate

// TOMORROW

// date with

// MM/dd/yyyy
{
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1);
date = calendar.getTime();
formatter = new SimpleDateFormat("MM/dd/yyyy");
val = formatter.format(date);
System.out.println("Tomorrow : " + val);
}

if ("~~RANDOM_STR~~".equals(val)) // generate date


with

// YYYY/MM/DD
{
// Define the static prefix
String prefix = "AS";

// Generate the date component in the format DDMMYY


SimpleDateFormat dateFormatter = new
SimpleDateFormat("ddMMyy");
String dateComponent = dateFormatter.format(new
Date());

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


StringBuilder sb = new StringBuilder();
int length = 2; // for length of string
for (int j = 0; j < length; j++) {
int index =
random.nextInt(alphabet.length());
char randomChar = alphabet.charAt(index);
sb.append(randomChar);
}
val = prefix + dateComponent+ sb.toString();
System.out.println("Random String is: " + val);
}

if ("~~RANDOM_AMT~~".equals(val)) // generate Random


amount
{
int min = 1000;
int max = 500000;
val = Integer.toString(random.nextInt(max +
min));
System.out.println("Random amt is: " + val);
}

return val;
}
}
}
return value;
}

@SuppressWarnings("rawtypes")
public void printSingleSheetData(ArrayList sheetData) {
System.out.println("----------------");
System.out.println("---- Result ----");
System.out.println("----------------");
logger.info("inside OtonomService");
ArrayList li2;
for (int i = 0; i < sheetData.size(); i++) {
System.out.print("Row " + i + " ----------------");
li2 = (ArrayList) sheetData.get(i);
for (int p = 0; p < li2.size(); p++) {
System.out.print(p + " - " + li2.get(p) + " ::: ");
}
System.out.println(" ");
logger.info("inside OtonomService");
}
}
}

result service:
package com.intellect.digipay.otonom.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import org.dhatim.fastexcel.Color;
import org.dhatim.fastexcel.Workbook;
import org.dhatim.fastexcel.Worksheet;
import org.springframework.stereotype.Component;
@Component
public class ResultService {

@SuppressWarnings("rawtypes")
public void writeResult(HashMap resultMap, String filePath, String fileName)
{
ArrayList dynamicResult = (ArrayList) resultMap.get("Dynamic");
ArrayList scopeResult = (ArrayList) resultMap.get("Scope");
ArrayList storyResult = (ArrayList) resultMap.get("Story");
ArrayList sketchResult = (ArrayList) resultMap.get("Sketch");
ArrayList routineResult = (ArrayList) resultMap.get("Routine");
ArrayList brandingResult = (ArrayList) resultMap.get("Branding");
ArrayList guideResult = (ArrayList) resultMap.get("Guide");
ArrayList readmeResult = (ArrayList) resultMap.get("Readme");
String timeStamp = new SimpleDateFormat("yyyy-MM-dd-HH-
mm").format(Calendar.getInstance().getTime());
File f = new File(filePath + "Result_"+timeStamp+"_"+fileName);

try (FileOutputStream fos = new FileOutputStream(f)) {


Workbook wb = new Workbook(fos, "Application", "1.0");
writeSheet("Dynamic_Values", wb, dynamicResult);
writeSheet("Scope", wb, scopeResult);
writeSheet("Result_Story", wb, storyResult);
writeSheet("Result_Sketch", wb, sketchResult);
writeSheet("Result_Routine", wb, routineResult);
writeSheet("Branding_Specs", wb, brandingResult);
writeSheet("Guide_Task", wb, guideResult);
writeSheet("Readme", wb, readmeResult);
wb.finish();
} catch (IOException e) {
e.printStackTrace();
}
}

@SuppressWarnings("rawtypes")
private void writeSheet(String sheetName, Workbook wb, ArrayList resultSheet)
{
Worksheet ws = wb.newWorksheet(sheetName);
ArrayList workList = new ArrayList();
int i;
int p = 0;
try {
for (i = 0; i < resultSheet.size(); i++) {
workList = (ArrayList) resultSheet.get(i);
for (p = 0; p < workList.size(); p++) {
ws.value(i, p, workList.get(p).toString());
if ("Pass".equalsIgnoreCase((String)
workList.get(p))) {
ws.style(i,
p).borderStyle("thin").fillColor(Color.LIGHT_GREEN).set();
}
if ("Fail".equalsIgnoreCase((String)
workList.get(p))) {
ws.style(i,
p).borderStyle("thin").fillColor(Color.BABY_PINK).set();
}
if ("TechFail".equalsIgnoreCase((String)
workList.get(p))) {
ws.style(i,
p).borderStyle("thin").fillColor(Color.RED).set();
}
if (workList.get(p).toString().startsWith("ID") ||
workList.get(p).toString().startsWith("Value")
||
workList.get(p).toString().startsWith("X")
||
workList.get(p).toString().startsWith("Param_")
||
workList.get(p).toString().startsWith("Flavour")
||
workList.get(p).toString().startsWith("Result_E")
||
workList.get(p).toString().startsWith("Result_A")) {
ws.width(p, 40);
}
if (i == 0) {
if
(workList.get(p).toString().startsWith("Result")
||
workList.get(p).toString().startsWith("Pass")
||
workList.get(p).toString().startsWith("Fail")
||
workList.get(p).toString().startsWith("TechFail")) {
ws.style(i,
p).borderStyle("thin").bold().fillColor(Color.NAVY_BLUE).fontColor(Color.WHITE)
.set();
} else {
ws.style(i,
p).borderStyle("thin").bold().fillColor(Color.YELLOW).set();
}
} else {
ws.style(i, p).borderStyle("thin").set();
}
}
}
} catch (Exception e) {
ws.value(0, 0, " ");
}
}
}

resubale method:
package com.intellect.digipay.otonom.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import Utilities.PropertyUtils;
import Utilities.RunTimeProperties;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;

//import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
//import context.RunTimeProperties;

public class ReusableMethods {

public static void getDate() {


SimpleDateFormat datetime = new SimpleDateFormat("YYYYMMdd");
Date date = new Date();
RunTimeProperties.setProperty("YYYYMMDD", datetime.format(date));
SimpleDateFormat time = new SimpleDateFormat("YYYY-MM-dd");

RunTimeProperties.setProperty("YYYY-MM-DD", time.format(date));
}

public static void PostFCR(String SSID, String testcase_no) throws


IOException {

// String FinalPath = "D:\\Otonom\\TC001.json";


String FinalPath = PropertyUtils.readProperty("FCFolder")+"\\" +
testcase_no + ".json";

System.out.println(FinalPath);
File file1 = new File(FinalPath);
Scanner sc = null;

try {
sc = new Scanner(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input + " ");
}

String json = sb.toString();


getDate();
json = json.replace("VAR_YYYYMMDD",
RunTimeProperties.getProperty("YYYYMMDD"))
.replace("VAR_YYY-MM-DD",
RunTimeProperties.getProperty("YYYY-MM-DD")).replace("VAR_SSID", SSID);
System.out.println(json);

try {
RequestConfig requestConfig =
RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
HttpClient httpClient =
HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

HttpPost httppost = new HttpPost(


"http://digipay-input-handler-dit-1-
fcl.cluster8.intellectproduct.com/digipaytrxmanager/create");

StringEntity userEntity = new StringEntity(json);


httppost.setEntity(userEntity);

HttpResponse response = httpClient.execute(httppost);


} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
}

public static void PostRTB(String TCNo,String testcase_no) throws IOException


{

String FinalPath = PropertyUtils.readProperty("RTBFolder")+"\\" +


testcase_no + ".json";

System.out.println(FinalPath);
File file1 = new File(FinalPath);
Scanner sc = null;

try {
sc = new Scanner(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input + " ");
}

String json = sb.toString();


getDate();
json = json.replace("VAR_refno",TCNo);
System.out.println(json);
try{

System.out.println("_________________");
HttpClient httpClient = HttpClientBuilder.create().build();

HttpPost httppost = new HttpPost("http://tlm-autoresponse-dit-1-


fcl.cluster8.intellectproduct.com/generator/rtbinput");

StringEntity userEntity;

userEntity = new StringEntity(json);


httppost.setEntity(userEntity);

HttpResponse response = httpClient.execute(httppost);


}

catch (ClientProtocolException e1) {


// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

public static void PostEarMark(String TCNo,String testcase_no) throws


IOException {

//String FinalPath = "D:\\Otonom\\TC003.json";


String FinalPath = PropertyUtils.readProperty("EMarkFolder")+"\\" +
testcase_no + ".json";
System.out.println(FinalPath);
File file1 = new File(FinalPath);
Scanner sc = null;

try {
sc = new Scanner(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input + " ");
}

String json = sb.toString();


getDate();
json = json.replace("VAR_refno",TCNo);

System.out.println(json);
try{
//RequestConfig requestConfig =
RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
System.out.println("_________________");
HttpClient httpClient = HttpClientBuilder.create().build();

HttpPost httppost = new HttpPost("http://tlm-autoresponse-dit-1-


fcl.cluster8.intellectproduct.com/generator/earmarkinput");

StringEntity userEntity;

userEntity = new StringEntity(json);


httppost.setEntity(userEntity);

HttpResponse response = httpClient.execute(httppost);


}

catch (ClientProtocolException e1) {


// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

public static void DeleteStrct(String testcase_no) throws IOException {

//String FinalPath = "D:\\Otonom\\TC003.json";


String FinalPath = PropertyUtils.readProperty("DeleteFolder")+"\\" +
testcase_no + ".json";
System.out.println(FinalPath);
File file1 = new File(FinalPath);
Scanner sc = null;

try {
sc = new Scanner(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input + " ");
}

String json = sb.toString();


getDate();

json = json
.replace("VAR_YYY-MM-DD",
RunTimeProperties.getProperty("YYYY-MM-DD"));
System.out.println(json);
try{
//RequestConfig requestConfig =
RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
System.out.println("_________________");
HttpClient httpClient = HttpClientBuilder.create().build();

HttpPost httppost = new HttpPost("http://tlm-limitcore-dit-1-


fcl.cluster8.intellectproduct.com/TLMCASController/CASProcess");

StringEntity userEntity;

userEntity = new StringEntity(json);


httppost.setEntity(userEntity);

HttpResponse response = httpClient.execute(httppost);


}

catch (ClientProtocolException e1) {


// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

/*public static void PostEarMark(String TCNo) {

RequestConfig requestConfig =
RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
HttpClient httpClient =
HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

HttpPost httppost = new HttpPost(


"http://digipay-input-handler-dit-1-
fcl.cluster8.intellectproduct.com/digipaytrxmanager/create");

RestAssured.baseURI = "http://tlm-autoresponse-dit-1-
fcl.cluster8.intellectproduct.com/generator/earmarkinput";
RequestSpecification request = RestAssured.given();

String FinalPath = "D:\\Otonom\\TC003.json";


System.out.println(FinalPath);
File file1 = new File(FinalPath);
Scanner sc = null;

try {
sc = new Scanner(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input + " ");
}

String json = sb.toString();


getDate();
json = json.replace("VAR_refno",
RunTimeProperties.getProperty("RefNo"));

System.out.println(json);

request.body(json);

Response response = request.post();


ResponseBody body = response.getBody();
System.out.println(response.getStatusLine());
System.out.println(body.asString());
}
*/
}

selenoid service:
package com.intellect.digipay.otonom.service;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.Condition.*;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Selenide;
import com.codeborne.selenide.SelenideConfig;
import com.codeborne.selenide.SelenideDriver;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.WebDriverRunner;
import com.deque.html.axecore.results.Results;
import com.deque.html.axecore.results.Rule;
import com.intellect.digipay.otonom.util.ItextpdfhealperUtil;
import com.deque.html.axecore.selenium.AxeBuilder;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import Utilities.PropertyUtils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
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.interactions.Action;
import static com.codeborne.selenide.Selenide.screenshot;

public class SelenideService {

Logger logger = LogManager.getLogger(SelenideService.class);


static WebElement driver = null;
private static List<String> tags =
Arrays.asList("wcag2a","wcag2aa","wcag2aaa");

BrandingService brandingService;
HttpService httpService;
String labelScope;
String brandingScope;
String sketch;
String routine;
String flavour;
String task;
String taskType;
String xpath;
String id;
String value;
Integer timeout;
String externalRef;
String externalRef1;
String taskResult = "Pass";
String expectedResult = " ";
String actualResult = " ";
String holder;
SelenideService hoverElement;
String collectVariables;
HashMap<String, String> resultMap = new HashMap<String, String>();
HashMap<String, String> brandingSpecs;
HashMap<String, String> collectVariablesMap = new HashMap<String, String>();
String filePath;
SelenideConfig con;
SelenideDriver sd;
org.openqa.selenium.WebDriver dri; //

@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })


public SelenideService(ArrayList brandingList, ArrayList httpList, ArrayList
databaseList, String filePath,
String browser) {
this.brandingService = new BrandingService(brandingList);
this.httpService = new HttpService(httpList);
this.filePath = filePath;

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");


Date date = new Date();

System.setProperty("java.awt.headless", "false");

Configuration config = new Configuration();


config.timeout = 20000;
config.reportsFolder = filePath + "\\reports\\" +
formatter.format(date);
//config.browser = browser;
config.browser = "firefox"; // Set to Firefox

if ("ie".equalsIgnoreCase(browser))
config.pageLoadStrategy = "none";
con = new SelenideConfig();
sd = new SelenideDriver(con);
dri = sd.getAndCheckWebDriver();

WebDriverRunner.setWebDriver(dri);

public HashMap<String, String> executeTask(HashMap<String, String> taskMap,


ItextpdfhealperUtil itextpdf) {
labelScope = taskMap.get("labelScope").trim();
brandingScope = taskMap.get("brandingScope").trim();
sketch = taskMap.get("sketch").trim();
routine = taskMap.get("routine").trim();
flavour = taskMap.get("flavour").trim();
task = taskMap.get("task").trim();
taskType = taskMap.get("taskType").trim();
xpath = taskMap.get("xpath").trim();
id = taskMap.get("id").trim();
value = taskMap.get("value").trim();
externalRef = taskMap.get("externalRef").trim();
externalRef1 = taskMap.get("externalRef1").trim();
collectVariables = taskMap.get("collectVariables").trim();
if (collectVariables == null) {
collectVariables = "defult";
}

expectedResult = "";
actualResult = "";

int rowAffected = 0;
try {
timeout = Integer.parseInt(taskMap.get("timeout").trim());
} catch (Exception e) {
timeout = 20;
}
if (Optional.ofNullable(timeout).orElse(0) < 5) {
timeout = 20;
}

System.out.println(" Executing routine - " + String.format("%-40s",


routine) + " : Task - "
+ String.format("%-40s", task) + " flavour " + flavour);
if (value.contains("$$")) {
System.out.println("About to replace $.......");
for (String name : collectVariablesMap.keySet()) {
String key = name.toString();
String value = collectVariablesMap.get(name).toString();
System.out.println(key + "--" + value);
}

System.out.println("Before replace ---->>>>>>" + value);


// value = collectVariablesMap.get(value.replace("$$", ""));
for (String name : collectVariablesMap.keySet()) {
if (name.toString().length() >= 1) {
value = value.replace("$$" + name.toString(),
collectVariablesMap.get(name));
}
}
System.out.println("After replace ---->>>>>>>" + value);

try {
switch (taskType.toLowerCase()) {

case "http_fcr":
System.out.println("-----------------------Start
post1------------");
String val1[] = value.split("\\|");
System.out.println(value);
ReusableMethods.PostFCR(val1[0], val1[1]);
collectVariablesMap.put(collectVariables, value);
break;

case "http_rtb":
System.out.println("-----------------------Start
post2------------");

System.out.println(value);
String val2[] = value.split("\\|");
ReusableMethods.PostRTB(val2[0], val2[1]);

collectVariablesMap.put(collectVariables, value);
break;

case "http_ecr":
System.out.println("-----------------------Start
post3------------");

System.out.println(value);
String val3[] = value.split("\\|");
ReusableMethods.PostEarMark(val3[0], val3[1]);
collectVariablesMap.put(collectVariables, value);
break;

case "delete_structure":
System.out.println("-----------------------Start
post4------------");

System.out.println(value);
ReusableMethods.DeleteStrct(value);
collectVariablesMap.put(collectVariables, value);
break;

case "open":
open(value);
taskResult = "Pass";
break;

case "tab":
int go;
try {
go = Integer.parseInt(value);
} catch (Exception e) {
go = 100;
}
for (int i = 0; i < go; i++) {
actions().sendKeys(Keys.TAB).build().perform();
if (getFocusedElement().getText().trim().length() ==
0) {
actualResult = actualResult + ", " + i;
}
}
break;

case "press_tab":
actions().sendKeys(Keys.TAB).build().perform();
break;

case "enter":
actions().sendKeys(Keys.ENTER).build().perform();
break;

case "disable":
try {
$(By.xpath(value)).shouldBe(enabled);
System.out.println("disabled");
taskResult = "Fail";
} catch (Exception e) {
System.out.println("Enabled");
taskResult = "Pass";
}

break;

case "enable":
try {
$(By.xpath(value)).shouldBe(disabled);
System.out.println("enabled");
taskResult = "Fail";
} catch (Exception e) {
System.out.println("disabled");
taskResult = "Pass";
}

break;

case "visible":
try {
$(By.xpath(value)).shouldBe(visible);
System.out.println("visible");
taskResult = "Pass";
} catch (Exception e) {
System.out.println("not visible");
taskResult = "Pass";
}

break;

case "http_api_call":
int httpResponse = this.httpService.makeHttpCall(value);
expectedResult = "Http Response 2XX";
actualResult = "Http Response " + httpResponse;

if (httpResponse >= 200 && httpResponse < 300) {


taskResult = "Pass";
} else {
taskResult = "Fail";
}
break;

case "keydown":

int go1;
try {
go1 = Integer.parseInt(value);
} catch (Exception e) {
go1 = 100;
}
for (int i = 0; i < go1; i++) {
actions().sendKeys(Keys.DOWN).build().perform();
if (getFocusedElement().getText().trim().length() ==
0) {
actualResult = actualResult + ", " + i;

}
}

break;

case "keydown_one_time":
actions().sendKeys(Keys.DOWN).build().perform();
break;

case "click":
if (id != null && !id.trim().isEmpty()) {
$$(id).first().shouldHave(enabled,
Duration.ofSeconds(timeout));
$$(id).first().click();
} else {
$$x(xpath).first().shouldHave(enabled,
Duration.ofSeconds(timeout));
$$x(xpath).first().click();
}
taskResult = "Pass";
break;

case"set_reference_currency":

String[] currency = {"AUD","CAD","THB"};

if(value.equals("AUD")) {

System.out.println(currency[1]);
}
else if(value.equals("CAD")) {
System.out.println(currency[2]);
}else{
System.out.println(currency[0]);
}

case "doubleclick":
if (id != null && !id.trim().isEmpty()) {
$$(id).first().shouldHave(enabled,
Duration.ofSeconds(timeout));
$$(id).first().doubleClick();
} else {
$$x(xpath).first().shouldHave(enabled,
Duration.ofSeconds(timeout));
$$x(xpath).first().doubleClick();
}
taskResult = "Pass";
break;

// case "close":
//
// Selenide.closeWindow();
// taskResult = "Pass";
// break;

case "close":
System.out.println("Attempting to close the current
window...");
try {
Selenide.closeWindow();
System.out.println("Window closed successfully.");
taskResult = "Pass";
} catch (Exception e) {
System.out.println("Failed to close the window: " +
e.getMessage());
taskResult = "Fail";
}
break;

case "clear_field":
if (id != null && !id.trim().isEmpty()) {
$$(id).first().shouldHave(enabled,
Duration.ofSeconds(timeout));
$$(id).first().clear();
} else {
$$x(xpath).first().shouldHave(enabled,
Duration.ofSeconds(timeout));
$$x(xpath).first().clear();
}
taskResult = "Pass";
break;

case "update_query":
rowAffected = updateQuery(value);
String s = Integer.toString(rowAffected);
collectVariablesMap.put(collectVariables, s);
taskResult = "Pass";
break;

case "select_query":
taskResult = selectQuery(value);
collectVariablesMap.put(collectVariables, taskResult);
taskResult = "Pass";
break;

case "delete_query":
rowAffected = deleteQuery(value);
String r = Integer.toString(rowAffected);
collectVariablesMap.put(collectVariables, r);
taskResult = "Pass";
break;

case "sleep":
sleep(1000 * Integer.parseInt(value));
taskResult = "Pass";
break;

case "back_space":
actions().sendKeys(Keys.BACK_SPACE).build().perform();
taskResult = "Pass";
break;

case "set_value":
if (id != null && !id.trim().isEmpty()) {
$$(id).first().shouldHave(enabled,
Duration.ofSeconds(timeout));
$$(id).first().click();
} else {
$$x(xpath).first().shouldHave(enabled,
Duration.ofSeconds(timeout));
$$x(xpath).first().click();
}
actions().sendKeys(value).build().perform();
collectVariablesMap.put(collectVariables, value);
taskResult = "Pass";
break;

case "check_value":
case "check_value_exact":
case "check_value_ignore":
holder = extractText();
expectedResult = value;
actualResult = holder;
collectVariablesMap.put(collectVariables, actualResult);
System.out.println("collectVariablesMap");
for (String name : collectVariablesMap.keySet()) {
String key = name.toString();
String value =
collectVariablesMap.get(name).toString();
System.out.println(key + "--" + value);

if (value.equals(holder))
taskResult = "Pass";
else
taskResult = "Fail";

if (taskType.equalsIgnoreCase("check_value_ignore"))
taskResult = "Pass";
break;

case "check_value_disabled":

String text2 = (String) ((JavascriptExecutor)


driver).executeScript("return arguments[0].value;",
driver.findElement(By.xpath(
"/html/body/app-root/clr-main-
container/div[2]/main/process-queue-complete/div/transaction-details/div/div/form/
clr-tabs/section/div/table/tr[1]/td[4]/input")));

System.out.println("getText----------" + text2);

holder = text2;
expectedResult = value;
actualResult = holder;
collectVariablesMap.put(collectVariables, actualResult);
System.out.println("collectVariablesMap");
for (String name : collectVariablesMap.keySet()) {
String key = name.toString();
String value =
collectVariablesMap.get(name).toString();
System.out.println(key + "--" + value);

if (value.equals(holder))
taskResult = "Pass";
else
taskResult = "Fail";

break;

case "placeholder":
expectedResult = value;
if (id != null && !id.trim().isEmpty()) {
$(id).shouldHave(Condition.attribute("placeholder",
value));
actualResult = $(id).getAttribute("placeholder");

} else {

$x(xpath).shouldHave(Condition.attribute("placeholder", value));
actualResult = $x(xpath).getAttribute("placeholder");
}

if (expectedResult.equals(actualResult))
taskResult = "Pass";
else
taskResult = "Fail";
break;

case "check_value_begins_with":
holder = extractText();
expectedResult = value;
actualResult = holder;

if (holder.startsWith(value))
taskResult = "Pass";
else
taskResult = "Fail";
break;

case "check_value_ends_with":
holder = extractText();
expectedResult = value;
actualResult = holder;

if (holder.endsWith(value))
taskResult = "Pass";
else
taskResult = "Fail";
break;

case "check_value_contains":
holder = extractText();
expectedResult = value;
actualResult = holder;

if (holder.contains(value))
taskResult = "Pass";
else
taskResult = "Fail";
break;

case "refresh_screen":
// Refresh the screen or reload the page
if (id != null && !id.trim().isEmpty()) {
((SelenideDriver) $$
(id).first()).getWebDriver().navigate().refresh();
} else {
((SelenideDriver) $$
(xpath).first()).getWebDriver().navigate().refresh();
}

// Optionally, you might want to wait for the refresh to


complete
Thread.sleep(2000); // sleep for 2 seconds, adjust as needed

// Log or set result


actualResult = "Screen refreshed";
taskResult = "Pass";
break;

case "check_branding_self":
case "check_branding_ignore":
if (id != null && !id.trim().isEmpty()) {
$$(id).first().shouldHave(exist,
Duration.ofSeconds(timeout));
} else {
$$x(xpath).first().shouldHave(exist,
Duration.ofSeconds(timeout));
}
brandingSpecs =
this.brandingService.getBrandingSpecs(value, taskType.toLowerCase());
boolean brandingcheck = true;

for (Map.Entry<String, String> entry :


brandingSpecs.entrySet()) {
expectedResult = expectedResult +
System.getProperty("line.separator") + entry.getKey() + ":"
+ entry.getValue();

if (id != null && !id.trim().isEmpty()) {


actualResult = actualResult +
System.lineSeparator() + entry.getKey() + ":"
+ $$
(id).first().getCssValue(entry.getKey());

if ("font-
family".equalsIgnoreCase(entry.getKey())) {
if (!$$
(id).first().getCssValue(entry.getKey()).contains(entry.getValue())) {
brandingcheck = false;
}
} else {
if (!entry.getValue().equals($$
(id).first().getCssValue(entry.getKey()))
&& !($$
(id).first().getCssValue(entry.getKey())).contains("auto")
&& !
entry.getValue().contains("auto")) {
brandingcheck = false;
}
}
} else {
actualResult = actualResult +
System.lineSeparator() + entry.getKey() + ":"
+ $
$x(xpath).first().getCssValue(entry.getKey());

if ("font-
family".equalsIgnoreCase(entry.getKey())) {
if (!$
$x(xpath).first().getCssValue(entry.getKey()).contains(entry.getValue())) {
brandingcheck = false;
}
} else {
try {
if (!entry.getValue().equals($
$x(xpath).first().getCssValue(entry.getKey()))
&& !($
$x(xpath).first().getCssValue(entry.getKey())).contains("auto")
&& !
entry.getValue().contains("auto")) {
brandingcheck = false;
}
} catch (Exception e) {
}
}
}
}

if (brandingcheck)
taskResult = "Pass";
else
taskResult = "Fail";
if (taskType.equalsIgnoreCase("check_branding_ignore"))
taskResult = "Pass";

break;

case "screenshot":
String screenshot2 = screenshot(sketch + "___" + routine + "___" +
flavour + "___" + task);
System.out.println("DDDDDDDD>>>>>>"+screenshot2);
//task
//itextpdf.writePDF(task);0000

itextpdf.writePDF(getScreenShotNameDetails(task), 2);
itextpdf.writePDF(getScreenShotTimeStamp(), 2);
itextpdf.insertImageInPDF(screenshot2.substring(6));
itextpdf.writePDFNewPage();
actualResult = sketch + "___" + routine + "___" + flavour + "___" +
task;
taskResult = "Pass";
break;

case "check_branding_hover":
if (id != null && !id.trim().isEmpty()) {
$$(id).first().shouldHave(exist,
Duration.ofSeconds(timeout)).hover();
} else {
$$x(xpath).first().shouldHave(exist,
Duration.ofSeconds(timeout)).hover();
}
brandingSpecs =
this.brandingService.getBrandingSpecs(value, taskType.toLowerCase());
for (Map.Entry<String, String> entry :
brandingSpecs.entrySet()) {
expectedResult = expectedResult +
System.getProperty("line.separator") + entry.getKey() + ":"
+ entry.getValue();

if (id != null && !id.trim().isEmpty()) {


actualResult = actualResult +
System.lineSeparator() + entry.getKey() + ":"
+ $$
(id).first().getCssValue(entry.getKey());

} else {
actualResult = actualResult +
System.lineSeparator() + entry.getKey() + ":"
+ $
$x(xpath).first().getCssValue(entry.getKey());
}
}

if (expectedResult.equals(actualResult))
taskResult = "Pass";
else
taskResult = "Fail";
break;

case "check_branding_active":

if (id != null && !id.trim().isEmpty()) {


$$(id).first().shouldHave(exist,
Duration.ofSeconds(timeout));
/*
* SelenideElement element = $(".foo");
Selenide.actions()
* .moveToElement(element) .clickAndHold()

* .pause(Duration.ofSeconds(5)) .release() .perform();


*/
SelenideElement element = (SelenideElement) $
$x("id");
System.out.println("before clickAndhold%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%");

WebDriver driver = new ChromeDriver();


Actions builder = new Actions(driver);
Action active =
builder.moveToElement(element).clickAndHold().build();

System.out.println($
(element).getCssValue("background-color"));

System.out.println("after clickAndhold%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%");

} else {
$$x(xpath).first().shouldHave(exist,
Duration.ofSeconds(timeout));
}

System.out.println("1##############################################################
#####");
brandingSpecs =
this.brandingService.getBrandingSpecs(value, taskType.toLowerCase());
System.out.println("brandingSpecs :" + brandingSpecs);
for (Map.Entry<String, String> entry :
brandingSpecs.entrySet()) {

System.out.println("2##############################################################
#####");
expectedResult = expectedResult +
System.getProperty("line.separator") + entry.getKey() + ":"
+ entry.getValue();

if (id != null && !id.trim().isEmpty()) {


actualResult = actualResult +
System.lineSeparator() + entry.getKey() + ":"
+ $$
(id).first().getCssValue(entry.getKey());

} else {
actualResult = actualResult +
System.lineSeparator() + entry.getKey() + ":"
+ $
$x(xpath).first().getCssValue(entry.getKey());
}
}

System.out.println("expectedResult :" + expectedResult);


System.out.println("actualResult :" + actualResult);

if (expectedResult.equals(actualResult))
taskResult = "Pass";
else
taskResult = "Fail";
break;

case "check_value_hover": // new


if (id != null && !id.trim().isEmpty()) {
$$(id).first().shouldHave(exist,
Duration.ofSeconds(timeout)).hover();
} else {
$$x(xpath).first().shouldHave(exist,
Duration.ofSeconds(timeout)).hover();
}

holder = extractText();
expectedResult = value;
actualResult = holder;
collectVariablesMap.put(collectVariables, actualResult);
System.out.println("collectVariablesMap");
for (String name : collectVariablesMap.keySet()) {
String key = name.toString();
String value =
collectVariablesMap.get(name).toString();
System.out.println(key + "--" + value);

}
if (expectedResult.equals(actualResult))
taskResult = "Pass";
else
taskResult = "Fail";
break;

case "scroll_up":
actions().sendKeys(Keys.PAGE_UP).build().perform();
break;

case "scroll_down":
actions().sendKeys(Keys.PAGE_DOWN).build().perform();

break;

case "target_new_tab":
int tab_val = Integer.parseInt(value);
switchTo().window(tab_val);
break;
case "check_a11y":
AxeBuilder builder = new AxeBuilder();
builder.withTags(tags);
//Results results = builder.analyze((WebDriver) driver);
Results results = builder.analyze(dri);
System.out.println("results a11y");
List<Rule> violations = results.getViolations();
System.out.println("violations.size() -
"+violations.size());
if (violations.size() == 0) {
actualResult = "No violations found";
taskResult = "Pass";
} else {

//AxeReporter.getReadableAxeResults("no-passes", dri,
violations);
//actualResult = AxeReporter.getAxeResultString();
Iterator<Rule> iterator = violations.iterator();
Rule rule;
String findings = " ";
/*
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
List nodes;
while (iterator.hasNext()) {
rule = iterator.next();
jo.clear();
jo.put("impact", rule.getImpact());
jo.put("tags", rule.getTags().toString());
jo.put("description", rule.getDescription());
jo.put("node-count", rule.getNodes().size());
jo.put("node-sample",
rule.getNodes().get(0).getFailureSummary()
+ " ~ " +
rule.getNodes().get(0).getHtml());
System.out.println("finding --" +
jo.toString());
//findings = findings + "~" + jo.toString();
ja.put(jo);
}
*/
JsonArray ja = new JsonArray();
JsonObject jo;
List nodes;
while (iterator.hasNext()) {
rule = iterator.next();
jo = new JsonObject();

jo.addProperty("impact", rule.getImpact());
jo.addProperty("node-count",
rule.getNodes().size());
jo.addProperty("tags",
rule.getTags().toString());
jo.addProperty("description",
rule.getDescription());
jo.addProperty("node-sample",
rule.getNodes().get(0).getFailureSummary()
+ " ~ " +
rule.getNodes().get(0).getHtml());
ja.add(jo);
}

Gson gson = new


GsonBuilder().setPrettyPrinting().create();
JsonElement je =
JsonParser.parseString(ja.toString());
actualResult = gson.toJson(je);
taskResult = "Fail";
}
System.out.println("a11y findings - ");
System.out.println(actualResult);

break;
default:
System.out.println("Incorrect Task_Type is configured.
Please refer Guide_Task sheet.");
logger.info("inside selenideservice");
break;
}

} catch (Exception ex) {


System.out.println(" " + ex.getMessage());
taskResult = "TechFail";
} catch (Throwable th) {
System.out.println(" " + th.getMessage());
taskResult = "TechFail";
}
Date date = new Date();

resultMap.put("Result_Task", taskResult);
resultMap.put("Result_Expected", expectedResult);
resultMap.put("Result_Actual", actualResult);
resultMap.put("Result_Timestamp", "" + new Timestamp(date.getTime()));
return resultMap;
}

private String extractText() {


if (id != null && !id.trim().isEmpty()) {
$$(id).first().shouldHave(exist, Duration.ofSeconds(15));
return $$(id).get(0).getText().trim();
} else {
$$x(xpath).first().shouldHave(exist, Duration.ofSeconds(15));
return $$x(xpath).get(0).getText().trim();
}
}

public static int updateQuery(String query) throws Exception {


Class.forName("org.postgresql.Driver");
int rowsAffected = 0;
Connection connection = null;
try {
connection =
DriverManager.getConnection(PropertyUtils.getProperties().getProperty("POSTGRES_URL
"),

PropertyUtils.getProperties().getProperty("POSTGRES_dBUsername"),

PropertyUtils.getProperties().getProperty("POSTGRES_dBUserPass"));
String schemaName =
PropertyUtils.getProperties().getProperty("STUB_SCHEMA_NAME");
connection.setSchema(schemaName);

Statement statement = connection.createStatement();


System.out.println("Updating records!!");

System.out.println(query);

rowsAffected = statement.executeUpdate(query);
return rowsAffected;
} catch (SQLException ex) {
System.out.println(ex.getMessage());
return 0;
} finally {
connection.close();
}

public static String selectQuery(String query) throws Exception {


Class.forName("org.postgresql.Driver");
boolean rowsAffected;
String value = " ";
Connection connection = null;
ResultSet rslt = null;
try {
connection =
DriverManager.getConnection(PropertyUtils.getProperties().getProperty("POSTGRES_URL
"),

PropertyUtils.getProperties().getProperty("POSTGRES_dBUsername"),

PropertyUtils.getProperties().getProperty("POSTGRES_dBUserPass"));
String schemaName =
PropertyUtils.getProperties().getProperty("STUB_SCHEMA_NAME");
connection.setSchema(schemaName);

Statement statement = connection.createStatement();


// System.out.println("Updating records!!");
System.out.println(query);

rowsAffected = statement.execute(query);

if (rowsAffected) {

rslt = statement.getResultSet();
if (rslt.next()) {
value = rslt.getString(1);

}
}
return value;
} catch (SQLException ex) {
System.out.println(ex.getMessage());

} finally {
connection.close();
}
return value;

public List<List<String>> getScreenShotNameDetails(String ssName) {

List<List<String>> row1 = new ArrayList<List<String>>();

List<String> row1Details = new ArrayList<String>();


row1Details.add(" �ScreenShot Details");
row1Details.add(" �" + ssName);
row1.add(row1Details);

return row1;

public List<List<String>> getScreenShotTimeStamp() {


LocalDateTime ldateTime = LocalDateTime.now();

List<List<String>> row2 = new ArrayList<List<String>>();

List<String> row2Details = new ArrayList<String>();


row2Details.add(" �DateTime");
row2Details.add(" " + ldateTime.toString().substring(0,
19).replace("T", " "));
row2.add(row2Details);

// writePDF(row1, 2);
return row2;

public static int deleteQuery(String query) throws Exception {


Class.forName("org.postgresql.Driver");
int rowsAffected = 0;
Connection connection = null;
try {
connection =
DriverManager.getConnection(PropertyUtils.readProperty("POSTGRES_URL"),
PropertyUtils.readProperty("POSTGRES_dBUsername"),
PropertyUtils.readProperty("POSTGRES_dBUserPass"));
String schemaName =
PropertyUtils.readProperty("STUB_SCHEMA_NAME");
connection.setSchema(schemaName);

Statement statement = connection.createStatement();


System.out.println("Deleting records!!");

System.out.println(query);

rowsAffected = statement.executeUpdate(query);
return rowsAffected;
} catch (SQLException ex) {
System.out.println(ex.getMessage());
return 0;
} finally {
connection.close();
}

}
}

helper utility:
package com.intellect.digipay.otonom.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.text.BadElementException;
//import com.intellect.iso.automation.constant.ISOConstant;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.itextpdf.*;

@Service
public class ItextpdfhealperUtil {

static Logger logger = LoggerFactory.getLogger(ItextpdfhealperUtil.class);


static Document gPDFDocument = null;
static String gPDFDocumentName = null;
//static PdfWriter lPdfWriter = null;

// @Autowired
// PostgresDBUtils postgresDBUtils;

// @Value("${OUTPUT_FILE_NAME_PREFIX}")
// String OUTPUT_FILE_NAME_PREFIX;
//
// @Value("${OUTPUT_FILE_EXTENSION}")
// String OUTPUT_FILE_EXTENSION;

/* @Value("${POSTGRES_REMREP_SCHEMA_PROP}")
String POSTGRES_REMREP_SCHEMA_PROP;

@Value("${POSTGRES_ISO_SCHEMA_PROP}")
String POSTGRES_ISO_SCHEMA_PROP;

@Value("${DB_CONNECTION_DATABASE}")
String DB_CONNECTION_DATABASE;

@Value("${DB_CONNECTION_SCHEMA}")
String DB_CONNECTION_SCHEMA;*/

// @Value("${OUTPUT_FILE_PATH}")
// String OUTPUT_FILE_PATH;

public void initializePDF(String pTestCaseName, String path) throws


FileNotFoundException, DocumentException {

System.err.println("initializePDF called");
if (gPDFDocument == null || !gPDFDocumentName.equals(pTestCaseName)) {
gPDFDocument = new Document(PageSize.A4.rotate());
//gPDFDocument.setMargins(20, -40, 30, 30);
gPDFDocument.setMargins(-60, -60, 30, 30);
//gPDFDocument.setMargins(marginLeft, marginRight, marginTop,
marginBottom)
gPDFDocumentName = pTestCaseName;
}
LocalDateTime curDateTime = LocalDateTime.now();
/*PdfWriter lPdfWriter = PdfWriter.getInstance(gPDFDocument,
new
FileOutputStream(OUTPUT_FILE_PATH+OUTPUT_FILE_NAME_PREFIX + pTestCaseName + "_"
+curDateTime.toString().substring(0, 19).replace("T", "").replace(":",
"").replace("-", "") + OUTPUT_FILE_EXTENSION ));
*/
System.err.println("Creating PDF a path {}"+ path);
PdfWriter lPdfWriter = PdfWriter.getInstance(gPDFDocument,
new FileOutputStream(path+"//"+ pTestCaseName + "_"
+curDateTime.toString().substring(0, 19).replace("T", "").replace(":",
"").replace("-", "") + ".pdf" ));
gPDFDocument.open();

// document.add(new Paragraph("lScriptOutput"+lScriptOutput));
}

public void printQueryResulltInPDFTable(ResultSet lRs, String pQuery, String


valueToReplace, String columnToReplace, String step)
throws SQLException, DocumentException {

logger.info("column toreplace :::"+valueToReplace);

if(valueToReplace!=null)pQuery = pQuery.replace(columnToReplace,
valueToReplace); // lDetails
// pQuery = postgresDBUtils.cleanSchemaName(pQuery);

LocalDateTime ldateTime = LocalDateTime.now();

// logger.info("----- PDF Printing pQuery -------------------{}",


pQuery);

List<String> qList = new ArrayList<String>();


List<String> stepList = new ArrayList<String>();
List<String> executionDetails = new ArrayList<String>();
stepList.add("STEP : " + step.toUpperCase() + " | Execution Date
Time : "
+ ldateTime.toString().substring(0, 19).replace("T", " "));
qList.add(pQuery);
List<List<String>> printQList = new ArrayList<List<String>>();
List<List<String>> stepDetails = new ArrayList<List<String>>();
List<List<String>> printDetails = new ArrayList<List<String>>();
//executionDetails.add("DB TABLE DATA");
//printDetails.add(executionDetails);
stepDetails.add(stepList);
printQList.add(qList);
writePDF(stepDetails, 1);
writePDF(printQList, 1);
if(lRs!=null) {
// printDetails.add(executionDetails);

writePDF(printDetails, 1);
int lRowCounter = 0;
ResultSetMetaData lRsMetaData = lRs.getMetaData();
int lColumnCount = lRsMetaData.getColumnCount();
List<List<String>> lFinalResult = new ArrayList<List<String>>();

List<String> lTempRecord = new ArrayList<String>();

while (lColumnCount > 0) {


lTempRecord.add(lRsMetaData.getColumnLabel(lColumnCount));
// logger.info("-----header------{}",
lRsMetaData.getColumnLabel(lColumnCount));
lColumnCount--;
}
lFinalResult.add(lTempRecord);

if (true) {

while (lRs.next()) {
lRowCounter++;
lTempRecord = new ArrayList<String>();
lColumnCount = lRsMetaData.getColumnCount();
while (lColumnCount > 0) {
lTempRecord.add(lRs.getString(lColumnCount--));
}
lFinalResult.add(lTempRecord);
// lColumnCount = lRsMetaData.getColumnCount();
}

// logger.info("-----lFinalResult------{}", lFinalResult);
if (lRowCounter > 0) {
writePDF(lFinalResult, lRsMetaData.getColumnCount());
} else {
List<List<String>> lNoResult = new
ArrayList<List<String>>();
List<String> lNoRecord = new ArrayList<String>();
lNoRecord.add("No Result Found..!!");
lNoResult.add(lNoRecord);
// writePDF("", BaseColor.RED, true);
writePDF(lNoResult, 1);
}

}
else {

}
/*
* if (lRs != null) lRs.close();
*/

public void printPDFHeader(String testCaseId,String externalRefNo) throws


DocumentException {

logger.info("Inside header print ----");

LocalDateTime ldateTime = LocalDateTime.now();

List<List<String>> row1 = new ArrayList<List<String>>();


List<List<String>> row2 = new ArrayList<List<String>>();
List<List<String>> row3 = new ArrayList<List<String>>();
List<List<String>> row4 = new ArrayList<List<String>>();
List<List<String>> row5 = new ArrayList<List<String>>();
/*List<String> row1Details = new ArrayList<String>();
row1Details.add(ISOConstant.DBNAME);
row1Details.add(" " + DB_CONNECTION_DATABASE);
row1.add(row1Details);

List<String> row2Details = new ArrayList<String>();


row2Details.add(ISOConstant.SCHEMANAME);
row2Details.add(" " + DB_CONNECTION_SCHEMA);
row2.add(row2Details);*/

List<String> row3Details = new ArrayList<String>();


// row3Details.add(ISOConstant.DTSTAMP);
row3Details.add(" " + ldateTime.toString().substring(0,
19).replace("T", " "));
row3.add(row3Details);

List<String> row4Details = new ArrayList<String>();


// row4Details.add(ISOConstant.TESTCASEID);
row4Details.add(" " + testCaseId);
row4.add(row4Details);

//Chunk linebreak = new Chunk(new LineSeparator());


//gPDFDocument.add(linebreak);
//Chunk linebreak = new Chunk();

//row1.add(row2Details);
row1.add(row3Details);
row1.add(row4Details);
writePDF(row1, 2);

//gPDFDocument.add(linebreak);
/*writePDF(row2, 2);
gPDFDocument.add(linebreak);

writePDF(row3, 2);
gPDFDocument.add(linebreak);

writePDF(row4, 2);
gPDFDocument.add(linebreak);

gPDFDocument.add(linebreak);*/

public static void writePDF(List<List<String>> pDBResults, int


pColumnCounter) throws DocumentException {
//Chunk linebreak = new Chunk(new DottedLineSeparator());
Chunk linebreak = new Chunk();
gPDFDocument.add(linebreak);
PdfPTable table = new PdfPTable(pColumnCounter);
float[] lColumnWidths = new float[pColumnCounter];// {10f, 20f, 30f,
10f};

for (int i = 0; i < pColumnCounter; i++) {


lColumnWidths[i] = 50f;
}

pDBResults.forEach(lRecord -> lRecord.forEach(lCellItem -> {


Phrase lPhrase = new Phrase(lCellItem);
PdfPCell lCell = new PdfPCell(lPhrase);
lCell.setPadding(7);
table.addCell(lCell);
}));

table.setTotalWidth(40f * pColumnCounter);
table.setWidths(lColumnWidths);

gPDFDocument.add(table);
}

public static void closePDF() {


//logger.info("Called closePDF :: {}", gPDFDocument.toString());
if (gPDFDocument != null) {
logger.info("Called closePDF not null:: {}");

gPDFDocument.close();
//lPdfWriter.close();

public static void writePDF(String pResults, BaseColor lColor, boolean


pSkipLineBreak) throws DocumentException {
if (!pSkipLineBreak) {
Chunk linebreak = new Chunk(new LineSeparator());
gPDFDocument.add(linebreak);
}
Font myFonColor = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12,
lColor);// BaseColor.RED
Paragraph lPara = new Paragraph(pResults, myFonColor);
gPDFDocument.add(lPara);

public static void writePDF(String pResults) throws DocumentException {


writePDF(pResults, BaseColor.BLACK, false);
}

public static void writePDFLine(String pResults) throws DocumentException {


writePDF(pResults, BaseColor.WHITE, false);
}

public static void writePDFNewPage() throws DocumentException {


gPDFDocument.newPage();
}

public static void insertImageInPDF(String screenshot2) throws


MalformedURLException, IOException, DocumentException {
// Creating an ImageData object
// String imageFile = "C:/itextExamples/javafxLogo.jpg";
// ImageData data = ImageDataFactory.create(imageFile);

// Creating an Image object


Image image1 = Image.getInstance(screenshot2);
// System.err.println("MERA INSERT PDF CALL");

image1.setAlignment(Element.ALIGN_CENTER);
image1.setBorderColor(BaseColor.BLACK);
image1.scaleAbsolute(500, 375);

gPDFDocument.add(image1);

propertyutils:
package Utilities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertyUtils {

private static final Properties properties;

public static Properties getProperties() {


return properties;
}

static {
properties = new Properties();

try {
ClassLoader classLoader = PropertyUtils.class.getClassLoader();
InputStream applicationPropertiesStream =
classLoader.getResourceAsStream("application.properties");
properties.load(applicationPropertiesStream);
} catch (Exception e) {
e.printStackTrace();
}

// public static String readProperty(String propertyname) throws IOException


// {
// FileReader fileread;
// String propertyvalue="default";
// String filepath="";
//
// //filepath = "D:\\MYDATA\\ISO_AUTOMATION\\Otonom\\Config\\
config.properties";
// filepath = "src\\main\\resources\\config.properties";
// try {
// fileread = new FileReader(filepath);
//
// Properties prop = new Properties();
// prop.load(fileread);
// propertyvalue = prop.getProperty(propertyname);
// }
// catch(FileNotFoundException e)
// {
// System.out.println("Exception caught: "+e.getMessage());
// }
//
// return propertyvalue;
//
// }

public static String readProperty(String propertyname) throws IOException {


FileReader fileread;
String propertyvalue = "default";
String filepath = "";

filepath = "D:\\Otonom\\Config\\config.properties";
try {
fileread = new FileReader(filepath);

Properties prop = new Properties();


prop.load(fileread);
propertyvalue = prop.getProperty(propertyname);
} catch (FileNotFoundException e) {
System.out.println("Exception caught: " + e.getMessage());
}

return propertyvalue;

run time property:


package Utilities;

import java.util.HashMap;
import java.util.Map;

public class RunTimeProperties {

private static Map<String, String> propertyMap;

static {
propertyMap = new HashMap<String, String>();
}

public static void setProperty(String key,String value){


propertyMap.put(key, value);
}

public static String getProperty(String key){


return propertyMap.get(key);
}

application.property
#-----------------------------------------------------------------------
PostgresCofig------------------------
#----------------------Integration-------------

STUB_SCHEMA_NAME=iso_dev1
POSTGRES_URL=jdbc:postgresql://10.197.12.130:5432/cibciso
POSTGRES_dBUsername=cibciso
POSTGRES_dBUserPass=ISOdit@2022

#chrome_driver_path=D:\\MYDATAA\\Softwares\\chromedriver\\chromedriver.exe
#otonom_home=D:\\MYDATAA\\ISO_AUTOMATION\\Otonom\\
#config_file_name=shakedown.xlsx
config_file_name=Otonom_sanity_sheet.xlsx

browser=chrome
browser=firefox

#screenshot_location=D:\\MYDATAA\\ISO_AUTOMATION\\Otonom\\reports

config.property

##chrome_driver_path=D:\\project_workspace\\ISO_automation_3_sept\\
chromedriver_win32\\chromedriver.exe
##otonom_home=D:\\Otonom\\
##config_file_name=Otonom_sanity_sheet.xlsx
##browser=chrome
#
##-----------------------------------------------------------------------
PostgresCofig------------------------
##----------------------Integration-------------
##STUB_SCHEMA_NAME=digipay
##POSTGRES_URL=jdbc:postgresql://18.222.93.56:5432/igtb_k1_irel_fo
##POSTGRES_dBUsername=igtbk1irel_ro
##POSTGRES_dBUserPass=igtbk1irel_ro
#
#
#
#STUB_SCHEMA_NAME=digipay_iso
#POSTGRES_URL=jdbc:postgresql://10.197.12.75:5432/testdb
#POSTGRES_dBUsername=testdb
#POSTGRES_dBUserPass=testdb

log4j.property
name=PropertiesConfig
property.filename = logs
appenders = 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}/logResult.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} -
%msg%n
appender.file.append=true

loggers=file
logger.file.name=com.intellect.digipay.otonom
logger.file.level = trace
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

rootLogger.level = trace
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

You might also like