VIVO/Vitro Java Style Guide (Adopted 2023, for VIVO/Vitro 1.14.x and above)

VIVO Java Style Guide is enforced on "main" branch

As of June 2023, the below VIVO/Vitro Java Style Guide will be enforced on all Pull Requests to the "main" branch for newly created files. Therefore, if a Pull Request to the "main" branch does not align with the below Style Guide, it will fail the build process within our GitHub CI.

  1. 4-space indents. NO TABS ALLOWED.
  2. One true brace style. Braces are required on all blocks.

    if (code) {
      // code
    } else {
      // code
    }
  3. Do not use wildcard imports (e.g. import java.util.*). Duplicated or unused imports are not allowed.
  4. Maximum length of lines is 120 characters (except for long URLs, packages or imports)

  5. No trailing spaces allowed (except in comments)
  6. Tokens should be surrounded by whitespace, e.g. http://checkstyle.sourceforge.net/config_whitespace.html#WhitespaceAround

    // This is NOT valid. Whitespace around tokens is missing
    String []={"one","two","three"}
    
    // This is valid. Whitespace exists around all tokens
    String [] = { "one", "two", "three" }
  7. Each line of code can only include one statement.  This also means each variable declaration must be on its own line, e.g.

    // This is NOT valid. Three variables are declared on one line
    String first = "", second = "", third = "";
    
    // This is valid. Each statement is on its own line
    String first = "";
    String second = "";
    String third = "";
  8. Each source file must contain the required VIVO/Vitro license header, e.g.

    /*
     * This file is distributed under the terms of the license in LICENSE
     */


Resources

IDE Support

Most major IDEs include plugins that support Checkstyle configurations. The plugin usually let you import an existing "checkstyle.xml" configuration to configure your IDE to use and/or validate against that style.

IntelliJ IDEA

