类org.apache.commons.lang.text.StrSubstitutor源码实例Demo

下面列出了怎么用org.apache.commons.lang.text.StrSubstitutor的API类实例代码及写法,或者点击链接到github查看源代码。

/**
 * This method selects a filepath of an appender.
 * 
 * @param appender The appender name
 * @param replaceVariables If true all variables(${var}) in the file path
 *        will be substituted
 * 
 * @return The log file path
 */
public String getFile(String appender, boolean replaceVariables) {
	String result = null;
	Element elem = xml.getChild("appender", "name", appender);
	if (elem != null) {
		List childs = elem.getChildren("param");
		Iterator children = childs.iterator();

		while (children.hasNext()) {
			Element child = (Element) children.next();

			if (child.getAttributeValue("name").equals("File")) {
				result = child.getAttributeValue("value");
			}
		}

		if (replaceVariables) {
			result = StrSubstitutor.replaceSystemProperties(result);
		}
	}

	return result;
}
 
源代码2 项目: qaf   文件: MetaDataScanner.java
/**
 * 
 * @param xmlTest
 * @param parameter
 * @return
 */
public static String getParameter(XmlTest xmlTest, String parameter) {
	String paramValue = "";

	boolean overrideUsingSystemProp = System.getProperties().containsKey(parameter);

	Map<String, String> context = xmlTest.getAllParameters();
	context.keySet().removeAll(System.getProperties().keySet());

	if (overrideUsingSystemProp) {
		paramValue = System.getProperty(parameter);
	} else if (context.containsKey(parameter)) {
		paramValue = context.get(parameter);
	} else if (getBundle().containsKey(parameter)) {
		try {
			// unresolved value
			paramValue = (String) getBundle().configurationAt(parameter).getRoot().getValue();
		} catch (Exception e) {
			paramValue = getBundle().getString(parameter, "");
		}
	}
	paramValue = StrSubstitutor.replace(paramValue, context);
	paramValue = getBundle().getSubstitutor().replace(paramValue);
	return paramValue;
}
 
源代码3 项目: qaf   文件: BDDDefinitionHelper.java
public static String replaceParams(String stepCall, Map<String, Object> context) {
	stepCall = convertPrameter(stepCall);
	//don't resolve quoted parameters.
	stepCall = stepCall.replace("\"${", "\"<%{").replace("'${", "'<%{");
	//qaf#321 
	StrLookup lookup = new StrLookup() {
		public String lookup(String var) {

			Object prop = context.get(var);
			if(prop==null) {
				prop = getBundle().getSubstitutor().getVariableResolver().lookup(var);
			}
			return (prop != null) ? JSONUtil.toString(prop) : null;
		}
	};		
	StrSubstitutor interpol = new StrSubstitutor(lookup);
	stepCall = interpol.replace(stepCall);
	
	stepCall = stepCall.replace( "\"<%{","\"${").replace( "'<%{","'${");
	return stepCall;
}
 
源代码4 项目: zerocode   文件: ScenarioExecutionStateTest.java
protected String createStepWith(String stepName) {
    Map<String, String> parammap = new HashMap<>();

    parammap.put("STEP.NAME", stepName);
    parammap.put("STEP.REQUEST", "{\n" +
            "    \"customer\": {\n" +
            "        \"firstName\": \"FIRST_NAME\"\n" +
            "    }\n" +
            "}");
    parammap.put("STEP.RESPONSE", "{\n" +
            "    \"id\" : 10101\n" +
            "}");

    StrSubstitutor sub = new StrSubstitutor(parammap);

    return sub.replace((new StepExecutionState()).getRequestResponseState());
}
 
