Showing posts with label Maven. Show all posts
Showing posts with label Maven. Show all posts

Sunday, May 15, 2016

NPM module Browser-Sync in Java / Web projects

Browser-Sync is a handy Node.js based NPM module which can be used for a faster web development. Browser-Sync synchronizes file changes and interactions across many devices. The most important feature is the live reloading. We can use the Browser-Sync in Java / Web projects too. Cagatay Civici created a great video tutorial how to use this module with the PrimeFaces showcase. The PrimeFaces showcase has a built-in Jetty server which looks to the source folder src/main/webapp as the web context root. After the Browser-Sync installation via the Node.js package manager NPM
 
npm install -g browser-sync
 
we have to start the Jetty server for the PrimeFaces showcase at http://localhost:8080/showcase. Afther that we can use this URL as proxy for a built-in server included in the Browser-Sync. The Browser-Sync should listen to changes under src/main/webapp
 
browser-sync start --proxy "http://localhost:8080/showcase" --files "src/main/webapp/**/*"
 
As result, a default browser will be started at http://localhost:3000/showcase with the PrimeFaces showcase. The port 3000 is the default port for the Browser-Sync.

This approach works well until you have made changes in Java files. Java files are not web resources under src/main/webapp. In Maven projects they located under src/main/java. That means, changes in Java files will not be recognized. The solution is exploded WAR. An exploded WAR is a directory where the web application gets deployed from. Every application server can deploy an exploded WAR. For Maven projects, this directory is normally target/webapp. The Maven WAR plugin has the goal war:exploded too. If you have an IDE, you can configure your web application as an exploded WAR. I have blogged about Hot Deployment with IntelliJ IDEA a couple of years ago. In IntelliJ, you can automatically copy changed files (CSS, JS, HTML resources and compiled Java files) to the directory for the exploded WAR.


Now, if you refresh the browser manually, you will see the changes in Java classes too. But we want to do this better. We want to use the highly praised live reloading! To achieve this goal, set files to be watched as follows
 
browser-sync start --proxy "http://localhost:8080/showcase" --files "target/classes/**/*.class, target/webapp/**/*"
 
The output looks like
[BS] Proxying: http://localhost:8080
[BS] Access URLs:
 ---------------------------------------------------------------------
       Local: http://localhost:3000/showcase
    External: http://192.168.178.27:3000/showcase
 ---------------------------------------------------------------------
          UI: http://localhost:3001
 UI External: http://192.168.178.27:3001
 ---------------------------------------------------------------------
Now, I can do any changes in all important files and see something like in the console
 
[BS] Watching files...
[BS] File changed: target\webapp\META-INF\MANIFEST.MF
[BS] File changed: target\webapp\WEB-INF\classes\some\showcase\bean\SomeBean.class
[BS] File changed: target\webapp\views\someView.xhtml
[BS] File changed: target\webapp\META-INF\MANIFEST.MF
The browser page gets updated by the Browser-Sync automatically (which uses WebSockets by the way). If you have trouble with your IDE, you can use Gulp to rescue! Here my idea for a gulpfile.js (Gulp 4).
var browsersync = require('browser-sync').create();

// init Browser-Sync
gulp.task('browser-sync', function() {
    browsersync.init({
        proxy: "http://localhost:8080/showcase"
    });
});

// compile changed Java files by Maven "mvn compile"
// compiled classes will be transfered to target/classes automatically
gulp.task('java', function () {
    // use 'spawn' to execute command using Node.js
    var spawn = require('child_process').spawn;

    // set the working directory to project root where gulpfile.js exists
    process.chdir(__dirname);

    // run "mvn compile"
    var child = spawn('mvn', ['compile']);

    // print output
    child.stdout.on('data', function(data) {
        if (data) {
            console.log(data.toString());
        }
    });
});

// copy changes from src/main/webapp to target/webapp 
gulp.task('webapp', function () {
    return gulp.src('src/main/webapp/**/*', {since: gulp.lastRun('webapp')})
        .pipe(gulp.dest('target/webapp'));
});

// watch files for changes
gulp.task('watch', function () {
    gulp.watch('src/main/java/**/*.java', gulp.series('java'));
    gulp.watch('src/main/webapp/**/*', gulp.series('webapp'));
    gulp.watch(['target/classes/**/*.class', 'target/webapp/**/*'], browsersync.reload);
});

// default task
gulp.task('default', gulp.series('browser-sync', 'watch'));
This file should be placed in the project root folder. Now, you are able to execute the command (Gulp should be installed of course)
 
gulp
 
and enjoy the live reloading! Please consider, the Gulp java task. Maven only compiles changed files. It works very fast! Without changes there are nothing to be compiled - the output of the mvn compile looks like:
 
[INFO] Nothing to compile - all classes are up to date
 
If we make a change in one Java file, the output looks like:
 
[INFO] Compiling 1 source file to <path>\showcase\target\classes
 
Note: The server should run in reloadable mode. E.g. Tomcat has a reloadable option in context.xml. Set it to true to force monitoring classes in /WEB-INF/classes/ and /WEB-INF/lib for changes and automatically reload the web application if a change is detected. JBoss has this feature automatically if you start it in the debug mode.

I can also imagine some complex Gulp tasks, such as compiling Java classes in dependent JAR files, build JARs and copy them to the WEB-INF/lib folder of the exploded WAR.

Sunday, June 14, 2015

Create source maps at project build time for JavaScript debugging

If you're doing front end web development, your web resources such as JavaScript and CSS files might be minificated, transpiled or compiled from a completely different language. If you now want to debug the generated code in the browser, you can not do that because the output code is obfuscated from the code you wrote. The solution is to use source maps. A good introduction to the source map can be found in the articles "Introduction to JavaScript Source Maps", "Enhance Your JavaScript Debugging with Cross-Browser Source Maps" and "An Introduction to Source Maps".

