aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlistair Bush <ali_bush@gentoo.org>2007-10-13 11:31:49 +0000
committerAlistair Bush <ali_bush@gentoo.org>2007-10-13 11:31:49 +0000
commit69dc0af9c47ba68fbd2ca0241048a77c6035030c (patch)
tree6e480b373dee95f4538977760372fea1ea572f5d
parentUpdated Version. (diff)
parentUpdating version (diff)
downloadjava-config-69dc0af9c47ba68fbd2ca0241048a77c6035030c.tar.gz
java-config-69dc0af9c47ba68fbd2ca0241048a77c6035030c.tar.bz2
java-config-69dc0af9c47ba68fbd2ca0241048a77c6035030c.zip
Tagged 2.1.1
svn path=/projects/java-config-2/tags/2.1.1/; revision=5480
-rw-r--r--trunk/AUTHORS10
-rw-r--r--trunk/MANIFEST.in4
-rw-r--r--trunk/NEWS28
-rw-r--r--trunk/README3
-rw-r--r--trunk/TODO9
-rw-r--r--trunk/config/20java-config2
-rw-r--r--trunk/config/compilers.conf5
-rw-r--r--trunk/config/jdk-defaults-alpha.conf2
-rw-r--r--trunk/config/jdk-defaults-amd64.conf2
-rw-r--r--trunk/config/jdk-defaults-hppa.conf2
-rw-r--r--trunk/config/jdk-defaults-ia64.conf2
-rw-r--r--trunk/config/jdk-defaults-mips.conf2
-rw-r--r--trunk/config/jdk-defaults-ppc.conf2
-rw-r--r--trunk/config/jdk-defaults-ppc64.conf2
-rw-r--r--trunk/config/jdk-defaults-sparc.conf2
-rw-r--r--trunk/config/jdk-defaults-x86-fbsd.conf2
-rw-r--r--trunk/config/jdk-defaults-x86.conf2
-rw-r--r--trunk/config/jdk.conf12
-rw-r--r--trunk/config/symlink-tools16
-rw-r--r--trunk/config/virtuals5
-rwxr-xr-xtrunk/make-release13
-rw-r--r--trunk/man/java-config-2.1129
-rw-r--r--trunk/setup.cfg17
-rw-r--r--trunk/setup.py61
-rwxr-xr-xtrunk/src/depend-java-query84
-rw-r--r--trunk/src/eselect/README1
-rw-r--r--trunk/src/eselect/java-nsplugin.eselect208
-rw-r--r--trunk/src/eselect/java-vm.eselect145
-rwxr-xr-xtrunk/src/gjl211
-rwxr-xr-xtrunk/src/java-config-2349
-rw-r--r--trunk/src/java_config_2/EnvironmentManager.py449
-rw-r--r--trunk/src/java_config_2/Errors.py53
-rw-r--r--trunk/src/java_config_2/FileParser.py84
-rw-r--r--trunk/src/java_config_2/OutputFormatter.py124
-rw-r--r--trunk/src/java_config_2/Package.py88
-rw-r--r--trunk/src/java_config_2/VM.py98
-rw-r--r--trunk/src/java_config_2/VersionManager.py274
-rw-r--r--trunk/src/java_config_2/Virtual.py220
-rw-r--r--trunk/src/java_config_2/__init__.py5
-rw-r--r--trunk/src/launcher.bash75
-rw-r--r--trunk/src/profile.d/java-config-2.csh22
-rw-r--r--trunk/src/profile.d/java-config-2.sh34
-rw-r--r--trunk/src/revdep-rebuild/60-java9
-rw-r--r--trunk/src/run-java-tool46
44 files changed, 2913 insertions, 0 deletions
diff --git a/trunk/AUTHORS b/trunk/AUTHORS
new file mode 100644
index 0000000..3f649d2
--- /dev/null
+++ b/trunk/AUTHORS
@@ -0,0 +1,10 @@
+aether: Jason A Mobarak <aether@gentoo.org>
+ali_bush: Alistair Bush <ali_bush@gentoo.org>
+axxo: Thomas Matthijs <axxo@gentoo.org>
+betelgeuse: Petteri Räty <betelgeuse@gentoo.org>
+caster: Vlastimil Babka <caster@gentoo.org>
+compnerd: Saleem Abdulrasool <compnerd@gentoo.org>
+nichoj: Joshua Nichols <nichoj@gentoo.org>
+karltk: Karl Trygve Kalleberg <karltk@gentoo.org>
+
+Mail java@gentoo.org if you are missing
diff --git a/trunk/MANIFEST.in b/trunk/MANIFEST.in
new file mode 100644
index 0000000..18e8dcc
--- /dev/null
+++ b/trunk/MANIFEST.in
@@ -0,0 +1,4 @@
+recursive-include man/ *
+recursive-include config/ *
+recursive-include src *
+include ChangeLog NEWS TODO
diff --git a/trunk/NEWS b/trunk/NEWS
new file mode 100644
index 0000000..650c803
--- /dev/null
+++ b/trunk/NEWS
@@ -0,0 +1,28 @@
+For full ChangeLog generated from svn commit logs see ChangeLog.
+
+Changes in 2.0.33:
+ * ENV_VARS support for package.env so that for example swt can
+ export MOZILLA_FIVE_HOME to using packages
+ * Make java-config not dependent on the files in the Portage tree
+ by importing them to our svn and installing them using distutils
+ * Make gjl add JAVA_LIBRARY_PATH and LD_LIBRARY_PATH variables to
+ java.library.path property
+ * Make profile.d scripts export MANPATH so that man java works when
+ running a system without generation 1
+
+Changes in 2.0.32:
+ * Fixed jrockit-jdk-bin in jdk-defaults-ia64.conf
+ * Prefer sun-jdk over blackdown-jdk in amd64 and x86 defaults
+ * Add keytool to wrappers
+ * improve gjl error handling when deps are not installed
+ * include this file in the release
+
+Changes in 2.0.31:
+ * Added support for conditional DEPEND atoms
+ http://bugs.gentoo.org/show_bug.cgi?id=156228
+ * java-config now always respects --nocolor
+ http://bugs.gentoo.org/show_bug.cgi?id=154493
+ * gjl can now be run with only a jar if the jar
+ does not have dependencies
+ * prefer sun-jdk over ibm-jdk-bin on x86 and amd64
+ * Added jdk-defaults-x86-fbsd.conf
diff --git a/trunk/README b/trunk/README
new file mode 100644
index 0000000..08ea0c7
--- /dev/null
+++ b/trunk/README
@@ -0,0 +1,3 @@
+Maintainer: Gentoo Java Team <java@gentoo.org>
+Java Configuration Utility for Gentoo
+
diff --git a/trunk/TODO b/trunk/TODO
new file mode 100644
index 0000000..997067d
--- /dev/null
+++ b/trunk/TODO
@@ -0,0 +1,9 @@
+1) EnvFileParser chokes on multiline vars
+For 2.1:
+ - handling virtuals
+ http://overlays.gentoo.org/proj/java/wiki/Virtuals
+
+For 3.0:
+ - Make EnvironmentManager's get_packages function return
+ a list packages instead of a dictionary. For lookup by name
+ we already have the get_package function.
diff --git a/trunk/config/20java-config b/trunk/config/20java-config
new file mode 100644
index 0000000..d435733
--- /dev/null
+++ b/trunk/config/20java-config
@@ -0,0 +1,2 @@
+MANPATH=/etc/java-config/system-vm/man/
+CONFIG_PROTECT_MASK="/etc/env.d/java/"
diff --git a/trunk/config/compilers.conf b/trunk/config/compilers.conf
new file mode 100644
index 0000000..2a615cf
--- /dev/null
+++ b/trunk/config/compilers.conf
@@ -0,0 +1,5 @@
+# If the ebuild supports it
+# it will check the COMPILERS var front to back and
+# use the fist compiler that is installed
+
+#COMPILERS="ecj-3.1 jikes javac"
diff --git a/trunk/config/jdk-defaults-alpha.conf b/trunk/config/jdk-defaults-alpha.conf
new file mode 100644
index 0000000..fe21913
--- /dev/null
+++ b/trunk/config/jdk-defaults-alpha.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= compaq-jdk
diff --git a/trunk/config/jdk-defaults-amd64.conf b/trunk/config/jdk-defaults-amd64.conf
new file mode 100644
index 0000000..792b5cc
--- /dev/null
+++ b/trunk/config/jdk-defaults-amd64.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= sun-jdk blackdown-jdk ibm-jdk-bin jrockit-jdk-bin
diff --git a/trunk/config/jdk-defaults-hppa.conf b/trunk/config/jdk-defaults-hppa.conf
new file mode 100644
index 0000000..4480996
--- /dev/null
+++ b/trunk/config/jdk-defaults-hppa.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= kaffe
diff --git a/trunk/config/jdk-defaults-ia64.conf b/trunk/config/jdk-defaults-ia64.conf
new file mode 100644
index 0000000..89c48a7
--- /dev/null
+++ b/trunk/config/jdk-defaults-ia64.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= jrockit-jdk-bin
diff --git a/trunk/config/jdk-defaults-mips.conf b/trunk/config/jdk-defaults-mips.conf
new file mode 100644
index 0000000..c649d0e
--- /dev/null
+++ b/trunk/config/jdk-defaults-mips.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= blackdown-jdk
diff --git a/trunk/config/jdk-defaults-ppc.conf b/trunk/config/jdk-defaults-ppc.conf
new file mode 100644
index 0000000..31a46e3
--- /dev/null
+++ b/trunk/config/jdk-defaults-ppc.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= ibm-jdk-bin
diff --git a/trunk/config/jdk-defaults-ppc64.conf b/trunk/config/jdk-defaults-ppc64.conf
new file mode 100644
index 0000000..31a46e3
--- /dev/null
+++ b/trunk/config/jdk-defaults-ppc64.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= ibm-jdk-bin
diff --git a/trunk/config/jdk-defaults-sparc.conf b/trunk/config/jdk-defaults-sparc.conf
new file mode 100644
index 0000000..c649d0e
--- /dev/null
+++ b/trunk/config/jdk-defaults-sparc.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= blackdown-jdk
diff --git a/trunk/config/jdk-defaults-x86-fbsd.conf b/trunk/config/jdk-defaults-x86-fbsd.conf
new file mode 100644
index 0000000..2af5546
--- /dev/null
+++ b/trunk/config/jdk-defaults-x86-fbsd.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= diablo-jdk
diff --git a/trunk/config/jdk-defaults-x86.conf b/trunk/config/jdk-defaults-x86.conf
new file mode 100644
index 0000000..792b5cc
--- /dev/null
+++ b/trunk/config/jdk-defaults-x86.conf
@@ -0,0 +1,2 @@
+# This files contain the default support jdk's
+*= sun-jdk blackdown-jdk ibm-jdk-bin jrockit-jdk-bin
diff --git a/trunk/config/jdk.conf b/trunk/config/jdk.conf
new file mode 100644
index 0000000..0c42763
--- /dev/null
+++ b/trunk/config/jdk.conf
@@ -0,0 +1,12 @@
+# User jdk configuration file
+# You can specify which jdk you prefer to use
+# see http://www.gentoo.org/doc/en/java.xml#doc_chap4_sect3 for more info
+#
+# example:
+
+#1.3=sun-jdk-1.4 ibm-jdk-bin
+#1.4=blackdown-jdk
+#1.5=sun-jdk
+
+#or if you want everything with sun-jdk
+#*=sun-jdk
diff --git a/trunk/config/symlink-tools b/trunk/config/symlink-tools
new file mode 100644
index 0000000..e0163e8
--- /dev/null
+++ b/trunk/config/symlink-tools
@@ -0,0 +1,16 @@
+appletviewer
+apt
+jar
+jarsigner
+java
+javac
+javadoc
+javah
+javap
+javaws
+jconsole
+jdb
+keytool
+rmic
+rmid
+rmiregistry
diff --git a/trunk/config/virtuals b/trunk/config/virtuals
new file mode 100644
index 0000000..7aafd0b
--- /dev/null
+++ b/trunk/config/virtuals
@@ -0,0 +1,5 @@
+# Example:
+#
+#javamail=gnu-javamail-1
+#javamail=sun-javamail-bin
+#jaf=sun-jaf-bin
diff --git a/trunk/make-release b/trunk/make-release
new file mode 100755
index 0000000..b16e745
--- /dev/null
+++ b/trunk/make-release
@@ -0,0 +1,13 @@
+#!/bin/bash
+version=${1}
+if [[ -z ${version} ]]; then
+ echo "I want a version"
+ exit 1
+fi
+svn up
+svn2cl --authors=AUTHORS
+sed -i "s/version =.*/version = \'${version}\',/" setup.py
+sed -i "s/__version__ =.*/__version__ = \'${version}\'/" src/java_config/__init__.py
+python setup.py sdist --force-manifest --formats=bztar
+
+cp -v dist/java-config-${version}.tar.bz2 $(portageq envvar DISTDIR)
diff --git a/trunk/man/java-config-2.1 b/trunk/man/java-config-2.1
new file mode 100644
index 0000000..691c858
--- /dev/null
+++ b/trunk/man/java-config-2.1
@@ -0,0 +1,129 @@
+.TH "JAVA-CONFIG" "1" "June 2005" "java-config 2.0.0" "User Commands"
+.SH "NAME"
+java\-config \- The Java configuration tool for Gentoo
+.SH "SYNOPSIS"
+.B java\-config
+\fI[options]\fB
+.SH "DESCRIPTION"
+.PP
+.I java\-config
+Is used to query/set properties of your system's Java environment. It can be
+used to list available VMs, java packages, set system default JVM and set user
+default JVM.
+.PP
+In addition, it is used by Portage as a common interface to querying
+properties about the various JVMs.
+.SH "OPTIONS "
+.TP
+\fB\-c \-\-javac\fI
+Show full path to currently selected Java compiler.
+.TP
+\fB\-j \-\-jar\fI
+Show full path to currently selected
+.I jar
+command.
+.TP
+\fB\-O \-\-jdk\-home\fI
+Show path to currently selected JDK.
+.TP
+\fB\-o \-\-jre\-home\fI
+Show path to currently selected JRE.
+.TP
+\fB\-v \-\-java\-version\fI
+Query current JVM for version.
+.TP
+\fB\-p [pkg1[\-SLOT],pkg2[\-SLOT],...] \-\-classpath[=package1,package2,...]\fI
+Calculate classpath for a package. If a package is installed in different
+slots you can also specify the slot to get the specific classpath informations.
+.TP
+\fB\-e filename \-\-exec=filename\fI
+Figure full path to one of the JDK/JRE utilities, such as
+.I keytool
+,
+.I rmic
+and others.
+.
+.TP
+\fB\-i PACKAGE(S), \-\-library=PACKAGE(S)\fI
+Print java library paths for these packages. Used for example in wrapper
+scripts like this: -Djava.library.path=$(java-config -i swt-3). Follows the same
+pkg[\-SLOT] convention as for example \-\-classpath.
+.
+.TP
+\fB\-l \-\-list\-available\-packages\fI
+List available Java packages. Used for selection by
+.I \-\-classpath
+,
+.I \-\-set\-system\-classpath
+and
+.I \-\-set\-user\-classpath
+.
+.TP
+\fB\-L \-\-list\-available\-vms\fI
+Lists available JVMs. Used with
+.I \-\-set\-system\-vm
+and
+.I \-\-set\-user\-vm
+.
+.TP
+\fB\-S <vm\-id> \-\-set\-system\-vm=<vm\-id>\fI
+Sets the system\-wide default JVM.
+.TP
+\fB\-s <vm\-id> \-\-set\-user\-vm=<vm\-id>\fI
+Sets the user\-specific JVM by putting all necessary env vars into
+.I $HOME/.gentoo/java\-env .
+.TP
+\fB\-f \-\-show\-active\-vm\fI
+Show the JVM that's currently active, as set via \-\-set\-system\-vm or \-\-set\-user\-vm.
+.TP
+\fB\-A <pkg1>,<pkg2>,... \-\-set\-system\-classpath=<package1>,<package2>,...\fI
+Sets the system\-wide default CLASSPATH.
+.TP
+\fB\-a <pkg1>,<pkg2>,... \-\-set\-user\-classpath=<package1>,<package2>,...\fI
+Sets the user\-specific CLASSPATH by putting all necessary env vars into
+.I $HOME/.gentoo/java\-env\-classpath
+(sourced from $HOME/.gentoo/java\-env).
+.TP
+\fB\-X \-\-clean\-system\-classpath\fI
+Cleans the system\-wide default classpath, leaving only vm needed jars
+on it.
+.TP
+\fB\-x \-\-clean\-user\-classpath\fI
+Cleans the user specific classpath that was specified by
+.I \-\-set\-user\-classpath
+by deleting
+.I $HOME/.gentoo/java\-env\-classpath .
+.
+.TP
+\fB\-n \-\-nocolor\fI
+Turn off all colors.
+.TP
+\fB\-P <vm\-id> \-\-print=<vm\-id>\fI
+Print the environment information for the specified virtual machine.
+.
+
+.SH "NOTES"
+You can get the <vm\-id> that is used with
+.I \-\-set\-system\-vm=<vm\-id>
+and
+.I \-\-set\-user\-vm=<vm\-id>
+in the output of
+.I java\-config \-\-list\-available\-vms
+inside the brackets. Ex. [blackdown\-jdk\-1.4.1] and you can use this to
+set your default Java Virtual Machine.
+
+.SH "AUTHORS"
+Karl Trygve Kalleberg <karltk@gentoo.org>
+.br
+Adrian Almenar <strider@gentoo.org>
+.br
+Jason Mobarak <aether@gentoo.org>
+
+.SH "BUGS"
+Report any bugs you find to http://bugs.gentoo.org/.
+
+.SH "SEE ALSO"
+env\-update(5)
+.TP
+The \fI/usr/bin/java\-config\fR script.
+.TP
diff --git a/trunk/setup.cfg b/trunk/setup.cfg
new file mode 100644
index 0000000..61d2c29
--- /dev/null
+++ b/trunk/setup.cfg
@@ -0,0 +1,17 @@
+[install_scripts]
+symlink-tools = appletviewer
+ apt
+ jar
+ jarsigner
+ java
+ javac
+ javadoc
+ javah
+ javap
+ javaws
+ jconsole
+ jdb
+ keytool
+ rmic
+ rmid
+ rmiregistry
diff --git a/trunk/setup.py b/trunk/setup.py
new file mode 100644
index 0000000..ea9d472
--- /dev/null
+++ b/trunk/setup.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+
+from distutils.command.install_scripts import install_scripts
+
+class my_install_scripts(install_scripts):
+ """Specialized data file install to handle our symlinks"""
+ install_scripts.user_options.append(('symlink-tools=', None,
+ 'List if files to symlink to run-java-tool in script directory'))
+
+ def initialize_options(self):
+ install_scripts.initialize_options(self)
+ self.symlink_tools = None
+
+ def finalize_options(self):
+ install_scripts.finalize_options(self)
+ self.ensure_string_list('symlink_tools')
+
+ def run(self):
+ from os import symlink
+ from distutils.util import change_root
+ from distutils import log
+ install_scripts.run(self)
+ for tool in self.symlink_tools:
+ s = self.install_dir + '/' + tool
+ log.info("Creating symlink %s -> run-java-tool" % s)
+ symlink('run-java-tool', s)
+
+from distutils.core import setup
+from glob import glob
+
+setup (
+ cmdclass={'install_scripts': my_install_scripts},
+ name = 'java-config',
+ version = '2.1.2',
+ description = 'java enviroment configuration tool',
+ long_description = \
+ """
+ java-config is a tool for configuring various enviroment
+ variables and configuration files involved in the java
+ enviroment for Gentoo Linux.
+ """,
+ maintainer = 'Gentoo Java Team',
+ maintainer_email = 'java@gentoo.org',
+ url = 'http://www.gentoo.org',
+ packages = ['java_config_2'],
+ package_dir = { 'java_config_2' : 'src/java_config_2' },
+ scripts = ['src/java-config-2','src/depend-java-query','src/run-java-tool', 'src/gjl'],
+ data_files = [
+ ('share/java-config-2/pym/java_config/', glob('src/java_config/*')),
+ ('share/man/man1', ['man/java-config-2.1']),
+ ('share/java-config-2/launcher', ['src/launcher.bash']),
+ ('share/eselect/modules', glob('src/eselect/*.eselect')),
+ ('/etc/java-config-2/', ['config/virtuals']),
+ ('/etc/java-config-2/build/', ['config/jdk.conf','config/compilers.conf']),
+ ('/etc/env.d/',['config/20java-config']),
+ ('/etc/profile.d/', glob('src/profile.d/*')),
+ ('/etc/revdep-rebuild/', ['src/revdep-rebuild/60-java'])
+ ]
+)
+
+# vim: noet:ts=4:
diff --git a/trunk/src/depend-java-query b/trunk/src/depend-java-query
new file mode 100755
index 0000000..01ea8d6
--- /dev/null
+++ b/trunk/src/depend-java-query
@@ -0,0 +1,84 @@
+#!/usr/bin/python -E
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+from java_config_2 import __version__
+from java_config_2.OutputFormatter import OutputFormatter
+from java_config_2.EnvironmentManager import EnvironmentManager
+from java_config_2.Errors import *
+from java_config_2.VersionManager import *
+
+import os
+import sys
+from commands import getoutput
+from string import join
+
+from optparse import OptionParser, make_option, OptionValueError
+
+def version(option, opt, value, parser):
+ printer._print("%H%BJava Dep Query Utility %GVersion " + str(__version__))
+ raise SystemExit()
+
+def nocolor(option, opt, value, parser):
+ printer.setColorOutputStatus(False)
+
+def is_sufficient(option, opt, value, parser):
+ try:
+ if verman.version_satisfies(value,manager.get_active_vm()):
+ printer._print("Active vm satisfies the depend string")
+ sys.exit(0)
+ else:
+ printer._print("Active vm does NOT satisfy the depend string")
+ sys.exit(1)
+
+ except RuntimeError, (ex):
+ printer._printError(str(ex))
+ sys.exit(1)
+
+def get_vm(option, opt, value, parser):
+ try:
+ if parser.values.need_virtual is not None:
+ vm = verman.get_vm(value, parser.values.need_virtual)
+ else:
+ vm = verman.get_vm(value)
+
+ printer._print(vm)
+ except Exception, ex:
+ printer._printError(str(ex))
+ sys.exit(1)
+
+def get_lowest(option, opt, value, parse):
+ try:
+ printer._print(verman.get_lowest(value))
+ except Exception, ex:
+ printer._printError(str(ex))
+ sys.exit(1)
+
+if __name__ == '__main__':
+ global printer, manager, verman
+ printer = OutputFormatter(True, True)
+ manager = EnvironmentManager()
+ verman = VersionManager()
+
+ usage = "depend-java-query [options]\n\n"
+ usage += "Java Dep Query Utility Version " + str(__version__) + "\n"
+ usage += "Copyright 2004-2006 Gentoo Foundation\n"
+ usage += "Distributed under the terms of the GNU General Public License v2\n"
+ usage += "Please contact the Gentoo Java Herd <java@gentoo.org> with problems."
+
+ options_list = [
+ make_option ("-V", "--version", action="callback", callback=version, help="Print version information"),
+ make_option ("-n", "--nocolor", action="callback", callback=nocolor, help="Disable color output"),
+ make_option ("-s", "--is-sufficient", action="callback", callback=is_sufficient, help="Check a depend string and see if current-vm is sufficiant", type="string", dest="dependstr"),
+ make_option ("-v", "--get-vm", action="callback", callback=get_vm, help="Return the best vm for this dep string", type="string", dest="dependstr"),
+ make_option ("-l", "--get-lowest", action="callback", callback=get_lowest, help="Return the lowest version in the depend, to be used with -target/-source fex.", type="string", dest="dependstr"),
+ make_option ("-p", "--need-virtual", action="store", help="When searching for a vm, make sure this virtual can be provided for.", type="string", dest="need_virtual")
+ ]
+
+ parser = OptionParser(usage, options_list)
+ (options, args) = parser.parse_args()
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/eselect/README b/trunk/src/eselect/README
new file mode 100644
index 0000000..b09e3fb
--- /dev/null
+++ b/trunk/src/eselect/README
@@ -0,0 +1 @@
+This is also in the eselect svn, and should also be update there!
diff --git a/trunk/src/eselect/java-nsplugin.eselect b/trunk/src/eselect/java-nsplugin.eselect
new file mode 100644
index 0000000..3d21db0
--- /dev/null
+++ b/trunk/src/eselect/java-nsplugin.eselect
@@ -0,0 +1,208 @@
+# Copyright 1999-2006 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Id: $
+
+inherit tests multilib
+
+DESCRIPTION="Manage the Java plugin for Netscape-like Browsers"
+MAINTAINER="java@gentoo.org"
+SVN_DATE='$Date: $'
+VERSION=$(svn_date_to_version "${SVN_DATE}" )
+
+
+PLUGINS_HOME="${ROOT}/usr/share/java-config-2/nsplugin"
+SYSTEM_PLUGIN_DIR="${ROOT}/usr/lib/nsbrowser/plugins"
+SYSTEM_PLUGIN_DIR_32="${ROOT}/usr/lib32/nsbrowser/plugins"
+SYSTEM_PLUGIN_DIR_64="${ROOT}/usr/lib64/nsbrowser/plugins"
+SYSTEM_PLUGIN="${SYSTEM_PLUGIN_DIR}/javaplugin.so"
+SYSTEM_PLUGIN_32="${SYSTEM_PLUGIN_DIR_32}/javaplugin.so"
+SYSTEM_PLUGIN_64="${SYSTEM_PLUGIN_DIR_64}/javaplugin.so"
+
+libdirs=$(list_libdirs)
+if has lib32 ${libdirs} && has lib64 ${libdirs}; then
+ IS_MULTILIB="true"
+else
+ IS_MULTILIB="false"
+fi
+### show action
+
+## {{{ show stuff
+
+ describe_show() {
+ echo "Show the current Java browser plugin"
+ }
+
+ do_show() {
+ local system_name=$(get_system_plugin_vm)
+ write_list_start "Current Java browser plugin"
+ if [[ -z "${system_name}" ]] ; then
+ write_kv_list_entry "(unset)" ""
+ else
+ write_kv_list_entry "${system_name}" ""
+ fi
+ }
+
+## }}}
+
+### list action
+
+
+
+## {{{ list stuff
+ describe_list() {
+ echo "List available Java browser plugins"
+ }
+
+ tweak_list_item() {
+ local vm=${1}
+ local system_name=${2}
+ local mark=""
+ if [[ ${vm} == ${system_name} ]]; then
+ mark="${mark} $(highlight 'current')"
+ fi
+ echo "${vm} ${mark}"
+ }
+
+ tweak_list() {
+ local targets=( ${@} )
+ system_name=$(get_system_plugin_vm)
+
+ for (( i = 0 ; i < ${#targets[@]} ; i = i + 1 )) ; do
+ twaek_list_item ${targets[${i}]} ${system_name}
+ done
+ }
+
+ do_list() {
+ if [[ ${IS_MULTILIB} != "true" ]]; then
+ MULTILIB_MODE="none"
+ local system_name=$(get_system_plugin_vm)
+ local targets=( $(get_targets) )
+ for (( i = 0 ; i < ${#targets[@]} ; i = i + 1 )) ; do
+ targets[${i}]=$(tweak_list_item ${targets[${i}]} ${system_name})
+ done
+
+ write_list_start "Available Java browser plugins"
+ write_numbered_list "${targets[@]}"
+ else
+ MULTILIB_MODE="32"
+ local system_name_32=$(get_system_plugin_vm)
+ local targets_32=( $(get_targets) )
+ for (( i = 0 ; i < ${#targets_32[@]} ; i = i + 1 )) ; do
+ targets_32[${i}]=$(tweak_list_item ${targets_32[${i}]} ${system_name_32})
+ done
+ write_list_start "Available 32-bit Java browser plugins"
+ write_numbered_list "${targets_32[@]}"
+
+ MULTILIB_MODE="64"
+ local system_name_64=$(get_system_plugin_vm)
+ local targets_64=( $(get_targets) )
+ for (( i = 0 ; i < ${#targets_64[@]} ; i = i + 1 )) ; do
+ targets_64[${i}]=$(tweak_list_item ${targets_64[${i}]} ${system_name_64})
+ done
+ write_list_start "Available 64-bit Java browser plugins"
+ write_numbered_list "${targets_64[@]}"
+ fi
+ }
+## }}}
+
+### set action
+
+## {{{ set stuff
+ describe_set() {
+ echo "Set the system Java browser plugin"
+ }
+
+ do_set() {
+ if [[ ${IS_MULTILIB} != "true" ]]; then
+ if [[ ${#} != 1 ]] ; then
+ die -q "Usage: set [nsplugin-vm]"
+ fi
+ MULTILIB_MODE="none"
+ else
+ if [[ ${#} != 2 ]] ; then
+ die -q "Usage: set [32bit or 64bit] [nsplugin-vm]"
+ fi
+ case ${1} in
+ 32bit) ;;
+ 64bit) ;;
+ *)
+ die -q "Usage: set [32bit or 64bit] [nsplugin-vm]"
+ ;;
+ esac
+ MULTILIB_MODE=${1%bit}
+ shift
+ fi
+
+ local vm=${1}
+
+ if is_number "${vm}" ; then
+ local targets=( $(get_targets) )
+ vm=${targets[$(( ${vm} - 1 ))]}
+ fi
+
+ if [[ -z ${vm} ]] ; then
+ die -q "You didn't specify valid plugin number to set"
+ fi
+
+ local plugin="${PLUGINS_HOME}/${vm}-javaplugin.so"
+
+ if [[ ! -f ${plugin} ]]; then
+ write_error_msg "Expected \"${plugin}\" to exist, but it doesn't."
+ write_error_msg "Perhaps \"${vm}\" isn't a valid name of VM built with nsplugin?"
+ return
+ fi
+
+ local system_plugin
+ case ${MULTILIB_MODE} in
+ 32) system_plugin=${SYSTEM_PLUGIN_32} ;;
+ 64) system_plugin=${SYSTEM_PLUGIN_64} ;;
+ none) system_plugin=${SYSTEM_PLUGIN} ;;
+ esac
+ mkdir -p $(dirname ${system_plugin}) || die -q "Error creating \"$(dirname ${SYSTEM_PLUGIN})\""
+ if [[ -w $(dirname ${system_plugin}) ]] ; then
+ ln -sf ${plugin} ${system_plugin} || die -q "Error creating nsplugin symlink"
+ else
+ die -q "Sorry, you don't have enough permission to set nsplugin"
+ fi
+ }
+## }}}
+
+get_targets() {
+ for plugin in $(ls ${PLUGINS_HOME}/*-javaplugin.so 2>/dev/null);
+ do
+ local vm=$(plugin_to_vm ${plugin})
+ local matches=""
+ case ${MULTILIB_MODE} in
+ 32)
+ [[ ${vm} = emul-linux-* ]] && matches="true"
+ ;;
+ 64)
+ [[ ${vm} != emul-linux-* ]] && matches="true"
+ ;;
+ none)
+ matches="true"
+ ;;
+ esac
+ [[ ${matches} == "true" ]] && echo ${vm}
+ done
+}
+
+plugin_to_vm() {
+ local base=$(basename ${1})
+ echo ${base%-javaplugin.so}
+}
+
+get_system_plugin_vm() {
+ local plugin;
+
+ if [[ ${MULTILIB_MODE} == "32" ]]; then
+ plugin=$(readlink ${SYSTEM_PLUGIN_32})
+ elif [[ ${MULTILIB_MODE} == "64" ]]; then
+ plugin=$(readlink ${SYSTEM_PLUGIN_64})
+ else
+ plugin=$(readlink ${SYSTEM_PLUGIN})
+ fi
+ plugin_to_vm ${plugin}
+}
+
+# vim: ts=4 sw=4 noet fdm=marker
diff --git a/trunk/src/eselect/java-vm.eselect b/trunk/src/eselect/java-vm.eselect
new file mode 100644
index 0000000..e33d0fc
--- /dev/null
+++ b/trunk/src/eselect/java-vm.eselect
@@ -0,0 +1,145 @@
+# Copyright 1999-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Id: $
+
+# Based on kernel.eselect
+
+DESCRIPTION="Manage the Java system and user VM"
+MAINTAINER="java@gentoo.org"
+SVN_DATE='$Date: $'
+VERSION=$(svn_date_to_version "${SVN_DATE}" )
+
+VM_BASE=/usr/lib/jvm/
+VM_SYSTEM="/etc/java-config-2/current-system-vm"
+VM_USER="${HOME}/.gentoo/java-config-2/current-user-vm"
+
+find_targets() {
+ local f
+ for f in ${VM_BASE}/* ; do
+ [[ -L ${f} ]] && echo $(basename ${f})
+ done
+}
+
+sym_to_vm() {
+ basename $(readlink "${1}")
+}
+
+### show action ###
+
+describe_show() {
+ echo "Show the current vm"
+}
+
+do_show() {
+ if [[ ${1} == "system" ]]; then
+ my_show ${VM_SYSTEM} 'system-vm'
+ elif [[ ${1} == "user" ]]; then
+ my_show ${VM_USER} 'user-vm'
+ else
+ my_show ${VM_SYSTEM} 'system-vm'
+ my_show ${VM_USER} 'user-vm'
+ fi
+}
+
+my_show() {
+ local symlink=${1} vm_type=${2}
+ write_list_start "Current ${vm_type}"
+ if [[ -L "${symlink}" ]] ; then
+ write_kv_list_entry "$(sym_to_vm ${symlink})" ""
+ else
+ write_kv_list_entry "(unset)" ""
+ fi
+}
+
+### list action ###
+
+describe_list() {
+ echo "List Available Virtual Machines"
+}
+
+do_list() {
+ targets=( $(find_targets) )
+ write_list_start "Available Java Virtual Machines:"
+ if [[ -n ${targets[@]} ]] ; then
+ local i system_name user_name
+
+ [[ -L ${VM_SYSTEM} ]] && system_name=$(sym_to_vm ${VM_SYSTEM})
+ [[ -L ${VM_USER} ]] && user_name=$(sym_to_vm ${VM_USER})
+
+ for (( i = 0 ; i < ${#targets[@]} ; i = i + 1 )) ; do
+ local mark=""
+ if [[ ${targets[${i}]} == ${system_name} ]]; then
+ mark="${mark} $(highlight 'system-vm')"
+ fi
+ if [[ ${targets[${i}]} == ${user_name} ]]; then
+ mark="${mark} $(highlight 'user-vm' )"
+ fi
+ targets[${i}]="${targets[${i}]} ${mark}"
+ done
+ write_numbered_list "${targets[@]}"
+ else
+ write_kv_list_entry "(none found)" ""
+ fi
+}
+
+### set action ###
+
+describe_set() {
+ echo "Set a new system-vm"
+}
+
+do_set() {
+ if [[ ${#} != 2 ]]; then
+ die -q "Usage [user|system] [vm]"
+
+ elif [[ ${1} == "system" ]]; then
+ if [[ -w $(dirname ${VM_SYSTEM}) ]]; then
+ my_set ${VM_SYSTEM} ${2}
+ else
+ die -q "Sorry, you don't have enough premission to set system"
+ fi
+ elif [[ ${1} == "user" ]]; then
+ if [[ ${UID} != 0 ]]; then
+ my_set ${VM_USER} ${2}
+ else
+ die -q "Sorry, you cannot set a user vm as root. Set the system vm instead"
+ fi
+ fi
+}
+
+my_set() {
+ local target=${2} symlink=${1}
+ if [[ -z ${target} ]] ; then
+ die -q "You didn't tell me what to set the symlink to"
+
+ elif [[ -L "${symlink}" ]] ; then
+ set_symlink "${target}" "${symlink}" || die -q "Couldn't set a new symlink"
+
+ elif [[ -e "${symlink}" ]] ; then
+ die -q "Target file already exists and is not a symlink: ${symlink}"
+
+ else
+ set_symlink "${target}" "${symlink}" || die -q "Couldn't set a new symlink"
+ fi
+}
+
+set_symlink() {
+ local target=${1} symlink=${2}
+ if is_number "${target}" ; then
+ targets=( $(find_targets) )
+ target=${targets[$(( ${target} - 1 ))]}
+ fi
+ if [[ -z ${target} ]] ; then
+ die -q "Target \"${1}\" doesn't appear to be valid!"
+ elif [[ -d "${VM_BASE}/${target}" ]] ; then
+ local sym_dir=$(dirname ${symlink})
+ if [[ ! -d ${sym_dir} ]]; then
+ mkdir -p ${sym_dir} || die -q "Could not create ${my_dir}"
+ fi
+ ln -snf "${VM_BASE}/${target}" "${symlink}"
+ else
+ die -q "Target \"${1}\" doesn't appear to be valid!"
+ fi
+}
+
+# vim: set ft=eselect :
diff --git a/trunk/src/gjl b/trunk/src/gjl
new file mode 100755
index 0000000..b50567e
--- /dev/null
+++ b/trunk/src/gjl
@@ -0,0 +1,211 @@
+#!/usr/bin/python -E
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+from java_config_2 import __version__
+from java_config_2.OutputFormatter import *
+from java_config_2.EnvironmentManager import *
+from java_config_2.VersionManager import *
+
+from commands import getoutput
+from string import join
+from sets import Set
+from optparse import OptionParser, make_option, OptionValueError
+import os
+from os.path import basename
+import sys
+
+# Needs some cleanup!
+# Someone please?
+
+def get_needed_packages(package):
+ unresolved = Set()
+ unresolved.add(package)
+
+ resolved = Set()
+
+ while len(unresolved) > 0:
+ pkg = unresolved.pop()
+ resolved.add(pkg)
+ # dep is in the form of (jar, pkg)
+ for dep in manager.get_pkg_deps(pkg):
+ dep_pkg = dep[-1]
+ p = manager.get_package(dep_pkg)
+ if p is None:
+ if ',' in dep_pkg:
+ msg = """
+Package %s has a broken DEPEND entry in package.env. Please reinstall it.
+If this does not fix it, please report this to http://bugs.gentoo.org
+"""
+ msg = msg % pkg
+ else:
+ msg = """
+Package %s not found in the system. This package is listed as a
+dependency of %s. Please run emerge -1Da %s and if it does not bring in the
+needed dependency, report this to http://bugs.gentoo.org.
+"""
+ msg = msg % (dep_pkg,pkg,pkg)
+ abort(msg)
+
+ if p not in resolved:
+ unresolved.add(p)
+
+ return resolved
+
+def get_needed_target(pkg):
+ highest_target = None
+ needs_jdk = False
+ for pkg in get_needed_packages(pkg):
+ pkg_needs_jdk = False
+ x = pkg.query("TARGET")
+ try:
+ target, pkg_needs_jdk = x
+ except (ValueError, TypeError):
+ target = x
+
+ needs_jdk |= pkg_needs_jdk
+ if highest_target:
+ if target > highest_target:
+ highest_target = target
+ else:
+ highest_target = target
+
+ return highest_target, needs_jdk
+
+
+def get_pkg_args(package):
+ missing_deps = Set()
+
+ classpath = manager.build_dep_path([package.name()], "CLASSPATH", missing_deps)
+ library = manager.build_dep_path([package.name()], "LIBRARY_PATH", missing_deps)
+
+ if len(missing_deps) > 0:
+ for dep in missing_deps:
+ printer._printError("Dependency package %s was not found!" % dep)
+
+ return ':'.join(classpath), ':'.join(library)
+
+def abort(msg):
+ printer._printError(msg)
+ sys.exit(1)
+
+
+# Options:
+def get_vm(pkg):
+ target, needs_jdk = get_needed_target(pkg)
+ if target:
+ if needs_jdk:
+ needed = ">=virtual/jdk-%s" % ( target ) # Need to dehardcode that for Virtuals...
+ else:
+ needed = ">=virtual/jre-%s" % ( target ) # Need to dehardcode that for Virtuals...
+ if verman.version_satisfies(needed, manager.get_active_vm()):
+ return None
+ else:
+ return verman.get_vm(needed)
+ else:
+ return verman.get_vm(pkg.query("VM"))
+
+def get_args(pkg):
+ args=""
+
+ classpath, library = get_pkg_args(pkg)
+ if classpath:
+ envcp = os.getenv('CLASSPATH')
+
+ if envcp:
+ classpath = ':'.join((envcp, classpath))
+
+ args += ' -classpath %s' % (classpath)
+
+ envlp = os.getenv('LD_LIBRARY_PATH')
+ envjlp = os.getenv('JAVA_LIBRARY_PATH')
+
+ newlibrary = '/lib:/usr/lib'
+ if library:
+ newlibrary = ':'.join((library, newlibrary))
+ if envjlp:
+ newlibrary = ':'.join((newlibrary, envjlp))
+ if envlp:
+ newlibrary = ':'.join((newlibrary, envlp))
+
+ args += ' -Djava.library.path="%s"' % (newlibrary)
+
+ if args:
+ return args
+ else:
+ return None
+
+def get_env(package):
+ env = manager.build_dep_env_vars([package.name()], Set())
+ return env
+
+def get_jar(pkg, gjar):
+ jars = pkg.classpath()
+ if jars:
+ for jar in jars.split(':'):
+ if gjar == basename(jar):
+ return jar
+ if normpath(gjar) == normpath(jar):
+ return gjar
+ return None
+
+def normpath(mypath):
+ newpath = os.path.normpath(mypath)
+ if newpath.startswith('//'):
+ return newpath[1:]
+ return newpath
+
+if __name__ == '__main__':
+ usage = "%prog [options]\n\n"
+ usage += "Java Utility Version " + str(__version__) + "\n"
+ usage += "Copyright 2004-2005 Gentoo Foundation\n"
+ usage += "Distributed under the terms of the GNU General Public License v2\n"
+ usage += "Please contact the Gentoo Java Herd <java@gentoo.org> with problems."
+
+ options_list = [
+ make_option ("-p", "--package", action="store", type="string", dest="package", help="The package"),
+ make_option ("-v", "--get-vm", action="store_true", dest="get_vm"),
+ make_option ("-a", "--get-args", action="store_true", dest="get_args"),
+ make_option ("-j", "--get-jar", action="store", type="string", dest="jar")
+ ]
+
+ parser = OptionParser(usage, options_list)
+ (options, args) = parser.parse_args()
+
+ global printer, manager, verman
+ printer = OutputFormatter(True, True)
+ manager = EnvironmentManager()
+ verman = VersionManager()
+
+ if not options.package:
+ abort("Too dumb todo anything without -p")
+
+ pkg = manager.get_package(options.package)
+ if not pkg:
+ abort("Invalid package: %s" % ( options.package ) )
+
+ if options.get_vm:
+ vm = get_vm(pkg)
+ if vm:
+ manager.set_active_vm(vm)
+ print 'gjl_vm="%s"' % ( vm )
+
+ if options.get_args:
+ args = get_args(pkg)
+ if args:
+ print 'gjl_args="%s";' % ( args )
+ env = get_env(pkg)
+ for k, v in env.iteritems():
+ print 'export %s="%s";' % ( k, v )
+
+ if options.jar:
+ jar = get_jar(pkg, options.jar)
+ if jar:
+ print 'gjl_starte="-jar %s"' % ( jar )
+ else:
+ abort("Couldn't find %s" % ( options.jar ) )
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java-config-2 b/trunk/src/java-config-2
new file mode 100755
index 0000000..bcea65f
--- /dev/null
+++ b/trunk/src/java-config-2
@@ -0,0 +1,349 @@
+#!/usr/bin/python -E
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2006 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+from java_config_2 import __version__
+from java_config_2.OutputFormatter import OutputFormatter
+from java_config_2.EnvironmentManager import EnvironmentManager
+from java_config_2.Errors import *
+
+import os
+import sys
+from commands import getoutput
+
+from optparse import OptionParser, make_option
+
+from sets import Set
+
+def version(option, opt, value, parser):
+ printer._print("%H%BJava Configuration Utility %GVersion " + str(__version__))
+ raise SystemExit()
+
+def nocolor(option, opt, value, parser):
+ printer.setColorOutputStatus(False)
+
+def get_command(command):
+ try:
+ printer._print(manager.get_active_vm().find_exec(command))
+ except PermissionError:
+ fatalError("The " + command + " executable was not found in the Java path")
+
+def java(option, opt, value, parser):
+ get_command('java')
+
+def javac(option, opt, value, parser):
+ get_command('javac')
+
+def jar(option, opt, value, parser):
+ get_command('jar')
+
+def query_active_vm(var):
+ try:
+ printer._print(manager.get_active_vm().query(var))
+ except EnvironmentUndefinedError:
+ fatalError("%s could not be found in the active VM environment" % var)
+
+def query_active_vm_cb(option, opt, value, parse, *args):
+ return query_active_vm(args[0])
+
+def tools(option, opt, value, parser):
+ jh = ''
+ try:
+ jh = manager.get_active_vm().query('JAVA_HOME')
+ except EnvironmentUndefinedError:
+ fatalError("JAVA_HOME not found in the active VM environment")
+ tools_jar = jh + '/lib/tools.jar'
+ if os.path.exists(tools_jar):
+ printer._print(tools_jar)
+ else:
+ sys.exit(1);
+
+def show_active_vm(option, opt, value, parser):
+ printer._print(manager.get_active_vm().name())
+
+def java_version(option, opt, value, parser):
+ try:
+ printer._print(getoutput('%s -version' % manager.get_active_vm().find_exec('java')))
+ except PermissionError:
+ fatalError("The java executable was not found in the Java path")
+
+def query_pkg_path(option, opt, value, parser, query):
+ packages = value.split(',')
+ path = Set()
+ missing_deps = Set()
+ if not parser.values.with_deps:
+ path = manager.build_path(packages, query)
+ else:
+ path = manager.build_dep_path(packages, query, missing_deps)
+
+ printer._print(':'.join(path))
+
+ error = False
+
+ if len(packages) > 0:
+ for package in packages:
+ printer._printError("Package %s was not found!" % package)
+ error = True
+
+ if len(missing_deps) > 0:
+ for dep in missing_deps:
+ printer._printError("Dependency package %s was not found!" % dep)
+ error = True
+
+ if error:
+ sys.exit(1)
+
+def get_virtuals_packages( option, opt, value, parser):
+ if manager.get_virtual(value):
+ output = manager.get_virtual(value).get_packages()
+ printer._print(','.join(output))
+ else:
+ printer._printError("Virtual package %s was not found" % value)
+ sys.exit(1)
+
+def get_env(option, opt, value, parser):
+ for env in value.split(','):
+ query_active_vm(env)
+
+def exec_cmd(option, opt, value, parser):
+ for cmd in iter(value.split(',')):
+ os.system(cmd)
+
+def list_available_packages(option, opt, value, parser):
+ for package in manager.get_packages().itervalues():
+ printer._print("[%s] %s (%s)" % (package.name(), package.description(), package.file()))
+
+def list_available_vms(option, opt, value, parser):
+ vm_list = manager.get_virtual_machines()
+ try:
+ active = manager.get_active_vm()
+ except InvalidVMError:
+ active = None
+
+ printer._print('%HThe following VMs are available for generation-2:%$')
+ for i, vm in vm_list.iteritems():
+ if vm is active:
+ printer._print('%G' + '*)\t%s [%s]%s' % (vm.query('VERSION'), vm.name(), '%$'))
+ else:
+ printer._print('%i)\t%s [%s]' % (i, vm.query('VERSION'), vm.name()))
+
+def print_environment(option, opt, value, parser):
+ vm = manager.get_vm(value)
+ if vm:
+ manager.create_env_entry(vm, printer, "%s=%s")
+ else:
+ fatalError("Could not find a vm matching: %s" % value)
+
+def set_system_vm(option, opt, value, parser):
+ vm = manager.get_vm(value)
+
+ if not vm:
+ fatalError("Could not find a vm matching: %s" % value)
+ else:
+ if os.getuid() is 0:
+ try:
+ manager.set_system_vm(vm)
+ printer._print("Now using %s as your generation-2 system JVM" % (vm) )
+ except PermissionError:
+ fatalError("You do not have enough permissions to set the system VM!")
+ except EnvironmentUndefinedError:
+ fatalError("The selected VM is missing critical environment variables.")
+ except InvalidConfigError, e:
+ fatalError("Target file already exists and is not a symlink: %s" % e.file)
+ else:
+ fatalError("You do not have enough permissions to set the system VM!")
+
+def set_user_vm(option, opt, value, parser):
+ vm = manager.get_vm(value)
+
+ if not vm:
+ fatalError("Could not find a vm matching: %s" % value)
+ else:
+ if os.getuid() is 0:
+ fatalError("The user 'root' should always use the System VM")
+ else:
+ try:
+ manager.set_user_vm(vm)
+ printer._print("Now using %s as your user JVM" % (vm))
+ except PermissionError:
+ fatalError("You do not have enough permissions to set the VM!")
+ except InvalidConfigError, e:
+ fatalError("Target file already exists and is not a symlink: %s" % e.file)
+
+# Deprecated
+def system_classpath_target():
+ # TODO: MAKE THIS MODULAR!! (compnerd)
+ return [{'file': '/etc/env.d/21java-classpath', 'format': '%s=%s\n' }]
+
+def user_classpath_target():
+ # TODO: MAKE THIS MODULAR!! (compnerd)
+ return [
+ {'file': os.path.join(os.environ.get("HOME"), '.gentoo/java-env-classpath'), 'format': 'export %s=%s\n' },
+ {'file': os.path.join(os.environ.get("HOME"), '.gentoo/java-env-classpath.csh'), 'format': 'setenv %s %s\n' }
+ ]
+# Deprecated
+def set_system_classpath(option, opt, value, parser):
+ deprecation_notice()
+ if os.getuid() is 0:
+ pkgs = value.split(',')
+ manager.set_classpath(system_classpath_target(), pkgs)
+
+ for package in pkgs:
+ printer._printError("Package %s was not found!" % package)
+
+ update_env()
+ else:
+ fatalError("You do not have enough permissions to set the system classpath!")
+
+# Deprecated
+def set_user_classpath(option, opt, value, parser):
+ deprecation_notice()
+ pkgs = value.split(',')
+ manager.set_classpath(user_classpath_target(), pkgs)
+
+ for package in pkgs:
+ printer._printError("Package %s was not found!" % package)
+
+ user_update_env()
+
+# Deprecated
+def append_system_classpath(option, opt, value, parser):
+ deprecation_notice()
+ if os.getuid() is 0:
+ pkgs = value.split(',')
+ manager.append_classpath(system_classpath_target(), pkgs)
+
+ for package in pkgs:
+ printer._printError("Package %s was not found!" % package)
+
+ update_env()
+ else:
+ fatalError("You do not have enough permissioins to append to the system classpath!")
+
+# Deprecated
+def append_user_classpath(option, opt, value, parser):
+ deprecation_notice()
+ pkgs = value.split(',')
+ manager.append_classpath(user_classpath_target(), pkgs)
+
+ for package in pkgs:
+ printer._printError("Package %s was not found!" % package)
+
+ user_update_env()
+
+# Deprecated
+def clean_system_classpath(option, opt, value, parser):
+ deprecation_notice()
+ if os.getuid() is 0:
+ manager.clean_classpath(system_classpath_target())
+ update_env()
+ else:
+ fatalError("You do not have enough permissions to clean the system classpath!")
+
+# Deprecated
+def clean_user_classpath(option, opt, value, parser):
+ deprecation_notice()
+ manager.clean_classpath(user_classpath_target())
+
+def select_vm(option, opt, value, parser):
+ if value == '':
+ return
+
+ vm = manager.get_vm(value)
+ if vm:
+ manager.set_active_vm(manager.get_vm(value))
+ else:
+ fatalError("The vm could not be found")
+
+def update_env():
+ printer._print(getoutput("/usr/sbin/env-update"))
+ printer._printAlert("If you want the changes too take effect in your current session, you should update\n\
+ your environment by running: source /etc/profile")
+
+def user_update_env():
+ printer._printAlert("Environment files in ~/.gentoo/ have been updated. You should source these from your shell's profile.\n\
+ If you want the changes too take effect in your current sessiosn, you should resource these files")
+
+def deprecation_notice():
+ printer._printWarning("Setting a user and system classpath is deprecated, this option will be removed from future versions.")
+
+def fatalError(msg):
+ printer._printError(msg)
+ sys.exit(1)
+
+if __name__ == '__main__':
+ global printer, manager
+ printer = OutputFormatter(True, True)
+ manager = EnvironmentManager()
+
+ usage = "java-config [options]\n\n"
+ usage += "Java Configuration Utility Version " + str(__version__) + "\n"
+ usage += "Copyright 2004-2005 Gentoo Foundation\n"
+ usage += "Distributed under the terms of the GNU General Public License v2\n"
+ usage += "Please contact the Gentoo Java Herd <java@gentoo.org> with problems."
+
+ options_list = [
+ make_option ("-V", "--version", action="callback", callback=version, help="Print version information"),
+ make_option ("-n", "--nocolor", action="callback", callback=nocolor, help="Disable color output"),
+ make_option ("" , "--select-vm", action="callback", callback=select_vm, help="Use this vm instead of the active vm when returning information", type="string", dest="vm"),
+ make_option ("-J", "--java", action="callback", callback=java, help="Print the location of the java executable"),
+ make_option ("-c", "--javac", action="callback", callback=javac, help="Print the location of the javac executable"),
+ make_option ("-j", "--jar", action="callback", callback=jar, help="Print the location of the jar executable"),
+ make_option ("-t", "--tools", action="callback", callback=tools, help="Print the path to tools.jar"),
+ make_option ("-f", "--show-active-vm", action="callback", callback=show_active_vm, help="Print the active Virtual Machine"),
+ make_option ("-v", "--java-version", action="callback", callback=java_version, help="Print version information for the active VM"),
+ make_option ("-g", "--get-env", action="callback", callback=get_env, help="Print an environment variable from the active VM", type="string", dest="var"),
+ make_option ("-P", "--print", action="callback", callback=print_environment, help="Print the environment for the specified VM", type="string", dest="vm"),
+ make_option ("-e", "--exec_cmd", action="callback", callback=exec_cmd, help="Execute something which is in JAVA_HOME", type="string", dest="command"),
+ make_option ("-L", "--list-available-vms", action="callback", callback=list_available_vms, help="List available Java Virtual Machines"),
+ make_option ("-S", "--set-system-vm", action="callback", callback=set_system_vm, help="Set the default Java VM for the system", type="string", dest="vm"),
+ make_option ("-s", "--set-user-vm", action="callback", callback=set_user_vm, help="Set the default Java VM for the user", type="string", dest="vm"),
+ make_option ("-l", "--list-available-packages", action="callback", callback=list_available_packages, help="List all available packages on the system."),
+ make_option ("-d", "--with-dependencies", action="store_true", help="Include package dependencies in --classpath and --library calls", default=False, dest="with_deps"),
+ make_option ("-p", "--classpath", action="callback", callback=query_pkg_path, help="Print entries in the environment classpath for these packages", type="string", dest="package(s)", callback_args = ("CLASSPATH",)),
+ make_option ("-i", "--library", action="callback", callback=query_pkg_path, help="Print java library paths for these packages", type="string", dest="package(s)", callback_args = ("LIBRARY_PATH",)),
+ make_option ("-A", "--set-system-classpath", action="callback", callback=set_system_classpath, help="(Deprecated) Set the system classpath to include the libraries", type="string", dest="package(s)" ),
+ make_option ("-B", "--append-system-classpath", action="callback", callback=append_system_classpath, help="(Deprecated) Append the libraries to the system classpath", type="string", dest="package(s)"),
+ make_option ("-X", "--clean-system-classpath", action="callback", callback=clean_system_classpath, help="(Deprecated) Clean the current system classpath"),
+ make_option ("-a", "--set-user-classpath", action="callback", callback=set_user_classpath, help="(Deprecated) Set the user classpath to include the libraries", type="string", dest="package(s)"),
+ make_option ("-b", "--append-user-classpath", action="callback", callback=append_user_classpath, help="(Deprecated) Append the libraries to the user classpath", type="string", dest="package(s)"),
+ make_option ("-x", "--clean-user-classpath", action="callback", callback=clean_user_classpath, help="(Deprecated) Clean the current user classpath"),
+ make_option ("", "--get-virtuals-packages", action="callback", callback=get_virtuals_packages, help="(Experimental) Return a list of packages that a virtual provides", type="string", dest="package(s)"),
+ make_option ("-r", "--runtime", action="callback", help="Print the runtime classpath",
+ callback=query_active_vm_cb, callback_args=("BOOTCLASSPATH",)),
+ make_option ("-O", "--jdk-home", action="callback", help="Print the location of the active JAVA_HOME",
+ callback=query_active_vm_cb, callback_args=("JAVA_HOME",)),
+ make_option ("-o", "--jre-home", action="callback", help="Print the location of the active JAVA_HOME",
+ callback=query_active_vm_cb, callback_args=("JAVA_HOME",))
+ ]
+
+ parser = OptionParser(usage, options_list)
+
+ if len(sys.argv) < 2:
+ parser.print_help()
+ else:
+ try:
+ # Makes sure that --nocolor is always the first argument
+ # because otherwise callbacks before it will output
+ # colored output
+ args = sys.argv[1:]
+ for opt in ( '-n', '--nocolor'):
+ try:
+ args.remove(opt)
+ args.insert(0,opt)
+ except ValueError:
+ pass
+
+ (options, args) = parser.parse_args(args=args)
+ except InvalidVMError:
+ fatalError("The active vm could not be found")
+ except ProviderUnavailableError, e:
+ message = "No providers are available, please ensure you have one of the following;\n"
+ message += "VM's: " + e.vms() + " (Your active vm must meet this.)\n"
+ message += "Packages's: " + e.packages() + "\n"
+ fatalError(message)
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/EnvironmentManager.py b/trunk/src/java_config_2/EnvironmentManager.py
new file mode 100644
index 0000000..cf39534
--- /dev/null
+++ b/trunk/src/java_config_2/EnvironmentManager.py
@@ -0,0 +1,449 @@
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+from OutputFormatter import *
+from Package import *
+from Virtual import *
+from VM import *
+from Errors import *
+
+from os.path import basename, dirname
+from glob import glob
+from sets import Set
+import os, re, sys
+
+class EnvironmentManager:
+ """This is the central class, which manages all information from the 'environment'"""
+ virtual_machines = None
+ packages = None
+ virtuals = None
+ virtuals_pref = None
+ active = None
+
+ # Location of the vm ev files
+ vms_path = '/usr/share/java-config-2/vm'
+ # Location of the package env files to load
+ pkg_path = '/usr/share/*/package.env'
+ virtual_path = '/usr/share/java-config-2/virtuals/*'
+
+ system_config_path="/etc/java-config-2/"
+
+ def __init__(self):
+ try:
+ self.load_active_vm()
+ except InvalidVMError:
+ pass
+ finally:
+ pass
+
+ def __call__(self):
+ return self
+
+ def load_vms(self):
+ """Load all the vm files, and check for correctness"""
+ self.virtual_machines = {}
+
+ if os.path.isdir(self.vms_path):
+ count = 1
+ filelist = os.listdir(self.vms_path)
+ filelist.sort()
+ for file in filelist:
+ conf = os.path.join(self.vms_path,file)
+ vm = None
+
+ try:
+ vm = VM(conf)
+ except InvalidConfigError:
+ continue
+ except PermissionError:
+ continue
+ except InvalidVMError, ex:
+ printer = OutputFormatter()
+ printer._printAlert("Invalid vm configuration file found: %s\nJava-config 2 requires some new variables, please update all your jdk/jre: file\n(%s)" % ( conf, ex ))
+ continue
+
+ self.virtual_machines[count] = vm
+ count += 1
+
+ def load_packages(self):
+ self.packages = {}
+ self.virtuals = {}
+ for package in iter(glob(self.pkg_path)):
+ pkg = Package(basename(dirname(package)), package)
+ self.packages[pkg.name()] = pkg
+
+ for virtual in iter(glob(self.virtual_path)):
+ virt = Virtual(basename(virtual), self, virtual)
+ self.packages[virt.name()] = virt
+ self.virtuals[virt.name()] = virt
+
+ def get_virtuals_pref(self):
+ if self.virtuals_pref is None:
+ self.load_virtuals_pref()
+ return self.virtuals_pref
+
+ def load_virtuals_pref(self):
+ self.virtuals_pref = EnvFileParser(self.system_config_path + "virtuals")
+
+ def load_active_vm(self):
+ vm_name = os.getenv("GENTOO_VM")
+ if vm_name:
+ vm = self.get_vm(vm_name)
+ if vm:
+ self.active = vm
+ return vm
+
+ for link in self.vm_links():
+ if os.path.islink(link):
+ vm_name = basename(os.readlink(link))
+ vm = self.get_vm(vm_name)
+ if vm:
+ self.active = vm
+ return vm
+ raise InvalidVMError
+
+ def set_active_vm(self, vm):
+ self.active = vm
+
+ def get_active_vm(self):
+ if self.active is None:
+ self.load_active_vm()
+ return self.active
+
+ def get_virtual_machines(self):
+ if self.virtual_machines is None:
+ self.load_vms()
+ return self.virtual_machines
+
+ def find_vm(self, name):
+ found = []
+ for id, vm in self.get_virtual_machines().iteritems():
+ if vm.name().startswith(name):
+ found.append(vm)
+ return found
+
+ def get_package(self, pkgname):
+ all_pkg = self.get_packages()
+ if all_pkg.has_key(pkgname):
+ return all_pkg[pkgname]
+ else:
+ return None
+
+ def get_packages(self):
+ """
+ Returns a dictionary of Packages indexed by their names.
+ For java-config-3 we probably want to change this to return
+ the list of packages directly.
+ """
+ if self.packages is None:
+ self.load_packages()
+ return self.packages
+
+ def get_virtuals(self):
+ if self.virtuals is None:
+ self.load_packages()
+ return self.virtuals
+
+ def get_virtual(self, virtname):
+ all_virt = self.get_virtuals()
+ if all_virt.has_key(virtname):
+ return all_virt[virtname]
+ else:
+ return None
+
+ def query_packages(self, packages, query):
+ results = []
+ all_pkg = self.get_packages()
+
+ for package in packages[:]:
+ if all_pkg.has_key(package):
+ packages.remove(package)
+ value = all_pkg[package].query(query)
+ if value:
+ results.append(value)
+ return results
+
+ def get_vm(self, machine):
+ vm_list = self.get_virtual_machines()
+ selected = None
+
+ for count in iter(vm_list):
+ vm = vm_list[count]
+
+ if str(machine).isdigit():
+ if int(machine) is count:
+ return vm
+ else:
+ # Check if the vm is specified via env file
+ if machine == vm.filename():
+ return vm
+
+ # Check if the vm is specified by name
+ if machine == vm.name():
+ return vm
+
+ # Check if the vm is specified via JAVA_HOME
+ if machine == vm.query('JAVA_HOME'):
+ return vm
+
+ # Check if vm is specified by partial name
+ if vm.name().startswith(machine):
+ selected = vm
+
+ if selected:
+ return selected
+ else:
+ return None
+
+ def create_env_entry(self, vm, stream, render="%s=%s\n"):
+ stream.write("# Autogenerated by java-config\n")
+ stream.write("# Java Virtual Machine: %s\n\n" % vm.query('VERSION'))
+
+ try:
+ ENV_VARS = vm.query('ENV_VARS')
+ for (item, value) in vm.get_config().iteritems():
+ if item in ENV_VARS:
+ stream.write(render % (item, value))
+ except IOError:
+ raise PermissionError
+ except EnvironmentUndefinedError:
+ raise EnvironmentUndefinedError
+
+ def set_user_vm(self, vm):
+ self.set_vm(vm, self.user_vm_link())
+
+ def set_system_vm(self, vm):
+ self.set_vm(vm, self.system_vm_link())
+
+ def set_vm(self, vm, target):
+ sym_dir = dirname(target)
+ if not os.path.isdir(sym_dir):
+ os.makedirs(sym_dir)
+
+ if os.path.islink(target):
+ os.remove(target)
+ elif os.path.exists(target):
+ raise InvalidConfigError(target)
+
+ os.symlink('/usr/lib/jvm/'+vm.name(),target)
+
+ def vm_links(self):
+ # Don't try to use user-vm if HOME is undefined
+ if os.environ.get('HOME') == None:
+ return [ self.system_vm_link() ]
+ else:
+ return [ self.user_vm_link(), self.system_vm_link() ]
+
+ def user_vm_link(self):
+ return os.path.join(os.environ.get('HOME'), '.gentoo/java-config-2/current-user-vm')
+
+ def system_vm_link(self):
+ return '/etc/java-config-2/current-system-vm'
+
+ def clean_classpath(self, targets):
+ for target in targets:
+ if os.path.isfile(target['file']):
+ try:
+ os.remove(target['file'])
+ except IOError:
+ raise PermissionError
+
+ def add_path_elements(self, elements, path):
+ if elements:
+ for p in elements.split(':'):
+ if p != '':
+ path.add(p)
+
+ def build_path(self, pkgs, query):
+ path = Set()
+ for lpath in self.query_packages(pkgs, query):
+ self.add_path_elements(lpath, path)
+
+ return path
+
+ def build_classpath(self, pkgs):
+ return self.build_path(pkgs, "CLASSPATH")
+
+ def get_pkg_deps(self, pkg):
+ """
+ Returns list of package's deps and optional deps.
+ Filters out optional deps that are not present.
+ """
+ deps = pkg.deps();
+ for opt_dep in pkg.opt_deps():
+ p = self.get_package(opt_dep[-1])
+ if p:
+ deps.append(opt_dep)
+
+ return deps
+
+ def add_dep_classpath(self, pkg, dep, classpath):
+ pkg_cp = pkg.classpath()
+ if pkg_cp:
+ if not dep or len(dep) == 1:
+ self.add_path_elements(pkg_cp, classpath)
+ else:
+ for cp in pkg_cp.split(':'):
+ if basename(cp) == dep[0]:
+ classpath.add(cp)
+
+ def build_dep_path(self, pkgs, query, missing_deps):
+ path = Set()
+
+ unresolved = Set()
+ resolved = Set()
+
+ for p in pkgs[:]:
+ pkg = self.get_package(p)
+ if pkg:
+ pkgs.remove(p)
+ lpath = pkg.query(query)
+ self.add_path_elements(lpath, path)
+ unresolved.add(pkg)
+
+ while len(unresolved) > 0:
+ pkg = unresolved.pop()
+ resolved.add(pkg)
+
+ if query != "CLASSPATH":
+ lpath = pkg.query(query)
+ self.add_path_elements(lpath, path)
+
+ for dep in self.get_pkg_deps(pkg):
+ p = self.get_package(dep[-1])
+
+ if p:
+ if p not in resolved:
+ unresolved.add(p)
+ if query == "CLASSPATH":
+ self.add_dep_classpath(p, dep, path)
+ else:
+ missing_deps.add(dep[-1])
+
+ return path
+
+ def add_pkg_env_vars(self, pkg, env):
+ """
+ Adds variables declared in `pkg`'s package.env via ENV_VARS
+ into the dictionary `env`
+ """
+ env_vars = pkg.query("ENV_VARS")
+ if (env_vars):
+ for var in env_vars.split(' '):
+ val = pkg.query(var)
+ assert val
+ if (not env.has_key(var)):
+ env[var] = val
+
+ def build_dep_env_vars(self, pkgs, missing_deps):
+ """
+ Returns a dictionary of variables declared via ENV_VARS in
+ package.env of all packages in list `pkgs` and all dependencies.
+ Encountered missing dependencies are recorded in `missing_deps`.
+ """
+ env = {}
+
+ unresolved = Set()
+ resolved = Set()
+
+ for p in pkgs:
+ pkg = self.get_package(p)
+ if pkg:
+ pkgs.remove(p)
+ unresolved.add(pkg)
+
+ while len(unresolved) > 0:
+ pkg = unresolved.pop()
+ resolved.add(pkg)
+
+ self.add_pkg_env_vars(pkg, env)
+
+ for dep in self.get_pkg_deps(pkg):
+ p = self.get_package(dep[-1])
+
+ if p:
+ if p not in resolved:
+ unresolved.add(p)
+ else:
+ missing_deps.add(dep[-1])
+ return env
+
+ def set_classpath(self, targets, pkgs):
+ classpath = self.build_classpath(pkgs)
+
+ if classpath:
+ self.clean_classpath(targets)
+
+ self.write_classpath(targets, classpath)
+
+ def get_old_classpath(self, target):
+ """Returns the current set classpath in the file"""
+ oldClasspath = ''
+ if os.path.isfile(target['file']):
+ try:
+ stream = open(target['file'], 'r')
+ except IOError:
+ raise PermissionError
+
+ for line in stream:
+ line = line.strip(' \n')
+ if line.find('CLASSPATH') != -1:
+ try:
+ oldClasspath = line.split(target['format'].split('%s')[-2])[-1].strip()
+ except:
+ pass
+ stream.close()
+
+ return oldClasspath
+
+ def append_classpath(self, targets, pkgs):
+ classpath = self.build_classpath(pkgs)
+
+ if classpath:
+ oldClasspath = None
+ for target in targets:
+ for cp in self.get_old_classpath(target).split(':'):
+ classpath.add(cp)
+
+ self.clean_classpath(targets)
+
+ self.write_classpath(targets, classpath)
+
+ def write_classpath(self, targets, classpath):
+ for target in targets:
+ dir = dirname(target['file'])
+ if not os.path.isdir(dir):
+ os.makedirs(dir)
+
+ try:
+ stream = open(target['file'], 'w')
+ except IOError:
+ raise PermissionError
+
+ stream.write(target['format'] % ("CLASSPATH", ':'.join(classpath)))
+ stream.close()
+
+ def have_provider(self, virtuals, virtualMachine, versionManager):
+ for virtualKey in virtuals.split():
+
+ if self.get_virtual(virtualKey):
+ if self.get_virtual(virtualKey).get_active_package():
+ # Virtual has active package
+ # We don't need to care about the vm.
+ return True
+ else:
+ if self.get_virtual(virtualKey)._config.has_key("VM"):
+ good_vm = self.get_virtual(virtualKey)._config["VM"]
+ if( good_vm and versionManager.version_satisfies(good_vm, virtualMachine) ):
+ return True
+ # Unable to find a suitable provider. Something must have gone wrong
+ # Either no Virtual or dependencies of virtual are missing.
+ return False
+
+# Singleton hack
+EnvironmentManager = EnvironmentManager()
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/Errors.py b/trunk/src/java_config_2/Errors.py
new file mode 100644
index 0000000..e7d8502
--- /dev/null
+++ b/trunk/src/java_config_2/Errors.py
@@ -0,0 +1,53 @@
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+class EnvironmentUndefinedError(Exception):
+ """
+ Environment Variable is undefined!
+ """
+
+class InvalidConfigError(Exception):
+ """
+ Invalid Configuration File
+ """
+ def __init__(self, file):
+ self.file = file
+
+class InvalidVMError(Exception):
+ """
+ Specified Virtual Machine does not exist or is invalid
+ """
+
+class ProviderUnavailableError(Exception):
+ """
+ No provider is available for the specified Virtual.
+ """
+
+ def __init__( self, virtual, vms, packages ):
+ self._virtual = virtual
+ self._vms = vms
+ self._packages = packages
+
+ def packages(self):
+ return self._packages
+
+ def virtual(self):
+ return self._virtual
+
+ def vms(self):
+ return self._vms
+
+class MissingOptionalsError(Exception):
+ """
+ Some optional utilities are missing from a valid VM
+ """
+
+class PermissionError(Exception):
+ """
+ The permission on the file are wrong or you are not a privileged user
+ """
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/FileParser.py b/trunk/src/java_config_2/FileParser.py
new file mode 100644
index 0000000..eae6185
--- /dev/null
+++ b/trunk/src/java_config_2/FileParser.py
@@ -0,0 +1,84 @@
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+from Errors import *
+import os
+
+
+class FileParser:
+ """
+ Parse some basic key=value configuration files.
+ Values are passed to the pair function.
+ """
+ def parse(self, file):
+ if not os.path.isfile(file):
+ raise InvalidConfigError(file)
+ if not os.access(file, os.R_OK):
+ raise PermissionError
+
+ stream = open(file, 'r')
+ for line in stream:
+ line = line.strip('\n')
+ if line.isspace() or line == '' or line.startswith('#'):
+ continue
+ else:
+ index = line.find('=')
+ name = line[:index]
+ value = line [index+1:]
+
+ if value == '':
+ continue
+ #raise InvalidConfigError(file)
+
+ value = value.strip('\\\'\"')
+
+ while value.find('${') >= 0:
+ item = value[value.find('${')+2:value.find('}')]
+
+ if self.config.has_key(item):
+ val = self.config[item]
+ else:
+ val = ''
+
+ value = value.replace('${%s}' % item, val)
+
+ self.pair(name,value)
+
+ stream.close()
+
+
+ def pair(self, key, value):
+ pass
+
+class EnvFileParser(FileParser):
+ """
+ Stores the configuation in a dictionary
+ """
+ def __init__(self, file):
+ self.config = {}
+ self.parse(file)
+
+ def pair(self, key, value):
+ self.config[key] = value
+
+ def get_config(self):
+ return self.config.copy()
+
+class PrefsFileParser(FileParser):
+ """
+ Stores it in a list.
+ """
+ def __init__(self, file):
+ self.config = []
+ self.parse(file)
+
+ def pair(self, key, value):
+ self.config.append([key,value.strip('\t ').split(' ')])
+
+ def get_config(self):
+ return self.config
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/OutputFormatter.py b/trunk/src/java_config_2/OutputFormatter.py
new file mode 100644
index 0000000..e79978a
--- /dev/null
+++ b/trunk/src/java_config_2/OutputFormatter.py
@@ -0,0 +1,124 @@
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+import os, sys
+
+class OutputFormatter:
+ codes = {
+ 'H': '\x1b[01m', # Bold
+ 'U': '\x1b[04m', # Underline
+ 'I': '\x1b[07m', # Inverse
+ 'b': '\x1b[34;01m', # Blue
+ 'B': '\x1b[34;06m', # Dark Blue
+ 'c': '\x1b[36;01m', # Cyan
+ 'C': '\x1b[36;06m', # Dark Cyan
+ 'g': '\x1b[32;01m', # Green
+ 'G': '\x1b[32;06m', # Dark Green
+ 'm': '\x1b[35;01m', # Magenta
+ 'M': '\x1b[35;06m', # Dark Magenta
+ 'r': '\x1b[31;01m', # Red
+ 'R': '\x1b[31;06m', # Dark Red
+ 'y': '\x1b[33;01m', # Yellow
+ 'Y': '\x1b[33;06m', # Dark Yellow
+ '$': '\x1b[0m', # Reset
+ '%': '%' # Percent
+ }
+
+ def __init__(self, displayColor=True, displayTitle=True, autoIndent=True):
+ self.colorOutput = displayColor
+ self.consoleTitle = displayTitle
+ self.autoIndent = autoIndent
+
+ if displayTitle and os.environ.has_key("TERM"):
+ if os.environ["TERM"] not in [ "xterm", "Eterm", "aterm", "rxvt" ]:
+ self.consoleTitle = False
+
+ def __call__(self, displayColor=True, displayTitle=True, autoIndent=True):
+ return self
+
+ def setColorOutputStatus(self, status):
+ self.colorOutput = status
+
+ def setDisplayTitleStatus(self, status):
+ if status and os.environ.has_key("TERM"):
+ if os.environ["TERM"] in [ "xterm", "Eterm", "aterm", "rxvt" ]:
+ self.consoleTitle = True
+ else:
+ self.consoleTitle = False
+ else:
+ self.consoleTitle = False
+
+ def isColorOutputEnabled(self):
+ return self.colorOutput
+
+ def isTitleDisplayEnabled(self):
+ return self.consoleTitle
+
+
+ def __setTitle(self, title):
+ if self.consoleTitle:
+ sys.stderr.write("\x1b]1;\x07\x1b]2;" + str(title) + "\x07")
+ sys.stderr.flush()
+
+ def __indent(self, prefix, message):
+ if self.autoIndent is True:
+ num = len(prefix)
+ return prefix + message.replace('\n', '\n'+' '*num)
+
+ else:
+ return prefix + message
+
+ def __parseColor(self, message):
+ colored = ''
+ striped = ''
+ replace = 0
+
+ for char in str(message):
+ if replace:
+ if char == ' ':
+ colored += self.codes['%'] + ' '
+ striped += self.codes['%'] + ' '
+ elif char == '%':
+ colored += self.codes[char]
+ striped += self.codes[char]
+ else:
+ colored += self.codes[char]
+ replace = 0
+ elif char == '%':
+ replace = 1
+ else:
+ colored += char
+ striped += char
+
+ if self.colorOutput:
+ return colored
+ else:
+ return striped
+
+ def write(self, message):
+ print self.__parseColor(message.strip())
+
+ def _print(self, message):
+ print self.__parseColor(message)
+
+ def _printError(self, message):
+ message = "%H%R" + self.__indent("!!! ERROR: ", message) + "%$"
+ sys.stderr.write(self.__parseColor(message) + '\n')
+
+ def _printWarning(self, message):
+ message = "%H%Y" + self.__indent("!!! WARNING: ", message) + "%$"
+ sys.stderr.write(self.__parseColor(message) + '\n')
+
+ def _printAlert(self, message):
+ message = "%H%C" + self.__indent("!!! ALERT: ", message) + "%$"
+ sys.stderr.write(self.__parseColor(message) + '\n')
+
+ def setTitle(self, message):
+ self.__setTitle(self.__parseColor(message))
+
+
+OutputFormatter = OutputFormatter()
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/Package.py b/trunk/src/java_config_2/Package.py
new file mode 100644
index 0000000..5135b1d
--- /dev/null
+++ b/trunk/src/java_config_2/Package.py
@@ -0,0 +1,88 @@
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+from FileParser import *
+
+class Package:
+ """
+ Class represeting an installed java package
+ """
+ def __init__(self, name, file = None):
+ self._file = file
+ self._name = name
+ if self._file:
+ self._config = EnvFileParser(file).get_config()
+ else:
+ self._config = {}
+
+ def __str__(self):
+ return self.name()
+
+ def name(self):
+ return self._name
+
+ def file(self):
+ return self._file
+
+ def description(self):
+ if self._config.has_key("DESCRIPTION"):
+ return self._config["DESCRIPTION"]
+ else:
+ return "No Description"
+
+ def classpath(self):
+ """
+ Returns this package's classpath
+ """
+ if self._config.has_key("CLASSPATH"):
+ return self._config["CLASSPATH"]
+ else:
+ return None
+
+ def query(self, var):
+ """
+ Return the value of the requested var form the env file
+ """
+ if self._config.has_key(var):
+ return self._config[var]
+ else:
+ return None
+
+ def deps(self):
+ """
+ Return all packages this package depends on
+ """
+ return self.__get_deps("DEPEND")
+
+ def opt_deps(self):
+ """
+ Return all packages this package optionally depends on
+ """
+ return self.__get_deps("OPTIONAL_DEPEND")
+
+ def provides(self):
+ """
+ Return the virtuals this package provides
+ """
+ pv = self.query('PROVIDES')
+ if pv:
+ return pv.split(" ")
+ return []
+
+ def __get_deps(self, query):
+ """
+ Internal function to get package's (optional) dependencies;
+ @param query: variable to read from package.env
+ """
+ depstr = self.query(query)
+ if depstr:
+ return [dep.split("@") for dep in depstr.split(":")]
+ else:
+ return []
+
+
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/VM.py b/trunk/src/java_config_2/VM.py
new file mode 100644
index 0000000..2cc29e2
--- /dev/null
+++ b/trunk/src/java_config_2/VM.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+from FileParser import *
+from Errors import *
+import os
+from string import upper
+
+
+class VM:
+ # Dont accept env files without these variables
+ needed_vars = [ "JAVA_HOME", "PROVIDES_TYPE", "PROVIDES_VERSION" ]
+
+ def __init__(self, file):
+ self.file = file
+ self.config = EnvFileParser(file).get_config()
+
+ for var in self.needed_vars:
+ if not self.config.has_key(var):
+ raise InvalidVMError("Missing: %s" %var)
+
+ def __cmp__(self, other):
+ return cmp(self.version(), other.version())
+
+ def __str__(self):
+ return self.name()
+
+ def get_config(self):
+ return self.config
+
+ def query(self, var):
+ if self.config.has_key(var):
+ return self.config[var]
+ else:
+ print "Undefined: " + var
+ raise EnvironmentUndefinedError
+
+ def filename(self):
+ return self.file
+
+ def name(self):
+ # TODO: MAKE THIS MODULAR!a (compnerd)
+ return self.file.split("/usr/share/java-config-2/vm/")[-1]
+
+ def is_jre(self):
+ return self.is_type("JRE")
+
+ def is_jdk(self):
+ return self.is_type("JDK")
+
+ def is_type(self, type):
+ if upper(type) in [upper(t) for t in self.query('PROVIDES_TYPE').split(' ')]:
+ return True
+ else:
+ return False
+
+ def type(self):
+ return self.query('PROVIDES_TYPE')
+
+ def version(self):
+ return self.query('PROVIDES_VERSION')
+
+ def find_exec(self, executable):
+ path = None
+
+ path = self.query('PATH')
+ paths = path.split(':')
+
+ for path in paths:
+ path = os.path.join(path, executable)
+
+ if os.path.isfile(path):
+ if not os.access(path, os.X_OK):
+ raise PermissionError
+ else:
+ return path
+ else:
+ raise PermissionError
+ return None
+
+ def get_provides(self):
+ if self.config.has_key('PROVIDES'):
+ return self.config['PROVIDES'].split(' ')
+ return []
+
+ def provides(self, virtuals):
+ for virtual in virtuals:
+ if self.config.has_key('PROVIDES'):
+ vp = self.config['PROVIDES'].split(' ')
+ if virtual not in vp:
+ return False
+ return True
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/VersionManager.py b/trunk/src/java_config_2/VersionManager.py
new file mode 100644
index 0000000..d8c8660
--- /dev/null
+++ b/trunk/src/java_config_2/VersionManager.py
@@ -0,0 +1,274 @@
+# -*- coding: UTF-8 -*-
+
+# Copyright 2005 Gentoo Foundation
+# Distributed under the terms of the GNU General Public license v2
+# $Header: $
+
+import sys
+sys.path.append("/usr/lib/portage/pym")
+
+import re
+from string import upper
+
+import VM, Errors
+from java_config_2.FileParser import *
+from java_config_2.EnvironmentManager import *
+import os, glob, re
+import os.path
+
+
+# Does not handle deps correctly
+# Does however do the right thing for the only types of deps we should see
+# Ignore blockers: portage doesn't support them in a way that is usefull for us
+class VersionManager:
+ """
+ Used to parse dependency strings, and find the best/prefered vm to use.
+ """
+ atom_parser = re.compile(r"([<>=]+)virtual/(jre|jdk)-([0-9\.*]+)")
+ virtuals_parser = re.compile(r"([<>=]+)?java-virtuals/(.*?)\s")
+ pref_files = ['/etc/java-config-2/build/jdk.conf', '/usr/share/java-config-2/config/jdk-defaults.conf']
+ _prefs = None
+
+ def __init__(self):
+ pass
+
+ def get_prefs(self):
+ if self._prefs:
+ return self._prefs
+ else:
+ self._prefs = []
+ for file in self.pref_files:
+ if os.path.exists(file):
+ self._prefs += PrefsFileParser(file).get_config()
+ return self._prefs
+
+ def parse_depend(self, atoms):
+ """Filter the dependency string for useful information"""
+ matched_atoms = []
+
+ import os
+ # gjl does not use use flags
+ try:
+ use = os.environ["USE"]
+
+ # Local import to avoid initializing portage elsewhere
+ from portage_dep import use_reduce,paren_reduce
+ from portage import flatten
+
+ # Normalize white space for Portage
+ atoms = " ".join(atoms.split())
+
+ # Remove conditional depends that are not turned on
+ atoms = " ".join(flatten(use_reduce(paren_reduce(atoms),uselist=use)))
+ except KeyError:
+ pass
+
+ # Should check if there are virtuals there
+
+ matches = self.atom_parser.findall(atoms)
+ virtuals_matches = self.virtuals_parser.findall(atoms)
+
+ if len(matches) > 0:
+ for match in matches:
+ matched_atoms.append({'equality':match[0], 'type':match[1], 'version':match[2]})
+
+ matched_atoms.sort()
+ matched_atoms.reverse()
+
+ return matched_atoms
+
+ def parse_depend_virtuals(self, atoms):
+ """Filter the dependency string for useful information"""
+ matched_atoms = []
+
+ import os
+ # gjl does not use use flags
+ try:
+ use = os.environ["USE"]
+
+ # Local import to avoid initializing portage elsewhere
+ from portage_dep import use_reduce,paren_reduce
+ from portage import flatten
+
+ # Normalize white space for Portage
+ atoms = " ".join(atoms.split())
+
+ # Remove conditional depends that are not turned on
+ atoms = " ".join(flatten(use_reduce(paren_reduce(atoms),uselist=use)))
+ except KeyError:
+ pass
+
+ # Should check if there are virtuals there
+
+ virtuals_matches = self.virtuals_parser.findall(atoms)
+
+ matched_virtuals = ""
+
+ for match in virtuals_matches:
+ matched_virtuals += " " + match[1]
+
+ return matched_virtuals
+
+ def matches(self, version_a, version_b, operator):
+ val = self.version_cmp(version_a, version_b)
+
+ if operator == '=': return val == 0
+ elif operator == '>=': return val >= 0
+ elif operator == '<=': return val <= 0
+ elif operator == '>': return val > 0
+ elif operator == '<': return val < 0
+ else: return False
+
+ def version_satisfies(self, atoms, vm):
+ version = vm.version()
+ matched_atoms = self.parse_depend(atoms)
+
+ for atom in matched_atoms:
+ if vm.is_type(atom['type']):
+ if self.matches(version, atom['version'], atom['equality']):
+ return True
+ return False
+
+ def get_lowest_atom(self, atoms):
+ lowest = None
+ for atom in atoms:
+ if not lowest:
+ lowest = atom
+ else:
+ if self.version_cmp(lowest['version'], atom['version']) > 0:
+ lowest = atom
+
+ if lowest:
+ return atom
+ else:
+ raise Exception("Couldn't find a VM dep")
+
+ def get_lowest(self, atoms):
+ atoms = self.parse_depend(atoms)
+ lowest = self.get_lowest_atom(atoms)
+ lowest = lowest['version']
+
+ if lowest:
+ return '.'.join(lowest.strip('*').split('.')[0:2])
+ else:
+ raise Exception("Couldn't find a VM dep")
+
+
+ def get_vm(self, atoms, need_virtual = None):
+ matched_atoms = self.parse_depend(atoms)
+ matched_virtuals = self.parse_depend_virtuals(atoms)
+
+ if len(matched_atoms) == 0:
+ return None
+ if len(matched_virtuals) == 0:
+ need_virtual = None
+ else:
+ need_virtual = matched_virtuals
+
+ prefs = self.get_prefs()
+
+ # first try to find vm based on preferences
+ low = self.get_lowest(atoms) # Lowest vm version we can use
+ for atom in matched_atoms:
+ for pref in prefs:
+ if pref[0] == low or pref[0] == "*": # We have a configured preference for this version
+ for vmProviderString in pref[1]: # Loop over the prefered once, and check if they are valid
+ gvm = self.find_vm(vmProviderString, atom)
+ if gvm:
+ if need_virtual: # Package we are finding a vm for needs a virtual
+ if gvm.provides(need_virtual): # we provide the virtual ourself good!
+ # Old way of doing, we no longer bother with PROVIDES
+ return gvm
+ else:
+ # New, correct way of searching for virtuals
+ if EnvironmentManager().have_provider(need_virtual, gvm, self): # We have a package available that provides it, will use that
+ return gvm
+ else:
+ return gvm # use it!
+
+ # no match in preferences, find anything we have
+ # Support for virtuals too here
+ for atom in matched_atoms:
+ gvm = self.find_vm("", atom)
+ if gvm:
+ if need_virtual: # Package we are finding a vm for needs a virtual
+ if gvm.provides(need_virtual): # we provide the virtual ourself good!
+ return gvm
+ else:
+ if EnvironmentManager().have_provider(need_virtual, gvm, self):
+ return gvm
+ else:
+ return gvm
+
+ # nothing found
+ raise Exception("Couldn't find suitable VM. Possible invalid dependency string.")
+
+
+ def find_vm(self, vmProviderString, atom):
+ vm_list = EnvironmentManager().find_vm(vmProviderString)
+ vm_list.sort()
+ vm_list.reverse()
+ for vm in vm_list:
+ if vm.is_type(atom['type']):
+ if self.matches(vm.version(), atom['version'], atom['equality']):
+ return vm
+ return None
+
+
+ def version_cmp(self, version1, version2):
+ #Parly stolen from portage.py
+ if version1 == version2:
+ return 0
+
+ version1 = version1.split('.')
+ version2 = version2.split('.')
+
+ check_len = None
+ for x in range(1, len(version1)):
+ if version1[x][-1] == '*':
+ version1[x] = version1[x][:-1]
+ check_len = x
+ if version1[x][0] == '0':
+ version1[x]='.' + version1[x]
+
+ for x in range(1, len(version2)):
+ if version2[x][-1] == '*':
+ version2[x] = version2[x][:-1]
+ if (not check_len) or (check_len and check_len > x):
+ check_len = x
+ if version2[x][0] == '0':
+ version2[x]='.' + version2[x]
+
+
+ if len(version2) < len(version1):
+ version2.extend(["0"]*(len(version1)-len(version2)))
+ elif len(version1) < len(version2):
+ version1.extend(["0"]*(len(version2)-len(version1)))
+
+ for x in range(0, len(version1)):
+ if check_len and x > check_len:
+ return 0
+ ret = float(version1[x]) - float(version2[x])
+ if ret != 0:
+ return ret
+ return 0
+
+#vator=VersionManager()
+#for i in [
+# ">=virtual/jdk-1.3",
+# ">=virtual/jdk-1.4",
+# ">=virtual/jdk-1.5",
+# "|| ( =virtual/jdk-1.4* =virtual/jdk-1.3* )",
+# "|| ( =virtual/jdk-1.3* =virtual/jdk-1.4* )",
+# "=virtual/jdk-1.5*",
+# "=virtual/jdk-1.4*",
+# "=virtual/jdk-1.3*",
+# ]:
+# print i
+# try:
+# print vator.get_vm(i)
+# except Exception, ex:
+# print ex
+# print
+
+# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/Virtual.py b/trunk/src/java_config_2/Virtual.py
new file mode 100644
index 0000000..bc286db
--- /dev/null
+++ b/trunk/src/java_config_2/Virtual.py
@@ -0,0 +1,220 @@
+# -*- coding: UTF-8 -*-
+
+# Copyright 2004-2007 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+from FileParser import *
+from Package import *
+import re, sys
+
+class Virtual(Package):
+ """
+ Class representing an installed java virtual.
+ """
+ def __init__(self, name, manager, file = None):
+ self._file = file
+ self._name = name
+ self._manager = manager
+
+ # Store possible installed packages and vms in arrays
+ self.providing_packages = ""
+ self.providing_vms = ""
+ self._packages = []
+ self._vms = []
+ self.active_package = None
+ self.needs_jdk = False
+ self.min_target = None
+ self.min_vm_target = None
+ self.loaded = False
+
+ if self._file:
+ self._config = EnvFileParser(file).get_config()
+ if self._config.has_key("PROVIDERS"):
+ self.providing_packages = self._config["PROVIDERS"].replace(" ", ", ")
+ temp_packages = self._config["PROVIDERS"].split(' ')
+ else:
+ temp_packages = []
+ if self._config.has_key("VM"):
+ self.providing_vms = self._config["VM"].replace(" ", ", ")
+ else:
+ self._config = {}
+ temp_packages = []
+
+ # Refactored to make __init__ smaller.
+ self.load_providers(temp_packages)
+
+ def load_providers(self, temp_packages):
+ # Now load system pref. Really should support
+ # List of packages instead of single package.
+ all_prefs = self._manager.get_virtuals_pref().get_config()
+ if all_prefs.has_key(self.name()):
+ if all_prefs[self.name()] in temp_packages:
+ self._packages.append(all_prefs[self.name()])
+ else:
+ if all_prefs.has_key('PREFER_UPSTREAM'):
+ for package in temp_packages:
+ if re.compile(all_prefs['PREFER_UPSTREAM'] + '*').match(package):
+ self._package.append(package)
+ break
+
+ for element in temp_packages:
+ if not element in self._packages:
+ self._packages.append(element)
+
+ def file(self):
+ # Investigate if anything uses this
+ # and whether what it should therefore return.
+ return self._file
+
+ def description(self):
+ if not self.use_active_package():
+ if self._manager.get_active_vm():
+ return self._name + ", Using: " + self._manager.get_active_vm().name()
+ return self.get_active_package().description()
+
+ def get_packages(self):
+ return self._packages
+
+ def classpath(self):
+ """
+ Returns this package's classpath
+ """
+ if not self.use_active_package():
+ if not self._config.has_key("VM_CLASSPATH"):
+ return ""
+ if self._manager.get_active_vm():
+ return self._manager.get_active_vm().query('JAVA_HOME') + self._config["VM_CLASSPATH"]
+ raise ProviderUnavailableError( self._name, self._providing_vms, self._providing_packages )
+ return self.get_active_package().classpath()
+
+ def query(self, var):
+ """
+ Return the value of the requested var from the env file
+ """
+ if (var == "TARGET"):
+ if self.loaded:
+ return self.min_target, self.needs_jdk
+ else:
+ self.load()
+ return self.min_target, self.needs_jdk
+
+ if( var == "CLASSPATH" ):
+ return self.classpath()
+
+ return ""
+
+ def deps(self):
+ """
+ Return all packages this package depends on
+ """
+ if not self.use_active_package():
+ return []
+ return self.get_active_package().deps()
+
+ def opt_deps(self):
+ """
+ Return all packages this package optionally depends on
+ """
+ if not self.use_active_package():
+ return []
+ return self.get_active_package().opt_deps()
+
+ def provides(self):
+ """
+ Return the virtuals this package provides
+ """
+ if not self.use_active_package():
+ if self._get_active_vm():
+ return self._manager.get_active_vm().provides()
+ return self.get_active_package().provides()
+
+ def needs_vm(self):
+ """
+ Return whether this Virtual requires a Virtual Machine.
+ """
+ return not self.use_active_package()
+
+ def get_active_package(self):
+ """
+ Return the active package package for the virtual.
+ """
+ if not self.loaded:
+ self.load()
+ return self.active_package
+
+ def use_active_package(self):
+ """
+ Return whether a package is to be used by the Virtual.
+ """
+ if not self.loaded:
+ self.load()
+
+ if not self._vms and not self.active_package:
+ raise ProviderUnavailableError( self._name, self.providing_vms, self.providing_packages )
+
+ # If no vm's then use active_package
+ if not self._vms and self.active_package:
+ return True
+
+ if self._vms:
+ import VersionManager
+ verman = VersionManager.VersionManager()
+ vm = self._manager.get_active_vm()
+ if vm and verman.version_satisfies( self._config["VM"], vm ):
+ # This is acceptable so return false
+ return False
+ else:
+ if not self.active_package:
+ available = ""
+ for vm in self._vms:
+ available = vm.name() + "\n"
+ raise ProviderUnavailableError( self._name, self.providing_vms, self.providing_packages )
+ else:
+ return True
+ return False
+
+ def load(self):
+ # Active package is the first available package
+ for package in self._packages:
+ # Improvement: we could put the VM in the list of providers
+ if self._manager.get_package(package) is not None:
+ self.active_package = self._manager.get_package(package)
+ # Set the minimum target version to the active package's target.
+ if self.active_package:
+ self.min_target = self.active_package.query("TARGET")
+
+ # Load possible vms. These are vm's that are installed.
+ vms = self._manager.get_virtual_machines()
+
+ if self._config.has_key("VM") and self._config["VM"]:
+ import VersionManager
+ verman = VersionManager.VersionManager()
+
+ # We assume that there was only one virtual/[jre|jdk] declared.
+ r = verman.parse_depend(self._config["VM"])[0]
+ version = r["version"]
+ if r["type"] == "jdk":
+ self.needs_jdk = True
+
+ for vm_index in vms:
+ vm = vms[vm_index]
+ if self.needs_jdk and not vm.is_jre:
+ continue
+ if verman.version_satisfies( self._config["VM"], vm ):
+ self._vms.append(vm)
+ if self.min_target:
+ if cmp(vm.version(), self.min_target) < 0:
+ self.min_target = vm.version()
+ else:
+ self.min_target = vm.version()
+ if self.min_vm_target:
+ if cmp(vm.version(), self.min_vm_target) < 0:
+ self.min_vm_target = vm.version()
+ else:
+ self.min_vm_target = vm.version()
+
+ #Set loaded to true, so function can determine what is going on
+ self.loaded = True
+
+#vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/trunk/src/java_config_2/__init__.py b/trunk/src/java_config_2/__init__.py
new file mode 100644
index 0000000..ac8a73d
--- /dev/null
+++ b/trunk/src/java_config_2/__init__.py
@@ -0,0 +1,5 @@
+'''
+java-config support files
+'''
+
+__version__ = '2.1.1'
diff --git a/trunk/src/launcher.bash b/trunk/src/launcher.bash
new file mode 100644
index 0000000..bf39409
--- /dev/null
+++ b/trunk/src/launcher.bash
@@ -0,0 +1,75 @@
+#!/bin/bash
+# Not-so-elegant? patches more then welcome
+
+abort() {
+ echo ${@} >&2
+ exit 1
+}
+
+# Source package env
+# ---------------------
+gjl_user_env="${HOME}/.gentoo/java-config-2/launcher.d/${gjl_package}"
+gjl_system_env="/etc/java-config-2/launcher.d/${gjl_package}"
+if [[ -f "${gjl_user_env}" ]]; then
+ source "${gjl_user_env}"
+elif [[ -f "${gjl_system_env}" ]]; then
+ source "${gjl_system_env}"
+fi
+
+# Build gjl arguments
+# ---------------------
+request="--package ${gjl_package} --get-args"
+
+if [[ -n ${gjl_main} ]]; then
+ gjl_starte=${gjl_main}
+elif [[ -n ${gjl_jar} ]]; then
+ request="${request} --get-jar ${gjl_jar}"
+else
+ # Check if the installed package has only one jar and use that
+ jars=$(java-config --classpath=${gjl_package})
+ if [[ "${jars/:}" = "${jars}" ]]; then
+ request="${request} --get-jar ${jars}"
+ else
+ abort "Need main or jar to start"
+ fi
+fi
+
+if [[ -z ${GENTOO_VM} ]]; then
+ request="${request} --get-vm"
+elif [[ -n ${GJL_DEBUG} ]]; then
+ echo "Detected \$GENTOO_VM is set, not trying to change vm" >&2
+fi
+
+# Get the information we need
+# ----------------------------
+[[ "${GJL_DEBUG}" ]] && echo "Calling: gjl ${request}"
+results=$(gjl ${request}) || abort "Couldn't get needed information"
+eval $results
+
+if [[ -n ${gjl_vm} ]]; then
+ export GENTOO_VM="${gjl_vm}"
+fi
+
+if [[ -z ${gjl_starte} ]]; then
+ abort "Dont know what to run :(("
+fi
+
+# Run it
+# --------
+
+# Rebuild arg list so it doesnt get messed up
+for arg in "${@}"; do
+ gjl_cmd_arg="${gjl_cmd_arg} \"${arg}\""
+done
+gjl_cmd="exec java ${gjl_args} ${gjl_java_args} ${gjl_starte} ${gjl_pkg_args} ${gjl_cmd_arg}"
+
+if [[ -n ${gjl_pwd} ]]; then
+ cd ${gjl_pwd}
+fi
+
+if [[ -n ${GJL_DEBUG} ]]; then
+ echo "Using: ${GENTOO_VM}" >&2
+ echo "Running: ${gjl_cmd}" >&2
+fi
+
+eval ${gjl_cmd}
diff --git a/trunk/src/profile.d/java-config-2.csh b/trunk/src/profile.d/java-config-2.csh
new file mode 100644
index 0000000..517a054
--- /dev/null
+++ b/trunk/src/profile.d/java-config-2.csh
@@ -0,0 +1,22 @@
+# Copyright 1999-2006 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License, v2 or later
+# $Header: /var/cvsroot/gentoo-x86/dev-java/java-config/files/java-config-2.profiled.csh,v 1.3 2007/01/13 17:17:08 grobian Exp $
+
+set gentoo_user_vm = "${HOME}/.gentoo/java-config-2/current-user-vm"
+set gentoo_system_vm = "/etc/java-config-2/current-system-vm"
+
+## If we have a current-user-vm (and aren't root)... set it to JAVA_HOME
+## Otherwise set to the current system vm
+if ( ( "$uid" != "0" ) && ( -l $gentoo_user_vm ) ) then
+ setenv JAVA_HOME $gentoo_user_vm
+else if ( -l $gentoo_system_vm ) then
+ setenv JAVA_HOME $gentoo_system_vm
+endif
+unset gentoo_user_vm gentoo_system_vm
+
+if ( $?JAVA_HOME ) then
+ # prepending to come before generation 1
+ setenv MANPATH "${JAVA_HOME}/man:${MANPATH}"
+ setenv JDK_HOME $JAVA_HOME
+ setenv JAVAC ${JDK_HOME}/bin/javac
+endif
diff --git a/trunk/src/profile.d/java-config-2.sh b/trunk/src/profile.d/java-config-2.sh
new file mode 100644
index 0000000..49155d1
--- /dev/null
+++ b/trunk/src/profile.d/java-config-2.sh
@@ -0,0 +1,34 @@
+# Copyright 1999-2006 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License, v2 or later
+# $Header: /var/cvsroot/gentoo-x86/dev-java/java-config/files/java-config-2.profiled.sh-r1,v 1.1 2007/03/16 11:13:16 betelgeuse Exp $
+
+# If we have a current-user-vm (and aren't root)... set it to JAVA_HOME
+gentoo_user_vm="${HOME}/.gentoo/java-config-2/current-user-vm"
+gentoo_system_vm="/etc/java-config-2/current-system-vm"
+
+# Please make sure that this script is POSIX compliant
+# See https://bugs.gentoo.org/show_bug.cgi?id=169925
+# for more details"
+
+if [ -z "${UID}" ] ; then
+ # id lives in /usr/bin which might not be mounted
+ if type id >/dev/null 2>/dev/null ; then
+ user_id=$(id -u)
+ else
+ [ "${USER}" = "root" ] && user_id=0
+ fi
+fi
+
+# The root user uses the system vm
+if [ "${user_id}" != 0 -a -L "${gentoo_user_vm}" ]; then
+ export JAVA_HOME=${gentoo_user_vm}
+# Otherwise set to the current system vm
+elif [ -L /etc/java-config-2/current-system-vm ]; then
+ export JAVA_HOME=${gentoo_system_vm}
+fi
+
+# prepending to come before generation 1
+export MANPATH="${JAVA_HOME}/man:${MANPATH}"
+export JDK_HOME=${JAVA_HOME}
+export JAVAC=${JDK_HOME}/bin/javac
+unset gentoo_user_vm gentoo_system_vm user_id
diff --git a/trunk/src/revdep-rebuild/60-java b/trunk/src/revdep-rebuild/60-java
new file mode 100644
index 0000000..1aca594
--- /dev/null
+++ b/trunk/src/revdep-rebuild/60-java
@@ -0,0 +1,9 @@
+# The VM dynamically loads these at runtime so they will end up as missing
+# but actually work just fine. See for example
+# https://bugs.gentoo.org/show_bug.cgi?id=152039
+#
+# This file should only have files the are used by things like swt. If there
+# are "broken" links inside the jre itself, the jre should install it's own
+# control file.
+
+LD_LIBRARY_MASK="libjvm.so libjawt.so"
diff --git a/trunk/src/run-java-tool b/trunk/src/run-java-tool
new file mode 100644
index 0000000..7ec2fcf
--- /dev/null
+++ b/trunk/src/run-java-tool
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+user_vm="${HOME}/.gentoo/java-config-2/current-user-vm"
+system_vm="/etc/java-config-2/current-system-vm"
+# Try GENTOO_VM
+if [[ -n ${GENTOO_VM} ]]; then
+ vmpath="/usr/lib/jvm/${GENTOO_VM}/"
+# Then user VM
+elif [[ -h ${user_vm} ]]; then
+ vmpath=$(readlink ${user_vm})
+# And fall back to the system VM
+else
+ vmpath=$(readlink ${system_vm})
+fi
+tool=$(basename $0)
+bin=${vmpath}/bin/${tool}
+jrebin=${vmpath}/jre/bin/${tool}
+
+vm_handle=$(basename ${vmpath})
+if [[ -x ${bin} ]]; then
+ exec ${bin} "${@}"
+elif [[ -x ${jrebin} ]]; then
+ exec ${jrebin} "${@}"
+else
+ if [[ ! -d ${vmpath} ]]; then
+ echo "* Home for VM '${vm_handle}' does not exist: ${vmpath}" >&2
+ if [[ -n ${GENTOO_VM} ]]; then
+ echo "* Invalid value for GENTOO_VM: ${GENTOO_VM}"
+ elif [[ -h ${user_vm} ]]; then
+ echo "* Invalid User VM: ${vm_handle}" >&2
+ else
+ echo "* Invalid System VM: ${vm_handle}" >&2
+ fi
+ else
+ if [[ ${tool} = "run-java-tool" ]]; then
+ echo "* run-java-tool was invoked directly" >&2
+ echo "* run-java-tool should only be used via symlinks to it" >&2
+ else
+ echo "* ${tool} is not available for ${vm_handle} on $(uname -m)" >&2
+ echo "* IMPORTANT: some Java tools are not available on some VMs on some architectures" >&2
+ fi
+ fi
+ exit 1
+fi
+
+