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;
}
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;
}
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);
}
}
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()));
}
}
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;
}
}
Aggregations