Java Code Examples for org.apache.commons.text.StringSubstitutor#replace()

The following examples show how to use org.apache.commons.text.StringSubstitutor#replace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Discord.java    From Rails with GNU General Public License v2.0 7 votes vote down vote up
public void sendMessage(String player) {
    setConfig();
    if ( webhook == null ) {
        return;
    }
    Map<String, String> keys = new HashMap<>();
    keys.put("game", root.getGameName());
    //keys.put("gameName", StringUtils.defaultIfBlank(root.getGameData().getUsersGameName(), "[none]"));
    keys.put("round", gameUiManager.getCurrentRound().getRoundName());
    keys.put("current", StringUtils.defaultIfBlank(playerNameMappings.get(player), player));
    keys.put("previous", StringUtils.defaultIfBlank(observer.getFormerPlayer().getId(), "[none]"));

    String msgBody = StringSubstitutor.replace(body, keys);
    log.debug("Sending message '{}' to Discord for user {}", msgBody, player);

    HttpPost httpPost = new HttpPost(webhook);
    try {
        httpPost.setEntity(new StringEntity(msgBody));
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPost.setHeader(HttpHeaders.USER_AGENT, "18xx Rails");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if ( response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT ) {
            log.debug("Unexpected Discord  response: {}", response);
        }
        response.close();
    }
    catch (IOException e) {
        log.error("Error sending message to Discord", e);
    }
}
 
Example 2
Source File: BigQueryConverters.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code String} using Key/Value style formatting.
 *
 * @param formatTemplate a String with bracketed keys to apply "I am a {key}"
 * @param row is a TableRow object which is used to supply key:values to the template
 *
 * <p> Extracts TableRow fields and applies values to the formatTemplate.
 * ie. formatStringTemplate("I am {key}"{"key": "formatted"}) -> "I am formatted"
 */
public static String formatStringTemplate(String formatTemplate, TableRow row) {
    // Key/Value Map used to replace values in template
    Map<String, String> values = new HashMap<>();

    // Put all column/value pairs into key/value map
    Set<String> rowKeys = row.keySet();
    for (String rowKey : rowKeys) {
      // Only String types can be used in comparison
      if(row.get(rowKey) instanceof String) {
        values.put(rowKey, (String) row.get(rowKey));
      }
    }
    // Substitute any templated values in the template
    String result = StringSubstitutor.replace(formatTemplate, values, "{", "}");
    return result;
}
 
Example 3
Source File: BuildString.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length < 1) {
		throw new ValueExprEvaluationException("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Literal)) {
		throw new ValueExprEvaluationException("First argument must be a string");
	}
	Literal s = (Literal) args[0];
	String tmpl = s.getLabel();
	Map<String, String> mappings = new HashMap<>(args.length);
	for (int i = 1; i < args.length; i++) {
		mappings.put(Integer.toString(i), args[i].stringValue());
	}
	String newValue = StringSubstitutor.replace(tmpl, mappings, "{?", "}");
	return valueFactory.createLiteral(newValue);
}
 
Example 4
Source File: BigQueryConverters.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Return a formatted String Using Key/Value Style formatting
 * from the TableRow applied to the Format Template.
 * ie. formatStringTemplate("I am {key}"{"key": "formatted"}) -> "I am formatted"
 */
public static String formatStringTemplate(String formatTemplate, TableRow row) {
    // Key/Value Map used to replace values in template
    Map<String, String> values = new HashMap<>();

    // Put all column/value pairs into key/value map
    Set<String> rowKeys = row.keySet();
    for (String rowKey : rowKeys) {
      // Only String types can be used in comparison
      if(row.get(rowKey) instanceof String) {
        values.put(rowKey, (String) row.get(rowKey));
      }
    }
    // Substitute any templated values in the template
    String result = StringSubstitutor.replace(formatTemplate, values, "{", "}");
    return result;
}
 
Example 5
Source File: BuildURI.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length < 1) {
		throw new ValueExprEvaluationException("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Literal)) {
		throw new ValueExprEvaluationException("First argument must be a string");
	}
	Literal s = (Literal) args[0];
	String tmpl = s.getLabel();
	Map<String, String> mappings = new HashMap<>(args.length);
	for (int i = 1; i < args.length; i++) {
		mappings.put(Integer.toString(i), args[i].stringValue());
	}
	String newValue = StringSubstitutor.replace(tmpl, mappings, "{?", "}");
	if (tmpl.charAt(0) == '<' && tmpl.charAt(tmpl.length() - 1) == '>') {
		return valueFactory.createURI(newValue.substring(1, newValue.length() - 1));
	}
	throw new ValueExprEvaluationException("Invalid URI template: " + tmpl);
}
 
Example 6
Source File: SettingsReader.java    From elasticsearch-beyonder with Apache License 2.0 6 votes vote down vote up
/**
 * Read a file content from the classpath
 * @param file filename
 * @return The file content
 */
public static String readFileFromClasspath(String file) {
	logger.trace("Reading file [{}]...", file);
	String content = null;

	try (InputStream asStream = SettingsReader.class.getClassLoader().getResourceAsStream(file)) {
		if (asStream == null) {
			logger.trace("Can not find [{}] in class loader.", file);
			return null;
		}
		content = IOUtils.toString(asStream, "UTF-8");
	} catch (IOException e) {
		logger.warn("Can not read [{}].", file);
	}

	return StringSubstitutor.replace(content, System.getenv());
}
 
Example 7
Source File: AboutDialog.java    From RemoteSupportTool with Apache License 2.0 5 votes vote down vote up
private String replaceVariables(String text) {
    Properties replacements = new Properties();

    replacements.setProperty("app.title", settings.getString("title"));
    replacements.setProperty("app.version", settings.getString("version"));
    replacements.setProperty("openjdk.name", StringUtils.defaultIfBlank(
            SystemUtils.JAVA_RUNTIME_NAME, SystemUtils.JAVA_VM_NAME));
    replacements.setProperty("openjdk.version", StringUtils.defaultIfBlank(
            SystemUtils.JAVA_RUNTIME_VERSION, SystemUtils.JAVA_VERSION));
    return StringSubstitutor.replace(text, replacements);
}
 
Example 8
Source File: PubsubMessageToTemplatedString.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public String apply(PubsubMessage message) {
  final String batchKey = StringSubstitutor.replace(template,
      DerivedAttributesMap.of(message.getAttributesMap()));
  if (batchKey.contains("$")) {
    throw new IllegalArgumentException("Element did not contain all the attributes needed to"
        + " fill out variables in the configured template: " + template);
  }
  return batchKey;
}
 
Example 9
Source File: AppProperties.java    From cuba with Apache License 2.0 5 votes vote down vote up
private String handleInterpolation(String value) {
    StringSubstitutor substitutor = new StringSubstitutor(key -> {
        String property = getSystemOrAppProperty(key);
        return property != null ? property : System.getProperty(key);
    });
    return substitutor.replace(value);
}
 
Example 10
Source File: Slack.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
public void sendMessage(String player) {
    setConfig();
    if ( webhook == null ) {
        return;
    }
    Map<String, String> keys = new HashMap<>();
    keys.put("game", root.getGameName());
    //keys.put("gameName", StringUtils.defaultIfBlank(root.getGameData().getUsersGameName(), "[none]"));
    keys.put("round", gameUiManager.getCurrentRound().getRoundName());
    keys.put("current", StringUtils.defaultIfBlank(playerNameMappings.get(player), player));
    keys.put("previous", StringUtils.defaultIfBlank(observer.getFormerPlayer().getId(), "[none]"));

    String msgBody = StringSubstitutor.replace(body, keys);
    log.debug("Sending message '{}' to Slack for user {}", msgBody, player);

    HttpPost httpPost = new HttpPost(webhook);
    try {
        httpPost.setEntity(new StringEntity(msgBody));
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPost.setHeader(HttpHeaders.USER_AGENT, "18xx Rails");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if ( response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT ) {
            // TODO: verify result
            log.debug("Unexpected Slack response: {}", response);
        }
        response.close();
    }
    catch (IOException e) {
        log.error("Error sending message to Slack", e);
    }
}
 
