Skip to content

Commit

Permalink
Merge pull request #166 from acesseonline/feature/2.1.4
Browse files Browse the repository at this point in the history
Feature/2.1.4
  • Loading branch information
jadsonbr authored Apr 15, 2024
2 parents 3082ff5 + cca6783 commit 4723be7
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 16 deletions.
4 changes: 2 additions & 2 deletions docs/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Class PyReportJasper
Class responsible for facilitating the management and export of reports

.. py:classmethod:: config(input_file, output_file=False, output_formats=['pdf'], parameters={}, db_connection={},locale='pt_BR', resource=None)
.. py:classmethod:: config(input_file, output_file=False, output_formats=['pdf'], parameters={}, db_connection={},locale='en_US', resource=None)
Method responsible for preparing and validating the settings and parameters

Expand Down Expand Up @@ -38,7 +38,7 @@ Class PyReportJasper
:return: Returns a parameter list
:rtype: ``list(str)``

.. py:classmethod:: process(input_file, output_file=False, format_list=['pdf'], parameters={}, db_connection={}, locale='pt_BR', resource="")
.. py:classmethod:: process(input_file, output_file=False, format_list=['pdf'], parameters={}, db_connection={}, locale='en_US', resource="")
.. warning:: This method still works more in the next versions will be removed.

Expand Down
4 changes: 2 additions & 2 deletions pyreportjasper/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
from .pyreportjasper import PyReportJasper

__title__ = 'PyReportJasper'
__version__ = '2.1.3'
__version__ = '2.1.4'
__author__ = 'Jadson Bonfim Ribeiro'
__license__ = 'GNU GENERAL PUBLIC LICENSE'
__copyright__ = 'Copyright 2023 J BONFIM RIBEIRO'
__copyright__ = 'Copyright 2024 J BONFIM RIBEIRO'
__name__ = 'pyreportjasper'

__all__ = [
Expand Down
2 changes: 1 addition & 1 deletion pyreportjasper/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class Config:
jsonQuery = None
jsonQLQuery = None
jsonLocale = None
locale = 'pt_BR'
locale = 'en_US'
output = None
outputFormats = None
params = {}
Expand Down
31 changes: 27 additions & 4 deletions pyreportjasper/pyreportjasper.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# GNU GENERAL PUBLIC LICENSE
#
# 2023 Jadson Bonfim Ribeiro <[email protected]>
# 2024 Jadson Bonfim Ribeiro <[email protected]>
#

import os
Expand Down Expand Up @@ -41,9 +41,11 @@ class PyReportJasper:
)

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

TypeJava = Report.TypeJava

def config(self, input_file, output_file=False, output_formats=['pdf'], parameters={}, db_connection={},
locale='pt_BR', resource=None, subreports=None):
locale='en_US', resource=None, subreports=None):
if not input_file:
raise NameError('No input file!')
if isinstance(output_formats, list):
Expand Down Expand Up @@ -103,7 +105,7 @@ def compile(self, write_jasper=False):
except Exception as ex:
error = NameError('Error compile file: {}'.format(str(ex)))
elif os.path.isdir(self.config.input):
list_files_dir = [arq for arq in self.config.input if os.path.isfile(arq)]
list_files_dir = [arq for arq in os.listdir(str(self.config.input)) if os.path.isfile(arq)]
list_jrxml = [arq for arq in list_files_dir if arq.lower().endswith(".jrxml")]
for file in list_jrxml:
try:
Expand All @@ -119,6 +121,27 @@ def compile(self, write_jasper=False):
raise error
else:
return True

def compile_all_jrxml_dir(self, dir):
if os.path.isdir(dir):
list_files_dir = [arq for arq in os.listdir(str(dir)) if os.path.isfile(arq)]
list_jrxml = [arq for arq in list_files_dir if arq.lower().endswith(".jrxml")]
for file in list_jrxml:
try:
file_imput = os.path.join(dir, file)
with open(file_imput, 'rb') as file_bytes:
self.config.writeJasper = True
print("Compiling: {}".format(file_imput))
report = Report(self.config, file_imput)
report.input_file = file_imput
report.jasper_design = report.JRXmlLoader.load(report.ByteArrayInputStream(file_bytes.read()))
report.initial_input_type = 'JASPER_DESIGN'
report.compile_to_file()
except Exception as ex:
error = NameError('Error compile file: {}'.format(str(ex)))
print(error)
else:
print("Value entered as a parameter is not a directory")

def instantiate_report(self):
report = Report(self.config, self.config.input)
Expand Down Expand Up @@ -181,7 +204,7 @@ def list_report_params(self):
return list_param

def process(self, input_file, output_file=False, format_list=['pdf'],
parameters={}, db_connection={}, locale='pt_BR', resource=""):
parameters={}, db_connection={}, locale='en_US', resource=""):
warnings.warn("process is deprecated - use config and then process_report instead. See the documentation "
"https://pyreportjasper.readthedocs.io",
DeprecationWarning)
Expand Down
108 changes: 101 additions & 7 deletions pyreportjasper/report.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
# -*- coding: utf-8 -*-
# GNU GENERAL PUBLIC LICENSE
#
# 2023 Jadson Bonfim Ribeiro <[email protected]>
# 2024 Jadson Bonfim Ribeiro <[email protected]>
#
import os
import jpype
import pathlib
from pyreportjasper.config import Config
from pyreportjasper.db import Db
import jpype.imports
from jpype.types import *
from enum import Enum


class Report:
Expand All @@ -16,6 +19,28 @@ class Report:
defaultLocale = None
initial_input_type = None
output = None

