use of org.apache.commons.lang3.text.StrSubstitutor in project jirm by agentgt.
the class SqlWriterStrategy method replacePropertyPaths.
public String replacePropertyPaths(final SqlObjectDefinition<?> definition, final String sql) {
StrLookup<String> lookup = new StrLookup<String>() {
@Override
public String lookup(String key) {
Optional<String> p = parameterPathToSql(definition, key);
check.state(p.isPresent(), "Invalid object path: {}", key);
return p.get();
}
};
StrSubstitutor s = new StrSubstitutor(lookup, "{{", "}}", '$');
String result = s.replace(sql);
return result;
}
use of org.apache.commons.lang3.text.StrSubstitutor in project jirm by agentgt.
the class SqlWriterStrategy method replaceProperties.
public String replaceProperties(final SqlObjectDefinition<?> definition, final String sql) {
StrLookup<String> lookup = new StrLookup<String>() {
@Override
public String lookup(String key) {
Optional<String> sqlName = definition.parameterNameToSql(key);
check.state(sqlName.isPresent(), "Property: {} not found in object.", key);
return sqlName.get();
}
};
StrSubstitutor s = new StrSubstitutor(lookup, "{{", "}}", '$');
String result = s.replace(sql);
return result;
}
use of org.apache.commons.lang3.text.StrSubstitutor in project spring-cloud-connectors by spring-cloud.
the class PropertiesFileResolver method findCloudPropertiesFileFromClasspath.
/**
* Looks for a resource named {@code filename} (usually {@value #BOOTSTRAP_PROPERTIES_FILENAME}) on the classpath. If present,
* it is loaded and
* inspected for a property named {@value LocalConfigConnector#PROPERTIES_FILE_PROPERTY}, which is interpolated from the system
* properties and returned.
*
* @return the filename derived from the classpath control file, or {@code null} if one couldn't be found
*/
File findCloudPropertiesFileFromClasspath() {
// see if we have a spring-cloud.properties at all
InputStream in = getClass().getClassLoader().getResourceAsStream(classpathPropertiesFilename);
if (in == null) {
logger.info("no " + classpathPropertiesFilename + " found on the classpath to direct us to an external properties file");
return null;
}
// load it as a properties file
Properties properties = new Properties();
try {
properties.load(in);
} catch (IOException e) {
logger.log(Level.SEVERE, "found " + classpathPropertiesFilename + " on the classpath but couldn't load it as a properties file", e);
return null;
}
// read the spring.cloud.propertiesFile property from it
String template = properties.getProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY);
if (template == null) {
logger.log(Level.SEVERE, "found properties file " + classpathPropertiesFilename + " on the classpath, but it didn't contain a property named " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY);
return null;
}
// if there's anything else, the client probably tried to put an app ID or other credentials there
if (properties.entrySet().size() > 1)
logger.warning("the properties file " + classpathPropertiesFilename + " contained properties besides " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY + "; ignoring");
logger.fine("substituting system properties into '" + template + "'");
File configFile = new File(new StrSubstitutor(systemPropertiesLookup(env)).replace(template));
logger.info("derived configuration file name: " + configFile);
return configFile;
}
use of org.apache.commons.lang3.text.StrSubstitutor in project stanbol by apache.
the class KiWiRepositoryService method activate.
@Activate
protected final void activate(ComponentContext context) throws ConfigurationException, RepositoryException {
log.info("activate KiWi repository ...");
if (context == null || context.getProperties() == null) {
throw new IllegalStateException("No valid" + ComponentContext.class + " parsed in activate!");
}
//copy the read-only configuration as we might need to change it before
//adding it to the registered service
final Dictionary<String, Object> config = copyConfig(context);
final BundleContext bc = context.getBundleContext();
//we want to substitute variables used in the dbURL with configuration,
//framework and system properties
StrSubstitutor strSubstitutor = new StrSubstitutor(new StrLookup<Object>() {
@Override
public String lookup(String key) {
Object val = config.get(key);
if (val == null) {
val = bc.getProperty(key);
}
return val.toString();
}
});
String name = (String) config.get(REPOSITORY_ID);
if (StringUtils.isBlank(name)) {
throw new ConfigurationException(REPOSITORY_ID, "The parsed Repository ID MUST NOT be NULL nor blank!");
} else {
log.debug(" - name: {}", name);
}
KiWiDialect dialect;
String db_type;
if (StringUtils.equalsIgnoreCase("postgres", (String) config.get(DB_DIALECT))) {
dialect = new PostgreSQLDialect();
db_type = "postgresql";
} else if (StringUtils.equalsIgnoreCase("mysql", (String) config.get(DB_DIALECT))) {
dialect = new MySQLDialect();
db_type = "mysql";
} else if (StringUtils.equalsIgnoreCase("h2", (String) config.get(DB_DIALECT))) {
dialect = new H2Dialect();
db_type = "h2";
} else {
throw new ConfigurationException(DB_DIALECT, "No valid database dialect was given");
}
log.debug(" - dialect: {}", dialect);
String db_url = (String) config.get(DB_URL);
if (StringUtils.isBlank(db_url)) {
//build the db url from parameters
String db_host = (String) config.get(DB_HOST);
if (StringUtils.isBlank(db_host)) {
db_host = DEFAULT_DB_HOST;
}
log.debug(" - db host: {}", db_host);
String db_name = (String) config.get(DB_NAME);
if (StringUtils.isBlank(db_name)) {
db_name = DEFAULT_DB_NAME;
}
log.debug(" - db name: {}", name);
int db_port;
Object value = config.get(DB_PORT);
if (value instanceof Number) {
db_port = ((Number) value).intValue();
} else if (value != null && !StringUtils.isBlank(value.toString())) {
db_port = Integer.parseInt(value.toString());
} else {
db_port = DEFAULT_DB_PORT;
}
log.debug(" - db port: {}", db_port);
String db_opts = (String) config.get(DB_OPTS);
log.debug(" - db options: {}", db_opts);
StringBuilder dbUrlBuilder = new StringBuilder("jdbc:").append(db_type);
if (dialect instanceof H2Dialect) {
//H2 uses a file path and not a host so we do not need the ://
dbUrlBuilder.append(':').append(db_host);
} else {
dbUrlBuilder.append("://").append(db_host);
}
if (db_port > 0) {
dbUrlBuilder.append(':').append(db_port);
}
if (!StringUtils.isBlank(db_name)) {
dbUrlBuilder.append('/').append(db_name);
}
if (!StringUtils.isBlank(db_opts)) {
dbUrlBuilder.append(db_opts);
}
dbUrl = strSubstitutor.replace(dbUrlBuilder);
} else if (!db_url.startsWith("jdbc:")) {
throw new ConfigurationException(DB_URL, "Database URLs are expected to start with " + "'jdbc:' (parsed: '" + db_url + "')!");
} else {
dbUrl = strSubstitutor.replace(db_url);
}
String db_user = (String) config.get(DB_USER);
if (StringUtils.isBlank(db_user)) {
db_user = DEFAULT_DB_USER;
} else {
db_user = strSubstitutor.replace(db_user);
}
log.debug(" - db user: {}", db_user);
String db_pass = (String) config.get(DB_PASS);
if (StringUtils.isBlank(db_pass)) {
log.debug(" - db pwd is set to default");
db_pass = DEFAULT_DB_PASS;
} else {
log.debug(" - db pwd is set to parsed value");
}
KiWiConfiguration configuration = new KiWiConfiguration("Marmotta KiWi", dbUrl, db_user, db_pass, dialect);
//parse cluster options
String cluster = (String) config.get(CLUSTER);
if (!StringUtils.isBlank(cluster)) {
log.debug(" - cluster: {}", cluster);
configuration.setClustered(true);
configuration.setClusterName(cluster);
String clusterAddress = (String) config.get(CLUSTER_ADDRESS);
if (!StringUtils.isBlank(clusterAddress)) {
configuration.setClusterAddress(strSubstitutor.replace(clusterAddress));
}
log.debug(" - cluster address: {}", configuration.getClusterAddress());
Object clusterPort = config.get(CLUSTER_PORT);
if (clusterPort instanceof Number) {
int port = ((Number) clusterPort).intValue();
if (port > 0) {
configuration.setClusterPort(port);
}
//else use default
} else if (clusterPort != null) {
try {
int port = Integer.parseInt(strSubstitutor.replace(clusterPort));
if (port > 0) {
configuration.setClusterPort(port);
}
} catch (NumberFormatException e) {
throw new ConfigurationException(CLUSTER_PORT, "Unable to parse " + "Cluster Port from configured value '" + clusterPort + "'!", e);
}
}
log.debug(" - cluster port ({})", configuration.getClusterPort());
String cachingBackend = (String) config.get(CACHING_BACKEND);
if (StringUtils.isBlank(cachingBackend)) {
configuration.setCachingBackend(CachingBackends.valueOf(DEFAULT_CACHING_BACKEND));
} else {
try {
configuration.setCachingBackend(CachingBackends.valueOf(strSubstitutor.replace(cachingBackend)));
} catch (IllegalArgumentException e) {
throw new ConfigurationException(CACHING_BACKEND, "Unsupported CachingBackend '" + cachingBackend + "' (supported: " + Arrays.toString(CachingBackends.values()) + ")!", e);
}
}
log.debug(" - caching Backend: {}", configuration.getCachingBackend());
String cacheMode = (String) config.get(CACHE_MODE);
if (StringUtils.isBlank(cacheMode)) {
cacheMode = DEFAULT_CACHE_MODE;
}
try {
configuration.setCacheMode(CacheMode.valueOf(strSubstitutor.replace(cacheMode)));
} catch (IllegalArgumentException e) {
throw new ConfigurationException(CACHE_MODE, "Unsupported CacheMode '" + cacheMode + "' (supported: " + Arrays.toString(CacheMode.values()) + ")!");
}
log.debug(" - cache mode: {}", configuration.getCacheMode());
} else {
// not clustered
log.debug(" - no cluster configured");
configuration.setClustered(false);
}
log.info(" ... initialise KiWi repository: {}", dbUrl);
KiWiStore store = new KiWiStore(configuration);
repository = new SailRepository(new KiWiSparqlSail(store));
repository.initialize();
//set the repository type property to KiWiStore
config.put(SAIL_IMPL, KiWiStore.class.getName());
repoRegistration = context.getBundleContext().registerService(Repository.class.getName(), repository, config);
log.info(" - successfully registered KiWi Repository {}", name);
}
use of org.apache.commons.lang3.text.StrSubstitutor in project tomee by apache.
the class Container method start.
public void start() throws Exception {
if (base == null || !base.exists()) {
setup(configuration);
}
final Properties props = configuration.getProperties();
if (props != null) {
StrSubstitutor substitutor = null;
for (final String s : props.stringPropertyNames()) {
final String v = props.getProperty(s);
if (v != null && v.contains("${")) {
if (substitutor == null) {
final Map<String, String> placeHolders = new HashMap<>();
placeHolders.put("tomee.embedded.http", Integer.toString(configuration.getHttpPort()));
placeHolders.put("tomee.embedded.https", Integer.toString(configuration.getHttpsPort()));
placeHolders.put("tomee.embedded.stop", Integer.toString(configuration.getStopPort()));
substitutor = new StrSubstitutor(placeHolders);
}
props.put(s, substitutor.replace(v));
}
}
// inherit from system props
final Properties properties = new Properties(System.getProperties());
properties.putAll(configuration.getProperties());
Logger.configure(properties);
} else {
Logger.configure();
}
final File conf = new File(base, "conf");
final File webapps = new File(base, "webapps");
final String catalinaBase = base.getAbsolutePath();
// set the env before calling anoything on tomcat or Catalina!!
// TODO: save previous value and restore in stop
System.setProperty("catalina.base", catalinaBase);
System.setProperty("openejb.deployments.classpath", "false");
System.setProperty("catalina.home", catalinaBase);
System.setProperty("catalina.base", catalinaBase);
System.setProperty("openejb.home", catalinaBase);
System.setProperty("openejb.base", catalinaBase);
System.setProperty("openejb.servicemanager.enabled", "false");
copyFileTo(conf, "catalina.policy");
copyTemplateTo(conf, "catalina.properties");
copyFileTo(conf, "context.xml");
copyFileTo(conf, "openejb.xml");
copyFileTo(conf, "tomcat-users.xml");
copyFileTo(conf, "web.xml");
final boolean initialized;
if (configuration.hasServerXml()) {
final File file = new File(conf, "server.xml");
if (!file.equals(configuration.getServerXmlFile())) {
final FileOutputStream fos = new FileOutputStream(file);
try {
IO.copy(configuration.getServerXmlFile(), fos);
} finally {
IO.close(fos);
}
}
// respect config (host/port) of the Configuration
final QuickServerXmlParser ports = QuickServerXmlParser.parse(file);
if (configuration.isKeepServerXmlAsThis()) {
// force ports to be able to stop the server and get @ArquillianResource
configuration.setHttpPort(Integer.parseInt(ports.http()));
configuration.setStopPort(Integer.parseInt(ports.stop()));
} else {
final Map<String, String> replacements = new HashMap<String, String>();
replacements.put(ports.http(), String.valueOf(configuration.getHttpPort()));
replacements.put(ports.https(), String.valueOf(configuration.getHttpsPort()));
replacements.put(ports.stop(), String.valueOf(configuration.getStopPort()));
IO.copy(IO.slurp(new ReplaceStringsInputStream(IO.read(file), replacements)).getBytes(), file);
}
tomcat.server(createServer(file.getAbsolutePath()));
initialized = true;
} else {
copyFileTo(conf, "server.xml");
initialized = false;
}
if (props != null && !props.isEmpty()) {
final File file = new File(conf, "system.properties");
if (file.isFile()) {
final Properties existing = IO.readProperties(file);
for (final String key : existing.stringPropertyNames()) {
if (!props.containsKey(key)) {
props.put(key, existing.getProperty(key));
}
}
}
final FileWriter systemProperties = new FileWriter(file);
try {
props.store(systemProperties, "");
} finally {
IO.close(systemProperties);
}
}
// Need to use JULI so log messages from the tests are visible
// using openejb logging conf in embedded mode
/* if we use our config (Logger.configure()) don't override it
copyFileTo(conf, "logging.properties");
System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager");
final File logging = new File(conf, "logging.properties");
if (logging.exists()) {
System.setProperty("java.util.logging.config.file", logging.getAbsolutePath());
}
*/
// Trigger loading of catalina.properties
CatalinaProperties.getProperty("foo");
tomcat.setBaseDir(base.getAbsolutePath());
tomcat.setHostname(configuration.getHost());
if (!initialized) {
tomcat.getHost().setAppBase(webapps.getAbsolutePath());
tomcat.getEngine().setDefaultHost(configuration.getHost());
tomcat.setHostname(configuration.getHost());
}
if (configuration.getRealm() != null) {
tomcat.getEngine().setRealm(configuration.getRealm());
}
if (tomcat.getRawConnector() == null && !configuration.isSkipHttp()) {
final Connector connector = createConnector();
connector.setPort(configuration.getHttpPort());
if (connector.getAttribute("connectionTimeout") == null) {
connector.setAttribute("connectionTimeout", "3000");
}
if (configuration.isHttp2()) {
// would likely need SSLHostConfig programmatically
connector.addUpgradeProtocol(new Http2Protocol());
}
tomcat.getService().addConnector(connector);
tomcat.setConnector(connector);
}
// create https connector
if (configuration.isSsl()) {
final Connector httpsConnector = createConnector();
httpsConnector.setPort(configuration.getHttpsPort());
httpsConnector.setSecure(true);
httpsConnector.setProperty("SSLEnabled", "true");
httpsConnector.setProperty("sslProtocol", configuration.getSslProtocol());
if (configuration.getKeystoreFile() != null) {
httpsConnector.setAttribute("", configuration.getKeystoreFile());
}
if (configuration.getKeystorePass() != null) {
httpsConnector.setAttribute("keystorePass", configuration.getKeystorePass());
}
httpsConnector.setAttribute("keystoreType", configuration.getKeystoreType());
if (configuration.getClientAuth() != null) {
httpsConnector.setAttribute("clientAuth", configuration.getClientAuth());
}
if (configuration.getKeyAlias() != null) {
httpsConnector.setAttribute("keyAlias", configuration.getKeyAlias());
}
if (configuration.isHttp2()) {
// would likely need SSLHostConfig programmatically
httpsConnector.addUpgradeProtocol(new Http2Protocol());
}
tomcat.getService().addConnector(httpsConnector);
if (configuration.isSkipHttp()) {
tomcat.setConnector(httpsConnector);
}
}
for (final Connector c : configuration.getConnectors()) {
tomcat.getService().addConnector(c);
}
if (!configuration.isSkipHttp() && !configuration.isSsl() && !configuration.getConnectors().isEmpty()) {
tomcat.setConnector(configuration.getConnectors().iterator().next());
}
// Bootstrap Tomcat
// create it after Logger is configured
Logger.getInstance(LogCategory.OPENEJB_STARTUP, Container.class).info("Starting TomEE from: " + base.getAbsolutePath());
if (configuration.getUsers() != null) {
for (final Map.Entry<String, String> user : configuration.getUsers().entrySet()) {
tomcat.addUser(user.getKey(), user.getValue());
}
}
if (configuration.getRoles() != null) {
for (final Map.Entry<String, String> user : configuration.getRoles().entrySet()) {
for (final String role : user.getValue().split(" *, *")) {
tomcat.addRole(user.getKey(), role);
}
}
}
if (!initialized) {
tomcat.init();
}
tomcat.start();
// Bootstrap OpenEJB
final Properties properties = new Properties();
properties.setProperty("openejb.deployments.classpath", "false");
properties.setProperty("openejb.loader", "tomcat-system");
properties.setProperty("openejb.home", catalinaBase);
properties.setProperty("openejb.base", catalinaBase);
properties.setProperty("openejb.servicemanager.enabled", "false");
if (configuration.getProperties() != null) {
properties.putAll(configuration.getProperties());
}
if (properties.getProperty("openejb.system.apps") == null) {
// will make startup faster and it is rarely useful for embedded case
properties.setProperty("openejb.system.apps", "false");
}
if (configuration.isQuickSession()) {
properties.put("openejb.session.manager", QuickSessionManager.class.getName());
}
try {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final Properties tomcatServerInfo = IO.readProperties(classLoader.getResourceAsStream("org/apache/catalina/util/ServerInfo.properties"), new Properties());
String serverNumber = tomcatServerInfo.getProperty("server.number");
if (serverNumber == null) {
// Tomcat5 only has server.info
final String serverInfo = tomcatServerInfo.getProperty("server.info");
if (serverInfo != null) {
final int slash = serverInfo.indexOf('/');
serverNumber = serverInfo.substring(slash + 1);
}
}
if (serverNumber != null) {
System.setProperty("tomcat.version", serverNumber);
}
final String serverBuilt = tomcatServerInfo.getProperty("server.built");
if (serverBuilt != null) {
System.setProperty("tomcat.built", serverBuilt);
}
} catch (final Throwable e) {
// no-op
}
final TomcatLoader loader = new TomcatLoader();
loader.initDefaults(properties);
// need to add properties after having initialized defaults
// to properties passed to SystemInstance otherwise we loose some of them
final Properties initProps = new Properties();
initProps.putAll(System.getProperties());
initProps.putAll(properties);
if (SystemInstance.isInitialized()) {
SystemInstance.get().getProperties().putAll(initProps);
} else {
SystemInstance.init(initProps);
}
SystemInstance.get().setComponent(StandardServer.class, (StandardServer) tomcat.getServer());
// needed again cause of init()
SystemInstance.get().setComponent(Server.class, tomcat.getServer());
loader.initialize(properties);
assembler = SystemInstance.get().getComponent(Assembler.class);
configurationFactory = new ConfigurationFactory();
if (configuration.isWithEjbRemote()) {
tomcat.getHost().addChild(new TomEERemoteWebapp());
}
}
Aggregations