예제 #1
0
파일: uno.py 프로젝트: hanya/pyuno3
    def __getattr__(self, elt):
        value = None

        RuntimeException = pyuno.getClass("com.sun.star.uno.RuntimeException")
        try:
            value = pyuno.getClass(self.__path__ + "." + elt)
        except RuntimeException:
            try:
                value = Enum(self.__path__, elt)
            except RuntimeException:
                try:
                    value = pyuno.getConstantByName(self.__path__ + "." + elt)
                except RuntimeException:
                    if elt.startswith("typeOf"):
                        try:
                            value = pyuno.getTypeByName(self.__path__ + "." + elt[6:])
                        except RuntimeException:
                            raise AttributeError("type {}.{} is unknown".format(self.__path__, elt))
                    elif elt == "__all__":
                        try:
                            module_names = pyuno.getModuleElementNames(self.__path__)
                            self.__all__ = module_names
                            return module_names
                        except RuntimeException:
                            raise AttributeError("__all__")
                    else:
                        raise AttributeError("type {}.{} is unknown".format(self.__path__, elt))
        setattr(self, elt, value)
        return value
예제 #2
0
파일: convwatch.py 프로젝트: CaoMomo/core
    def tearDown(self):
        if self.soffice:
            if self.xContext:
                try:
                    print("tearDown: calling terminate()...")
                    xMgr = self.xContext.ServiceManager
                    xDesktop = xMgr.createInstanceWithContext(
                            "com.sun.star.frame.Desktop", self.xContext)
                    xDesktop.terminate()
                    print("...done")
#                except com.sun.star.lang.DisposedException:
                except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
                    print("caught UnknownPropertyException")
                    pass # ignore, also means disposed
                except pyuno.getClass("com.sun.star.lang.DisposedException"):
                    print("caught DisposedException")
                    pass # ignore
            else:
                self.soffice.terminate()
            ret = self.soffice.wait()
            self.xContext = None
            self.socket = None
            self.soffice = None
            if ret != 0:
                raise Exception("Exit status indicates failure: " + str(ret))
def exportDoc(xDoc, filterName, validationCommand, filename, connection, timer):
    props = [ ("FilterName", filterName) ]
    saveProps = tuple([mkPropertyValue(name, value) for (name, value) in props])
    extensions = { "calc8": ".ods",
                    "MS Excel 97": ".xls",
                    "Calc Office Open XML": ".xlsx",
                    "writer8": ".odt",
                    "Office Open XML Text": ".docx",
                    "Rich Text Format": ".rtf",
                    "MS Word 97": ".doc",
                    "impress8": ".odp",
                    "draw8": ".odg",
                    "Impress Office Open XML": ".pptx",
                    "MS PowerPoint 97": ".ppt",
                    "math8": ".odf",
                    "StarOffice XML (Base)": ".odb"
                    }
    base = os.path.splitext(filename)[0]
    filename = base + extensions[filterName]
    fileURL = "file:///srv/crashtestdata/current" + filename
    t = None
    try:
        args = [connection]
        t = threading.Timer(timer.getExportTime(), alarm_handler, args)
        t.start()      
        xDoc.storeToURL(fileURL, saveProps)
    except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
        if t.is_alive():
            writeExportCrash(filename)
        raise # means crashed, handle it later
    except pyuno.getClass("com.sun.star.lang.DisposedException"):
        if t.is_alive():
            writeExportCrash(filename)
        raise # means crashed, handle it later
    except pyuno.getClass("com.sun.star.lang.IllegalArgumentException"):
        pass # means could not open the file, ignore it
    except pyuno.getClass("com.sun.star.task.ErrorCodeIOException"):
        pass
    except:
        pass
    finally:
        if t.is_alive():
            t.cancel()

    print("xDoc.storeToURL " + fileURL + " " + filterName + "\n")
    if validationCommand:
        validationCommandWithURL = validationCommand + " " + fileURL[7:]
        print(validationCommandWithURL)
        try:
            output = str(subprocess.check_output(validationCommandWithURL, shell=True), encoding='utf-8')
            print(output)
            if ("Error" in output) or ("error" in output):
                print("Error validating file")
                validLog = open(fileURL[7:]+".log", "w")
                validLog.write(output)
                validLog.close()
        except subprocess.CalledProcessError:
            pass # ignore that exception
def loadFromURL(xContext, url, t):
    xDesktop = xContext.ServiceManager.createInstanceWithContext(
            "com.sun.star.frame.Desktop", xContext)
    props = [("Hidden", True), ("ReadOnly", True)] # FilterName?
    loadProps = tuple([mkPropertyValue(name, value) for (name, value) in props])

    xListener = EventListener()
    xGEB = xContext.ServiceManager.createInstanceWithContext(
        "com.sun.star.frame.GlobalEventBroadcaster", xContext)
    xGEB.addDocumentEventListener(xListener)

    try:
        xDoc = None
        xDoc = xDesktop.loadComponentFromURL(url, "_blank", 0, loadProps)
        component = getComponent(xDoc)
        if component == "calc":
            try:
                if xDoc:
                    xDoc.calculateAll()
            except AttributeError:
                pass
            t.cancel()
            return xDoc
        elif component == "writer":
            time_ = 0
            t.cancel()
            while time_ < 30:
                if xListener.layoutFinished:
                    return xDoc
