Unfortunately this will fail when HEAD is detached.  When HEAD is detached this method returns the 40 digit hex SHA-1.  C Git in the same case puts "detached HEAD" into the head-name file.

It can also return null.  Which will NPE later on when you fill the head-name file.

I think the only safe thing to do is:

  Ref head = repo.getRef(Constants.HEAD);
  if (head == null || head.getObjectId() == null)
    throw new RefNotFoundException(...);

  String headName;
  if (head.isSymbolic())
    headName = head.getTarget().getName();
  else
    headName = "detached HEAD";

  ObjectId headId = head.getObjectId();

Its perhaps longer, but it gives you direct access to the various states that are involved.