Skip to content

Commit

Permalink
Enhanced PYTHONPATH detection for Java version (#75)
Browse files Browse the repository at this point in the history
Fixes #71
  • Loading branch information
Mihai Pârvu authored Nov 21, 2018
1 parent 74e24d8 commit 3188cfc
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 27 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</parent>
<groupId>org.robotframework</groupId>
<artifactId>remoteswinglibrary</artifactId>
<version>2.2.2</version>
<version>2.2.3</version>
<packaging>jar</packaging>

<name>robotframework-remoteswinglibrary</name>
Expand Down
61 changes: 37 additions & 24 deletions src/main/python/RemoteSwingLibrary.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
from robot.libraries.Process import Process
from robot.libraries.Remote import Remote
from robot.libraries.BuiltIn import BuiltIn, run_keyword_variant
from robot.utils import timestr_to_secs, get_link_path
from robot.utils import timestr_to_secs, get_link_path, is_string
from robotbackgroundlogger import BackgroundLogger

logger = BackgroundLogger()
Expand Down Expand Up @@ -115,7 +115,7 @@ def _tobool(value):
return str(value).lower() in ("true", "1", "yes")


__version__ = '2.2.2'
__version__ = '2.2.3'


class RemoteSwingLibrary(object):
Expand Down Expand Up @@ -200,30 +200,36 @@ class RemoteSwingLibrary(object):
AGENT_PATH = os.path.abspath(os.path.dirname(__file__))
POLICY_FILE = None
_output_dir = ''
JAVA9_OR_NEWER = None
JAVA9_OR_NEWER = False

def _remove_policy_file(self):
if self.POLICY_FILE and os.path.isfile(self.POLICY_FILE):
os.remove(self.POLICY_FILE)
self.POLICY_FILE = None

def _java9_or_newer(self):
version = self._read_java_version()
return float(version) >= 1.9
try:
version = float(self._read_java_version())
except:
logger.warn('Failed to auto-detect Java version. Assuming Java is older than 9. To run in newer Java'
'compatibility mode set java9_or_newer=True when importing the library.')
return False
return version >= 1.9

def _read_java_version(self):
@staticmethod
def _read_java_version():
def read_python_path_env():
if 'PYTHONPATH' in os.environ:
classpath = os.environ['PYTHONPATH'].split(os.pathsep)
for path in classpath:
if 'remoteswinglibrary' in path:
return path
if 'remoteswinglibrary' in path.lower():
return str(path)
return None

def read_sys_path():
for item in sys.path:
if 'remoteswinglibrary' in item and '.jar' in item:
return item
if 'remoteswinglibrary' in item.lower() and '.jar' in item.lower():
return str(item)
return None

def construct_classpath(location):
Expand All @@ -233,40 +239,48 @@ def construct_classpath(location):
return classpath

location = read_python_path_env() or read_sys_path()
os.environ['CLASSPATH'] = construct_classpath(location)
if location:
os.environ['CLASSPATH'] = construct_classpath(location)

p = subprocess.Popen(['java', 'org.robotframework.remoteswinglibrary.ReadJavaVersion'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=os.environ)
version, err = p.communicate()
return version

def __init__(self, port=0, debug=False):
def __init__(self, port=0, debug=False, java9_or_newer='auto-detect'):
"""
*port*: optional port for the server receiving connections from remote agents
``port``: optional port for the server receiving connections from remote agents
*debug*: optional flag that will start agent in mode with more logging for troubleshooting (set to TRUE to enable)
``debug``: optional flag that will start agent in mode with more logging for troubleshooting
(set to ``True`` to enable)
``java9_or_newer``: optional flag that by default will try to automatically detect if Java version is greater
than 8. If it fails to detect, manually set it to ``True`` or ``False`` accordingly. If the value is different
from ``true``, ``1`` or ``yes`` (case insensitive) it will default to ``False``.
*Note:* RemoteSwingLibrary is a so called Global Scope library. This means when it is imported once it will be
available until end of robot run. Parameters used in imports from others suites will be ignored.
If you need to change import options between suites, please use `Reinitiate` keyword.
"""

self._initiate(port, debug)
self._initiate(port, debug, java9_or_newer)

if os.path.exists(self._output("remote-stderr")):
shutil.rmtree(self._output("remote-stderr"))
if os.path.exists(self._output("remote-stdout")):
shutil.rmtree(self._output("remote-stdout"))

def _initiate(self, port=0, debug=False):
def _initiate(self, port=0, debug=False, java9_or_newer='auto-detect'):
if RemoteSwingLibrary.DEBUG is None:
RemoteSwingLibrary.DEBUG = _tobool(debug)
if RemoteSwingLibrary.PORT is None:
RemoteSwingLibrary.PORT = self._start_port_server(int(port))
if RemoteSwingLibrary.JAVA9_OR_NEWER is None:
if java9_or_newer == 'auto-detect':
RemoteSwingLibrary.JAVA9_OR_NEWER = _tobool(self._java9_or_newer())
elif _tobool(java9_or_newer):
RemoteSwingLibrary.JAVA9_OR_NEWER = True
try:
BuiltIn().set_global_variable('\${REMOTESWINGLIBRARYPATH}',
self._escape_path(RemoteSwingLibrary.AGENT_PATH))
Expand All @@ -275,7 +289,7 @@ def _initiate(self, port=0, debug=False):
except RobotNotRunningError:
pass

def reinitiate(self, port=0, debug=False):
def reinitiate(self, port=0, debug=False, java9_or_newer='auto-detect'):
"""
Restarts RemoteSwingLibrary with new import parameters.
"""
Expand All @@ -287,7 +301,7 @@ def reinitiate(self, port=0, debug=False):
RemoteSwingLibrary.TIMEOUT = 60
self._remove_policy_file()

self._initiate(port, debug)
self._initiate(port, debug, java9_or_newer)

@property
def current(self):
Expand Down Expand Up @@ -355,7 +369,7 @@ def set_java_tool_options(self, close_security_dialogs=True, remote_port=0):
en_us_locale = "-Duser.language=en -Duser.country=US "
self._create_env(close_security_dialogs, remote_port)
logger.info("Java version > 9: " + str(RemoteSwingLibrary.JAVA9_OR_NEWER))
if RemoteSwingLibrary.JAVA9_OR_NEWER:
if RemoteSwingLibrary.JAVA9_OR_NEWER is True:
self._agent_command += ' --add-exports=java.desktop/sun.awt=ALL-UNNAMED'
os.environ['JAVA_TOOL_OPTIONS'] = en_us_locale + self._agent_command
logger.debug("Set JAVA_TOOL_OPTIONS='%s%s'" % (en_us_locale, self._agent_command))
Expand Down Expand Up @@ -576,10 +590,9 @@ def log_java_system_properties(self):
"""
env = self._run_from_services('getEnvironment')
logger.info(env)
if IS_PYTHON3:
return env.decode("utf_8")
else:
return env
if IS_PYTHON3 and not is_string(env):
return env.decode('utf-8')
return env

def get_keyword_names(self):
overrided_keywords = ['startApplication',
Expand Down
9 changes: 7 additions & 2 deletions src/test/robotframework/acceptance/webstart.robot
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
*** Settings ***
Library RemoteSwingLibrary debug=True
Library FileServer
Library OperatingSystem
Suite Setup FileServer.Start
Suite Teardown FileServer.Stop
Suite Teardown Clean Up
Force tags Webstart

*** Variables ***
${WEBSTART DIR}= ${CURDIR}/webstart


*** Test Cases ***
Webstart Test
[Timeout] 60 seconds
Expand All @@ -17,3 +17,8 @@ Webstart Test
Select Main Window
List Components In Context
Ensure Application Should Close 5 seconds Push Button systemExitButton

*** Keywords ***
Clean Up
FileServer.Stop
Remove Files *.png

0 comments on commit 3188cfc

Please sign in to comment.