Helpful git command chaining

I am currently working in a team of two using a git repository. In that environment, you want to have a clean history which can only achieved with the git rebase command. Using this small code snippet, I can fetch the changes online, rebase my code according to the changes fetched and push my changes automatically. If an error occurs, the command will abort.

git fetch && git rebase && git push

However, this does not work if you still have files locally which are not committed, e.g. some changed files in your working directory. For this purpose, the stash can be used. The git stash is a stack for storing changes temporarily. By saving the uncommitted changes before fetching and rebasing, you can integrate them back afterwards.

git stash save && git fetch && git rebase && git push && git stash pop

What git tricks do you use?

PS: The commands above work on *nix and Windows.

Advertisements

Ant Patterns – Continued

This is a follow up post of the previous one about the build tool Apache Ant and usage patterns called Ant Patterns.

Converting a Path to a Property

You can use Ant to gather a list of files from a fileset and convert this using pathconvert to a property with each file on a separate line. The property ${line.separator} is a JVM and OS dependent system property which is automatically available for every ant script.

<fileset id="my.files" dir="." includes="**/*.php">
      <!-- any condition, etc. ... -->
</fileset>
<!-- joins all files together into one string -->
<pathconvert pathsep="${line.separator}" property="my.files.flattend" refid="my.files"/>

The resulting property can then by piped to a program which receives the list on its standard input (STDIN) adhereing to the Unix principles. An example is shown below which uses a ruby script.

<fileset id="my.files" dir="." includes="**/*.php">
      <!-- any condition, etc. ... -->
</fileset>
<!-- joins all files together into one string -->
<pathconvert pathsep="${line.separator}" property="my.files.flattend" refid="my.files"/>
<!-- pipes the list of all files seperated by new lines to a script -->
<exec executable="ruby.exe" inputstring="${my.files.flattend}">
      <arg value="${my.script.name}"/>
</exec>

Note: Usage of the Ant Pattern Executing Platform Independent from the previous post in conjunction with this pattern is strongly recommended.

Ant as a Template System

Ant can use its property resolution mechanism for evaluating templates. This is useful if you need to generate files using templates. The templates can be read from any file while the properties can be stated within the ant file directly, read from a property file, xml file or requested from the user. An example is given below with leverages the copy task with its filterchain which can provide additional operations for the files to be copied, in this case the expansion of the properties. The filterchain basically implements the Unix pipes the Ant way.

<!-- make sure properties are set using the property, propertyfile, xmlproperty or input task -->
<property name="name" value="World" />

<!-- apply template by copying -->
<copy file="${template}" tofile="${target}"> 
  <filterchain> 
    <!-- fill the blanks with values -->
    <expandproperties/> 
  </filterchain> 
</copy>

Given the contents of the template.tt are Hello ${name}, the contents of the ${target} file will be Hello World.

This approach gives only simple property expansion as loops, conditions or any other mechanism normally used in templates does not work. However, this may suffice for some use cases.

Formatting XML Files Resulting from XSLT Transformations

Ant can use xslt stylesheets in the xslt task to transform a XML file to another XML file or simple text. In many cases, the result is another XML file which should look formatted well. However, Ant uses by default Apache Xalan as its XSL engine which contains a bug ignoring the indent attribute of the ouput tag. The listing below shows such the stub of a stylesheet which results in unindented XML code.

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
    <!-- templates and stuff -->
</xsl:stylesheet>

This can be solved by adding the special indent-amount attribute to the output element with the namespace http://xml.apache.org/xslt and set it, for example, to 4 spaces.

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt">
    <xsl:output method="xml" indent="yes" encoding="UTF-8" xalan:indent-amount="4"/>
    <!-- templates and stuff -->
</xsl:stylesheet>

More information about this can be found here.

Additional Links

Ant Patterns

Ant is a common build tool with very extensive documentation. It is still widely used and I recommend this tool for automating file system heavy steps. You can even call Ant tasks directly in Groovy using the AntBuilder which brings you an extremely powerful and well documented API without any hustle.

Here I have gathered a few Ant Patterns that you should be aware of when you build an Ant script.

Presence Validator for Properties

The properties can be loaded from a properties file, xml file or set directly using the property task. A property can only be defined once and cannot be overridden as it has the semantics of a final constant.