#                print("delaying...")
                time_ += 1
                time.sleep(1)
        else:
            t.cancel()
            return xDoc
        file = open("file.log", "a")
        file.write("layout did not finish\n")
        file.close()
        return xDoc
    except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
        xListener = None
        raise # means crashed, handle it later
    except pyuno.getClass("com.sun.star.lang.DisposedException"):
        xListener = None
        raise # means crashed, handle it later
    except pyuno.getClass("com.sun.star.lang.IllegalArgumentException"):
        pass # means could not open the file, ignore it
    except:
        if xDoc:
            print("CLOSING")
            xDoc.close(True)
        raise
    finally:
        if xListener:
            xGEB.removeDocumentEventListener(xListener)
예제 #5
0
def _uno_struct__init__(self, *args, **kwargs):
    """Initializes a UNO struct.

    Referenced from the pyuno shared library.

    This function can be called with either an already constructed UNO struct, which it
    will then just reference without copying, or with arguments to create a new UNO struct.
    """

    # Check to see if this function was passed an existing UNO struct
    if len(kwargs) == 0 and len(args) == 1 and getattr(args[0], "__class__",
                                                       None) == self.__class__:
        self.__dict__['value'] = args[0]
    else:
        struct, used = pyuno._createUnoStructHelper(
            self.__class__.__pyunostruct__, args, **kwargs)

        for kwarg in kwargs.keys():
            if not used.get(kwarg):
                RuntimeException = pyuno.getClass(
                    "com.sun.star.uno.RuntimeException")
                raise RuntimeException(
                    "_uno_struct__init__: unused keyword argument '%s'." %
                    kwarg, None)

        self.__dict__["value"] = struct
예제 #6
0
    def tearDown(self):
        """Terminate a LibreOffice instance created with the path connection method.

        First tries to terminate the soffice instance through the normal
        XDesktop::terminate method and waits for about 30 seconds before
        considering this attempt failed. After the 30 seconds the subprocess
        is terminated """

        if self.soffice:
            if self.xContext:
                try:
                    print("tearDown: calling terminate()...")
                    xMgr = self.xContext.ServiceManager
                    xDesktop = xMgr.createInstanceWithContext(
                        "com.sun.star.frame.Desktop", self.xContext)
                    xDesktop.terminate()
                    print("...done")
                except pyuno.getClass(
                        "com.sun.star.beans.UnknownPropertyException"):
                    print("caught UnknownPropertyException while TearDown")
                    pass  # ignore, also means disposed
                except pyuno.getClass("com.sun.star.lang.DisposedException"):
                    print("caught DisposedException while TearDown")
                    pass  # ignore
            else:
                self.soffice.terminate()

            DEFAULT_SLEEP = 0.1
            time_ = 0
            while time_ < 30:
                time_ += DEFAULT_SLEEP
                ret_attr = self.soffice.poll()
                if ret_attr is not None:
                    break
                time.sleep(DEFAULT_SLEEP)

            ret = 0
            if ret_attr is None:
                ret = 1
                self.soffice.terminate()

            # ret = self.soffice.wait()
            self.xContext = None
            self.socket = None
            self.soffice = None
            if ret != 0:
                raise Exception("Exit status indicates failure: " + str(ret))
예제 #7
0
파일: connection.py 프로젝트: beppec56/core
    def tearDown(self):
        """Terminate a LibreOffice instance created with the path connection method.

        First tries to terminate the soffice instance through the normal
        XDesktop::terminate method and waits for about 30 seconds before
        considering this attempt failed. After the 30 seconds the subprocess
        is terminated """

        if self.soffice:
            if self.xContext:
                try:
                    print("tearDown: calling terminate()...")
                    xMgr = self.xContext.ServiceManager
                    xDesktop = xMgr.createInstanceWithContext(
                            "com.sun.star.frame.Desktop", self.xContext)
                    xDesktop.terminate()
                    print("...done")
                except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
                    print("caught UnknownPropertyException while TearDown")
                    pass  # ignore, also means disposed
                except pyuno.getClass("com.sun.star.lang.DisposedException"):
                    print("caught DisposedException while TearDown")
                    pass  # ignore
            else:
                self.soffice.terminate()

            DEFAULT_SLEEP = 0.1
            time_ = 0
            while time_ < 30:
                time_ += DEFAULT_SLEEP
                ret_attr = self.soffice.poll()
                if ret_attr is not None:
                    break
                time.sleep(DEFAULT_SLEEP)

            ret = 0
            if ret_attr is None:
                ret = 1
                self.soffice.terminate()

            # ret = self.soffice.wait()
            self.xContext = None
            self.socket = None
            self.soffice = None
            if ret != 0:
                raise Exception("Exit status indicates failure: " + str(ret))