源代码5 项目: slr-toolkit   文件: TemplateACMSigplanConf.java
@Override
public String fillDocument(String document, SlrProjectMetainformation metainformation, DataProvider dataProvider,
		Map<Term, String> mainDimensions) {
	Map<String, String> valuesMap = new HashMap<String, String>();
	valuesMap.put(SLRVARIABLE_TITLE, metainformation.getTitle());
	valuesMap.put(SLRVARIABLE_ABSTRACT, metainformation.getProjectAbstract());
	valuesMap.put(SLRVARIABLE_KEYWORDS, metainformation.getKeywords());
	valuesMap.put(SLRVARIABLE_AUTHORS, this.generateAuthorSection(metainformation));
	valuesMap.put(SLRVARIABLE_STATISTICS, this.generateStatistics(dataProvider));
	valuesMap.put(SLRVARIABLE_TAXONOMYDESCRIPTION, metainformation.getTaxonomyDescription());
	
	double imageToTextWidthFactor = 0.4;
	valuesMap.put(SLRVARIABLE_DIMENSIONCHARTS, this.generateDimensionCharts(mainDimensions, imageToTextWidthFactor));

	StrSubstitutor sub = new StrSubstitutor(valuesMap);
	String resolvedString = sub.replace(document);

	return resolvedString;
}
 
源代码6 项目: slr-toolkit   文件: TemplateSpringerLncs.java
@Override
public String fillDocument(String document, SlrProjectMetainformation metainformation, DataProvider dataProvider,
		Map<Term, String> mainDimensions) {
	Map<String, String> valuesMap = new HashMap<String, String>();
	valuesMap.put(SLRVARIABLE_TITLE, metainformation.getTitle());
	valuesMap.put(SLRVARIABLE_ABSTRACT, metainformation.getProjectAbstract());
	valuesMap.put(SLRVARIABLE_KEYWORDS, metainformation.getKeywords());
	valuesMap.put(SLRVARIABLE_AUTHORS, this.generateAuthorSection(metainformation));
	valuesMap.put(SLRVARIABLE_STATISTICS, this.generateStatistics(dataProvider));
	valuesMap.put(SLRVARIABLE_TAXONOMYDESCRIPTION, metainformation.getTaxonomyDescription());
	
	double imageToTextWidthFactor = 0.8;
	valuesMap.put(SLRVARIABLE_DIMENSIONCHARTS, this.generateDimensionCharts(mainDimensions, imageToTextWidthFactor));

	StrSubstitutor sub = new StrSubstitutor(valuesMap);
	String resolvedString = sub.replace(document);

	return resolvedString;
}
 
源代码7 项目: slr-toolkit   文件: TemplateIEEEconf.java
@Override
public String fillDocument(String document, SlrProjectMetainformation metainformation, DataProvider dataProvider,
		Map<Term, String> mainDimensions) {
	Map<String, String> valuesMap = new HashMap<String, String>();
	valuesMap.put(SLRVARIABLE_TITLE, metainformation.getTitle());
	valuesMap.put(SLRVARIABLE_ABSTRACT, metainformation.getProjectAbstract());
	valuesMap.put(SLRVARIABLE_KEYWORDS, metainformation.getKeywords());
	valuesMap.put(SLRVARIABLE_AUTHORS, this.generateAuthorSection(metainformation));
	valuesMap.put(SLRVARIABLE_STATISTICS, this.generateStatistics(dataProvider));
	valuesMap.put(SLRVARIABLE_TAXONOMYDESCRIPTION, metainformation.getTaxonomyDescription());
	
	double imageToTextWidthFactor = 0.4;
	valuesMap.put(SLRVARIABLE_DIMENSIONCHARTS, this.generateDimensionCharts(mainDimensions, imageToTextWidthFactor));

	StrSubstitutor sub = new StrSubstitutor(valuesMap);
	String resolvedString = sub.replace(document);

	return resolvedString;
}
 
