Пример #1
0
 def __init__(self):
     ClassLoader.__init__(self)
     c = self.super__defineClass("ContextAbstract",
                                 CONTEXT_ABSTRACT, 0,
                                 len(CONTEXT_ABSTRACT),
                                 ClassLoader.protectionDomain)
     self.super__resolveClass(c)
Пример #2
0
def get_yaml_config(yaml_filename):
    '''
    Load contents of <yaml_filename> into dictionary.
    Note file_handler's filename needs to be an absolute path and hence
    manually changed from here.
    '''
    # Create helper object to load log config from jar resources
    # Load config details from yaml file.
    # Note getResource returns a java.net.URL object which is incompatible
    # with Python's open method, so we need to work around it by copying the
    # file to the home directory and open from there.
    yaml_path = 'resources/config/{}'.format(yaml_filename)
    loader = ClassLoader.getSystemClassLoader()
    config_file_url = loader.getResource(yaml_path)
    # In Unix getResource returns the path with prefix "file:" but in
    # Windows prefix is "jar:file:"
    path_to_jar = str(config_file_url).split('file:')[1]
    path_to_jar = path_to_jar.split('!')[0]

    path_to_config = get_log_path(yaml_filename)

    # Check if log config file exists already.
    # If it doesn't, paste it from JAR's resources to there.
    # If it does, check is up to date with latest version
    if not os.path.isfile(path_to_config):
        copy_yaml_to_home(path_to_jar, yaml_path, path_to_config)
    else:
        # We are running from the JAR file, not the local console
        update_yaml_config(path_to_jar, yaml_path, path_to_config)

    # Load YAML config
    return yaml.load(open(path_to_config, 'r'))
Пример #3
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)
Пример #4
0
def get_jython_jar():
    from java.lang import ClassLoader  # @UnresolvedImport
    cl = ClassLoader.getSystemClassLoader()
    paths = map(lambda url: url.getFile(), cl.getURLs())
    for p in paths:
        if 'jython.jar' in p:
            return p
    raise RuntimeError('Unable to find jython.jar')
Пример #5
0
def archive_read(archive, path):
    from java.lang import ClassLoader
    from java.io import InputStreamReader, BufferedReader

    # --- make sure this works from within .jar files and such
    stream = ClassLoader.getSystemResourceAsStream(path)
    reader = BufferedReader(InputStreamReader(stream))
    archive.addAll(reader)
Пример #6
0
def archive_read(archive, path):
    from java.lang import ClassLoader
    from java.io import InputStreamReader, BufferedReader

    # --- make sure this works from within .jar files and such
    stream = ClassLoader.getSystemResourceAsStream(path)
    reader = BufferedReader(InputStreamReader(stream))
    archive.addAll(reader)
Пример #7
0
def get_jython_jar():
    from java.lang import ClassLoader  # @UnresolvedImport
    cl = ClassLoader.getSystemClassLoader()
    paths = map(lambda url: url.getFile(), cl.getURLs())
    for p in paths:
        if 'jython.jar' in p:
            return p
    raise RuntimeError('Unable to find jython.jar')
Пример #8
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()])
 def __init__(self):
     if ClassPath._instance:
         self.__dict__.update(ClassPath._instance.__dict__)
     else:
         if 'CLASSPATH' in os.environ:
             self._path = classpath.split(classpathsep)
         else:
             raise InstallationError("Cannot find CLASSPATH environmment variable")
         self._stdloader = ClassLoader.getSystemClassLoader()
         ClassPath._instance = self
Пример #10
0
 def __init__(self):
     if ClassPath._instance:
         self.__dict__.update(ClassPath._instance.__dict__)
     else:
         if 'CLASSPATH' in os.environ:
             self._path = classpath.split(classpathsep)
         else:
             self._path = []
         self._stdloader = ClassLoader.getSystemClassLoader()
         ClassPath._instance = self
Пример #11
0
 def addURL(self, u): 
      """Purpose: Call this with u= URL for 
      the new Class/jar to be loaded""" 
      sysloader = javaClassLoader.getSystemClassLoader() 
      sysclass = URLClassLoader 
      method = sysclass.getDeclaredMethod("addURL", [javaURL]) 
      a = method.setAccessible(1) 
      jar_a = jarray.array([u], javaObject) 
      b = method.invoke(sysloader, [u]) 
      return u 
