Where to place properties files when running tests via maven + grizzly + jersey test framework? - maven

The my.properties file from my source (src/main/resources) folder keepa getting picked up and used when I try to run my JerseyTest ... whereas I would like the properties files in the test folder (src/test/resources) to be utilized.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
myProperties.load(classLoader.getResourceAsStream("my.properties"));
}
How can I configure this in Maven?
I'm using:
maven-compiler-plugin version 2.1
jersey-test-framework-grizzly2 version 1.13
UPDATE (Resolved based on accepted answer):
I noticed the text skip non existing resourceDirectory:
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) # xxx ---
[WARNING] Using platform encoding (MacRoman actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /xxx/xxx/xxx/xxx/src/test/resources
Turns out that I had misspelled resources, after fixing it, everything works as outlined in the accepted answer.
While I was wasting my time looking for workarounds, I did find some interesting links for configuring properties files based on profiles:
How can I change a .properties file in maven depending on my profile?
http://maven.apache.org/guides/mini/guide-building-for-different-environments.html

When running something from the src/test/java folder, the default behavior is:
It will pick up the files in src/main/resources;
Except when there is a file with the same name in src/test/resources.
So basically it will "overwrite" the content of src/main/resources with the content of src/test/resources:
If you got a file in both folders, the one in src/test/resources will prevail.
If you got a file only in src/main/resources, it will be used.
If you got a file only in src/test/resources, it will be used.

Related

Vaadin 10 and springboot - How to package a jar?

The question is simple, but I spent the last 2 days trying to deploy my app. And so far it doesn't.
I have a single CSS file for my style, and when I execute the jar, CSS is not found (404) or the jar won't package.
As stated here: Spring Boot Executable jar structure
"Do not use the src/main/webapp folder if your application will be packaged as a jar"
and
"You should place your static resources in src/main/resources instead."
so put the CSS here:
src/main/resources/styles.css
In Vaadin documentation (which is very pour on how to package...) I import the CSS like this:
#StyleSheet("styles.css")
Source : https://vaadin.com/docs/v11/flow/importing-dependencies/tutorial-include-css.html
Then I package my project:
mvn clean package -Pproduction
I get this error:
[ERROR] Failed to execute goal com.vaadin:vaadin-maven-plugin:11.0.0:package-for-production (default) on project importparcoursup: Execution default of goal com.vaadin:vaadin-maven-plugin:11.0.0:package-for-production failed: An import that ends with 'styles.css' cannot be resolved: the corresponding file 'C:\Workspace\lasteclipeandjava10\parcoursup\target\frontend\styles.css' was not found.
[ERROR] Double check the corresponding import and verify the following:
[ERROR] * the import string is correct
[ERROR] * the file imported is either present in 'frontend://' directory of the project or in one of the project WebJar dependencies or in one of the regular jar dependencies
[ERROR] * if the file is present in one of the regular jar dependencies, it should be located in META-INF/resources/frontend directory in the jar
Can someone provide a simple example of a 'springboot + Vaadin10' app packaged as a jar with static resources inside ?
I tried so many configurations (put the CSS in META-INF, include webapp resources in the maven build process...) but after 2 days, I still can't deploy my app on the server!
finally the solution
css has to be here:
src/main/resources/META-INF/resources/frontend/styles.css
then declared as:
#StyleSheet("frontend://styles.css")
This could be helpful too even though I still miss an example:
Vaadin 10 makes some changes to the way it loads static resources,
such as application templates, custom styles and any additional
JavaScript files. The gist of it is that such files should be put in
src/main/webapp/frontend/ when building a .war file and
src/main/resources/META-INF/resources/frontend/ when building a .jar
file.
Link to Vaadin Dokumentation: Vaadin 10 and static resources

Spring Tools Suite and Gradle - Setup to use correct resources from inside STS

I have a Spring Boot Gradle project setup in Spring Tools Suite (3.7.2 RELEASE) with the following source folders:
- src/integration-test/java
- src/integration-test/resources
- src/main/java
- src/main/resources
- src/test/java
- src/test/resources`
Whenever I run the application or unit tests from within STS, I see that STS is using the resources found under src/integration-test/resources.
I see a duplicate resource warning in STS for files which exist in all 3 resource source folders. For example, I have an application.properties in all 3 source folders and I see following:
The resource is a duplicate of src/integration-test/resources/application.properties and was not copied to the output folder
If I run the application as a JAR or unit tests/integration tests from the command line (via gradle build), everything seems to use the correct resources. This makes me believe it is a problem with how STS/Eclipse is handling gradle.
Does anybody know of how I can configure STS to use the correct resource source folders when using gradle?
I think my problem may be related to (or the same as?) Spring Boot incorrectly loads test configuration when running from eclipse+gradle, https://issuetracker.springsource.com/browse/STS-3882, https://issues.gradle.org/browse/GRADLE-1777
I also tried the solution found here, but that seems to only fix Maven builds:
Spring Tool Suite finds spring-boot integration test configuration and does not start main application
I think my problem may be related to...
Yes, it is related but in my opinion not the same. That problem is caused by the runtime classpath being incorrect. This problem is an error coming from the eclipse project builder so it is a compile-time issue.
The problems are closely related though. Depending on your point of view, you could say they are the same (incorrect mixing of test and compile-time classpaths).
Here, specifically, the problem is that the eclipse builder tries to copy all the resources it finds in source folders to the project's single output folder. Each source folder has a 'application.properties'. The builder warns that it could not copy some of them because one would overwrite the other.
I think there may be a solution for this problem. But it is a solution that really should come from Gradle + ( BuildShip | STS Gradle Tooling) than from you.
It is possible in Eclipse to configure each source-folder individually to target a specific outputfolder. Maven + M2E are doing this correcty, but Gradle + (BuildsShip | STS Gradle Tooling) combdos do not.
For example this is what maven puts into the eclipse .classpath file when it configures a test resources folder:
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
Notice how it explicitly sets the output folder for that entry (to something different from the project's default output folder).
You may be able to address the problem yourself by modifying the .classpath for a gradle project in a similar way. Either by doing it manually or from your build.gradle.
I'm not sure this is worth it however as you will then likely still get hit by the runtime classpath issue (since these folders will still be added to your runtime classpath, your runtime classpath will end-up with two appication.properties resources, one which will 'shadow' the other. See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=482315)
I would say, the right thing to do is add a comment to the issue I linked, and hope they fix it soon as there is only so much you can do yourself by hacking the build.gradle file to modify the .classpath (this can not solve the runtime classpath issue, but in order to solve the runtime classpath issue, they would have to configure source folders to target individual output folder similar to what m2e does).
I would add this as a comment to #Kris's answer but it's too long.
I have solved the runtime classpath issue by adding the code below to my build.gradle file. The code generates an Eclipse launch configuration for the Spring Boot application class and includes only the runtime classpath (i.e. no test JARs).
My project uses the Gradle 'eclipse' plugin to generate the Eclipse project files (which I then import into Eclipse). Running the eclipseClasspath Gradle target will generate the launch file in the project's root directory.
def mainClassName = "com.example.MyApplication"
task eclipseApplicationLaunch {
group "IDE"
description "Generate an Eclipse launch configuration file for the Spring Boot application class"
}
eclipseApplicationLaunch << {
def writer = new FileWriter("${mainClassName.substring(mainClassName.lastIndexOf(".")+1)}.launch")
def xml = new groovy.xml.MarkupBuilder(writer)
xml.doubleQuotes = true
xml.launchConfiguration(type: "org.eclipse.jdt.launching.localJavaApplication") {
listAttribute(key:"org.eclipse.debug.core.MAPPED_RESOURCE_PATHS") {
listEntry(value:"/${project.name}/src/main/java/${mainClassName.replace(".","/")}.java")
}
listAttribute(key:"org.eclipse.debug.core.MAPPED_RESOURCE_TYPES") {
listEntry(value:"1")
}
listAttribute(key:"org.eclipse.jdt.launching.CLASSPATH") {
listEntry(value:"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\r\n<runtimeClasspathEntry containerPath=\"org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/\" javaProject=\"${project.name}\" path=\"1\" type=\"4\"/>\r\n")
listEntry(value:"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\r\n<runtimeClasspathEntry path=\"3\" projectName=\"${project.name}\" type=\"1\"/>\r\n")
configurations.runtime.resolvedConfiguration.resolvedArtifacts.each { artifact ->
def filePath = artifact.file.canonicalPath.replace("\\","/")
listEntry(value:"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\r\n<runtimeClasspathEntry externalArchive=\"${filePath}\" path=\"3\" type=\"2\"/>\r\n")
}
}
booleanAttribute(key:"org.eclipse.jdt.launching.DEFAULT_CLASSPATH", value:"false")
stringAttribute(key:"org.eclipse.jdt.launching.MAIN_TYPE", value:"${mainClassName}")
stringAttribute(key:"org.eclipse.jdt.launching.PROGRAM_ARGUMENTS", value:"--spring.profiles.active=local --spring.config.location=conf/")
stringAttribute(key:"org.eclipse.jdt.launching.PROJECT_ATTR", value:"${project.name}")
stringAttribute(key:"org.eclipse.jdt.launching.VM_ARGUMENTS", value:"-Djava.net.preferIPv4Stack=true")
}
writer.close()
}
eclipseClasspath.dependsOn eclipseApplicationLaunch
I haven't modified the Eclipse .classpath file as per Kris' suggestion. Instead, I have added #Profile("test") to my test application class and #ActiveProfiles("test") to my test classes.

sass-maven-plugin does not compile scss files

I try to integrate scss conversion into our existing maven project.
I tried to add
<plugin>
<groupId>nl.geodienstencentrum.maven</groupId>
<artifactId>sass-maven-plugin</artifactId>
<version>${maven.sass.plugin.version}</version>
<executions>
<execution>
<id>generate-css</id>
<phase>generate-resources</phase>
<goals>
<goal>update-stylesheets</goal>
</goals>
<configuration>
<sassOptions>
<always_update>true</always_update>
</sassOptions>
<includes>
<include>${scssSourceInclude}</include>
</includes>
<sassSourceDirectory>${project.basedir}/src/main/webapp/scss</sassSourceDirectory>
<destination>${project.build.directory}/${project.build.finalName}/css</destination>
<!-- <destination>${project.basedir}/src/main/webapp/css</destination> -->
</configuration>
</execution>
</executions>
</plugin>
When I run mvn clean install command, it compiles correctly for destination which is set to "target" directory:
[INFO] --- sass-maven-plugin:2.12:update-stylesheets (generate-css) # ui.web ---
[INFO] Checked 1 files for d:\work\git\repository\project\src\main\webapp\scss
[INFO] Checked 0 files for d:\work\git\repository\project\target\ui.web\css
[INFO] Compiling Sass templates
[INFO] No resource element was specified, using short configuration.
[INFO] Queueing Sass template for compile: d:\work\git\repository\project/src/main/webapp/scss => d:\work\git\repository\project/target/ui.web/css
...
In case of using second (commented) destination it skips scss compilation:
[INFO] --- sass-maven-plugin:2.12:update-stylesheets (generate-css) # ui.web ---
[INFO] Checked 1 files for d:\work\git\repository\project\src\main\webapp\scss
[INFO] Checked 959 files for d:\work\git\repository\project\src\main\webapp\css
[INFO] Skip compiling Sass templates, no changes.
The only difference is that I need generated css files in src directories due to further processing (minification, concatenation, adding licence header, etc.)
Dir structure:
src
|-main
|-webapp
|-scss
|- common.scss
|- app.scss
|- admin
|- admin.scss
|-css
Can somebody explain to me why the files are not processed into src directories? Is there some missing configuration which I should apply?
I think your problem would be solved by upgrading version 2.22 or later. Here's why:
The console output of the build with <destination>${project.basedir}/src/main/webapp/css</destination> shows that you already have 959 files in the destination directory. Given that you have only a single file in src/main/webapp/scss I'm assuming that most of the 959 files in src/main/webapp/css are normal, non-generated CSS files and that you intend to add those generated by the plugin.
Looking at the source of the plugin, in versions prior to 2.22, the criteria for building given that files exist in both source and destination directories is that the source directory tree has a file younger than any of the files in the destination directory. See UpdateStylesheetsMojo#buildRequired() for the 2.12 implementation. Note that the plugin does not compare source and destination files by name, it only compares "extreme" timestamps. I suspect that the build that skips compilation finds no file in src/main/webapp/scss that are younger than all files in src/main/webapp/css. You could test my hypothesis by modifying one of the .scss files before building. Issue #136: Wrong "build required" analysis when source and destination are the same describes a very similar problem. This is solved by pull request #137:
add css filter at destination when checking buildrequired which is part of version 2.22. This should make your build actually compile .scss files even in the face of newer .css files in the destination directory.
Stepping back a bit, I would advise against modifying src/ during the build. As stated in Introduction to the Standard Directory Layout
The src directory contains all of the source material for building the project [...]
whereas
The target directory is used to house all output of the build.
Behavior is built around this convention. For example mvn clean removes target/ (or more generally ${project.build.directory}). It makes no attempt at removing files generated within src/. Looking at a developer reply on the issue mentioned above it's pretty clear that the developers of the plugin share this sentiment:
Why would anyone want to mix source code and compiled code at all?
Considering this convention, I would recommend you move the .scss files to src/main/sass (the default value of sassSourceDirectory) and let the plugin output .css files to e.g. ${project.build.directory}/generated-css-resources. Then let the plugins handling minification, concatenation and license header operate on this directory as well as src/main/webapp/css. If they don't support this with configuration, you can still likely achieve this with two executions of the plugins, one for each directory. An alternative is to aggregate the generated and non-generated .css files in a directory ${project.build.directory}/aggregated-css with the help of Maven Resources Plugin's copy-resources goal, making sure the generated come first, to avoid the initial problem, and use this directory as input to further processing. I'm sure there are other ways to solve this problem as well.
I am not sure about the solution, but I tried the workaround mentioned in this post https://github.com/jruby/jruby/issues/2498 and it worked for me.
Basically downgrade the sass-maven-plugin version to 2.0 and it should work.

jersey-freemarker not resolving templates

I am trying to create a simple jersey-freemarker webapp, which I'm running with the jetty-maven-plugin.
But the FreemarkerViewProcessor won't find my templates.
I have created a jersey resource at #Path("/") with a #GET public Viewable getIndex() method, that gets invoked once I request http://localhost:8080/.
This Viewable is set to use the "index" template.
Assume the resource is com.example.MainResource (located in src/main/java/com/example/MainResource.java), and the index.ftl template file is located in src/main/webapp/templates/com/example/MainResource/index.ftl.
In my servlet setup, I tell jersey-freemarker about the templates directory, using a configuration Map: config.put(FreemarkerViewProcessor.FREEMARKER_TEMPLATES_BASE_PATH, "templates");.
When debugging the FreemarkerViewProcessor, I see that it is indeed looking for the template resource based on the path /templates/com/example/MainResource/index.ftl.
Where should I put my template files so the FreemarkerViewProcessor will find them? Or how do I include my templates directory in the classpath?
PS: mvn jetty:run produces the following output (in part):
[INFO] Configuring Jetty for project: jettytest-servlet
[INFO] webAppSourceDirectory not set. Trying src/main/webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = ~/jettytest-servlet/target/classes
[INFO] Context path = /
[INFO] Tmp directory = ~/jettytest-servlet/target/tmp
[INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
[INFO] Web overrides = none
[INFO] web.xml file = file:~/jettytest-servlet/src/main/webapp/WEB-INF/web.xml
[INFO] Webapp directory = ~/jettytest-servlet/src/main/webapp
Update:
The FreemarkerViewProcessor always uses a default Configuration, which sais to use a class-loader based template loader.
As per #ddekany's comment, I should therefore place my templates/ in WEB-INF/classes/. To me that feels dirty; it seems like this should be taken care of by Maven.
Because of the FreemarkerViewProcessor's design (always using a class-loader configuration), I have posted this follow-up question. In the meantime, suggestions telling me how I can add the src/main/webapp/ directory to the classpath are welcome as well.
As I found out here, using my own FreemarkerViewProcessor is not that difficult. So I copied the jersey-freemarker implementation and adapted it to use a Guice-injected Configuration object that I bind in my ServletModule.
Now I don't need the jersey-freemarker module any more, and I can skip putting stuff in the servlet config Map for freemarker.

what is the use of webapp-cache.xml?

what is the use of webapp-cache.xml? Does it cache any data like images, htmls etc..?? I can see that it gets created after maven build, however I could not understand the importance of this webapp-cache.xml.
Taken from the Maven WAR Plugin Docs
cacheFile:
The file containing the webapp structure cache.
Type: java.io.File
Since: 2.1-alpha-1
Required: Yes
Default: ${project.build.directory}/war/work/webapp-cache.xml
The WAR plugin uses this file in the process of creating the WAR file.

Resources