How use maven profile propertied in project config.properties - java

I'd use different environments to run testng tests. In pom.xml I specified my profiles like:
<profiles>
<profile>
<id>local</id>
<properties>
<browser.name>firefox</browser.name>
<site.url>my_url1</site.url>
</properties>
</profile>
<profile>
<id>remote</id>
<properties>
<browser.name>chrome</browser.name>
<site.url>my_url2</site.url>
</properties>
</profile>
</profiles>
In config.properties I set following:
browser=${browser.name}
siteUrl=${site.url}
In java code I read properties like:
public static String getProp(String name) {
Properties properties = new Properties();
try {
properties.load(PropertyReader.class.getResourceAsStream("/config.properties"));
} catch (IOException e) {}
String value = "";
if (name != null) {
value = properties.getProperty(name);
}
return value;
}
When I try to run tests using mvn test -Plocal I got errors because properties are not read correctly and browser is equal "${browser.name}" instead of "firefox". How could I fix this?

Related

Spring profiles with Gradle

I'm running a spring boot project with three different property files (application.properties, application-prod.properties, application-uat.properties. I'm using Maven and if I don't specify any argument, it will pick the default property file which is application.properties. Here's how the related files look.
application.properties
#Set active profile
spring.profiles.active=#activatedProperties#
#MongoDB configuration
spring.data.mongodb.host=${MONGODB_HOST:localhost}
spring.data.mongodb.port=${MONGODB_PORT:27017}
spring.data.mongodb.database=database
spring.data.mongodb.username=username
spring.data.mongodb.password=password
pom.xml
<profiles>
<profile>
<id>UAT</id>
<properties>
<activatedProperties>uat</activatedProperties>
</properties>
</profile>
<profile>
<id>PROD</id>
<properties>
<activatedProperties>prod</activatedProperties>
</properties>
</profile>
</profiles>
How can I achieve the same with Gradle? How can I let Gradle to pick the default (application.properties) if I don't specify any arguement?
I think this link will be useful for you...
https://docs.gradle.org/current/userguide/migrating_from_maven.html#migmvn:profiles_and_properties
Sample:
if (!hasProperty('buildProfile')) ext.buildProfile = 'default'
apply from: "profile-${buildProfile}.gradle"
task greeting {
doLast {
println message
}
}
#profile-default.gradle
ext.message = 'foobar'
#profile-test.gradle
ext.message = 'testing 1 2 3'
#profile-prod.gradle
ext.message = 'Hello, world!'
This link can be useful too:
https://www.baeldung.com/spring-profiles

Java9 Module - Maven: ServiceLoader.load( HelloInterface.class) cannot find Interface class

In IntelliJ/Maven I want to work with Java9 / modules and the ServiceLoader. I built a simple 2 module project. Using maven the ServiceLoader.load( ...) cannot find the implementation of the HelloInterface.class. Why?
I created the project via IntelliJ by first adding the 2 modules. Rebuilding the project works fine. Clean/installing via Maven also works fine - well, the unit test fails ;-(
UPDATE 1: Running with IntelliJ is OK due to putting the module-info.java right under the sources root. I compile using the "Rebuild project".
How can I use this 2 module project with the ServiceLoader with Maven?
My simple project struture is:
pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
</plugins>
</build>
<modules>
<module>java9.com.hello</module>
<module>java9.com.hello.client</module>
</modules>
File: module java9.com.hello / src / main / java / module-info.jar
module java9.com.hello {
exports com.hello;
exports com.hello.services;
provides com.hello.services.HelloInterface with com.hello.services.HelloWorldIntefaceImpl;
}
File: module java9.com.hello / com.hello.services.HelloInterface.java
public interface HelloInterface {
String sayHello();
}
File: module java9.com.hello / com.hello.services.HelloWorldIntefaceImpl.java
public class HelloWorldIntefaceImpl implements HelloInterface {
public String sayHello() {
String helloString = "Hello world by Inteface!";
System.out.println( helloString);
return helloString;
}
}
File: module java9.com.hello / pom.xml (without the boilerplate)
<parent>
<artifactId>jdk-new-features</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>java9.com.hello</artifactId>
File: module java9.com.hello.client / src / main / java / module-info.jar.
This file is giving the compiler error.
module java9.com.hello.client {
requires java9.com.hello; // <==== gives the ERROR
uses com.hello.services.HelloInterface;
}
File: module java9.com.hello.client / com.hello.client.HelloWorldClient.java
public class HelloWorldClient {
public static void main (String arg[]) {
HelloWorld hello = new HelloWorld();
System.out.println(hello.sayHelloWorld());
Iterable<HelloInterface> services = ServiceLoader.load(HelloInterface.class);
HelloInterface service = services.iterator().next();
service.sayHello();
}
public String callService() {
Iterable<HelloInterface> services = ServiceLoader.load(HelloInterface.class);
HelloInterface service = services.iterator().next();
return service.sayHello();
}
}
The pom.xml is: module java9.com.hello.client / pom.xml:
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>java9.com.hello</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
Unit test file: module java9.com.hello.client / com.hello.client.HelloWorldClientTest.java
public class HelloWorldClientTest {
#Test
public void testModuleInterfaceImplementation() {
HelloWorldClient helloWorldClient = new HelloWorldClient();
assertEquals( "Hello world by Inteface!", helloWorldClient.callService());
}
}

Caused by: java.util.zip.ZipException: invalid code lengths set

I get this error while trying to build a project on Android Studio. It happens when trying to compress the final artifact with a binary file on res/raw/file.dat.
The solution like explained here: Maven corrupting binary files in source/main/resources when building jar
Is to add the file or res/raw folder to a "false" filtering on build. But the problem is that i configure my internal maven repository with JFrog Articatory following this: https://inthecheesefactory.com/blog/how-to-setup-private-maven-repository/en
The question:
How to convert this:
<project>
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources/lib</directory>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
...
</plugins>
</build>
</project>
Into gradle style:
def libraryGroupId = 'XXXXXXX'
def libraryArtifactId = 'XXXXXX'
def libraryVersion = '0.0.1'
publishing {
publications {
aar(MavenPublication) {
groupId libraryGroupId
version libraryVersion
artifactId libraryArtifactId
artifact("$buildDir/outputs/aar/${artifactId}-release.aar")
}
}
}
artifactory {
contextUrl = 'XXXXXXXXXX'
publish {
repository {
repoKey = 'libs-release-local'
username = artifactory_username
password = artifactory_password
}
defaults {
publications('aar')
publishArtifacts = true
properties = ['qa.level': 'basic', 'q.os': 'android', 'dev.team': 'core']
publishPom = true
}
}
I've tried using pom.xml but it kepts saying does not recognized TAG project in .xml file.
Thanks!!!
android {
sourceSets {
main {
assets.srcDirs = ['src/main/res/raw']
}
}
}

Parametrize webapp using Jenkins, Maven and JVM parameters

Two objectives:
I want to use parametrized jenkins builds to build a war file and set some properties during the build in the war file.
I also want to be able to refine those properties on the server, where the war file is deployed.
Number 1 is to set properties that fit to the target environment, Number 2 is to be able to quickly change them without having to rebuild the whole application again.
Choosing a maven profile is not flexible enough in this case.
An example would be a port number, that is different for every build, but can spontaneously be changed by the system administrator of the system where the file is deployed.
My idea was to use the maven-resource-filtering plugin to add the build parameters on build into property files. Then on startup of the webapp on the glassfish/tomcat to also look at the set JVM variables.
Am I thinking in the right direction?
After some research the solution for me looks as followed,
for a given parameter "test":
To objective 1.: Use command line parameters when executing maven build, e.g use:
install -Dtest=OnBuildValue
Then use the maven resources plugin, that replaces strings like test=${test} in property files, through the given parameter on build. Add:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven.resources.version}</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
...
<build>
...
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/parameters.properties</exclude>
</excludes>
<filtering>false</filtering>
</resource>
</resources>
....
</build>
To objective 2.: To be able to change the parameter "test" in the container, without having to rebuild the war file, add a JVM parameter -DTEST=ContainerValue.
Now we need some logic:
private static String getBuildParameter(String paramName)
throws IOException {
Resource resource = new ClassPathResource(
"/META-INF/spring/parameters.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
return props.getProperty(paramName);
}
public static String getParameter(final String paramName,
final String defaultValue, final String logMessage) {
String value = System.getProperty(paramName);
if (value!=null) {
Logger.getLogger(ParameterManager.class.getName()).log(
Level.WARNING,
"Parameter: " + paramName + ": " + value
+ " found in JVM parameters.");
return value;
}
try {
value = getBuildParameter(paramName.toLowerCase());
} catch (IOException e) {
// catch, log exception...
}
if (value!=null) {
Logger.getLogger(ParameterManager.class.getName()).log(
Level.WARNING,
"Parameter: " + paramName + ": " + value
+ " found in parameters set on build time.");
return value;
}
Logger.getLogger(ParameterManager.class.getName()).log(
Level.WARNING,
"Parameter: " + paramName + ": " + defaultValue
+ " as default parameter. " + logMessage);
return defaultValue;
}
The methods are static because I use them to initialize constants like this:
public static final String TEST_STRING;
static {
TEST_STRING = getParameter("TEST", "default value",
"The default is set, please ensure, that this is intended!");
}
Those constants can then be read from everywhere inside your project. How you call this logic, or if you can implement it differently is up to you. I'm sure there are nicer ways, and I would be glad to hear about your implementation, but this works for me.
Note to 1.:
If you use Eclipse you can define the maven parameters under Run->Run configurations-> Goals.
BUT if you use the glassfish tools (m2e plugin) to deploy your project to your glassfish, it will not use the run configuration. You then have to create the file .m2/settings.xml looking like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd>
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies/>
<profiles>
<profile>
<id>m2e</id>
<activation>
<property>
<name>m2e.version</name>
</property>
</activation>
<properties>
<test>xmlparameter</test>
</properties>
</profile>
</profiles>
<activeProfiles/>
</settings>

How to switch conf tomcat with maven

I have ,in a java high envirgure project using Maven, to add integrations test. To do that, I must add a new test's database (minimalist true copy of the database). Until then it's good.
By against the problem is that I have two differents configurations in my file:
\web\target\tomcat\conf\context.xml
So I always put a ressource in a comment.
exemple of ressource :
<Resource
auth = "jdbc / soarepo"
driverClassName = "oracle.jdbc.driver.OracleDriver"
logAbandoned = "true"
maxActive = "32"
maxIdle = "32"
maxWait = "10000"
name = "jdbc / soarepo"
password = "..."
username = "..."
removeAbandoned = "true"
removeAbandonedTimeout = "60"
type = "javax.sql.DataSource"
url = "jdbc: oracle: thin: # ..."
/>
Q: How do I switch from one to another ressource with Maven?
I already use a profile for integration tests. So I have to change what resources when the profile is called ?
If you are using the Maven Tomcat Plugin to run your web application, you can specify the path of a custom server-dependent deployment descriptor, context.xml, using the contextFile property:
<profiles>
<profile>
<id>integration-tests</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<contextFile>/path/to/context/file</contextFile>
</configuration>
</plugin>
</plugins>
</build>
</profile>
.. Other profiles ..
</profiles>

Categories