I'm having config issues in Grails 3 and want to hook into the config setup process, unless there's a better way
We have a plugin(jasypt) that requires config set in the application.yml or it throws errors(example below). We need to set the config values in runtime.groovy, but they don't override any values set in the yml
application.yml
jasypt:
algorithm: "PBEWITHSHA256AND256BITAES-CBC-BC"
providerName: "BC"
password: "-"
keyObtentionIterations: 10
runtime.groovy
jasypt {
algorithm = ExternalSecureKeyConfig.getInstance().jasypt.algorithm
providerName = ExternalSecureKeyConfig.getInstance().jasypt.providerName
password = ExternalSecureKeyConfig.getInstance().jasypt.password
keyObtentionIterations = ExternalSecureKeyConfig.getInstance().jasypt.keyObtentionIterations
}
Debugging during startup and runtime shows that none of the config gets overridden (password stays "-"). If I move config from the yml to application.groovy the runtime values get applied but I get the following error on startup
org.jasypt.exceptions.EncryptionInitializationException: If "encryptorRegisteredName" is not specified, then "password" (and optionally "algorithm" and "keyObtentionIterations") must be specified
Currently I'm hoping I can manually set the jsypt config values or hook into the groovy config setup to ensure they override the prev set yml values. Having trouble figuring how to do this or if it's possible
jasypt v 2.0.2 with Grails 3.3.10 (hibernate5, gorm 6.1)
Solve
Overriding the application.yml config with values from a custom config file. Still find is strand the runtime.groovy doesn't override yml config values.
class Application extends GrailsAutoConfiguration implements EnvironmentAware {
static void main(String[] args) {
GrailsApp.run(Application, args)
}
#Override
void setEnvironment(Environment environment) {
URL jasyptConfigUrl = getClass().classLoader.getResource('jasypt.groovy')
if (jasyptConfigUrl) {
def jasyptConfig = new ConfigSlurper().parse(jasyptConfigUrl)
environment.propertySources.addFirst(new MapPropertySource('jasypt.groovy', jasyptConfig))
}
}
}
Related
I want to use two (Mysql) databases in my Springboot application. Following the instructions I use the following configuration
app.properties
spring.datasource.url = jdbc:mysql://localhost:3306/db1?createDatabaseIfNotExist=true&autoReconnect=true
spring.datasource.username = root
spring.datasource.password = password
spring.seconddatasource.url = jdbc:mysql://localhost:3306/db2?createDatabaseIfNotExist=true&autoReconnect=true
spring.seconddatasource.username = root
spring.seconddatasource.password = password
DataSourceConfig.java
#Configuration
public class DataSourceConfig {
#Bean("dataSource")
#Primary
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create()
.type(DriverManagerDataSource.class)
.build();
}
#Bean("secondDataSource")
#ConfigurationProperties(prefix = "spring.seconddatasource")
public DataSource secondDataSource() {
return DataSourceBuilder.create()
.type(DriverManagerDataSource.class)
.build();
}
}
The application starts without errors but only the first database (or whichever datasource bean is marked as primary) gets created. Why not the second?
EDIT:
Once I create the second database manually, the application connects to both of them just fine. It is the automatic creation of the non-primary database only that is causing the problems.
Because you're using #ConfigurationProperties wrong. The annotation most certainly does not point a bean to the relevant configuration. The first DB gets created because, well, spring.datasource.* are actually standard Spring Boot properties.
If you wish to create two data sources, at the very least you'll need to set the appropriate properties (url, password) on the second one yourself. You may inject your custom properties (spring.seconddatasource.*) into the configuration class using #Value, of course.
I am using play java 2.5.
I have created a database with following java code.
public OnStartup() throws SQLException {
//demo create database with java code
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=root&password=12345678");
Statement s = con.createStatement();
int Result = s.executeUpdate("CREATE DATABASE recruit3");
}
Module:
public class OnStartupModule extends AbstractModule {
#Override
public void configure() {
bind(OnStartup.class).asEagerSingleton();
}
}
application.conf:
play.modules {
enabled += "be.objectify.deadbolt.java.DeadboltModule"
enabled += modules.CustomDeadboltHook
enabled += modules.OnStartupModule
}
default.driver=com.mysql.jdbc.Driver
default.url="jdbc:mysql://localhost:3306/recruit3"
default.username=root
default.password="12345678"
My question is, why running the web-app creating
error Cannot connect to database [default]
How to fix that, if I don't want to create the database with mysql workbench.
Any suggestion or cannot do this, please tell me.
Thanks for advance.
As well as moving your database keys to the db.default namespace, you should be injecting Database into OnStartup to access the database configured with those properties.
First, add Play's JDBC support to build.sbt.
libraryDependencies += javaJdbc
If you're already running activator, make sure you use the reload command to pick up the changes to the build.
Update your application.conf to place the database configuration into the correct namespace.
db {
default {
driver=com.mysql.jdbc.Driver
url="jdbc:mysql://localhost:3306/recruit3"
username=root
password="12345678"
}
}
Finally, update OnStartup to receive a Database object that will be injected by Play.
import javax.inject.Inject;
import play.db.Database;
public class OnStartup {
#Inject
public OnStartup(final Database db) throws SQLException {
db.withConnection((Connection conn) -> {
final Statement s = con.createStatement();
return s.executeUpdate("CREATE DATABASE recruit3");
});
}
}
This allows you to configure the database one time, in application.conf, instead of hard-coding DB configuration into a class.
You can find more information here.
Your database keys start with default instead of db.default. The correct syntax is something like this:
db {
default {
driver=com.mysql.jdbc.Driver
url="jdbc:mysql://localhost:3306/recruit3"
username=root
password="12345678"
}
}
You already made your class as eager singleton, so it should work
I am trying to set up an ASP.Net Core application to read in configuration settings from a json file. I am using VS2015 and .NetCore 1.0 (with .Net Core Tools preview 2). I am having problems getting a simple piece of boiler plate code to compile.
I am using the following code, which was published at
http://asp.net-hacker.rocks/2016/03/21/configure-aspnetcore.html
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights
// pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
However, the IDE/compiler complains that 'the name "Configuration" does not exist in the current context' (last line of code). The only suggestion from the IDE is to include Microsoft.Extensions.Configuration. However this is a namespace which does not contain an object or property named "Configuration".
In addition 'AddApplicationInsightsSettings' fails with does IConfigurationBuilder not contain a definition for AddApplicationInsightsSettings and no extension method AddApplicationInsightsSettings accepting a first argument of type IConfigurationBuilder could be found
Any suggestions please ?
Thanks
Simply add Configuration property to your Startup class, tutorial has missed this 'step':
public IConfigurationRoot Configuration { get; set; }
ConfigurationBuilder.Build() method just returns instance of IConfigurationRoot, that you should save, if need to get settings further in Startup class (in ConfigureServices method for example).
Regarding second error, looks like you didn't add the Application Insights dependency:
{
"dependencies": {
"Microsoft.ApplicationInsights.AspNetCore": "1.0.0"
}
}
I'm evaluating asp.net core and .net core and I'm not yet sure about some things. In the past it was possible to configure many components using the web.config out of the box.
To name some examples:
There was the membership-provider and I could implement many providers but I was able ton configure later which provider should be used. This was dependend of the use-case. Now I should use asp.net identity - but I can only find configurations that are performed in sourcecode.
Same for authentication. I can define "CookieAuthentication" and have to set the name, loginpath or the timeout within sourcecode. In the past I was able to set timeout, etc... via web.config.
Is there any way to configure partially these things out of the box from a config-file? Or is this not supported anymore and I have to implement this configuration on my own? In the past this was a really comfortable way.
In ASP.NET Core, Web.config file is used ONLY for IIS configuration, you cannot use it for application configuration, but there are new, better, more flexible configuration options that you can use.
There are multiple configuration sources that you can use, but in this example I'm using json. These examples are from working code in my SimpleAuth project.
You can configure things in startup from configuration files.
First you add a config file in json format that maps to your class. You can see my example class here, and the json file it maps from here
builder.AddJsonFile("simpleauthsettings.json", optional: true);
Then, in the ConfigureServices method you configure your class to be wired up from the config system as shown
services.Configure<SimpleAuthSettings>(Configuration.GetSection("SimpleAuthSettings"));
Then you add an IOptions accessor of your class to the method signature of the Configure method in the Startup.cs
The Dependency Injection will inject it into that method for you so you can use it there to configure things. Specifically I'm setting the cookie authentication scheme and name from my settings object.
The noteworthy part is that you can add whatever you want to the Configure method signature, and as long as it is something that has been registered in the ConfigureServices method, the DI will be able to inject it for you.
public class Startup
{
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
// this file is the custom configuration file to hydrate my settings from
builder.AddJsonFile("simpleauthsettings.json", optional: true);
....
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
....
services.Configure<SimpleAuthSettings>(Configuration.GetSection("SimpleAuthSettings"));
....
}
// note that the DI can inject whatever you need into this method signature
// I added IOptions<SimpleAuthSettings> authSettingsAccessor to the method signature
// you can add anything you want as long as you register it in ConfigureServices
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IOptions<SimpleAuthSettings> authSettingsAccessor
)
{
...
// Add cookie-based authentication to the request pipeline
SimpleAuthSettings authSettings = authSettingsAccessor.Value;
var ApplicationCookie = new CookieAuthenticationOptions
{
AuthenticationScheme = authSettings.AuthenticationScheme,
CookieName = authSettings.AuthenticationScheme,
AutomaticAuthenticate = true,
AutomaticChallenge = true,
LoginPath = new PathString("/Login/Index"),
Events = new CookieAuthenticationEvents
{
//OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
}
};
app.UseCookieAuthentication(ApplicationCookie);
// authentication MUST be added before MVC
app.UseMvc();
}
}
I'm writting bundle with declarative services usage. For configuration I'm using properties in DS declaration. Those props can be normally changed by Config Admin, but they are not persisted. After container restart, component has default values.
I'am using Config admin like this:
Configuration c = configurationAdmin.getConfiguration(UserAgent.SERVICE_PID, null);
System.out.println(c.getProperties()); // every time is null!
Dictionary props = new Hashtable();
props.put(UserAgent.PROPERTY_PORT, 5555);
c.update(props);
and in component I have:
// ...
#Modified
public void updated(ComponentContext context) {
config = context.getProperties();
init();
}
#Activate
protected void activate(ComponentContext context) {
config = context.getProperties();
init();
}
//...
I'm using Felix, properties file is stored in cache
service.bundleLocation="file:bundles/cz.b2m.osgi.phonus.core_1.0.0.SNAPSHOT.jar"
service.pid="cz.b2m.osgi.phonus.sip"
port=I"5555"
But after restart isn't loaded. What I'm doing wrong? Thanks for all tips.
Problem was in Pax Runner which every restart (clean) erased the data folder of Config Admin bundle.
To make sure that Pax Runner does not clear the data, you can use the --usePersistedState=true flag.