Search in sources :

Example 26 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project DSpace by DSpace.

the class V7_0_2020_10_31__CollectionCommunity_Metadata_Handle method migrate.

@Override
public void migrate(Context context) throws Exception {
    HandleService handleService = DSpaceServicesFactory.getInstance().getServiceManager().getServicesByType(HandleService.class).get(0);
    String dbtype = DatabaseUtils.getDbType(context.getConnection());
    String sqlMigrationPath = "org/dspace/storage/rdbms/sqlmigration/metadata/" + dbtype + "/";
    String dataMigrateSQL = MigrationUtils.getResourceAsString(sqlMigrationPath + "V7.0_2020.10.31__CollectionCommunity_Metadata_Handle.sql");
    // Replace ${handle.canonical.prefix} variable in SQL script with value from Configuration
    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("handle.canonical.prefix", handleService.getCanonicalPrefix());
    StringSubstitutor sub = new StringSubstitutor(valuesMap);
    dataMigrateSQL = sub.replace(dataMigrateSQL);
    DatabaseUtils.executeSql(context.getConnection(), dataMigrateSQL);
    migration_file_size = dataMigrateSQL.length();
}
Also used : HashMap(java.util.HashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor) HandleService(org.dspace.handle.service.HandleService)

Example 27 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project Insights by CognizantOneDevOps.

the class WebhookEventProcessing method doEvent.

public boolean doEvent() {
    // Check if it has webhook event
    List<Boolean> status = new ArrayList<>();
    if (!eventPayload.get(0).has("webhookEvent")) {
        log.error("Webhook event processing ===== webhookEvent property not present in webhook response for webhook {}", webhookConfig.getWebHookName());
        return true;
    }
    String event = eventPayload.get(0).get("webhookEvent").getAsString();
    JsonObject eventJson = eventConfigMap.get(event);
    if (eventJson == null) {
        log.error("Webhook event processing ===== webhookEvent or query property not present in event processing config json {}", eventConfigMap);
        return true;
    }
    Map<String, String> keyValuesMap = getKeyValues();
    StringSubstitutor substitutor = new StringSubstitutor(keyValuesMap, "{", "}");
    JsonArray queryArray = eventJson.get("query").getAsJsonArray();
    for (JsonElement element : queryArray) {
        String rawquery = element.getAsString();
        String query = substitutor.replace(rawquery);
        status.add(executeQuery(query));
    }
    return !status.contains(Boolean.FALSE);
}
Also used : JsonArray(com.google.gson.JsonArray) StringSubstitutor(org.apache.commons.text.StringSubstitutor) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject)

Example 28 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project Insights by CognizantOneDevOps.

the class ReportEmailSubscriber method updateEmailHistoryWithEmailTemplateValues.

/**
 * Method to update values in Email History table
 *
 * @param incomingTaskMessage
 * @param emailTemplate
 * @return
 */