예제 #8
0
파일: uno.py 프로젝트: AsherBond/DimSim
def _uno_import( name, *optargs ):
    try:
#       print "optargs = " + repr(optargs)
        if len(optargs) == 0:
           return _g_delegatee( name )
           #print _g_delegatee
        return _g_delegatee( name, *optargs )
    except ImportError:
        if len(optargs) != 3 or not optargs[2]:
           raise
    globals = optargs[0]
    locals = optargs[1]
    fromlist = optargs[2]
    modnames = name.split( "." )
    mod = None
    d = sys.modules
    for x in modnames:
        if d.has_key(x):
           mod = d[x]
        else:
           mod = pyuno.__class__(x)  # How to create a module ??
        d = mod.__dict__

    RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
    for x in fromlist:
       if not d.has_key(x):
          if x.startswith( "typeOf" ):
             try: 
                d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
             except RuntimeException,e:
                raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
          else:
            try:
                # check for structs, exceptions or interfaces
                d[x] = pyuno.getClass( name + "." + x )
            except RuntimeException,e:
                # check for enums 
                try:
                   d[x] = Enum( name , x )
                except RuntimeException,e2:
                   # check for constants
                   try:
                      d[x] = getConstantByName( name + "." + x )
                   except RuntimeException,e3:
                      # no known uno type !
                      raise ImportError( "type "+ name + "." +x + " is unknown" )
예제 #9
0
파일: uno.py 프로젝트: beppec56/openoffice
def _uno_import( name, *optargs, **kwargs ):
    try:
#       print "optargs = " + repr(optargs)
        return _g_delegatee( name, *optargs, **kwargs )
    except ImportError:
        # process optargs
        globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
        if not fromlist:
            raise
    modnames = name.split( "." )
    mod = None
    d = sys.modules
    for x in modnames:
        if x in d:
            mod = d[x]
        else:
            mod = pyuno.__class__(x)  # How to create a module ??
        d = mod.__dict__
    
    RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
    for x in fromlist:
        if x not in d:
            if x.startswith( "typeOf" ):
                try:
                    d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
                except RuntimeException as e:
                    raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
            else:
                try:
                    # check for structs, exceptions or interfaces
                    d[x] = pyuno.getClass( name + "." + x )
                except RuntimeException as e:
                    # check for enums
                    try:
                        d[x] = Enum( name , x )
                    except RuntimeException as e2:
                        # check for constants
                        try:
                            d[x] = getConstantByName( name + "." + x )
                        except RuntimeException as e3:
                            # no known uno type !
                            raise ImportError( "type "+ name + "." +x + " is unknown" )
    return mod
예제 #10
0
def _uno_import( name, *optargs, **kwargs ):
    try:
#       print "optargs = " + repr(optargs)
        return _g_delegatee( name, *optargs, **kwargs )
    except ImportError:
        # process optargs
        globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
        if not fromlist:
            raise
    modnames = name.split( "." )
    mod = None
    d = sys.modules
    for x in modnames:
        if x in d:
            mod = d[x]
        else:
            mod = pyuno.__class__(x)  # How to create a module ??
        d = mod.__dict__
    
    RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
    for x in fromlist:
        if x not in d:
            if x.startswith( "typeOf" ):
                try:
                    d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
                except RuntimeException as e:
                    raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
            else:
                try:
                    # check for structs, exceptions or interfaces
                    d[x] = pyuno.getClass( name + "." + x )
                except RuntimeException as e:
                    # check for enums
                    try:
                        d[x] = Enum( name , x )
                    except RuntimeException as e2:
                        # check for constants
                        try:
                            d[x] = getConstantByName( name + "." + x )
                        except RuntimeException as e3:
                            # no known uno type !
                            raise ImportError( "type "+ name + "." +x + " is unknown" )
    return mod
예제 #11
0
    def tearDown(self):
        if self.soffice:
            if self.xContext:
                try:
                    print("tearDown: calling terminate()...")
                    xMgr = self.xContext.ServiceManager
                    xDesktop = xMgr.createInstanceWithContext(
                        "com.sun.star.frame.Desktop", self.xContext)
                    xDesktop.terminate()
                    print("...done")


