Optionally support building and running with locally installed JDK

Change-Id: Ie08a4bf7952c0ed62dbc31dba0faa33eae9b133d
diff --git a/tools/build/bazel/jdk_genrule.bzl b/tools/build/bazel/jdk_genrule.bzl
index 14e5aa2..5d9bae5 100644
--- a/tools/build/bazel/jdk_genrule.bzl
+++ b/tools/build/bazel/jdk_genrule.bzl
@@ -29,7 +29,14 @@
         **kwargs):
     new_tools = tools + ["@bazel_tools//tools/jdk:current_java_runtime"]
     new_toolchains = toolchains + ["@bazel_tools//tools/jdk:current_java_runtime"]
-    new_cmd = "echo \"export PATH=$$PWD/$(JAVABASE)/bin:$$PATH:\" > jdk_genrule_setup.sh; " + \
+
+    # Add JAVABASE/bin to the PATH env.
+    # Prepend PWD (sandbox path) if JAVABASE is not an absolute path.
+    new_cmd = "echo 'if [[ \"$(JAVABASE)\" = /* ]]; then " + \
+              "JHOME=$(JAVABASE); " + \
+              "else JHOME=$$PWD/$(JAVABASE); " + \
+              "fi' > jdk_genrule_setup.sh; " + \
+              "echo 'export PATH=$$JHOME/bin:$$PATH:' >> jdk_genrule_setup.sh; " + \
               "source jdk_genrule_setup.sh; " + cmd
 
     native.genrule(
diff --git a/tools/build/jdk/BUILD b/tools/build/jdk/BUILD
index 84856ee..59934fc 100644
--- a/tools/build/jdk/BUILD
+++ b/tools/build/jdk/BUILD
@@ -28,16 +28,16 @@
 #  produced JDK tar.
 
 genrule(
-    name = "default_jdk_tar",
+    name = "current_jdk_tar",
     srcs = [
         "@bazel_tools//tools/jdk:current_java_runtime",
         ":conf-security",
     ],
-    outs = ["default_jdk.tar.gz"],
-    cmd = "mkdir default_jdk && " +
-          "mv $(JAVABASE)/* default_jdk/ && " +
-          "mv tools/build/jdk/* default_jdk/ && " +
-          "tar -hczf $(location default_jdk.tar.gz) default_jdk",
+    outs = ["current_jdk.tar.gz"],
+    cmd = "mkdir current_jdk && " +
+          "cp -r $(JAVABASE)/* current_jdk/ && " +
+          "cp -r tools/build/jdk/* current_jdk/ && " +
+          "tar -hczf $(location current_jdk.tar.gz) current_jdk",
     output_to_bindir = True,
     toolchains = ["@bazel_tools//tools/jdk:current_java_runtime"],
     visibility = ["//visibility:public"],
diff --git a/tools/package/onos-run-karaf b/tools/package/onos-run-karaf
index e898006..6fce6e8 100755
--- a/tools/package/onos-run-karaf
+++ b/tools/package/onos-run-karaf
@@ -5,6 +5,7 @@
 
 ONOS_TAR=
 JDK_TAR=
+ABSOLUTE_JAVABASE=
 
 [ -f $ONOS_TAR ] || (echo "$ONOS_TAR not found" && exit 1)
 
@@ -28,8 +29,11 @@
   *)        md5cmd='md5sum';;
 esac
 
-# Use provided JDK as JAVA_HOME if given
-if [[ -f ${JDK_TAR} ]]; then
+# Either use the given ABSOLUTE_JAVABASE as JAVA_HOME, or extract the passed
+# JDK_TAR and use that.
+if [[ -d ${ABSOLUTE_JAVABASE} ]]; then
+    export JAVA_HOME=${ABSOLUTE_JAVABASE}
+elif [[ -f ${JDK_TAR} ]]; then
     JDK_DIR=$ONOS_DIR-jdk
     JDK_MD5=$JDK_DIR/CHECKSUM