Ejemplo n.º 1
0
    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 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)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
def addJarToClassPath(pathToJar):
    jarURL = File(pathToJar).toURL()
    systemClassLoader = javaClassLoader.getSystemClassLoader()
    parametersArray = jarray.array([javaURL], javaClass)
    method = URLClassLoader.getDeclaredMethod('addURL', parametersArray)
    method.setAccessible(1)
    invokeParameters = jarray.array([jarURL], javaObject)
    method.invoke(systemClassLoader, invokeParameters)
Ejemplo n.º 6
0
def importJar(jarFile):
    if not os.path.exists(jarFile):
        raise IOError("Can't import " + jarFile)
    from java.net import URL, URLClassLoader
    from java.lang import ClassLoader
    from java.io import File
    m = URLClassLoader.getDeclaredMethod("addURL", [URL])
    m.accessible = 1
    m.invoke(ClassLoader.getSystemClassLoader(), [File(jarFile).toURL()])
Ejemplo n.º 7
0
 def test_assignable_varargs(self):
     "array.array objects can be used in the varargs position"
     # modified from test case in http://bugs.jython.org/issue2423;
     from java.lang import Class
     from java.net import URL, URLClassLoader
     params = jarray.array([URL], Class)
     # URLClassLoader.addURL is protected, so workaround via reflection
     method = URLClassLoader.getDeclaredMethod('addURL', params)
     # and verify we got the right method after all
     self.assertEqual(method.name, "addURL")
Ejemplo n.º 8
0
def import_jar(jarfile):
    from java.net import URL, URLClassLoader
    from java.lang import ClassLoader
    from java.io import File

    if __debug__:
        print 'importing {0}'.format(jarvile)

    method = URLClassLoader.getDeclaredMethod("addURL", [URL])
    method.accessible = 1
    method.invoke(ClassLoader.getSystemClassLoader(), [File(jarFile).toURL()])
Ejemplo n.º 9
0
    def test_assignable_varargs(self):
        "array.array objects can be used in the varargs position"
        # modified from test case in http://bugs.jython.org/issue2423;
        from java.lang import Class
        from java.net import URL, URLClassLoader

        params = jarray.array([URL], Class)
        # URLClassLoader.addURL is protected, so workaround via reflection
        method = URLClassLoader.getDeclaredMethod("addURL", params)
        # and verify we got the right method after all
        self.assertEqual(method.name, "addURL")
Ejemplo n.º 10
0
def _get_classloader(jarfile):
    """Makes a new classloader loaded with the jarfile. This is useful since it
    seems very difficult to get jars added to the correct classpath for
    ResourceBundle.getBundle to find."""
    from java.net import URLClassLoader, URL
    from java.io import File
    import jarray

    file_ = File(jarfile)
    ary = jarray.array([file_.toURL()], URL)
    classloader = URLClassLoader.newInstance(ary)
    return classloader
Ejemplo n.º 11
0
 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)
Ejemplo n.º 12
0
    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))
Ejemplo n.º 13
0
def _jython_set_classpath(jars):
    '''
    import a jar at runtime (needed for JDBC [Class.forName])

    adapted by Bastian Bowe from
    http://stackoverflow.com/questions/3015059/jython-classpath-sys-path-and-jdbc-drivers
    '''
    from java.net import URL, URLClassLoader
    from java.lang import ClassLoader
    from java.io import File
    m = URLClassLoader.getDeclaredMethod("addURL", [URL])
    m.accessible = 1
    urls = [File(i).toURL() for i in jars]
    m.invoke(ClassLoader.getSystemClassLoader(), urls)
Ejemplo n.º 14
0
def _jython_set_classpath(jars):
    '''
    import a jar at runtime (needed for JDBC [Class.forName])

    adapted by Bastian Bowe from
    http://stackoverflow.com/questions/3015059/jython-classpath-sys-path-and-jdbc-drivers
    '''
    from java.net import URL, URLClassLoader
    from java.lang import ClassLoader
    from java.io import File
    m = URLClassLoader.getDeclaredMethod("addURL", [URL])
    m.accessible = 1
    urls = [File(i).toURL() for i in jars]
    m.invoke(ClassLoader.getSystemClassLoader(), urls)
Ejemplo n.º 15
0
    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])
Ejemplo n.º 16
0
def importJar(jarFile):
    '''
    import a jar at runtime (needed for JDBC [Class.forName])

    adapted from http://forum.java.sun.com/thread.jspa?threadID=300557
    Author: SG Langer Jan 2007 translated the above Java to Jython
    Author: [email protected] simplified and updated for jython-2.5.3b3

    >>> importJar('mysql-connector-java-5.1.29-bin.jar')
    >>> import java.lang.Class
    >>> java.lang.Class.forName('com.mysql.jdbc.Driver')
    <type 'com.mysql.jdbc.Driver'>
    '''
    from java.net import URL, URLClassLoader
    from java.lang import ClassLoader
    from java.io import File
    m = URLClassLoader.getDeclaredMethod("addURL", [URL])
    m.accessible = 1
    m.invoke(ClassLoader.getSystemClassLoader(), [File(jarFile).toURL()])
