Difference between revisions of "PyUNOServer"

From Apache OpenOffice Wiki
Jump to: navigation, search
 
m
 
(13 intermediate revisions by 4 users not shown)
Line 1: Line 1:
The PyUNOServer is a script that pretends to work as a server for OpenOffice.org where it can broadcast and recieve calls using XMLRPC. This means that can get data from other apps on an architecture used for WebServices.
+
[[image:Py-uno_128.png|right|PyUNO Logo]]
 +
The PyUNOServer is a script that works as an XML server for OpenOffice.org Calc where it can exchange data through XML calls. This means that can get data from other apps that are XML compliant. You can download the script from [http://es.openoffice.org/files/documents/73/2929/pyUnoServer.tar.gz this mirror] since the original site seems to be down.
  
 
The zip file contains 3 files:  
 
The zip file contains 3 files:  
* PyUNOServerV2.py - The Python Script
+
* '''PyUNOServerV2.py''' - The Python Script
* PyUNOServerV2.pyc - compiled version
+
* '''PyUNOServerV2.pyc''' - compiled version
* PyUNOServer.sh2 - the script to conect to the service
+
* '''PyUNOServer.sh2''' - the script to conect to the service
  
<code>[python]
+
The script have just 1 script called '''PyUNOServerV2.py''' however there is a faster, bytecode-compiled script. It also includes a bash script which loads the path to the openoffice.org application.
# -*- coding: iso-8859-1 -*-
+
#
+
# pyUnoServer - version 2.0
+
#
+
# (C) 2005 ECWeb Ingenieria y Desarrollo - http://www.ecweb.cl/
+
# Written by:
+
# - Jose Antonio Akel <jakel@NOSPAMecweb.cl>
+
# - Hector Vergara <hector@NOSPAMecweb.cl>
+
# - Luis Gonzalez Miranda <lgm@NOSPAMecweb.cl>
+
#
+
# This program is freely distributable per the following license:
+
#
+
# Permission to use, copy, modify, and distribute this software and its
+
# documentation for any purpose and without fee is hereby granted,
+
# provided that the above copyright notice appears in all copies and that
+
# both that copyright notice and this permission notice appear in
+
# supporting documentation.
+
#
+
# I DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL I
+
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
+
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+
# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+
# SOFTWARE.
+
  
“"”
+
'''NOTE: This script will work on just certain distros since the location of OpenOffice.org might vary. We recomend to load the path manually.'''
This program implements a XMLRPC gateway to Openoffice's Spreadsheet Calculator,
+
allowing external programs to exchange data with spreadsheets.
+
“"”
+
  
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
+
This script uses the following libraries:
import os
+
import uno
+
import sys
+
import time
+
import logging
+
import urllib
+
+
class PyUNOServer(SimpleXMLRPCServer):
+
+
def _dispatch(self, method, params):
+
try:
+
func = getattr(self, '' + method)
+
except:
+
self.logger.error("El Metodo '"+method+"' no esta soportado!")
+
raise Exception('method "%s" is not supported' % method)
+
else:
+
try:
+
ret = func(*params)
+
self.logger.info("Llamada: "+str(method)+str(params)+" | Retorno: "+str(ret))
+
return ret
+
except:
+
self.logger.info("Llamada: "+str(method)+str(params))
+
self.logger.error("Error: "+str(sys.exc_type)+":"+str(sys.exc_value))
+
ef init(self):
+
"""
+
This method starts an Openoffice session and initializes the XMLRPC server
+
"""
+
  
#Creo algunas constantes de utilidad
+
* '''OS''' - This module provides a more portable way of using operating system dependent functionality than importing a operating system dependent built-in module like posix or nt.
self.EMPTY = uno.Enum("com.sun.star.table.CellContentType", "EMPTY")
+
* '''UNO''' - Python UNO implementation module, this can used by python 2.3.4 '''only''' which is the python provided within openoffice.org. It provides all the interfaces from OpenOffice.org into python.
self.TEXT = uno.Enum("com.sun.star.table.CellContentType", "TEXT")
+
* '''SYS''' - This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.
self.FORMULA = uno.Enum("com.sun.star.table.CellContentType", "FORMULA")
+
* '''time''' - This module provides various time-related functions. It is always available, but not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.
self.VALUE = uno.Enum("com.sun.star.table.CellContentType", "VALUE")
+
* '''logging''' - Logging is performed by calling methods on instances of the Logger class (hereafter called loggers). Each instance has a name, and they are conceptually arranged in a name space hierarchy using dots (periods) as separators.
# Creo un Logger
+
* '''urllib''' - This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. Some restrictions apply -- it can only open URLs for reading, and no seek operations are available.
self.logger = logging.getLogger('pyUnoServer')
+
* '''SimpleXMLRPCServer''' - The SimpleXMLRPCServer module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler.
hdlr = logging.FileHandler('./pyUnoServer.log')
+
formatter = logging.Formatter('%(asctime)s %(levelname)s -- %(message)s')
+
hdlr.setFormatter(formatter)
+
self.logger.addHandler(hdlr)  
+
self.logger.setLevel(logging.INFO)
+
self.sessions = []
+
self.sessionSerial = 0
+
# Echo a correr el OpenOffice Calc obteniendo su PID
+
self.PID = os.spawnlp(os.P_NOWAIT,"/usr/bin/oocalc","","-accept=socket,host=localhost,port=2002;urp;")
+
  
self.logger.info("OOCalc Iniciado con el PID "+str(self.PID))
 
while 1:
 
try:
 
localContext = uno.getComponentContext()
 
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
 
smgr = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" )
 
remoteContext = smgr.getPropertyValue( "DefaultContext" )
 
self.desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext)
 
self.logger.info("Sistema conectado al socket de UNO")
 
break
 
except:
 
time.sleep(0.5)
 
ef openSession(self, session):
 
"""
 
This method opens a new session.
 
Sample usage from PHP:
 
- $sessionString is your a session ID provided by your program):
 
$openSession = array( new XML_RPC_VALUE($sessionString, "string"));
 
$sessionID = queryXMLRPC($client, "openSession", $openSession);
 
return $sessionID;
 
"""
 
currentSerial = -1
 
for i in range(0,len(self.sessions)):
 
if self.sessions[i][0] == session:
 
currentSerial = i
 
break
 
  
if currentSerial == -1:
+
<source lang=python>
self.sessions.append([session,[]])
+
# -*- coding: iso-8859-1 -*-
currentSerial = len(self.sessions)-1
+
#
return currentSerial
+
# pyUnoServer - version 2.0
 +
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
 +
import os
 +
import uno
 +
import sys
 +
import time
 +
import logging
 +
import urllib
  
ef getSessions(self):
+
class PyUNOServer(SimpleXMLRPCServer):
return self.sessions
+
ef openBook(self, session, bookPath):
+
"""
+
This method opens a new Openoffice spreadsheet book.
+
Sample usage from PHP:
+
- $sessionID is the session's ID returned by openSession()
+
- $path is the path to the book in the server's filesystem
+
$openBookQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($path,"string") );
+
$bookID = queryXMLRPC($client, "openBook", $openBookQuery);
+
return $bookID;
+
"""
+
currentSerial = session
+
bookPath = bookPath.strip()
+
print bookPath
+
exists = os.path.exists(bookPath)
+
if exists == False:
+
raise Exception('El libro %s no existe', bookPath)
+
else:
+
self.logger.info("se ha encontrado el libro!")
+
  
currentBook = -1
+
def _dispatch(self, method, params):
  
for i in range(0, len(self.sessions[currentSerial][1])):
+
try:
try:
+
func = getattr(self, '' + method)
book = self.sessions[currentSerial][1][i]
+
except:
 +
self.logger.error("El Metodo '"+method+"' no esta soportado!")
 +
raise Exception('method "%s" is not supported' % method)
 +
else:
 +
try:
 +
ret = func(*params)
 +
self.logger.info("Llamada: %s%s | Retorno: %s" % (method, params, ret))
 +
return ret
 +
except:
 +
self.logger.info("Llamada: %s%s" % (method, params))
 +
