Search in sources :

Example 21 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project component-runtime by Talend.

the class ApiMockUpdate method capture.

private static CompletableFuture<Void> capture(final Map<String, byte[]> files, final Executor executor, final String path, final String base, final Map<String, String> templates, final Function<WebTarget, byte[]> target) {
    return CompletableFuture.runAsync(() -> {
        final String outputPath = new StringSubstitutor(templates, "{", "}").replace(path);
        log.info("Trying to grab {}", outputPath);
        final Client client = ClientBuilder.newClient();
        try {
            WebTarget webTarget = client.target(base).path(path);
            for (final Map.Entry<String, String> tpl : templates.entrySet()) {
                webTarget = webTarget.resolveTemplate(tpl.getKey(), tpl.getValue());
            }
            webTarget.property("http.connection.timeout", 30000L).property("http.receive.timeout", 60000L);
            files.put(outputPath, target.apply(webTarget));
            log.info("Grabbed to grab {}", outputPath);
        } catch (final ProcessingException | WebApplicationException ex) {
            log.error("Error on {}", outputPath, ex);
            throw ex;
        } finally {
            client.close();
        }
    }, executor);
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) StringSubstitutor(org.apache.commons.text.StringSubstitutor) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) HashMap(java.util.HashMap) Map(java.util.Map) Collections.emptyMap(java.util.Collections.emptyMap) ProcessingException(javax.ws.rs.ProcessingException)

Example 22 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project cos-fleetshard by bf2fc6cc711aee1a0c2a.

the class ConnectorContext method resolvePlaceholders.

public String resolvePlaceholders(String in) {
    Map<String, Object> properties = new HashMap<>();
    properties.put(COS_OPERATORS_NAMESPACE, cosCtx.getOperatorsNamespace());
    properties.put(COS_CONNECTORS_NAMESPACE, cosCtx.getConnectorsNamespace());
    properties.put(COS_CLUSTER_ID, clusterId());
    properties.put(COS_OPERATOR_ID, operatorId());
    properties.put(COS_OPERATOR_VERSION, operatorVersion());
    properties.put(COS_DEPLOYMENT_ID, connector().getSpec().getDeploymentId());
    properties.put(COS_DEPLOYMENT_RESOURCE_VERSION, connector().getSpec().getDeployment().getDeploymentResourceVersion());
    properties.put(COS_CONNECTOR_ID, connector().getSpec().getConnectorId());
    properties.put(COS_CONNECTOR_RESOURCE_VERSION, connector().getSpec().getDeployment().getConnectorResourceVersion());
    properties.put(COS_MANAGED_CONNECTOR_NAME, connector().getMetadata().getName());
    properties.put(COS_MANAGED_CONNECTOR_SECRET_NAME, secret().getMetadata().getName());
    return new StringSubstitutor(properties).replace(in);
}
Also used : HashMap(java.util.HashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor)

Example 23 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project openpos-framework by JumpMind.

the class DmlTemplate method generateSQL.