#                except com.sun.star.lang.DisposedException:
                except pyuno.getClass(
                        "com.sun.star.beans.UnknownPropertyException"):
                    print("caught UnknownPropertyException while TearDown")
                    pass  # ignore, also means disposed
                except pyuno.getClass("com.sun.star.lang.DisposedException"):
                    print("caught DisposedException while TearDown")
                    pass  # ignore
            else:
                self.soffice.terminate()

            DEFAULT_SLEEP = 0.1
            time_ = 0
            while time_ < 5:
                time_ += DEFAULT_SLEEP
                ret_attr = self.soffice.poll()
                if ret_attr is not None:
                    break
                time.sleep(DEFAULT_SLEEP)

            ret = 0
            if ret_attr is None:
                ret = 1
                self.soffice.terminate()

            # ret = self.soffice.wait()
            self.xContext = None
            self.socket = None
            self.soffice = None
            if ret != 0:
                raise Exception("Exit status indicates failure: " + str(ret))
예제 #12
0
def _uno_struct__init__(self,*args, **kwargs):
    if len(kwargs) == 0 and len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
        self.__dict__["value"] = args[0]
    else:
        struct, used = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args,**kwargs)
        for kw in kwargs.keys():
            if not (kw in used and used[kw]):
                RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
                raise RuntimeException("_uno_struct__init__: unused keyword argument '" + kw + "'", None)
        self.__dict__["value"] = struct
예제 #13
0
    def tearDown(self):
        if self.soffice:
            if self.xContext:
                try:
                    print("tearDown: calling terminate()...")
                    xMgr = self.xContext.ServiceManager
                    xDesktop = xMgr.createInstanceWithContext(
                            "com.sun.star.frame.Desktop", self.xContext)
                    xDesktop.terminate()
                    print("...done")
#                except com.sun.star.lang.DisposedException:
                except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
                    print("caught UnknownPropertyException while TearDown")
                    pass # ignore, also means disposed
                except pyuno.getClass("com.sun.star.lang.DisposedException"):
                    print("caught DisposedException while TearDown")
                    pass # ignore
            else:
                self.soffice.terminate()

            DEFAULT_SLEEP = 0.1
            time_ = 0
            while time_ < 5:
                time_ += DEFAULT_SLEEP
                ret_attr = self.soffice.poll()
                if ret_attr is not None:
                    break
                time.sleep(DEFAULT_SLEEP)

            ret = 0
            if ret_attr is None:
                ret = 1
                self.soffice.terminate()

            # ret = self.soffice.wait()
            self.xContext = None
            self.socket = None
            self.soffice = None
            if ret != 0:
                raise Exception("Exit status indicates failure: " + str(ret))
예제 #14
0
    def tearDown(self):
        """Terminate a LibreOffice instance created with the path connection method.

        First tries to terminate the soffice instance through the normal
        XDesktop::terminate method and waits for about 30 seconds before
        considering this attempt failed. After the 30 seconds the subprocess
        is terminated """

        if self.soffice:
            if self.xContext:
                try:
                    print("tearDown: calling terminate()...")
                    xMgr = self.xContext.ServiceManager
                    xDesktop = xMgr.createInstanceWithContext(
                        "com.sun.star.frame.Desktop", self.xContext)
                    xDesktop.terminate()
                    print("...done")
                except pyuno.getClass(
                        "com.sun.star.beans.UnknownPropertyException"):
                    print("caught UnknownPropertyException while TearDown")
                    pass  # ignore, also means disposed
                except pyuno.getClass("com.sun.star.lang.DisposedException"):
                    print("caught DisposedException while TearDown")
                    pass  # ignore
            else:
                self.soffice.terminate()

            try:
                if sys.version_info >= (3, 3):
                    ret = self.soffice.wait(30)  # will throw when timed out
                else:
                    ret = self.soffice.wait()  # no timeout in python that old
            finally:
                self.xContext = None
                self.socket = None
                self.soffice = None

            if ret != 0:
                raise Exception("Exit status indicates failure: " + str(ret))
예제 #15
0
    def connect(self, socket):
        xLocalContext = uno.getComponentContext()
        xUnoResolver = xLocalContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", xLocalContext)
        url = "uno:" + socket + ";urp;StarOffice.ComponentContext"
        log("OfficeConnection: connecting to: " + url)
        while True:
            try:
                xContext = xUnoResolver.resolve(url)
                return xContext
#            except com.sun.star.connection.NoConnectException
            except pyuno.getClass("com.sun.star.connection.NoConnectException"):
                log("NoConnectException: sleeping...")
                time.sleep(1)
예제 #16
0
파일: convwatch.py 프로젝트: CaoMomo/core
    def connect(self, socket):
        xLocalContext = uno.getComponentContext()
        xUnoResolver = xLocalContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", xLocalContext)
        url = "uno:" + socket + ";urp;StarOffice.ComponentContext"
        print("OfficeConnection: connecting to: " + url)
        while True:
            try:
                xContext = xUnoResolver.resolve(url)
                return xContext
#            except com.sun.star.connection.NoConnectException
            except pyuno.getClass("com.sun.star.connection.NoConnectException"):
                print("NoConnectException: sleeping...")
                time.sleep(1)