Example 11
Source File: ConvertUtil.java    From gushici with GNU General Public License v3.0 5 votes vote down vote up
public static String getSvg(String content, Double fontSize, Double spacing) {
    int length = content.length();
    double realWidth = length * fontSize + (length-1) * spacing;
    double realFontSize = fontSize;
    Map<String, Object> templateValue  = new HashMap<>();
    templateValue.put("width", realWidth);
    templateValue.put("font-size", realFontSize);
    templateValue.put("spacing", spacing);
    templateValue.put("content", content);
    templateValue.put("height", realFontSize * 1.1);
    StringSubstitutor sub = new StringSubstitutor(templateValue);
    return sub.replace(svgTemplate);
}
 
Example 12
Source File: MergeStatementBuilder.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
public String buildMergeStatement(
    String replicaTable,
    String stagingTable,
    List<String> primaryKeyFields,
    List<String> allFields) {
  // Key/Value Map used to replace values in template
  Map<String, String> mergeQueryValues = new HashMap<>();

  mergeQueryValues.put("replicaTable", replicaTable);
  mergeQueryValues.put("replicaAlias", REPLICA_TABLE_NAME);
  mergeQueryValues.put("stagingAlias", STAGING_TABLE_NAME);
  mergeQueryValues.put("deleteColumn", configuration.deletedFieldName()); // TODO require config options

  mergeQueryValues.put(
    "stagingViewSql",
    buildLatestViewOfStagingTable(
        stagingTable, allFields, primaryKeyFields,
        configuration.timestampFieldName(), configuration.deletedFieldName(),
        configuration.partitionRetention()));

  mergeQueryValues.put("joinCondition", buildJoinConditions(primaryKeyFields, REPLICA_TABLE_NAME, STAGING_TABLE_NAME));
  mergeQueryValues.put("timestampCompareSql", buildTimestampCheck(configuration.timestampFieldName()));
  mergeQueryValues.put("mergeUpdateSql", buildUpdateStatement(allFields));
  mergeQueryValues.put("mergeInsertSql", buildInsertStatement(allFields));

  String mergeStatement = StringSubstitutor.replace(configuration.mergeQueryTemplate(), mergeQueryValues, "{", "}");
  return mergeStatement;
}
 
Example 13
Source File: QueryConfigUtils.java    From kayenta with Apache License 2.0 5 votes vote down vote up
private static String expandTemplate(
    String templateToExpand, Map<String, String> templateBindings) {
  try {
    log.debug("Expanding template='{}' with variables={}", templateToExpand, templateBindings);
    StringSubstitutor substitutor = new StringSubstitutor(templateBindings);
    substitutor.setEnableUndefinedVariableException(true);
    String expandedTemplate = substitutor.replace(templateToExpand);
    log.debug("Expanded template='{}'", expandedTemplate);

    return expandedTemplate;
  } catch (Exception e) {
    throw new IllegalArgumentException(
        "Problem evaluating custom filter template: " + templateToExpand, e);
  }
}
 
Example 14
Source File: PlaceholderReplacer.java    From Plan with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public String apply(String string) {
    StringSubstitutor sub = new StringSubstitutor(this);
    sub.setEnableSubstitutionInVariables(true);
    return sub.replace(string);
}
 
Example 15
Source File: LogFile.java    From Rails with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String getPropertyValue() {
    ConfigManager.initConfiguration(false);

    String logDir = Config.get(CONFIG_LOG_DIRECTORY);
    if ( StringUtils.isBlank(logDir) ) {
        logDir = System.getProperty("user.home");
        switch ( SystemOS.get() ) {
            case MAC:
            case UNIX:
                logDir += File.separator + ".rails" + File.separator;
                break;

            case WINDOWS:
                // should point to the Documents directory on Windows
                logDir = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + File.separator + "Rails" + File.separator;
                break;

            default:
                logDir += File.separator + "Rails" + File.separator;
                // nothing to do
        }
    }

    String fileName = Config.get(CONFIG_LOG_FILENAME_PATTERN);
    if ( StringUtils.isNotBlank(fileName) ) {
        if ( fileName.startsWith(File.separator ) ) {
            // use the whole thing as is
            logDir = "";
        }
        // support inject of date, etc
        StringSubstitutor substitutor = StringSubstitutor.createInterpolator();
        substitutor.setEnableSubstitutionInVariables(true);
        fileName = substitutor.replace(fileName);
        if ( SystemOS.get() == SystemOS.MAC || SystemOS.get() == SystemOS.UNIX ) {
            // sanitize
            fileName = fileName.replace(' ', '_');
        }
    }
    else {
        fileName = "18xx_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".log";
    }

    return logDir + fileName;
}
 
