## Force cleaning of workspace during automated Maven builds

I’ve been using Maven for years, but once in a while forget to ‘clean‘ before building, resulting in old artifacts being included in the output. This can be problematic when refactoring for security items. Thankfully, it is very easy to add a ‘clean‘ step to your pom.xml to force clean each build.

BONUS – the plugin has some additional capabilities, specifically you can specify files outside of ‘target’ to be removed. This can be useful for any custom reporting or logging that you might create.

The Maven clean plug-in can be added to the pom.xml as such:

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>${maven-clean-plugin.version}</version> <executions> <execution> <id>auto-clean</id> <phase>initialize</phase> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> REFERENCES: ## Selenium HtmlUnit driver separated in 2.53.0 I’ve been a user of Selenium testing for several years, though I noticed that some classes related to the HtmlUnit WebDriver were missing after upgrading from 2.52.0 to 2.53.0. After some research, I discovered that it is now a separate dependency allowing for a separate release cycle. Additionally, if you don’t use this (relatively generic) webdriver, you will no longer need to have it in your binaries. Here’s all you need to do to add it to your Maven projects for testing. In your pom.xml file: <properties> <selenium.version>2.53.0</selenium.version> <htmlunitdriver.version>2.20</htmlunitdriver.version> </properties> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>${selenium.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>htmlunit-driver</artifactId>
<version>${htmlunitdriver.version}</version> <scope>test</scope> </dependency> </dependencies> REFERENCES: ## Code signing of java applets – using Maven To sign your java assets during the maven build process, you can add the following to the pom.xml to make use of the values we established in the keystore creation step. WARNING: for security and maintainability purposes, you should define the ‘configuration’ items in your local ‘settings.xml’ file instead of in the pom.xml as is done here for example only! <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jarsigner-plugin</artifactId> <version>1.4</version> <executions> <execution> <id>sign</id> <goals> <goal>sign</goal> </goals> </execution> <execution> <id>verify</id> <goals> <goal>verify</goal> </goals> </execution> </executions> <configuration> <alias>selfsigned</alias><!--${project.name} -->
<keystore>selfsignkeys.store</keystore><!-- NOTE: you can also specify an absolute path here -->
<storepass>123456</storepass>
<keypass>123456</keypass>
</configuration>
</plugin>

REFERENCES:

I’ve migrated most of my projects to Maven, but occasionally have some developers that prefer to use Ant in their development environments. One problem that I used to have with Ant was that it required all dependencies to be checked into the SCM repository for each project. I recently found an Ant plugin that allows for it to read the Maven pom.xml and download the required dependencies, thus making projects MUCH easier to maintain! the steps are very simple.

Maven – pom.xml

• Make sure that you have your dependencies (nexus?) setup and tested here.

Maven – global settings.xml

• Make sure that your repositories are correctly configured.

Ant – build.xml (very minimal, I usually add as a step in existing scripts vs. using as standalone)