I will try to summarize the quintessence about the source maps and concentrate on JavaScript only. Generating CSS by LESS / SASS is interesting too, but it is not yet supported by my Maven plugin I will present in this blog post. How to use a source map? In order to use a source map, your browser development tools need to be able to find it. If your generated code is JavaScript, one way to let the development tools know where to look is to add a comment to the end of the generated code which defines the sourceMappingURL - the location of the source map. For example: //# sourceMappingURL=mylib.js.map or //# sourceMappingURL=/mypath/mylib.js.map or //# sourceMappingURL=http://sourcemaps/mylib.js.map. If you now open a development tool and the source map support is enabled, the browser will stream down the source map which points to the original file and show the original file instead of generated one (minificated, compiled, transpiled, etc.). Now, you can set a breakpoint in the original file and debug it as it would be delivered with you web application! Such debugging is possible due to the fact that a source map provides a way of mapping code within a generated file back to it's original position in a source file. I found a nice bild here to visualize the entire process.


Source maps are supported in all major browser that are shipped with built-in support for source maps. If you follow my links to the articles I mentioned above, you can see some examples for Internet Expoler 11, Firefox and Google Chrome. Chrome's Dev Tools enables the source maps support by default. Simple check if the checkbox "Enable JavaScript source maps" is enabled.


If you a fan of Firefox, you should use the Firefox' Web Console (Shift + Ctrl + K) and check if the same option is enabled in settings too. Please note that Firebug doesn't support debugging by source maps. You have to use the native Firefox' Web Console as I said. Internet Explorer 11 also rocks with source maps. It has even more features - you can add source map files from your local disk. Simple right-click on a generated (e.g. compressed) file and select "Choose source map". The article "Enhance Your JavaScript Debugging with Cross-Browser Source Maps" which I mentioned above, has a lot of picture for IE and debugging TypeScript files.

Source maps can be created during your build. If you work with Node.js and npm, the best tool is UglifyJS - a popular command line utility that allows you to combine and compress JavaScript files. If you work with Maven, you can use my Maven plugin for resource optimization I wrote a some years ago and just updated for supporting source maps. It uses the superb Google Closure Compiler which offers a support for source map creation and many other cool features. Please refer the documentation of the Maven plugin to see how to set the various source map configuration options. The simplest configuration which we also use in the current PrimeFaces Extensions release looks like as follows:
<plugin>
    <groupId>org.primefaces.extensions</groupId>
    <artifactId>resources-optimizer-maven-plugin</artifactId>
    <version>2.0.0</version>
    <configuration>
        <sourceMap>
            <create>true</create>
            <outputDir>${project.basedir}/src/sourcemap/${project.version}</outputDir>
            <sourceMapRoot>
              https://raw.githubusercontent.com/primefaces-extensions/core/master/src/sourcemap/${project.version}/
            </sourceMapRoot>
        </sourceMap>
    </configuration>
    <executions>
        <execution>
            <id>optimize</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>optimize</goal>
            </goals>
        </execution>
    </executions>
</plugin>
By this way, only compressed JavaScript files will be packaged within released JAR file. Uncompressed files are not within the JAR. The JAR is smaller and free from redundant stuff. For the PrimeFaces Extensions, the source map and uncompressed files are checked in below the project root. For example, the folder with source maps and original files for the current release 3.2.0 is located here: https://github.com/primefaces-extensions/core/tree/master/src/sourcemap/3.2.0 That means, a compressed file, say timeline.js, has the following line at the end:

//# sourceMappingURL=https://raw.githubusercontent.com/primefaces-extensions/core/master/src/sourcemap/3.2.0/timeline.js.map

The source map timeline.js.map has the content (I truncated some long lines):
{
  "version":3,
  "file":"timeline.js",
  "lineCount":238,
  "mappings":"A;;;;;;;;;;;;;;;;;;;;AA4DqB,WAArB,GAAI,MAAOA,MAAX,GACIA,KADJ,CACY,EADZ,CAUsB,YAAtB,GAAI,...
  "sources":["timeline.source.js"],
  "names":["links","google","undefined","Array","prototype","indexOf","Array.prototype.indexOf",...]
}
It would be probably better to bring these files to a CDN, like cdnjs, but CDNs are not really intended for source maps. Another option would be a PrimeFaces repository. We will see how to handle that in the future. The next picture demonstrates how the debugging for the compressed JS file timeline.js looks in my Firefox.


Due to the Firefox built-in source map support we see the uncompressed JS file timeline.source.js. I set a breakpoint on the line with the if-statement if (index < 0). After that I clicked on an event in the Timeline component. The breakpoint was jumped up. Now, I can debug step by step and see my local and global variables on the right side. As you probably see, the variable index is shown as a (I marked it red as var index). This is a shortcoming of the current source map specification. You can read this discussion for more details.

Again, keep in mind - the source maps and original files will be only loaded when you open up the browser dev. tools and enable this support explicitly. If the dev. tools has identified that a source map is available, it will be fetched along with referenced source file(s). If a source map file is not available, you will see a 404 "not found message" in the dev. tool (not bad at all in my opinion).

That's all. My next posts will be about AngularJS and less about JSF. Stay tuned.

Saturday, April 14, 2012

High Performance Webapps. Use Data URIs. Theory.