예제 #17
0
파일: unotest.py 프로젝트: zzz99977/core
    def connect(self, channel):
        xLocalContext = uno.getComponentContext()
        xUnoResolver = xLocalContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", xLocalContext)
        url = ("uno:%s;urp;StarOffice.ComponentContext" % channel)
        if self.verbose:
            print("Connecting to: ", url)
        while True:
            try:
                self.xContext = xUnoResolver.resolve(url)
                return self.xContext
#            except com.sun.star.connection.NoConnectException
            except pyuno.getClass("com.sun.star.connection.NoConnectException"):
                print("WARN: NoConnectException: sleeping...")
                time.sleep(1)
예제 #18
0
    def connect(self, channel):
        xLocalContext = uno.getComponentContext()
        xUnoResolver = xLocalContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", xLocalContext)
        url = ("uno:%s;urp;StarOffice.ComponentContext" % channel)
        if self.verbose:
            print("Connecting to: ", url)
        while True:
            try:
                self.xContext = xUnoResolver.resolve(url)
                return self.xContext
#            except com.sun.star.connection.NoConnectException
            except pyuno.getClass("com.sun.star.connection.NoConnectException"):
                print("WARN: NoConnectException: sleeping...")
                time.sleep(1)
예제 #19
0
def _uno_struct__init__(self, *args, **kwargs):
    if len(kwargs) == 0 and len(args) == 1 and hasattr(
            args[0], "__class__") and args[0].__class__ == self.__class__:
        self.__dict__["value"] = args[0]
    else:
        struct, used = pyuno._createUnoStructHelper(
            self.__class__.__pyunostruct__, args, **kwargs)
        for kw in kwargs.keys():
            if not (kw in used and used[kw]):
                RuntimeException = pyuno.getClass(
                    "com.sun.star.uno.RuntimeException")
                raise RuntimeException(
                    "_uno_struct__init__: unused keyword argument '" + kw +
                    "'", None)
        self.__dict__["value"] = struct
예제 #20
0
파일: connection.py 프로젝트: beppec56/core
    def connect(self, socket):
        """ Tries to connect to the LibreOffice instance through the specified socket"""
        xLocalContext = uno.getComponentContext()
        xUnoResolver = xLocalContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", xLocalContext)
        url = "uno:" + socket + ";urp;StarOffice.ComponentContext"
        print("OfficeConnection: connecting to: " + url)
        while True:
            if self.soffice.poll() is not None:
                raise Exception("soffice has stopped.")

            try:
                xContext = xUnoResolver.resolve(url)
                return xContext
            except pyuno.getClass("com.sun.star.connection.NoConnectException"):
                print("NoConnectException: sleeping...")
                time.sleep(1)
예제 #21
0
    def connect(self, socket):
        """ Tries to connect to the LibreOffice instance through the specified socket"""
        xLocalContext = uno.getComponentContext()
        xUnoResolver = xLocalContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", xLocalContext)
        url = "uno:" + socket + ";urp;StarOffice.ComponentContext"
        print("OfficeConnection: connecting to: " + url)
        while True:
            if self.soffice and self.soffice.poll() is not None:
                raise Exception("soffice has stopped.")

            try:
                xContext = xUnoResolver.resolve(url)
                return xContext
            except pyuno.getClass("com.sun.star.connection.NoConnectException"):
                print("NoConnectException: sleeping...")
                time.sleep(1)
예제 #22
0
파일: uno.py 프로젝트: CloCkWeRX/core
def _uno_struct__init__(self, *args, **kwargs):
    """Initializes a UNO struct.

    Referenced from the pyuno shared library.

    This function can be called with either an already constructed UNO struct, which it
    will then just reference without copying, or with arguments to create a new UNO struct.
    """

    # Check to see if this function was passed an existing UNO struct
    if len(kwargs) == 0 and len(args) == 1 and getattr(args[0], "__class__", None) == self.__class__:
        self.__dict__['value'] = args[0]
    else:
        struct, used = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__, args, **kwargs)

        for kwarg in kwargs.keys():
            if not used.get(kwarg):
                RuntimeException = pyuno.getClass("com.sun.star.uno.RuntimeException")
                raise RuntimeException("_uno_struct__init__: unused keyword argument '%s'." % kwarg, None)

        self.__dict__["value"] = struct
