code: public static Node getClosestExistingAncestor(final Session session, final String path)
              throws RepositoryException {
  
          String potentialPath = path.startsWith("/") ? path : "/" + path;
          while (!potentialPath.isEmpty()) {
              if (session.nodeExists(potentialPath)) {
                  return session.getNode(potentialPath);
              }
              potentialPath = potentialPath.substring(0, potentialPath.lastIndexOf('/'));
          }
          return session.getRootNode();
      }
docs: Get the closest ancestor that current exists
  
  @param session the given session
  @param path the given path
  @return the closest ancestor that current exists
  @throws RepositoryException if repository exception occurred