To ensure that a property is set, you can use the fail task to abort unless the property has been defined beforehand.

<fail unless="property.key"/>
<echo message="property.key = ${property.key}"/>

However, failing without a message makes the error very hard to come by. Therefore, the message attribute should be used to indicate the failure reason.

<fail message=""the property property.key is not defined" unless="property.key"/>
<echo message="property.key = ${property.key}"/>

If there are many property checks in a build file, these two lines have to be duplicated for every property to check. Much better is the use of a macrodef task which is basically a custom task with private properties named attributes.

<!-- definition of validate-presence-of-property task -->
<macrodef name="validate-presence-of-property">
       <attribute name="propertyKey"/>
       <sequential>
               <fail message="the property @{propertyKey} is not defined" unless="@{propertyKey}"/>
               <echo message="@{propertyKey} = ${@{propertyKey}}"/>
       </sequential>
</macrodef>

<!-- usage of the macrodef -->
<validate-presence-of-property propertyKey="my.property" />

The @{propertyKey} resolves to the given attribute value, in the example above to my.property. If you need the value of my.property, you have to evaluate it using the standard evaluation mechanism ${@{propertyKey}}.

The presented solution has been adapted from this presentation. This pattern can be reused for validate the presence of files, folders and the like using arbitrary conditions.

Default Values for Properties

A very common use case is to define a property with a default value and let the user override that value with a property file. As a property can only be initialized once, we can use this to implement this very simple by importing the properties from a file and try to set the properties to their default values afterwards. Setting the default value will fail (without an error) in case the property already exists.

<!-- include properties from file -->
<property file="my.properties"/>

<!-- set defaults which are only set if the properties do not already exist -->
<property name="some.property" value="default-value"/>

Updating/Removing Itself

Ant can delete/modify its own build file. This can be useful if you want to update the build file with an update target. A use case for this is to generate the build.xml from another xml file via xslt as I have implemented it in this project. In that case, I generate the build.xml from the manifest.xml of a Joomla extension.

<!-- updating using a stylesheet -->
<xslt in="manifest.xml" out="build.xml" style="some-stylesheet.xsl" force="true"/>
<!-- removing -->
<delete file="build.xml"/>

For this pattern, I was inspired by this blog post which shows that ant can delete itself.

Executing Platform Independent

Executing commands on the command line with ant can be problematic with the exec task. Under linux or Mac OSX you can execute the command directly while you need to prepend cmd /c under Windows as described here. Because the scripts should be platform independent, you can make use of the osfamily attribute of the exec task which executes the task only if the operating system matches the given osfamily.

<exec executable="cmd" osfamily="windows">
     <arg value="/c"/>
     <arg value="ruby"/>
     <arg value="-v"/>
</exec>
<exec executable="ruby" osfamily="unix">
     <arg value="-v"/>
</exec>

However, I you need to call several commands on the command line, you get code duplication. Macrodef to the rescue.

<!-- macro for executing a command plattform independent -->
<macrodef name="execute">
       <attribute name="executable"/>
       <element name="args" implicit="yes"/>
       <sequential>
                <exec osfamily="windows" executable="cmd">
                       <arg value="/c"/>
                       <arg value="@{executable}"/>
                       <args/>
                </exec>
                <exec osfamily="unix" executable="@{executable}">
                       <args/>
               </exec>
      </sequential>
</macrodef>

<!-- usage -->
<execute executable="ruby">
    <arg value="-v"/>
</execute>

Simple Usage Information

Most tools provide usage information when called without parameter. As we want to write self-documenting code, you can use the ant -p or ant -projecthelp commands which print all targets which have the description attribute set on the console. We can let Ant call itself via command line as shown in the following listing:

<project name="test" default="usage">
     <target name="usage" description="usage information">
        <exec executable="cmd">
            <arg value="/c"/>
            <arg value="ant"/>
            <arg value="-p"/>
        </exec>
    </target>
</project>

It is important to set the default attribute of the project to usage to call the usage target when no targets are specified.

You can combine the pattern Executing Platform Independet with this to get the following ant script:

<project name="test" default="usage">
     <target name="usage" description="usage information">
        <execute executable="ant">
            <arg value="-p"/>
        </execute>
    </target>
</project>

More about printing usage information in Ant can be found here.