Пример #12
0
    def load(self, urlString):

        url = ClassLoader.getSystemClassLoader().getResource(urlString)
        #url = URL(urlString)
        loader = FXMLLoader(url)
        root = loader.load()
        self.controller = loader.getController()
        self.scene = Scene(root)
        self.stage.setScene(self.scene)
        self.stage.show()
Пример #13
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()])
Пример #14
0
 def addURL(self, u):
     '''
        Reflexivity to add a jar in the system class loader
     '''
     sysloader = ClassLoader.getSystemClassLoader()
     sysclass = URLClassLoader
     method = sysclass.getDeclaredMethod("addURL", [URL])
     # Could raise java.lang.SecurityException
     method.setAccessible(1)
     method.invoke(sysloader, [u])
     return u
Пример #15
0
 def __init__(self):
     if ClassPath._instance:
         self.__dict__.update(ClassPath._instance.__dict__)
     else:
         if 'CLASSPATH' in os.environ:
             self._path = classpath.split(classpathsep)
         else:
             raise InstallationError(
                 "Cannot find CLASSPATH environmment variable")
         self._stdloader = ClassLoader.getSystemClassLoader()
         ClassPath._instance = self
Пример #16
0
 def actionPerformed(self, event):
   browsers = ["google-chrome", "firefox", "opera", "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla"]
   osName = System.getProperty("os.name")
   helpHTML = ClassLoader.getSystemResource("help.html").toString()
   if osName.find("Mac OS") == 0:
     Class.forName("com.apple.eio.FileManager").getDeclaredMethod( "openURL", [String().getClass()]).invoke(None, [helpHTML])
   elif osName.find("Windows") == 0:
     Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + helpHTML)
   else:
     browser = None
     for b in browsers:
       if browser == None and Runtime.getRuntime().exec(["which", b]).getInputStream().read() != -1:
         browser = b
         Runtime.getRuntime().exec([browser, helpHTML])
Пример #17
0
def get_logging_config():
    """Returns the absolute path to the logging config file
    """

    # We need to find the path to the /pyrig
    from java.lang import ClassLoader
    cl = ClassLoader.getSystemClassLoader()
    paths = map(lambda url: url.getFile(), cl.getURLs())

    # Search all available paths for the one to /pyrig
    path = next(x for x in paths if "pyrig" in x)

    # Now we can return the absolute path to the logging file
    return os.path.join(path, "logging.conf")
Пример #18
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)
Пример #19
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)
Пример #20
0
def set_font():
    """
    Loads font from resources' ttf file.
    DejaVuSans doesn't work in Retina display screens properly, so check OS,
    if OSX then use Monaco instead.
    """
    if "mac" in System.getProperty("os.name").lower():
        font = Font("Monaco", Font.PLAIN, 14)
    else:
        path_to_ttf = 'resources/fonts/dejavu/ttf/DejaVuSans.ttf'
        loader = ClassLoader.getSystemClassLoader()
        stream = loader.getResourceAsStream(path_to_ttf)
        font = Font.createFont(Font.TRUETYPE_FONT, stream)
        font = font.deriveFont(Font.PLAIN, 14)
    return font
Пример #21
0
def set_font(font_size):
    '''
    Loads font from resources' ttf file.
    DejaVuSans doesn't work in Retina display screens properly, so check OS,
    if OSX then use Monaco instead.
    '''
    # Take into account user preferred font size
    if "mac" in System.getProperty("os.name").lower():
        font = Font("Monaco", Font.PLAIN, font_size)
    else:
        path_to_ttf = 'resources/fonts/dejavu/ttf/DejaVuSans.ttf'
        loader = ClassLoader.getSystemClassLoader()
        stream = loader.getResourceAsStream(path_to_ttf)
        font = Font.createFont(Font.TRUETYPE_FONT, stream)
        font = font.deriveFont(Font.PLAIN, font_size)
    return font
Пример #22
0
def loadResource(resourceName):
    cl = ClassLoader.getSystemClassLoader()
    istream = cl.getResourceAsStream(resourceName)
    lines = ""
    if istream == None:
        raise Exception("Cannot find '" + resourceName + "' on classpath")
    else:
        reader = InputStreamReader(istream)
        breader = BufferedReader(reader)
        while True:
            line = breader.readLine()
            if line == None:
                break
            if lines != '':
                lines += '\n'
            lines += line
        breader.close()
    return lines