self.logger.error("Error: %s:%s" % sys.exc_info()[:2])
 +
 
 +
def init(self):
 +
"""
 +
This method starts an Openoffice session and initializes the XMLRPC server
 +
"""
 
 
bookname = book[0]
+
# Generate some useful constants
bookhandler = book[1]
+
self.EMPTY = uno.Enum("com.sun.star.table.CellContentType", "EMPTY")
bookmodtime = book[2]
+
self.TEXT = uno.Enum("com.sun.star.table.CellContentType", "TEXT")
 +
self.FORMULA = uno.Enum("com.sun.star.table.CellContentType", "FORMULA")
 +
self.VALUE = uno.Enum("com.sun.star.table.CellContentType", "VALUE")
 +
 
 +
# Generate a Logger
 +
self.logger = logging.getLogger('pyUnoServer')
 +
hdlr = logging.FileHandler('./pyUnoServer.log')
 +
formatter = logging.Formatter('%(asctime)s %(levelname)s -- %(message)s')
 +
hdlr.setFormatter(formatter)
 +
self.logger.addHandler(hdlr)
 +
self.logger.setLevel(logging.INFO)
 +
 
 +
self.sessions = []
 +
self.sessionSerial = 0
 +
 
 +
# Start Calc and grep the PID
 +
self.PID = os.spawnlp(os.P_NOWAIT,"/usr/bin/oocalc","","-accept=socket,host=localhost,port=2002;urp;")
 +
 +
self.logger.info("OOCalc Iniciado con el PID %d" % self.PID)
 +
 
 +
while 1:
 +
try:
 +
localContext = uno.getComponentContext()
 +
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
 +
smgr = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" )
 +
remoteContext = smgr.getPropertyValue( "DefaultContext" )
 +
self.desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext)
 +
self.logger.info("Sistema conectado al socket de UNO")
 +
break
 +
except:
 +
time.sleep(0.5)
 +
 
 +
def openSession(self, session):
 +
"""
 +
This method opens a new session.
 +
Sample usage from PHP:
 +
- $sessionString is your a session ID provided by your program):
 +
 
 +
$openSession = array( new XML_RPC_VALUE($sessionString, "string"));
 +
$sessionID = queryXMLRPC($client, "openSession", $openSession);
 +
return $sessionID;
 +
"""
 +
 
 +
for i,x in enumerate(self.sessions):
 +
if x[0] == session:
 +
currentSerial = i
 +
break
 +
else:
 +
self.sessions.append([session,[]])
 +
currentSerial = len(self.sessions)-1
 +
 
 +
return currentSerial
 
 
if bookname == bookPath:
+
 
 +
def getSessions(self):
 +
return self.sessions
 +
 
 +
def openBook(self, session, bookPath):
 +
"""
 +
This method opens a new Openoffice spreadsheet book.
 +
Sample usage from PHP:
 +
- $sessionID is the session's ID returned by openSession()
 +
- $path is the path to the book in the server's filesystem
 +
 
 +
$openBookQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($path,"string") );
 +
$bookID = queryXMLRPC($client, "openBook", $openBookQuery);
 +
return $bookID;
 +
"""
 +
 
 +
currentSerial = session
 +
bookPath = bookPath.strip()
 +
print bookPath
 +
 
 +
 
 +
exists = os.path.exists(bookPath)
 +
if exists == False:
 +
raise Exception('El libro %s no existe', bookPath)
 +
else:
 +
self.logger.info("se ha encontrado el libro!")
 +
 +
currentBook = -1
 +
 +
for i, book in enumerate(self.sessions[currentSerial][1]):
 +
try:
 +
 +
bookname = book[0]
 +
bookhandler = book[1]
 +
bookmodtime = book[2]
 +
 +
if bookname == bookPath:
 +
modtime = os.path.getmtime(bookPath)
 +
if modtime > bookmodtime:
 +
book[1].dispose()
 +
self.sessions[currentSerial][1].remove(book)
 +
else:
 +
currentBook = i
 +
break
 +
except:
 +
self.logger.error("El libro "+currentBook+" no existe!")
 +
 +
 
 +
if currentBook < 0:
 +
handler = self.desktop.loadComponentFromURL( "file://" + bookPath ,"_blank",0,())
 +
 
 +
if handler == None:
 +
raise Exception('El libro no existe o tiene caracteres extraños...')
 +
 
 
modtime = os.path.getmtime(bookPath)
 
modtime = os.path.getmtime(bookPath)
if (modtime > bookmodtime):
+
book[1].dispose()
+
estruct = [bookPath,handler,modtime]
self.sessions[currentSerial][1].remove(book)
+
self.sessions[currentSerial][1].append(estruct)
else:
+
currentBook = len(self.sessions[currentSerial][1])-1
currentBook = i
+
break
+
return currentBook
except:
+
 
self.logger.error("El libro "+currentBook+" no existe!")
+
def closeBook(self, sessionID, bookID):
 
 
if (currentBook < 0 ):
+
books = self.sessions[sessionID][1]
handler = self.desktop.loadComponentFromURL( "file://" + bookPath ,"_blank",0,())
+
if(handler == None):
+
# Close the document. It doesn't look very elegant but thats the way is documented.
raise Exception('El libro no existe o tiene caracteres extraños...')
+
books[bookID][1].dispose()
modtime = os.path.getmtime(bookPath)
+
self.sessions[sessionID][1].remove(books[bookID])
+
estruct = [bookPath,handler,modtime]
+
return 1
self.sessions[currentSerial][1].append(estruct)
+
currentBook = len(self.sessions[currentSerial][1])-1
+
+
return currentBook
+
ef closeBook(self, sessionID, bookID):
+
  
books = self.sessions[sessionID][1]
 
  
#esto cierra el documento. Parece Cerdo, pero segun la documentcion, asi es
+
def getBookSheets(self, sessionID, bookID):
books[bookID][1].dispose()
+
"""
self.sessions[sessionID][1].remove(books[bookID])
+
This method return an array with the book's worksheets.
 +
Sample usage from PHP:
 +
- $sessionID is the session's ID returned by openSession()
 +
- $bookID is the book's ID returned by openBook()
  
return 1
+
$sheetsQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($bookID, "int") );
ef getBookSheets(self, sessionID, bookID):
+
$sheets = queryXMLRPC($client, "getBookSheets" , $sheetsQuery);
"""
+
return $sheets;
This method return an array with the book's worksheets.
+
"""
Sample usage from PHP:
+
- $sessionID is the session's ID returned by openSession()
+
sheets = self.sessions[sessionID][1][bookID][1].getSheets().createEnumeration()
- $bookID is the book's ID returned by openBook()
+
$sheetsQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($bookID, "int") );
+
container = []
$sheets = queryXMLRPC($client, "getBookSheets" , $sheetsQuery);
+
while sheets.hasMoreElements():
return $sheets;
+
currentSheet = sheets.nextElement()
"""
+
container.append(currentSheet.getName().encode("UTF-8"))
 +
 +
return container
  
sheets = self.sessions[sessionID][1][bookID][1].getSheets().createEnumeration()
+
def getCellValue (self,sheet,x,y):
  
container = []
+
cell = sheet.getCellByPosition(x,y)
while(sheets.hasMoreElements()):
+
cellType  = cell.getType()
currentSheet = sheets.nextElement()
+
container.append(currentSheet.getName().encode("UTF-8"))
+
+
return container
+
ef getCellValue (self,sheet,x,y):
+
cell = sheet.getCellByPosition(x,y)
+
cellType  = cell.getType()
+
if cellType == self.TEXT :
+
data = cell.getString().encode("UTF-8")
+
if data == None:
+
return ""
+
return data.encode("UTF-8")
+
+
if cellType == self.FORMULA or cellType == self.VALUE :
+
data = cell.getValue()
+
if data == None:
+
return 0
+
return cell.getValue()
+
if cellType == self.EMPTY :
+
return ""
+
ef getCell(self, session, book, sheet, x, y):
+
"""
+
This method returns the content of a cell.
+
Sample usage from PHP:
+
- $sessionID is the session's ID returned by openSession()
+
- $bookID is the book's ID returned by openBook()
+
- $sheet is the sheet's ID as returned by getBookSheets()
+
$query = array(
+
new XML_RPC_Value($sessionID, "int"),
+
new XML_RPC_VALUE($bookID, "int"),
+
new XML_RPC_VALUE($sheet, "int"),
+
new XML_RPC_Value($x, "int"),
+
new XML_RPC_Value($y, "string")
+
);
+
$result = queryXMLRPC($client, "getCell", $query);
+
return $result;
+
"""
+
sheetref = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
+
valor = self.getCellValue(sheetref,x,y)
+
return valor
+
  
