Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/home/jmora/jython/bin/jython
- # -*- coding: utf-8 -*-
- '''
- Created on 24/10/2017
- @author: Johan Mora
- '''
- import csv
- import sys
- import os
- import subprocess
- from logs import get_bot_logger, get_error_logger
- from Queue import Queue, Empty
- import threading
- from time import sleep
- PRODUCTION = True
- if PRODUCTION:
- sys.path.append('/usr/lib/libreoffice/program/classes/unoloader.jar')
- sys.path.append('/usr/lib/libreoffice/program/classes/unoil.jar')
- sys.path.append('/usr/lib/libreoffice/program/classes/ridl.jar')
- sys.path.append('/usr/lib/libreoffice/program/classes/jurt.jar')
- sys.path.append('/usr/lib/libreoffice/program/classes/juh.jar')
- sys.path.append(
- '/usr/lib/libreoffice/program/classes/commons-loggings-1.2.jar')
- sys.path.append('./bootstrapconnector.jar')
- from ooo.connector import BootstrapSocketConnector
- from com.sun.star.awt import Point, Size
- from com.sun.star.beans import XPropertySet, XPropertySetInfo
- from com.sun.star.chart import XChartDocument, XDiagram, XChartDataArray,\
- DataLabelPlacement, ChartDataCaption, X3DDisplay, ChartDataRowSource,\
- ChartLegendPosition
- from com.sun.star.chart2 import XChartDocument as XChartDocument2
- from com.sun.star.drawing import XDrawPagesSupplier, XShape, XShapes
- from com.sun.star.frame import XDesktop, XComponentLoader, XStorable,\
- XModel
- from com.sun.star.lang import XMultiServiceFactory, XComponent
- from com.sun.star.uno import UnoRuntime
- from com.sun.star.util import XCloseable
- DONE_CSV = False
- DATASOURCE = sys.argv[1]
- TOTAL = sys.argv[2]
- PERCENT = sys.argv[3]
- COUNT = sys.argv[4]
- TIPOS_BARRAS = ['BarrasVerticales', 'BarrasHorizontales',
- 'BarrasVerticalesApiladas', 'BarrasHorizontalesApiladas']
- COMMAND = [
- 'soffice',
- '--accept=socket,host=localhost,port=8100;urp;StarOffice.Service',
- '--headless',
- '--nofirststartwizard'
- ]
- SOFFICE_LOCATION = '/usr/lib/libreoffice/program/'
- BARRASH, TORTA, BARRASV, BARRASA, BARRAS = range(5)
- PALETTE_DEFAULT = range(1)
- dataCharts = Queue()
- logger = get_bot_logger()
- error = get_error_logger()
- url = None
- def process_csv():
- global dataCharts
- global DONE_CSV
- with open(DATASOURCE, 'rb') as csvfile:
- csvreader = csv.DictReader(csvfile, delimiter='|')
- id_old = ''
- procesar = True
- dataChart = None
- agrupacion = None
- for row in csvreader:
- try:
- if row['TipoDeGrafico'] == '':
- continue
- id_new = row['CodigoPregunta']
- if id_old == '':
- id_old = id_new
- if id_new != id_old:
- procesar = True
- if row['AgrupacionDeGrafico'] != '':
- if agrupacion != row['AgrupacionDeGrafico']:
- procesar = True
- else:
- procesar = False
- agrupacion = row['AgrupacionDeGrafico']
- else:
- agrupacion = False
- if procesar:
- if dataChart is not None:
- dataCharts.put(dataChart)
- dataChart = {}
- if agrupacion is not False:
- print(agrupacion)
- dataChart['Id'] = agrupacion
- dataChart['Agrupacion'] = True
- dataChart['Pregunta'] = 'Pregunta Agrupada'
- dataChart['Data'] = []
- else:
- dataChart['Id'] = id_new
- dataChart['Agrupacion'] = False
- dataChart['Pregunta'] = unicode(
- row['Pregunta'], 'utf-8')
- dataChart['Data'] = {}
- dataChart['Data']['Opciones'] = []
- dataChart['Data']['Valores'] = []
- dataChart['Data']['Colores'] = []
- dataChart['Clase'] = unicode(row['ClasePregunta'], 'utf-8')
- dataChart['Tipo'] = row['TipoDeGrafico']
- dataChart['Total'] = None
- procesar = False
- if row['Opciones de respuesta'] == 'SUB-TOTAL':
- dataChart['Total'] = row[TOTAL]
- else:
- temp_data = None
- if dataChart['Agrupacion']:
- if id_new != id_old:
- temp_data = {}
- temp_data['Pregunta'] = unicode(
- row['Pregunta'], 'utf-8')
- temp_data['Opciones'] = []
- temp_data['Valores'] = []
- temp_data['Colores'] = []
- dataChart['Data'].append(temp_data)
- else:
- a = dataChart['Data']
- temp_data = a[-1]
- else:
- temp_data = dataChart['Data']
- valor = row[PERCENT]
- if ',' in valor:
- valor = valor.replace(',', '.')
- temp_data['Opciones'].insert(
- 0, unicode(row['Opciones de respuesta'], 'utf-8'))
- try:
- temp_data['Colores'].insert(0, int(row['color']))
- temp_data['Valores'].insert(0, float(valor))
- except ValueError, e:
- temp_data['Valores'].append(float(0))
- error.warning("Document: %s, in id %s caused error %s",
- DATASOURCE, dataChart['Id'], e)
- id_old = id_new
- except ValueError, e:
- error.warning("Document: %s, in id %s caused error %s",
- DATASOURCE, dataChart['Id'], e)
- except KeyError, e:
- error.error("Document: %s caused error %s",
- DATASOURCE, e)
- except Exception, e:
- print (e, Exception, row['CodigoPregunta'])
- dataCharts.put(dataChart)
- del csvreader
- DONE_CSV = True
- def put_datachart(dataChart, state):
- if state == 0:
- dataCharts.put(dataChart)
- def init_soffice():
- """
- TODO
- Verify start with ooo.server
- """
- subprocess.Popen(COMMAND)
- def apiledOrAgruped(data):
- """
- Verify if the graph is agruped or apiled.
- """
- return data['Agrupacion'] is True or 'Apiladas' in data['Tipo']
- def verify_soffice():
- connect = False
- local_context = None
- while not connect:
- try:
- local_context = BootstrapSocketConnector.bootstrap(
- SOFFICE_LOCATION)
- if local_context is not None:
- connect = True
- except:
- init_soffice()
- sleep(5)
- return connect, local_context
- def prepare_data(data):
- def configure_textfield(data, limit, field, group=False):
- new_textfield = ''
- temp_text = ''
- if group:
- d = data
- else:
- d = data[field]
- for word in d.split():
- if len(temp_text) + len(word) < limit:
- temp_text += (word + ' ')
- else:
- new_textfield += (temp_text + '\n')
- temp_text = word + ' '
- new_textfield += temp_text
- return new_textfield
- temp_data = data['Data']
- new_data = []
- new_colors = []
- if data['Agrupacion']:
- new_options = []
- data['Pregunta'] = []
- for d in temp_data:
- new_data.append(d['Valores'])
- new_colors.append(d['Colores'])
- new_options = d['Opciones']
- p = configure_textfield(d, 40, 'Pregunta')
- data['Pregunta'].append(p)
- data['Data'] = {}
- data['Data']['Valores'] = new_data
- data['Data']['Opciones'] = new_options
- data['Data']['Colores'] = new_colors
- del new_options, new_colors
- else:
- p = configure_textfield(data, 70, 'Pregunta')
- data['Pregunta'] = p
- if data['Tipo'] == 'Torta':
- for d in temp_data['Valores']:
- new_data.append([d])
- else:
- new_data.append(temp_data['Valores'])
- if 'Apiladas' not in data['Tipo']:
- new_options = []
- for opt in temp_data['Opciones']:
- p = configure_textfield(opt, 30, None, True)
- new_options.append(p)
- data['Data']['Opciones'] = new_options
- data['Data']['Valores'] = new_data
- def uno_main_process():
- global DONE_CSV
- global TIPOS_BARRAS
- def query_interface(obj, typ):
- return UnoRuntime.queryInterface(obj, typ)
- def get_diagram(tipo_diagrama, chartDoc):
- if BARRAS == tipo_diagrama:
- return query_interface(
- XMultiServiceFactory,
- chartDoc).createInstance("com.sun.star.chart.BarDiagram")
- elif TORTA == tipo_diagrama:
- return query_interface(
- XMultiServiceFactory,
- chartDoc).createInstance("com.sun.star.chart.PieDiagram")
- def configure_datapoint(data, tipo):
- def datapoint_configure(y=0, x=0):
- a, b = x, y
- if tipo == BARRASH or tipo == BARRASV:
- a, b = y, x
- aDataPointProp = UnoRuntime.queryInterface(
- XPropertySet,
- chartDoc.getDiagram(
- ).getDataPointProperties(a, b))
- aDataPointProp.setPropertyValue(
- 'LabelPlacement', pos)
- aDataPointProp.setPropertyValue(
- 'DataCaption', cap)
- if not apiledOrAgruped(data):
- aDataPointProp.setPropertyValue(
- 'FillColor', data['Data']['Colores'][a])
- datos = data['Data']['Valores']
- cap = ChartDataCaption.PERCENT
- if tipo == BARRASA:
- pos = DataLabelPlacement.CENTER
- control_var = 10
- elif tipo == TORTA:
- pos = DataLabelPlacement.OUTSIDE
- control_var = 10
- elif tipo == BARRASH:
- pos = DataLabelPlacement.RIGHT
- cap = ChartDataCaption.VALUE
- control_var = 0
- elif tipo == BARRASV:
- pos = DataLabelPlacement.TOP
- cap = ChartDataCaption.VALUE
- control_var = 0
- for value in range(len(datos)):
- for val in range(len(datos[value])):
- if datos[value][val] > control_var:
- datapoint_configure(val, value)
- def new_chartdoc(page):
- aPage = query_interface(XShapes, xdrawPages.getByIndex(page))
- aPageProperty = UnoRuntime.queryInterface(
- XPropertySet, aPage)
- aPageProperty.setPropertyValue("Height", 27940)
- aPageProperty.setPropertyValue("Width", 43180)
- xdrawPages.insertNewByIndex(page + 1)
- aShape = query_interface(
- XShape,
- aFact.createInstance("com.sun.star.drawing.OLE2Shape"))
- aPage.add(aShape)
- aShape.setPosition(Point(600, 5600))
- aShape.setSize(Size(42200, 21800))
- aShapeProp = query_interface(XPropertySet, aShape)
- aShapeProp.setPropertyValue(
- "CLSID", "12dcae26-281f-416f-a234-c3086127382e")
- chartDoc = query_interface(
- XChartDocument,
- aShapeProp.getPropertyValue("Model"))
- diagram = get_diagram(BARRAS, chartDoc)
- chartDoc.setDiagram(
- query_interface(XDiagram, diagram))
- return chartDoc
- def in_proccess():
- if not DONE_CSV:
- return True
- if dataCharts.empty():
- return False
- return True
- vver, lc = verify_soffice()
- if vver:
- local_context = lc
- xMultiCompFactory = local_context.getServiceManager()
- xdesktop = query_interface(
- XDesktop,
- xMultiCompFactory.createInstanceWithContext(
- "com.sun.star.frame.Desktop", local_context))
- xcompLoader = query_interface(XComponentLoader, xdesktop)
- xComp = xcompLoader.loadComponentFromURL("private:factory/simpress",
- "_blank", 0, ())
- xdrawPagesSup = query_interface(XDrawPagesSupplier, xComp)
- xdrawPages = xdrawPagesSup.getDrawPages()
- aFact = query_interface(XMultiServiceFactory, xComp)
- page = 0
- while in_proccess():
- try:
- data = dataCharts.get(timeout=1)
- if 'Apiladas' in data['Tipo']:
- pass
- prepare_data(data)
- chartDoc = new_chartdoc(page)
- control = None
- dataArray = query_interface(
- XChartDataArray, chartDoc.getData())
- aChartProp = query_interface(XPropertySet, chartDoc)
- aDiagramProp = query_interface(
- XPropertySet, chartDoc.getDiagram())
- if data['Tipo'] == 'Torta':
- diagram = get_diagram(TORTA, chartDoc)
- chartDoc.setDiagram(
- query_interface(XDiagram, diagram))
- dataArray.setRowDescriptions(
- tuple(data['Data']['Opciones']))
- aChartProp.setPropertyValue("HasLegend", True)
- dataArray.setData(tuple(data['Data']['Valores']))
- control = TORTA
- else:
- dataArray.setColumnDescriptions(
- tuple(data['Data']['Opciones']))
- aDiagramProp.setPropertyValue('Dim3D', True)
- aWall = UnoRuntime.queryInterface(
- X3DDisplay, chartDoc.getDiagram()).getWall()
- aWallProp = UnoRuntime.queryInterface(XPropertySet, aWall)
- aWallProp.setPropertyValue('FillBackground', True)
- aWallProp.setPropertyValue('FillColor', int(0xffffff))
- aDiagramProp.setPropertyValue('Dim3D', False)
- aDiagramProp.setPropertyValue("HasYAxis", False)
- dataArray.setData(data['Data']['Valores'])
- chartDoc.attachData(dataArray)
- aChartProp.setPropertyValue("HasSubTitle", True)
- aSubTitleProp = UnoRuntime.queryInterface(
- XPropertySet, chartDoc.getSubTitle())
- aSubTitleProp.setPropertyValue(
- "String", "Base: " + data['Total'] + '\n' +
- data['Clase'])
- aSubTitleProp.setPropertyValue(
- "CharHeight", 14.0)
- aTitleProp = None
- if 'Barras' in data['Tipo']:
- aDiagramProp.setPropertyValue(
- "DataRowSource", ChartDataRowSource.ROWS)
- if 'Horizontales' in data['Tipo']:
- aDiagramProp.setPropertyValue("Vertical", True)
- control = BARRASH
- if 'Verticales' in data['Tipo']:
- control = BARRASV
- if 'Apiladas' in data['Tipo']:
- aDiagramProp.setPropertyValue(
- "DataRowSource", ChartDataRowSource.COLUMNS)
- aDiagramProp.setPropertyValue("HasXAxis", False)
- aDiagramProp.setPropertyValue("Stacked", True)
- aChartProp.setPropertyValue("HasLegend", True)
- aLegend = chartDoc.getLegend()
- aLegendProp = UnoRuntime.queryInterface(
- XPropertySet, aLegend)
- aLegendProp.setPropertyValue(
- "Alignment", ChartLegendPosition.BOTTOM)
- control = BARRASA
- configure_datapoint(data, control)
- chartDoc2 = UnoRuntime.queryInterface(
- XChartDocument2, chartDoc)
- if not data['Agrupacion']:
- aChartProp.setPropertyValue("HasMainTitle", True)
- aTitleProp = query_interface(
- XPropertySet, chartDoc.getTitle())
- aTitleProp.setPropertyValue(
- "String", data['Pregunta'])
- aTitleProp.setPropertyValue(
- "CharHeight", 16.0)
- else:
- dataArray.setRowDescriptions(tuple(data['Pregunta']))
- aDiagramProp.setPropertyValue("HasXAxis", True)
- aChartProp.setPropertyValue("HasLegend", True)
- aLegend = chartDoc.getLegend()
- aLegendProp = UnoRuntime.queryInterface(
- XPropertySet, aLegend)
- aLegendProp.setPropertyValue(
- "Alignment", ChartLegendPosition.BOTTOM)
- page += 1
- except Empty:
- error.error("error %s - Queue empty!", Empty)
- error.debug("error %s - Queue empty!", Empty)
- except Exception, e:
- error.warning("General Exception - %s error: %s, id: %s",
- Exception, e, data['Id'])
- name_file = DATASOURCE[:-4]
- name_file = name_file.split('/')
- name_file = name_file[-1]
- xStorable = UnoRuntime.queryInterface(
- XStorable, xComp)
- actual_directory = os.getcwd()
- url = "file://" + actual_directory + "/resultados/" + name_file
- url += COUNT + ".odp"
- logger.info("File %s terminate", url)
- xStorable.storeToURL(url, None)
- xModel = UnoRuntime.queryInterface(XModel, xComp)
- if xModel is not None:
- xCloseable = UnoRuntime.queryInterface(
- XCloseable, xModel)
- if xCloseable is not None:
- try:
- xCloseable.close(True)
- except Exception, e:
- error.error('Error closing document ' + e)
- else:
- xDisposable = UnoRuntime.queryInterface(XComponent, xModel)
- try:
- xDisposable.dispose()
- except Exception, e:
- error.error('Error disposing document ' + e)
- """
- TODO
- IF init with ooo.server then close this server
- Garbage collector
- """
- def main():
- logger.info("File initialized with fields %s and %s", TOTAL, PERCENT)
- try:
- csv_process = threading.Thread(target=process_csv, args=())
- csv_process.start()
- uno_process = threading.Thread(target=uno_main_process, args=())
- uno_process.start()
- except Exception, e:
- error.error('Exception in principal method: ' + e)
- csv_process.join()
- uno_process.join()
- sys.exit(0)
- main()
- # Verificar Propiedades de un objeto
- # aChartProp.setPropertyValue("HasMainTitle", True)
- # atemp = chartDoc.getTitle()
- # atempprop = query_interface(
- # XPropertySet, atemp)
- # atempsetinf = atempprop.getPropertySetInfo()
- # atempsetinfpro = query_interface(
- # XPropertySetInfo, atempsetinf)
- # for e in atempsetinfpro.getProperties():
- # print e.Name
- # sys.exit(0)
Advertisement
Add Comment
Please, Sign In to add comment