Пример #23
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()])
Пример #24
0
def get_yaml_config(yaml_filename):
    '''
    Load contents of <yaml_filename> into dictionary.
    Note file_handler's filename needs to be an absolute path and hence
    manually changed from here.
    '''
    # Create helper object to load log config from jar resources
    # Load config details from yaml file.
    # Note getResource returns a java.net.URL object which is incompatible
    # with Python's open method, so we need to work around it by copying the
    # file to the home directory and open from there.
    yaml_path = 'resources/config/{}'.format(yaml_filename)
    loader = ClassLoader.getSystemClassLoader()
    config_file_url = loader.getResource(yaml_path)
    # In Unix getResource returns the path with prefix "file:" but in
    # Windows prefix is "jar:file:"
    path_to_jar = str(config_file_url).split('file:')[1]
    path_to_jar = path_to_jar.split('!')[0]

    path_to_config = get_log_path(yaml_filename)

    # Check if log config file exists already.
    # If it doesn't, paste it from JAR's resources to there.
    # If it does, check is up to date with latest version
    if not os.path.isfile(path_to_config):
        copy_yaml_to_home(path_to_jar, yaml_path, path_to_config)
    else:
        # We are running from the JAR file, not the local console
        update_yaml_config(path_to_jar, yaml_path, path_to_config)

    # Load local YAML file and perform required patches on the settings in
    # memory if the settings version is different between the jar and the local
    # file. Ensures that memory and file settings always match.
    (jar_config, local_config,
     jar_version, local_version) = get_config_versions(path_to_jar, yaml_path,
                                                       path_to_config)

    if yaml_filename == 'settings.yaml':
        if different_versions(jar_version, local_version):
            return patch_config(local_config)

    return local_config
Пример #25
0
    def prepare_security_token_request(params):
        """Construct the request body to acquire security token from STS endpoint"""
        #logger = SamlTokenProvider.logger(SamlTokenProvider.prepare_security_token_request.__name__)
        #logger.debug_secrets('params: %s', params)
        ### logger.info("params: %s" % params)

        # Modified for reading SAML.xml from JAR file
        loader = ClassLoader.getSystemClassLoader()
        stream = loader.getResourceAsStream("office365/runtime/auth/SAML.xml")
        reader = InputStreamReader(stream)
        bufferedReader = BufferedReader(reader)
        data = ""
        line = bufferedReader.readLine()
        while (line):
            data += line
            line = bufferedReader.readLine()
        bufferedReader.close()
        for key in params:
            data = data.replace('[' + key + ']', params[key])
        return data
Пример #26
0
def read_from_jar(relative_path):
    '''
    reads a file from within a jar. returns the file content
    '''
    from java.lang import ClassLoader
    from java.io import InputStreamReader, BufferedReader

    loader = ClassLoader.getSystemClassLoader()
    stream = loader.getResourceAsStream(relative_path)
    reader = BufferedReader(InputStreamReader(stream))
    
    line = reader.readLine()
    buf = ''
    while line is not None:
        buf += line
        line = reader.readLine()
        
    reader.close()
    stream.close()
    return buf
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 
Пример #28
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()])
Пример #29
0
def getResourceDirectoryForModuleName(moduleName):
    resourceDirectory = None
    try:
        prefix = "content/"
        moduleNamePath = moduleName.replace(".", "/")
        resourcePath = prefix + moduleNamePath
        
        if PYCYCLE_DEBUG_RESOURCE_ROOT is None:
            # serving from the "content" directory embedded in the JAR file
            resourceDirectory = _ClassLoader.getSystemResource(resourcePath).toExternalForm()
        #
        else:
            # serving from the "content" directory from the debug root
            resourceDirectory = _File(PYCYCLE_DEBUG_RESOURCE_ROOT, resourcePath).toString()
        #
    #
    except Exception as ex:
        message = "Could not get resource directory for module '" + str(moduleName) + "'. "
        message += "Caused by: \n" + repr(ex)
        raise RuntimeError(message)
    #
    return resourceDirectory
