PyLucene 3.4.0-1 import
[pylucene.git] / jcc / jcc / windows.py
1 #   Licensed under the Apache License, Version 2.0 (the "License");
2 #   you may not use this file except in compliance with the License.
3 #   You may obtain a copy of the License at
4 #
5 #       http://www.apache.org/licenses/LICENSE-2.0
6 #
7 #   Unless required by applicable law or agreed to in writing, software
8 #   distributed under the License is distributed on an "AS IS" BASIS,
9 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 #   See the License for the specific language governing permissions and
11 #   limitations under the License.
12
13 import os, _winreg
14
15
16 class WindowsRegistry(object):
17
18     def __init__(self):
19         self.handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
20
21     def get(self, key, name):
22
23         handle = None
24         try:
25             handle = _winreg.OpenKey(self.handle, key)
26             return _winreg.QueryValueEx(handle, name)[0]
27         finally:
28             if handle is not None:
29                 handle.Close()
30
31     def close(self):
32         self.handle.Close()
33
34
35 def get_jvm_dll_directory(client_or_server="client"):
36
37     jre_key = r"SOFTWARE\JavaSoft\Java Runtime Environment"
38     jdk_key = r"SOFTWARE\JavaSoft\Java Development Kit"
39     current_key = r"%s\%s"
40
41     registry = None
42     try:
43         registry = WindowsRegistry()
44
45         try: # try JRE
46             version = registry.get(jre_key, "CurrentVersion")
47             path = registry.get(current_key %(jre_key, version), "JavaHome")
48             if not os.path.exists(path):
49                 path = None
50         except:
51             path = None
52
53         if not path:
54             try: # try JDK
55                 version = registry.get(jdk_key, "CurrentVersion")
56                 path = registry.get(current_key %(jdk_key, version), "JavaHome")
57                 if os.path.exists(path):
58                     path = os.path.abspath(os.path.join(path, "jre"))
59                 else:
60                     path = None
61             except:
62                 path = None
63
64     finally:
65         if registry is not None:
66             registry.close()
67
68     if path:
69         path = os.path.abspath(os.path.join(path, "bin", client_or_server))
70         if os.path.exists(os.path.join(path, "jvm.dll")):
71             return path
72
73     return None
74
75
76 def add_jvm_dll_directory_to_path():
77
78     path = os.environ['Path'].split(os.pathsep)
79     dll_path = get_jvm_dll_directory()
80     if dll_path is not None:
81         path.append(dll_path)
82         os.environ['Path'] = os.pathsep.join(path)
83         return True
84
85     raise ValueError, "jvm.dll could not be found"