aboutsummaryrefslogtreecommitdiff
blob: c2cca4bfb6c5bdcad54dcc395868cfab5de9ae81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/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 import __version__
from java_config.OutputFormatter import OutputFormatter
from java_config.EnvironmentManager import EnvironmentManager
from java_config.Errors import *
from java_config.versionator import *

import os
import sys
from commands import getoutput

from optparse import OptionParser, make_option


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 java(option, opt, value, parser):
    try:
        printer._print(manager.get_active_vm().find_exec('java'))
    except PermissionError:
        printer._printError("The java executable was not found in the Java path")
    except InvalidVMError:
        printer._printError("The active vm could not be found")

def javac(option, opt, value, parser):
    try:
        printer._print(manager.get_active_vm().find_exec('javac'))
    except PermissionError:
        printer._printError("The javac executable was not found in the Java path")
    except InvalidVMError:
        printer._printError("The active vm could not be found")

def jar(option, opt, value, parser):
    try:
        printer._print(manager.get_active_vm().find_exec('jar'))
    except PermissionError:
        printer._printError("The jar executable was not found in the Java path")
    except InvalidVMError:
        printer._printError("The active vm could not be found")

def jdk_home(option, opt, value, parser):
    try:
        printer._print(manager.get_active_vm().query('JDK_HOME'))
    except EnvironmentUndefinedError:
        print
    except InvalidVMError:
        printer._printError("The active vm could not be found")

def jre_home(option, opt, value, parser):
    try:
        printer._print(manager.get_active_vm().query('JRE_HOME'))
    except EnvironmentUndefinedError:
        print
    except InvalidVMError:
        printer._printError("The active vm could not be found")

def runtime(option, opt, value, parser):
    try:
        printer._print(manager.get_active_vm().query('BOOTCLASSPATH'))
    except EnvironmentUndefinedError:
        print
    except InvalidVMError:
        printer._printError("The active vm could not be found")


def show_active_vm(option, opt, value, parser):
    try:
        printer._print(manager.get_active_vm().name())
    except InvalidVMError:
        printer._printError("The active vm could not be found")

def java_version(option, opt, value, parser):
    try:
        printer._print(getoutput('%s -version' % manager.get_active_vm().find_exec('java')))
    except PermissionError:
        printer._printError("The java executable was not found in the Java path")
    except InvalidVMError:
        printer._printError("The active vm could not be found")

def classpath(option, opt, value, parser):
    packages = value.split(',')
    classpath = manager.query_packages(packages, "CLASSPATH")

    for package in packages:
        printer._printError("Package %s was not found!" % package)

    printer._print(':'.join(classpath))

def get_env(option, opt, value, parser):
    try:
        for env in value.split(','):
            printer._print(manager.get_active_vm().query(env))
    except EnvironmentUndefinedError:
        print
    except InvalidVMError:
        printer._printError("The active vm could not be found")

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():
        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

    for i, vm in vm_list.iteritems():
        if vm is active:
            printer._print('%H%G' + '*) %s [%s] (%s)' % (vm.query('VERSION'), vm.name(), vm.filename()) + '%$')
        else:
            if vm.is_jdk():
                printer._print('%H' + '%i) %s [%s] (%s)' % (i, vm.query('VERSION'), vm.name(), vm.filename()) + '%$')
            else:
                printer._print('%i) %s [%s] (%s)' % (i, vm.query('VERSION'), vm.name(), vm.filename()) + '%$')

# TODO: FIX THIS!!
# Should be able to print in CSH or SH compatible format
def print_environment(option, opt, value, parser):
    # Possibly Unneeded
    """
    config = manager.get_vm(value).get_config()
    """
    manager.create_env_entry(manager.get_vm(value), printer, "%s=%s")

