A JBoss Project
Red Hat

Posts tagged with 'maven'

I previously decribed how to use a combination of maven-war-plugin webresources and Maven profiles, in order to deploy minified resources. In this article, we’ll expand on these concepts a bit, to demonstrate how to deploy test resources, in a somewhat elegant and portable way.

User story

In some cases, you want your web application to deploy test resources, whether it’s logging or database configuration files, or even some test mocks during development.

When you’re using Eclipse Java EE, m2e-wtp explicitely prevents test resources from being deployed (in order to limit behavior discrepancies between Maven CLI and Eclipse), and if you try to mess with Eclipse’s Deployment Assembly page, its settings will be reset next time you perform a Maven > Update projet configuration.

So you need a solution that works for both Eclipse, command line and even other IDEs as well. Let’s see how you can achieve that…​

Pre-requisites

You only need :

  1. a Java EE based Eclipse distribution for the following to work: stock Eclipse, JBoss Developer Studio or SpringSource Tools Suite for instance, as long as m2e-wtp is installed with it.

  2. a Maven project with packaging war

Configure a new dev profile

In order to deploy test resources with WTP, we need to add a new Maven dev profile to the <profiles> section of your pom.xml. This can easily be done with Ctrl+space assist. Selecting the m2e profile template and changing the id to dev will get you started.

The profile is automatically enabled when running in m2e, via the m2e.version property.

Then, you need to add a maven-war-plugin configuration to the <build><plugins> section of the new profile, and configure <webResources> so that test resources from the test output directory are copied to WEB-INF/classes, using a regexp to only include specific files.

Eventually, this is how your dev profile should look :