I continue to write tips for perfomance optimization of websites. The last post was about jQuery objects. This post is about data URIs. Data URIs are an interesting concept on the Web. Read "Data URIs explained" please if you don't know what it does mean. Data URIs are a technique for embedding resources as base 64 encoded data, avoiding the need for extra HTTP requests. It gives you the ability to embed files, especially images, inside of other files, especially CSS. Not only images are supported by data URIs, but embedded inline images are the most interesting part of this technique. This technique allows separate images to be fetched in a single HTTP request rather than multiple HTTP requests, what can be more efficient. Decreasing the number of requests results in better page performance. "Minimize HTTP requests" is actually the first rule of the "Yahoo! Exceptional Performance Best Practices", and it specifically mentions data URIs.

"Combining inline images into your (cached) stylesheets is a way to reduce HTTP requests and avoid increasing the size of your pages... 40-60% of daily visitors to your site come in with an empty cache. Making your page fast for these first time visitors is key to a better user experience."

Data URI format is specified as

data:[<mime type>][;charset=<charset>][;base64],<encoded data>

We are only interesting for images, so that mime types can be e.g. image/gif, image/jpeg or image/png. Charset should be omitted for images. The encoding is indicated by ;base64. One example of a valid data URI:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
        AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
HTML fragments with inline images like the above example are not really interesting because they are not cached. Data URIs in CSS files (style sheets) are cached along with CSS files and that brings benefits. Some advantages describing in Wikipedia:
  1. HTTP request and header traffic is not required for embedded data, so data URIs consume less bandwidth whenever the overhead of encoding the inline content as a data URI is smaller than the HTTP overhead. For example, the required base64 encoding for an image 600 bytes long would be 800 bytes, so if an HTTP request required more than 200 bytes of overhead, the data URI would be more efficient.
  2. For transferring many small files (less than a few kilobytes each), this can be faster. TCP transfers tend to start slowly. If each file requires a new TCP connection, the transfer speed is limited by the round-trip time rather than the available bandwidth. Using HTTP keep-alive improves the situation, but may not entirely alleviate the bottleneck.
  3. When browsing a secure HTTPS web site, web browsers commonly require that all elements of a web page be downloaded over secure connections, or the user will be notified of reduced security due to a mixture of secure and insecure elements. On badly configured servers, HTTPS requests have significant overhead over common HTTP requests, so embedding data in data URIs may improve speed in this case.
  4. Web browsers are usually configured to make only a certain number (often two) of concurrent HTTP connections to a domain, so inline data frees up a download connection for other content.
Furthermore, data URIs are better than sprites. Images organized as CSS sprites (many small images combined to one big) are difficult to be maintained. Maintenance costs are high. Imagine, you want to change some small images in the sprite, their position, size, color or whatever. Well, there are tools allowing to generate sprites, but later changes are not easy. Especially changes in size cause a shift of all positions and a lot of CSS changes. And don't forget - a sprite still requires one HTTP request :-).

What browsers support data URIs? Data URIs are supported for all modern browsers: Gecko-based (Firefox, SeaMonkey, Camino, etc.), WebKit-based (Safari, Google Chrome), Opera, Konqueror, Internet Explorer 8 and higher. For Internet Explorer 8 data URIs must be smaller than 32 KB. Internet Explorer 9 does not have this 32 KB limitation. IE versions 5-7 lack support of data URIs, but there is MHTML – when you need data URIs in IE7 and under.

Are there tools helping with automatic data URI embedding? Yes, there are some tools. The most popular is a command line tool CSSEmbed. Especially if you need to support old IE versions, you can use this command line tool which can deal with MHTML. Maven plugin for web resource optimization, which is a part of PrimeFaces Extensions project, has now a support for data URIs too. The plugin allows to embed data URIs for referenced images in style sheets at build time. This Maven plugin doesn't support MHTML. It's problematic because you need to include CSS files with conditional comments separately - for IE7 and under and all other browsers. How does the conversion to data URIs work?
  1. Plugin reads the content of CSS files. A special java.io.Reader implementation looks for tokens #{resource[...]} in CSS files. This is a syntax for image references in JSF 2. Token should start with #{resource[ and ends with ]}. The content inside contains image path in JSF syntax. Theoretically we can also support other tokens (they are configurable), but we're not interested in such kind of support :-) Examples:
    .ui-icon-logosmall {
        background-image: url("#{resource['images/logosmall.gif']}") !important;
    }
    
    .ui-icon-aristo {
         background-image: url("#{resource['images:themeswitcher/aristo.png']}") !important;
    }
    
  2. In the next step the image resource for each background image is localized. Images directories are specified according to the JSF 2 specification and suit WAR as well as JAR projects. These are ${project.basedir}/src/main/webapp/resources and ${project.basedir}/src/main/resources/META-INF/resources. Every image is tried to be found in those directories.
  3. If the image is not found in the specified directories, then it doesn't get transformed. Otherwise, the image is encoded into base64 string. The encoding is performed only if the data URI string is less than 32KB in order to support IE8 browser. Images larger than that amount are not transformed. Data URIs looks like
    .ui-icon-logosmall {
        background-image: url("data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgA ... ASUVORK5CYII=") !important;
    }
    
    .ui-icon-aristo {
        background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA ... BJRU5ErkJggg==") !important;
    }
    
Configuration in pom.xml is simple. To enable this feature set useDataUri flag to true. Example:
<plugin>
    <groupId>org.primefaces.extensions</groupId>
    <artifactId>resources-optimizer-maven-plugin</artifactId>
    <configuration>
        <useDataUri>true</useDataUri>
        <resourcesSets>
            <resourcesSet>
                <inputDir>${project.build.directory}/webapp-resources</inputDir>
            </resourcesSet>
        </resourcesSets>
    </configuration>
</plugin>
Enough theory in this post. The next one will describe a practice part. I will expose some measurements, screenshots and give tips how large images should be, where CSS should be placed, what is the size of CSS file with data URIs and whether a GZIP filter can help here. Stay tuned.

Friday, February 17, 2012

Advanced injection of Maven properties into Java application

