use of com.microsoft.playwright.BrowserType.LaunchOptions in project Insights by CognizantOneDevOps.
the class GrafanaPDFHandler method printableDashboardAsPdf.
/**
* Generates printable pdf from Grafana dashboard panels.
* @param assessmentReportDTO
* @param grafanaDashboardConfig
* @param incomingTaskMessageJson
* @param exportedFilePath
*/
private synchronized void printableDashboardAsPdf(InsightsAssessmentConfigurationDTO assessmentReportDTO, String exportedFilePath) {
Playwright playwright = null;
try {
playwright = Playwright.create();
long startTime = System.nanoTime();
BrowserType browserType = playwright.chromium();
LaunchOptions launchOptions = new LaunchOptions();
launchOptions.setHeadless(Boolean.TRUE);
launchOptions.setDevtools(Boolean.FALSE);
Browser browser = browserType.launch(launchOptions);
BrowserContext context = browser.newContext();
Page page = context.newPage();
JsonElement config = JsonUtils.parseStringAsJsonElement(pdfconfigDto.getDashboardJson());
int loadTime = config.getAsJsonObject().get("loadTime").getAsInt() * 1000;
log.debug("Worlflow Detail ==== LoadTIme configured for Grafana in milliseconds ===== {} ", loadTime);
String grafanaEndpoint = getGrafanaEndPoint();
log.debug("Worlflow Detail ==== grafanaEndpoint from config ===== {} ", grafanaEndpoint);
JsonArray panelArray = config.getAsJsonObject().get("panelUrls").getAsJsonArray();
List<String> grafanaPanelList = new ArrayList<>(0);
panelArray.forEach(e -> {
String panelUrl = e.getAsString().replace("<GRAFANA_URL>", grafanaEndpoint);
log.debug("Worlflow Detail ==== Panel url ===== {} ", panelUrl);
grafanaPanelList.add(panelUrl);
});
Map<String, String> headers = getGrafanaHeaders(config);
NavigateOptions navigateOptions = new NavigateOptions();
navigateOptions.setWaitUntil(WaitUntilState.NETWORKIDLE);
String dashboardElement = readDashboardElementJson();
log.debug("Worlflow Detail ==== dashboardReportElement.json fetched successfully");
JsonObject dashboardElementJson = JsonUtils.parseStringAsJsonObject(dashboardElement).get("Printable").getAsJsonObject();
JsonArray elementList = dashboardElementJson.get("elements").getAsJsonArray();
List<byte[]> imageList = new ArrayList<>();
for (int idx = 0; idx < grafanaPanelList.size(); idx++) {
page.setExtraHTTPHeaders(headers);
page.waitForTimeout(TRANSITION_TIME);
page.setViewportSize(1200, 800);
page.route("**", route -> route.resume());
page.onRequest(request -> log.debug("Request >> {} {} ", request.method(), request.url()));
page.onResponse(response -> log.debug("Response << {} {} ", response.status(), response.url()));
page.navigate(grafanaPanelList.get(idx), navigateOptions);
Page.WaitForSelectorOptions waitForSelectorOptions = new Page.WaitForSelectorOptions();
waitForSelectorOptions.setState(WaitForSelectorState.ATTACHED);
log.debug("Waiting for panel {} to load completely before screenshot == {} ", idx, Instant.now());
page.waitForTimeout(loadTime);
log.debug("Waiting time completed for dashboard == {} ", Instant.now());
for (JsonElement ele : elementList) {
page.evaluate(ele.getAsString());
}
ElementHandle elementHandle = page.querySelector(dashboardElementJson.get("screenshotElement").getAsString());
page.waitForTimeout(TRANSITION_TIME);
byte[] image = elementHandle.screenshot();
imageList.add(image);
}
String dynamicTemplate = assessmentReportDTO.getPdfReportDirPath() + File.separator + assessmentReportDTO.getAsseementreportname() + "." + ReportEngineUtils.HTML_EXTENSION;
log.debug("Worlflow Detail ==== Generated DynamicTemplate.html name ===== {} ", dynamicTemplate);
prepareHtml(imageList, dynamicTemplate);
page = context.newPage();
page.navigate(new File(dynamicTemplate).getAbsolutePath());
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setPrintBackground(Boolean.TRUE);
pdfOptions.setDisplayHeaderFooter(true);
pdfOptions.setHeaderTemplate(updateLogoImgInHeaderTemplate(false));
pdfOptions.setFooterTemplate(fetchTemplate(FOOTER_HTML));
pdfOptions.setMargin(new Margin().setTop("85").setRight("10").setBottom("5").setLeft("10"));
byte[] dashboardPdf = page.pdf(pdfOptions);
String frontPagePath = assessmentReportDTO.getPdfReportDirPath() + File.separator + MODIFIED_FRONT_PAGE_TEMPLATE;
modifyFrontPageTemplate(frontPagePath);
page = context.newPage();
page.navigate("file:" + new File(frontPagePath).getAbsolutePath());
pdfOptions.setHeaderTemplate(updateLogoImgInHeaderTemplate(true));
pdfOptions.setFooterTemplate(fetchTemplate("frontPagefooter.html"));
byte[] frontPagePdf = page.pdf(pdfOptions);
page.close();
context.close();
browser.close();
byte[] finalPdf = mergePDFFiles(frontPagePdf, dashboardPdf, exportedFilePath);
pdfExecutionUtils.saveToVisualizationContainer(assessmentReportDTO, finalPdf);
long processingTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
log.debug(LOG_MESSAGE, assessmentReportDTO.getExecutionId(), assessmentReportDTO.getWorkflowId(), assessmentReportDTO.getConfigId(), pdfconfigDto.getWorkflowType(), "-", "-", processingTime, PDF_TYPE + pdfconfigDto.getPdfType() + SCHEDULE + pdfconfigDto.getScheduleType() + SOURCE + pdfconfigDto.getSource());
} catch (Exception e) {
log.error("Worlflow Detail ==== Grafana Dashboard export as Printable PDF Completed with error {} ", e.getMessage());
log.error(LOG_MESSAGE, assessmentReportDTO.getExecutionId(), assessmentReportDTO.getWorkflowId(), assessmentReportDTO.getConfigId(), "-", "-", "-", 0, " Grafana Dashboard export as Printable PDF Completed with error " + e.getMessage());
log.error(e);
throw new InsightsJobFailedException(e.getMessage());
} finally {
try {
playwright.close();
} catch (Exception e) {
log.error("Worlflow Detail ==== Unable to close Playwright {} ", e.getMessage());
log.error(LOG_MESSAGE, assessmentReportDTO.getExecutionId(), assessmentReportDTO.getWorkflowId(), assessmentReportDTO.getConfigId(), "-", "-", "-", 0, " Unable to close Playwright " + e.getMessage());
}
}
}
use of com.microsoft.playwright.BrowserType.LaunchOptions in project Insights by CognizantOneDevOps.
the class GrafanaPDFHandler method grafanaDashboardAsPdf.
/**
* Uses playwright to create current url of grafana dashboard as pdf
* @param assessmentReportDTO
* @param grafanaDashboardConfig
* @param incomingTaskMessageJson
* @param exportedFilePath
*/
private void grafanaDashboardAsPdf(InsightsAssessmentConfigurationDTO assessmentReportDTO, String exportedFilePath) {
JsonElement config = JsonUtils.parseStringAsJsonElement(pdfconfigDto.getDashboardJson());
String grafanaEndpoint = getGrafanaEndPoint();
int loadTime = config.getAsJsonObject().get("loadTime").getAsInt() * 1000;
log.debug("Worlflow Detail ==== LoadTIme configured for Grafana in milliseconds ===== {} ", loadTime);
String grafanaUrl = config.getAsJsonObject().get("dashUrl").getAsString().replace("<GRAFANA_URL>", grafanaEndpoint);
log.debug("Worlflow Detail ==== grafanadashboard Url ===== {} ", grafanaUrl);
Playwright playwright = null;
String pageContent = "";
try {
playwright = Playwright.create();
long startTime = System.nanoTime();
BrowserType browserType = playwright.chromium();
LaunchOptions launchOptions = new LaunchOptions();
launchOptions.setHeadless(Boolean.TRUE);
launchOptions.setDevtools(Boolean.FALSE);
Browser browser = browserType.launch(launchOptions);
BrowserContext context = browser.newContext();
Page page = context.newPage();
Map<String, String> headers = getGrafanaHeaders(config);
page.setExtraHTTPHeaders(headers);
page.onRequest(request -> log.debug("Request >> {} {} ", request.method(), request.url()));
page.onResponse(response -> log.debug("Response << {} {} ", response.status(), response.url()));
NavigateOptions navigateOptions = new NavigateOptions();
navigateOptions.setWaitUntil(WaitUntilState.NETWORKIDLE);
page.navigate(grafanaUrl, navigateOptions);
pageContent = page.content();
page.waitForLoadState();
log.debug("Worlflow Detail ==== Waiting for dashboard to load == loadTime {} time {} ", loadTime, Instant.now());
page.waitForTimeout(loadTime);
log.debug("Worlflow Detail ====Waiting exit post configured time to load Dashboard == {} ", Instant.now());
String dashboardElement = readDashboardElementJson();
log.debug("Worlflow Detail ==== reading elements from dashboardReportElement.json");
JsonObject dashboardElementJson = JsonUtils.parseStringAsJsonObject(dashboardElement).get("dashboard").getAsJsonObject();
JsonArray elementList = dashboardElementJson.get("elements").getAsJsonArray();
for (JsonElement ele : elementList) {
page.evaluate(ele.getAsString());
}
Object width = page.evaluate(dashboardElementJson.get("width").getAsString());
log.debug("Worlflow Detail ==== Grafana grid Width ===== {} ", width);
int dashboardwidth = width instanceof Integer ? (int) width + 40 : Integer.parseInt(width.toString());
log.debug("Worlflow Detail ==== Grafana Dashboard width ===== {} ", dashboardwidth);
Object height = page.evaluate(dashboardElementJson.get("height").getAsString());
log.debug("Worlflow Detail ==== Grafana grid height ===== {} ", height);
int dashboardlength = height instanceof Integer ? (int) height + 160 : Integer.parseInt(height.toString());
log.debug("Worlflow Detail ==== Grafana Dashboard length ===== {} ", dashboardlength);
page.evaluate(dashboardElementJson.get("screenshotElement").getAsString());
log.debug("Waiting for dashboard to load completely before screenshot == {} ", Instant.now());
page.waitForTimeout(loadTime);
log.debug("Waiting time completed for dashboard == {} ", Instant.now());
page.waitForLoadState(LoadState.NETWORKIDLE);
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setPrintBackground(Boolean.TRUE);
pdfOptions.setWidth(dashboardwidth + "px");
pdfOptions.setHeight(dashboardlength + "px");
pdfOptions.setScale(1);
pdfOptions.setDisplayHeaderFooter(true);
pdfOptions.setHeaderTemplate(updateLogoImgInHeaderTemplate(false));
pdfOptions.setFooterTemplate(fetchTemplate(FOOTER_HTML));
pdfOptions.setMargin(new Margin().setTop("90").setRight("0").setBottom("50").setLeft("0"));
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN));
byte[] dashboardPdf = page.pdf(pdfOptions);
log.debug("Worlflow Detail ==== dashboard pdf generated ===");
String frontPagePath = assessmentReportDTO.getPdfReportDirPath() + File.separator + MODIFIED_FRONT_PAGE_TEMPLATE;
modifyFrontPageTemplate(frontPagePath);
page = context.newPage();
page.navigate("file:" + new File(frontPagePath).getAbsolutePath());
pdfOptions.setHeaderTemplate(updateLogoImgInHeaderTemplate(true));
pdfOptions.setFooterTemplate(fetchTemplate("frontPagefooter.html"));
pdfOptions.setHeight("1600px");
byte[] frontPagePdf = page.pdf(pdfOptions);
page.close();
context.close();
browser.close();
byte[] finalPdf = mergePDFFiles(frontPagePdf, dashboardPdf, exportedFilePath);
if (Boolean.FALSE.equals(pdfconfigDto.getIsAssessmentReport())) {
pdfExecutionUtils.saveToVisualizationContainer(assessmentReportDTO, finalPdf);
}
long processingTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
log.debug(LOG_MESSAGE, assessmentReportDTO.getExecutionId(), assessmentReportDTO.getWorkflowId(), assessmentReportDTO.getConfigId(), pdfconfigDto.getWorkflowType(), "-", "-", processingTime, PDF_TYPE + pdfconfigDto.getPdfType() + SCHEDULE + pdfconfigDto.getScheduleType() + SOURCE + pdfconfigDto.getSource());
} catch (Exception e) {
log.error("Worlflow Detail ==== Grafana Dashboard export as PDF Completed with error {} ", e.getMessage());
log.error(LOG_MESSAGE, assessmentReportDTO.getExecutionId(), assessmentReportDTO.getWorkflowId(), assessmentReportDTO.getConfigId(), "-", "-", "-", 0, " Grafana Dashboard export as PDF Completed with error " + e.getMessage());
log.error("Dashboard page content ========== {} ", pageContent);
log.error(e);
throw new InsightsJobFailedException(e.getMessage());
} finally {
try {
playwright.close();
} catch (Exception e) {
log.error("Worlflow Detail ==== Unable to close Playwright {} ", e.getMessage());
log.error(LOG_MESSAGE, assessmentReportDTO.getExecutionId(), assessmentReportDTO.getWorkflowId(), assessmentReportDTO.getConfigId(), "-", "-", "-", 0, " Unable to close Playwright " + e.getMessage());
}
}
}
Aggregations