Ejemplo n.º 17
0
    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 addFile(jarFile):
    '''
    http://stackoverflow.com/questions/3015059/jython-classpath-sys-path-and-jdbc-drivers
    import a jar at runtime (needed for JDBC [Class.forName])

    adapted from http://forum.java.sun.com/thread.jspa?threadID=300557
    Author: SG Langer Jan 2007 translated the above Java to Jython
    Author: [email protected] simplified and updated for jython-2.5.3b3

    >>> importJar('jars/jtds-1.2.5.jar')
    >>> import java.lang.Class
    >>> java.lang.Class.forName('net.sourceforge.jtds.jdbc.Driver')
    <type 'net.sourceforge.jtds.jdbc.Driver'>
    '''
    from java.net import URL, URLClassLoader
    from java.lang import ClassLoader
    from java.io import File
    m = URLClassLoader.getDeclaredMethod("addURL", [URL])
    m.accessible = 1
    m.invoke(ClassLoader.getSystemClassLoader(), [File(jarFile).toURL()])
    return 
Ejemplo n.º 19
0
 def importJar(jarFile):
     '''
     import a jar at runtime (needed for JDBC [Class.forName])
 
     adapted from http://forum.java.sun.com/thread.jspa?threadID=300557
     Author: SG Langer Jan 2007 translated the above Java to Jython
     Author: [email protected] simplified and updated for jython-2.5.3b3
 
     >>> importJar('jars/jtds-1.2.5.jar')
     >>> import java.lang.Class
     >>> java.lang.Class.forName('net.sourceforge.jtds.jdbc.Driver')
     <type 'net.sourceforge.jtds.jdbc.Driver'>
     '''
     from java.net  import URL, URLClassLoader
     from java.lang import ClassLoader
     from java.io   import File
     
     print "## Inside importJar <%s>" % jarFile
     
     m = URLClassLoader.getDeclaredMethod("addURL", [URL])
     m.accessible = 1
     m.invoke(ClassLoader.getSystemClassLoader(), [File(jarFile).toURL()])
Ejemplo n.º 20
0
 def set_classloader(self, path):
     prev_cl = self.flyway.getClassLoader()
     url_cl = URLClassLoader.newInstance([path], prev_cl)
     print "New classloader: [%s]" % url_cl.getURLs()
     self.flyway.setClassLoader(url_cl)
Ejemplo n.º 21
0
 def __init__(self):
     URLClassLoader.__init__(self, [])
     self.addURL(URL("file:///home/jiwon/workspace/graphlite/socialite-all.jar"))
Ejemplo n.º 22
0
#!/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)
Ejemplo n.º 23
0
    #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())
Ejemplo n.º 24
0
 def add_url_with_url_classloader(self, classloader, url):
     method = URLClassLoader.getDeclaredMethod("addURL", [URL])
     method.setAccessible(1)
     method.invoke(classloader, [url])
     return url
Ejemplo n.º 25
0
 def __init__(self):
     URLClassLoader.__init__(self, [], ClassLoader.getSystemClassLoader())
Ejemplo n.º 26
0
 def import_support_jar(self):
     addURL = URLClassLoader.getDeclaredMethod('addURL', [URL])
     addURL.accessible = True
     addURL.invoke(URLClassLoader.getSystemClassLoader(), [File(os.path.abspath(self.supportjar)).toURL()])
Ejemplo n.º 27
0
#!/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)
 def __init__(self, url):
     AppResourceLoader.__init__(self)
     classloader = URLClassLoader(array((url, ), URL))
     self.setClassLoader(classloader)
Ejemplo n.º 29
0
    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")
Ejemplo n.º 30
0
def getClassloader():
    jarPath = os.path.join(OCSG_HOME, "modules", CONFIG_JAR)
    classLoader = URLClassLoader(
        jarray.array([File(jarPath).toURI().toURL()], URL))
    return classLoader
Ejemplo n.º 31
0
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)
Ejemplo n.º 32
0
 def set_classloader(self, path):
     prev_cl = self.flyway.getClassLoader()
     url_cl = URLClassLoader.newInstance([path], prev_cl)
     print "New classloader: [%s]" % url_cl.getURLs()
     self.flyway.setClassLoader(url_cl)
Ejemplo n.º 33
0
    import processing
except ImportError:
    # Import framework libs
    libsdir = os.path.abspath(
        os.path.join(os.path.dirname(__file__), 'java_libs'))

    libs = [os.path.join(libsdir, lib) for lib in os.listdir(libsdir)]

    # Import user libraries
    for root, dirnames, filenames in os.walk('libraries'):
        for libfile in fnmatch.filter(filenames, '*.jar'):
            libs.append(os.path.join(root, libfile))

    for lib in libs:
        sys.path.append(lib)
        m = URLClassLoader.getDeclaredMethod("addURL", [URL])
        m.accessible = 1
        m.invoke(ClassLoader.getSystemClassLoader(), [File(lib).toURL()])

# Python imports
import __builtin__

# Java imports
from java.lang import Class
from java.lang.reflect import Modifier
from javax.swing import JFrame
from processing.core import PApplet


class Sketch(PApplet):
    """
Ejemplo n.º 34
0
    import processing
except ImportError:
    # Import framework libs
    libsdir = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                           'java_libs'))

    libs = [os.path.join(libsdir, lib) for lib in os.listdir(libsdir)]

    # Import user libraries
    for root, dirnames, filenames in os.walk('libraries'):
        for libfile in fnmatch.filter(filenames, '*.jar'):
            libs.append(os.path.join(root, libfile))

    for lib in libs:
        sys.path.append(lib)
        m = URLClassLoader.getDeclaredMethod("addURL", [URL])
        m.accessible = 1
        m.invoke(ClassLoader.getSystemClassLoader(), [File(lib).toURL()])

# Python imports
import __builtin__

# Java imports
from java.lang import Class
from java.lang.reflect import Modifier
from javax.swing import JFrame
from processing.core import PApplet


class Sketch(PApplet):
    """
Ejemplo n.º 35
0
 def __init__(self, code):
     URLClassLoader.__init__(self, [], sys.classpath._stdloader)
     self.code = code