use of org.apache.commons.text.StringSubstitutor in project cuba by cuba-platform.
the class TestContainer method initAppProperties.
@SuppressWarnings("ResultOfMethodCallIgnored")
protected void initAppProperties() {
Properties properties = new Properties();
List<String> locations = getAppPropertiesFiles();
DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
for (String location : locations) {
Resource resource = resourceLoader.getResource(location);
if (resource.exists()) {
try (InputStream stream = resource.getInputStream()) {
properties.load(stream);
} catch (IOException e) {
throw new RuntimeException("Unable to load properties file", e);
}
} else {
log.warn("Resource {} not found, ignore it", location);
}
}
StringSubstitutor substitutor = new StringSubstitutor(key -> {
String subst = properties.getProperty(key);
return subst != null ? subst : System.getProperty(key);
});
for (Object key : properties.keySet()) {
String value = substitutor.replace(properties.getProperty((String) key));
appProperties.put((String) key, value);
}
File dir;
dir = new File(appProperties.get("cuba.confDir"));
dir.mkdirs();
dir = new File(appProperties.get("cuba.logDir"));
dir.mkdirs();
dir = new File(appProperties.get("cuba.tempDir"));
dir.mkdirs();
dir = new File(appProperties.get("cuba.dataDir"));
dir.mkdirs();
AppContext.setProperty(AppConfig.CLIENT_TYPE_PROP, ClientType.WEB.toString());
appProperties.put(AppConfig.CLIENT_TYPE_PROP, ClientType.WEB.toString());
}
use of org.apache.commons.text.StringSubstitutor in project powerauth-restful-integration by lime-company.
the class PowerAuthAnnotationInterceptor method expandResourceId.
/**
* The method substitutes placeholders (marked via "${placeholder}") in resourceID attribute value by
* the actual parameters of the handler method. The implementation takes into account all method parameters
* that are annotated via @RequestParam or @PathVariable annotations and extracts values from the request
* parameter map.<br>
* <br>
* <b>
* Note: In case both @RequestParam and @PathVariable with the same name exist, the value of @RequestParam
* takes precedence. This is because @RequestParam usually maps to the HTTP GET query parameter that cannot
* be easily changed in existing API, while @PathVariable is just a URL placeholder that can be renamed in
* the code with no impact on functionality.
* </b>
*
* @param resourceId Resource ID with possible placeholders.
* @param request HttpServletRequest for the current execution.
* @param handlerMethod Handler method that is responsible for the request processing.
* @return Resource ID with substituted placeholders.
*/
@SuppressWarnings("unchecked")
private String expandResourceId(String resourceId, HttpServletRequest request, HandlerMethod handlerMethod) {
// Get method parameters that could be replaced in the context of resource ID
final Map<String, String> parameters = new TreeMap<>();
final MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
for (MethodParameter mp : methodParameters) {
// Handle parameters annotated by @RequestParam annotation.
// These are stored in the servlet request parameter map.
// Note: @RequestParam must be processed before @PathVariable since
// in API, it cannot be renamed (the path variable is just
// a placeholder and can have arbitrary name).
final RequestParam requestParam = mp.getParameterAnnotation(RequestParam.class);
if (requestParam != null) {
final String name = requestParam.name();
final String value = request.getParameter(name);
if (value != null) {
// do not check "&& !parameters.containsKey(name)" because in the case of
// a name conflict, we want @RequestParam to overwrite @PathVariable value
parameters.put(name, value);
}
} else {
// Handle parameters annotated by @PathVariable annotation.
// These are stored by Spring in the servlet request attributes map, under a special
// URI_TEMPLATE_VARIABLES_ATTRIBUTE key that contains Map<String, String> with path
// variable mapping.
final PathVariable pathVariable = mp.getParameterAnnotation(PathVariable.class);
if (pathVariable != null) {
final String name = pathVariable.name();
final Map<String, String> pathVariableMap = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (pathVariableMap != null && !parameters.containsKey(name)) {
// prevent overwriting value that is already assigned
final String value = pathVariableMap.get(name);
if (value != null) {
parameters.put(name, value);
}
}
}
}
}
// Substitute the placeholders
final StringSubstitutor sub = new StringSubstitutor(parameters);
return sub.replace(resourceId);
}
use of org.apache.commons.text.StringSubstitutor in project dropwizard by dropwizard.
the class TcpSocketAppenderFactoryTest method testBufferingTcpLogging.
@Test
void testBufferingTcpLogging() throws Exception {
try (ServerSocket serverSocket = createServerSocket();
TcpServer tcpServer = new TcpServer(serverSocket)) {
Future<List<String>> receivedMessages = tcpServer.receive();
DefaultLoggingFactory loggingFactory = yamlConfigurationFactory.build(new SubstitutingSourceProvider(new ResourceConfigurationSourceProvider(), new StringSubstitutor(Collections.singletonMap("tcp.server.port", serverSocket.getLocalPort()))), "yaml/logging-tcp-buffered.yml");
loggingFactory.configure(new MetricRegistry(), "tcp-test");
List<String> loggedMessages = generateLogs(LoggerFactory.getLogger("com.example.app"));
// We have to flush the buffer manually
loggingFactory.reset();
assertThat(receivedMessages.get(1, TimeUnit.MINUTES)).allSatisfy(s -> assertThat(s).startsWith("INFO")).extracting(s -> s.substring(s.lastIndexOf("com.example.app: ") + "com.example.app: ".length())).containsExactlyElementsOf(loggedMessages);
}
}
use of org.apache.commons.text.StringSubstitutor in project dropwizard by dropwizard.
the class TlsSocketAppenderFactoryTest method testTlsLogging.
@Test
void testTlsLogging() throws Exception {
try (ServerSocket serverSocket = createServerSocket();
TcpServer tcpServer = new TcpServer(serverSocket)) {
Future<List<String>> receivedMessages = tcpServer.receive();
DefaultLoggingFactory loggingFactory = yamlConfigurationFactory.build(new SubstitutingSourceProvider(new ResourceConfigurationSourceProvider(), new StringSubstitutor(Maps.of("tls.trust_store.path", resourcePath("/stores/tls_client.jks"), "tls.trust_store.pass", "client_pass", "tls.server_port", serverSocket.getLocalPort()))), "/yaml/logging-tls.yml");
loggingFactory.configure(new MetricRegistry(), "tls-appender-test");
Logger logger = LoggerFactory.getLogger("com.example.app");
List<String> loggedMessages = generateLogs(logger);
loggingFactory.reset();
assertThat(receivedMessages.get(1, TimeUnit.MINUTES)).hasSize(100).allSatisfy(s -> assertThat(s).startsWith("INFO")).extracting(s -> s.substring(s.lastIndexOf("com.example.app: ") + "com.example.app: ".length())).containsExactlyElementsOf(loggedMessages);
}
}
use of org.apache.commons.text.StringSubstitutor in project dropwizard by dropwizard.
the class SubstitutingSourceProviderTest method shouldSubstituteCorrectly.
@Test
void shouldSubstituteCorrectly() throws IOException {
StringLookup dummyLookup = (x) -> "baz";
DummySourceProvider dummyProvider = new DummySourceProvider();
SubstitutingSourceProvider provider = new SubstitutingSourceProvider(dummyProvider, new StringSubstitutor(dummyLookup));
assertThat(provider.open("foo: ${bar}")).hasSameContentAs(new ByteArrayInputStream("foo: baz".getBytes(StandardCharsets.UTF_8)));
// ensure that opened streams are closed
assertThatIOException().isThrownBy(() -> dummyProvider.lastStream.read()).withMessage("Stream closed");
}
Aggregations