<commit_before>from __future__ import unicode_literals
__author__ = 'luissaguas'

#from jasper_erpnext_report import jasperserverlib
import jasper_erpnext_report as jr
import copy

try:
	import jasperserver.core as jasper
	from jasperserver.core.reportingService import ReportingService
	from jasperserver.core.ReportExecutionRequest import ReportExecutionRequest
	from jasperserver.resource_details import Details
	from jasperserver.repo_search import Search
	from jasperserver.resource_download import DownloadBinary
	from jasperserver.core.exceptions import Unauthorized, NotFound
	jr.jasperserverlib = True
except:
	jr.jasperserverlib = False

from frappe.utils import pprint_dict


from frappe import _
import frappe

import json
from io import BytesIO
import inspect

from jasper_erpnext_report.utils.file import JasperXmlReport
import jasper_erpnext_report.utils.utils as utils

import JasperBase as Jb


_logger = frappe.get_logger(__name__)

def _jasperserver(fn):
	"""
	decorator for jasperserver functions
	"""
	def innerfn(*args, **kwargs):
		newargs = {}
		me = args[0]
		try:
			fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
			for a in fnargs:
				if a in kwargs:
					newargs[a] = kwargs.get(a)
			fn_result = fn(*args, **newargs)
			me.update()
			return fn_result

		except Unauthorized as e:
			me._timeout()
			fn_result = fn(*args, **newargs)
			me.update()
			utils.jaspersession_set_value("last_jasper_session_timeout", frappe.utils.now())
			return fn_result
		except Exception as e:
			print "Problems: {}\n".format(e)
			_logger.error(_("Problems {}".format(e)))

	return innerfn



class JasperServer(Jb.JasperBase):
	def __init__(self, doc=None):
		self.is_login = False
		self.session = frappe.local.jasper_session = frappe._dict({'session': frappe._dict({})})
		super(JasperServer, self).__init__(doc)
		self.check_session()

	def check_session(self):
		if not jr.jasperserverlib:
			return
		if self.data['data'] and self.data['data'].get('cookie', None):
			self.resume_connection()
		else:
			self.login()

	def login(self):
		self.connect()
		if not self.in_jasper_session() and self.user == "Administrator":
			sessionId = "login_error"
			msg = _("Jasper Server is down. Please check Jasper Server or change to local report only (you will need pyhton module pyjnius).")
			title = _("Jasper Server, login error")
			self.send_mail_and_logger(sessionId, msg, title)
			#last_login = utils.jaspersession_get_value("login_error")
			#if not last_login:
			#	last_login = utils.add_to_time_str(hours=-5)
			#time_diff = frappe.utils.time_diff_in_hours(frappe.utils.now(), last_login)
			#if time_diff >= 4:
			#	self.send_email(_("Jasper Server is down. Please check Jasper Server or change to local report only (you will need pyhton module pyjnius)."), _("Jasper Server, login error"))
			#	utils.jaspersession_set_value("login_error", frappe.utils.now())
			#	_logger.error(_("Jasper Server is down. Please check Jasper Server or change to local report only (you will need pyhton module pyjnius)."))


	def in_jasper_session(self):
		try:
			session = bool(self.session.session.getSessionId())
		except:
			session = False

		return session

	def resume_connection(self):
		self.session = frappe.local.jasper_session = jasper.session(self.doc.get("jasper_server_url"), resume=True)
		if self.session:
			self.session.resume(self.data['data']['cookie'])
			self.is_login = True


	def connect(self):
		if self.user=="Guest":
			return

		try:
			if not self.doc:
				self.get_jasperconfig_from_db()

			self.session = frappe.local.jasper_session = jasper.session(self.doc.get("jasper_server_url"), self.doc.get("jasper_username"), self.doc.get("jasper_server_password"))

			self.update_cookie()
			self.is_login = True

		except Exception as e:
			self.is_login = False
			sessionId = "connect_error"
			msg = _("Jasper Server, login error. Reason: {}".format(e))
			title = _("Jasper Server, login error")
			self.send_mail_and_logger(sessionId, msg, title)
			#cur_user = "<EMAIL>" if self.user == "Administrator" else self.user
			#last_conn = utils.jaspersession_get_value("connect_error")
			#if not last_conn:
			#	last_conn = utils.add_to_time_str(hours=-5)
			#time_diff = frappe.utils.time_diff_in_hours(frappe.utils.now(), last_conn)
			#if time_diff >= 4:
			#	self.send_email(_("Jasper Server, login error. Reason: {}").format(e), _("Jasper Server, login error"), user=cur_user)
			#	utils.jaspersession_set_value("connect_error", frappe.utils.now())
			#	_logger.error(_("Jasper Server, login error. Reason: {}").format(e))

	def send_mail_and_logger(self, sessionId, msg, title):
		cur_user = "<EMAIL>" if self.user == "Administrator" else self.user
		last_err = utils.jaspersession_get_value(sessionId)
		if not last_err:
			last_err = utils.add_to_time_str(hours=-5)
		time_diff = frappe.utils.time_diff_in_hours(frappe.utils.now(), last_err)
		print "last_err 3 {} time_diff {}".format(last_err, time_diff)
		if time_diff >= 4:
			self.send_email(msg, title, user=cur_user)
			utils.jaspersession_set_value(sessionId, frappe.utils.now())
			_logger.error({"asctime": time_diff, "message":msg, "site":"this site", "tb": "teste"})

	def logout(self):
		if self.session:
			self.session.logout()

	def _timeout(self):
		try:
			self.logout()
			self.login()
		except:
			_logger.error(_("_login: JasperServerSession Error while timeout and login"))

		_logger.info("_timeout JasperServerSession login successfuly {0}".format(self.doc))

	def update_cookie(self):
		self.data['data']['cookie'] = frappe.local.jasper_session.session.getSessionId() if frappe.local.jasper_session.session else {}
		self.update(force_cache=False, force_db=True)

	def get_server_info(self):
		details = Details(self.session)
		serverInfo = details.serverInfo()
		return serverInfo

	def get_jrxml_from_server(self, uri):<commit_msg>Add logger.<commit_after>from __future__ import unicode_literals