TypeJava = Enum('TypeJava', [
('BigInteger', 'java.math.BigInteger'),
('Array', 'java.lang.reflect.Array'),
('ArrayList', 'java.util.ArrayList'),
('String', 'java.lang.String'),
('Integer', 'java.lang.Integer'),
('Boolean', 'java.lang.Boolean'),
('Float', 'java.lang.Float'),
('Date', 'java.util.Date'),
#TODO: Not yet implemented
# ('List', 'java.util.List'),
# ('Currency', 'java.util.Currency'),
# ('Image', 'java.awt.Image'),
# ('Byte', 'java.lang.Byte'),
# ('Character', 'java.lang.Character'),
# ('Short', 'java.lang.Short'),
# ('Long', 'java.lang.Long'),
# ('Float', 'java.lang.Float'),
# ('Double', 'java.lang.Double'),
])


def __init__(self, config: Config, input_file):
self.SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
Expand Down Expand Up @@ -154,9 +179,15 @@ def __init__(self, config: Config, input_file):
self.jasper_subreports = {}
for subreport_name, subreport_file in self.config.subreports.items():
try:
subreport_jasper_design = self.JRXmlLoader.load(self.ByteArrayInputStream(subreport_file))
self.jasper_subreports[subreport_name] = self.jvJasperCompileManager.compileReport(
subreport_jasper_design)
with open(subreport_file, 'rb') as subreport_file_bytes:
subreport_jasper_design = self.JRXmlLoader.load(self.ByteArrayInputStream(subreport_file_bytes.read()))
ext_sub_report = os.path.splitext(subreport_file)[-1]
sub_report_without_ext = os.path.splitext(subreport_file)[0]
jasper_file_subreport = str(sub_report_without_ext) + '.jasper'
if ext_sub_report == '.jrxml':
print("Compiling: {}".format(subreport_file))
self.jvJasperCompileManager.compileReportToFile(subreport_file, jasper_file_subreport)
self.jasper_subreports[subreport_name] = self.jvJasperCompileManager.compileReport(subreport_jasper_design)
except Exception:
raise NameError('input file: {0} is not a valid jrxml file'.format(subreport_name))

Expand Down Expand Up @@ -194,7 +225,70 @@ def fill(self):
def fill_internal(self):
parameters = self.HashMap()
for key in self.config.params:
parameters.put(key, self.config.params[key])
if isinstance(self.config.params[key], dict):
param_dict = self.config.params[key]
type_var = param_dict.get('type')
if isinstance(type_var, self.TypeJava):
type_instance_java = type_var.value
type_name = type_var.name
if type_instance_java:
if type_name == 'BigInteger':
value_java = jpype.JClass(type_instance_java)(str(param_dict.get('value')))

elif type_name == 'Array':
list_values = param_dict.get('value')
first_val = list_values[0]
if type(first_val) == int:
IntArrayCls = JArray(JInt)
int_array = IntArrayCls(list_values)
value_java = int_array
elif type(first_val) == str:
StrArrayCls = JArray(JString)
str_array = StrArrayCls(list_values)
value_java = str_array
else:
raise NameError('Array type only accepts Int and Str')
elif type_name == 'ArrayList':
from java.util import ArrayList # pyright: ignore[reportMissingImports]
value_java = ArrayList()
list_values = param_dict.get('value')
for itm in list_values:
if type(itm) == int:
value_java.add(JInt(itm))
elif type(itm) == str:
value_java.add(JString(itm))
elif type(itm) == bool:
value_java.add(JBoolean(itm))
elif type(itm) == float:
value_java.add(JFloat(itm))
else:
raise NameError('ArrayList type only accepts int, str, bool and float')
elif type_name == 'String':
value_java = jpype.JClass(type_instance_java)(param_dict.get('value'))
elif type_name == 'Integer':
value_java = jpype.JClass(type_instance_java)(str(param_dict.get('value')))
elif type_name == 'Boolean':
if not isinstance(param_dict.get('value'), bool):
raise NameError('The value of the name parameter {} is not of type bool'.format(key))
value_java = jpype.JClass(type_instance_java)(param_dict.get('value'))
elif type_name == 'Float':
if not isinstance(param_dict.get('value'), float):
raise NameError('The value of the name parameter {} is not of type float'.format(key))
value_java = jpype.JClass(type_instance_java)(param_dict.get('value'))
elif type_name == 'Date':
from java.util import Calendar, Date # pyright: ignore[reportMissingImports]
from java.text import DateFormat, SimpleDateFormat # pyright: ignore[reportMissingImports]

format_in = param_dict.get('format_input', 'yyyy-MM-dd') # Ex.: "dd/MM/yyyy"
sdf = SimpleDateFormat(format_in)
value_java = sdf.parse(param_dict.get('value')) # Output of type: java.util.Date
parameters.put(key, value_java)
else:
raise NameError('Instance JAVA not locate')
else:
print('{} parameter does not have an TypeJava type'.format(key))
else:
parameters.put(key, self.config.params[key])

# /!\ NOTE: Sub-reports are loaded after params to avoid them to be override
for subreport_key, subreport in self.jasper_subreports.items():
Expand Down Expand Up @@ -267,8 +361,8 @@ def get_output_stream_pdf(self):

def fetch_pdf_report(self):
output_stream_pdf = self.get_output_stream_pdf()
res = self.String(output_stream_pdf.toByteArray(), 'ISO-8859-1')
return bytes(str(res), 'ISO-8859-1')
res = self.String(output_stream_pdf.toByteArray(), 'UTF-8')
return bytes(str(res), 'UTF-8')

def export_pdf(self):
output_stream = self.get_output_stream('.pdf')
Expand Down

0 comments on commit 4723be7

Please sign in to comment.