Generated test can't read property from application.yml - spring-cloud-contract

Just trying hands with Spring Cloud Contract. While running the generated test on provider side and when the application context is instantiated, it is unable to read config values from application.yml. When i move the test from generated build folder to src/test/java then issue is not seen anymore.
Which implies since build folder is outside of project src/.. structure, it can't read the config.
How can i fix it?

How do you access the value from application.yml
Let's suppose in application.yml you have the following content:
example:
baseUri: https://jsonplaceholder.typicode.com
You can simply access it in your test using:
#Value("${example.baseUri}")
String exampleBaseUri;
Additionally, if you want a profile just for tests you can create a file application-test.yml where you add properties. To access it values from this file you need to add before your test class:
#ActiveProfiles("test")

Related

Configure a symfony database connection from ini file?

On the server I need to deploy my symfony 5.2.4 application, the database configuration is defined in an ini file for which the path is set as an environment variable.
The way I have done it right now is to run composer dump-env dev then in .env.local.php, add some code to load the inifile, parse it, then construct my database url and set DATABASE_URL to that value like that:
$inifile = parse_ini_file($_SERVER["DB_INI_PATH"]);
$databaseurl = 'mysql://'.$inifile["user"].':'.$inifile["password"].'#'.$inifile["host"].':'.$inifile["port"].'/'.$inifile["db"];
But this means that I have some code in this file that can't be versioned (because it also contains my APP_SECRET value), and anytime I need to redump my env, I will need to readd that custom code.
I have not found a proper place to add this ini file decoding process in my symfony app, so I am looking for any advice on the proper way to do that, in a way that would be versionable.
You can write your doctrine config in php and you will have access to environment variables. You can add your logic in "config/packages/prod/doctrine.php". The example in the docs shows how to set doctrine.dbal.url go here and click on the php tab for the example code: https://symfony.com/doc/current/configuration.html#configuration-based-on-environment-variables

Spring MVC application.properties not override by profile file application-dev.properties

I was looking at a way to configure different application.properties file depending on a JVM environnement variable.
I found this documentation on Spring references.
In addition to application.properties files, profile-specific properties can also be defined using the naming convention application-{profile}.properties.
Profile specific properties are loaded from the same locations as standard application.properties, with profile-specific files always overriding the default ones irrespective of whether the profile-specific files are inside or outside your packaged jar.
Then I did that :
Configuration structure
And then added a -Dspring.profiles.active=dev to my JVM options.
Profile option for JVM
I tried to see that my params in dev are used but it isn't the case. Te application loads the data from the application.properties file.
Any idea why?
Try to modify the default properties file's name to 'application-default.properties', as it is said in the documentation:
The Environment has a set of default profiles (by default [default]) which are used if no active profiles are set (i.e. if no profiles are explicitly activated then properties from application-default.properties are loaded).
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

Spring Boot Environment-specific configurations

I have a spring boot application that uses the actuator, auto-configuration and JPA. I want to be able to use an in-memory DB in my test profile, a MySQL DB configuration during development and a separate production DB configuration when the app is deployed in production. Presumably from the java command line I should be able to specify the environment and the right configuration file or config block in application.properties (or .yml) will be picked up.
I have not found a good post with example describing how to do this switching so I thought I'd ask if anyone has a good example. My main aim is to pre-define the spring.datasource and spring.jpa properties at build time and then at run-time switch the app config per environment "dynamically" using the java command line argument. Secondary goal would be to do the same with the management configurations, etc.
Thank you.
Thanks to #Richard for the mention of spring.profiles.active JVM variable. Since my question was specific to the way Spring Boot does this and since there is much more to the answer, I am inclined to answer this myself and include all the details of how I arrived at the answer in the hopes that it will save others time.
First, you can indeed pick the correct profile on the java command line by adding -Dspring.profiles.active=profile_name when you are running your Spring Boot app. (this is assuming your deployment preference is an uber jar with embedded container - Tomcat in my case)
I wanted to leave MySQL datasource configurations under the default profile and put H2 in-memory datasource configuration under a test profile. However, the way Spring Boot picks the right datasource based on profile is not so obvious. Even though I had MySQL details under the default profile and I had the in-memory H2 datasource details under the test profile, it would still pick H2 as the datasource even when spring.profiles.active was omitted from the command line. This was contrary to my assumption that default profile will be picked, well, by default :-)
I ended up having to put H2 configuration under the default profile and then create a local profile that included the MySQL datasource configuration. Here's what I ended up with in my application.yml
spring:
profiles: default
spring:
datasource:
driverClassName: org.h2.Driver
url: jdbc:h2:mem:sampletest;MODE=MySQL
---
spring:
profiles: test
spring.jpa:
hibernate:
ddl-auto: create-drop
---
spring:
profiles: local
spring.datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1/sampledev
username: sample
password: sample
spring.jpa:
hibernate:
dialect: org.hibernate.dialect.MySQLInnoDBDialect
ddl-auto: update
This worked. I was able to switch between default profiles and the local profile by omitting or adding the -Dspring.profiles.active=local on the java command line. Because test profile inherits from default it is also using H2
One more nuance: I added ddl-auto: create-drop to the test profile which uses the in-memory DB to facilitate automatic table creation / teardown for unit tests. But for the local profile which uses MySQL I changed it to update. Implication being that for the local profile I have to first create the database outside of the application.
this article shows how to use spring profiles, available in spring 3.1 and later. It will do exactly what you want.
http://chariotsolutions.com/blog/post/spring-3-1-environment-profiles-2/
set a JVM variable like this: spring.profiles.active=development
then in your configuration xml you can wrap environment specific xml with the profile tags
<beans profiles="development">
<bean id="dataSource" class="..."></bean>
<bean id="messagingProvider" class="..."></bean>
</beans>
You can also set the profile on annotation-driven classes with #Profile("development") at the beginning of the class. That class will only be autowired if the profile matches.
For unit tests you can set the active profile on a test class with #ActiveProfile(profiles = "test", "CI"), it will run using test and CI resources

Editing configuration files in Pax Exam

I am using Pax Exam to perform integration tests to my OSGi application. I have a configuration factory in which I specify the Karaf feature of my application to be installed in the test container and then modify some of a proerty of a .cfg file installed as part of my feature.
public class TestConfigurationFactory implements ConfigurationFactory {
#Override
public Option[] createConfiguration() {
return options(
karafDistributionConfiguration()
.frameworkUrl(
maven().groupId("org.apache.karaf")
.artifactId("apache-karaf")
.version("3.0.1").type("tar.gz"))
.unpackDirectory(new File("target/exam"))
.useDeployFolder(false),
keepRuntimeFolder(),
// Karaf (own) features.
KarafDistributionOption.features(
maven().groupId("org.apache.karaf.features")
.artifactId("standard").classifier("features")
.version("3.0.1").type("xml"), "scr"),
// CXF features.
KarafDistributionOption.features(maven()
.groupId("org.apache.cxf.karaf")
.artifactId("apache-cxf").version("2.7.9")
.classifier("features").type("xml")),
// Application features.
KarafDistributionOption.features(
maven().groupId("com.me.project")
.artifactId("my-karaf-features")
.version("1.0.0-SNAPSHOT")
.classifier("features").type("xml"), "my-feature"),
KarafDistributionOption.editConfigurationFilePut(
"etc/com.me.test.cfg", "key", "value"));
}
}
The property I specify in editConfigurationFilePut is modified correctly, however the rest of the .cfg file's properties are deleted. If I use the editConfigurationFilePut method to edit one of Karaf's configuration files it works as expected (just adds the new property without modifying the existing ones) so I am thinking that perhaps the problem is that Pax Exam attempts to modify the configuration before the .cfg file is installed by my feature and therefore creates a new file to put the property in. If this is the case is there some way to synchronise this process so that the .cfg file is edited only after the feature is properly installed?
There are a two different reasons for this.
1) The feature does get installed after the configfile has been "edited"
2) The feature only contains a config section and not a configfile section
I'd guess reason one is the most likely cause of this since it needs a running Karaf to install a feature through Pax Exam. So to work around reason one, replace the config with a config file present in your test project.
For reason two, make sure the feature actually does reference a config instead of a configuration admin config, or add your config to the configuration of the config-admin service. You can achieve this by injecting the ConfigAdmin service in your unit test and add your properties to the configuration pid.
EDIT:
Combine both solutions
Since because of 1) it takes longer for the config-file to be actually available, let config-admin service do the rest.
Make sure your test does retrieve the config-admin service either by injecting it or by waiting for it's availability.
Now within a #Before method make sure you wait till your config is complete and change it from there on. This way you don't need to duplicate the config files.

Access Resource File

Can anyone tell how to access resource file in class library asp.net mvc4? I'm building a generic Class Library that I will use it in all my projects. I tried with following code:
HttpContext.GetGlobalResourceObject();
Can anyone tell any other method is there to access the resource file in class library?
Edit based on the comments, including best practices :
To create a Resource file in MVC4 :
In the solution explorer, right click on your project.
Then, you click on "Add", then on "Add ASP.Net folder", and then click on App_GlobalResources.
On the new folder, you right click. Then you add a new Resource File.
You open then this Resource file and can add new resources.
The lefter column is where you set the keys, and the righter one is for the values you have to insert inside it.
Then; it is really easy, you just have to write the following parts of code to access the values you want.
On the c# side, it is :
Resources.NameOfYourResFile.NameOfYourResKey
On the ASP side, assuming that you're using razor, it is :
#Resources.NameOfYourResFile.NameOfYourResKey
Example :
If you have created a a file named "Global.resx", and created the key "ApplicationTitle", which has "My super website" as value, you just have to write the following line of code to put it for example into a string :
string siteTitle = Resources.Global.ApplicationTitle;
and that's it
When you create your resource you have to set the access level from internal (by default) to public. After this you simply can access your resources (if you reference the assembly) by the name of the resource and the static properties generated into them.
I would suggest you to create a new library for Resources
Once you are done making resources key value pairs then add the reference of your Resource Library in to your project. and then you are able to access the resource library in this way
Namespace.ReourceLibraryName.Key
just include System.Web.dll in your class library project and access the resource file just like you would have accessed in the MVC project
HttpContext.GetGlobalResourceObject();
when you add a refrence to this class library project inside your MVC project and run the project this code will be executed in the context of the MVC project and you will get the correct instance of HttpContext.
Note:- directly using HttpContext like this would create problems when you will try to test this application
You can add your resource file any where in your class library, but I think your question is how to use it, If your resource files name is Res1.resx and there is a key in it called message then you can call
Res1.message
from your classes in that library. But you I am sure you would like to use it event from out side the library for that you need to make your resource file public, please refer Visual Studio - Resx File default 'internal' to 'public'
please do let me know if it is the one you need or some thing else?

Resources