def test_host_lookup(): import java try: strClass = java.type("java.lang.String") assert strClass.valueOf(True) == "true" except NotImplementedError as e: assert "host lookup is not allowed" in str(e) try: java.type("this.type.does.not.exist") except NotImplementedError as e: assert "host lookup is not allowed" in str(e) except KeyError as e: assert True else: assert False, "requesting a non-existing host symbol should raise KeyError"
def test_non_index_array_access(): import java try: al = java.type("java.util.ArrayList")() assert al.size() == len(al) == 0 except IndexError: assert False, "using __getitem__ to access keys of an array-like foreign object should work" except NotImplementedError as e: assert "host lookup is not allowed" in str(e)
def test_direct_call_of_truffle_object_methods(): import java try: al = java.type("java.util.ArrayList")() assert al.__len__() == al.size() == len(al) except IndexError: assert False, "calling the python equivalents for well-known functions directly should work" except NotImplementedError as e: assert "host lookup is not allowed" in str(e)
def __setup__(*args): import os __dir__ = os.path.dirname(__file__) javafile = os.path.join(__dir__, "Image.java") with open(javafile, "w") as f: f.write(JAVA_CODE) os.system("javac " + javafile) import java java.add_to_classpath(__dir__) global Image Image = java.type("Image")
def test_java_imports(): import java try: al = java.type("java.util.ArrayList")() except NotImplementedError as e: assert "host lookup is not allowed" in str(e) else: import java.util.ArrayList assert repr(java.util.ArrayList()) == "[]" from java.util import ArrayList assert repr(ArrayList()) == "[]" assert java.util.ArrayList == ArrayList
def test_foreign_slice_setting(): import java il = java.type("int[]")(20) try: il[0:2] = 1 except TypeError: assert True else: assert False, "should throw a type error" il[0] = 12 assert il[0] == 12 il[0:10] = [10] * 10 assert list(il) == [10] * 10 + [0] * 10, "not equal" try: il[0] = 1.2 except TypeError: assert True else: assert False, "should throw a type error again"
def test_java_imports(): import java try: al = java.type("java.util.ArrayList")() except NotImplementedError as e: assert "host lookup is not allowed" in str(e) else: import java.util.ArrayList assert repr(java.util.ArrayList()) == "[]" from java.util import ArrayList assert repr(ArrayList()) == "[]" if __graalpython__.jython_emulation_enabled: assert java.util.ArrayList == ArrayList import sun assert type(sun.misc) is type(java) import sun.misc.Signal assert sun.misc.Signal is not None
def ghidraal_import(name, globals=None, locals=None, fromlist=(), level=0): if _ghidraal_use_jythonic_imports: try: return _ghidraal_original_import(name, globals=globals, locals=locals, fromlist=fromlist, level=level) except ModuleNotFoundError as module_not_found: for pn in _ghidraal_package_names: # hide packages from the Jython JAR (see import logic in # Python's standard copy module, for example) if pn.startswith('org.python.'): continue namedot = name + '.' if pn == name or pn.startswith(namedot): # *** looks like name is a Java package name if fromlist is None or len(fromlist)==0: # peel off first bit _after_ java b = _ghidraal_original_import('java.%s' % name, globals=globals, locals=locals, fromlist=fromlist, level=level) parts = name.split('.') return getattr(b,parts[0]) else: return _ghidraal_original_import('java.%s' % name, globals=globals, locals=locals, fromlist=fromlist, level=level) # try for a Java class name parts = name.split('.')[:1] if len(parts) > 0: if '.'.join(parts) in _ghidraal_package_names: try: t = java.type(name) # *** looks like name is a Java class name if fromlist is None or len(fromlist)==0: # peel off first bit _after_ java b = _ghidraal_original_import('java.%s' % name, globals=globals, locals=locals, fromlist=fromlist, level=level) parts = name.split('.') return getattr(b,parts[0]) else: return _ghidraal_original_import('java.%s' % name, globals=globals, locals=locals, fromlist=fromlist, level=level) except BaseException: pass # fall through raise module_not_found else: return _ghidraal_original_import(name, globals=globals, locals=locals, fromlist=fromlist, level=level)
# Java context import java array = java.type("int[]")(4) array[2] = 42 print(array[2])
docker exec --tty bgbilling-billing \ polyglot --jvm --jvm.cp=/bgbilling/lib/app/kernel.jar:/bgbilling/lib/ext/joda-time-2.10.jar --language python \ /bgbilling/polyglot/demo/demo.py """ import java from os import listdir from os.path import isfile, join print("Hello from Python") # Java: Calling static method # version_info_type = java.type("bitel.billing.common.VersionInfo") version_info_string = version_info_type.getVersionInfo( "server").getVersionString() print(version_info_string) # Java: Using objects # date_time_format_type = java.type("org.joda.time.format.DateTimeFormat") formatter = date_time_format_type.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z") date_time_type = java.type("org.joda.time.DateTime") dt = date_time_type(2018, 5, 31, 4, 0, 0, 0) print(dt.toString(formatter)) # Plain old Python # path = "/bgbilling/polyglot/demo"
def prepareJVM(self): self.ClassLoader = java.type("java.lang.ClassLoader") self._systemClassLoader = self.ClassLoader.getSystemClassLoader()
import java import polyglot import sys SettingsJavaClass = java.type('ch.ehi.basics.settings.Settings') settings = SettingsJavaClass() ValidatorJavaClass = java.type('org.interlis2.validator.Validator') settings.setValue(ValidatorJavaClass.SETTING_ILIDIRS, ValidatorJavaClass.SETTING_DEFAULT_ILIDIRS) logFileName = "ilivalidator.log" settings.setValue(ValidatorJavaClass.SETTING_LOGFILE, logFileName) ValidatorJavaClass.runValidation("2457.xtf", settings) print("Python version") print(sys.version) print("Version info.") print(sys.version_info)
#!/usr/bin/python print("Running with tornadoVM") import java import time myclass = java.type('uk.ac.manchester.tornado.examples.polyglot.MyCompute') for i in range(5): start = time.time() output = myclass.computeMxM() end = time.time() print("Total time: " + str((end-start)))
import java Config = java.type('ch.ehi.ili2db.gui.Config') Ili2db = java.type('ch.ehi.ili2db.base.Ili2db') Ili2dbException = java.type('ch.ehi.ili2db.base.Ili2dbException') GpkgMain = java.type('ch.ehi.ili2gpkg.GpkgMain') settings = Config() GpkgMain().initConfig(settings) settings.setFunction(Config.FC_IMPORT) settings.setDoImplicitSchemaImport(True) settings.setModels("DM01AVCH24LV95D") settings.setDefaultSrsCode("2056") settings.setNameOptimization(Config.NAME_OPTIMIZATION_TOPIC) settings.setCreateEnumDefs(Config.CREATE_ENUM_DEFS_MULTI) settings.setDbfile("254900.gpkg") # https://github.com/claeis/ili2db/blob/11e48f5493ebaef6bd7613522ddf1725cf7f244e/src/ch/ehi/ili2db/gui/Config.java#L493 # Es gibt zwei Methoden mit dem gleichen Namen. Eine davon ist statisch. # settings.setStrokeArcs(Config.STROKE_ARCS_ENABLE) # oder Config.setStrokeArcs(settings, Config.STROKE_ARCS_ENABLE) settings.setValidation(False) settings.setItfTransferfile(True) settings.setDburl("jdbc:sqlite:" + settings.getDbfile()) settings.setXtffile("254900.itf") try: Ili2db.run(settings, None) except Ili2dbException as value: # not sure if this works as expected print("fubar") print(value)
else: return _ghidraal_original_import('java.%s' % name, globals=globals, locals=locals, fromlist=fromlist, level=level) # try for a Java class name parts = name.split('.')[:1] if len(parts) > 0: if '.'.join(parts) in _ghidraal_package_names: try: t = java.type(name) # *** looks like name is a Java class name if fromlist is None or len(fromlist)==0: # peel off first bit _after_ java b = _ghidraal_original_import('java.%s' % name, globals=globals, locals=locals, fromlist=fromlist, level=level) parts = name.split('.') return getattr(b,parts[0]) else: return _ghidraal_original_import('java.%s' % name, globals=globals, locals=locals, fromlist=fromlist, level=level) except BaseException: pass # fall through raise module_not_found else: return _ghidraal_original_import(name, globals=globals, locals=locals, fromlist=fromlist, level=level) if '_ghidraal_use_jythonic_imports' not in globals(): import builtins # fetch packages visible to GhidraScript's ClassLoader gs_classloader = java.type('ghidra.app.script.GhidraScript')['class'].getClassLoader() _ghidraal_package_names = [p.getName() for p in gs_classloader.getDefinedPackages()] _ghidraal_original_import = builtins.__import__ _ghidraal_use_jythonic_imports = True builtins.__import__ = ghidraal_import
import java Block = java.type('net.minecraft.block.Block') AbstractBlock = java.type('net.minecraft.block.AbstractBlock') Material = java.type('net.minecraft.block.Material') BlockItem = java.type('net.minecraft.item.BlockItem') ItemGroup = java.type('net.minecraft.item.ItemGroup') Registry = java.type('net.minecraft.util.registry.Registry') Identifier = java.type('net.minecraft.util.Identifier') ActionResult = java.type('net.minecraft.util.ActionResult') LiteralText = java.type('net.minecraft.text.LiteralText') FabricBlockSettings = java.type( 'net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings') FabricItemSettings = java.type( 'net.fabricmc.fabric.api.item.v1.FabricItemSettings') IncludeMethodFilter = java.type( 'dev.vriska.quiltlangpolyglot.IncludeMethodFilter') ProxyFactory = java.type('javassist.util.proxy.ProxyFactory') def onUsePythonBlock(block, state, world, pos, player, hand, hit): if not world.isClient: player.sendMessage(LiteralText('Hello from Python!'), False) return ActionResult.SUCCESS def pythonBlockHandler(self, method, proceed, args): return onUsePythonBlock(self, *args)
import sys import java Integer = java.type("java.lang.Integer") Long = java.type("java.lang.Long") Address = java.type("org.ergoplatform.appkit.Address") RestApiErgoClient = java.type("org.ergoplatform.appkit.RestApiErgoClient") ErgoClientException = java.type("org.ergoplatform.appkit.ErgoClientException") ConstantsBuilder = java.type("org.ergoplatform.appkit.ConstantsBuilder") ErgoToolConfig = java.type("org.ergoplatform.appkit.config.ErgoToolConfig") Parameters = java.type("org.ergoplatform.appkit.Parameters") amountToPay = Long.parseLong(sys.argv[1]) conf = ErgoToolConfig.load("freeze_coin_config.json") nodeConf = conf.getNode() newBoxSpendingDelay = Integer.parseInt( conf.getParameters().get("newBoxSpendingDelay")) ownerAddress = Address.create(conf.getParameters().get("ownerAddress")) ergoClient = RestApiErgoClient.create(nodeConf) def send(ctx): wallet = ctx.getWallet() totalToSpend = amountToPay + Parameters.MinFee boxes = wallet.getUnspentBoxes(totalToSpend) if not boxes.isPresent(): raise ErgoClientException( "Not enough coins in the wallet to pay " + totalToSpend, None) prover = ctx.\
x, y = t if isinstance(x, float) and isinstance(y, float): x0, x1 = int(floor(x)), int(ceil(x)) y0, y1 = int(floor(y)), int(ceil(y)) xoff, yoff = x - x0, y - y0 return (1.0 - xoff) * (1.0 - yoff) * self[x0, y0] + \ (1.0 - xoff) * ( yoff) * self[x0, y1] + \ ( xoff) * (1.0 - yoff) * self[x1, y0] + \ ( xoff) * ( yoff) * self[x1, y1] else: return Image.__getitem__(self, (x, y)) SZ = 20 import java INPUT_DATA = java.type("int[]")(SZ * SZ) for i in range(SZ * SZ): INPUT_DATA[i] = i def measure(num): img = Image(SZ, SZ, data=INPUT_DATA) for i in range(num): img = img.sobel(horizontal=True, vertical=True) img = img.fisheye(bilinear=True, fraction=3) return img def __benchmark__(num=10000): return measure(num)
import java BigInteger = java.type('java.math.BigInteger') print(BigInteger.valueOf(2).pow(100).toString())
import java PlayerJoinEvent = java.type('org.bukkit.event.player.PlayerJoinEvent') EventPriority = java.type('org.bukkit.event.EventPriority') Script = java.type('uwu.smsgamer.serverscripter.scripts.Script') ScriptCommand = java.type('uwu.smsgamer.serverscripter.spigot.utils.ScriptCommand') ScriptListenerHelper = java.type("uwu.smsgamer.serverscripter.spigot.utils.ScriptListenerHelper") class TestCommand: # Can't extend ScriptCommand because it's a foreign class def onCommand(self, sender, command, label, args): sender.sendMessage("Hello from GVM Python!") return True def onTabComplete(self, sender, command, alias, args): return ["python", "test"] def on_join(event): event.getPlayer().sendMessage("Hello from GVM Python!") def on_enable(): tc = TestCommand() ScriptCommand.registerCommand(ScriptCommand("gvmpytest", "GraalVM Python Test", "/gvmpytest", [], tc, tc)) ScriptListenerHelper.registerEvent(PlayerJoinEvent, EventPriority.NORMAL, on_join, script)
import java # Alternative way to add Java libraries to GraalVM from JavaScript # java.add_to_classpath("lib/reactive-streams-1.0.2.jar") # java.add_to_classpath("lib/neo4j-java-driver-4.0.0.jar") # This brings in the required classes graphDatabase = java.type('org.neo4j.driver.GraphDatabase') authTokens = java.type('org.neo4j.driver.AuthTokens') config = java.type('org.neo4j.driver.Config') # This is a call to the static factory method named `driver` driver = graphDatabase.driver( 'bolt://localhost:7687', authTokens.basic('neo4j', 'secret'), config.builder().withMaxConnectionPoolSize( 1) # Don't need a bigger pool size for a script # .withEncryption() # Uncomment this if you want to connect against https://neo4j.com/aura/ .build()) # Python dicts are not (yet?) automatically converted to Java maps, so we need to use Neo4j's Values for building parameters values = java.type('org.neo4j.driver.Values') def findConnections(driver): query = """ MATCH (:Person {name:$name})-[:ACTED_IN]->(m)<-[:ACTED_IN]-(coActor) RETURN DISTINCT coActor """ session = driver.session()
import java webBeans = java.type( "org.apache.webbeans.config.WebBeansContext").currentInstance() lifecyle = webBeans.getService( java.type("org.apache.webbeans.spi.ContainerLifecycle")) lifecyle.startApplication(None) numberApi = java.type("javax.enterprise.inject.spi.CDI")\ .current()\ .select(java.type("org.tomitribe.graalvm.microprofile.number.api.client.NumberResourceApi"))\ .get() print(numberApi.getNumber())