Collection of Links for Other Useful Ant Tipps

XSLT Tricks

Curly Brackets and Dollar Signs

When you want to generate the expression ${property.key} with XSLT and you simply write this in the template, XSLT will interpret the curly brackets as an XPath Expression and will print out the value it calculates. It will fail silently and the output just shows $ having evaluated {property.key} to an empty string.

The trick is to use double curly brackets as shown in the listing below. It will evaluate the expression in the first curley brackets pair which is an curly brackets expression getting returned as a string.

<!-- evaluates to $ -->
<xsl:template match="...">
${property.key}
</xsl:template>

<!-- evaluates to ${property.key} -->
<xsl:template match="...">
${{property.key}}
</xsl:template>

Adding types to variables

You can add types to variables in your stylesheet. This allows for better error messages as these types are checked during execution.

<!-- variable with dynamic type -->
<xsl:template match="...">
     <xsl:variable name="var1" select="..." />
</xsl:template>

<!-- variable with static type string -->

<xsl:template match="...">
     <xsl:variable name="var1" select="..." as="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" />
</xsl:template>

More information and other cool tricks for making XSLT2 safer can be found at http://www.ibm.com/developerworks/library/x-safexslt/

Converting VSD Drawings to PNGs – VBScript

This VBScript contains the logic to convert each drawing (page) of a specific Microsoft Visio file to a png named after its source page name and saves it to a target directory.

Option Explicit

' constants required for opening files in Visio
Const visOpenRO = 2
Const visOpenMinimized = 16
Const visOpenHidden = 64
Const visOpenMacrosDisabled = 128
Const visOpenNoWorkspace = 256

' constants required for setting ExportSize in Visio
Const visRasterFitToCustomSize = 3
Const visRasterPixel = 0


Sub export(filePath, exportDirectory, widthInPixels, heightInPixels)

    ' open file
    Dim visioApplication : Set visioApplication = CreateObject("Visio.Application")

    ' set export size
    visioApplication.Settings.SetRasterExportSize visRasterFitToCustomSize, widthInPixels, heightInPixels, visRasterPixel

    ' open document in Visio without showing it to the user
    visioApplication.Documents.OpenEx filePath, visOpenRO + visOpenMinimized + visOpenHidden + visOpenMacrosDisabled + visOpenNoWorkspace

    ' iterate over all pages and export each one
    Dim currentItemIndex
    For currentItemIndex = 1 To visioApplication.ActiveDocument.Pages.Count

        Dim currentItem : Set currentItem = visioApplication.ActiveDocument.Pages.Item(currentItemIndex)

        ' use the lowercase name for the file
        Dim exportPath : exportPath = exportDirectory & "\" & LCase(currentItem.Name) & ".png"

        ' export happens here!
    	currentItem.Export exportPath
    Next

    ' Quit Visio
    visioApplication.Quit
End Sub

' current directory
Dim currentDirectory : currentDirectory = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")

' file to open
Dim filePath : filePath = currentDirectory & "\AI - stundenplan.vsd"

' set export directory
Dim exportDirectory : exportDirectory = currentDirectory

export filePath, exportDirectory, 3557, 4114

Annotations about VBScript in general to better understand what is going on in this script.

  • The colon (:) is the statement separator. This can be used to declare and assign a variable in one line.
  • Use Dim NAME : NAME = VALUE for variables referencing not objects
  • Use Set NAME = OBJECT for variables referencing objects
  • Line Comments are started with '
  • No parantheses are allowed for calling Subs (procedures) or Functions
  • Stating Option Explicit at the first line requires each variable to be declared before it can be used
  • To determine what parameters to set, you can use the record macro function in Visio. This button is not directly available in Visio 2010, refer to this guide on how to make it visible.
  • The object explorer of Visio 2010 is very helpful to find the correct functions or procedures.
  • Use the ampersand (&) to concatenate strings

Find the most used first word (and every word) in your git commit messages