<profile>
  <id>dev</id>
  <activation>
    <property> <!-- this will automatically be enabled when using m2e -->
    <name>m2e.version</name>
    </property>
  </activation>
  <build>
    <plugins>
    ...
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <!-- this will inherit existing maven-war-plugin configuration-->
        <configuration>
          <webResources>
            <resource>
              <directory>${project.build.testOutputDirectory}</directory>
              <includes>
                <include>**/some/test/resources/**</include>
              </includes>
              <targetPath>WEB-INF/classes/</targetPath>
            </resource>
          </webResources>
        </configuration>
      </plugin>
    </plugins>
  </build>
</profile>

In Eclipse, the matching test resources are not served directly but are actually copied/processed to target/m2e-wtp/web-resources/WEB-INF/classes and deployed from there.

If the original configuration already defines <webResources>, use <webResources combine.children="append"> in the dev profile, so all resources get deployed. You can learn more about merging plugin configuration on the Sonatype blog.

If you decide to declare this profile in a parent pom, don’t forget to put the <plugins> node under the <pluginManagement> section, or else, these configurations will not be inherited by your war projects.

This extra configuration will be merged to your existing maven-war-plugin configuration (check the maven-war-plugin configuration in the Effective POM tab of the pom.xml editor).

Now, using m2e-wtp, every time a test resource is modified, it will automatically be deployed to your server, on-the-fly. This is borderline magic, I know.

Conclusion

Hopefully, this article gave you a glimpse of the powerful Maven capabilities m2e-wtp brings to Eclipse, showing how you can easily deploy your test resources in your development environment in a portable way.

Take it easy!

In JBoss Tools and JBoss Developer Studio, we’re continuously working to augment the Maven integration experience in Eclipse. Some of the features we’ve been playing with, if deemed successful, will eventually be contributed back to m2e, like the Maven Profile Management UI. Others, more centered around JBoss technologies, will stay under the JBoss Tools umbrella.

JBoss Tools 4.2 and Developer Studio 8, based on Eclipse Luna, take advantage of all the nice improvements made to m2e 1.5.0 and then, add some more :

m2eclipse-egit integration

The Import > Checkout Maven Projects from SCM wizard doesn’t have any SCM provider by default, which can be pretty frustrating at times. With Git becoming the new de facto source control system, it only made sense to make m2eclipse-egit the sensible default SCM provider for m2e.

m2eclipse-egit will now be automatically installed when a JBoss Maven integration feature is installed from the JBoss Tools update site.

It is installed by default with JBoss Developer Studio 8.0.0 as well.

Maven Central Archetype catalog

Since m2e 1.5.0 no longer downloads Nexus Indexes by default, a very small, outdated subset of Maven Archetypes is available out of the box.

To mitigate that, the JBoss Tools Maven integration feature now registers by default the Maven Central Archetype catalog, providing more than 9600 archetypes to chose from, when creating a new Maven project. Accessing the complete list of archetypes is even way, waayyyy faster (a couple seconds) than relying on the old Nexus index download.

maven central catalog

Pom properties-controlled project configurators

JBoss project configurators for m2e now support an activation property in the <properties> section of pom.xml. Expected values are true/false and override the workspace-wide preferences found under Preferences > JBoss Tools > JBoss Maven Integration.

Available properties are :

  • <m2e.cdi.activation>true</m2e.cdi.activation> for the CDI Project configurator,

  • <m2e.seam.activation>true</m2e.seam.activation> for the Seam Project configurator,

  • <m2e.hibernate.activation>true</m2e.hibernate.activation> for the Hibernate Project configurator,

  • <m2e.portlet.activation>true</m2e.portlet.activation> for the Portlet Project configurator.

The pom.xml editor also provides matching XML templates for these properties, when doing ctrl+space in the <properties> section.

Maven Repository wizard improvements

The Configure Maven Repositories wizard, available under Preferences > Jboss Tools > JBoss Maven Integration saw a couple improvements as well :

Advanced options for maven repositories

You can now choose the repository layout, enable/disable snapshots or releases, and change the update policy in the advanced section :

maven repository advanced

Automatically identify local Maven repositories

When adding a new Maven repository, you can scan for JBoss Maven repositories unzipped locally, with the Recognize JBoss Maven Enterprise Repositories…​ button, in order to automatically add it to your .m2/settings.xml.

recognize maven repo

The identification process now looks for a .maven-repository file at the root of the folder you selected. This file follows the .properties file format and is expected to contain up to 3 attributes :

  • repository-id : the repository id

  • name : a (descriptive) repository name. Optional, defaults to repository-id

  • profile-id : the profile id the repository will be activated from. Optional, defaults to repository-id

As a concrete example, the JBoss Mobile repository .maven-repository file would contain :

repository-id=local-jboss-mobile
name=JBoss Mobile Maven Repository
profile-id=local-jboss-mobile

What’s next?

Tired of seeing these "Project configuration is out-of-date" errors whenever you tweak your pom.xml? We’re currently playing with a plugin that will automatically do the Maven > Update project configuration for you. You can try a very alpha version from the following p2 repository : http://download.jboss.org/jbosstools/builds/staging/jbosstools-playground_master/all/repo/. Let us know if/how it works for you, so we can decide what to do next with it.

Enjoy and see you soon!

Fred Bricon
@fbricon

The Maven Integration for Eclipse plugin, a.k.a. m2e, released version 1.5.0 a few weeks ago, as part of the annual Eclipse release train, this year known as Luna. 77 Bugs were fixed as part of that release, compatible with both Eclipse Kepler and Luna. I believe it’s a pretty solid one, with numerous interesting fixes and usability improvements that deserve a blog post. So here goes, in no particular order:

Improved project import workflow

Selecting Maven projects to import used to take an inordinate amount of time, due to a suboptimal - I love that word :-) - Maven Lifecycle Mapping Analysis (LMA). LMA is used to determine whether the projects would require further configuration to operate properly in Eclipse. That LMA is now only run after projects are imported, making selection of projects to import much, much faster (< couple seconds vs 1-2 min for the wildfly 8.0 codebase and its 130 projects, for instance)

After import, lifecycle mapping error markers are collected on imported projects and the discovery service is invoked to find proposals to fix those errors.

Another improvement to this workflow is the ability to easily import multi-module projects to an Eclipse Working Set. The default name is inferred from the root project but can be overridden manually:

m2e workingset import

More performance improvements during import itself are to be expected to be included in m2e 1.6.0.

See bugs 409732, 408042 and 417466.

Improved memory consumption

Maven project instance caching strategy has been revisited to reduce memory consumption. For a workspace with 300+ projects for instance, heap memory used went from 2.5GB down to well under 1GB without any noticeable side effects.

Nexus index download disabled by default

Before m2e 1.5, by default, Nexus indexes were downloaded on new workspace startup, then subsequently once a week. Depending on your internet connection, that whole process could take 15 minutes or more, heavily pegging the CPU. Once the indexes were updated, the size of the workspace would increase by approximately 500 MB. Even though space is relatively cheap these days, those with many workspaces (eg., for testing) or large workspaces, this extra disk usage can add up quickly.

m2e 1.5.0 now has this feature disabled by default. You can still enable it in Preferences  Maven  Download repository index updates on startup. One major downside of having this feature disabled by default though, is Archetype and Artifact/Plugin searches are now much less efficient, as they rely on this indexed content.

See bug 404417

New Maven Profile management UI

The JBoss Tools team contributed its Maven Profile management interface to m2e 1.5.0. This new interface eases switching between profiles.

Rather than right-clicking on a project, going to the Properties  Maven page, then manually (mis)typing a list of active or disabled profiles, you can now just use Ctrl+Alt+P to open the new Maven Profile selection interface.

m2e profile selection

The new interface is also accessible from the Maven context menu: Right-click project Maven  Select Maven Profiles…​

The list of available profiles is inferred from profiles defined in:

  • the project pom.xml

  • the project’s parent hierarchy

  • user and global maven settings.xml

When several projects are selected, only the common available profiles are displayed for selection. Common profiles are profiles defined in settings.xml or profiles having the same id in different pom.xml.

You can learn more about that feature from the original JBoss Tools blog

See bug 428094

Easily update outdated projects

The Update Maven Project dialog (launched via Right-click project Maven  Update Project…​ or via Alt-F5), now shows a dirty overlay on projects which need updating.

Additionally, an "Add out-of-date" button adds all out-of-date (OOD) projects to the current selection. If an OOD project has not been selected, a warning is shown underneath the selection table with a link equivalent to "Add out-of-date". Warning text and "Add out-of-date" button tooltip show a count of unselected OOD projects.

m2e select ood projects

See bug 422667

No more Unsupported IClasspathEntry kind=4

There’s a very popular question on StackOverflow about an m2e bug that plagued many users of the maven-eclipse-plugin: m2e would throw Unsupported IClasspathEntry kind=4 exceptions on classpath entries generated by the maven-eclipse-plugin (one of the reasons why you should never mix maven-eclipse-plugin and m2e).

m2e 1.5.0 no longer complains about these unsupported classpath entries, but unexpected classpath issues may still arise, should you mix duplicate jars from m2e and those added by the maven-dependency-plugin.

New checksum settings

Ever connected to a network with limited Internet access or simply stayed at a hotel where you needed to get past a for-pay-firewall, resulting in HTML pages being downloaded instead of jars? There’s nothing better to pollute your local Maven repository. Maven CLI builds can use these flags:

  • -C - fail build if checksums do not match

  • -c - warn if checksums do not match

m2e now has a global Checksum Policy available in Preferences  Maven, that will help you keep your sanity, and yor local repository clean:

m2e checksum policy flag

While m2e actually won’t create any Warning markers on projects when "Warn" is selected, it will override existing checksum policies set on repositories.

Improved settings for Errors/Warnings preferences

m2e has been known for generating specific errors that have puzzled more than one user in the past:

  • Project Configuration is not up-to-date - a change in pom.xml might require a full project configuration update.

  • Plugin execution not covered by lifecycle - m2e doe not know if it is safe to execute a maven plugin as part of the Eclipse build

With the new Preferences  Errors/Warnings page, users can now decide according to their own needs whether these errors should be downgraded to Warning, or even be ignored entirely.

m2e warnerrors prefs

See bugs 433776, 434053

Maven runtime changes

A few changes have been made with regards to the Maven runtime(s):

  • The embedded Maven runtime has been updated to maven 3.2.1.

  • The Netty/AsynHttpClient transport layer as been replaced with OkHttp 1.5.4. OkHttp is now the default HTTP client on the Android platform. It brings HTTP 2.0 and SPDY support to artifact downloads. Please note though, NTLM authentication is not supported.

  • Maven runtime installations can now be customized with a name, and additional libraries can be added. Maven Launch configurations now reference the Maven runtime by name, instead of using a hard-coded location so the configuration is more portable.

See bugs 427932, 418263, 432436

Accept contributions from Gerrit

In order to lower the contribution barrier and increase contributor diversity, the m2e project now accepts changes contributed via the Gerrit review system. Head over the wiki that explains how to use it. Does it work? Hell yeah! After several significant contributions, Anton Tanasenko has joined the m2e team as commiter!

Welcome Anton!

See bug 374665

Conclusion

With new blood on the m2e team, numerous fixed bugs and some big new features & improvements, m2e 1.5.0 is a pretty exciting release. Hope you guys appreciate this year’s release, before an even better version next time.

So if you haven’t installed m2e 1.5.0 yet, head over to https://www.eclipse.org/m2e/download/ and have at it.

We’d love to hear your feedback on the mailing list, or whether you report bugs or enhancement requests.

Fred Bricon
@fbricon

Some time ago, I described how to perform CSS and JS minification using Eclipse, Maven and WRO4J, thanks to m2e-wro4j.

In this article, we’ll deploy a Java EE 6 Restful application with an HTML5 front-end on a Wildfly application server. We’ll see how, using m2e-wro4j, m2e-wtp and the JBoss Tools Maven Profile Management UI, you can easily switch between minified and regular build profiles.

Setup your Eclipse-based IDE

First you’ll need to install a couple things into an Eclipse Java EE installation. I recommend you use Red Hat JBoss Developer Studio, as it comes with m2e, m2e-wtp, the Maven Profile Manager, the Wildfly server adapter and JBoss Central out-of-the-box, but any Eclipse based installation (Kepler) will do, provided you install the proper plugins.

Red Hat JBoss Developer Studio Eclipse Java EE
  • You can download and install Red Hat JBoss Developer Studio 7.1.1 from here

  • or install it over an existing Eclipse (Kepler) installation from the Eclipse Marketplace

Make sure you install the following JBoss Tools features :

  • Maven Profiles Management

  • JBossAS Server

  • JBoss Central

m2e-wro4j can then be installed from JBoss Central’s Software/Update tab :

m2e wro4j installation

Alternatively, you can find and install m2e-wro4j from the Eclipse Marketplace too.

Also make sure you have a Wildfly server installed on your machine.

About m2e-wro4j

The m2e-wro4j connector allows wro4j-maven-plugin to be invoked when .js, .css, .coffee, .less, .sass, .scss, .json, .template or pom.xml files are modified.

Given the following configuration :

<plugin>
    <groupId>ro.isdc.wro4j</groupId>
    <artifactId>wro4j-maven-plugin</artifactId>
    <version>${version.ro.isdc.wro4j}</version>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <targetGroups>app.min,m.screen.min,d.screen.min</targetGroups>
        <cssDestinationFolder>${project.build.directory}/${project.build.finalName}/css/</cssDestinationFolder>
        <jsDestinationFolder>${project.build.directory}/${project.build.finalName}/js/</jsDestinationFolder>
        <wroManagerFactory>ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory</wroManagerFactory>
    </configuration>
</plugin>

When m2e-wtp is present, m2e-wro4j automatically translates ${project.build.directory}/${project.build.finalName}/* output directories (the default values used by wro4j-maven-plugin) to ${project.build.directory}/m2e-wtp/web-resources/. This gives you on-the-fly redeployment of optimized resources on WTP controlled servers.

In order to use wro4j-maven-plugin, you need a wro.xxx descriptor (that would be src/main/webapp/WEB-INF/wro.xml by default) and a wro.properties. Read https://code.google.com/p/wro4j/wiki/MavenPlugin for more details.

Create an HTML 5 project

Now let’s get to work. From the JBoss Central Getting Started tab, click on the HTML 5 project icon to create a Maven based web application with a JAX-RS back-end and an HTML 5 front-end.

html5 project jboss central

I used kitchensink as a project name.

This project already has some wro4j-maven-plugin configuration we can use. All we need is to make the switch between regular and minified versions of the build more user friendly.

Enable minification

First, we need to remove one xml snippet from the pom.xml which prevents wro4j-maven-plugin from running during Eclipse builds, thus cancelling m2e-wro4j’s efforts. Go to the minify profile and delete :

<pluginManagement>
    <plugins>
        <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
        <plugin>
            <groupId>org.eclipse.m2e</groupId>
            <artifactId>lifecycle-mapping</artifactId>
            <version>${version.org.eclipse.m2e}</version>
            <configuration>
                <lifecycleMappingMetadata>
                    <pluginExecutions>
                        <pluginExecution>
                            <pluginExecutionFilter>
                                <groupId>ro.isdc.wro4j</groupId>
                                <artifactId>
                                    wro4j-maven-plugin
                                </artifactId>
                                <version>${version.ro.isdc.wro4j}</version>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </pluginExecutionFilter>
                            <action>
                                <ignore></ignore>
                            </action>
                        </pluginExecution>
                    </pluginExecutions>
                </lifecycleMappingMetadata>
            </configuration>
        </plugin>
    </plugins>
</pluginManagement>

In order to use the minified versions of javascript and css files in the app, the original index.html file requires you to (un)comment several lines like :

yep: {
    //assign labeled callbacks for later execution after script loads.
    //we are on mobile device so load appropriate CSS
    "jqmcss": "css/jquery.mobile-1.3.1.min.css",
    // For minification, uncomment this line
    //"mcss": "css/m.screen.min.css"
    // For minification, comment out this line
    "mcss": "css/m.screen.css"
},
nope: {
    //we are on desktop
    // For minification, uncomment this line
    //"scss": "css/d.screen.min.css"
    // For minification, comment out this line
    "scss": "css/d.screen.css"
},

This is clearly not practical if you want to be able to quickly switch between minified and original versions of your files.

Fortunately, we can take advantage of some Maven black magic, also known as web resource filtering, to dynamically use the proper (non-minified) version of these files, depending on the profile we’re building with.

We have 3 things to do :

  1. define a maven property for the minified file extension currently in use

  2. enable web resource filtering in the maven-war-plugin configuration

  3. modify index.html so it uses the aforementioned maven property

Setup the maven property

In the main <properties> block, at the top of your pom.xml, add the following property :

<!-- By default, the original filename will be used -->
<min.ext></min.ext>

Now add a <properties> block to the minify profile :

<properties>
  <min.ext>.min</min.ext>
</properties>

Enable web resource filtering

Modify the default maven-war-plugin configuration to enable filtering on html files :

<plugin>
  <artifactId>maven-war-plugin</artifactId>
  <version>${version.war.plugin}</version>
  <configuration>
    <!-- Java EE 6 doesn't require web.xml, Maven needs to catch up! -->
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <webResources>
      <webResource>
        <directory>src/main/webapp</directory>
        <filtering>true</filtering>
        <includes><include>*.html</include></includes>
      </webResource>
    </webResources>
  </configuration>
</plugin>

Use the maven property

In index.html, replace at least the following occurrences :

from to

js/app.js

js/app${min.ext}.js

css/m.screen.css

css/m.screen{min.ext}.css

css/d.screen.css

css/d.screen{min.ext}.css

You can also apply similar changes to lodash and jquery if you want.

At this point, you should see the filtered target/m2e-wtp/web-resources/index.html references the original resources, as the minified extension enabled by default is an empty string.

Switch between minified and regular profiles

Let’s see what happens when enabling the minify profile. Ctrl+Alt+P is a shortcut bringing up the Maven Profile Management UI. Just check/uncheck profiles to enable/disable them :

profile selection

Once the minify profile is active, you’ll see that :

  • css/m.screen.min.css, css/d.screen.min.css,js/app.min.js are generated under target/m2e-wtp/web-resources/

  • target/m2e-wtp/web-resources/index.html now references the minified versions of the resources

minified resources

Deploy the application on WildFly

  • Right click on your project and select Run As > Run on Server …​

  • Create a new Wildfly Server if necessary, pointing at your locally installed server

  • Once the server is created and deployed, a browser window should open :

deployed application1

If you’re on a desktop, modify the color of the h1 class in src/main/webapp/css/d.screen.css and save. This will trigger wro4j-maven-plugin:run which will regenerate the minified version under target/m2e-wtp/web-resources/css/d.screen.min.css, which in turn will be deployed on Wildfly by the server adapter.

Reloading the page (after the build is complete) will show the changes directly :

deployed application2

Now you can switch back to using the regular, non-minified version by hitting Ctrl+Alt+P in the workbench, unselect the minify profile and wait for the build to complete. After you reload your browser page, you’ll notice, if you look at the source page, the minified versions are not referenced anymore.

The minified files still exist under target/m2e-wtp/web-resources/ and are deployed as such. They’re unused, so they’re harmless, but you’d need to perform a clean build to remove them, if necessary.

Conclusion

Dealing with optimized resources in Eclipse is made really easy with a combination of the right tools. Just focus on code, save your work, see the changes instantly. WRO4J and wro4j-maven-plugin can give you much more than what we just saw here (resource aggregation, obfuscation, less processing …​). Hopefully you’ll want to give it a try after reading this article, and if you do, don’t forget to give us your feedback.

Issues with m2e-wro4j can be opened at https://github.com/jbosstools/m2e-wro4j/issues.

Issues with the Maven Profile Manager can be opened at :

As always, for all your WRO4J or wro4j-maven-plugin specific issues, I strongly encourage you to :

Have fun!

JBoss Tools 4.29.1.Final for Eclipse 2023-09

by Stéphane Bouchet on Jun 13, 2024.

JBoss Tools 4.29.0.Final for Eclipse 2023-09

by Stéphane Bouchet on Nov 02, 2023.

JBoss Tools 4.28.0.Final for Eclipse 2023-06

by Stéphane Bouchet on Jul 03, 2023.

JBoss Tools for Eclipse 2023-06M2

by Stéphane Bouchet on Jun 05, 2023.

JBoss Tools 4.27.0.Final for Eclipse 2023-03

by Stéphane Bouchet on Apr 07, 2023.

Looking for older posts ? See the Archived entries.
back to top