Search in sources :

Example 66 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project jahia by Jahia.

the class SettingsBean method load.

/**
 * This method load and convert properties from the jahia.properties file,
 * and set some variables used by the SettingsBean class.
 */
@Override
public void load() {
    if (properties == null && propertiesFileName != null) {
        properties = new PropertiesManager(propertiesFileName).getPropertiesObject();
    }
    // try to get values from the properties object...
    try {
        detectServer();
        // disk path, url's and context...
        maintenanceMode = getBoolean("maintenanceMode", false);
        sessionExpiryTime = getInt("sessionExpiryTime", 60);
        initPaths();
        // files...
        jahiaFileUploadMaxSize = getLong("jahiaFileUploadMaxSize", 104857600);
        studioMaxDisplayableFileSize = getLong("studioMaxDisplayableFileSize", 1048576);
        characterEncoding = getString("characterEncoding", "UTF-8");
        if (System.getProperty(ZipEntryCharsetDetector.ZIP_ENTRY_ALTERNATIVE_ENCODING) == null) {
            String zipEntryCharsets = getString(ZipEntryCharsetDetector.ZIP_ENTRY_ALTERNATIVE_ENCODING, null);
            if (StringUtils.isNotEmpty(zipEntryCharsets)) {
                System.setProperty(ZipEntryCharsetDetector.ZIP_ENTRY_ALTERNATIVE_ENCODING, zipEntryCharsets);
            }
        }
        // Activation / deactivation of relative URLs, instead of absolute URLs, when generating URL to exit the Admin Menu for example
        useRelativeSiteURLs = getBoolean("useRelativeSiteURLs", false);
        jahiaJCRUserCountLimit = getLong("jahiaJCRUserCountLimit", -1);
        // base URL (schema, host, port) to call the web apps deployer service.
        jahiaWebAppsDeployerBaseURL = getString("jahiaWebAppsDeployerBaseURL", "http://127.0.0.1:8080/manager");
        // multi language default language code property.
        defaultLanguageCode = getString("org.jahia.multilang.default_language_code", "en");
        defaultLocale = LanguageCodeConverters.languageCodeToLocale(defaultLanguageCode);
        considerDefaultJVMLocale = getBoolean("considerDefaultJVMLocale", false);
        considerPreferredLanguageAfterLogin = getBoolean("considerPreferredLanguageAfterLogin", false);
        // mail notification settings...
        mail_maxRegroupingOfPreviousException = getInt("mail_maxRegroupingOfPreviousException", 500);
        isProcessingServer = getBoolean("processingServer", true);
        siteURLPortOverride = getInt("siteURLPortOverride", 0);
        isSiteErrorEnabled = getBoolean("site.error.enabled", false);
        operatingMode = getString("operatingMode", "development");
        productionMode = !"development".equalsIgnoreCase(operatingMode);
        distantPublicationServerMode = "distantPublicationServer".equalsIgnoreCase(operatingMode);
        permanentMoveForVanityURL = getBoolean("permanentMoveForVanityURL", true);
        dumpErrorsToFiles = getBoolean("dumpErrorsToFiles", true);
        ErrorFileDumper.setFileDumpActivated(dumpErrorsToFiles);
        fileDumpMaxRegroupingOfPreviousException = getInt("fileDumpMaxRegroupingOfPreviousException", 500);
        useJstackForThreadDumps = getBoolean("useJstackForThreadDumps", false);
        urlRewriteSeoRulesEnabled = getBoolean("urlRewriteSeoRulesEnabled", false);
        urlRewriteRemoveCmsPrefix = getBoolean("urlRewriteRemoveCmsPrefix", false);
        urlRewriteUseAbsoluteUrls = getBoolean("urlRewriteUseAbsoluteUrls", true);
        disableJsessionIdParameter = getBoolean("disableJsessionIdParameter", true);
        jsessionIdParameterName = getString("jsessionIdParameterName", "jsessionid");
        guestUserResourceModuleName = getString("guestUserResourceModuleName");
        guestUserResourceKey = getString("guestUserResourceKey");
        guestGroupResourceModuleName = getString("guestGroupResourceModuleName");
        guestGroupResourceKey = getString("guestGroupResourceKey");
        fileServletStatisticsEnabled = getBoolean("jahia.fileServlet.statisticsEnabled", false);
        importMaxBatch = getInt("importMaxBatch", 500);
        maxNameSize = getInt("jahia.jcr.maxNameSize", 32);
        expandImportedFilesOnDisk = getBoolean("expandImportedFilesOnDisk", false);
        expandImportedFilesOnDiskPath = getString("expandImportedFilesOnDiskPath", "/tmp");
        accessManagerPathPermissionCacheMaxSize = getInt("accessManagerPathPermissionCacheMaxSize", 100);
        queryApproxCountLimit = getInt("queryApproxCountLimit", 100);
        readOnlyMode = getBoolean("readOnlyMode", false);
        internetExplorerCompatibility = getString("internetExplorerCompatibility", "IE=10");
        atmosphereAsyncSupport = getString("atmosphere.asyncSupport", null);
        useWebsockets = getBoolean("atmosphere.useWebsockets", false);
        areaAutoActivated = getBoolean("area.auto.activated", true);
        moduleSpringBeansWaitingTimeout = getInt("jahia.moduleSpringBeansWaitingTimeout", 5 * 60);
        moduleStartLevel = getInt("jahia.moduleStartLevel", 90);
        jahiaSiteImportScannerInterval = getInt("jahia.site.import.scanner.interval", 1000);
        atmosphereHeartbeatFrequency = getString("jahia.atmosphere.heartbeat", "60");
        String authorizedRedirectHostsStr = getString("authorizedRedirectHosts", null);
        authorizedRedirectHosts = StringUtils.isBlank(authorizedRedirectHostsStr) ? new String[0] : authorizedRedirectHostsStr.trim().split("\\s*,\\s*");
        settings.put("userManagementUserNamePattern", getString("userManagementUserNamePattern", "[\\w\\{\\}\\-]+"));
        settings.put("userManagementGroupNamePattern", getString("userManagementGroupNamePattern", "[\\w\\{\\}\\-]+"));
        settings.put("default_templates_set", getString("default_templates_set"));
        settings.put("legacy.import.externalLink.internationalized", getBoolean("legacy.import.externalLink.internationalized", false));
        settings.put("legacy.import.externalLink.nodeType", getString("legacy.import.externalLink.nodeType", Constants.JAHIANT_EXTERNAL_PAGE_LINK));
        settings.put("legacy.import.externalLink.urlPropertyName", getString("legacy.import.externalLink.urlPropertyName", Constants.URL));
        settings.setFast(true);
        clusterActivated = getBoolean("cluster.activated", false);
        setSystemProperty("cluster.activated", Boolean.toString(clusterActivated));
        if (System.getProperty("cluster.node.serverId") == null) {
            setSystemProperty("cluster.node.serverId", getString("cluster.node.serverId", "jahiaServer1"));
        }
        DatabaseUtils.setDatasource(dataSource);
        initJcrSystemProperties();
        initStartupOptions();
        if (clusterActivated) {
            clusterSettingsInitializer.initClusterSettings(this);
        }
        checkIndexConsistencyIfNeeded();
        reindexIfNeeded();
        readTldConfigJarsToSkip();
        initJerichoLogging();
        initDatabaseIfNeeded();
        if (isProcessingServer()) {
            Patcher.getInstance().executeScripts("contextInitializing");
        }
        // Init String substitutor
        Map<String, StringLookup> l = new HashMap<>();
        l.put("jahia", this::getPropertyValue);
        stringSubstitutor = new StringSubstitutor(StringLookupFactory.INSTANCE.interpolatorStringLookup(l, null, true));
        stringSubstitutor.setEnableSubstitutionInVariables(true);
    } catch (NullPointerException | NumberFormatException e) {
        logger.error("Properties file is not valid...!", e);
    }
}
Also used : PropertiesManager(org.jahia.utils.properties.PropertiesManager) FastHashMap(org.apache.commons.collections.FastHashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor) StringLookup(org.apache.commons.text.lookup.StringLookup)