Пример #30
0
 def load(self, img_file, namehint=None):
     """
     Load image from file as a java.awt.image.BufferedImage.
     Return the bufferedimage as a Surface.
     """
     try:
         try:
             f = env.japplet.class.getResource(img_file.replace('\\','/'))    #java uses /, not os.path Windows \
             if not f:
                 raise
         except:
             cload = ClassLoader.getSystemClassLoader()
             f = cload.getResourceAsStream(img_file.replace('\\','/'))
             print "fe"
             
     except:
         
         f = File(img_file)
     
     bimage = ImageIO.read(f)
     surf = Surface(bimage)
     return surf
 def execute(self):
     self.customize(self.options)
     connection = None
     try:
         connection = Overthere.getConnection(CifsConnectionBuilder.CIFS_PROTOCOL, self.options)
         connection.setWorkingDirectory(connection.getFile(self.remotePath))
         # upload the script and pass it to cscript.exe
         targetFile = connection.getTempFile('parameters', '.txt')
         OverthereUtils.write(String(self.script).getBytes(), targetFile)
         targetFile.setExecutable(True)
         exeFile = connection.getTempFile('HpToolsLauncher', '.exe')
         sysloader = ClassLoader.getSystemClassLoader()
         OverthereUtils.write(sysloader.getResourceAsStream("HpTools/HpToolsLauncher.exe"), exeFile)
         exeFile.setExecutable(True)
         # run cscript in batch mode
         scriptCommand = CmdLine.build(exeFile.getPath(), '-paramfile', targetFile.getPath())
         return connection.execute(self.stdout, self.stderr, scriptCommand)
     except Exception, e:
         stacktrace = StringWriter()
         writer = PrintWriter(stacktrace, True)
         e.printStackTrace(writer)
         self.stderr.handleLine(stacktrace.toString())
         return 1
Пример #32
0
from java.lang import ClassLoader
from java.io import InputStreamReader, BufferedReader

# --- Gavrog stuff
from org.gavrog.joss.geometry import SpaceGroupFinder, CrystalSystem
from org.gavrog.joss.pgraphs.io import Net
from org.gavrog.joss.pgraphs.io import Archive


# ============================================================
#   Prepare for RCSR lookup
# ============================================================

# --- get RCSR archive file (possibly from a .jar or the web)
rcsr_path = "org/gavrog/apps/systre/rcsr.arc"
rcsr_stream = ClassLoader.getSystemResourceAsStream(rcsr_path)
reader = BufferedReader(InputStreamReader(rcsr_stream))

# --- create an archive object from it
archive = Archive("1.0")
archive.addAll(reader)


# ============================================================
#   Main data processing
# ============================================================

# --- dictionary of seen nets
seen = {}

# --- count the nets that we read
Пример #33
0
 def __init__(self):
     ClassLoader.__init__(self)
     c = self.super__defineClass("ContextAbstract", CONTEXT_ABSTRACT, 0,
             len(CONTEXT_ABSTRACT), ClassLoader.protectionDomain)
     self.super__resolveClass(c)
