Search in sources :

Example 16 with InsightsJobFailedException

use of com.cognizant.devops.platformreports.exception.InsightsJobFailedException in project Insights by CognizantOneDevOps.

the class PDFExecutionSubscriber method updateFailedTaskStatusLog.

private void updateFailedTaskStatusLog(List<JsonObject> failedJobs, InsightsAssessmentConfigurationDTO assessmentReportDTO) {
    JsonObject statusObject = new JsonObject();
    JsonArray kpiArray = new JsonArray();
    for (JsonObject failedJob : failedJobs) {
        if (failedJob.has(AssessmentReportAndWorkflowConstants.KEYARRAY)) {
            failedJob.get(AssessmentReportAndWorkflowConstants.KEYARRAY).getAsJsonArray().forEach(id -> kpiArray.add(id));
        }
    }
    statusObject.addProperty("executionId", assessmentReportDTO.getExecutionId());
    statusObject.addProperty(AssessmentReportAndWorkflowConstants.WORKFLOW_ID, assessmentReportDTO.getWorkflowId());
    statusObject.add("kpiList", kpiArray);
    // statusLog set here which is class variable of WorkflowTaskSubscriberHandler
    statusLog = new Gson().toJson(statusObject);
    log.error("Worlflow Detail ==== some of the Kpi's visualization is failed to execute statusLog {} ", statusLog);
    log.error("Type=TaskExecution  executionId={} workflowId={} ConfigId={} WorkflowType={} KpiId={} Category={} ProcessingTime={} message={}", assessmentReportDTO.getExecutionId(), assessmentReportDTO.getWorkflowId(), assessmentReportDTO.getConfigId(), "-", "-", "-", 0, "reportId: " + assessmentReportDTO.getReportId() + "reportName: " + assessmentReportDTO.getReportName() + "VisualizationUtil" + assessmentReportDTO.getVisualizationutil() + "some of the Kpi's visualization is failed to execute");
    throw new InsightsJobFailedException("Worlflow Detail ==== some of the Kpi's visualization is failed to execute");
}
Also used : JsonArray(com.google.gson.JsonArray) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson)

Example 17 with InsightsJobFailedException

use of com.cognizant.devops.platformreports.exception.InsightsJobFailedException in project Insights by CognizantOneDevOps.

the class GrafanaPDFHandler method updateLogoImgInHeaderTemplate.

/**
 * Method use to fetch Logo Image from database or filesystem and update in header template.
 *
 * @return
 */
private String updateLogoImgInHeaderTemplate(Boolean isFrontPage) {
    try {
        String headerContent = fetchTemplate(HEADER_HTML);
        StringBuilder headerTemplate = new StringBuilder(headerContent);
        byte[] image = null;
        Icon logoEntity = new IconDAL().fetchEntityData("logo");
        if (logoEntity.getImage() != null) {
            image = logoEntity.getImage();
        } else {
            InputStream imageStream = new FileInputStream(new File(LOGO_IMAGE_PATH).getCanonicalPath());
            image = IOUtils.toByteArray(imageStream);
        }
        StringBuilder imageTag = new StringBuilder();
        imageTag.append("src=\"data:image/webp;base64,").append(Base64.getEncoder().encodeToString(image)).append("\" alt=\"OneDevOps\" ");
        int index = headerTemplate.indexOf("<img");
        headerTemplate.insert(index + 5, imageTag);
        if (Boolean.FALSE.equals(isFrontPage)) {
            String titleSpan = "<span style=\"padding-left: 15%;\" float: middle;>" + pdfconfigDto.getTitle() + "</span>";
            int titleIndex = headerTemplate.indexOf("</div>");
            headerTemplate.insert(titleIndex, titleSpan);
        }
        return headerTemplate.toString();
    } catch (Exception e) {
        log.error("Workflow Detail ==== Error while updating logo image in header template  ", e);
        throw new InsightsJobFailedException(e.getMessage());
    }
}
Also used : IconDAL(com.cognizant.devops.platformdal.icon.IconDAL) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Icon(com.cognizant.devops.platformdal.icon.Icon) File(java.io.File) FileInputStream(java.io.FileInputStream) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) IOException(java.io.IOException)

Example 18 with InsightsJobFailedException

use of com.cognizant.devops.platformreports.exception.InsightsJobFailedException in project Insights by CognizantOneDevOps.

the class GrafanaPDFHandler method saveHtmlFile.

/**
 * Method to save Html File.
 *
 * @param fileName
 * @param fileContent
 */
private void saveHtmlFile(String fileName, StringBuilder fileContent) {
    PrintWriter printWriter = null;
    try (FileWriter fileWriter = new FileWriter(fileName)) {
        printWriter = new PrintWriter(fileWriter);
        printWriter.print(fileContent);
    } catch (Exception e) {
        log.error("Workflow Detail ==== Error while saving Html file  ", e);
        throw new InsightsJobFailedException(e.getMessage());
    } finally {
        if (printWriter != null) {
            printWriter.close();
        }
    }
}
Also used : InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) FileWriter(java.io.FileWriter) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Example 19 with InsightsJobFailedException

use of com.cognizant.devops.platformreports.exception.InsightsJobFailedException 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());
        }
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) PdfOptions(com.microsoft.playwright.Page.PdfOptions) Page(com.microsoft.playwright.Page) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) BrowserType(com.microsoft.playwright.BrowserType) BrowserContext(com.microsoft.playwright.BrowserContext) NavigateOptions(com.microsoft.playwright.Page.NavigateOptions) ElementHandle(com.microsoft.playwright.ElementHandle) Playwright(com.microsoft.playwright.Playwright) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) LaunchOptions(com.microsoft.playwright.BrowserType.LaunchOptions) JsonElement(com.google.gson.JsonElement) File(java.io.File) Browser(com.microsoft.playwright.Browser) Margin(com.microsoft.playwright.options.Margin)

Example 20 with InsightsJobFailedException

use of com.cognizant.devops.platformreports.exception.InsightsJobFailedException in project Insights by CognizantOneDevOps.

the class GrafanaPDFHandler method generatePDF.

@Override
public void generatePDF(InsightsAssessmentConfigurationDTO assessmentReportDTO) {
    try {
        createPDFDirectory(assessmentReportDTO);
        preparePDFDTO(assessmentReportDTO);
        prepareAndExportPDFFile(assessmentReportDTO);
    } catch (Exception e) {
        log.error(e);
        throw new InsightsJobFailedException(e.getMessage());
    }
}
Also used : InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) IOException(java.io.IOException)

Aggregations

InsightsJobFailedException (com.cognizant.devops.platformreports.exception.InsightsJobFailedException)63 IOException (java.io.IOException)31 JsonObject (com.google.gson.JsonObject)29 InsightsCustomException (com.cognizant.devops.platformcommons.exception.InsightsCustomException)21 ArrayList (java.util.ArrayList)16 File (java.io.File)14 JsonArray (com.google.gson.JsonArray)12 HashMap (java.util.HashMap)11 InsightsKPIResultDetails (com.cognizant.devops.platformreports.assessment.datamodel.InsightsKPIResultDetails)8 List (java.util.List)8 InsightsContentDetail (com.cognizant.devops.platformreports.assessment.datamodel.InsightsContentDetail)7 ReportEngineEnum (com.cognizant.devops.platformreports.assessment.util.ReportEngineEnum)7 ExecutionException (java.util.concurrent.ExecutionException)7 ContentConfigDefinition (com.cognizant.devops.platformreports.assessment.datamodel.ContentConfigDefinition)6 InsightsAssessmentConfigurationDTO (com.cognizant.devops.platformreports.assessment.datamodel.InsightsAssessmentConfigurationDTO)5 FileNotFoundException (java.io.FileNotFoundException)5 NoSuchFileException (java.nio.file.NoSuchFileException)5 Map (java.util.Map)5 InsightsContentConfig (com.cognizant.devops.platformdal.assessmentreport.InsightsContentConfig)4 InsightsReportVisualizationContainer (com.cognizant.devops.platformdal.assessmentreport.InsightsReportVisualizationContainer)4