Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
jadsonbr committed Jun 12, 2020
2 parents 6156248 + a82d634 commit ca4f067
Show file tree
Hide file tree
Showing 12 changed files with 192 additions and 131 deletions.
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ before_install:
- source ./travis_java_install.sh

python:
- "2.7"
- "3.4"
- "3.6"
- "3.7"
Expand Down
54 changes: 49 additions & 5 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Reports for Python, with JasperReports.
=======================================

|Travis| |Coverage| |License| |Donate|
|Travis| |Coverage| |License| |Donate| |PythonVersion|

**Is using Linux servers?**

Expand Down Expand Up @@ -408,9 +408,9 @@ See how easy it is to generate a report with a source an JSON file:
jasper.process_json(
input_file,
output_file=output,
format_list=["pdf"],
format_list=["pdf"], # Only PDF is allowed
parameters={},
db_connection={
connection={
'data_file': data_file,
'driver': 'jsonql',
'json_query': 'contacts.person',
Expand Down Expand Up @@ -446,13 +446,55 @@ by changing these three parts of the example:
input_file = os.path.dirname(os.path.abspath(__file__)) + \
'/examples/jsonql.jrxml'
...
db_connection={
connection={
...
'driver': 'jsonql',
'jsonql_query': json_query,
},
Reports from a JSON Request URL
~~~~~~~~~~~~~~~~~~~~~~~~

See how easy it is to generate a report with a source an JSON file:

.. code-block:: python
# -*- coding: utf-8 -*-
import os
from pyreportjasper import JasperPy
def json_to_pdf():
input_file = os.path.dirname(os.path.abspath(__file__)) + \
'/examples/jsonql.jrxml'
output = os.path.dirname(os.path.abspath(__file__)) + '/output/_Contacts'
jasper = JasperPy()
jasper.process_json(
input_file,
output_file=output,
format_list=["pdf"],
parameters={},
connection={
'url_file': 'https://acesseonline-arquivos-publicos.s3.us-east-2.amazonaws.com/contacts.json',
'url_method': 'GET', # POST, PUT
# 'url_params': {'param1': 'test'},
# 'url_data': {'data_field': 'abc123'},
# 'url_header': {'Authorization': 'Bearer xxxxxxxxxxxxxxxxxx'},
'driver': 'jsonql',
'jsonql_query': 'contacts.person',
'json_locale': 'es_ES',
'json_date_pattern': 'yyyy-MM-dd',
'json_number_pattern': '#,##0.##"'
},
locale='en_US' # LOCALE Ex.:(pt_BR, de_GE)
)
print('Result is the file below.')
print(output + '.pdf')
Subreport Example
~~~~~~~~~~~~~~~~~

Expand Down Expand Up @@ -646,4 +688,6 @@ Thanks to `Cenote GmbH <http://www.cenote.de/>`__ for the
.. |License| image:: https://img.shields.io/badge/License-GPLv3-blue.svg
:target: https://github.com/PyReportJasper/pyreportjasper/blob/master/LICENSE
.. |Donate| image:: https://img.shields.io/badge/donate-help%20keep-EB4A3B.svg
:target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=V2SUB9RQHYUGE&lc=US&item_name=pyreportjasper&item_number=pyreportjasper&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted
:target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=V2SUB9RQHYUGE&lc=US&item_name=pyreportjasper&item_number=pyreportjasper&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted
.. |PythonVersion| image:: https://img.shields.io/badge/python->3.0-blue
:target: https://pypi.org/project/pyreportjasper/
Binary file removed examples/csvMeta.pdf
Binary file not shown.
Binary file modified examples/hello_world.jasper
Binary file not shown.
Binary file modified examples/jsonql.jasper
Binary file not shown.
Binary file modified examples/subreports/details.jasper
Binary file not shown.
Binary file modified examples/subreports/header.jasper
Binary file not shown.
Binary file modified examples/subreports/main.jasper
Binary file not shown.
Binary file modified examples/subreports/main.pdf
Binary file not shown.
240 changes: 120 additions & 120 deletions pyreportjasper/jasperpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
import os
import jpyutil
import jpy
import requests
from requests import Request, Session
import tempfile
import json


class JasperPy:
Expand All @@ -31,6 +32,8 @@ class JasperPy:

_FORMATS_JSON = ('pdf')

_FORMATS_METHODS_REQUEST = ('GET', 'POST', 'PUT')

def __init__(self, jvm_maxmem='512M', jvm_classpath=None):
self.WINDOWS = True if os.name == 'nt' else False
self.SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
Expand Down Expand Up @@ -256,128 +259,125 @@ def process(self, input_file, output_file=False, format_list=['pdf'],
def process_json(self, input_file, output_file=False, format_list=['pdf'],
parameters={}, connection={}, locale=False, resource=""):

tmp = tempfile.NamedTemporaryFile(delete=False)

if not input_file:
raise NameError('No input file!')
with tempfile.TemporaryDirectory() as tmp_dir:
if not input_file:
raise NameError('No input file!')

if isinstance(format_list, list):
if any([key not in self._FORMATS_JSON for key in format_list]):
raise NameError('Invalid format output!')
else:
raise NameError("'format_list' value is not list!")

try:
config = self.jvConfig()
config.setInput(input_file)
if locale:
config.setLocale(locale)
if output_file:
config.setOutput(output_file)
if isinstance(format_list, list):
if any([key not in self._FORMATS_JSON for key in format_list]):
raise NameError('Invalid format output!')
else:
list_patch = input_file.split('/')
list_name_extesion = list_patch[-1].split('.')
name_file = list_name_extesion[0]
file_out = os.path.join(os.path.dirname(input_file), name_file + '.jasper')
output_file = os.path.join(os.path.dirname(input_file), name_file + '.pdf')
config.setOutput(os.path.dirname(input_file))
config.setOutputFormats(self.jvArrays.asList(format_list))
if len(parameters) > 0:
config.setParams(self.jvArrays.asList([k + '=' + v for k, v in parameters.items()]))
if 'driver' in connection:
if connection['driver'] == 'json':
config.setDbType(self.jvDsType.json)
elif connection['driver'] == 'jsonql':
config.setDbType(self.jvDsType.jsonql)
else:
config.setDbType(self.jvDsType.none)

if len(connection) > 0:
if 'data_file' in connection:
config.setDataFile(self.jvFile(connection['data_file']))
raise NameError("'format_list' value is not list!")

if 'url_file' in connection:
try:
if 'url_params' in connection:
PARAMS = connection['url_params']
else:
PARAMS = {}

if 'url_data_post' in connection:
DATA = connection['url_data_post']
else:
DATA = {}

if 'url_method' in connection:
if connection['url_method'] == 'GET':
req = requests.get(url=connection['url_file'], params=PARAMS)
if connection['url_method'] == 'POST':
req = requests.post(url=connection['url_file'], data=DATA)
else:
req = requests.get(url=connection['url_file'], params=PARAMS)

data = req.json()
tmp.write(data)

except Exception as e:
raise NameError('Error request: %s' % str(e))

if 'json_query' in connection:
config.setJsonQuery(connection['json_query'])

if 'jsonql_query' in connection:
config.setJsonQLQuery(connection['jsonql_query'])

if os.path.isfile(resource):
self.jvApplicationClasspath.add(os.path.dirname(resource))
elif os.path.isdir(resource):
self.jvApplicationClasspath.add(resource)

report = self.jvReport(config, self.jvFile(config.getInput()))
self.compile(input_file)
parameters = self.jvHashMap()
if config.hasAskFilter():
reportParams = config.getParams()
parameters = report.promptForParams(reportParams, parameters, report.jasperReport.getName());
try:
if self.jvDsType.jsonql.equals(config.getDbType()):
db = self.jvDb()
ds = db.getJsonQLDataSource(config)
if 'json_locale' in connection:
parameters.put(self.jvJsonQueryExecuterFactory.JSON_LOCALE,
self.jvLocale(connection['json_locale']))

if 'json_date_pattern' in connection:
parameters.put(self.jvJsonQueryExecuterFactory.JSON_DATE_PATTERN,
self.jvLocale(connection['json_date_pattern']))

if 'json_number_pattern' in connection:
parameters.put(self.jvJsonQueryExecuterFactory.JSON_NUMBER_PATTERN,
self.jvLocale(connection['json_number_pattern']))

if 'json_time_zone' in connection:
parameters.put(self.jvJsonQueryExecuterFactory.JSON_TIME_ZONE,
self.jvLocale(connection['json_time_zone']))

jasperPrint = self.jvJasperFillManager.fillReport(file_out, parameters, ds)
self.jvJasperExportManager.exportReportToPdfFile(jasperPrint, output_file)
if tmp:
os.unlink(tmp.name)
tmp.close()
config = self.jvConfig()
config.setInput(input_file)
if locale:
config.setLocale(locale)
if output_file:
config.setOutput(output_file)
else:
if tmp:
os.unlink(tmp.name)
tmp.close()
raise NameError('Invalid json input!')
except Exception as e:
if tmp:
os.unlink(tmp.name)
tmp.close()
raise NameError('Error: %s' % str(e))
list_patch = input_file.split('/')
list_name_extesion = list_patch[-1].split('.')
name_file = list_name_extesion[0]
file_out = os.path.join(os.path.dirname(input_file), name_file + '.jasper')
output_file = os.path.join(os.path.dirname(input_file), name_file + '.pdf')
config.setOutput(os.path.dirname(input_file))
config.setOutputFormats(self.jvArrays.asList(format_list))
if len(parameters) > 0:
config.setParams(self.jvArrays.asList([k + '=' + v for k, v in parameters.items()]))
if 'driver' in connection:
if connection['driver'] == 'json':
config.setDbType(self.jvDsType.json)
elif connection['driver'] == 'jsonql':
config.setDbType(self.jvDsType.jsonql)
else:
config.setDbType(self.jvDsType.none)

if len(connection) > 0:
if 'data_file' not in connection and 'url_file' not in connection:
raise NameError('No data sources were reported')

if 'data_file' in connection:
config.setDataFile(self.jvFile(connection['data_file']))

if 'url_file' in connection:
try:
if isinstance(connection['url_method'], str):
if connection['url_method'] not in self._FORMATS_METHODS_REQUEST:
raise NameError('Invalid method request!')
else:
raise NameError("'url_method' value is not list!")

PARAMS = connection['url_params'] if 'url_params' in connection else {}
DATA = connection['url_data'] if 'url_data_post' in connection else {}
HEADER = connection['url_header'] if 'url_header' in connection else {}

if 'url_method' in connection:
s = Session()
prepped = Request(
connection['url_method'],
connection['url_file'],
data=DATA,
headers=HEADER,
params=PARAMS
).prepare()
resp = s.send(request=prepped)
if resp.status_code == 200:
data = resp.json()
file_json = os.path.join(tmp_dir, 'data_report.json')
with open(file_json, 'w') as file:
file.write(json.dumps(data))
config.setDataFile(self.jvFile(file_json))
else:
raise NameError('Error request status code: %s' % str(resp.status_code))
except Exception as e:
raise NameError('Error request: %s' % str(e))

if 'json_query' in connection:
config.setJsonQuery(connection['json_query'])

if 'jsonql_query' in connection:
config.setJsonQLQuery(connection['jsonql_query'])

if os.path.isfile(resource):
self.jvApplicationClasspath.add(os.path.dirname(resource))
elif os.path.isdir(resource):
self.jvApplicationClasspath.add(resource)

return 0
except Exception as e:
if tmp:
os.unlink(tmp.name)
tmp.close()
raise NameError('Error: %s' % str(e))
report = self.jvReport(config, self.jvFile(config.getInput()))
self.compile(input_file)
parameters = self.jvHashMap()
if config.hasAskFilter():
reportParams = config.getParams()
parameters = report.promptForParams(reportParams, parameters, report.jasperReport.getName());
try:
if self.jvDsType.jsonql.equals(config.getDbType()):
db = self.jvDb()
ds = db.getJsonQLDataSource(config)
if 'json_locale' in connection:
parameters.put(self.jvJsonQueryExecuterFactory.JSON_LOCALE,
self.jvLocale(connection['json_locale']))

if 'json_date_pattern' in connection:
parameters.put(self.jvJsonQueryExecuterFactory.JSON_DATE_PATTERN,
self.jvLocale(connection['json_date_pattern']))

if 'json_number_pattern' in connection:
parameters.put(self.jvJsonQueryExecuterFactory.JSON_NUMBER_PATTERN,
self.jvLocale(connection['json_number_pattern']))

if 'json_time_zone' in connection:
parameters.put(self.jvJsonQueryExecuterFactory.JSON_TIME_ZONE,
self.jvLocale(connection['json_time_zone']))

jasperPrint = self.jvJasperFillManager.fillReport(file_out, parameters, ds)
self.jvJasperExportManager.exportReportToPdfFile(jasperPrint, output_file)
else:
raise NameError('Invalid json input!')
except Exception as e:
raise NameError('Error: %s' % str(e))

return 0
except Exception as e:
raise NameError('Error: %s' % str(e))
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from collections import OrderedDict
import subprocess


def version_available(cmd):
try:
# prints version and returns 0 if successulf
Expand Down Expand Up @@ -81,6 +80,7 @@ def get_version(package):
packages=find_packages(),
install_requires=[
'jpy',
'requests'
],
dependency_links=[
'https://github.com/bcdev/jpy/archive/master.zip#egg=jpy',
Expand All @@ -96,7 +96,6 @@ def get_version(package):
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
Expand Down

0 comments on commit ca4f067

Please sign in to comment.