public SqlStatement generateSQL(String sql, Map<String, Object> params) {
    List<String> keys = new ArrayList<>();
    StringSubstitutor literalSubstitution = new StringSubstitutor(new StringLookup() {

        @Override
        public String lookup(String key) {
            Object paramValue = params.get(key);
            return paramValue != null ? paramValue.toString() : "null";
        }
    }, "$${", "}", '\\');
    StringSubstitutor sub = new StringSubstitutor(new StringLookup() {

        @Override
        public String lookup(String key) {
            keys.add(key);
            return ":" + key;
        }
    });
    String preparedSql = literalSubstitution.replace(sql);
    preparedSql = sub.replace(preparedSql);
    String preppedWhereClause = literalSubstitution.replace(this.getWhere());
    preppedWhereClause = sub.replace(preppedWhereClause);
    StringBuilder buff = new StringBuilder();
    preparedSql = stripWhere(preparedSql);
    boolean hasWhereKeyword = false;
    buff.append(preparedSql);
    if (!StringUtils.isEmpty(preppedWhereClause)) {
        hasWhereKeyword = true;
        buff.append(" WHERE ");
        buff.append(preppedWhereClause);
    }
    for (String optionalWhereClause : this.getOptionalWhereClauses()) {
        Set<String> optionalWhereClauseKeys = new LinkedHashSet<>();
        String preppedOptionalWhereClause = literalSubstitution.replace(optionalWhereClause);
        StringSubstitutor optionalSubstitution = new StringSubstitutor(new StringLookup() {

            @Override
            public String lookup(String key) {
                optionalWhereClauseKeys.add(key);
                return ":" + key;
            }
        });
        preppedOptionalWhereClause = optionalSubstitution.replace(preppedOptionalWhereClause);
        boolean shouldInclude = true;
        for (String key : optionalWhereClauseKeys) {
            if (!params.containsKey(key)) {
                shouldInclude = false;
                break;
            }
        }
        if (shouldInclude) {
            if (!hasWhereKeyword) {
                buff.append(" WHERE 1=1 ");
                hasWhereKeyword = true;
            }
            buff.append(" AND (");
            buff.append(preppedOptionalWhereClause);
            buff.append(")");
            keys.addAll(optionalWhereClauseKeys);
        }
    }
    SqlStatement sqlStatement = new SqlStatement();
    sqlStatement.setSql(buff.toString());
    for (String key : keys) {
        Object value = params.get(key);
        if (value == null) {
            value = params.get("*");
            params.put(key, value);
        }
        if (value == null) {
            if (params.containsKey(key)) {
                throw new PersistException(String.format("Required query parameter '%s' was present but the value is null. A value must be provided. Cannot build query: %s", key, sqlStatement.getSql()));
            } else {
                throw new PersistException(String.format("Missing required query parameter '%s'. Cannot build query: %s", key, sqlStatement.getSql()));
            }
        } else if (value instanceof Boolean) {
            boolean bool = (Boolean) value;
            value = bool ? 1 : 0;
            params.put(key, value);
        } else if (value instanceof AbstractTypeCode) {
            value = ((AbstractTypeCode) value).value();
            params.put(key, value);
        }
    }
    if (params != null) {
        params.remove("*");
    }
    sqlStatement.setParameters(params);
    return sqlStatement;
}
Also used : StringLookup(org.apache.commons.text.lookup.StringLookup) SqlStatement(org.jumpmind.pos.persist.SqlStatement) PersistException(org.jumpmind.pos.persist.PersistException) StringSubstitutor(org.apache.commons.text.StringSubstitutor) AbstractTypeCode(org.jumpmind.pos.util.model.AbstractTypeCode)

Example 24 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project cdmlib by cybertaxonomy.

the class AccountSelfManagementService method sendEmail.

/**
 * Uses the {@link StringSubstitutor} as simple template engine.
 * Below named values are automatically resolved, more can be added via the
 * <code>valuesMap</code> parameter.
 *
 * @param userEmail
 *  The TO-address
 * @param userName
 *  Used to set the value for <code>${userName}</code>. Optional, may be null.
 * @param subjectTemplate
 *  A {@link StringSubstitutor} template for the email subject
 * @param bodyTemplate
 *  A {@link StringSubstitutor} template for the email body
 * @param additionalValuesMap
 *  Additional named values for to be replaced in the template strings.
 */
public void sendEmail(String userEmail, String userName, String subjectTemplate, String bodyTemplate, Map<String, String> additionalValuesMap) throws MailException {
    String from = env.getProperty(SendEmailConfigurer.FROM_ADDRESS);
    String dataSourceBeanId = env.getProperty(CdmConfigurationKeys.CDM_DATA_SOURCE_ID);
    String supportEmailAddress = env.getProperty(CdmConfigurationKeys.MAIL_ADDRESS_SUPPORT);
    if (additionalValuesMap == null) {
        additionalValuesMap = new HashedMap<>();
    }
    if (supportEmailAddress != null) {
        additionalValuesMap.put(CdmConfigurationKeys.MAIL_ADDRESS_SUPPORT, supportEmailAddress);
    }
    if (userName != null) {
        additionalValuesMap.put("userName", userName);
    }
    additionalValuesMap.put("dataBase", dataSourceBeanId);
    StringSubstitutor substitutor = new StringSubstitutor(additionalValuesMap);
    // TODO use MimeMessages for better email layout?
    // TODO user Thymeleaf instead for HTML support?
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(userEmail);
    message.setSubject(substitutor.replace(subjectTemplate));
    message.setText(substitutor.replace(bodyTemplate));
    emailSender.send(message);
}
Also used : SimpleMailMessage(org.springframework.mail.SimpleMailMessage) StringSubstitutor(org.apache.commons.text.StringSubstitutor)