Via Twitter, I found this interesting gist (https://gist.github.com/2140115) which contains a one-line bash command for “Find[ing] the most used verbs in your git commit messages” in a git repo.

$ git log --pretty=format:'%s' | cut -d " " -f 1 | sort | uniq -c | sort -nr
      2 Added
      1 Improved

In the following, I have extracted the neccessary information from the help/man pages to understand, how this is achieved. I also preserved the intermediate states which are printed after a command is explained.

git log # "Show commit logs"(git log --help)
git log --pretty=format:'%s' # print each commit log as a line containing solely its subject

$ git log --pretty=format:'%s'
Improved README
Added CHANGELOG
Added README

cut # "print selected parts of lines from each FILE to standard output."(cut --help)
cut -d, --delimiter=DELIM # "use DELIM instead of TAB for field delimiter"(cut --help)
cut -f, --fields=LIST # "output only these fields"(cut --help)
cut -d " " -f 1 # split line by " " and output only the first field

$ git log --pretty=format:'%s' | cut -d " " -f 1
Improved
Added
Added

sort # "Write sorted concatenation of all FILE(s) to standard output."(sort --help)

$ git log --pretty=format:'%s' | cut -d " " -f 1 | sort
Added
Added
Improved

uniq # "Discard all but one of successive identical lines from INPUT (or standard input), wirting to OUTPUT (or standard output)"(uniq --help)
uniq -c, --count # "prefix lines by the number of occurrences"(uniq --help)

$ git log --pretty=format:'%s' | cut -d " " -f 1 | sort | uniq -c
      2 Added
      1 Improved

sort # "Write sorted concatenation of all FILE(s) to standard output."(sort --help)
sort -r # "reverse the result of comparisons"(sort --help)
sort -n # "compare according to string numerical value, imply -b"(sort --help)
sort -b # "ignore leading blanks in sort fields or keys"(sort --help)

$ git log --pretty=format:'%s' | cut -d " " -f 1 | sort | uniq -c | sort -nr
      2 Added
      1 Improved

If you want all the words (and not only the first words of each commit), the cut command does not suffice. In that case, sed, a “stream editor for filtering and transforming text”(sed man page) can be leveraged. It is shown in the following.

$ git log --pretty=format:'%s'
Improved README
Added CHANGELOG
Added README

sed # "stream editor for filtering and transforming text"(sed man page)
sed s/regexp/replacement/ # "Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement."(sed --help)
\s # whitespace character
\n # new line
sed 's/\s/\n/g' # replace all whitespace characters by new lines

$ git log --pretty=format:'%s' | sed 's/\s/\n/g'
Improved
README
Added
CHANGELOG
Added
README

$ git log --pretty=format:'%s' | sed 's/\s/\n/g' | sort
Added
Added
CHANGELOG
Improved
README
README

$ git log --pretty=format:'%s' | sed 's/\s/\n/g' | sort | uniq -c
      2 Added
      1 CHANGELOG
      1 Improved
      2 README

$ git log --pretty=format:'%s' | sed 's/\s/\n/g' | sort | uniq -c | sort -nr
      2 README
      2 Added
      1 Improved
      1 CHANGELOG

But beware, as this can be too much for your command line buffer to handle. This can be solved by piping the result to less.

$ git log --pretty=format:'%s' | sed 's/\s/\n/g' | sort | uniq -c | sort -nr | less
      2 README
      2 Added
      1 Improved
      1 CHANGELOG

It can still be improved, e.g., to convert all upper case letters to lower case ones. This is possible using tr '[:upper:]' '[:lower:]' which uses the tr tool that is able to “translate, squeeze, and/or delete characters from standard input, writing to standard output”(tr --help). In that case it translates every upper case letter to a lower case one while copying the other characters.

The Java Initializers

In Java, the concepts of classes and instances are the core concepts. A class as well as each instance has variables and methods. To differentiate, the variables and methods corresponding to the class have to be marked static while variables and methods default to the instance (if not marked static). In the following, I focus only on the variables.

The following example shows the declaration for class and instance variables:

public class Variables {
  static String classVariable; // initialized with default value null

  String instanceVariable; // initialized with default value null
}

Class Variables

Class variables are interpreted in the order they appear in the file. I can directly assign values to a class variable (direct initialization) or call a static method which initialises the variable through its return value. This, however, can lead to problems as shown in the next listing:

public class Variables {
  static String directlyInitialized = "class variable";
  static String directlyInitializedWithMethod = init();
  static String anotherDirectlyInitialized = "test";

  private static String init() {
    return anotherDirectlyInitialized;
  }

  public static void main(String[] args) {
    System.out.println(directlyInitializedWithMethod); // prints null
  }
}

This will print out null as the variable anotherDirectlyInitialized is initialized after the directlyInitializedWithMethod is initialized. The compiler does not detect it, it is the responsibility of the programmer to avoid such situations. We could solve this issue by reordering the statements, however, this is an area where we can do errors easily.

There is another alternative, namely, class initializers. These initializers are executed after all static variables have been initialized.

public class Variables {
  static String directlyInitialized = "class variable";
  static String directlyInitializedWithMethod;
  static String anotherDirectlyInitialized = "test";

  static {
    directlyInitializedWithMethod = anotherDirectlyInitialized;
  }

  public static void main(String[] args) {
    System.out.println(directlyInitializedWithMethod); // prints test
  }
}

This static block can contain any complex setup logic. It is executed after all static variables are initialised but before any method call to the class is issued. Good use cases are the computation of constants or preinitialization of other instances which require more than a simple constructor or method call.

Instance Variables

The approach of initializing static variables is also applied to instance variables. I can directly assign values to an instance variable (direct initialization) or call a method which initialises the variable through its return value. This, however, can lead to the same initialization problems.

public class Variables {
  String directlyInitialized = "class variable";
  String directlyInitializedWithMethod = init();
  String anotherDirectlyInitialized = "test";

  private String init() {
    return anotherDirectlyInitialized;
  }

  public static void main(String[] args) {
    InstanceVariables object = new InstanceVariables();
    System.out.println(object.directlyInitializedWithMethod); // prints null
  }
}

However, there is also an initializer construct for instance variables. This construct is called before any constructor is called and allows to initialize instance variables regardless of their ordering.

public class Variables {
  String directlyInitialized = "class variable";
  String directlyInitializedWithMethod;
  String anotherDirectlyInitialized = "test";

  {
    directlyInitializedWithMethod = anotherDirectlyInitialized;
  }

  public static void main(String[] args) {
    InstanceVariables object = new InstanceVariables();
    System.out.println(object.directlyInitializedWithMethod); // prints test
  }
}

Another real use case of these instance initializers is to add values to a HashMap on creation as seen in the next code snippet:

// regular approach
Map<String, String> myMap = new HashMap<>();
myMap.put("DE", "German");
myMap.put("EN", "English");
		
		
Map<String, String> otherMap = new HashMap<String, String>() {
	// anonymous subclass of HashMap

	{
		// instance initializer setting specific values
		this.put("DE", "German");
		this.put("EN", "English");
	}

};

The advantage is, that the latter can be used to initialize a field in a class directly with specific values.

BPEL Engines …

If you want to work with a BPEL engine, you always have some trouble. Always!

For my diploma thesis, I used the OpenESB engine 2.2 which was originally developed by Sun. I had made good experience working with this engine during other courses at university. The installation is very simple as there is a single installer which installs and configures NetBeans, Glassfish and the OpenESB engine in one step. Everything can be controlled from within NetBeans (starting and stopping of Glassfish, (un)deployment of BPEL processes, debugging!). Additionally, NetBeans provides extensive validations to ensure that the BPEL process is correct.

After Sun’s acquisition by Oracle, the engine has not been maintained anymore. Many pages of its documentation are broken and it is very very hard to find a download link in this mess. A few people are trying to keep it alive under http://openesb-dev.org/. They released a new version (2.3) at https://openesb-dev.org/file/showfiles.php?group_id=102. This version is from February 2011 and has only been declared a milestone instead of a stable release. I do not have much hope that this project will be relevant for praxis in the future.

For a paper of mine, I wanted to use the OpenESB engine 2.2. I had required a specific construct which is valid according to the BPEL standard. The engine, however, only threw NullPointerExceptions when it executed the problematic part of the process. Therefore, I had to look for alternatives.

Next, I evaluated the Apache ODE 1.3.5, however, I could not get it working. I had so many NullPointerExceptions in the log files … it was simply ridiculous.

Consequently, I said to myself, lets just use industry proven product which have to be great. This is how I began looking at the BPEL engine from Oracle which is shipped with their Oracle SOA Suite 11g product. Its installation is quite cumbersome and takes half a day to complete. When it is installed, the start of the server takes more than 5 minutes. It is hard to handle as everything feels very slow, but, I got it working! Thus, I used it for my paper and it worked out well.

As this product is very heavy-weight, I was still looking for a more light-weight alternative running only in a simple servlet container for other research projects.

This week, my collegue Jörg Lenhard pointed me to the bpel-g engine. This engine is based on the open sourced code of the ActiveBPEL engine and looks really promising according to their own comparison with other open source BPEL engines. It starts within ca. 20 seconds on a simple servlet container like tomcat. Here is a small guide on how to get this engine running as the project site does not contain one:

  1. Download Tomcat 7.0.26, unpack it and start it using startup.bat/startup.sh
  2. Download bpel-g-web-5.2.war and copy it into $TOMCAT_HOME/webapps
  3. Download h2-1.2.122.jar and copy it into $TOMCAT_HOME/webapps/bpel-g-web-5.2/WEB-INF/lib
  4. Restart tomcat and point your browser to localhost:8080/bpel-g-web-5.2

Note: You have to use the version 1.2.122 of the in-memory database h2 as newer versions do not work!

Maybe this engine suffices for my work? I will investigate!

PS: It is a pity that bpel-g is hosted using SVN instead of git …

Line Separators

Line separators are a funny problem in itself. Each operating system uses different kind of escape sequences to determine a new line.

  • Windows: \r\n
  • Unix/Linux/Mac OS X: \n
  • pre-OSX Mac: \r

Orignially, the write head of typewriters could only do few tasks. I listed the most important ones below:

  • Write symbol and move the cursor one column to the right.
  • \r | carriage return | CR | Move cursor to the first column of the line.
  • \n | line feed         | LF | Move cursor to the next row/line at the same column.
  • \b | backspace     | BS | Move cursor one column back.
  • \t | horizontal tab  | HT | Move cursor to the next tab-stop.
In order to get the cursor to the beginning of the new line, you needed to use a carriage return followed by a line feed. This behaviour resulted in the \r\n escape sequence of windows. Others simplified it by selecting either \n or \r.

In Java, which is plattform independent, you get the plattform dependent escape sequence by obtaining the system property named line.separator.

String lineSeparator = System.getProperty("line.separator");

Other plattform specific system properties as the path.separator (backslash or slash) can be found at this guide.

Objects – A Not Very Well Known Utility Class In Java

The Java API has some quite useful classes which are not well known. One of them is the Objects class with several static helper methods. Most of them help dealing with null values (which is quite a pain if you have to do it by yourself). The Objects class is available since Java 7.

I really like the requireNonNull methods as you often have to write code that checks for null values. As it can be seen in the code snippet below, the static method requireNonNull is available in two versions. I prefer the one with the additional message as a NullPointerException is not very expressive in itself.

public void solve(String problem) {
    // throws NullPointerException if problem is null
    Objects.requireNonNull(problem);

    // throws NullPointerException with passed text if problem is null
    Objects.requireNonNull(problem,"problem is null");

    // solve problem
}

Null can also be problematic if you want to create a String as it is automatically transformed to an empty String. This is not always desired as null and an empty String cannot be differentiated anymore. The Objects class provides the toString method, which is also available in two versions as it can be seen in the code listing below.

public void printProblem(String problem) {
     // converts null to "null", otherwise calls toString()
     String output = Objects.toString(problem);

     // converts null to "no problem given", otherwise calls toString()
     String anotherOutput = Objects.toString(problem,"no problem given");

     // print problem
}

There are also two methods regarding the generation of hashcodes. Using the Objects.hashcode(Object o) method, the hashcode method of the Object o is called. In case of a null reference, 0 is returned. For computing the hash value for several objects, you can resort to Objects.hash(Object… values) which delegates the hash generation to the Arrays.hashCode method. These methods are not that useful to me as almost always I use an IDE to generate the hashCode method of an Object using its fields for me.

Additionally, the methods named equals and deepEquals help to compare objects for equality taking the null value explicitly into account while compare itself uses a Comparator. I can not see any immediate use for me regarding these methods either, but perhaps an occasion for them may arise.

I recommend that you read through the source code of the Objects.class. It is quite simple and easy to understand. You could write a class with the same functionality by yourself, however, you get this behaviour fully tested and already implemented for free! So use it!