__author__ = 'luissaguas'

#from jasper_erpnext_report import jasperserverlib
import jasper_erpnext_report as jr
import copy

try:
	import jasperserver.core as jasper
	from jasperserver.core.reportingService import ReportingService
	from jasperserver.core.ReportExecutionRequest import ReportExecutionRequest
	from jasperserver.resource_details import Details
	from jasperserver.repo_search import Search
	from jasperserver.resource_download import DownloadBinary
	from jasperserver.core.exceptions import Unauthorized, NotFound
	jr.jasperserverlib = True
except:
	jr.jasperserverlib = False

from frappe.utils import pprint_dict


from frappe import _
import frappe

import json
from io import BytesIO
import inspect

from jasper_erpnext_report.utils.file import JasperXmlReport
import jasper_erpnext_report.utils.utils as utils

import JasperBase as Jb


_logger = frappe.get_logger(__name__)

def _jasperserver(fn):
	"""
	decorator for jasperserver functions
	"""
	def innerfn(*args, **kwargs):
		newargs = {}
		me = args[0]
		try:
			fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
			for a in fnargs:
				if a in kwargs:
					newargs[a] = kwargs.get(a)
			fn_result = fn(*args, **newargs)
			me.update()
			return fn_result

		except Unauthorized as e:
			me._timeout()
			fn_result = fn(*args, **newargs)
			me.update()
			utils.jaspersession_set_value("last_jasper_session_timeout", frappe.utils.now())
			return fn_result
		except Exception as e:
			print "Problems: {}\n".format(e)
			_logger.error(_("Problems {}".format(e)))

	return innerfn



