Search in sources :

Example 61 with StringSubstitutor

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

the class QueryTemplate method generateSQL.

public SqlStatement generateSQL(Query<?> query, Map<String, Object> params) {
    String select = this.getSelect();
    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 preppedSelectClause = literalSubstitution.replace(select);
    preppedSelectClause = sub.replace(preppedSelectClause);
    String preppedWhereClause = literalSubstitution.replace(this.getWhere());
    preppedWhereClause = sub.replace(preppedWhereClause);
    StringBuilder buff = new StringBuilder();
    preppedSelectClause = stripWhere(preppedSelectClause);
    boolean hasWhereKeyword = false;
    buff.append(preppedSelectClause);
    if (!StringUtils.isEmpty(preppedWhereClause)) {
        hasWhereKeyword = true;
        buff.append(" WHERE ");
        buff.append(preppedWhereClause);
    }
    boolean firstIncluded = true;
    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;
            }
            if (query.isUseAnd() || firstIncluded) {
                buff.append(" AND (");
            } else {
                buff.append(" OR (");
            }
            buff.append(preppedOptionalWhereClause);
            buff.append(")");
            keys.addAll(optionalWhereClauseKeys);
        }
        if (shouldInclude) {
            firstIncluded = false;
        }
    }
    splitTooManyValuesInClause(query, params, buff);
    if (!StringUtils.isEmpty(this.getGroupBy())) {
        buff.append(" GROUP BY ");
        buff.append(this.getGroupBy());
    }
    if (!StringUtils.isEmpty(this.getOrderBy())) {
        buff.append(" ORDER BY ");
        buff.append(this.getOrderBy());
    }
    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 62 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project xm-ms-entity by xm-online.

the class SimpleTemplateProcessor method processTemplate.

@SneakyThrows
public String processTemplate(String template, Object object) {
    String json = objectMapper.writeValueAsString(object);
    DocumentContext document = JsonPath.using(defaultConfiguration().addOptions(SUPPRESS_EXCEPTIONS)).parse(json);
    StringSubstitutor sub = new StringSubstitutor();
    sub.setVariableResolver(key -> {
        String defaultValue = "";
        if (key.contains(":")) {
            defaultValue = key.split(":")[1];
        }
        return String.valueOf(firstNonNull((Object) document.read(key), defaultValue));
    });
    String result = sub.replace(template);
    log.debug("Template {}, params {}, result {}", template, json, result);
    return result;
}
Also used : StringSubstitutor(org.apache.commons.text.StringSubstitutor) DocumentContext(com.jayway.jsonpath.DocumentContext) SneakyThrows(lombok.SneakyThrows)

Example 63 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project jib by google.

the class BuildFiles method toBuildFileSpec.

/**
 * Read a build file from disk and apply templating parameters.
 */
private static BuildFileSpec toBuildFileSpec(Path buildFilePath, Map<String, String> templateParameters) throws IOException {
    ObjectMapper yamlObjectMapper = new ObjectMapper(new YAMLFactory());
    StringSubstitutor templater = new StringSubstitutor(templateParameters).setEnableUndefinedVariableException(true);
    try (StringSubstitutorReader reader = new StringSubstitutorReader(Files.newBufferedReader(buildFilePath, Charsets.UTF_8), templater)) {
        return yamlObjectMapper.readValue(reader, BuildFileSpec.class);
    }
}
Also used : StringSubstitutorReader(org.apache.commons.text.io.StringSubstitutorReader) StringSubstitutor(org.apache.commons.text.StringSubstitutor) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 64 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project bdp-core by noi-techpark.

the class PropertiesWithEnv method substitueEnv.

public void substitueEnv() {
    Map<String, String> environment = new HashMap<>(localEnv);
    environment.putAll(System.getenv());
    StringSubstitutor sub = new StringSubstitutor(environment);
    sub.setEnableUndefinedVariableException(true);
    sub.setValueDelimiter(":");
    for (Entry<Object, Object> entry : super.entrySet()) {
        entry.setValue(sub.replace(entry.getValue()));
    }
}
Also used : HashMap(java.util.HashMap) StringSubstitutor(org.apache.commons.text.StringSubstitutor)

Example 65 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project SORMAS-Project by hzi-braunschweig.

the class GeocodingService method getLatLon.

private GeoLatLon getLatLon(LocationQuery query, String urlTemplate) {
    StringSubstitutor substitutor = new StringSubstitutor(buildQuerySubstitutions(query));
    String url = substitutor.replace(urlTemplate);
    URI targetUrl;
    try {
        targetUrl = new URIBuilder(url).build();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
    Client client = ClientHelper.newBuilderWithProxy().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).build();
    WebTarget target = client.target(targetUrl);
    Response response = null;
    // prevent timeouts on invalid addresses from causing errors
    try {
        response = target.request(MediaType.APPLICATION_JSON_TYPE).get();
    } catch (ProcessingException exception) {
        if (logger.isWarnEnabled()) {
            logger.warn("geosearch query '{}' threw Exception with cause {}", query, exception.getCause().toString());
        }
        return null;
    }
    String responseText = readResponseAsText(response);
    if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
        if (logger.isErrorEnabled()) {
            logger.error("geosearch query '{}' returned {} - {}:\n{}", query, response.getStatus(), response.getStatusInfo(), responseText);
        }
        return null;
    }
    Object jsonLatitude = null;
    Object jsonLongitude = null;
    // JsonPath.read sometimes returns Integer that can't be casted to double, @see #6506
    try {
        jsonLatitude = JsonPath.read(responseText, configFacade.getGeocodingLatitudeJsonPath());
        Double latitude = jsonLatitude != null ? Double.parseDouble(jsonLatitude.toString()) : null;
        jsonLongitude = JsonPath.read(responseText, configFacade.getGeocodingLongitudeJsonPath());
        Double longitude = jsonLongitude != null ? Double.parseDouble(jsonLongitude.toString()) : null;
        return new GeoLatLon(latitude, longitude);
    } catch (PathNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("geosearch coordinates not found in '{}'" + responseText);
        }
        return null;
    } catch (NumberFormatException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("geosearch coordinates can't be parsed: lat: {}, lon: {}", jsonLatitude, jsonLongitude);
        }
        return null;
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) Response(javax.ws.rs.core.Response) StringSubstitutor(org.apache.commons.text.StringSubstitutor) WebTarget(javax.ws.rs.client.WebTarget) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) Client(javax.ws.rs.client.Client) ProcessingException(javax.ws.rs.ProcessingException) GeoLatLon(de.symeda.sormas.api.geo.GeoLatLon)

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