def _fix_classloader_problems(self): # Get path to jython jar jython_jar = None for path in sys.path: if '.jar' in path and 'jython' in path.lower(): jython_jar = path[:path.index('.jar') + 4] if jython_jar is None: raise Exception("Could not locate jython jar in path!") classloader = URLClassLoader( [URL("file://" + jython_jar)], JavaThread.currentThread().getContextClassLoader()) JavaThread.currentThread().setContextClassLoader(classloader)
def __init__(self, app): #name: reference code for this tool used for exmaple in 'config.cfg' self.name = self.title.lower().replace(" ", "_") if self.name in app.toolsStatus: self.isActive = app.toolsStatus[self.name] else: self.isActive = True #localization if self.isTranslated: localeDir = File.separator.join([self.app.SCRIPTDIR, "tools", "data", self.title.replace(" ", ""), "locale"]) urls = [File(localeDir).toURI().toURL()] loader = URLClassLoader(urls) currentLocale = Locale.getDefault() self.strings = ResourceBundle.getBundle("MessagesBundle", currentLocale, loader) if self.name == "favourites": self.title = self.strings.getString("Favourites") if self.name == "favourites": ref = "Favourites" else: ref = self.title.replace(" ", "") self.bigIcon = ImageIcon(File.separator.join([app.SCRIPTDIR, "tools", "data", ref, "icons", "tool_24.png"])) self.smallIcon = ImageIcon(File.separator.join([app.SCRIPTDIR, "tools", "data", ref, "icons", "tool_16.png"])) if not hasattr(self, "isLocal") or not self.isLocal: self.isLocal = False if self.name in app.toolsPrefs: self.update_preferences() if not hasattr(self, "markerPosition"): self.markerPosition = None self.views = [] for viewName, checksList in self.toolInfo.iteritems(): self.views.append(View(app, self, viewName, checksList))
def setupDatabaseOcsg(dsMap): try: jarPath = os.path.join(WL_HOME, "server", "lib", "mbeantypes", OCSG_UTIL_JAR) cl = URLClassLoader(jarray.array([File(jarPath).toURI().toURL()], URL)) clz = cl.loadClass(OCSG_UTIL_CLASS) m = clz.getMethod( "main", jarray.array([Class.forName("[Ljava.lang.String;")], Class)) m.invoke(None, jarray.array([dsMap[OCSG_DATASOURCE]], Object)) except Exception, ex: print "Unable to populate database", ex sys.exit(1)
def get_test_classes(self): urls = [ URL('file:' + os.path.abspath(self.test_classesdir) + '/'), URL('file:' + os.path.abspath(self.testjar)) ] urls.extend(URLClassLoader.getSystemClassLoader().getURLs()) loader = URLClassLoader(urls) for fname in [ name for name in self.get_java_files() if 'test' in name.lower() ]: classname = os.path.splitext(fname)[0] yield loader.loadClass(classname)
def make_jar_classloader(jar): import os from java.net import URL, URLClassLoader url = URL('jar:file:%s!/' % jar) if os._name == 'nt': # URLJarFiles keep a cached open file handle to the jar even # after this ClassLoader is GC'ed, disallowing Windows tests # from removing the jar file from disk when finished with it conn = url.openConnection() if conn.getDefaultUseCaches(): # XXX: Globally turn off jar caching: this stupid # instance method actually toggles a static flag. Need a # better fix conn.setDefaultUseCaches(False) return URLClassLoader([url])
def run(self, ctx): try: assert isinstance(ctx, IClientContext) loader = URLClassLoader([File(JAR_PATH).toURI().toURL()], self.getClass().getClassLoader()) instance = Class.forName(CLASS, True, loader).newInstance() assert isinstance(instance, AbstractEnginesPlugin) # 1. update ui bridge UIBridge = utils.get_object("com.yoavst.jeb.bridge.UIBridge", loader) UIBridge.update(ctx) print UIBridge # 2. Launch plugin utils.launch_plugin(instance, ctx, loader) return except: traceback.print_exc(file=sys.stdout)
def __init__(self): self.SCRIPTDIR = SCRIPTDIR #Localization urls = [ File(File.separator.join([self.SCRIPTDIR, "data", "locale"])).toURI().toURL() ] loader = URLClassLoader(urls) currentLocale = Locale.getDefault() self.strings = ResourceBundle.getBundle("MessagesBundle", currentLocale, loader) #Read config self.favZone = None self.zones = None self.config = ConfigLoader(self) """Build tools instances""" self.allTools = AllTools(self).tools for tool in self.allTools: if tool.name == "favourites": self.favouritesTool = tool break self.realTools = [ tool for tool in self.allTools if tool.name not in ("favourites", "localfile") ] #remove tools disabled from config file self.tools = [ tool for tool in self.allTools if tool.isActive or tool.name in ("favourites") ] #add favourite checks to Favourites tool if "favourites" in self.toolsPrefs: favChecks = self.toolsPrefs["favourites"]["checks"] if favChecks != "": for favCheck in favChecks.split("|"): (toolName, viewName, checkName) = favCheck.split(".") for tool in self.tools: if tool.name == toolName: for view in tool.views: if view.name == viewName: for check in view.checks: if check.name == checkName: self.favouritesTool.views[ 0].checks.append(check) """Build dialog for manual reporting of false positive""" self.falsePositiveDlg = FalsePositiveDialog( Main.parent, self.strings.getString("false_positives_title"), True, self) """Build qat_script toggleDialog""" #BUG: it steals icon from validator. #Is it possible ot use an icon not from 'dialogs' dir? icon = "validator.png" self.dlg = QatDialog(self.strings.getString("qat_dialog_title"), icon, "Show ", None, 250, self) self.create_new_dataset_if_empty() Main.map.addToggleDialog(self.dlg) """Build processing dialog""" self.downloadAndReadDlg = DownloadAndReadDialog( Main.parent, self.strings.getString("download_dialog_title"), False, self) """Build quality assurance tools menu""" self.menu = QatMenu(self, "QA Tools") menu.add(self.menu) menu.repaint() """Initialization""" #Read ids of OSM objects that the user wants to be ignored self.ignore_file = File.separator.join( [self.SCRIPTDIR, "data", "ignoreids.csv"]) self.read_ignore() self.falsePositive = [] # info regarding false positive self.selectedTool = self.tools[0] self.selectedView = self.selectedTool.views[0] # first view self.selectedTableModel = self.selectedView.tableModel self.selectedChecks = [] self.downloadingChecks = [] self.clickedError = None self.errorsData = None self.zoneBbox = None # bbox of current JOSM view self.selectedError = None self.url = None # url of errors self.errorLayers = [] # list of layers with error markers self.selectionChangedFromMenuOrLayer = False self.dlg.toolsCombo.setSelectedIndex(0) print "\nINFO: Quality Assurance Tools script is running: ", self.SCRIPTVERSION # Check if using the latest version if self.checkUpdate == "on": update_checker.Updater(self, "auto")
#!/usr/bin/env jython import sys, inspect, os cucumber_jython_shaded_path = os.path.dirname( inspect.getfile(inspect.currentframe())) + "/cucumber-jython-shaded.jar" sys.path.append(cucumber_jython_shaded_path) from java.io import File from java.net import URLClassLoader from cucumber.api.cli import Main from cucumber.runtime import Runtime from cucumber.runtime.jython import JythonBackend cl = URLClassLoader([File(cucumber_jython_shaded_path).toURL()], Main.getClassLoader()) Main.run(sys.argv[1:], cl)
#os.path.join(_base, "slf4j-log4j12-1.7.21.jar"), os.path.join(_base, "antlr-runtime-4.5.3.jar"), os.path.join(_base, "cglib-nodep-3.2.4.jar") ] for lib in ESPER_LIBS: print(lib) sys.path.append(lib) def initialize_log4j(): try: from org.apache.log4j import (ConsoleAppender, Level, Logger, PatternLayout) rootLogger = Logger.getRootLogger() print(dir(rootLogger)) rootLogger.level = Level.DEBUG layout = PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n") appender = ConsoleAppender(layout) rootLogger.addAppender(appender) except: import traceback print(traceback.format_exc()) from java.lang import Thread, ClassLoader from java.net import URLClassLoader, URL esperClassLoader = URLClassLoader([URL("file:" + lib) for lib in ESPER_LIBS], ClassLoader.getSystemClassLoader())
def __init__(self, url): AppResourceLoader.__init__(self) classloader = URLClassLoader(array((url, ), URL)) self.setClassLoader(classloader)
from java.net import URL, URLClassLoader # TODO: Generalize path. url = URL('file:///home/curtis/minecraft/python/mcx/mcx.jar') cl = URLClassLoader([url]) try: gol3d = cl.loadClass('GameOfLife3D') golFactory = gol3d.getConstructors()[0] except: print('Failed to load GameOfLife3D Java code.') def golfast(world, xMin, xMax, yMin, yMax, zMin, zMax, max_adjacent_dims=3, birth_min=6, birth_max=6, starvation_max=3, suffocation_min=8): if not golFactory: print('Sorry, the golfast function is not available.') return return golFactory.newInstance(world, xMin, xMax, yMin, yMax, zMin, zMax, max_adjacent_dims, birth_min, birth_max, starvation_max, suffocation_min)
def getClassloader(): jarPath = os.path.join(OCSG_HOME, "modules", CONFIG_JAR) classLoader = URLClassLoader( jarray.array([File(jarPath).toURI().toURL()], URL)) return classLoader
#!/usr/bin/env jython import sys, inspect, os jar_path = os.path.dirname(inspect.getfile( inspect.currentframe())) + "/cucumber-jython-full.jar" sys.path.append(jar_path) from java.io import File from java.net import URLClassLoader from cucumber.cli import Main from cucumber.runtime import Runtime from cucumber.runtime.jython import JythonBackend url = File(jar_path).toURL() cl = URLClassLoader([url], Main.getClassLoader()) def createRuntime(resourceLoader, gluePaths, classLoader, dryRun): # TODO - pass in current jython runtime - PythonInterpreter jythonBackend = JythonBackend(resourceLoader) return Runtime(resourceLoader, gluePaths, classLoader, [jythonBackend], dryRun) Main.run(sys.argv[1:], cl)