源代码8 项目: slr-toolkit   文件: TemplatePlainArticle.java
@Override
public String fillDocument(String document, SlrProjectMetainformation metainformation, DataProvider dataProvider,
		Map<Term, String> mainDimensions) {
	Map<String, String> valuesMap = new HashMap<String, String>();
	valuesMap.put(SLRVARIABLE_TITLE, metainformation.getTitle());
	valuesMap.put(SLRVARIABLE_ABSTRACT, metainformation.getProjectAbstract());
	valuesMap.put(SLRVARIABLE_KEYWORDS, metainformation.getKeywords());
	valuesMap.put(SLRVARIABLE_AUTHORS, this.generateAuthorSection(metainformation));
	valuesMap.put(SLRVARIABLE_TAXONOMYDESCRIPTION, metainformation.getTaxonomyDescription());
	valuesMap.put(SLRVARIABLE_STATISTICS, this.generateStatistics(dataProvider));
	
	double imageToTextWidthFactor = 1;
	valuesMap.put(SLRVARIABLE_DIMENSIONCHARTS, this.generateDimensionCharts(mainDimensions, imageToTextWidthFactor));

	StrSubstitutor sub = new StrSubstitutor(valuesMap);
	String resolvedString = sub.replace(document);

	return resolvedString;
}
 
源代码9 项目: slr-toolkit   文件: TemplateTUDSCR.java
@Override
public String fillDocument(String document, SlrProjectMetainformation metainformation, DataProvider dataProvider,
		Map<Term, String> mainDimensions) {
	Map<String, String> valuesMap = new HashMap<String, String>();
	valuesMap.put(SLRVARIABLE_TITLE, metainformation.getTitle());
	valuesMap.put(SLRVARIABLE_ABSTRACT, metainformation.getProjectAbstract());
	valuesMap.put(SLRVARIABLE_KEYWORDS, metainformation.getKeywords());
	valuesMap.put(SLRVARIABLE_AUTHORS, this.generateAuthorSection(metainformation));
	valuesMap.put(SLRVARIABLE_TAXONOMYDESCRIPTION, metainformation.getTaxonomyDescription());
	valuesMap.put(SLRVARIABLE_STATISTICS, this.generateStatistics(dataProvider));
	
	double imageToTextWidthFactor = 1;
	valuesMap.put(SLRVARIABLE_DIMENSIONCHARTS, this.generateDimensionCharts(mainDimensions, imageToTextWidthFactor));

	StrSubstitutor sub = new StrSubstitutor(valuesMap);
	String resolvedString = sub.replace(document);

	return resolvedString;
}
 
源代码10 项目: incubator-sentry   文件: PathUtils.java
public static boolean impliesURI(String privilege, String request) {
  try {
    URI privilegeURI = new URI(new StrSubstitutor(System.getProperties()).replace(privilege));
    URI requestURI = new URI(request);
    if (privilegeURI.getScheme() == null || privilegeURI.getPath() == null) {
      LOGGER.warn("Privilege URI " + request + " is not valid. Either no scheme or no path.");
      return false;
    }
    if (requestURI.getScheme() == null || requestURI.getPath() == null) {
      LOGGER.warn("Request URI " + request + " is not valid. Either no scheme or no path.");
      return false;
    }
    return PathUtils.impliesURI(privilegeURI, requestURI);
  } catch (URISyntaxException e) {
    LOGGER.warn("Request URI " + request + " is not a URI", e);
    return false;
  }
}
 
源代码11 项目: usergrid   文件: EmailFlowIT.java
private void testProperty( String propertyName, boolean containsSubstitution ) {
    String propertyValue = setup.get( propertyName );
    assertTrue( propertyName + " was not found", isNotBlank( propertyValue ) );
    logger.info( propertyName + "=" + propertyValue );

    if ( containsSubstitution ) {
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put( "reset_url", "test-url" );
        valuesMap.put( "organization_name", "test-org" );
        valuesMap.put( "activation_url", "test-url" );
        valuesMap.put( "confirmation_url", "test-url" );
        valuesMap.put( "user_email", "test-email" );
        valuesMap.put( "pin", "test-pin" );
        StrSubstitutor sub = new StrSubstitutor( valuesMap );
        String resolvedString = sub.replace( propertyValue );
        assertNotSame( propertyValue, resolvedString );
    }
}
 
