Make envsetup.sh set JAVA_HOME correctly for java7.

Note that despite the location of this change, this function
is run only during "lunch" and not during ". build/envsetup.sh"

Also, make it easier to switch back and forth between java6 and 7
on the same session.

bug: 8992787

Change-Id: I56ec0ba8552b46c04204a8b96b9abc0180f7605f
diff --git a/envsetup.sh b/envsetup.sh
index 289fdb2..5cefc83 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -1322,9 +1322,23 @@
     \cd $T/$pathname
 }
 
-# Force JAVA_HOME to point to java 1.6 if it isn't already set
+# Force JAVA_HOME to point to java 1.7 or java 1.6  if it isn't already set.
+#
+# Note that the MacOS path for java 1.7 includes a minor revision number (sigh).
+# For some reason, installing the JDK doesn't make it show up in the
+# JavaVM.framework/Versions/1.7/ folder.
 function set_java_home() {
+    # Clear the existing JAVA_HOME value if we set it ourselves, so that
+    # we can reset it later, depending on the value of EXPERIMENTAL_USE_JAVA7.
+    #
+    # If we don't do this, the JAVA_HOME value set by the first call to
+    # build/envsetup.sh will persist forever.
+    if [ -n "$ANDROID_SET_JAVA_HOME" ]; then
+      export JAVA_HOME=""
+    fi
+
     if [ ! "$JAVA_HOME" ]; then
+      if [ ! "$EXPERIMENTAL_USE_JAVA7" ]; then
         case `uname -s` in
             Darwin)
                 export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
@@ -1333,6 +1347,20 @@
                 export JAVA_HOME=/usr/lib/jvm/java-6-sun
                 ;;
         esac
+      else
+        case `uname -s` in
+            Darwin)
+                export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home
+                ;;
+            *)
+                export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
+                ;;
+        esac
+      fi
+
+      # Keep track of the fact that we set JAVA_HOME ourselves, so that
+      # we can change it on the next envsetup.sh, if required.
+      export ANDROID_SET_JAVA_HOME=true
     fi
 }