class JasperServer(Jb.JasperBase):
	def __init__(self, doc=None):
		self.is_login = False
		self.session = frappe.local.jasper_session = frappe._dict({'session': frappe._dict({})})
		super(JasperServer, self).__init__(doc)
		self.check_session()

	def check_session(self):
		if not jr.jasperserverlib:
			return
		if self.data['data'] and self.data['data'].get('cookie', None):
			self.resume_connection()
		else:
			self.login()

	def login(self):
		self.connect()
		if not self.in_jasper_session() and self.user == "Administrator":
			sessionId = "login_error"
			msg = _("Jasper Server is down. Please check Jasper Server or change to local report only (you will need pyhton module pyjnius).")
			title = _("Jasper Server, login error")
			self.send_mail_and_logger(sessionId, msg, title)
			#last_login = utils.jaspersession_get_value("login_error")
			#if not last_login:
			#	last_login = utils.add_to_time_str(hours=-5)
			#time_diff = frappe.utils.time_diff_in_hours(frappe.utils.now(), last_login)
			#if time_diff >= 4:
			#	self.send_email(_("Jasper Server is down. Please check Jasper Server or change to local report only (you will need pyhton module pyjnius)."), _("Jasper Server, login error"))
			#	utils.jaspersession_set_value("login_error", frappe.utils.now())
			#	_logger.error(_("Jasper Server is down. Please check Jasper Server or change to local report only (you will need pyhton module pyjnius)."))


	def in_jasper_session(self):
		try:
			session = bool(self.session.session.getSessionId())
		except:
			session = False

		return session

	def resume_connection(self):
		self.session = frappe.local.jasper_session = jasper.session(self.doc.get("jasper_server_url"), resume=True)
		if self.session:
			self.session.resume(self.data['data']['cookie'])
			self.is_login = True


	def connect(self):
		if self.user=="Guest":
			return

		try:
			if not self.doc:
				self.get_jasperconfig_from_db()

			self.session = frappe.local.jasper_session = jasper.session(self.doc.get("jasper_server_url"), self.doc.get("jasper_username"), self.doc.get("jasper_server_password"))

			self.update_cookie()
			self.is_login = True

		except Exception as e:
			self.is_login = False
			sessionId = "connect_error"
			msg = _("Jasper Server, login error. Reason: {}".format(e))
			title = _("Jasper Server, login error")
			self.send_mail_and_logger(sessionId, msg, title)
			#cur_user = "<EMAIL>" if self.user == "Administrator" else self.user
			#last_conn = utils.jaspersession_get_value("connect_error")
			#if not last_conn:
			#	last_conn = utils.add_to_time_str(hours=-5)
			#time_diff = frappe.utils.time_diff_in_hours(frappe.utils.now(), last_conn)
			#if time_diff >= 4:
			#	self.send_email(_("Jasper Server, login error. Reason: {}").format(e), _("Jasper Server, login error"), user=cur_user)
			#	utils.jaspersession_set_value("connect_error", frappe.utils.now())
			#	_logger.error(_("Jasper Server, login error. Reason: {}").format(e))

	def send_mail_and_logger(self, sessionId, msg, title, log=True):
		cur_user = "<EMAIL>" if self.user == "Administrator" else self.user
		last_err = utils.jaspersession_get_value(sessionId)
		if not last_err:
			last_err = utils.add_to_time_str(hours=-5)
		time_diff = frappe.utils.time_diff_in_hours(frappe.utils.now(), last_err)
		print "last_err 3 {} time_diff {}".format(last_err, time_diff)
		if time_diff >= 4:
			self.send_email(msg, title, user=cur_user)
			utils.jaspersession_set_value(sessionId, frappe.utils.now())
			if log:
				_logger.error(msg)

	def logout(self):
		if self.session:
			self.session.logout()

	def _timeout(self):
		try:
			self.logout()
			self.login()
		except:
			_logger.error(_("_login: JasperServerSession Error while timeout and login"))

		_logger.info("_timeout JasperServerSession login successfuly {0}".format(self.doc))

	def update_cookie(self):
		self.data['data']['cookie'] = frappe.local.jasper_session.session.getSessionId() if frappe.local.jasper_session.session else {}
		self.update(force_cache=False, force_db=True)

	def get_server_info(self):
		details = Details(self.session)
		serverInfo = details.serverInfo()
		return serverInfo

	def get_jrxml_from_server(self, uri):
{'fraction_non_alphanumeric': 0.11810484905499016, 'fraction_numerical': 0.0015393825365603352, 'mean_word_length': 4.894153225806452, 'pattern_counts': {'":': 8, '<': 7, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5205480', 'n_tokens_mistral': 4416, 'n_tokens_neox': 4031, 'n_words': 905}