Пример #34
0
    # 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):
    """
    A subclass of processing's ``PApplet`` that provides convenience methods
    for running and displaying Applets.
Пример #35
0
 def findImageResource(self, name):
     #Create helper object to load icon images in jar
     loader = ClassLoader.getSystemClassLoader()
     #Load image
     return loader.getResource("resources/images/" + name + ".png")
Пример #36
0
def find_image_resource(name):
    # Create helper object to load icon images in jar
    loader = ClassLoader.getSystemClassLoader()
    # Load image
    return loader.getResource("resources/images/" + name.lower() + ".png")
Пример #37
0
#!/bin/sh
''''exec "$(dirname "$0")"/ImageJ.sh --jython "$0" "$@" # (call again with fiji)'''

import sys
from java.lang import ClassLoader

classLoader = ClassLoader.getSystemClassLoader()
for c in sys.argv[1:]:
    slashed = c.replace('.', '/') + '.class'
    try:
        jar = classLoader.getResource(slashed).toString()
        if jar.startswith('jar:file:'):
            jar = jar[9:]
        exclamation = jar.find('!/')
        if exclamation >= 0:
            jar = jar[0:exclamation]
        print 'Class', c, 'is in', jar
    except:
        print 'Class', c, 'was not found in the classpath'
Пример #38
0
from java.lang import ClassLoader
from java.io import InputStreamReader, BufferedReader

# --- Gavrog stuff
from org.gavrog.joss.geometry import SpaceGroupFinder, CrystalSystem
from org.gavrog.joss.pgraphs.io import Net
from org.gavrog.joss.pgraphs.io import Archive


# ============================================================
#   Prepare for RCSR lookup
# ============================================================

# --- get RCSR archive file (possibly from a .jar or the web)
rcsr_path = "org/gavrog/apps/systre/rcsr.arc"
rcsr_stream = ClassLoader.getSystemResourceAsStream(rcsr_path)
reader = BufferedReader(InputStreamReader(rcsr_stream))

# --- create an archive object from it
archive = Archive("1.0")
archive.addAll(reader)


# ============================================================
#   Helper function
# ============================================================

def minimalImageWithNodeNames(net):
    if net.isMinimal():
        return net, dict((v, [str(net.getNodeName(v))]) for v in net.nodes())
    else:
Пример #39
0
from ij.plugin import RGBStackMerge

sys.path.append(str(os.path.dirname(os.path.abspath(__file__))))
from correct_3d_script import run_3d_drift_correct

from ij.plugin import ChannelSplitter
from ij.gui import OvalRoi, Roi
from java.io import File
#from ij.macro import MacroRunner
from ij.io import FileSaver
import csv
from emblcmci import BleachCorrection_MH
from ij.plugin.filter import BackgroundSubtracter
from java.lang import ClassLoader

ClassLoader.getSystemClassLoader().loadClass(
    'de.embl.cba.illuminationcorrection.basic.BaSiCCommand')
import de.embl.cba.illuminationcorrection.basic as basic

## Parsing commandline input about input folder
folder = FOLDER
###############################################


def run():
    print("Input folder:" + folder)
    find_folders(folder)


def create_folder(dirName):
    if not os.path.exists(dirName):
        os.mkdir(dirName)
Пример #40
0
def find_image_resource(name):
    # Create helper object to load icon images in jar
    loader = ClassLoader.getSystemClassLoader()
    # Load image
    return loader.getResource("resources/images/" + name.lower() + ".png")
Пример #41
0
 def resolveEntity(self, publicId, systemId):
     return InputSource(
         ClassLoader.getSystemResourceAsStream("dtds/" +
                                               os.path.split(systemId)[1]))
Пример #42
0
 def __init__(self):
     URLClassLoader.__init__(self, [], ClassLoader.getSystemClassLoader())
Пример #43
0
#!/bin/sh
''''exec "$(dirname "$0")"/ImageJ.sh --jython "$0" "$@" # (call again with fiji)'''

import sys
from java.lang import ClassLoader

classLoader = ClassLoader.getSystemClassLoader()
for c in sys.argv[1:]:
	slashed = c.replace('.', '/') + '.class'
	try:
		jar = classLoader.getResource(slashed).toString()
		if jar.startswith('jar:file:'):
			jar = jar[9:]
		exclamation = jar.find('!/')
		if exclamation >= 0:
			jar = jar[0:exclamation]
		print 'Class', c, 'is in', jar
	except:
		print 'Class', c, 'was not found in the classpath'
Пример #44
0
 def add_url_pre9(self, url):
     return self.add_url_with_url_classloader(
         ClassLoader.getSystemClassLoader(), url)
Пример #45
0
 def resolveEntity(self, publicId, systemId):
   return InputSource(ClassLoader.getSystemResourceAsStream("dtds/" + os.path.split(systemId)[1]))
Пример #46
0
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

from java.lang import ClassLoader
from java.io import InputStreamReader, BufferedReader, OutputStreamWriter, FileOutputStream, File
import java.lang.Byte
import jarray
import subprocess
import os
import array
from org.apache.commons.io import IOUtils

print "We are in python"
fileStream = File("output")

inStream = ClassLoader.getSystemClassLoader().getResourceAsStream(
    "exec/go/hello")
out = FileOutputStream(fileStream)
IOUtils.copy(inStream, out)
fileStream.setExecutable(True)
out.flush()
out.close()
function_call = subprocess.Popen(["./output"],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
output = function_call.stdout.read()
print output
# print(function_call)
Пример #47
0
 def __init__(self):
     self.system_class_loader = ClassLoader.getSystemClassLoader()
     self.url_class_loader = URLClassLoader
Пример #48
0
    # 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):
    """
    A subclass of processing's ``PApplet`` that provides convenience methods
    for running and displaying Applets.