Spring boot: reference pom properties from application.properties in tests - spring

This is my src/test/resources/application.yml:
app:
name: Configuration And Profiles
desc: This is an app to try out ${app.name}
version: #modelVersion#
I'm just trying to get the model version from my pom file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
...
The test:
#WebMvcTest(ProfilingController.class)
public class RestControllerTest {
#Value("${app.version}")
private String version;
#Test
public void testHelloEnv() throws Exception {
System.out.println("VERSION: " + version);
}
}
The error I get:
org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character '#' that cannot start any token. (Do not use # for indentation)
in 'reader', line 4, column 12:
version: #modelVersion#
^
The funny part is that I got the same property in the src/main/resource/application.yml, but in that case when I run the app normally, version: #modelVersion is correctly populated from pom and I can get the version without issues. It's like test's application.yml is not aware of pom.xml
any thoughts?
NOTE: using '#modelVersion' between single quotes prevents the error but I get the string #modelVersion instead of its value 4.0.0
Tech:
Spring boot version: 2.5.6
Junit version: Jupiter (5)
Maven version: 3.8.3

As described in the documentation resource filtering is enabled by the spring-boot-starter-parent
That is not the case for 'test' properties, so if you need this,
you need to enable filtering in the test-resources:
in your pom.xml
<build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
...
</build>

Related

Mulesoft Maven configuration error. Can't depoloy to Cloudhub from terminal

I am trying to deploy my mule project from Anypoint using terminal "mvn clean package deploy-DmuleDeploy" command. I am not sure what this error is saying but i'm sure it has to do with my maven version. I've installed maven on my mac using homebrew, but it is version 3.8.6. The "embedded maven installation" under preferences-AnypointStudio-maven in Anypoint says 3.6.3. Then the plugin version on my .pom file says 3.5.4. Do i need to change any of these versions? Should i edit the one in the .pom file? Should i downgrade my mac maven version? Any help would be appreciated. I've posted a partial error and a partial .pom file. Please let me know if you need any more info to help me. Thank you
> [ERROR] Failed to execute goal org.mule.tools.maven:mule-maven-plugin:3.5.4:process-sources (default-process-sources) on project maven: Execution default-process-sources of goal org.mule.tools.maven:mule-maven-plugin:3.5.4:process-sources failed: An API incompatibility was encountered while executing org.mule.tools.maven:mule-maven-plugin:3.5.4:process-sources: java.lang.IllegalAccessError: class org.mule.maven.client.internal.util.FileUtils (in unnamed module #0x6d9fb2d1) cannot access class sun.net.www.protocol.jar.JarURLConnection (in module java.base) because module java.base does not export sun.net.www.protocol.jar to unnamed module #0x6d9fb2d1
[ERROR] -----------------------------------------------------
[ERROR] realm = extension>org.mule.tools.maven:mule-maven-plugin:3.5.4
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/Users/ammanbesaw/.m2/repository/org/mule/tools/maven/mule-maven-plugin/3.5.4/mule-maven-plugin-3.5.4.jar
Pom file
> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>maven</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>mule-application</packaging>
<name>maven</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<app.runtime>4.4.0-20220523</app.runtime>
<mule.maven.plugin.version>3.5.4</mule.maven.plugin.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<plugin>
<groupId>org.mule.tools.maven</groupId>
<artifactId>mule-maven-plugin</artifactId>
<version>3.5.4</version>
<extensions>true</extensions>
The cause of the error seems to be that Maven is using a Java/JDK version that is not supported by Mule. Only Java/JDK versions 8 and 11 are supported. Ensure that Maven is executing a supported JDK version.
While making a build for your project in any cloud environment. Try to change image from linux/unix to window or window to other. Operating system and image should be the same to successfully build.

Maven: module-info.java:[6,21] module not found: org.slf4j

I'm currently migrating a project to Java 11 (i.e. >= 9) and because JavaFX seems not to work without modules, anymore, I'm currently adding module-info.java files to all sub-projects. But I get the following error:
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/mangu/workspace/cloudstore.2/co.codewizards.java9test.project1/src/main/java/module-info.java:[6,21] module not found: org.slf4j
[INFO] 1 error
I'm running OpenJDK 11.0.3, Maven 3.6.1 (embedded in Eclipse 2019-06) and I definitely have the dependency for the module org.slf4j declared in my pom.xml!
In order to simplify things, I created a little, minimal test-project causing the same error.
Here's the test-project's pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>co.codewizards.java9test</groupId>
<artifactId>co.codewizards.java9test.project1</artifactId>
<version>0.1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>9</maven.compiler.source>
<maven.compiler.target>9</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta4</version>
</dependency>
</dependencies>
</project>
I tried both: 1.8.0-beta4 and 2.0.0-alpha0. Eclipse shows me an existing module-info.class in both JARs (i.e. currently inside slf4j-api-1.8.0-beta4.jar).
Here's the module-info.java:
module co.codewizards.java9test.project1 {
requires java.base;
requires java.se;
requires org.slf4j;
}
And here's the output from mvn clean install -Dmaven.test.skip=true -X (but run inside Eclipse): mvn.log
Any idea what I'm doing wrong?
Update: I just uploaded the little test project: co.codewizards.java9test.project1.7z
Your maven logs show slf4j-api being placed on the classpath, not modulepath.
You need to upgrade the version of maven-compiler-plugin, as modulepath is supported only since version 3.6, whereas your build uses version 3.1.
I was getting the same issue due to older verion of slf4j was coming from one of dependency in pom. So I resolved it by adding below slf4j dependency to my pom :
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.29</version>
</dependency>
module-info:
module my.service {
requires org.slf4j;
}

Spring boot application suddenly fails to start. SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

I m new to spring. I was writing spring boot applications with maven in last few days and had no issue in building or running on windows with STS. Then today for packaging i created a new project and and tried to build it with maven using win command prompt. Build failed and said that theres no compiler set("Perhaps your'e using a JRE"). Then I set JAVA_HOME in system variables and retried but then it started giving me
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"
SLF4J: Defaulting to no-operation (NOP) logger implementation
....
Caused by:
java.lang.ClassNotFoundException:ch.qos.logback.classic.turbo.TurboFilter
Now I can't run any app which were working fine earlier either with STS/Eclipse, that error pops up.
I deleted .m2 and rebuilt.still not working.
Tried in a different windows pc with a fresh STS installation. It also doesn't work. this pops up.
Did they change libraries?
I deleted JAVA_HOME and retried.But no success.
I'm using a pretty simple pom and an application.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pmanu</groupId>
<artifactId>testMaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
</project>
AppStart.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#RestController
#SpringBootApplication
public class AppStart {
public static void main(String[] args) {
SpringApplication.run(AppStart.class, args);
}
#RequestMapping("/")
public String get(){
return "Hello";
}
}
Please Help. I'd prefer to go ahead with spring 1.5.6.RELEASE artifacts.
I saw some answers saying that a logging jar like log4j has to be added to classpath.
But isn't maven parent supposed to have them configured? If there's any other proper way I'd prefer not to add an unnecessay dependancy for my applications.
How come this arised all of a sudden?

Elasticsearch Java API from web application-error: java.lang.NoClassDefFoundError: Could not initialize class org.elasticsearch.threadpool.ThreadPool

I couldn't use elasticsearch Java API through JSP. In the following, I have tried to explain what I have done. :|
I have installed elasticseach 2.3.3 on my system by following the elastic instruction and run it from command prompt. everything is working perfectly. It may be useful to say, I have changed below parameters from elasticsearch.yml.
cluster.name: cluster_233
node.name: node_233
bootstrap.mlockall: true
network.host: 127.0.0.1
Then with Netbeans, I have created a Maven project -> Web application project and set the below dependency in pom.xml :
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
<type>jar</type>
</dependency>
Also I have added the Guava version 18 dependency into project and then download all the project dependencies by right clicking on Dependencies and select Download Declared Dependencies . Then created a java class and write below code:
package com.mycompany.esmaven;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
public class aClass {
public String test() throws Exception {
String str = tryToIndex();
String dfd = "";
return str;
}
public String tryToIndex() throws Exception {
Node node = NodeBuilder.nodeBuilder().settings(
Settings.builder()
.put("path.home", "d:/elasticsearch-2.3.3")
.put("cluster.home", "cluster_233")
).node();
Client client = node.client();
client.prepareIndex("kodcucom", "article", "1")
.setSource(putJsonDocument("ElasticSearch: Java API",
"ElasticSearch provides the Java API, all operations "
+ "can be executed asynchronously using a client object.",
new Date(),
new String[]{"elasticsearch"},
"Hüseyin Akdoğan")).execute().actionGet();
node.close();
return "Done";
}
public static Map<String, Object> putJsonDocument(String title,
String content, Date postDate, String[] tags, String author) {
Map<String, Object> jsonDocument = new HashMap<String, Object>();
jsonDocument.put("title", title);
jsonDocument.put("conten", content);
jsonDocument.put("postDate", postDate);
jsonDocument.put("tags", tags);
jsonDocument.put("author", author);
return jsonDocument;
}
}
And through a jsp page tried to call the test() function (I'm going to integrate elasticsearch with a web application). Always after building the project at the first load the below error will appear:
java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;
and after refreshing the page the context of error will change to:
java.lang.NoClassDefFoundError: Could not initialize class org.elasticsearch.threadpool.ThreadPool
This is the POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ISTEX</groupId>
<artifactId>mvnESwebapp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mvnESwebapp</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Also, I would like to mention, with this POM I can index my JSON from the main function. But the problem is I did not know how to run the application through JSP pages.
I really appreciate you for sharing your knowledge.
Regards,
Amin
FWIW, I ran into the same issue as described above -- that is, the error message I saw was the threadpool initialization error the author describes. The solution described in the link below solved the problem for me:
https://discuss.elastic.co/t/could-not-initialize-class-org-elasticsearch-threadpool-threadpool/47575
UPDATED per comment suggestion:
In my case, the fix was to add a guava dependency entry in my POM file. I used the dependency given in the webpage at the link above:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
That, at least in my case, solved the problem.
With Java applications, errors like
java.lang.NoSuchMethodError
java.lang.NoClassDefFoundError
generally indicate that you are missing a dependency or you have conflicting dependency. For example, Guava 18.0 and Guava 19.0 are completely different as far as Java is concerned, but they share a lot of code. As the jars are loaded, one will naturally be loaded first, so any attempted usage of the second will cause misleading errors like those above.
Also I have added the Guava version 18 dependency into project and then download all the project dependencies by right clicking on Dependencies and select Download Declared Dependencies
Elasticsearch 2.3.3 already depends on Guava 18.0. As such, it's a transitive dependency of the Elasticsearch project.
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
<type>jar</type>
</dependency>
Your Maven dependency is probably creating a collision with one of your other dependencies. Take a look at your Netbeans dependencies, or more appropriately ask Maven to do it directly:
mvn dependency:tree -Dverbose
This will print out the dependency tree for you to find conflicts. Look for jars that are duplicated with different versions and stop the mismatch from happening.
As a side note, at the time of this answer, Guava 19 is the latest version. So even though ES 2.3.3 wants Guava 18, some other dependency of yours could easily and reasonably want a different version of Guava.

Could not connect to remote://localhost:9999. The connection timed out Jboss 7.1.1 Final

I am deploying builds to local and remote Jboss AS 7.1.1 Final at port 9999. Maven uses jboss plugin 'jboss-as-maven-plugin:7.1.1.Final' to manage builds to servers. I have confirmed that server is up and running and port is accessible at 9999. But "many times" build fails with following error for both local and remote Jboss. Jboss ic configured in Standalone mode single node cluster.
Stranglely build doesn't fail every time but most of the time. Not sure if we need to upgrade Maven plugin to higher version.
[INFO] o.h.m.e.h.MavenExecutionResultHandler - Build failed with
exception(s) [INFO] o.h.m.e.h.MavenExecutionResultHandler - [1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to
execute goal
org.jboss.as.plugins:jboss-as-maven-plugin:7.1.1.Final:undeploy
(default-cli) on project Test: Error executing UNDEPLOY [DEBUG]
Closing connection to remote [ERROR] Failed to execute goal
org.jboss.as.plugins:jboss-as-maven-plugin:7.1.1.Final:undeploy
(default-cli) on project Test: Error executing UNDEPLOY:
java.net.ConnectException: JBAS012144: Could not connect to
remote://localhost:9999. The connection timed out -> [Help 1]
UPDATE
<plugin>
<groupId>org.jboss.as.plugins</groupId>
<artifactId>jboss-as-maven-plugin</artifactId>
<version>7.1.1.Final</version>
<configuration>
<filename>${project.build.finalName}.jar</filename>
<username>${userName}</username>
<password>${password}</password>
</configuration>
</plugin>
I am now using latest version of Maven plug-in but it seems that connection timeout error is more frequent now. I am starting to think if Jboss behaves differently when trying to make too many remote deployment with different sub projects of the application. I am having 21 sub projects being deployed from a master POM. Sample configuration is as follows
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.master</groupId>
<artifactId>master</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<name>Master</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<modules>
<module>module1</module>
<module>module2</module>
<module>module3</module>
<module>module4</module>
<module>module5</module>
<module>module6</module>
<module>module7</module>
<module>module8</module>
<module>module9</module>
<module>module10</module>
<module>module11</module>
<module>module12</module>
<module>module13</module>
</modules>
First, check plugin configuration.
For example:
<plugin>
<groupId>org.jboss.as.plugins</groupId>
<artifactId>jboss-as-maven-plugin</artifactId>
<version>7.9.Final</version>
<inherited>true</inherited>
<configuration>
<hostname>${jboss.hostname}</hostname>
<port>${jboss.port}</port>
<username>${jboss.user}</username>
<password>${jboss.pass}</password>
<timeout>30000</timeout>
</configuration>
</plugin>
If hostname, port number(default 9999), username and password are ok, you can try increasing "timeout" (default is 5000ms, you can try with 30000ms).
It worked for me.
4 Possible Solutions to Question
Remove your Local Cache settings which will be your local m2 repo Or Point to new m2 repo from your maven settings.xml file.
Try to connect to your local nexus/archiva (if any other) using relevant/appropriate credentials.It is only your Maven Plugin causing this problem.
Try to use the latest JBoss Deploy Plugin available in this link.
Alternatively check your windows/Linux firewall settings have been enabled or it.

Resources