Example 25 with StringSubstitutor

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

the class FlywayUpgradeUtils method upgradeFlywayTable.

/**
 * Ensures the Flyway migration history table (FLYWAY_TABLE) is upgraded to the latest version of Flyway safely.
 * <P>
 * Unfortunately, Flyway does not always support skipping major versions (e.g. upgrading directly from Flyway
 * v3.x to 5.x is not possible, see https://github.com/flyway/flyway/issues/2126).
 * <P>
 * While sometimes it's possible to do so, other times you MUST upgrade through each major version. This method
 * ensures we upgrade the Flyway history table through each version of Flyway where deemed necessary.
 *
 * @param flyway initialized/configured Flyway object
 * @param connection current database connection
 */
protected static synchronized void upgradeFlywayTable(Flyway flyway, Connection connection) throws SQLException {
    // Whether the Flyway table needs updating or not
    boolean needsUpgrade = false;
    // if the Flyway migration history table is NOT valid for the current version of Flyway
    try {
        flyway.info();
    } catch (Exception e) {
        // ignore error, but log info statement to say we will try to upgrade to fix problem
        log.info("Flyway table '{}' appears to be outdated. Will attempt to upgrade it automatically. " + "Flyway Exception was '{}'", FLYWAY_TABLE, e.toString());
        needsUpgrade = true;
    }
    if (needsUpgrade) {
        // Get the DSpace version info from the LAST migration run.
        String lastMigration = getCurrentFlywayState(connection);
        // database to be compatible with Flyway 4.2.0 (which can be upgraded directly to Flyway 6.x)
        if (lastMigration.startsWith("5.")) {
            // Based on type of DB, get path to our Flyway 4.x upgrade script
            String dbtype = getDbType(connection);
            String scriptPath = UPGRADE_SCRIPT_PATH + dbtype + "/upgradeToFlyway4x.sql";
            log.info("Attempting to upgrade Flyway table '{}' using script at '{}'", FLYWAY_TABLE, scriptPath);
            // Load the Flyway v4.2.0 upgrade SQL script as a String
            String flywayUpgradeSQL = MigrationUtils.getResourceAsString(scriptPath);
            // As this Flyway upgrade SQL was borrowed from Flyway v4.2.0 directly, it contains some inline
            // variables which need replacing, namely ${schema} and ${table} variables.
            // We'll use the StringSubstitutor to replace those variables with their proper values.
            Map<String, String> valuesMap = new HashMap<>();
            valuesMap.put("schema", getSchemaName(connection));
            valuesMap.put("table", FLYWAY_TABLE);
            StringSubstitutor sub = new StringSubstitutor(valuesMap);
            flywayUpgradeSQL = sub.replace(flywayUpgradeSQL);
            // Run the script to update the Flyway table to be compatible with FLyway v4.x
            executeSql(connection, flywayUpgradeSQL);
        }
        // NOTE: no other DSpace versions require a specialized Flyway upgrade script at this time.
        // DSpace 4 didn't use Flyway. DSpace 6 used Flyway v4, which Flyway v6 can update automatically.
        // After any Flyway table upgrade, we MUST run a Flyway repair() to cleanup migration checksums if needed
        log.info("Repairing Flyway table '{}' after upgrade...", FLYWAY_TABLE);
        flyway.repair();
    }
}
Also used : HashMap(java.util.HashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor) SQLException(java.sql.SQLException)

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