• (example):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE project>
<project name="example" basedir="." default="dependencies" xmlns:artifact="antlib:org.apache.maven.artifact.ant">
<target name="dependencies">
<echo message="--- getting dependencies from maven pom.xml ---" />
<artifact:pom id="pom" file="pom.xml" /><!-- settingsFile="settings.xml" -->
<artifact:dependencies filesetId="test.dependencies" pomRefId="pom" useScope="test" />
<copy todir="${antlib.dir}"> <fileset refid="test.dependencies" /> <mapper type="flatten" /> </copy> </target> </project> • Make sure that you put the JAR (maven-ant-tasks-2.1.3.jar) in the proper place… Executing: • ant dependencies If everything is working well, you can now purge most of the JAR’s that reside inside your web projects as the Ant build process can retrieve them based on values in the Maven pom.xml file. ## Load Testing web application with Selenium and TestNG I’ve used Selenium for while to do verification tests of web applications, recently I discovered a very simple way to use it with TestNG and Maven to do some performance testing. TestNG allows for the use of annotations to allow multi-threading and iterations. pom.xml: <dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.44.0</version> <scope>test</scope> </dependency> <dependencies> And as for a simple test to get started with… scripting of steps is available online or could be in a future blog post. /* * COPYRIGHT. none */ package com.example.selenium; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.firefox.FirefoxDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Simple test example for Selenium */ public class SeleniumTest { private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumTest.class); /** * TODO Un-comment or change if needed to set your local path! */ @BeforeClass public void oneTimeSetUp() { System.out.println("-------------------------------------- init ----------------------------------------"); //System.setProperty("webdriver.firefox.bin","C:\\path\\to\\firefox.exe"); } /** * NOTE: uses TestNG - behaves differently than JUnit */ @Test(invocationCount = 1, threadPoolSize = 5) public void testLoadApp() { final String fn = "testLoadApp"; final String baseUrl = "http://www.giantgeek.com/index.php"; LOGGER.debug("[START] Thread Id: {} is started!", Thread.currentThread().getId()); WebDriver driver = null; final long start = System.currentTimeMillis(); try{ driver = (WebDriver)new FirefoxDriver(); driver.get(baseUrl); final String actual = driver.getTitle(); LOGGER.debug("Page Title is {}", actual); final String expected = "GIANTGEEK.COM"; Assert.assertEquals(actual,expected); //perform whatever actions, like login, submit form or navigation }catch(final WebDriverException ex){ LOGGER.warn(fn+":WebDriverException:{}",ex); }catch(final Exception ex){ LOGGER.warn(fn+":Exception:{}",ex); } finally { final long elapsed = System.currentTimeMillis() - start; LOGGER.debug("[END] Thread Id: {}, elapsed={}", Thread.currentThread().getId(),elapsed); if(driver != null){ driver.quit(); } } } } WARNING: Selenium Tests MAY fail if the browser used for testing is updated in the Operating System. Updating the pom.xml to a newer release usually helps! REFERENCES: ## Read XML Properties in Java Once in a while you need to externalize some configuration without the overhead of a complete framework, here’s a simple method to read an XML formatted property file in java. In most cases, it’s a performance advantage to wrap this up in a Singleton pattern, but that’s a different topic altogether. private getAttributes() { final String filename = "example.properties"; final InputStream input = getClass().getClassLoader().getResourceAsStream(filename); if(input==null){ System.err.println("Cannot find properties:"+ filename); } final java.util.Properties props = new java.util.Properties(); try { props.loadFromXML(input); hostprop = props.getProperty("hostname",null); userprop = props.getProperty("username",null); pswdprop = props.getProperty("password",null); } catch(final Exception e){ System.err.println("Error occurred while reading properties file:"+ input); e.printStackTrace(); } finally{ try { input.close(); } catch(final java.io.IOException ex){ ex.printStackTrace(); } } } The matching file would resemble… <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <entry key="hostname">localhost</entry> <entry key="username">example</entry> <entry key="password">example</entry> </properties> ## “msapplication-config” and browserconfig.xml Windows-8/MSIE-11 introduced Tiles, as such server administrators may have started seeing HTTP 404 errors in their server logs as it attempts to look for a “browserconfig.xml” file at the root of a website domain. If you are inclined to use this file, you should definitely look into the documentation for how to best make use of it. Others may just wish to prevent the error from making “noise” in their log files. To remove the error, add the following to your pages; alternately you COULD define the URL of your file as the ‘content’ attribute: <meta name="msapplication-config" content="none" /> You can alternately place an empty /browserconfig.xml on your web server for each domain. An common example of how to use this file is below: <?xml version="1.0" encoding="utf-8"?> <browserconfig> <msapplication> <tile> <square70x70logo src="/mstile-70x70.png"/> <square150x150logo src="/mstile-150x150.png"/> <wide310x150logo src="/mstile-310x150.png"/> <square310x310logo src="/mstile-310x310.png"/> <TileColor>#8bc53f</TileColor> <TileImage src="/mstile-150x150.png" /> </tile> </msapplication> </browserconfig> REFERENCES: ## Maven build script for replacement of text in web.xml (and others) Automated replacement of BUILD_LABEL token in web.xml <description> with Maven. For JAR’s the replacement is commented out, but can be any file. NOTE: This proves to be rather difficult to do because of the way that Maven copies resources as it’s building the WAR. The most reliable manner I’ve found (so far) is below, it works by making a .tmp copy of the web.xml in a different path and then later uses it in the WAR. <plugins> <plugin> <groupId>com.google.code.maven-replacer-plugin</groupId> <artifactId>replacer</artifactId> <version>1.5.3</version> <configuration> <quiet>false</quiet> </configuration> <executions> <execution> <id>replaceBuildLabel</id> <phase>prepare-package</phase> <goals> <goal>replace</goal> </goals> <configuration> <file>${basedir}/src/main/webapp/WEB-INF/web.xml</file>
<outputFile>${project.build.directory}/web.xml.tmp</outputFile> <replacements> <replacement> <token>BUILD_LABEL</token> <value>Maven-${maven.build.timestamp}</value>
</replacement>
</replacements>
<regex>false</regex>
<quiet>false</quiet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.5</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<webXml>${project.build.directory}/web.xml.tmp</webXml> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries> </manifest> <manifestEntries> <url>${project.url}</url>
<Build-Label>${maven.build.timestamp}</Build-Label> </manifestEntries> </archive> </configuration> </plugin> </plugins> Most importantly, you will want to have this token in the web.xml file for replacement, the description line is best used for this as such: <description>ExampleWAR [BUILD_LABEL]</description> during the build, that value would be replaced to something like: <description>ExampleWAR [Maven-20141015-1700]</description> REFERENCES: ## Ant build script for replacement of text in web.xml (and others) Automated replacement of BUILD_LABEL in web.xml <description> with Ant. For JAR’s the replacement is commented out, but can be any file <replace file="${webapp.dir}/WEB-INF/web.xml" token="BUILD_LABEL" value="Ant-${DSTAMP}-${TSTAMP}" />
<war destfile="${jar.dir}/${ant.project.name}.war" webxml="\${webapp.dir}/WEB-INF/web.xml" compress="true">

Most importantly, you will want to have this token in the web.xml file for replacement, the description line is best used for this as such:

<description>ExampleWAR [BUILD_LABEL]</description>

during the build, that value would be replaced to something like:

<description>ExampleWAR [Ant-20141015-1700]</description>

REFERENCES:

## Maven/Ant echoproperties at build time

Once you have started using automation tools for continuous builds, you often find edge cases where your builds have minor variations due to the environments on which the projects have been built. To isolate these, it is often useful to have the build tool output a snapshot of it’s properties at the time the project was built. Thankfully, Ant and Maven make this easy to implement, required additions to your config files are below for each tool.

Maven: (pom.xml)

....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>install</phase>
<configuration>
<target>
<echoproperties />
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>

NOTE: ‘target’ is preferred over ‘tasks’ in newer versions of the plugin, it was deprecated in 1.5.

Ant: (build.xml)

...
<echoproperties />
...

REFERENCES: