
  # -------------------------------------------------------------------------------------------------------------------------  #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #           File Name              :  java functions.r                                                                       #
  #           Last Updated Funclist  :  08 Feb 2015,  5:12 AM (Sunday)                                                         #
  #                                                                                                                            #
  #           Author Name            :  Rick Saporta                                                                           #
  #           Author Email           :  RickSaporta@gmail.com                                                                  #
  #           Author URL             :  www.github.com/rsaporta                                                                #
  #                                                                                                                            #
  #           Packages Called        :  rJava                                                                                  #
  #           Packages Used via NS   :  NA                                                                                     #
  #                                                                                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #   jgc                    (  )                                                                                              #
  #   getJavaMemoryParameter (  )                                                                                              #
  #   setJavaMemoryParameter ( initial=128, max=2048, units=c("m", "g", "k"), stops.of.power.for.rounding=1                    #
  #                            , java.handles.signals=TRUE, reset=FALSE, java.pkg.name="rJava", reload.packages=TRUE           #
  #                            , verbose=TRUE, showWarnings=verbose )                                                          #
  #   JavaTest               ( stopRun=TRUE, runInit=TRUE )                                                                    #
  #                                                                                                                            #
  #                                                                                                                            #
  #                                                     <END FUNCS>                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  # -------------------------------------------------------------------------------------------------------------------------  #

jgc <- function() {
  rJava::.jcall("java/lang/System", method = "gc")
}

#
#  http://stackoverflow.com/questions/15826202/where-is-java-7-installed-on-mac-os-x
# 
# function(java_home = "/usr/libexec/java_home", v=NULL) {
#   if (!file.exists(java_home))
#     stop ("cannot find java_home = '", java_home, "'")
# 
#   if (!is.null(v))
#     java_home <- sprintf("%s -v %f", java_home, v)
# 
#   jdir <- system(java_home, intern=TRUE)
#   dir(jdir)
# }



getJavaMemoryParameter <- function(){
  getOption("java.parameters")
}


setJavaMemoryParameter <- function(initial=128, max=2048, units=c("m", "g", "k"), stops.of.power.for.rounding=1, java.handles.signals=TRUE ,reset=FALSE, java.pkg.name="rJava", reload.packages=TRUE, verbose=TRUE, showWarnings=verbose) {
## ## http://stackoverflow.com/a/14763095/1492421
## The flag Xmx specifies maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool.
## That means your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory.

  if (!length(initial) && !length(max)) 
    stop("At least one of 'initial' or 'max' must have a length of 1")

  if (!is.numeric(initial) || !is.numeric(max))
    stop("Parameters 'initial' and 'max' must be numeric\nHINT:  Use eg  units=\"m\"  to set the units")

  units <- match.arg(units)

  verboseMsg(verbose, "SETTING JAVA PARAMETERS", time=FALSE)

  if (isTRUE(reset)) {
    initial <- 32
    max <- 128
    units <- m
    java.handles.signals <- TRUE
    verboseMsg(verbose, "Reseting  java.parameters", time=FALSE)
  }

  max <- roundToPower(max, 2, stops=stops.of.power.for.rounding)
  initial <- roundToPower(initial, 2, stops=stops.of.power.for.rounding)

  initparam <- if (length(initial)) sprintf(" -Xmx%s%s", initial, units)
  maxparam <- if (length(max)) sprintf(" -Xmx%s%s", max, units)
  params <- paste(initparam, maxparam)
  message("params are :", params, "\n")

  if (isTRUE(java.handles.signals))
    params <- paste(params, "-Xrs")

  verboseMsg(verbose, "Previous params was:  '", getOption("java.parameters"), "'", sep="", time=FALSE)

  ret <- options(java.parameters=params)

  if (reload.packages)  {
    ## Find all depenendent packages
    pkgs <- findDependentPakcages(java.pkg.name, self.include=TRUE)

    if (!length(pkgs))
      verboseMsg(verbose, "There are no Java packages currently loaded.")

    ## Unload all the packages
    for (pkg in pkgs) {
      verboseMsg(verbose, "Attempting to remove package ", pkg, time=FALSE)
      try(detach(paste0("package:", pkg), force=TRUE, character.only=TRUE, unload=TRUE), silent=FALSE)
    }

    if (length(pkgs))
      verboseMsg(verbose, "\nReloading packages:", pasteQ(pkgs, wrap=FALSE), "\n", time=FALSE)

    ## Reload all the packages
    for (pkg in rev(pkgs))
      try(suppressPackageStartupMessages(require(pkg, character.only=TRUE)), silent=FALSE)
  }
  
  return(params)
}


JavaTest <- function(stopRun=TRUE, runInit=TRUE) {
  ## ensures that rJava is up and running.  If Java is NOT running and...
  ##    stopRun=T, will throw an error. If stop=False, will throw a warning.
  ## If runInit=T, will load rJava and run .jinit() prior to running .jcheck()

  # Load rJava and initialize java
  if (runInit) {
    library(rJava)
    .jinit()
  }

  # Run .jCheck
  errString <- ".jcheck() failed.  Please troubleshoot rJava"
  if (isErr(.jcheck())) {
    if (stopRun) {
      stop(errString)
    }
    else  {
      warning(errString)
    }
  }
}