Example 16
Source File: DynamicPathTemplate.java    From gcp-ingestion with Mozilla Public License 2.0 4 votes vote down vote up
/** Return the dynamic part of the output path with placeholders filled in. */
private String replaceDynamicPart(Map<String, String> attributes) {
  return StringSubstitutor.replace(dynamicPart, attributes);
}
 
Example 17
Source File: APIImportConfigAdapter.java    From apimanager-swagger-promote with Apache License 2.0 3 votes vote down vote up
/**
 * This method is replacing variables such as ${TokenEndpoint} with declared variables coming from either 
 * the Environment-Variables or from system-properties.
 * @param inputFile The API-Config file to be replaced and returned as String
 * @return a String representation of the API-Config-File
 * @throws IOException if the file can't be found
 */
private String substitueVariables(File inputFile) throws IOException {
	StringSubstitutor substitutor = new StringSubstitutor(CommandParameters.getInstance().getEnvironmentProperties());
	String givenConfig = new String(Files.readAllBytes(inputFile.toPath()), StandardCharsets.UTF_8);
	givenConfig = StringSubstitutor.replace(givenConfig, System.getenv());
	return substitutor.replace(givenConfig);
}
 
Example 18
Source File: APIImportConfigAdapter.java    From apimanager-swagger-promote with Apache License 2.0 3 votes vote down vote up
/**
 * This method is replacing variables such as ${TokenEndpoint} with declared variables coming from either 
 * the Environment-Variables or from system-properties.
 * @param inputFile The API-Config file to be replaced and returned as String
 * @return a String representation of the API-Config-File
 * @throws IOException if the file can't be found
 */
private String substitueVariables(File inputFile) throws IOException {
	StringSubstitutor substitutor = new StringSubstitutor(CommandParameters.getInstance().getEnvironmentProperties());
	String givenConfig = new String(Files.readAllBytes(inputFile.toPath()), StandardCharsets.UTF_8);
	givenConfig = StringSubstitutor.replace(givenConfig, System.getenv());
	return substitutor.replace(givenConfig);
}
 
Example 19
Source File: SimplisticHttpGetGateWay.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
private HttpEntity<String> getRequestEntity( GenericHttpGatewayConfig config, String text, Set<String> recipients )
{
    Map<String, String> valueStore = getValueStore( config, text, recipients );

    final StringSubstitutor substitutor = new StringSubstitutor( valueStore ); // Matches on ${...}

    String data = substitutor.replace( config.getConfigurationTemplate() );

    return new HttpEntity<>( data, getHeaderParameters( config ) );
}
 
Example 20
Source File: GoogleAuthenticatorUtils.java    From google-authenticator-integration with MIT License 3 votes vote down vote up
/**
 * 生成 Google Authenticator Key Uri
 * Google Authenticator 规定的 Key Uri 格式: otpauth://totp/{issuer}:{account}?secret={secret}&issuer={issuer}
 * https://github.com/google/google-authenticator/wiki/Key-Uri-Format
 * 参数需要进行 url 编码 +号需要替换成%20
 *
 * @param secret 密钥 使用 createSecretKey 方法生成
 * @param account 用户账户 如: [email protected]
 * @param issuer 服务名称 如: Google,GitHub
 */
@SneakyThrows
public static String createKeyUri(String secret, String account, String issuer) {
    String qrCodeStr = "otpauth://totp/${issuer}:${account}?secret=${secret}&issuer=${issuer}";
    Builder<String, String> mapBuilder = ImmutableMap.builder();
    mapBuilder.put("account", URLEncoder.encode(account, "UTF-8").replace("+", "%20"));
    mapBuilder.put("secret", URLEncoder.encode(secret, "UTF-8").replace("+", "%20"));
    mapBuilder.put("issuer", URLEncoder.encode(issuer, "UTF-8").replace("+", "%20"));
    return StringSubstitutor.replace(qrCodeStr, mapBuilder.build());
}