Spring boot application properties with different keys [duplicate] - java

This question already has answers here:
Spring Boot - inject map from application.yml
(8 answers)
Closed 4 years ago.
How can i define a Object to read my application.mysql-databases by key:
swaw:
stage: dev
ip: x.x.x.x
port: 3306
databases:
mysql:
url: "jdbc:mysql://...."
password:
dba: AAA
read: BBB
mssql:
url: "jdbc:mssql://...."
password:
dba: CCC
read: DDD
informix:
....
I try with this object:
#ConfigurationProperties(prefix = "swaw.databases")
public class Databases {
private Map<String, DatabasesConfig> map;
public static class DatabasesConfig {
private String url;
private Password password;
//GETTER AND SETTER
i get per request: {"ip":"1x.x.x.x","port":"3306","databases":null}

#emoleumassi - Try this one :
#ConfigurationProperties(prefix = "databases")
public class Databases {
private String url;
private Password password;
//GETTER AND SETTER
}

Related

Dijital Ocean spaces listObjects not working

My application.yml
## PostgreSQL
spring:
datasource:
url: jdbc:postgresql://myip:5432/db?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
username: wqeqe
password: qweqwewqe$qwewqe
jpa:
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
show-sql: true
---
server:
port: 8085
## DO properties
do:
spaces:
key: mykey
secret: mysecret
endpoint: digitaloceanspaces.com
region: myregion
bucket: mybusket
My read config read appication.yml
#Configuration
#PropertySource("classpath:application.yml")
#ConfigurationProperties(prefix = "do.spaces")
public class DoConfig {
#Value("${key}")
private String doSpaceKey;
#Value("${secret}")
private String doSpaceSecret;
#Value("${endpoint}")
private String doSpaceEndpoint;
#Value("${region}")
private String doSpaceRegion;
#Bean
public AmazonS3 getS3() {
BasicAWSCredentials creds = new BasicAWSCredentials(doSpaceKey, doSpaceSecret);
return AmazonS3ClientBuilder.standard()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(doSpaceEndpoint, doSpaceRegion))
.withCredentials(new AWSStaticCredentialsProvider(creds)).build();
}
}
My service
#Override
public List<TemplateDto> getAll() {
return (List<TemplateImage>) templateImageRepository.findAll();
}
My repo
#Repository
public interface TemplateImageRepository extends PagingAndSortingRepository<TemplateImage,Long> {
}
Hi everyone I am using this project dijital ocean spaces but the problem listObject images don't return null. What is the problem please help me I am new working is the file servers.
Thanks !!!

Multiple databases in dropwizard

I am trying to read and write into two databases and I am running into issues:
config.yml
database1:
driverClass: com.mysql.jdbc.Driver
user: user1
password: user!23
url: jdbc:mysql://url.to.connect:3306/db1
properties: charSet: UTF-8
maxWaitForConnection: 1s
minSize: 8
maxSize: 32
checkConnectionWhileIdle: false
checkConnectionHealthWhenIdleFor: 10s
closeConnectionIfIdleFor: 1 minute
database2:
driverClass: com.mysql.jdbc.Driver
user: user2
password: user!23
url: jdbc:mysql://url.to.connect:3306/db2
properties: charSet: UTF-8
maxWaitForConnection: 1s
minSize: 8
maxSize: 32
checkConnectionWhileIdle: false
checkConnectionHealthWhenIdleFor: 10s
closeConnectionIfIdleFor: 1 minute
configuration.java
public class ExampleConfiguration extends Configuration {
#Valid
#NotNull
private DataSourceFactory database1 = new DataSourceFactory();
#Valid
#NotNull
private DataSourceFactory database2 = new DataSourceFactory();
#JsonProperty("database1")
public DataSourceFactory getDb1DataSourceFactory() {
return database1;
}
#JsonProperty("database2")
public DataSourceFactory getDb2DataSourceFactory() {
return database2;
}
}
Now following: Maintain multiple migration files in parallel in dropwizard, I tried to add a bootstrap bundle as follows:
#Override
public void initialize(Bootstrap< ExampleConfiguration > bootstrap) {
bootstrap.addCommand(new RenderCommand());
bootstrap.addBundle(new AssetsBundle());
bootstrap.addBundle(new MigrationsBundle<ExampleConfiguration>() {
#Override
public DataSourceFactory getDataSourceFactory(ExampleConfiguration configuration) {
return configuration.getDb1DataSourceFactory();
}
});
bootstrap.addBundle(new MigrationsBundle<ExampleConfiguration>() {
#Override
public DataSourceFactory getDataSourceFactory(ExampleConfiguration configuration) {
return configuration.getDb2DataSourceFactory();
}
});
bootstrap.addBundle(hibernateBundle);
}
But I got command 'db' has been already used. I am still unclear what is happening in initialize(). How can I switch between DB instances for read and write operations?
Thank you.
You should override each MigrationsBundle implementation's method name to provide unique command's name. Then using CLI you will need to specify correct name to use according database configuration.

how to get values to spring.boot.admin.client.username/ password from database?

I have spring boot admin project and now I hardcoded the username and passwords in application.properties file like this.
spring.boot.admin.client.username=user
spring.boot.admin.client.password=pass
spring.boot.admin.client.instance.metadata.user.name=user
spring.boot.admin.client.instance.metadata.user.password=pass
But want to get that values from database not hardcoded like this.I want to configs to connect to self register the admin server as a client.I am beginner to SpringBoot. How can I do it? Thanks.
So every configuration in an application.properties file can be configured via Javacode. First you have to create a Datasource for your project. Add the spring-data-jpa dependency to your project and config the datasource.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
more you can find here: A Guide to JPA with Spring
To configure for example the two properties spring.boot.admin.client.username=user and spring.boot.admin.client.password=pass you need to create a #Configuration class which creates a ClientProperties Bean.
#Configuration
public class AdminClientConfig {
private final JdbcTemplate jdbcTemplate;
private final Environment environment;
public AdminClientConfig(JdbcTemplate jdbcTemplate,
Environment environment) {
super();
this.jdbcTemplate = jdbcTemplate;
this.environment = environment;
}
#Bean
public ClientProperties clientProperties() {
ClientProperties cp = new ClientProperties(environment);
cp.setUsername(getUsername());
cp.setPassword(getPassword());
return cp;
}
private String getUsername() {
String username = jdbcTemplate.queryForObject(
"select username from AnyTable where id = ?",
new Object[] { "123" }, String.class);
return username;
}
private String getPassword() {
String password = jdbcTemplate.queryForObject(
"select password from AnyTable where id = ?",
new Object[] { "123" }, String.class);
return password;
}
}
So the JdbcTemplate has already a Database connection and creates the query to get the Username and Password from the Database. The ClientProperties Bean can then be set.
P.S.: This code is not tested but gives you a some hints to get the job done.

Setting up Spring Data LDAP Embedded for tests with base DN

I have a weird behaviour of Spring Data Ldap and was wondering how I can fight it.
From the looks of it, it seems that the base information is either lost or handled differently when I use a "proper" LDAP server and the embedded version.
The embedded version should be used for some of my integration tests. But what works perfectly fine when I configure my LDAP server like so:
spring:
ldap:
urls: ldap://localhost:389
base: dc=e-mehlbox,dc=eu
username: cn=admin,dc=e-mehlbox,dc=eu
password: root
in my application.yml. But once I set up the embedded server, my searches fail:
spring:
ldap:
urls: ldap://localhost:9321
base: dc=e-mehlbox,dc=eu
username: uid=admin
password: secret
embedded:
base-dn: dc=e-mehlbox,dc=eu
credential:
username: uid=admin
password: secret
ldif: classpath:test-schema.ldif
port: 9321
validation:
enabled: false
Enabling debugging, it shows the missing base DN. Here are the corresponding lines for the working configuration agains a "real" LDAP server:
2018-01-10 18:06:55.296 DEBUG 23275 --- [ main] o.s.ldap.core.LdapTemplate : Searching - base=ou=internal,ou=Users, finalFilter=(&(&(objectclass=inetOrgPerson)(objectclass=organizationalPerson)(objectclass=person)(objectclass=qmailUser))(uid=big.bird)), scope=javax.naming.directory.SearchControls#6a013bdd
2018-01-10 18:06:55.311 DEBUG 23275 --- [ main] o.s.l.c.support.AbstractContextSource : Got Ldap context on server 'ldap://localhost:389/dc=e-mehlbox,dc=eu'
The interesting bit is the Ldap context, having the base in it.
And this the output when I switch to the embedded LDAP:
2018-01-10 18:08:42.836 DEBUG 23569 --- [ main] o.s.ldap.core.LdapTemplate : Searching - base=ou=internal,ou=Users, finalFilter=(&(&(objectclass=inetOrgPerson)(objectclass=organizationalPerson)(objectclass=person)(objectclass=qmailUser))(uid=big.bird)), scope=javax.naming.directory.SearchControls#55202ba6
2018-01-10 18:08:42.871 DEBUG 23569 --- [ main] o.s.l.c.support.AbstractContextSource : Got Ldap context on server 'ldap://localhost:9321'
I am a bit lost, as I can not find any other configuration options to set the base DN.
Some details of my project:
Right now, I am using the following Spring Data LDAP related dependencies (my project is Gradle driven):
compile (
"org.springframework.boot:spring-boot-starter-data-ldap:1.5.9.RELEASE",
"org.springframework.data:spring-data-ldap:1.0.9.RELEASE"
)
testCompile (
"org.springframework.ldap:spring-ldap-test:2.3.2.RELEASE",
"com.unboundid:unboundid-ldapsdk:4.0.3"
)
And here is one of my entity classes:
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#EqualsAndHashCode(doNotUseGetters = true)
#ToString(doNotUseGetters = true)
#Entry(
objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "qmailUser"},
base = "ou=internal,ou=Users")
public class User implements Serializable {
#Id
private Name dn;
#Attribute(name = "entryUuid", readonly = true)
private String entryUuid;
#Attribute(name = "uid")
private String username;
#Attribute(name = "userPassword")
private byte[] password;
#Attribute(name = "mail")
private String internalMailAddress;
#Attribute(name = "mailAlternateAddress")
private List<String> mailAddresses;
#Attribute(name = "displayName")
private String displayName;
#Attribute(name = "accountStatus")
private String status;
#Attribute(name = "givenName")
private String firstName;
#Attribute(name = "sn")
private String lastName;
#Attribute(name = "mailMessageStore")
private String mailboxHome;
}
Any ideas? Is this a bug or just me not seeing the obvious?
Thanks to #vdubus and this question, I got it working.
It seems like the embedded LDAP server version does not set the configured base DN (see the other SO question). But adding the following class to my project fixes this:
import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.ldap.LdapProperties;
import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.env.Environment;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.support.LdapContextSource;
#Configuration
#EnableConfigurationProperties({LdapProperties.class, EmbeddedLdapProperties.class})
#ConditionalOnClass(InMemoryDirectoryServer.class)
public class EmbeddedLdapConf {
private final Environment environment;
private final LdapProperties properties;
public EmbeddedLdapConf(Environment environment, LdapProperties properties) {
this.environment = environment;
this.properties = properties;
}
#Bean
#DependsOn("directoryServer")
public ContextSource ldapContextSource() {
final LdapContextSource source = new LdapContextSource();
source.setUrls(this.properties.determineUrls(this.environment));
source.setBase(this.properties.getBase());
return source;
}
}
If you prefer to solve it purely in the test properties, you can add the base to the ldap url instead.
I don't know why configuring the embedded ldap messes up the normal ldap config, but this way you can at least verify that it's a properties-only thing that works without additional code.
spring:
ldap:
urls:
- ldap://localhost:12345/dc=stuff,dc=test,dc=my
embedded:
base-dn: dc=stuff,dc=test,dc=my
ldif: classpath:test.ldif
port: 12345
validation:
enabled: false

How set initial size connection to postgresql in application.yml

Always when i connect to my database, I see 10 idle connection. How can I set this in application.yml.
I use spring boot 1.5.6.RELEASE.
It's not working:
spring:
datasource:
maxActive: 5
maxIdle: 5
minIdle: 5
initialSize: 5
When I created #Bean it's working, but I need solution in application.yml
#Configuration
public class DBConfig {
#Value("${dbconfig.driver-class-name}")
private String driverClassName;
#Value("${dbconfig.url}")
private String url;
#Value("${dbconfig.username}")
private String username;
#Value("${dbconfig.password}")
private String password;
#Bean
public DataSource dataSource() throws SQLException {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
I think you're missing to say these are properties. I think the following will work.
spring:
dataSource:
properties:
maxActive: 5
maxIdle: 5
minIdle: 5
initialSize: 5
Note: If you're using tomcat-jdbc, you have to define it explicitly like,
spring:
dataSource:
tomcat:
max-active: 5
max-idle: 5
min-idle: 5
initial-size: 5

Categories