def set_system_vm(option, opt, value, parser):
    vm = manager.get_vm(value)

    if os.getuid() is 0:
        if vm.is_jre():
            printer._printWarning("The specified VM is a JRE! It is suggested you use a JDK!")

        try:
            manager.set_system_vm(vm)
        except PermissionError:
            printer._printError("You do not have enough permissions to set the system VM!")
        except EnvironmentUndefinedError:
            printer._printError("The selected VM is missing critical environment variables.")
    else:
        printer._printError("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 os.getuid() is 0:
        printer._printError("The user 'root' should always use the System VM")
    else:
        try:
            manager.set_user_vm(vm)
        except PermissionError:
            printer._printError("You do not have enough permissions to set the VM!")

def set_system_classpath(option, opt, value, parser):
    # TODO: MAKE THIS MODULAR!!
    env_file = os.path.join('/', 'etc', 'env.d', '21java-classpath')

    if os.getuid() is 0:
        manager.set_classpath(env_file, value.split(","))
        update_env()
    else:
       printer._printError("You do not have enough permissions to set the system classpath!")

def set_user_classpath(option, opt, value, parser):
    # TODO: MAKE THIS MODULAR!!
    env_file = os.path.join(os.environ.get("HOME"), '.gentoo', 'java-classpath')

    manager.set_classpath(env_file, value.split(","))

def append_system_classpath(option, opt, value, parser):
    # TODO: MAKE THIS MODULAR!!
    env_file = os.path.join('/', 'etc', 'env.d', '21java-classpath')

    if os.getuid() is 0:
        manager.append_classpath(env_file, value.split(','))
        update_env()
    else:
        printer._printError("You do not have enough permissioins to append to the system classpath!")

def append_user_classpath(option, opt, value, parser):
    # TODO: MAKE THIS MODUlAR!!
    env_file = os.path.join(os.environ.get("HOME"), '.gentoo', 'java-classpath')

    manager.append_classpath(env_file, value.split(','))

    update_env()

def clean_system_classpath(option, opt, value, parser):
    # TODO: MAKE THIS MODULAR!!
    env_file = os.path.join('/', 'etc', 'env.d', '21java-classpath')

    if os.getuid() is 0:
        manager.clean_classpath(env_file)
        update_env()
    else:
        printer._printError("You do not have enough permissions to clean the system classpath!")

def clean_user_classpath(option, opt, value, parser):
    # TODO: MAKE THIS MODULAR!!
    env_file = os.path.join(os.environ.get("HOME"), '.gentoo', 'java-classpath')

    manager.clean_classpath(env_file)
    update_env()

def library(option, opt, value, parser):
    packages = value.split(',')
    library = manager.query_packages(packages, "LIBRARY_PATH")

    for package in packages:
        printer._printError("Package %s was not found!" % package)

    printer._print(':'.join(library))
    
def select_vm(option, opt, value, parser):
    manager.set_active_vm(manager.get_vm(value))

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\nyour environment by running:\nsource /etc/profile")



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 ("-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 ("-O", "--jdk-home",                action="callback", callback=jdk_home,                  help="Print the location of the active JDK home"),
                     make_option ("-o", "--jre-home",                action="callback", callback=jre_home,                  help="Print the location of the active JRE home"),
                     make_option ("-r", "--runtime",                 action="callback", callback=runtime,                   help="Print the runtime classpathh"),
                     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 ("-p", "--classpath",               action="callback", callback=classpath,                 help="Print entries in the environment classpath",               type="string", dest="package"),
                     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 ("-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-packages", action="callback", callback=list_available_packages,   help="List all available packages on the system."),
                     make_option ("-L", "--list-available-vms",      action="callback", callback=list_available_vms,        help="List available Java Virtual Machines"),
                     make_option ("-P", "--print",                   action="callback", callback=print_environment,         help="Print the environment for the specified VM",               type="string", dest="vm"),
                     make_option ("-S", "--set-system-vm",           action="callback", callback=set_system_vm,             help="Set the default Java VM for the system",                   type="string", dest="SystemVM"),
                     make_option ("-s", "--set-user-vm",             action="callback", callback=set_user_vm,               help="Set the default Java VM for the user",                     type="string", dest="UserVM"),
                     make_option ("-A", "--set-system-classpath",    action="callback", callback=set_system_classpath,      help="Set the system classpath to include the libraries",        type="string", dest="SetSystemCP" ),
                     make_option ("-a", "--set-user-classpath",      action="callback", callback=set_user_classpath,        help="Set the user classpath to include the libraries",          type="string", dest="SetUserCP"),
                     make_option ("-B", "--append-system-classpath", action="callback", callback=append_system_classpath,   help="Append the libraries to the system classpath",             type="string", dest="AppendSystemCP"),
                     make_option ("-b", "--append-user-classpath",   action="callback", callback=append_user_classpath,     help="Append the libraries to the user classpath",               type="string", dest="AppendUserCP"),
                     make_option ("-X", "--clean-system-classpath",  action="callback", callback=clean_system_classpath,    help="Clean the current system classpath"),
                     make_option ("-x", "--clean-user-classpath",    action="callback", callback=clean_user_classpath,      help="Clean the current user classpath"),
                     make_option (""  , "--select-vm",               action="callback", callback=select_vm,                 help="Use this vm when returning information not the active vm", type="string", dest="vm"),
                     make_option ("-i", "--library",                 action="callback", callback=library,                   help="Print entries in the package library")
                   ]

    parser = OptionParser(usage, options_list)
    (options, args) = parser.parse_args()

# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap: