Search in sources :

Example 36 with StringSubstitutor

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());
}
Also used : StringSubstitutor(org.apache.commons.text.StringSubstitutor) InputStream(java.io.InputStream) Resource(org.springframework.core.io.Resource) ExternalResource(org.junit.rules.ExternalResource) IOException(java.io.IOException) File(java.io.File) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader)

Example 37 with StringSubstitutor

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);
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) StringSubstitutor(org.apache.commons.text.StringSubstitutor) TreeMap(java.util.TreeMap) MethodParameter(org.springframework.core.MethodParameter) Map(java.util.Map) TreeMap(java.util.TreeMap) PathVariable(org.springframework.web.bind.annotation.PathVariable)

Example 38 with StringSubstitutor

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);
    }
}
Also used : SubstitutingSourceProvider(io.dropwizard.configuration.SubstitutingSourceProvider) IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) MetricRegistry(com.codahale.metrics.MetricRegistry) Logger(org.slf4j.Logger) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) ResourceConfigurationSourceProvider(io.dropwizard.configuration.ResourceConfigurationSourceProvider) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Duration(io.dropwizard.util.Duration) StringSubstitutor(org.apache.commons.text.StringSubstitutor) Test(org.junit.jupiter.api.Test) ServerSocket(java.net.ServerSocket) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Future(java.util.concurrent.Future) SubstitutingSourceProvider(io.dropwizard.configuration.SubstitutingSourceProvider) DataSize(io.dropwizard.util.DataSize) Jackson(io.dropwizard.jackson.Jackson) YamlConfigurationFactory(io.dropwizard.configuration.YamlConfigurationFactory) BaseValidator(io.dropwizard.validation.BaseValidator) Collections(java.util.Collections) StringSubstitutor(org.apache.commons.text.StringSubstitutor) ResourceConfigurationSourceProvider(io.dropwizard.configuration.ResourceConfigurationSourceProvider) MetricRegistry(com.codahale.metrics.MetricRegistry) ServerSocket(java.net.ServerSocket) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 39 with StringSubstitutor

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);
    }
}
Also used : IntStream(java.util.stream.IntStream) Maps(io.dropwizard.util.Maps) BeforeEach(org.junit.jupiter.api.BeforeEach) MetricRegistry(com.codahale.metrics.MetricRegistry) Logger(org.slf4j.Logger) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) ResourceConfigurationSourceProvider(io.dropwizard.configuration.ResourceConfigurationSourceProvider) Collectors(java.util.stream.Collectors) File(java.io.File) StringSubstitutor(org.apache.commons.text.StringSubstitutor) Test(org.junit.jupiter.api.Test) ServerSocket(java.net.ServerSocket) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Future(java.util.concurrent.Future) SubstitutingSourceProvider(io.dropwizard.configuration.SubstitutingSourceProvider) Jackson(io.dropwizard.jackson.Jackson) YamlConfigurationFactory(io.dropwizard.configuration.YamlConfigurationFactory) BaseValidator(io.dropwizard.validation.BaseValidator) MetricRegistry(com.codahale.metrics.MetricRegistry) ServerSocket(java.net.ServerSocket) Logger(org.slf4j.Logger) SubstitutingSourceProvider(io.dropwizard.configuration.SubstitutingSourceProvider) StringSubstitutor(org.apache.commons.text.StringSubstitutor) ResourceConfigurationSourceProvider(io.dropwizard.configuration.ResourceConfigurationSourceProvider) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 40 with StringSubstitutor

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");
}
Also used : Test(org.junit.jupiter.api.Test) StringLookup(org.apache.commons.text.lookup.StringLookup) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IOException(java.io.IOException) Assertions.assertThatIOException(org.assertj.core.api.Assertions.assertThatIOException) StandardCharsets(java.nio.charset.StandardCharsets) InputStream(java.io.InputStream) StringSubstitutor(org.apache.commons.text.StringSubstitutor) StringSubstitutor(org.apache.commons.text.StringSubstitutor) ByteArrayInputStream(java.io.ByteArrayInputStream) StringLookup(org.apache.commons.text.lookup.StringLookup) Test(org.junit.jupiter.api.Test)

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