(These instructions are based on IntelliJ 2021.2.3.  They should apply to other recent versions, but some menus or settings may have changed.)

  • Install the IntelliJ IDEA checkstyle plugin: https://plugins.jetbrains.com/plugin/1065-checkstyle-idea
    • File →  Settings →  Plugins
    • Restart IDE
  • Configure it to use our custom checkstyle.xml for VIVO/Vitro
    • File →  Settings → Tools → Checkstyle
      • In older versions of IntelliJ, this menu may be under File → Settings → Other Settings → Checkstyle
    • Add a "Configuration File" (press the + in the table). Select VIVO/Vitro checkstyle.xml
    • Make it "Active"
    • Click Apply
  • Update IDEA's Code Style to obey the Checkstyle Rules (See also https://stackoverflow.com/a/35273850/3750035)
    • File → Settings → Editor → Code Style
    • Click the small gear icon next to "Scheme", Select "Import Scheme" → CheckStyle Configuration
    • Select our checkstyle.xml
    • Click OK
    • Click Apply
  • After importing the Checkstyle settings, your "Copyright profiles" may get reset (if you had them previously configured).  If you want IntelliJ to automatically add a copyright statement / license at the top of every Java class, you should ensure this is (re)configured:
    • File → Settings → Editor → Copyright 
    • Add a Copyright profile.  If you wish to use the DSpace copyright/license statement, the text of it is available in the LICENSE_HEADER file in the codebase (or see the Code Style Guide above)
    • Select the profile from the list, and adjust the formatting (unchecking the option "Add blank line after")
  • Optionally, you also may wish to change some default IntelliJ settings, to allow the IDE to automatically reformat code for you (when making bulk edits). This is especially important if you plan to do any bulk cleanup of existing code using IntelliJ tools
    • First, fix the default order import statements per our CheckStyle rules (these don't seem to be auto updated by the Checkstyle plugin at this time)
      • File → Settings → Editor → Code Style → Java → Imports
      • In the "Import Layout" section, ensure  the settings are in this order
        • "import static all other imports"
        • <blank line>
        • "import java.*"
        • <blank line>
        • "import javax.*"
        • <blank line>
        • "import all other imports"
      • Once reordered, click OK
    • Then, update to auto-wrap lines at the right margin
      • File → Settings → Editor → Code Style → Java → Wrapping and Braces
      • CHECK "Ensure right margin is not exceeded"
      • Click OK
    • Then, OPTIONALLY, for better looking bulk reformatting (i.e. results in more human-readable code), you may want to tweak which types of statements are set to "Wrap if long" 
      • (NOTE: Without these settings, IDEA's bulk "Reformat Code" option sometimes will generate line breaks wherever the line ends, which can result in somewhat odd looking code. These settings cleanup some of the more odd line wrappings that may occur.)
      • File → Settings → Editor → Code Style → Java → Wrapping and Braces
      • Optionally, set all of the following to "Wrap if long":
        • Extends/implements list (also check "align when multiline")
        • Extends/implements keyword
        • Throws list
        • Throws keyword
        • Method declaration parameters (also check "align when multiline")
        • Method call arguments (also check "align when multiline")
        • Chained method calls (also check "align when multiline")
        • "for()" statement (also check "align when multiline")
        • "try-with-resources" (also check "align when multiline")
      • Click OK
    • Finally, update IDEA's Javadoc settings to not insert "<p>" on blank Javadoc lines 
      • File → Settings → Editor → Code Style → Java → JavaDoc
      • UNCHECK "Generate <p> on empty lines"
      • Make sure "Keep empty lines" is checked
      • Click OK
  • Application of code style
    • Common shortcut for organizing imports is ctrl+alt+o
    • Common shortcut for code reformatting is ctrl+alt+l
Eclipse

These instructions were created using Eclipse 2022-03.

  • Apply Java Formatter configuration and imports order for workspace or project
    • For workspace
    • For project
      • Right click on the project, click on Properties.
      • In new window select on the left Java Code Style → Formatter.
      • Mark checkbox Enable project specific settings
      • Click "Import..." select VIVO and Vitro formatter profile.xml
      • Select Java → Code Style → Organize Imports.
      • Mark checkbox Enable project specific settings
      • Click "Import..." select vivo-vitro.importorder
NetBeans

These instructions worked for NetBeans 8.2.

  •  Download the NetBeans Checkstyle plugin: http://plugins.netbeans.org/plugin/3413/checkstyle-beans
    • Go to "Tools → Plugins  → Downloaded → Add Plugins... ":
      •  Add the downloaded plugin and install it! You will have to restart NetBeans.
  • Go to "Tools → Options → Miscellaneous → Checkstyle" :

The plugin still works in Apache NetBeans 12.6.  It can be obtained at https://www.sickboy.cz/checkstyle/download.html.  The instructions above should still work.

VSCode

These instructions are for VSCode version 1.63.2.

  • Open the Extensions panel. Search for and install the Checkstyle for Java extension by ShengChen. Follow the configuration docs for the plugin. The important parts are: set the configuration file, by right clicking the checkstyle.xml file and select Set the Checkstyle Configuration File . You will need to use the command Checkstyle: Set the Checkstyle Version (Help>Show All Commands, or hit F1 on your keyboard) to manually set the Checkstyle version to 8.30. The extension will automatically download the required checkstyle jar file if it needs to. Other versions of Checkstyle jar are known to not work (8.18 and 9.2.1 as of this writing all currently throw errors). 
  • You'll need to restart VSCode after adding the Checkstyle for Java extension
  • You will want to modify the setting for Java → Completion: Import Order (in the settings.json file for VScode): add this to your settings.json file: 

    "java.completion.importOrder": ["#","java","javax","com","org"],

  • Whenever you select an option to "organize imports", VSCode will incorrectly add a single blank line in your imports block, where our checkstyle configuration says it should not. The checkstyle plugin will alert you to this fact, and you can remove it manually. Unfortunately, VSCode does not currently support specifying the exact importOrder in the java.completion.importOrder that we require. But this is close enough.

Checking code style from commandline

If you do not use one of the above IDEs to write your code, you can always verify your code from the command-line using the following Maven command.  

# This checks the code style of all source code under the current directory
# It also ensures all source code has the required license header.
mvn -U checkstyle:check license:check


Fixing existing code / PRs

Use IntelliJ to perform bulk cleanup
  • First, you MUST follow all the configurations in the IntelliJ configuration section above.  Especially pay attention to the settings marked optional, unless you are doing bulk edits.  Since you want to do bulk edits, those settings are now required.
  • Now open up any Java source file. You'll see Checkstyle warnings appear (if any) in RED.
    • This highlighting is enabled via the checkstyle plugin.
  • Bulk Reformat (an entire module): You can also reformat code in bulk in IDEA: https://www.jetbrains.com/help/idea/editor-basics.html#reformat_rearrange_code
    • Right click on a single directory / module
    • Select "Reformat Code"
      • Check "Optimize imports"  (This will remove any import statements with an asterisk)
      • Leave "Rearrange entries" unchecked (This will rearrange methods/variables based on arrangement settings in IDEA. We don't need this)
      • Under "Filters" → Check "File Masks" and enter in "*.java, *.xml"  (As we'll only bulk reformat Java and XML files)
      • Click Run
  • Finally, run Checkstyle against the module. There likely will still be a few failures to fix manually.

    # mvn install  (Only necessary if checkstyle:check below complains about missing SNAPSHOT dependencies)
    mvn -U checkstyle:check
  • Also double check license headers are still accurate. Sometimes these get "munged" during bulk reformat (as IDEA occasionally tries to merge nearby comments into one larger comment)

    mvn license:check
  • No labels