Implementing quality in Java projects


Published on

Based on the example of the XWiki Open Source project ( this session will describe a number of practices to improve the quality of a Java project. Also, it will show how to implement these practices so that they are automatically checked and enforced. Some examples include: *How to make sure your project does not break binary compatibility unintentionally and, more generally, how to successfully evolve an API without breaking your users; *How to manage the JAR hell and avoid duplication of classes in your application at runtime; *How to automatically control the test coverage and the associated policies; *How to automate functional testing of web applications and how to avoid false-positives that plague any project..

Published in: Technology, Education

Implementing quality in Java projects

  1. 1. Implementing Qualityon Java projectsVincent MassolCommitter XWikiCTO XWiki SAS@vmassolSaturday, April 20, 13
  2. 2. Vincent Massol• Speaker Bio•CTO XWiki SAS• Your Projects•XWiki (community-driven open source project)•Past: Maven, Apache Cargo, Apache Cactus, PatternTesting• Other Credentials:•LesCastCodeurs podcast•Creator of OSSGTP open source group in ParisSaturday, April 20, 13
  3. 3. What is Quality?Saturday, April 20, 13
  4. 4. The XWiki project in summary• 9 years old• 28 activecommitters• 7 committersdo 80% ofwork• 700KNCLOC• 11 commits/daySaturday, April 20, 13
  5. 5. Examples of Quality actions• Coding rules (Checkstyle, ...)• Test coverage• Track bugs• Don’t use Commons Lang 2.x• Use SLF4J and don’t drawLog4J/JCL in dependencies• Automated build• Automated unit tests• Stable automated functionaltests• Ensure API stability• Code reviews• License header checks• Release with Java 6• Ensure javadoc exist• Prevent JAR hell• Release often (every 2 weeks)• Collaborative design• Test on supportedenvironments (DB & Browsers)Saturday, April 20, 13
  6. 6. Quality Tip #1API StabilitySaturday, April 20, 13
  7. 7. The ProblemClass Not Found or Method NotFoundSaturday, April 20, 13
  8. 8. API Stability - Deprecations/*** ...* @deprecated since 2.4M1 use {@link #transform(* Block, TransformationContext)}*/@Deprecatedvoid transform(XDOM dom, Syntax syntax)throws TransformationException;Saturday, April 20, 13
  9. 9. API Stability - CLIRR (1/2)<plugin><groupId>org.codehaus.mojo</groupId><artifactId>clirr-maven-plugin</artifactId><configuration><ignored><difference><differenceType>7006</differenceType><className>org/xwiki/.../MetaDataBlock</className><method>org.xwiki....block.Block clone()</method><to>org.xwiki.rendering.block.MetaDataBlock</to><justification>XDOM#clone() doesnt clone the metadata</justification></difference>...Saturday, April 20, 13
  10. 10. API Stability - CLIRR (2/2)Example from XWiki 5.0M1 Release notesSaturday, April 20, 13
  11. 11. API Stability - Internal PackageJavadocCLIRR<plugin><groupId>org.codehaus.mojo</groupId><artifactId>clirr-maven-plugin</artifactId><excludes><exclude>**/internal/**</exclude><exclude>**/test/**</exclude><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-javadoc-plugin<configuration><excludePackageNames>*.internal.*</excludePackageNames>Saturday, April 20, 13
  12. 12. API Stability - Legacy ModuleAspect Weaving+ “Legacy” Profile<plugin><groupId>org.codehaus.mojo</groupId><artifactId>aspectj-maven-plugin</...>...<configuration><weaveDependencies><weaveDependency><groupId>org.xwiki.rendering</...><artifactId>xwiki-rendering-api</...>...Saturday, April 20, 13
  13. 13. API Stability - Young APIs/*** ...* @since 5.0M1*/@Unstable(<optional explanation>)public EntityReference createEntityReference(String name,...){...}+ max duration for keeping the annotation!Saturday, April 20, 13
  14. 14. API Stability - Next steps• Annotation or package for SPI?• Better define when to use the @Unstableannotation• Not possible to add a new method to an existingInterface without breaking compatibility•Java 8 and Virtual Extension/Defender methodsinterface TestInterface {  public void testMe();  public void newMethod() default {    System.out.println("Default from interface"); }Saturday, April 20, 13
  15. 15. Quality Tip #2JAR HellSaturday, April 20, 13
  16. 16. The ProblemClass Not Found or Method NotFound or not working featureSaturday, April 20, 13
  17. 17. No duplicate classes @ runtime<plugin><groupId>com.ning.maven.plugins</groupId><artifactId>maven-duplicate-finder-plugin</artifactId><executions><execution><phase>verify</phase><goals><goal>check</goal></goals><configuration><failBuildInCaseOfConflict>true</...><exceptions>...Saturday, April 20, 13
  18. 18. Surprising results...• Commons Beanutils bundles some classes from CommonsCollections, apparently to avoid drawing a dependency to it...• Xalan bundles a lot of other projects (org/apache/xml/**, org/apache/bcel/**, JLex/**, java_cup/**, org/apache/regexp/**). Inaddition, it even has these jars in its source tree without anyindication about their versions...• stax-api, geronimo-stax-api_1.0_spec and xml-apis all* classes• xmlbeans and xml-apis draw incompatible versions oforg.w3c.dom.* classes14 exceptions in total!Saturday, April 20, 13
  19. 19. Maven: dependency version issue<dependencies><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.4.0</version></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>0.9.9</version><!-- Depends on org.slf4j:slf4j-api:1.5.0 --></dependency></dependencies>Will run logback 0.9.9with slf4J-api 1.4.0instead of 1.5.0!Saturday, April 20, 13
  20. 20. Maven: ensure correct version<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-enforcer-plugin</artifactId><executions><execution><id>enforce-version-compatibility</id><phase>verify</phase><goals><goal>enforce</goal></goals><configuration><rules><requireUpperBoundDeps/></rules>Saturday, April 20, 13
  21. 21. Quality Tip #3Test CoverageSaturday, April 20, 13
  22. 22. The ProblemMore bugs reported, overallquality goes down and harder todebug softwareSaturday, April 20, 13
  23. 23. Use Jacoco to fail the build<plugin><groupId>org.jacoco</groupId><artifactId>jacoco-maven-plugin</artifactId><executions><execution><id>jacoco-prepare</id><goals><goal>prepare-agent</goal></goals></execution><execution><id>jacoco-check</id><goals><goal>check</goal></goals></execution></executions><configuration><check><instructionRatio>${xwiki.jacoco.instructionRatio}</...></check>}Saturday, April 20, 13
  24. 24. Strategy• When devs add code (and thustests), increase the TPC percentage• Put the Jacoco check in “Quality”Maven Profile• Have a CI job to execute thatprofile regularly•About 15% overhead compared to buildwithout checks• “Cheat mode”: Add easier-to-writetestSaturday, April 20, 13
  25. 25. Quizz Time![INFO] --- jacoco-maven-plugin: (jacoco-check)[INFO] All coverage checks have been met.[INFO] --- jacoco-maven-plugin: (jacoco-check)[WARNING] Insufficient code coverage for INSTRUCTION: 75.52% < 75.53%Step 1: Building on my local machine gives the following:Step 2: Building on the CI machine gave:Non determinism! Why?Saturday, April 20, 13
  26. 26. Quizz Answerprivate Map componentEntries = new ConcurrentHashMap();...for (Map.Entry entry : componentEntries.entrySet()){if (entry.getValue().instance == component) {  key = entry.getKey();    oldDescriptor = entry.getValue().descriptor;    break;  }}... because the JVM is non deterministic!Saturday, April 20, 13
  27. 27. Quality Tip #4Functional TestingStabilitySaturday, April 20, 13
  28. 28. The ProblemToo many false positivesleading to developers notpaying attention to CI emailsanymore... leading to failingsoftwareSaturday, April 20, 13
  29. 29. False positives examples• The JVM has crashed• VNC is down (we run Selenium tests)• Browser crash (we run Selenium tests)• Git connection issue• Machine slowness (if XWiki cannot start under 2 minutesthen it means the machine has some problems)• Nexus is down (we deploy our artifacts to a Nexusrepository)• Connection issue (Read time out)Saturday, April 20, 13
  30. 30. Step 1: Groovy PostBuild Plugin (1/2)def messages = [[".*A fatal error has been detected by the Java Runtime Environment.*","JVM Crash", "A JVM crash happened!"],[".*Error: cannot open display: :1.0.*","VNC not running", "VNC connection issue!"],...]def shouldSendEmail = truemessages.each { message ->if (manager.logContains(message.get(0))) {manager.addWarningBadge(message.get(1))manager.createSummary("warning.gif").appendText(...)manager.buildUnstable()shouldSendEmail = false}}Saturday, April 20, 13
  31. 31. Step 1: Groovy PostBuild Plugin (2/2)... continued from previous slide...if (!shouldSendEmail) {def pa = new ParametersAction([new BooleanParameterValue("noEmail", true)])}Saturday, April 20, 13
  32. 32. Step 2: Mail Ext Pluginimport hudson.model.*build.actions.each { action ->if (action instanceof ParametersAction) {if (action.getParameter("noEmail")) {cancel = true}}}Pre-send ScriptSaturday, April 20, 13
  33. 33. Results+ use the Scriptler plugin to automate configuration for all jobsSaturday, April 20, 13
  34. 34. Quality Tip #5Bug Fixing DaySaturday, April 20, 13
  35. 35. The ProblemBugs increasing, evensimple to fixones, devs focusing too much onnew features (i.e. scope creep)vs fixing what existsBugs created vs closedSaturday, April 20, 13
  36. 36. Bug Fixing Day• Every Thursday• Goal is to close the max number of bugs• Triaging: Can be closed with Won’t fix,Duplicate, Cannot Reproduce, etc• Close low hanging fruits in priority• Started with last 365 days then with last 547days and currently with last 730 days (weneed to catch up with 6 bugs!)Saturday, April 20, 13
  37. 37. ResultsSaturday, April 20, 13
  38. 38. ConclusionSaturday, April 20, 13
  39. 39. Parting words• Slowly add new quality check over time• Everyone must be on board• Favor Active Quality (i.e. make the build fail) overPassive checks• Be ready to adapt/remove checks if found not usefulenough• Quality brings some risks:•Potentially less committers for your project (especially opensource)Saturday, April 20, 13
  40. 40. Be proud of your Quality!“I have offended God andmankind because my workdidnt reach the quality it shouldhave.”Leonardo da Vinci, on his death bedSaturday, April 20, 13