源代码12 项目: keycloak   文件: LDAPEmbeddedServer.java
private void importLdif() throws Exception {
    Map<String, String> map = new HashMap<String, String>();
    map.put("hostname", this.bindHost);
    if (this.ldapSaslPrincipal != null) {
        map.put("ldapSaslPrincipal", this.ldapSaslPrincipal);
    }

    // Find LDIF file on filesystem or classpath ( if it's like classpath:ldap/users.ldif )
    InputStream is = FindFile.findFile(ldifFile);
    if (is == null) {
        throw new IllegalStateException("LDIF file not found on classpath or on file system. Location was: " + ldifFile);
    }

    final String ldifContent = StrSubstitutor.replace(StreamUtil.readString(is), map);
    log.info("Content of LDIF: " + ldifContent);
    final SchemaManager schemaManager = directoryService.getSchemaManager();

    importLdifContent(directoryService, ldifContent);
}
 
源代码13 项目: kylin-on-parquet-v2   文件: KylinConfigBase.java
/**
 *
 * @param propertyKeys the collection of the properties; if null will return all properties
 * @return properties which contained in propertyKeys
 */
protected Properties getProperties(Collection<String> propertyKeys) {
    Map<String, String> envMap = System.getenv();
    StrSubstitutor sub = new StrSubstitutor(envMap);

    Properties filteredProperties = new Properties();
    for (Entry<Object, Object> entry : this.properties.entrySet()) {
        if (propertyKeys == null || propertyKeys.contains(entry.getKey())) {
            filteredProperties.put(entry.getKey(), sub.replace((String) entry.getValue()));
        }
    }
    return filteredProperties;
}
 
public String resolve(Map<String, String> environmentVariables) throws UnresolvedPropertyException {
    String evaluatedProperty = StrSubstitutor.replace(property, environmentVariables);
    if(ENVIRONMENT_VARIABLE_PATTERN.matcher(evaluatedProperty).find()) {
        throw new UnresolvedPropertyException(evaluatedProperty, propertyName);
    }
    return evaluatedProperty;
}
 
源代码15 项目: waterdrop   文件: StringTemplate.java
/**
 * @param timeFormat example : "yyyy-MM-dd HH:mm:ss"
 * */
public static String substitute(String str, String timeFormat) {

    final SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
    final String formatteddDate = sdf.format(new Date());

    final Map valuesMap = new HashMap();
    valuesMap.put("uuid", UUID.randomUUID().toString());
    valuesMap.put("now", formatteddDate);
    valuesMap.put(timeFormat, formatteddDate);
    final StrSubstitutor sub = new StrSubstitutor(valuesMap);
    return sub.replace(str);
}
 
源代码16 项目: RIBs   文件: Generator.java
/**
 * @return the source for the generated file.
 */
public final String generate() {
  StrSubstitutor substitutor = new StrSubstitutor(templateValuesMap);
  String newFile = substitutor.replace(templateString);
  System.out.println(newFile);
  return newFile;
}
 
源代码17 项目: mycore   文件: MCRCommandLineInterface.java
/**
 * Expands variables in a command.
 * Replaces any variables in form ${propertyName} to the value defined by
 * {@link MCRConfiguration2#getString(String)}.
 * If the property is not defined no variable replacement takes place.
 * @param command a CLI command that should be expanded
 * @return expanded command
 */
public static String expandCommand(final String command) {
    StrSubstitutor strSubstitutor = new StrSubstitutor(MCRConfiguration2.getPropertiesMap());
    String expandedCommand = strSubstitutor.replace(command);
    if (!expandedCommand.equals(command)) {
        LOGGER.info("{} --> {}", command, expandedCommand);
    }
    return expandedCommand;
}
 
源代码18 项目: GomJabbar   文件: FaultCommandInjector.java
private String formatCommand(final String command, final Target target) {
  Map<Object, Object> valuesMap = new HashMap<>();
  valuesMap.put("host", target.getHost());
  valuesMap.put("module", target.getModule());
  valuesMap.putAll(System.getProperties());

  return new StrSubstitutor(valuesMap).replace(command);
}
 
源代码19 项目: qaf   文件: QAFInetrceptableDataProvider.java
private static Map<?, ?> getParameters(TestNGScenario scenario) {
	Map<String, Object> methodParameters = scenario.getMetaData();
	String description = scenario.getDescription();
	if (isNotBlank(description) && JSONUtil.isValidJsonString(description)) {
		Map<String, Object> paramsFromDesc = new JSONObject(description).toMap();
		description =(String) paramsFromDesc.remove("description");
		methodParameters.putAll(paramsFromDesc);
		scenario.setDescription(description);
	}

	// highest priority test data overridden through property with test name prefix
	String testParameters = getConfigParameters(scenario.getMethodName() + ".testdata");
	if(isBlank(testParameters)){
		//second priority overridden through property "global.testdata"
		testParameters = getConfigParameters("global.testdata");
		if(isBlank(testParameters)){
			//default provided with test case
			testParameters = new JSONObject(methodParameters).toString();
		}
	}
	
	String cls = scenario.getConstructorOrMethod().getMethod().getDeclaringClass().getSimpleName();
	String mtd = scenario.getMethodName();
	testParameters = testParameters.replace("${class}", cls);
	testParameters = testParameters.replace("${method}", mtd);
	testParameters = StrSubstitutor.replace(testParameters, methodParameters);
	testParameters = getBundle().getSubstitutor().replace(testParameters);
	try {
		return new JSONObject(testParameters).toMap();
	} catch (JsonSyntaxException e) {
		// old way of setting global data or testdata using key=value
		return StringUtil.toMap(testParameters, true);
	}
}
 
源代码20 项目: zerocode   文件: CalculatorTest.java
@Test
void testParamResolver() {
    String WelcomeMessage="Hello ${firstName} ${lastName}!";
    Map<String, String> valuesMap = new HashMap<>();
    valuesMap.put("firstName", "Peter");
    valuesMap.put("lastName", "Osi");
    StrSubstitutor sub = new StrSubstitutor(valuesMap);
    String message = sub.replace(WelcomeMessage);
    assertEquals("Hello Peter Osi!", message);
}
 
源代码21 项目: zerocode   文件: ScenarioExecutionState.java
public String getResolvedScenarioState() {
    final String commaSeparatedStepResults = getAllStepsInStringList().stream()
            .map(i -> i)
            .collect(Collectors.joining(", "));
    paramMap.put("STEP_REQUEST_RESPONSE_SECTION", commaSeparatedStepResults);

    return (new StrSubstitutor(paramMap)).replace(scenarioStateTemplate);
}
 
源代码22 项目: zerocode   文件: TokenUtils.java
public static String resolveKnownTokens(String requestJsonOrAnyString) {
    Map<String, Object> paramMap = new HashMap<>();

    final List<String> testCaseTokens = getTestCaseTokens(requestJsonOrAnyString);
    testCaseTokens.stream().distinct().forEach(runTimeToken -> {
        populateParamMap(paramMap, runTimeToken);
    });

    StrSubstitutor sub = new StrSubstitutor(paramMap);

    return sub.replace(requestJsonOrAnyString);
}
 
源代码23 项目: zerocode   文件: StepExecutionStateTest.java
@Test
public void willHaveReqResp_resolved() throws Exception {

    Map<String, String> parammap = new HashMap<>();

    parammap.put("STEP.NAME", "Step-1");
    parammap.put("STEP.REQUEST", "{\n" +
            "    \"customer\": {\n" +
            "        \"firstName\": \"FIRST_NAME\"\n" +
            "    }\n" +
            "}");
    parammap.put("STEP.RESPONSE", "{\n" +
            "    \"id\" : 10101\n" +
            "}");

    StrSubstitutor sub = new StrSubstitutor(parammap);
    String resolvedString = sub.replace(stepExecutionState.getRequestResponseState());

    JSONAssert.assertEquals(String.format("{%s}", resolvedString), "{\n" +
            "    \"Step-1\": {\n" +
            "        \"request\": {\n" +
            "            \"customer\": {\n" +
            "                \"firstName\": \"FIRST_NAME\"\n" +
            "            }\n" +
            "        },\n" +
            "        \"response\": {\n" +
            "            \"id\": 10101\n" +
            "        }\n" +
            "    }\n" +
            "}", true);
}
 