ef setCell(self,session,book,sheet,x,y,value):
+
if cellType == self.TEXT :
"""
+
data = cell.getString().encode("UTF-8")
This method sets the content of a cell.
+
if data == None:
Sample usage from PHP:
+
return ""
- $sessionID is the session's ID returned by openSession()
+
return data.encode("UTF-8")
- $bookID is the book's ID returned by openBook()
+
- $sheet is the sheet's ID as returned by getBookSheets()
+
if cellType == self.FORMULA or cellType == self.VALUE :
$query = array(
+
data = cell.getValue()
new XML_RPC_Value($sessionID, "int"),
+
if data == None:
new XML_RPC_VALUE($bookID, "int"),
+
return 0
new XML_RPC_VALUE($sheet, "int"),
+
return cell.getValue()
new XML_RPC_Value($x, "int"),
+
new XML_RPC_Value($y, "int"),
+
new XML_RPC_Value($value, "string")
+
);
+
$result = queryXMLRPC($client, "setCell", $query);
+
return $result;
+
"""
+
  
bookObject = self.sessions[session][1][book][1]
+
if cellType == self.EMPTY :
cell = bookObject.getSheets().getByIndex(sheet).getCellByPosition(x,y)
+
return ""
cell.setValue(value)
+
return 1
+
en que cambiara todo? mmm...
+
ef massiveSetCell(self, data):
+
for valores in data:
+
session,sheetid,x,y,valor = valores.split("|")
+
code = self.setCell(self.trim(session),self.trim(sheetid),self.trim(x),self.trim(y),valor)
+
if code < 0:
+
return code
+
return 1
+
ef getSheetPreview(self,session,book,sheet):
+
sheet = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
+
range = sheet.getCellRangeByPosition(0,0,8,23).getDataArray()
+
return range
+
  
ef trim(self, cadena):
 
return cadena.strip()
 
  
 +
def getCell(self, session, book, sheet, x, y):
 +
"""
 +
This method returns the content of a cell.
 +
Sample usage from PHP:
 +
- $sessionID is the session's ID returned by openSession()
 +
- $bookID is the book's ID returned by openBook()
 +
- $sheet is the sheet's ID as returned by getBookSheets()
  
server = PyUNOServer2)  
+
$query = array(
 +
new XML_RPC_Value($sessionID, "int"),
 +
new XML_RPC_VALUE($bookID, "int"),
 +
new XML_RPC_VALUE($sheet, "int"),
 +
new XML_RPC_Value($x, "int"),
 +
new XML_RPC_Value($y, "string")
 +
);
  
server.init() server.logger.info(“Servicio Inicializado…”)
+
$result = queryXMLRPC($client, "getCell", $query);
 +
return $result;
 +
"""
  
try:  
+
sheetref = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
erver.serve_forever()
+
valor = self.getCellValue(sheetref,x,y)
 +
return valor
 +
 +
def setCell(self,session,book,sheet,x,y,value):
 +
"""
 +
This method sets the content of a cell.
 +
Sample usage from PHP:
 +
- $sessionID is the session's ID returned by openSession()
 +
- $bookID is the book's ID returned by openBook()
 +
- $sheet is the sheet's ID as returned by getBookSheets()
  
except KeyboardInterrupt:  
+
$query = array(
erver.logger.info("Cerrando el socket...")
+
new XML_RPC_Value($sessionID, "int"),
erver.server_close()
+
new XML_RPC_VALUE($bookID, "int"),
s.kill(server.PID,1)
+
new XML_RPC_VALUE($sheet, "int"),
erver.logger.info("Socket cerrado.")</code>
+
new XML_RPC_Value($x, "int"),
 +
new XML_RPC_Value($y, "int"),
 +
new XML_RPC_Value($value, "string")
 +
);
 +
 
 +
$result = queryXMLRPC($client, "setCell", $query);
 +
return $result;
 +
"""
 +
 +
bookObject = self.sessions[session][1][book][1]
 +
cell = bookObject.getSheets().getByIndex(sheet).getCellByPosition(x,y)
 +
cell.setValue(value)
 +
return 1
 +
 
 +
#what will change? mmm...
 +
def massiveSetCell(self, data):
 +
for valores in data:
 +
session,sheetid,x,y,valor = valores.split("|")
 +
code = self.setCell(self.trim(session),self.trim(sheetid),self.trim(x),self.trim(y),valor)
 +
if code < 0:
 +
return code
 +
return 1
 +
 
 +
def getSheetPreview(self,session,book,sheet):
 +
 
 +
sheet = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
 +
range = sheet.getCellRangeByPosition(0,0,8,23).getDataArray()
 +
return range
 +
 +
 
 +
def trim(self, cadena):
 +
return cadena.strip()
 +
 +
server = PyUNOServer(("localhost", 8000))
 +
 
 +
server.init()
 +
server.logger.info("Servicio Inicializado...")
 +
 
 +
try:
 +
server.serve_forever()
 +
except KeyboardInterrupt:
 +
server.logger.info("Cerrando el socket...")
 +
server.server_close()
 +
os.kill(server.PID,1)
 +
server.logger.info("Socket cerrado.")
 +
</source>
  
 
==startPyUnoServer.sh2==
 
==startPyUnoServer.sh2==
<code>[bash]
+
<source lang=bash>
 
#!/bin/bash
 
#!/bin/bash
 
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/openoffice/program/
 
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/openoffice/program/
Line 295: Line 318:
 
echo "Logging en pyUnoServer.log"
 
echo "Logging en pyUnoServer.log"
 
python pyUnoServerV2.py
 
python pyUnoServerV2.py
echo "CHAO!"
+
echo "Ciao!"
</code>
+
</source>
 +
 
 +
[[Category:Python]][[Category:Uno]]

Latest revision as of 05:49, 15 May 2010

PyUNO Logo

The PyUNOServer is a script that works as an XML server for OpenOffice.org Calc where it can exchange data through XML calls. This means that can get data from other apps that are XML compliant. You can download the script from this mirror since the original site seems to be down.

The zip file contains 3 files:

  • PyUNOServerV2.py - The Python Script
  • PyUNOServerV2.pyc - compiled version
  • PyUNOServer.sh2 - the script to conect to the service

The script have just 1 script called PyUNOServerV2.py however there is a faster, bytecode-compiled script. It also includes a bash script which loads the path to the openoffice.org application.

NOTE: This script will work on just certain distros since the location of OpenOffice.org might vary. We recomend to load the path manually.

This script uses the following libraries:

  • OS - This module provides a more portable way of using operating system dependent functionality than importing a operating system dependent built-in module like posix or nt.
  • UNO - Python UNO implementation module, this can used by python 2.3.4 only which is the python provided within openoffice.org. It provides all the interfaces from OpenOffice.org into python.
  • SYS - This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.
  • time - This module provides various time-related functions. It is always available, but not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.
  • logging - Logging is performed by calling methods on instances of the Logger class (hereafter called loggers). Each instance has a name, and they are conceptually arranged in a name space hierarchy using dots (periods) as separators.
  • urllib - This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. Some restrictions apply -- it can only open URLs for reading, and no seek operations are available.
  • SimpleXMLRPCServer - The SimpleXMLRPCServer module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler.


# -*- coding: iso-8859-1 -*-
#
# pyUnoServer - version 2.0
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
import os
import uno
import sys
import time
import logging
import urllib
 
class PyUNOServer(SimpleXMLRPCServer):
 
	def _dispatch(self, method, params):
 
		try:
			func = getattr(self, '' + method)
		except:
			self.logger.error("El Metodo '"+method+"' no esta soportado!")
			raise Exception('method "%s" is not supported' % method)
		else:
			try:
				ret = func(*params)
				self.logger.info("Llamada: %s%s | Retorno: %s" % (method, params, ret))
				return ret
			except:
				self.logger.info("Llamada: %s%s" % (method, params))
				self.logger.error("Error: %s:%s" % sys.exc_info()[:2])
 
	def init(self):
		"""
		This method	starts an Openoffice session and initializes the XMLRPC server
		"""
 
		# Generate some useful constants
		self.EMPTY = uno.Enum("com.sun.star.table.CellContentType", "EMPTY")
		self.TEXT = uno.Enum("com.sun.star.table.CellContentType", "TEXT")
		self.FORMULA = uno.Enum("com.sun.star.table.CellContentType", "FORMULA")
		self.VALUE = uno.Enum("com.sun.star.table.CellContentType", "VALUE")
 
		# Generate a Logger
		self.logger = logging.getLogger('pyUnoServer')
		hdlr = logging.FileHandler('./pyUnoServer.log')
		formatter = logging.Formatter('%(asctime)s %(levelname)s -- %(message)s')
		hdlr.setFormatter(formatter)
		self.logger.addHandler(hdlr) 
		self.logger.setLevel(logging.INFO)
 
		self.sessions = []
		self.sessionSerial = 0
 
		# Start Calc and grep the PID
		self.PID = os.spawnlp(os.P_NOWAIT,"/usr/bin/oocalc","","-accept=socket,host=localhost,port=2002;urp;")
 
		self.logger.info("OOCalc Iniciado con el PID %d" % self.PID)
 
		while 1:
			try: 
				localContext = uno.getComponentContext()
				resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
				smgr = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" )
				remoteContext = smgr.getPropertyValue( "DefaultContext" )
				self.desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext)
				self.logger.info("Sistema conectado al socket de UNO")
				break
			except:
				time.sleep(0.5)
 
	def openSession(self, session):
		"""
		This method opens a new session.
		Sample usage from PHP:
		 - $sessionString is your a session ID provided by your program):
 
			$openSession = array( new XML_RPC_VALUE($sessionString, "string"));
			$sessionID = queryXMLRPC($client, "openSession", $openSession);
			return $sessionID;
		"""
 
		for i,x in enumerate(self.sessions):
			if x[0] == session:
				currentSerial = i
				break
		else:
			self.sessions.append([session,[]])
			currentSerial = len(self.sessions)-1
 
		return currentSerial
 
 
	def getSessions(self):
		return self.sessions
 
	def openBook(self, session, bookPath):
		"""
		This method opens a new Openoffice spreadsheet book.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $path is the path to the book in the server's filesystem
 
		$openBookQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($path,"string") );
		$bookID = queryXMLRPC($client, "openBook", $openBookQuery);
		return $bookID;
		"""
 
		currentSerial = session
		bookPath = bookPath.strip()
		print bookPath
 
 
		exists = os.path.exists(bookPath)
		if exists == False:
			raise Exception('El libro %s no existe', bookPath)
		else:
			self.logger.info("se ha encontrado el libro!")
 
		currentBook = -1
 
		for i, book in enumerate(self.sessions[currentSerial][1]):
			try:
 
				bookname = book[0]
				bookhandler = book[1]
				bookmodtime = book[2]
 
				if bookname == bookPath:
					modtime = os.path.getmtime(bookPath)
					if modtime > bookmodtime:
						book[1].dispose()
						self.sessions[currentSerial][1].remove(book)
					else:
						currentBook = i
					break
			except:
				self.logger.error("El libro "+currentBook+" no existe!")
 
 
		if currentBook < 0:
			handler = self.desktop.loadComponentFromURL( "file://" + bookPath ,"_blank",0,())
 
			if handler == None:
				raise Exception('El libro no existe o tiene caracteres extraños...')
 
			modtime = os.path.getmtime(bookPath)
 
			estruct = [bookPath,handler,modtime]
			self.sessions[currentSerial][1].append(estruct)
			currentBook = len(self.sessions[currentSerial][1])-1
 
		return currentBook
 
	def closeBook(self, sessionID, bookID):
 
		books = self.sessions[sessionID][1]
 
		# Close the document. It doesn't look very elegant but thats the way is documented.
		books[bookID][1].dispose()
		self.sessions[sessionID][1].remove(books[bookID])
 
		return 1
 
 
	def getBookSheets(self, sessionID, bookID):
		"""
		This method return an array with the book's worksheets.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
 
		$sheetsQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($bookID, "int") );
		$sheets = queryXMLRPC($client, "getBookSheets" , $sheetsQuery);
		return $sheets;
		"""
 
		sheets = self.sessions[sessionID][1][bookID][1].getSheets().createEnumeration()
 
		container = []
		while sheets.hasMoreElements():
			currentSheet = sheets.nextElement()
			container.append(currentSheet.getName().encode("UTF-8"))
 
		return container
 
	def getCellValue (self,sheet,x,y):
 
		cell = sheet.getCellByPosition(x,y)
		cellType  = cell.getType()
 
		if cellType == self.TEXT :
			data = cell.getString().encode("UTF-8")
			if data == None:
				return ""
			return data.encode("UTF-8")
 
		if cellType == self.FORMULA or cellType == self.VALUE :
			data = cell.getValue()
			if data == None:
				return 0
			return cell.getValue()
 
		if cellType == self.EMPTY :
			return ""
 
 
	def getCell(self, session, book, sheet, x, y):
		"""
		This method returns the content of a cell.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
		 - $sheet is the sheet's ID as returned by getBookSheets()
 
		$query = array(	
						new XML_RPC_Value($sessionID, "int"), 
						new XML_RPC_VALUE($bookID, "int"), 
						new XML_RPC_VALUE($sheet, "int"), 
						new XML_RPC_Value($x, "int"), 
						new XML_RPC_Value($y, "string")
					);
 
		$result = queryXMLRPC($client, "getCell", $query);
		return $result;
		"""
 
		sheetref = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
		valor = self.getCellValue(sheetref,x,y)
		return valor
 
	def setCell(self,session,book,sheet,x,y,value):
		"""
		This method sets the content of a cell.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
		 - $sheet is the sheet's ID as returned by getBookSheets()
 
		$query = array(
						new XML_RPC_Value($sessionID, "int"), 
						new XML_RPC_VALUE($bookID, "int"), 
						new XML_RPC_VALUE($sheet, "int"), 
						new XML_RPC_Value($x, "int"), 
						new XML_RPC_Value($y, "int"),
						new XML_RPC_Value($value, "string")
					);
 
		$result = queryXMLRPC($client, "setCell", $query);
		return $result;
		"""
 
		bookObject = self.sessions[session][1][book][1]
		cell = bookObject.getSheets().getByIndex(sheet).getCellByPosition(x,y)
		cell.setValue(value)
		return 1
 
	#what will change? mmm...
	def massiveSetCell(self, data):
			for valores in data:
				session,sheetid,x,y,valor = valores.split("|")
				code = self.setCell(self.trim(session),self.trim(sheetid),self.trim(x),self.trim(y),valor)
				if code < 0:
					return code
			return 1
 
	def getSheetPreview(self,session,book,sheet):
 
		sheet = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
		range = sheet.getCellRangeByPosition(0,0,8,23).getDataArray()
		return range
 
 
	def trim(self, cadena):
		return cadena.strip()
 
server = PyUNOServer(("localhost", 8000))
 
server.init()
server.logger.info("Servicio Inicializado...")
 
try:
	server.serve_forever()
except KeyboardInterrupt:
	server.logger.info("Cerrando el socket...")
	server.server_close()
	os.kill(server.PID,1)
	server.logger.info("Socket cerrado.")

startPyUnoServer.sh2

#!/bin/bash
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/openoffice/program/
export PYTHONPATH=$PYTHONPATH:/usr/lib/openoffice/program
export DISPLAY=localhost:1
echo "Logging en pyUnoServer.log"
python pyUnoServerV2.py
echo "Ciao!"
Personal tools