private MailReport updateEmailHistoryWithEmailTemplateValues(JsonObject incomingTaskMessage, InsightsEmailTemplates emailTemplate) {
    try {
        workflowId = incomingTaskMessage.get(AssessmentReportAndWorkflowConstants.WORKFLOW_ID).getAsString();
        executionId = incomingTaskMessage.get(AssessmentReportAndWorkflowConstants.EXECUTIONID).getAsLong();
        InsightsWorkflowConfiguration workflowConfig = workflowDAL.getWorkflowConfigByWorkflowId(workflowId);
        Map<String, String> valuesMap = new HashMap<>();
        if (workflowConfig.getAssessmentConfig() != null) {
            valuesMap.put("ReportDisplayName", workflowConfig.getAssessmentConfig().getAsseementReportDisplayName());
        }
        valuesMap.put("TimeOfReportGeneration", InsightsUtils.specficTimeFormat(executionId, "yyyy-MM-dd"));
        valuesMap.put("Schedule", workflowConfig.getScheduleType());
        StringSubstitutor sub = new StringSubstitutor(valuesMap, "{", "}");
        InsightsReportVisualizationContainer emailHistoryConfig = workflowDAL.getEmailExecutionHistoryByExecutionId(incomingTaskMessage.get(AssessmentReportAndWorkflowConstants.EXECUTIONID).getAsLong());
        if (emailHistoryConfig != null) {
            emailHistoryConfig.setMailFrom(emailTemplate.getMailFrom());
            emailHistoryConfig.setMailTo(emailTemplate.getMailTo());
            emailHistoryConfig.setMailCC(emailTemplate.getMailCC());
            emailHistoryConfig.setMailBCC(emailTemplate.getMailBCC());
            if (emailHistoryConfig.getMailBody() == null) {
                emailHistoryConfig.setMailBody(sub.replace(emailTemplate.getMailBody()));
            }
            emailHistoryConfig.setSubject(sub.replace(emailTemplate.getSubject()));
            emailHistoryConfig.setStatus(WorkflowTaskEnum.EmailStatus.IN_PROGRESS.toString());
            emailHistoryConfig.setMailId(emailTemplate.getId());
            workflowDAL.updateEmailExecutionHistory(emailHistoryConfig);
            return collectInfoFromDataBase(incomingTaskMessage, emailHistoryConfig);
        } else {
            throw new InsightsJobFailedException("No record found in Email History table");
        }
    } catch (InsightsJobFailedException e) {
        throw new InsightsJobFailedException(e.getMessage());
    } catch (Exception e) {
        log.error("Workflow Detail ==== ReportEmailSubscriber Incorrect email format found ===== ", e);
        throw new InsightsJobFailedException("Error while updating values to Email History ");
    }
}
Also used : InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) InsightsReportVisualizationContainer(com.cognizant.devops.platformdal.assessmentreport.InsightsReportVisualizationContainer) HashMap(java.util.HashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor) InsightsWorkflowConfiguration(com.cognizant.devops.platformdal.workflow.InsightsWorkflowConfiguration) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) AddressException(javax.mail.internet.AddressException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 29 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project Insights by CognizantOneDevOps.

the class SystemNotificationDetailSubscriber method handleTaskExecution.

@Override
public void handleTaskExecution(byte[] body) throws IOException {
    try {
        long startTime = System.nanoTime();
        String incomingTaskMessage = new String(body, StandardCharsets.UTF_8);
        JsonObject incomingTaskMessageJson = JsonUtils.parseStringAsJsonObject(incomingTaskMessage);
        String workflowId = incomingTaskMessageJson.get("workflowId").getAsString();
        executionId = incomingTaskMessageJson.get("executionId").getAsLong();
        workflowConfig = workflowDAL.getWorkflowConfigByWorkflowId(workflowId);
        String htmlDataComponentResponseBuffer = componentHTML(healthUtil.getDataComponentStatus(), "Data Component");
        String htmlServiceResponseBuffer = componentHTML(healthUtil.getServiceStatus(), "Services");
        String htmlAgentResponseBuffer = getAgentHTML();
        Map<String, String> idDataMap = new LinkedHashMap<>();
        idDataMap.put("table_agent", htmlAgentResponseBuffer);
        idDataMap.put("table_services", htmlServiceResponseBuffer);
        idDataMap.put("table_data_components", htmlDataComponentResponseBuffer);
        String mailHTML = createEmailHTML(idDataMap);
        Map<String, String> valuesMap = new HashMap<>();
        valuesMap.put("date", InsightsUtils.specficTimeFormat(incomingTaskMessageJson.get("executionId").getAsLong(), "yyyy-MM-dd"));
        StringSubstitutor sub = new StringSubstitutor(valuesMap, "{", "}");
        mailHTML = sub.replace(mailHTML);
        setDetailsInEmailHistory(incomingTaskMessageJson, mailHTML);
        InsightsStatusProvider.getInstance().createInsightStatusNode("SystemNotificationDetailSubscriber completed", PlatformServiceConstants.SUCCESS);
        long processingTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
        log.debug("Type=TaskExecution  executionId={} workflowId={} ConfigId={} WorkflowType={} KpiId={} Category={} ProcessingTime={} message={}", executionId, workflowConfig.getWorkflowId(), "-", workflowConfig.getWorkflowType(), "-", "-", processingTime, "-");
    } catch (InsightsJobFailedException ijfe) {
        log.error("Worlflow Detail ==== SystemNotificationDetail Subscriber Completed with error ", ijfe);
        InsightsStatusProvider.getInstance().createInsightStatusNode("SystemNotificationDetail Completed with error " + ijfe.getMessage(), PlatformServiceConstants.FAILURE);
        log.error("Type=TaskExecution  executionId={} workflowId={} ConfigId={} WorkflowType={} KpiId={} Category={} ProcessingTime={} message={}", executionId, workflowConfig.getWorkflowId(), "-", workflowConfig.getWorkflowType(), "-", "-", 0, workflowConfig.getStatus() + "SystemNotificationDetail Subscriber Completed with error" + ijfe.getMessage());
        statusLog = ijfe.getMessage();
        throw ijfe;
    } catch (Exception e) {
        log.error("Worlflow Detail ==== SystemNotificationDetail Subscriber Completed with error ", e);
        InsightsStatusProvider.getInstance().createInsightStatusNode("SystemNotificationDetail Completed with error " + e.getMessage(), PlatformServiceConstants.FAILURE);
        log.error("Type=TaskExecution  executionId={} workflowId={} ConfigId={} WorkflowType={} KpiId={} Category={} ProcessingTime={} message={}", executionId, workflowConfig.getWorkflowId(), "-", workflowConfig.getWorkflowType(), "-", "-", 0, workflowConfig.getStatus() + "SystemNotificationDetail Subscriber Completed with error" + e.getMessage());
        throw new InsightsJobFailedException(e.getMessage());
    }
}
Also used : InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor) JsonObject(com.google.gson.JsonObject) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap)