예제 #23
0
    def run(self, xContext, connection):
        print(self.count + "- Loading document: " + self.file)
        t = None
        args = None
        try:
            url = "file://" + quote(self.file)
            file = open("file.log", "a")
            file.write(url + "\n")
            file.close()
            xDoc = None
            args = [connection]
            t = threading.Timer(self.timer.getImportTime(), alarm_handler,
                                args)
            t.start()
            xDoc = loadFromURL(xContext, url, t, self.args.component)
            t.cancel()
            if xDoc:
                exportTest = ExportFileTest(xDoc, self.file, self.args,
                                            self.timer, self.isImport)
                exportTest.run(connection)
                self.exportedFiles = exportTest.exportedFiles

        except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
            print("caught UnknownPropertyException " + self.file)
            if not t.is_alive():
                print("TIMEOUT!")
            else:
                t.cancel()
                handleCrash(self.file, 0)
            connection.tearDown()
            connection.setUp()
            xDoc = None
        except pyuno.getClass("com.sun.star.lang.DisposedException"):
            print("caught DisposedException " + self.file)
            if not t.is_alive():
                print("TIMEOUT!")
            else:
                t.cancel()
                handleCrash(self.file, 1)
            connection.tearDown()
            connection.setUp()
            xDoc = None
        finally:
            if t.is_alive():
                t.cancel()
            try:
                if xDoc:
                    t = threading.Timer(10, alarm_handler, args)
                    t.start()
                    xDoc.close(True)
                    t.cancel()
            except pyuno.getClass(
                    "com.sun.star.beans.UnknownPropertyException"):
                print("caught UnknownPropertyException while closing")
                connection.tearDown()
                connection.setUp()
            except pyuno.getClass("com.sun.star.lang.DisposedException"):
                print("caught DisposedException while closing")
                if t.is_alive():
                    t.cancel()
                else:
                    pass
                connection.tearDown()
                connection.setUp()
 def run(self, xContext, connection):
     print("Loading document: " + self.file)
     t = None
     args = None
     try:
         url = "file://" + quote(self.file)
         file = open("file.log", "a")
         file.write(url + "\n")
         file.close()
         xDoc = None
         args = [connection]
         t = threading.Timer(self.timer.getImportTime(), alarm_handler, args)
         t.start()      
         xDoc = loadFromURL(xContext, url, t)
         print("doc loaded")
         t.cancel()
         if xDoc:
             exportTest = ExportFileTest(xDoc, self.file, self.enable_validation, self.timer)
             exportTest.run(connection)
     except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
         print("caught UnknownPropertyException " + self.file)
         if not t.is_alive():
             print("TIMEOUT!")
         else:
             t.cancel()
             handleCrash(self.file, 0)
         connection.tearDown()
         connection.setUp()
         xDoc = None
     except pyuno.getClass("com.sun.star.lang.DisposedException"):
         print("caught DisposedException " + self.file)
         if not t.is_alive():
             print("TIMEOUT!")
         else:
             t.cancel()
             handleCrash(self.file, 1)
         connection.tearDown()
         connection.setUp()
         xDoc = None
     finally:
         if t.is_alive():
             t.cancel()
         try:
             if xDoc:
                 t = threading.Timer(10, alarm_handler, args)
                 t.start()
                 print("closing document")
                 xDoc.close(True)
                 t.cancel()
         except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
             print("caught UnknownPropertyException while closing")
             connection.tearDown()
             connection.setUp()
         except pyuno.getClass("com.sun.star.lang.DisposedException"):
             print("caught DisposedException while closing")
             if t.is_alive():
                 t.cancel()
             else:
                 pass
             connection.tearDown()
             connection.setUp()
         print("...done with: " + self.file)
         subprocess.call("rm core*", shell=True)
예제 #25
0
파일: uno.py 프로젝트: mszostak/core
def _uno_import( name, *optargs, **kwargs ):
    try:
#       print "optargs = " + repr(optargs)
        return _g_delegatee( name, *optargs, **kwargs )
    except ImportError as e:
        # process optargs
        globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
        # from import form only, but skip if an uno lookup has already failed
        if not fromlist or hasattr(e, '_uno_import_failed'):
            raise
        # hang onto exception for possible use on subsequent uno lookup failure
        py_import_exc = e
    modnames = name.split( "." )
    mod = None
    d = sys.modules
    for x in modnames:
        if x in d:
           mod = d[x]
        else:
           mod = pyuno.__class__(x)  # How to create a module ??
        d = mod.__dict__

    RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
    for x in fromlist:
       if x not in d:
          failed = False
          if x.startswith( "typeOf" ):
             try:
                d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
             except RuntimeException:
                failed = True
          else:
            try:
                # check for structs, exceptions or interfaces
                d[x] = pyuno.getClass( name + "." + x )
            except RuntimeException:
                # check for enums
                try:
                   d[x] = Enum( name , x )
                except RuntimeException:
                   # check for constants
                   try:
                      d[x] = getConstantByName( name + "." + x )
                   except RuntimeException:
                      # check for constant group
                      try:
                          d[x] = _impl_getConstantGroupByName( name, x )
                      except ValueError:
                          failed = True

          if failed:
              # We have an import failure, but cannot distinguish between
              # uno and non-uno errors as uno lookups are attempted for all
              # "from xxx import yyy" imports following a python failure.
              #
              # In Python 3, the original python exception traceback is reused
              # to help pinpoint the actual failing location.  Its original
              # message, unlike Python 2, is unlikely to be helpful for uno
              # failures, as it most commonly is just a top level module like
              # 'com'.  So our exception appends the uno lookup failure.
              # This is more ambiguous, but it plus the traceback should be
              # sufficient to identify a root cause for python or uno issues.
              #
              # Our exception is raised outside of the nested exception
              # handlers above, to avoid Python 3 nested exception
              # information for the RuntimeExceptions during lookups.
              #
              # Finally, a private attribute is used to prevent further
              # processing if this failure was in a nested import.  That
              # keeps the exception relevant to the primary failure point,
              # preventing us from re-processing our own import errors.

              uno_import_exc = ImportError("%s (or '%s.%s' is unknown)" %
                                           (py_import_exc, name, x))
              if sys.version_info[0] >= 3:
                  uno_import_exc = uno_import_exc.with_traceback(py_import_exc.__traceback__)
              uno_import_exc._uno_import_failed = True
              raise uno_import_exc

    return mod
예제 #26
0
    def run(self, xContext, connection):
        print("Loading document: " + self.file)
        t = None
        args = None
        try:
            url = "file://" + quote(self.file)
            file = open("file.log", "a")
            file.write(url + "\n")
            file.close()
            xDoc = None
            args = [connection]
            t = threading.Timer(self.timer.getImportTime(), alarm_handler,
                                args)
            t.start()
            xDoc = loadFromURL(xContext, url, t)
            print("doc loaded")
            t.cancel()
            if xDoc and self.doExport:
                exportTest = ExportFileTest(xDoc, self.file,
                                            self.enable_validation, self.timer)
                exportTest.run(connection)
                self.exportedFiles = exportTest.exportedFiles

        except pyuno.getClass("com.sun.star.beans.UnknownPropertyException"):
            print("caught UnknownPropertyException " + self.file +
                  " timedOut: " + str(connection.suicided()))
            if not connection.suicided():
                t.cancel()
                handleCrash(self.file, 0)
            connection.tearDown()
            connection.setUp()
            xDoc = None
        except pyuno.getClass("com.sun.star.lang.DisposedException"):
            print("caught DisposedException " + self.file + " timedOut: " +
                  str(connection.suicided()))
            if not connection.suicided():
                t.cancel()
                handleCrash(self.file, 1)
            connection.tearDown()
            connection.setUp()
            xDoc = None
        finally:
            if t.is_alive():
                t.cancel()
            try:
                if xDoc:
                    t = threading.Timer(10, alarm_handler, args)
                    t.start()
                    print("closing document")
                    xDoc.close(True)
                    t.cancel()
            except pyuno.getClass(
                    "com.sun.star.beans.UnknownPropertyException"):
                print("caught UnknownPropertyException while closing")
                connection.tearDown()
                connection.setUp()
            except pyuno.getClass("com.sun.star.lang.DisposedException"):
                print("caught DisposedException while closing")
                if t.is_alive():
                    t.cancel()
                else:
                    pass
                connection.tearDown()
                connection.setUp()
            print("...done with: " + self.file)
예제 #27
0
def _uno_import(name, *optargs, **kwargs):
    """Overrides built-in import to allow directly importing LibreOffice classes."""

    try:
        return _builtin_import(name, *optargs, **kwargs)
    except ImportError as e:
        # process optargs
        globals, locals, fromlist = list(optargs)[:3] + [
            kwargs.get('globals', {}),
            kwargs.get('locals', {}),
            kwargs.get('fromlist', [])
        ][len(optargs):]

        # from import form only, but skip if an uno lookup has already failed
        if not fromlist or hasattr(e, '_uno_import_failed'):
            raise

        # hang onto exception for possible use on subsequent uno lookup failure
        py_import_exc = e

    mod = None
    d = sys.modules

    for module in name.split("."):
        if module in d:
            mod = d[module]
        else:
            # How to create a module ??
            mod = pyuno.__class__(module)

        d = mod.__dict__

    RuntimeException = pyuno.getClass("com.sun.star.uno.RuntimeException")

    for class_name in fromlist:
        if class_name not in d:
            failed = False

            try:
                # check for structs, exceptions or interfaces
                d[class_name] = pyuno.getClass(name + "." + class_name)
            except RuntimeException:
                # check for enums
                try:
                    d[class_name] = Enum(name, class_name)
                except RuntimeException:
                    # check for constants
                    try:
                        d[class_name] = getConstantByName(name + "." +
                                                          class_name)
                    except RuntimeException:
                        # check for constant group
                        try:
                            d[class_name] = _impl_getConstantGroupByName(
                                name, class_name)
                        except ValueError:
                            failed = True

            if failed:
                # We have an import failure, but cannot distinguish between
                # uno and non-uno errors as uno lookups are attempted for all
                # "from xxx import yyy" imports following a python failure.
                #
                # In Python 3, the original python exception traceback is reused
                # to help pinpoint the actual failing location.  Its original
                # message, unlike Python 2, is unlikely to be helpful for uno
                # failures, as it most commonly is just a top level module like
                # 'com'.  So our exception appends the uno lookup failure.
                # This is more ambiguous, but it plus the traceback should be
                # sufficient to identify a root cause for python or uno issues.
                #
                # Our exception is raised outside of the nested exception
                # handlers above, to avoid Python 3 nested exception
                # information for the RuntimeExceptions during lookups.
                #
                # Finally, a private attribute is used to prevent further
                # processing if this failure was in a nested import.  That
                # keeps the exception relevant to the primary failure point,
                # preventing us from re-processing our own import errors.

                uno_import_exc = ImportError("%s (or '%s.%s' is unknown)" %
                                             (py_import_exc, name, class_name))

                if sys.version_info[0] >= 3:
                    uno_import_exc = uno_import_exc.with_traceback(
                        py_import_exc.__traceback__)

                uno_import_exc._uno_import_failed = True
                raise uno_import_exc

    return mod
예제 #28
0
def getClass(typeName):
    """Returns the class of a concrete UNO exception, struct, or interface."""

    return pyuno.getClass(typeName)
예제 #29
0
파일: uno.py 프로젝트: CloCkWeRX/core
def getClass(typeName):
    """Returns the class of a concrete UNO exception, struct, or interface."""

    return pyuno.getClass(typeName)
예제 #30
0
파일: unohelper.py 프로젝트: t2y/unotools
def unoclass(name: str) -> type:
    """
    >>> unoclass('com.sun.star.text.XText')
    <class 'uno.com.sun.star.text.XText'>
    """
    return pyuno.getClass(name)
예제 #31
0
def getClass(typeName):
    """returns the class of a concrete uno exception, struct or interface
    """
    return pyuno.getClass(typeName)
예제 #32
0
파일: uno.py 프로젝트: beppec56/openoffice
def getClass( typeName ):
    """returns the class of a concrete uno exception, struct or interface
    """
    return pyuno.getClass(typeName)
예제 #33
0
def _uno_import(name, *optargs, **kwargs):
    try:
        #       print "optargs = " + repr(optargs)
        return _g_delegatee(name, *optargs, **kwargs)
    except ImportError as e:
        # process optargs
        globals, locals, fromlist = list(optargs)[:3] + [
            kwargs.get('globals', {}),
            kwargs.get('locals', {}),
            kwargs.get('fromlist', [])
        ][len(optargs):]
        # from import form only, but skip if an uno lookup has already failed
        if not fromlist or hasattr(e, '_uno_import_failed'):
            raise
        # hang onto exception for possible use on subsequent uno lookup failure
        py_import_exc = e
    modnames = name.split(".")
    mod = None
    d = sys.modules
    for x in modnames:
        if x in d:
            mod = d[x]
        else:
            mod = pyuno.__class__(x)  # How to create a module ??
        d = mod.__dict__

    RuntimeException = pyuno.getClass("com.sun.star.uno.RuntimeException")
    for x in fromlist:
        if x not in d:
            failed = False
            if x.startswith("typeOf"):
                try:
                    d[x] = pyuno.getTypeByName(name + "." + x[6:len(x)])
                except RuntimeException:
                    failed = True
            else:
                try:
                    # check for structs, exceptions or interfaces
                    d[x] = pyuno.getClass(name + "." + x)
                except RuntimeException:
                    # check for enums
                    try:
                        d[x] = Enum(name, x)
                    except RuntimeException:
                        # check for constants
                        try:
                            d[x] = getConstantByName(name + "." + x)
                        except RuntimeException:
                            failed = True

            if failed:
                # We have an import failure, but cannot distinguish between
                # uno and non-uno errors as uno lookups are attempted for all
                # "from xxx import yyy" imports following a python failure.
                #
                # The traceback from the original python exception is kept to
                # pinpoint the actual failing location, but in Python 3 the
                # original message is most likely unhelpful for uno failures,
                # as it will most commonly be a missing top level module,
                # like 'com'.  Our exception appends the uno lookup failure.
                # This is more ambiguous, but it plus the traceback should be
                # sufficient to identify a root cause for python or uno issues.
                #
                # Our exception is raised outside of the nested exception
                # handlers above, to avoid Python 3 nested exception
                # information for the RuntimeExceptions during lookups.
                #
                # Finally, a private attribute is used to prevent further
                # processing if this failure was in a nested import.  That
                # keeps the exception relevant to the primary failure point,
                # preventing us from re-processing our own import errors.

                uno_import_exc = ImportError(
                    "%s (or '%s.%s' is unknown)" %
                    (py_import_exc, name, x)).with_traceback(
                        py_import_exc.__traceback__)
                uno_import_exc._uno_import_failed = True
                raise uno_import_exc

    return mod