In the last post I have shown how to inject Maven project informations into Java application. This topic describes the injection for more useful properties. Advantage: no needs to define then any project specific Java constants and change constants with each release. Current project infos already exist in pom.xml. In the PrimeFaces Extensions project we have defined some profile dependent properties like these
...
<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>${primefaces.core.version}</version>
</dependency> 
<dependency>
    <groupId>org.primefaces.extensions</groupId>
    <artifactId>primefaces-extensions</artifactId>
    <version>${pe.impl.version}</version>
</dependency>
...
<properties>
    <java.version.source>1.6</java.version.source>
    <java.version.target>1.6</java.version.target>
    <jetty.server.version>8.1.0.RC2</jetty.server.version>
    <pe.jsf.impl>mojarra</pe.jsf.impl>
    <pe.jsf.displayname>Mojarra</pe.jsf.displayname>
    <pe.jsf.group>com.sun.faces</pe.jsf.group>
    <pe.jsf.artifact>jsf</pe.jsf.artifact>
    <pe.jsf.version>2.1.6</pe.jsf.version>
    <pe.impl.version>0.3.0-SNAPSHOT</pe.impl.version>        
    <pe.webapp.filter>development</pe.webapp.filter>
    <pe.webapp.online>false</pe.webapp.online>
    <primefaces.core.version>3.1.1</primefaces.core.version>
    <primefaces.theme.version>1.0.3</primefaces.theme.version>
</properties>
And we also configured two Maven plugins which put more useful properties to Maven based applications.
<plugin>
    <groupId>com.google.code.maven-svn-revision-number-plugin</groupId>
    <artifactId>maven-svn-revision-number-plugin</artifactId>
    <version>1.7</version>
    <executions>
        <execution>
            <goals>
                <goal>revision</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <entries>
            <entry>
                <prefix>svn</prefix>
            </entry>
        </entries>
    </configuration>                    
</plugin>
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>buildnumber-maven-plugin</artifactId>
    <version>1.0</version>
    <executions>
        <execution>
            <id>generate-timestamp</id>
            <phase>validate</phase>
            <goals>
                <goal>create-timestamp</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <format>{0,date,yyyy-MM-dd HH:mm}</format>
        <items>
            <item>timestamp</item>
        </items>
    </configuration>
</plugin>
Let's start now. Property file under src/main/resources is called now pe-showcase.properties and has again only one line (surprise).
 
application.properties=${project.properties}
 
This line gets resolved at build time as follows:
application.properties={pe.jsf.impl=mojarra, pe.jsf.group=com.sun.faces, timestamp=1329486964505, svn.committedRevision=928, svn.revision=928, primefaces.theme.version=1.0.3, pe.impl.version=0.3.0-SNAPSHOT, pe.jsf.displayname=Mojarra, jetty.server.version=8.1.0.RC2, svn.committedDate=2012-02-17 01:48:44 +0100 (Fri, 17 Feb 2012), pe.jsf.version=2.1.6, primefaces.core.version=3.1.1, ...}
The task is now to parse this resolved line in a Java application. A good entry point for parsing in JSF is an application scoped bean noted with eager=true.
@ApplicationScoped
@ManagedBean(eager = true)
public class TechnicalInfo {

    private static final Logger LOGGER = Logger.getLogger(TechnicalInfo.class.getName());

    private String primeFaces;
    private String primeFacesExt;
    private String jsfImpl;
    private String server;
    private String revision;
    private String buildTime;
    private boolean online = false;
    private boolean mojarra = true;

    @PostConstruct
    protected void initialize() {
        ResourceBundle rb;
        try {
            rb = ResourceBundle.getBundle("pe-showcase");

            String strAppProps = rb.getString("application.properties");
            int lastBrace = strAppProps.indexOf("}");
            strAppProps = strAppProps.substring(1, lastBrace);

            Map<String, String> appProperties = new HashMap<String, String>();
            String[] appProps = strAppProps.split("[\\s,]+");
            for (String appProp : appProps) {
                String[] keyValue = appProp.split("=");
                if (keyValue != null && keyValue.length > 1) {
                    appProperties.put(keyValue[0], keyValue[1]);
                }
            }

            primeFaces = "PrimeFaces: " + appProperties.get("primefaces.core.version");
            primeFacesExt = "PrimeFaces Extensions: " + appProperties.get("pe.impl.version");
            jsfImpl = "JSF-Impl.: " + appProperties.get("pe.jsf.displayname") + " " + appProperties.get("pe.jsf.version");
            server = "Server: Jetty " + appProperties.get("jetty.server.version");
            revision = "SVN-Revision: " + appProperties.get("svn.revision");

            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(Long.valueOf(appProperties.get("timestamp")));
            buildTime = "Build time: " + formatter.format(calendar.getTime());

            online = Boolean.valueOf(appProperties.get("pe.webapp.online"));
            mojarra = appProperties.get("pe.jsf.impl").contains("mojarra");
        } catch (MissingResourceException e) {
            LOGGER.warning("Resource bundle 'pe-showcase' was not found");
        }
    }

    ... getter ...

}
Access in JSF facelets:
<h:panelGrid columns="7" style="float: left;">
    <h:panelGroup styleClass="ui-icon ui-icon-info"/>
    <h:outputText value="#{technicalInfo.primeFaces},"/>
    <h:outputText value="#{technicalInfo.primeFacesExt},"/>
    <h:outputText value="#{technicalInfo.jsfImpl},"/>
    <h:outputText value="#{technicalInfo.server},"/>
    <h:outputText value="#{technicalInfo.revision},"/>
    <h:outputText value="#{technicalInfo.buildTime}"/>
</h:panelGrid>
And voilĆ . We have done this! Click on image to enlarge it.

Wednesday, February 15, 2012

Inject Maven project informations into Java application

Do you have a Maven project and would like to inject project informations from pom.xml into your application to avoid duplications? This is possible with resource filtering. This small guide will help you to achieve that. More funny advanced examples are coming soon in the next post. I have applied this approach for PrimeFaces Extensions project, so that all examples are related to this project.

Step 1. Create a property file under src/main/resources. In my case it's called primefaces-extensions.properties and consists of only one line.
 
application.version=${project.version}
 
Placeholder ${...} gets resolved at project build time. Maven also exposes other project properties like ${project.artifactId}, ${project.name}, etc. Please refer Maven properties guide. Not only Maven self exposes such properties. Various Maven plugins as buildnumber-maven-plugin and maven-svn-revision-number-plugin expose useful properties too.

Step 2. To get placeholders replaced you need to enable filtering in your pom.xml.
<build>
    <resources>
        <resource>src/main/resources</resource>
        <filtering>true</filtering>
    </resources>
    ...
</build>

Step 3. Access in Java is simple. I have created a singleton class VersionProvider for that (because I only have one placeholder for project version). Project version is cached after the first access.
public final class VersionProvider {

    private static final Logger LOGGER = Logger.getLogger(VersionProvider.class.getName());

    private static final VersionProvider INSTANCE = new VersionProvider();
    private String version;

    private VersionProvider() {
        ResourceBundle rb;
        try {
            rb = ResourceBundle.getBundle("primefaces-extensions");
            version = rb.getString("application.version");
        } catch (MissingResourceException e) {
            LOGGER.warning("Resource bundle 'primefaces-extensions' was not found or error while reading current version.");
        }
    }

    public static String getVersion() {
        return INSTANCE.version;
    }
}

Step 4. Using in any places is simple as well. Just call VersionProvider.getVersion(). For instance in the following JSF listener class
public class PostConstructApplicationEventListener implements SystemEventListener {

    private static final Logger LOGGER = Logger.getLogger(PostConstructApplicationEventListener.class.getName());

    @Override
    public boolean isListenerForSource(final Object source) {
        return true;
    }

    @Override
    public void processEvent(final SystemEvent event) {
        if (StringUtils.isNotBlank(VersionProvider.getVersion())) {
            LOGGER.log(Level.INFO, "Running on PrimeFaces Extensions {0}", VersionProvider.getVersion());
        }
    }
}
or in JSF resource handler
public class PrimeFacesExtensionsResource extends ResourceWrapper {

    private Resource wrapped;
    private String version;

    public PrimeFacesExtensionsResource(final Resource resource) {
        super();
        wrapped = resource;

        // get current version
        if (StringUtils.isNotBlank(VersionProvider.getVersion())) {
            version = "&v=" + VersionProvider.getVersion();
        } else {
            version = UUID.randomUUID().toString();
        }
    }

    @Override
    public String getRequestPath() {
        return super.getRequestPath() + version;
    }

    ...
}
With resource filtering you don't need to care about available current project infos in Java programs.

Sunday, January 1, 2012

New release of web resource optimization plugin

I have released a new 0.3 version of the Maven plugin for web resource optimization. As I mentioned in the last posts this plugin was created as a part of the PrimeFaces Extensions project. It produces better compression results than YUI Compressor and has some nice features. The current release fixes only one issue. Release notes are here. The plugin is available in the Maven central repository.

If you have any questions regarding to the configuration, ask me please in the PrimeFaces Extensions forum. This forum is also a good place for all questions to the components and more. Unfortunately, but PrimeFaces lead doesn't like to see any discussions related to our extensions in the main PrimeFaces forum. He considers such topics as advertisement and locks / removes them. That hurts and is weird because if it would be an advertisement, it would be an advertisement for PrimeFaces. We have "PrimeFaces" in the name "PrimeFaces Extensions". The aim was never to do an advertisement or get money. This project is just for fun, everybody can participate in.

Currently we are working on the last use cases for our showcase and plan to do a release in the middle of January. Next releases will be published at frequent intervals and include less stuff - approximately 2-4 new components, client behaviors, converters or similar JSF 2 related artefacts. Some stuff is amazing, so stay tuned.

Best wishes for the New Year!

Tuesday, December 27, 2011

Maven plugin for web resource optimization - advanced settings

In the last post I have introduced a new Maven plugin resources-optimizer-maven-plugin. This post is about two advanced features. Aggregation tag has a sub-tag subDirMode. This is an aggregation per sub-folder. Assume, JavaScript / CSS files are grouped by sub-folders which represent software modules. Resources of each module can be optimized separately in an easy way. As output we would have aggregated files per sub-folder. Names of aggregated files are the same as their folder names where they are placed. Files are aggregated in the lexicographic order. The following pictures demonstrate this approach.

Original source files below sub-folder keyfilter:


Aggregated file in target below sub-folder keyfilter:


This can be achieved with the following resources set
<resourcesSet>
    <includes>
        ...
        <include>keyfilter/**</include>
        ...
    </includes>
    <aggregations>
        <aggregation>
            <inputDir>...</inputDir>
            <subDirMode>true</subDirMode>
        </aggregation>
    </aggregations>
</resourcesSet>
The second feature is a preparation of uncompressed resources. Sometimes you have to build / deliver compressed and uncompressed resources. In JSF you can use then uncompressed resources if ProjectStage is "Development". RichFaces has e.g. this handy feature. resources-optimizer-maven-plugin allows to define several aggregation tags, e.g. one for compressed and one for uncompressed resources. The following picture demonstrates this approach.

Two folders, for compressed (primefaces-extensions) and uncompressed (primefaces-extensions-uncompressed) resources:


That can be achieved with this resources set
<resourcesSet>
    <includes>
        ...
    </includes>
    <aggregations>
        <aggregation>
            <inputDir>${resources.dir.compressed}</inputDir>
            ...
        </aggregation>
        <aggregation>
            <withoutCompress>true</withoutCompress>
            <inputDir>${resources.dir.uncompressed}</inputDir>
            ...
        </aggregation>
    </aggregations>
</resourcesSet>

<properties>
    <resources.dir.compressed>
        ${project.build.directory}/classes/META-INF/resources/primefaces-extensions
    </resources.dir.compressed>
    <resources.dir.uncompressed>
        ${project.build.directory}/classes/META-INF/resources/primefaces-extensions-uncompressed
    </resources.dir.uncompressed>
</properties>
Output directory for uncompressed resources should be created first. Put maven-resources-plugin with phase generate-resources in front of resources-optimizer-maven-plugin (phase prepare-package).
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <executions>
        <execution>
            <id>copy-resources</id>
            <phase>generate-resources</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <outputDirectory>${resources.dir.uncompressed}</outputDirectory>
                <resources>
                    <resource>
                        <directory>${project.basedir}/src/main/resources/META-INF/resources/primefaces-extensions</directory>
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>
These were examples for an JAR project. The same is also valid for WAR (web) projects of course.

Monday, December 19, 2011

New Maven plugin for web resource optimization

Two months ago I released the first version of a new Maven plugin for web resource optimization. This plugin was created as a part of the PrimeFaces Extensions project. What is the PrimeFaces Extensions project? Thomas Andraschko and me have launched this young project with the aim of extending JSF library PrimeFaces. What does extending mean? We don't have "extends SomePrimeFacesComponent" in the code. It doesn't make sense to copy-&-paste or overwrite existing PrimeFaces code. PrimeFaces is a rapidly evolving component set and costs to maintain the entire code from release to release would be too high. Extending means, we use core functionality of PrimeFaces like core.js and CoreRenderer.java. Well. What for components and other stuff we have is not the topic of this post. This is a topic for next post(s). I just would like to appeal to everybody having JSF / PrimeFaces expert knowledge to contact us. Any help would be appreciated. We have great ideas and plans, but Thomas and me are full time worker and involving in various daily projects, so that time for PrimeFaces Extensions is very sparse. Even worse in my case. I can only work 15-20% for JSF in my daily work currently. So, everybody with experience in JSF / PrimeFaces can join this open source project.

Maven plugin for resource optimization can compress and merge JavaScript and CSS files very efficiently. It produces better results than all plugins I know. The new Maven plugin combines Google Closure Compiler (for JavaScript files) and YUI Compressor (for CSS files). The new plugin is highly configurable and allows some nice features which don't exist in other plugins. I would like to mention some highlights:
  • Flexible resource sets describing resources to be processed.
  • Settings for compilation and warning levels for Google Closure Compiler. Defaults are SIMPLE_OPTIMIZATIONS and QUIET.
  • Aggregation with or without compression.
  • Suffix for compressed / aggregated files if needed.
  • SubDirMode for files aggregation. Resources of each software module can be optimized separately in an easy way. It makes sense e.g. for component / widget development because you can say "merge files for component A to one big file and don't merge files for component B".
  • Possiblity to define a file to be prepended to the aggregated file.
  • Possiblity to build compressed and uncompressed resources at the same time. PrimeFaces community already asked about uncompressed resources for development stage. RichFaces and some other libs can deliver uncompressed resources if the ProjectStage is "Development". We have also done this for PrimeFaces Extensions by means of this plugin. A special JSF ResourceHandler can stream down uncompressed resources to the browser for the ProjectStage "Development". Never crypto-messages like "e is undefined" anymore!
I have tried to write a more or less comprehensive documentaion. Simple check it! We already use this plugin with success in 6-8 JAR and WAR projects. I have also drawn a comparison diagram for PrimeFaces: size in bytes without compression, with yuicompressor-maven-plugin and with our resources-optimizer-maven-plugin. And I have prepared a configuration for PrimeFaces to make changes easy. More details in the online documentation. We would be glad to see the resources-optimizer-maven-plugin in PrimeFaces! It's worth. This plugin is available in the Maven central repository. In the meantime I have released a new 0.2 version. Feedback is welcome. Thanks.

The next Maven plugin I'm planning to write is a CDK (component development kit) for PrimeFaces components (low prio, depends on free time). PrimeFaces has already one, but only for internal use. Futhermore, PrimeFaces's plugin doesn't generate component's source files under source folder (they are not under version control) and has an expensive configuration. The new CDK will be configurable via name conventions and avoid expensive configuration. The technique for that will be Java Emitter Templates (JET) from Eclipse Modeling Framework. Here is again - every help is appreciated. We have some code styles, so that our code is clean and optimized. But it's not a problem at all to follow them, even in a remote team. I'm convinced, the work in a distributed team can be very efficient.

Friday, September 16, 2011

Inheritance in Maven based web projects

Sometimes you want to define a base web project and reuse all web based stuff in all other web projects. This is not rare in big projects. The first thought coming in mind is inheritance. Is there any inheritance between web projects at all? Yes, in a manner of speaking. In Maven based projects there is a nice "overlay" feature for maven-war-plugin. You can point to the base WAR project in the overlay tag and the base project gets extracted bevor it's stuff will be extended or overwritten by inherited project. An example:
<plugin>
    <artifactId>maven-war-plugin</artifactId>
    ...
    <configuration>
        <overlays>
            <overlay>
                <groupId>ip.client</groupId>
                <artifactId>ip-theme-framework</artifactId>
                <classifier>webapp</classifier>
                <excludes>
                    <exclude>META-INF/**</exclude>
                    <exclude>WEB-INF/web.xml</exclude>
                    <exclude>WEB-INF/lib/**</exclude>
                    <exclude>WEB-INF/classes/**</exclude>
                </excludes>
            </overlay>
        </overlays>
    </configuration>
</plugin>
You have also to add a dependency in your inherited project for the base project, of course. Well, this feature works fine, but there is a problem with transitive dependencies. Dependencies defined in the base project are "invisible" for inherited projects. You can not use transitive dependencies, they aren't going to be inherited. And adding of all dependencies again in inherited projects is error-prone and causes some issues during release management. To solve this problem, we can set packaging of all web projects as jar. That's what we do in my company.
<packaging>jar</packaging>
With packaging jar you have still a WAR archive at the end, but Java sources are packed to one jar file which is placed by Maven below WEB-INF/lib inside of the WAR. WEB-INF/classes stays empty. Dependencies get now accepted. One thing to keep in mind: WAR projects with packaging jar should be specified twice as dependencies. Once without <type> and once with <type>war</type>. An example:
<dependency>
    <groupId>ip.client</groupId>
    <artifactId>ip-theme-framework</artifactId>
</dependency>
<dependency>
    <groupId>ip.client</groupId>
    <artifactId>ip-theme-framework</artifactId>
    <classifier>webapp</classifier>
    <type>war</type>
    <scope>runtime</scope>
</dependency>
The last be not least is the support in IDEs. JAR projects are not recognized as web projects in Eclipse, IntelliJ or somewhere else and you lose all goodies from your preferred IDE. A solution is simple and uses profiles. Define a property ${packaging.war} for a special profile (see my last post).
<profile>
    <id>ide</id>
    <properties>
        <packaging.war>war</packaging.war>
    </properties>
</profile>
write variable packaging.war in the packaging tag of your project
<packaging>${packaging.war}</packaging>
and let Maven run with this profile when creating IDE specific files:
mvn -Pide eclipse:eclipse
mvn -Pide idea:idea
...
Summary: Overlays help to reuse web projects. They also help to customize web projects by having one big core project and many small custom specific projects which only have specific CSS, Images (logos, ect.) and messages in property files. Custom specific Maven projects don't have Java classes - the aim is to overwrite / extend resources of core project and achieve a custom Look-&-Feel.

Wednesday, September 14, 2011

Filter web.xml with Maven

Maven (build manager for Java projects) has a feature called "filtering". As is generally known you can replace with Maven any variables defined with placeholders like ${my.variable}. Such variables can be placed in property files or any other resource files like CSS, JavaScript, (X)HTML. I normally place placeholders in web.xml and replace them by real values while Maven runs with a certain profile. My default Maven profile is e.g. "development". Another profile is "release". To build artefacts with "release" profile I run
mvn -Prelease clean install
Option -P is for profile you want to build software with. How to set up filtering of web.xml exactly? At first we need to create a directory "filter" under "src/main" and place two (or more) property files under "src/main/filter". In order to demonstrate filtering for two profiles I'm going to create development.properties and release.properties. So, our structure looks now as follows:


Let us define the content of development.properties as
jsf.faceletsRefreshPeriod=2
jsf.resourceUpdateCheckPeriod=2
and the content of release.properties as
jsf.faceletsRefreshPeriod=-1
jsf.resourceUpdateCheckPeriod=-1
The next step is to modify web.xml. web.xml gets two placeholders:
...
<context-param>
    <param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
    <param-value>${jsf.faceletsRefreshPeriod}</param-value>
</context-param>
<context-param>
    <param-name>com.sun.faces.resourceUpdateCheckPeriod</param-name>
    <param-value>${jsf.resourceUpdateCheckPeriod}</param-value>
</context-param>
...
The last step is to modify pom.xml. Actually we don't need two profiles. Let us only define the "release" profile and assume default case without any profiles as "development".
<profiles>
    <profile>
        <id>release</id>
        <properties>
            <webapp.filter>release</webapp.filter>
        </properties>
    </profile>
</profiles>
Important thing is to define a property "webapp.filter" for "release" profile. For default case we have also to add this line to pom.xml (somewhere at the end):
<properties>
    <webapp.filter>development</webapp.filter>
</properties>
To make it working together with maven-war plugin (in this case) we need to activate filtering feature. That means, before WAR archive gets packed, placeholders in web.xml should be already replaced by real values from property files. This task is simple:
<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <executions>
        <execution>
            <id>war</id>
            <phase>package</phase>
            <goals>
                <goal>war</goal>
            </goals>
            <configuration>
                ...
                <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
                <filters>
                    <filter>${basedir}/src/main/filter/${webapp.filter}.properties</filter>
                </filters>
            </configuration>
        </execution>
    </executions>
</plugin>
We leverages here the variable ${webapp.filter} which points to file name depends on currently active profile. That's all. You can now run builds with
// build for development
mvn clean install

// build for release
mvn -Prelease clean install
There is only one issue when using Jetty Maven plugin and let it runs with
mvn jetty:run
Jetty looks as default under source directory and scans src/main/webapp/WEB-INF/web.xml. But located there web.xml has placeholders. How to solve that? A solution is easy. This is a bonus part of this post. We can leverages overrideDescriptor tag and specify a XML file with our own parts of web.xml which overwrite the same parts in src/main/webapp/WEB-INF/web.xml when Jetty running.
<plugin>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>maven-jetty-plugin</artifactId>
    <configuration>
        <webAppConfig>
            ...
            <overrideDescriptor>src/main/resources/overrideweb.xml</overrideDescriptor>
        </webAppConfig>
    </configuration>
</plugin>
The content of overrideweb.xml is (we normally need settings for default "development" profile when Jetty running)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
        <param-value>2</param-value>
    </context-param>
    <context-param>
        <param-name>com.sun.faces.resourceUpdateCheckPeriod</param-name>
        <param-value>2</param-value>
    </context-param>
    <context-param>
        <param-name>com.sun.faces.injectionProvider</param-name>
        <param-value>com.sun.faces.vendor.WebContainerInjectionProvider</param-value>
    </context-param>
    <context-param>
        <param-name>com.sun.faces.spi.AnnotationProvider</param-name>
        <param-value>com.sun.faces.config.AnnotationScanner</param-value>
    </context-param>
    
    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
</web-app>
Happy filtering!

Wednesday, September 7, 2011

Useful Maven commandos

Everybody who uses Maven from console / terminal knows how sometimes difficult to remember all handy commandos using in day job. A small reference list should help.

Skip running tests for a particular project.
mvn clean install -Dmaven.test.skip=true
Continue build if it has been failed at certain point. Maybe you have many sub-projects and build your entire project from top to down. "-rf" parameters allow to continue maven running where you want after any build errors. Assume my current top directory where I let Maven run is D:\SVN and the build was broken at D:\SVN\eIP\CoreServer\DatastoreConnector. Following command let go on with the build and skip this not compilable or not testable sub-project.
mvn clean install -rf eIP\CoreServer\DatastoreConnector
Get source jar files (e.g. for Eclipse projects). Having source files in local repository allow to jump into this directly from your preferred IDE.
mvn eclipse:eclipse -DdownloadSources=true
or run
mvn dependency:sources
to download all source jars for a given project into local repository. The same for JavaDoc (if it's available).
mvn eclipse:eclipse -DdownloadJavadocs=true
Output project's dependency tree. I like that! You can see versions of all used artefacts.
mvn dependency:tree
Output is like this one
[INFO] ip.client:ip-jsftoolkit:jar:3.4.1-SNAPSHOT
[INFO] +- ip.client:ip-filter-security:jar:3.4.0:compile
[INFO] |  +- com.scalaris.commons:scalaris-commons-enterprise:jar:2.3.1-SNAPSHOT:compile
[INFO] |  |  +- com.scalaris.commons:scalaris-commons-lang:jar:2.3.0:compile
[INFO] |  |  +- org.apache.commons:commons-lang3:jar:3.0:compile
[INFO] |  |  \- commons-lang:commons-lang:jar:2.6:compile
[INFO] |  +- ip.client:ip-client-commons:jar:3.4.0:compile
[INFO] |  |  +- ip.services:ip-core-services:jar:3.4.0:compile
[INFO] |  |  |  \- ip.datatransfer:ip-datatransfer-commons:jar:3.4.0:compile
..................................................
[INFO] |  +- commons-httpclient:commons-httpclient:jar:3.0.1:compile
[INFO] |  +- org.apache.commons:commons-jexl:jar:2.0:compile
[INFO] |  \- joda-time:joda-time:jar:1.6.2:compile
[INFO] +- javax.ejb:ejb:jar:3.0:provided
[INFO] +- javax.servlet:servlet-api:jar:2.5:provided
[INFO] \- com.scalaris.commons:scalaris-commons-test:jar:2.2.8-SNAPSHOT:test
[INFO]    +- jmock:jmock:jar:1.2.0:test
[INFO]    +- junit:junit:jar:3.8.2:test
Filter project's dependency tree in order to see only a specified dependency. The syntax for filter patterns is as follows: [groupId]:[artifactId]:[type]:[version]
mvn dependency:tree -Dincludes=com.sun.faces:jsf-impl
Display the effective pom of a project. The effective pom represents the current pom state for a project (incl. maven super pom and active profiles).
mvn help:effective-pom
Generate files needed for an IntelliJ IDEA project setup.
mvn idea:idea
This plugin has no way to determine the name of the JDK you are using. It uses by default the same JDK as output java -version. Using with defined JDK:
mvn idea:idea -DjdkName=1.5
Create a web project from scratch.
mvn archetype:create 
 -DarchetypeGroupId=org.apache.maven.archetypes 
 -DarchetypeArtifactId=maven-archetype-webapp 
 -DarchetypeVersion=1.0 
 -DgroupId=com.maventest 
 -DartifactId=mywebtest 
 -Dversion=1.0-SNAPSHOT
Deploy artefact in global repository (located e.g. in file://///xyz.abc.com/maven/repo-m2).
mvn deploy:deploy-file
 -DgroupId=com.maventest
 -DartifactId=mywebtest
 -Dversion=1.0-SNAPSHOT
 -Dpackaging=war
 -Dfile=mywebapp.jar
 -DrepositoryId=xyz-release 
 -Durl=file://///xyz.abc.com/maven/repo-m2
Check all the dependencies used in your project and display a list of those dependencies with newer versions available.
mvn versions:display-dependency-updates

...
[INFO] The following dependency updates are available:
[INFO]   org.apache.maven:maven-artifact ........................ 2.0 -> 2.0.9
[INFO]   org.apache.maven:maven-plugin-api ...................... 2.0 -> 2.0.9
[INFO]   org.apache.maven:maven-project ....................... 2.0.2 -> 2.0.9
[INFO]   org.codehaus.plexus:plexus-utils ....................... 1.1 -> 1.5.6
Check all the plugins and reports used in your project and display a list of those plugins with newer versions available.
mvn versions:display-plugin-updates

...
[INFO] The following plugin updates are available:
[INFO]   maven-deploy-plugin ...................................... 2.5 -> 2.7
[INFO]   maven-jar-plugin ..................................... 2.3.1 -> 2.3.2
[INFO]   maven-plugin-plugin ...................................... 2.7 -> 2.9
[INFO]   maven-resources-plugin ................................. 2.4.3 -> 2.5
Decompile Java classes in the maven central repository :-). Useful if source code isn't available. The trick is here.