private String resolvePropertyValue(String spec, MessageContext msgCtxt) {
    if (spec.indexOf('{') > -1 && spec.indexOf('}')>-1) {
        // Replace ALL curly-braced items in the spec string with
        // the value of the corresponding context variable.
        TemplateString ts = new TemplateString(spec);
        Map<String,String> valuesMap = new HashMap<String,String>();
        for (String s : ts.variableNames) {
            valuesMap.put(s, (String) msgCtxt.getVariable(s));
        }
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        String resolvedString = sub.replace(ts.template);
        return resolvedString;
    }
    return spec;
}
 
private String resolvePropertyValue(String spec, MessageContext msgCtxt) {
    if (spec.indexOf('{') > -1 && spec.indexOf('}')>-1) {
        // Replace ALL curly-braced items in the spec string with
        // the value of the corresponding context variable.
        TemplateString ts = new TemplateString(spec);
        Map<String,String> valuesMap = new HashMap<String,String>();
        for (String s : ts.variableNames) {
            valuesMap.put(s, (String) msgCtxt.getVariable(s));
        }
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        String resolvedString = sub.replace(ts.template);
        return resolvedString;
    }
    return spec;
}
 
private String formatNameInternal(final Address address, final String format) {
    if (address != null) {

        final Map<String, String> values = new HashMap<>();
        values.put("salutation", StringUtils.defaultString(address.getSalutation()));
        values.put("firstname", StringUtils.defaultString(address.getFirstname()));
        values.put("middlename", StringUtils.defaultString(address.getMiddlename()));
        values.put("lastname", StringUtils.defaultString(address.getLastname()));

        return new StrSubstitutor(values, "{{", "}}").replace(format);

    }
    return StringUtils.EMPTY;
}
 
private String formatNameInternal(final Customer customer, final String format) {
    if (customer != null) {

        final Map<String, String> values = new HashMap<>();
        values.put("salutation", StringUtils.defaultString(customer.getSalutation()));
        values.put("firstname", StringUtils.defaultString(customer.getFirstname()));
        values.put("middlename", StringUtils.defaultString(customer.getMiddlename()));
        values.put("lastname", StringUtils.defaultString(customer.getLastname()));

        return new StrSubstitutor(values, "{{", "}}").replace(format);

    }
    return StringUtils.EMPTY;
}
 
源代码28 项目: govpay   文件: CustomIuv.java
public String buildPrefix(Applicazione applicazione, String prefix, Map<String, String> values) {
	if(prefix == null) return "";
	
	StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
	String result = sub.replace(prefix);

	return result;
}
 
源代码29 项目: kylin   文件: KylinConfigBase.java
/**
 * @param propertyKeys the collection of the properties; if null will return all properties
 * @return properties which contained in propertyKeys
 */
protected Properties getProperties(Collection<String> propertyKeys) {
    Map<String, String> envMap = System.getenv();
    StrSubstitutor sub = new StrSubstitutor(envMap);

    Properties filteredProperties = new Properties();
    for (Entry<Object, Object> entry : this.properties.entrySet()) {
        if (propertyKeys == null || propertyKeys.contains(entry.getKey())) {
            filteredProperties.put(entry.getKey(), sub.replace((String) entry.getValue()));
        }
    }
    return filteredProperties;
}
 
源代码30 项目: slr-toolkit   文件: StringSubstitutorTest.java
@Test
public void testStringSubstitution() throws MalformedURLException {
	Map<String, String> subMap = new HashMap<>();
	String afterChange = "afterChange";
	subMap.put(SlrLatexTemplate.SLRVARIABLE_ABSTRACT, afterChange);

	String dontChangeMeString = "dontChangeMe";
	String oldString = "${" + SlrLatexTemplate.SLRVARIABLE_ABSTRACT + "}" + "," + dontChangeMeString;

	StrSubstitutor sub = new StrSubstitutor(subMap);
	String newString = sub.replace(oldString);

	assertFalse(newString.contains(SlrLatexTemplate.SLRVARIABLE_ABSTRACT));
	assertTrue(newString.contains(dontChangeMeString));
}
 
 类所在包
 类方法
 同包方法