Example 30 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project Insights by CognizantOneDevOps.

the class BaseContentCategoryImpl method getContentText.

/**
 * Prepare content text based on kpi result property
 *
 * @param key
 * @param resultValuesMap
 * @return
 * @throws InsightsCustomException
 */
public String getContentText(String key, Map<String, Object> resultValuesMap) {
    String contentText = null;
    try {
        String messageConfigText = "";
        resultValuesMap = resultValuesMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> getResultValueForDisplay(e.getValue())));
        StringSubstitutor sub = new StringSubstitutor(resultValuesMap, "{", "}");
        JsonObject valueMessageObject = JsonUtils.parseStringAsJsonObject(String.valueOf(contentConfigDefinition.getMessage()));
        JsonElement messageInference = valueMessageObject.get(key);
        if (messageInference != null) {
            messageConfigText = messageInference.getAsString();
        } else if (key.equalsIgnoreCase(ReportEngineUtils.NEUTRAL_MESSAGE_KEY)) {
            log.error("Worlflow Detail ==== In Content,No data found for content {} ", contentConfigDefinition.getContentName());
            messageConfigText = "No data found for content  - " + contentConfigDefinition.getContentName();
        } else {
            log.error("Worlflow Detail ==== In Content, Error while getting message text for key{}] ", key);
            messageConfigText = "No message found for content  - " + contentConfigDefinition.getContentName();
        }
        contentText = sub.replace(messageConfigText);
    } catch (Exception e) {
        log.error("Worlflow Detail ==== In Content, Error while getting contentText  ", e);
    }
    return contentText;
}
Also used : StringSubstitutor(org.apache.commons.text.StringSubstitutor) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) InsightsJobFailedException(com.cognizant.devops.platformreports.exception.InsightsJobFailedException) InsightsCustomException(com.cognizant.devops.platformcommons.exception.InsightsCustomException)

Aggregations

StringSubstitutor (org.apache.commons.text.StringSubstitutor)71 HashMap (java.util.HashMap)24 Test (org.junit.jupiter.api.Test)19 IOException (java.io.IOException)11 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)9 File (java.io.File)8 List (java.util.List)8 InputStream (java.io.InputStream)6 Collectors (java.util.stream.Collectors)6 StringLookup (org.apache.commons.text.lookup.StringLookup)6 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)6 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)5 SubstitutingSourceProvider (io.dropwizard.configuration.SubstitutingSourceProvider)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 MetricRegistry (com.codahale.metrics.MetricRegistry)4 JsonObject (com.google.gson.JsonObject)4 URL (java.net.URL)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Scanner (java.util.Scanner)4