Example 67 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project MailTrigger by BjoernKW.

the class PlaceholderProcessor method parseInputField.

private String parseInputField(String input, Map<String, String> replacements) {
    if (input != null && input.length() > 0) {
        StringSubstitutor substitutor = new StringSubstitutor(replacements);
        String output = substitutor.replace(input);
        checkForRemainingPlaceholders(output);
        return output;
    }
    return input;
}
Also used : StringSubstitutor(org.apache.commons.text.StringSubstitutor)

Example 68 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project constellation by constellation-app.

the class DataAccessParametersIoProviderNGTest method loadParameters.

@Test
public void loadParameters() throws IOException {
    final DataAccessPane dataAccessPane = mock(DataAccessPane.class);
    final DataAccessTabPane dataAccessTabPane = mock(DataAccessTabPane.class);
    when(dataAccessPane.getDataAccessTabPane()).thenReturn(dataAccessTabPane);
    final QueryPhasePane tab1 = mock(QueryPhasePane.class);
    final QueryPhasePane tab2 = mock(QueryPhasePane.class);
    when(dataAccessTabPane.newTab(anyString())).thenReturn(tab1).thenReturn(tab2);
    final GlobalParametersPane globalParametersPane1 = mock(GlobalParametersPane.class);
    final GlobalParametersPane globalParametersPane2 = mock(GlobalParametersPane.class);
    when(tab1.getGlobalParametersPane()).thenReturn(globalParametersPane1);
    when(tab2.getGlobalParametersPane()).thenReturn(globalParametersPane2);
    // By adding the settings bit here, it forces mockito to generate two different
    // classes. Otherwise they would be two different objects but have the same class name
    final Plugin plugin1 = mock(Plugin.class, withSettings().extraInterfaces(Comparable.class));
    final Plugin plugin2 = mock(Plugin.class, withSettings().extraInterfaces(Serializable.class));
    final DataSourceTitledPane dataSourceTitledPane1 = mock(DataSourceTitledPane.class);
    when(dataSourceTitledPane1.getPlugin()).thenReturn(plugin1);
    final DataSourceTitledPane dataSourceTitledPane2 = mock(DataSourceTitledPane.class);
    when(dataSourceTitledPane2.getPlugin()).thenReturn(plugin2);
    when(tab1.getDataAccessPanes()).thenReturn(List.of(dataSourceTitledPane1, dataSourceTitledPane2));
    when(tab2.getDataAccessPanes()).thenReturn(List.of());
    final PluginParameter pluginParameter1 = mock(PluginParameter.class);
    when(pluginParameter1.getId()).thenReturn("param1");
    final PluginParameter pluginParameter2 = mock(PluginParameter.class);
    when(pluginParameter2.getId()).thenReturn("param2");
    final PluginParameter pluginParameter3 = mock(PluginParameter.class);
    when(pluginParameter3.getId()).thenReturn("param3");
    final PluginParameter pluginParameter4 = mock(PluginParameter.class);
    when(pluginParameter4.getId()).thenReturn("param4");
    final PluginParameters globalPluginParameters1 = new PluginParameters();
    globalPluginParameters1.addParameter(pluginParameter1);
    globalPluginParameters1.addParameter(pluginParameter2);
    globalPluginParameters1.addParameter(pluginParameter3);
    final PluginParameters globalPluginParameters2 = new PluginParameters();
    globalPluginParameters2.addParameter(pluginParameter3);
    globalPluginParameters2.addParameter(pluginParameter4);
    when(globalParametersPane1.getParams()).thenReturn(globalPluginParameters1);
    when(globalParametersPane2.getParams()).thenReturn(globalPluginParameters2);
    try (final MockedStatic<JsonIO> jsonIOStaticMock = Mockito.mockStatic(JsonIO.class)) {
        final ObjectMapper objectMapper = new ObjectMapper();
        final String json = IOUtils.toString(new FileInputStream(getClass().getResource("resources/preferences.json").getPath()), StandardCharsets.UTF_8);
        // We do not know the mockito plugin names ahead of time so substitute them in now
        final StringSubstitutor substitutor = new StringSubstitutor(Map.of("INSERT_PLUGIN1_NAME", plugin1.getClass().getSimpleName(), "INSERT_PLUGIN2_NAME", plugin2.getClass().getSimpleName()));
        final List<DataAccessUserPreferences> preferences = objectMapper.readValue(substitutor.replace(json), new TypeReference<List<DataAccessUserPreferences>>() {
        });
        jsonIOStaticMock.when(() -> JsonIO.loadJsonPreferences(eq(Optional.of("DataAccessView")), any(TypeReference.class))).thenReturn(preferences);
        DataAccessParametersIoProvider.loadParameters(dataAccessPane);
    }
    verify(dataAccessTabPane, times(2)).newTab(anyString());
    // tab1 global parameters
    verify(pluginParameter1).setStringValue("tab1_param1_value");
    verify(pluginParameter3).setStringValue(null);
    // tab1 plugin parameters - only plugin1 because plugin2 is disabled
    verify(dataSourceTitledPane1).setParameterValues(Map.of(plugin1.getClass().getSimpleName() + "." + "__is_enabled__", "true", plugin1.getClass().getSimpleName() + "." + "param1", "plugin1_param1_value"));
    // tab2 global parameters
    verify(pluginParameter4).setStringValue("tab2_param4_value");
    // tab2 plugin parameters
    verify(dataSourceTitledPane2, times(0)).setParameterValues(anyMap());
}
Also used : JsonIO(au.gov.asd.tac.constellation.utilities.genericjsonio.JsonIO) Serializable(java.io.Serializable) DataAccessPane(au.gov.asd.tac.constellation.views.dataaccess.panes.DataAccessPane) QueryPhasePane(au.gov.asd.tac.constellation.views.dataaccess.panes.QueryPhasePane) GlobalParametersPane(au.gov.asd.tac.constellation.views.dataaccess.panes.GlobalParametersPane) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) FileInputStream(java.io.FileInputStream) DataAccessUserPreferences(au.gov.asd.tac.constellation.views.dataaccess.api.DataAccessUserPreferences) DataSourceTitledPane(au.gov.asd.tac.constellation.views.dataaccess.panes.DataSourceTitledPane) DataAccessTabPane(au.gov.asd.tac.constellation.views.dataaccess.components.DataAccessTabPane) StringSubstitutor(org.apache.commons.text.StringSubstitutor) List(java.util.List) PluginParameters(au.gov.asd.tac.constellation.plugins.parameters.PluginParameters) TypeReference(com.fasterxml.jackson.core.type.TypeReference) PluginParameter(au.gov.asd.tac.constellation.plugins.parameters.PluginParameter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Plugin(au.gov.asd.tac.constellation.plugins.Plugin) Test(org.testng.annotations.Test)

Example 69 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project fpl-ccd-configuration by hmcts.

the class OrderDetailsWithEndTypeGenerator method getMonthMessage.

private String getMonthMessage(Map<String, String> context, LocalDateTime orderExpiration, String formatString, Integer numOfMonths, String courtResponsibilityAssignmentMessage, String dayOrdinalSuffix) {
    context.put("endDate", formatLocalDateTimeBaseUsingFormat(orderExpiration, String.format(formatString, dayOrdinalSuffix)));
    context.put("numOfMonths", numOfMonths.toString());
    context.put("decoratedNumberOfMonths", numOfMonths + (numOfMonths > 1 ? " months" : " month"));
    return new StringSubstitutor(context).replace(courtResponsibilityAssignmentMessage);
}
Also used : StringSubstitutor(org.apache.commons.text.StringSubstitutor)

Example 70 with StringSubstitutor

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

the class InsightsKPIProcessor method getQueryBySchedule.

private void getQueryBySchedule(long nextRunTime, WorkflowTaskEnum.WorkflowSchedule schedule, int days, String query, long endTime, List<QueryModel> queryModelList) {
    long startTime = System.nanoTime();
    Map<String, Long> dateReplaceMap = new HashMap<>();
    List<String> neo4jQueries = new ArrayList<>();
    if (days <= 31) {
        int noOfQueries = days;
        long startDate = InsightsUtils.getStartFromTime(nextRunTime, schedule.name()) - 1;
        long endDate = InsightsUtils.addDaysInGivenTime(startDate, 1) - 1;
        if (schedule.name().equalsIgnoreCase("Monthly")) {
            noOfQueries = InsightsUtils.getMonthDays(startDate);
        }
        for (int i = 0; i < noOfQueries; i++) {
            QueryModel qmodel = new QueryModel();
            dateReplaceMap.put(ReportEngineUtils.START_TIME_FIELD, startDate);
            dateReplaceMap.put(ReportEngineUtils.END_TIME_FIELD, endDate);
            StringSubstitutor sub = new StringSubstitutor(dateReplaceMap, "{", "}");
            qmodel.setRecordDate(startDate);
            qmodel.setQuery(sub.replace(query));
            queryModelList.add(qmodel);
            startDate = InsightsUtils.addDaysInGivenTime(startDate, 1);
            endDate = InsightsUtils.addDaysInGivenTime(endDate, 1);
            long processingTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
            log.debug("Type=TaskExecution  executionId={} workflowId={} ConfigId={} WorkflowType={} KpiId={} Category={} ProcessingTime={} message={}", kpiConfigDTO.getExecutionId(), kpiConfigDTO.getWorkflowId(), kpiConfigDTO.getReportId(), "-", kpiConfigDTO.getKpiId(), kpiConfigDTO.getCategory(), processingTime, "queryStartTime: " + startDate + "queryEndTime: " + endDate + "schedule: " + kpiConfigDTO.getSchedule());
        }
    } else {
        int weeks = days / 7;
        long startOfTheDayInWeek = InsightsUtils.getStartFromTime(nextRunTime, schedule.name()) - 1;
        long endDayOfTheWeek = InsightsUtils.addDaysInGivenTime(startOfTheDayInWeek, 7) - 1;
        for (int i = 0; i < weeks; i++) {
            QueryModel qmodel = new QueryModel();
            dateReplaceMap.put(ReportEngineUtils.START_TIME_FIELD, startOfTheDayInWeek);
            dateReplaceMap.put(ReportEngineUtils.END_TIME_FIELD, endDayOfTheWeek);
            StringSubstitutor sub = new StringSubstitutor(dateReplaceMap, "{", "}");
            neo4jQueries.add(sub.replace(query));
            qmodel.setRecordDate(startOfTheDayInWeek);
            qmodel.setQuery(sub.replace(query));
            queryModelList.add(qmodel);
            startOfTheDayInWeek = InsightsUtils.addDaysInGivenTime(startOfTheDayInWeek, 7);
            endDayOfTheWeek = InsightsUtils.addDaysInGivenTime(endDayOfTheWeek, 7);
            if (endDayOfTheWeek > endTime) {
                endDayOfTheWeek = endTime;
            }
            log.debug("Type=TaskExecution  executionId={} workflowId={} ConfigId={} WorkflowType={} KpiId={} Category={} ProcessingTime={} message={}", kpiConfigDTO.getExecutionId(), kpiConfigDTO.getWorkflowId(), kpiConfigDTO.getReportId(), "-", kpiConfigDTO.getKpiId(), kpiConfigDTO.getCategory(), 0, "queryStartTime: " + startOfTheDayInWeek + "queryEndTime: " + endDayOfTheWeek + "schedule: " + kpiConfigDTO.getSchedule());
        }
    }
}
Also used : HashMap(java.util.HashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor) ArrayList(java.util.ArrayList) QueryModel(com.cognizant.devops.platformreports.assessment.datamodel.QueryModel)

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