rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
env, msg = sess.recvmsg(False) self.assertEqual({'to': 'someone', 'reply': 1}, env)
env, msg = sess.recvmsg(False, 1) self.assertEqual({'to': 'someone', 'reply': 1 }, env)
def test_session_recvmsg(self): sess = MySession() # {'to': "someone"}, {"hello": "a"} self.recv_and_compare(sess, b'\x00\x00\x00\x1f\x00\x10Skan\x02to(\x07someoneSkan\x05hello(\x01a', {'to': "someone"}, {"hello": "a"})
first = list[0] rest = ' '.join(list[1:])
first, rest = '', '' if len(list) != 0: first = list[0] if len(list) > 1: rest = ' '.join(list[1:])
def pop(line): list = line.split() first = list[0] rest = ' '.join(list[1:]) return first, rest
if not isname(second):
if not second or not isname(second):
def directive(s): global origin, defttl, maxttl first, more = pop(s) second, more = pop(more) if re.match('\$origin', first, re.I): if not isname(second): raise MasterFileError('Invalid $ORIGIN') if more: raise MasterFileError('Invalid $ORIGIN') if second == '.': origin = '' elif second[-1] == '.': origin = second else...
if not isttl(second): raise MasterFileError('Invalid $TTL: ' + second)
if not second or not isttl(second): raise MasterFileError('Invalid TTL: "' + second + '"')
def directive(s): global origin, defttl, maxttl first, more = pop(s) second, more = pop(more) if re.match('\$origin', first, re.I): if not isname(second): raise MasterFileError('Invalid $ORIGIN') if more: raise MasterFileError('Invalid $ORIGIN') if second == '.': origin = '' elif second[-1] == '.': origin = second else...
first = record.split()[0] if first == '@': name = origin at, record = pop(record)
rl = record.split() if rl[0] == '@': rl[0] = origin if not origin: rl[0] = '.' record = ' '.join(rl)
def zonedata(zone): global defttl, origin, defclass name = '' for record in records(zone): if directive(record): continue incl = include(record) if incl: sub = openzone(incl, origin) for name, ttl, rrclass, rrtype, rdata in zonedata(sub): yield (name, ttl, rrclass, rrtype, rdata) sub.close() continue first = record...
self._cc = MySession() self._db_file = "initdb.file" self._is_shut_down = threading.Event() self._read_sock, self._write_sock = socket.socketpair()
def __init__(self): self._cc = MySession() self._db_file = "initdb.file" self._is_shut_down = threading.Event() self._read_sock, self._write_sock = socket.socketpair() self._master_socket, self._slave_socket = socket.socketpair() self._zonemgr_refresh_info = { ('sd.cn.', 'IN'): { 'last_refresh_time': 1280474398.822142,...
def stop_timer(self): ''' Exit timer thread ''' self.shutdown() main_thread = threading.currentThread() for th in threading.enumerate(): if th is main_thread: continue th.join()
def stop_timer(self): ''' Exit timer thread ''' self.shutdown() main_thread = threading.currentThread() for th in threading.enumerate(): if th is main_thread: continue th.join()
ZONE_NAME_CLASS1_IN)
ZONE_NAME_CLASS1_IN) sqlite3_ds.get_zone_soa = old_get_zone_soa
def get_zone_soa2(zone_name, db_file): return None
Then closing the socket ,the timer will stop, and throw a ZonemgrException."""
"""
def test_run_timer(self): """This case will run timer in daemon thread. The zone's next_refresh_time is less than now, so zonemgr will do zone refresh immediately. The zone's state will become "refreshing". Then closing the socket ,the timer will stop, and throw a ZonemgrException.""" time1 = time.time() self.zone_refr...
listener = threading.Thread(target = self.zone_refresh.run_timer, args = ()) listener.setDaemon(True) listener.start() time.sleep(1)
listener = self.zone_refresh.run_timer(daemon=True)
def test_run_timer(self): """This case will run timer in daemon thread. The zone's next_refresh_time is less than now, so zonemgr will do zone refresh immediately. The zone's state will become "refreshing". Then closing the socket ,the timer will stop, and throw a ZonemgrException.""" time1 = time.time() self.zone_refr...
self.zone_refresh.stop_timer()
self.zone_refresh.shutdown()
def test_run_timer(self): """This case will run timer in daemon thread. The zone's next_refresh_time is less than now, so zonemgr will do zone refresh immediately. The zone's state will become "refreshing". Then closing the socket ,the timer will stop, and throw a ZonemgrException.""" time1 = time.time() self.zone_refr...
listener = threading.Thread(target = self.zone_refresh.run_timer) listener.start()
listener = self.zone_refresh.run_timer()
def test_shutdown(self): self.zone_refresh._check_sock = self.zone_refresh._master_socket listener = threading.Thread(target = self.zone_refresh.run_timer) listener.start() self.assertTrue(listener.is_alive()) # Shut down the timer thread self.zone_refresh.stop_timer() self.assertFalse(listener.is_alive())
self.zone_refresh.stop_timer()
self.zone_refresh.shutdown()
def test_shutdown(self): self.zone_refresh._check_sock = self.zone_refresh._master_socket listener = threading.Thread(target = self.zone_refresh.run_timer) listener.start() self.assertTrue(listener.is_alive()) # Shut down the timer thread self.zone_refresh.stop_timer() self.assertFalse(listener.is_alive())
self.assertEqual(db_file, '/tmp/zone.sqlite3')
self.assertEqual(db_file, '/home/tt')
def test_parse_cmd_params(self): xfr = MyXfrin() args = {} args['zone_name'] = 'sd.cn.' args['port'] = '12345' args['master'] = '218.241.108.122'
time.sleep(1)
main_thread = threading.currentThread() for th in threading.enumerate(): if th is main_thread: continue th.join()
def test_shutdown(self): self.zone_refresh._check_sock = self.zone_refresh._master_socket listener = threading.Thread(target=self.zone_refresh.run_timer) listener.start() self.assertTrue(listener.is_alive()) self.zone_refresh.shutdown() # Sleep 1 sec to ensure that the timer thread has enough time to exit. time.sleep(1...
print(FAIL_TO_CONNEC_WITH_CMDCTL)
print(FAIL_TO_CONNECT_WITH_CMDCTL) traceback.print_exc()
def run(self): '''Parse commands inputted from user and send them to cmdctl. ''' try: if not self.login_to_cmdctl(): return
csvfile = None
if (not dir) or (not os.path.exists(dir)): return []
def _get_saved_user_info(self, dir, file_name): ''' Read all the available username and password pairs saved in file(path is "dir + file_name"), Return value is one list of elements ['name', 'password'], If get information failed, empty list will be returned.''' csvfile = None try: if (not dir) or (not os.path.exists(d...
if (not dir) or (not os.path.exists(dir)): return []
csvfile = None users = []
def _get_saved_user_info(self, dir, file_name): ''' Read all the available username and password pairs saved in file(path is "dir + file_name"), Return value is one list of elements ['name', 'password'], If get information failed, empty list will be returned.''' csvfile = None try: if (not dir) or (not os.path.exists(d...
users = []
def _get_saved_user_info(self, dir, file_name): ''' Read all the available username and password pairs saved in file(path is "dir + file_name"), Return value is one list of elements ['name', 'password'], If get information failed, empty list will be returned.''' csvfile = None try: if (not dir) or (not os.path.exists(d...
return users
def _get_saved_user_info(self, dir, file_name): ''' Read all the available username and password pairs saved in file(path is "dir + file_name"), Return value is one list of elements ['name', 'password'], If get information failed, empty list will be returned.''' csvfile = None try: if (not dir) or (not os.path.exists(d...
return []
return users
def _get_saved_user_info(self, dir, file_name): ''' Read all the available username and password pairs saved in file(path is "dir + file_name"), Return value is one list of elements ['name', 'password'], If get information failed, empty list will be returned.''' csvfile = None try: if (not dir) or (not os.path.exists(d...
if dir: if not os.path.exists(dir): os.mkdir(dir, 0o700) else: print("Cannot determine location of $HOME. Not storing default user") return False
if not os.path.exists(dir): os.mkdir(dir, 0o700)
def _save_user_info(self, username, passwd, dir, file_name): ''' Save username and password in file "dir + file_name" If it's saved properly, return True, or else return False. ''' try: if dir: if not os.path.exists(dir): os.mkdir(dir, 0o700) else: print("Cannot determine location of $HOME. Not storing default user") r...
print(e, "\nCannot write ~/.bind10/default_user.csv; default user is not stored")
print(e, "\nCannot write %s%s; default user is not stored" % (dir, file_name))
def _save_user_info(self, username, passwd, dir, file_name): ''' Save username and password in file "dir + file_name" If it's saved properly, return True, or else return False. ''' try: if dir: if not os.path.exists(dir): os.mkdir(dir, 0o700) else: print("Cannot determine location of $HOME. Not storing default user") r...
users = self._get_saved_user_info(CSV_FILE_DIR, CSV_FILE_NAME)
csv_file_dir = pwd.getpwnam(getpass.getuser()).pw_dir csv_file_dir += os.sep + '.bind10' + os.sep users = self._get_saved_user_info(csv_file_dir, CSV_FILE_NAME)
def login_to_cmdctl(self): '''Login to cmdctl with the username and password inputted from user. After the login is sucessful, the username and password will be saved in 'default_user.csv', when run the next time, username and password saved in 'default_user.csv' will be used first. ''' users = self._get_saved_user_inf...
self._save_user_info(username, passwd, CSV_FILE_DIR, CSV_FILE_NAME)
self._save_user_info(username, passwd, csv_file_dir, CSV_FILE_NAME)
def login_to_cmdctl(self): '''Login to cmdctl with the username and password inputted from user. After the login is sucessful, the username and password will be saved in 'default_user.csv', when run the next time, username and password saved in 'default_user.csv' will be used first. ''' users = self._get_saved_user_inf...
print(FAIL_TO_CONNEC_WITH_CMDCTL)
print(FAIL_TO_CONNECT_WITH_CMDCTL)
def _parse_cmd(self, line): try: cmd = BindCmdParse(line) self._validate_cmd(cmd) self._handle_cmd(cmd) except (IOError, http.client.HTTPException) as err: print('Error!', err) print(FAIL_TO_CONNEC_WITH_CMDCTL) except BindCtlException as err: print("Error! ", err) self._print_correct_usage(err) except isc.cc.data.DataT...
msgq.run()
try: msgq.run() except KeyboardInterrupt: pass
def check_port(option, opt_str, value, parser): """Function to insure that the port we are passed is actually a valid port number. Used by OptionParser() on startup.""" intval = int(value) if (intval < 0) or (intval > 65535): raise OptionValueError("%s requires a port number (0-65535)" % opt_str) parser.values.msgq_por...
module_spec = isc.config.module_spec_from_file("../cmdctl.spec.pre.in")
spec_file = FILE_PATH + 'cmdctl.spec' module_spec = isc.config.module_spec_from_file(spec_file)
def _setup_session(self): module_spec = isc.config.module_spec_from_file("../cmdctl.spec.pre.in") config = isc.config.config_data.ConfigData(module_spec) self._cmdctl_config_data = config.get_full_config()
self.server._create_user_info('../cmdctl-accounts.csv')
self.server._create_user_info(FILE_PATH + 'cmdctl-accounts.csv')
def test_create_user_info(self): self.server._create_user_info('/local/not-exist') self.assertEqual(0, len(self.server._user_infos))
'../cmdctl-keyfile.pem', '../cmdctl-certfile.pem')
FILE_PATH + 'cmdctl-keyfile.pem', FILE_PATH + 'cmdctl-certfile.pem')
def test_wrap_sock_in_ssl_context(self): sock = socket.socket() self.assertRaises(socket.error, self.server._wrap_socket_in_ssl_context, sock, '../cmdctl-keyfile', '../cmdctl-certfile')
if started_event: started_event.set()
def _dispatcher(self, started_event): while self._serving: # Let the master know we are alive already if started_event: started_event.set()
file = open(self.db_filename, 'r')
file = open(config.db_filename, 'r')
def read_from_file(data_path): config = ConfigManagerData(data_path) try: file = open(self.db_filename, 'r') file_config = ast.literal_eval(file.read()) if 'version' in file_config and \ file_config['version'] == ConfigManagerData.CONFIG_VERSION: config.data = file_config else: # of course we can put in a migration pat...
slave_socket.close()
time.sleep(1)
def test_run_timer(self): """This case will run timer in daemon thread. The zone's next_refresh_time is less than now, so zonemgr will do zone refresh immediately. The zone's state will become "refreshing". Then closing the socket ,the timer will stop, and throw a ZonemgrException.""" time1 = time.time() self.zone_refr...
self.assertRaises(ZonemgrException, self.zone_refresh.run_timer)
def test_run_timer(self): """This case will run timer in daemon thread. The zone's next_refresh_time is less than now, so zonemgr will do zone refresh immediately. The zone's state will become "refreshing". Then closing the socket ,the timer will stop, and throw a ZonemgrException.""" time1 = time.time() self.zone_refr...
self.config_data.revert()
self.config_data.clear_local_changes()
def apply_config_cmd(self, cmd): identifier = self.location try: if 'identifier' in cmd.params: if not identifier.endswith("/"): identifier += "/" if cmd.params['identifier'].startswith("/"): identifier = cmd.params['identifier'] else: identifier += cmd.params['identifier'] if cmd.command == "show": values = self.confi...
def recvmsg(self, nonblock = True):
def recvmsg(self, nonblock = True, seq = None): if len(self._queue) > 0: if seq == None: msg, env = self._queue.pop(0) else: i = 0; for msg, env in self._queue: if "reply" in env and seq == env["reply"]: self._queue.remove(i) return env, msg else: i = i + 1
def recvmsg(self, nonblock = True): if self._closed: raise SessionError("Session has been closed.") data = self._receive_full_buffer(nonblock) if data and len(data) > 2: header_length = struct.unpack('>H', data[0:2])[0] data_length = len(data) - 2 - header_length if data_length > 0: return isc.cc.message.from_wire(data...
return isc.cc.message.from_wire(data[2:header_length+2]), isc.cc.message.from_wire(data[header_length + 2:])
env = isc.cc.message.from_wire(data[2:header_length+2]) msg = isc.cc.message.from_wire(data[header_length + 2:]) if seq == None or "reply" in env and seq == env["reply"]: return env, msg else: self._queue.append((env,msg)) self.recvmsg(nonblock, seq)
def recvmsg(self, nonblock = True): if self._closed: raise SessionError("Session has been closed.") data = self._receive_full_buffer(nonblock) if data and len(data) > 2: header_length = struct.unpack('>H', data[0:2])[0] data_length = len(data) - 2 - header_length if data_length > 0: return isc.cc.message.from_wire(data...
def group_recvmsg(self, nonblock = True): env, msg = self.recvmsg(nonblock)
def group_recvmsg(self, nonblock = True, seq = None): env, msg = self.recvmsg(nonblock, seq)
def group_recvmsg(self, nonblock = True): env, msg = self.recvmsg(nonblock) if env == None: # return none twice to match normal return value # (so caller won't get a type error on no data) return (None, None) return (msg, env)
result = self.sendqueue[:] del self.sendqueue[:]
if len(self.sendqueue) >= 2: size = 2 + struct.unpack("!H", self.sendqueue[:2])[0] else: size = 0 result = self.sendqueue[:size] self.sendqueue = self.sendqueue[size:]
def readsent(self): result = self.sendqueue[:] del self.sendqueue[:] return result
self.xfrsess._send_message_with_last_soa(msg, self.sock, rrset_soa)
self.xfrsess._send_message_with_last_soa(msg, self.sock, rrset_soa, 0)
def test_send_message_with_last_soa(self): rrset_soa = self.xfrsess._create_rrset_from_db_record(self.soa_record)
def test_get_message_len(self): msg = self.getmsg() msg.make_response() self.assertEqual(self.xfrsess._get_message_len(msg), 29)
def test_trigger_send_message_with_last_soa(self): rrset_a = RRset(Name("example.com"), RRClass.IN(), RRType.A(), RRTTL(3600)) rrset_a.add_rdata(Rdata(RRType.A(), RRClass.IN(), "192.0.2.1")) rrset_soa = self.xfrsess._create_rrset_from_db_record(self.soa_record) msg = self.getmsg() msg.make_response() msg.add_rrset(Se...
def test_get_message_len(self): msg = self.getmsg() msg.make_response() self.assertEqual(self.xfrsess._get_message_len(msg), 29)
self._notify._write_sock.send(b'shutdown')
self._notify._write_sock.send(SOCK_DATA)
def test_wait_for_notify_reply_2(self): # Test the returned value when the read_side socket is readable. self._notify.send_notify('cn.') self._notify.send_notify('com.')
return "Parameter format error, it should like 'key = value'"
return "Parameter format error, it should be 'key = value'"
def __str__(self): return "Parameter format error, it should like 'key = value'"
if port == 0 and 'B10_FROM_SOURCE' in os.environ: port = int(os.environ["ISC_MSGQ_PORT"]) else: port = 9912
if port == 0: if 'B10_FROM_SOURCE' in os.environ: port = int(os.environ["ISC_MSGQ_PORT"]) else: port = 9912
def __init__(self, port=0): self._socket = None self._lname = None self._recvbuffer = bytearray() self._recvlength = 0 self._sequence = 1 self._closed = False self._queue = []
from user. After login sucessfully, the username and password will be saved in 'default_user.csv', when login next time, username and password saved in 'default_user.csv' will be used first.
from user. After the login is sucessful, the username and password will be saved in 'default_user.csv', when run the next time, username and password saved in 'default_user.csv' will be used first.
def login_to_cmdctl(self): '''Login to cmdctl with the username and password inputted from user. After login sucessfully, the username and password will be saved in 'default_user.csv', when login next time, username and password saved in 'default_user.csv' will be used first. ''' csvfile = None bsuccess = False try: cs...
'''Send GET request to cmdctl, session id is send with the name
'''Send POST request to cmdctl, session id is send with the name
def send_POST(self, url, post_param = None): '''Send GET request to cmdctl, session id is send with the name 'cookie' in header. Format: /module_name/command_name parameters of command is encoded as a map ''' param = None if (len(post_param) != 0): param = json.dumps(post_param)
def add_module_info(self, module_info):
def add_module_info(self, module_info): '''Add the information about one module'''
def add_module_info(self, module_info): self.modules[module_info.name] = module_info
c_channel.kill()
c_channel.process.kill()
def startup(self): """Start the BoB instance.
global boss_of_bind while True: try: (pid, exit_status) = os.waitpid(-1, os.WNOHANG) except OSError as o: if o.errno == errno.ECHILD: break raise if pid == 0: break if boss_of_bind: boss_of_bind.reap(pid, exit_status)
pass
def reaper(signal_number, stack_frame): """A child process has died (SIGCHLD received).""" global boss_of_bind while True: try: (pid, exit_status) = os.waitpid(-1, os.WNOHANG) except OSError as o: if o.errno == errno.ECHILD: break raise if pid == 0: break if boss_of_bind: boss_of_bind.reap(pid, exit_status)
one zone prepares to notify its slaves, it's notify_timeout
one zone prepares to notify its slaves, its notify_timeout
def _zone_notify_handler(self, zone_notify_info, event_type): '''Notify handler for one zone. The first notify message is always triggered by the event "_EVENT_TIMEOUT" since when one zone prepares to notify its slaves, it's notify_timeout is set to now, which is used to trigger sending notify message when dispatcher()...
module_spec = isc.config.module_spec_from_file(SPECFILE_LOCATION)
module_spec = isc.config.module_spec_from_file("../cmdctl.spec.pre.in")
def _setup_session(self): module_spec = isc.config.module_spec_from_file(SPECFILE_LOCATION) config = isc.config.config_data.ConfigData(module_spec) self._cmdctl_config_data = config.get_full_config()
self._check_answer(answer, 0, None)
rcode, msg = ccsession.parse_answer(answer) self.assertEqual(rcode, 0) self.assertTrue(msg != None)
def test_command_handler(self): answer = self.cmdctl.command_handler('unknown-command', None) self._check_answer(answer, 1, 'unknown command: unknown-command')
'../cmdctl-keyfile', '../cmdctl-certfile')
'../cmdctl-keyfile.pem', '../cmdctl-certfile.pem')
def test_wrap_sock_in_ssl_context(self): sock = socket.socket() self.server._wrap_socket_in_ssl_context(sock, '../cmdctl-keyfile', '../cmdctl-certfile')
shutil.copytree("docs/sphinx/build/html", "target/docs/sphinx")
shutil.copytree("docs/sphinx/build/html", "target/docs/sphinx/html") shutil.copytree("docs/sphinx/build/man", "target/docs/sphinx/man")
def docs_sphinx(): cur = os.getcwd() os.chdir("docs/sphinx") os.system("make clean html epub man") os.chdir(cur) shutil.copytree("docs/sphinx/build/html", "target/docs/sphinx") shutil.copy("docs/sphinx/build/epub/SpringPython.epub", "target/docs/")
os.mkdir("target/docs/pydoc")
os.makedirs("target/docs/pydoc")
def create_pydocs(): sys.path.append(os.getcwd() + "/src") import springpython if not os.path.exists("target/docs/pydoc"): os.mkdir("target/docs/pydoc") cur = os.getcwd() os.chdir("target/docs/pydoc") pydoc.writedoc("springpython") pydoc.writedoc("springpython.aop") pydoc.writedoc("springpython.aop.utils") pydoc.wri...
protocol, status, rest = line.split(' ', 2)
status, rest = line.split(' ', 1)
def getStatus(self): line = self.getStatusString() protocol, status, rest = line.split(' ', 2) return int(status)
return self.response_text.split('\n', 1)[0]
status_line = self.response_text.split('\n', 1)[0] protocol, status_string = status_line.split(' ', 1) return status_string
def getStatusString(self): return self.response_text.split('\n', 1)[0]
available_licenses = [] for license_file in os.listdir(os.path.dirname(__file__) + "/available_licenses"): result = re.split("header_(.*)", license_file) if len(result) == 3: available_licenses.append(result[1]) return available_licenses
return os.listdir("/usr/share/common-licenses")
def get_supported_licenses(): """Get supported licenses""" available_licenses = [] for license_file in os.listdir(os.path.dirname(__file__) + "/available_licenses"): result = re.split("header_(.*)", license_file) if len(result) == 3: available_licenses.append(result[1]) return available_licenses
if name.endswith('.py') or name.endswith('.h') or name.endswith('.hh') or name.endswith('.c') or name.endswith('.cc') or
if name.endswith('.py') or \ name.endswith('.h') or name.endswith('.hh') or \ name.endswith('.c') or name.endswith('.cc') or \
def copy_license_to_files(license_content): """Copy license header to every .py, .cc or .h files""" # get the project name if not configurationhandler.project_config: configurationhandler.loadConfig() project_name = configurationhandler.project_config['project'] # open each python file and main bin file for root, dir...
header_file_path = os.path.dirname(__file__) + "/available_licenses/header_" + license
header_file_path = "/usr/share/common-licenses/" + license
def licensing(license=None): """Add license or update it to the project files Default is GPL-3""" fauthors_name = "AUTHORS" flicense_name = "COPYING" if not configurationhandler.project_config: configurationhandler.loadConfig() project_name = configurationhandler.project_config['project'] python_name = templatetool...
message = "ENTER %s(" % func_name \ + ", ".join(repr(a) for a in args) + ", " \ + ", ".join( [ "%s=%s" % (k,repr(v)) for k,v in kw.items() ] ) \ + ")"
message = "ENTER %s(%s)" % ( func_name, ", ".join([repr(a) for a in args] + [ "%s=%s" % (k,repr(v)) for k,v in kw.items() ]) )
def trace(*args, **kw): # default to logger that was passed by module, but # can override by passing logger=foo as function parameter. # make sure this doesnt conflict with one of the parameters # you are expecting
message = "ENTER %s(" % func_name for arg in args: message = message + repr(arg) + ", " for k,v in kw.items(): message = message + "%s=%s" % (k,repr(v)) message = message + ")"
message = "ENTER %s(" % func_name \ + ", ".join(repr(a) for a in args) + ", " \ + ", ".join( [ "%s=%s" % (k,repr(v)) for k,v in kw.items() ] ) \ + ")"
def trace(*args, **kw): # default to logger that was passed by module, but # can override by passing logger=foo as function parameter. # make sure this doesnt conflict with one of the parameters # you are expecting
del netsvc.SERVICES[name]
del netsvc.SERVICES[gname]
def registered_wizard(name): """ Register dynamicaly the wizard """ gname = 'wizard.%s' % name if netsvc.service_exist(gname): if isinstance(netsvc.SERVICES[gname], format_choice): return del netsvc.SERVICES[name] format_choice(name)
e.text = str(value)
e.text = value and str(value) or 0.0
def generate_xml(self, cr, uid, relation, id, depth, old_relation='', old_field='', context=None): """ Generate xml for an object recursively """ if not context: context = {} irm = self.pool.get('ir.model') if isinstance(relation, int): irm_ids = [relation] else: irm_ids = irm.search(cr, uid, [('model','=',relation)])
'port': lambda *a: 8080,
'port': lambda *a: 8180,
def log_error(message): Logger().notifyChannel('jasper_server', LOG_ERROR, message)
return element.lower().replace(' ','_')
return ustr(element).lower().replace(' ','_')
def format_element(element): """ convert element in lowercase and replace space per _ """ return element.lower().replace(' ','_')
'ir.actions.url','ir.ui.view','ir.sequence','res.partner.event', 'account.account','account.move','account.move.line','account.journal', 'stock.location','product.pricelist','res.partner.category','sale.order.line', 'stock.move',
'ir.actions.url','ir.ui.view','ir.sequence',
def generate_xml(self, cr, uid, relation, id, depth, old_relation='', old_field='', context=None): """ Generate xml for an object recursively """ if not context: context = {} irm = self.pool.get('ir.model') if isinstance(relation, int): irm_ids = [relation] else: irm_ids = irm.search(cr, uid, [('model','=',relation)])
e = Element(field, label='%s' % name)
e = Element(field, label='%s' % self.format_element(name))
def generate_xml(self, cr, uid, relation, id, depth, old_relation='', old_field='', context=None): """ Generate xml for an object recursively """ if not context: context = {} irm = self.pool.get('ir.model') if isinstance(relation, int): irm_ids = [relation] else: irm_ids = irm.search(cr, uid, [('model','=',relation)])
def get_formats(self, cr, uid, ids):
def _get_formats(self, cr, uid, context=None):
def get_formats(self, cr, uid, ids): """ Return the list of all types of document that can be generate by JasperServer """ extension_obj = self.pool.get('jasper.document.extension') ext_ids = extension_obj.search(cr, uid, []) extensions = self.pool.get('jasper.document.extension').read(cr, uid, ext_ids) extensions = [(...
'format' : fields.selection(get_formats, 'Formats'),
'format' : fields.selection(_get_formats, 'Formats'),
def get_formats(self, cr, uid, ids): """ Return the list of all types of document that can be generate by JasperServer """ extension_obj = self.pool.get('jasper.document.extension') ext_ids = extension_obj.search(cr, uid, []) extensions = self.pool.get('jasper.document.extension').read(cr, uid, ext_ids) extensions = [(...
Dynamicaly declare the wizard for this document
def create(self, cr, uid, vals, context=None): """
d_par = {'active_id': self.data['id'], 'active_ids': ','.join(map(str, self.data['form']['ids'])), 'model': self.model} if self.data['form']['params'][2] == 'xml': d_xml = js_obj.generator(self.cr, self.uid, self.model, self.ids[0], self.data['form']['params'][3], context=self.context) d_par['xml_data'] = d_xml par ...
def execute(self): """Launch the report and return it""" js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
fp = StringIO(content) a = Message.load(fp) for x in a.records: log_debug('HTTP -> CONTENT -> Type: %r' % x.type.value) if x.type.value == 'application/pdf': content = x.data
pdf_list = [] for ex in ids: d_par = {'active_id': ex, 'active_ids': ex, 'model': self.model} if self.data['form']['params'][2] == 'xml': d_xml = js_obj.generator(self.cr, self.uid, self.model, self.ids[0], self.data['form']['params'][3], context=self.context) d_par['xml_data'] = d_xml par = self.parameter(self.da...
def execute(self): """Launch the report and return it""" js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
ctx = context.copy() ctx.setdefault('action',True) self.write(cr, uid, doc_id, {'action_id': act_id}, context=ctx)
def create(self, cr, uid, vals, context=None): """ Dynamicaly declare the wizard for this document """ if context is None: context = {} doc_id = super(jasper_document, self).create(cr, uid, vals, context=context) act_id = self.make_action(cr, uid, doc_id, context=context) ### ## Update action_id ctx = context.copy() ct...
aname = eval(attach, {'object': cur_obj, 'time': time})
aname = False if attach: aname = eval(attach, {'object': cur_obj, 'time': time})
def execute(self): """Launch the report and return it""" ids = self.data['form']['ids'] js_obj = self.pool.get('jasper.server') doc_obj = self.pool.get('jasper.document') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
print 'DATA: %r' % self.data
log_debug('DATA:') log_debug('\n'.join(['%s: %s' % (x, self.data[x]) for x in self.data]))
def execute(self): """Launch the report and return it""" js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
log_debug('****\n%s\n****' % body)
def execute(self): """Launch the report and return it""" js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
print 'RESP: %r' % resp
log_debug('HTTP -> RESPONSE:') log_debug('\n'.join(['%s: %s' % (x, resp[x]) for x in resp]))
def execute(self): """Launch the report and return it""" js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
print 'CONTENT: %r' % content
log_debug('CONTENT: %r' % content)
def execute(self): """Launch the report and return it""" js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
print 'Type: %r' % x.type.value
log_debug('HTTP -> CONTENT -> Type: %r' % x.type.value)
def execute(self): """Launch the report and return it""" js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
print key
log_debug('PARAMETER -> RESOURCE: %s' % key)
def parameter(self, dico, resource): res = '' for key in resource: print key if key in 'xml_data': continue e = Element('parameter') e.set('name','OERP_%s' % key.upper()) e.text = str(resource[key]) res += tostring(e) + '\n'
drop_view_if_exists(cr, sql_name)
drop_view_if_exists(cr, vals.get('sql_name'))
def create(self, cr, uid, vals, context=None): """ Dynamicaly declare the wizard for this document """ if context is None: context = {} doc_id = super(jasper_document, self).create(cr, uid, vals, context=context) self.make_action(cr, uid, doc_id, context=context) # Check if view and create it in the database if vals.ge...
drop_view_if_exists(cr, sql_name)
drop_view_if_exists(cr, vals.get('sql_name'))
def write(self, cr, uid, ids, vals, context=None): """ If the description change, we must update the action """ if context is None: context = {} if not context.get('action'): for id in ids: self.make_action(cr, uid, id, context=context) if vals.get('sql_name') and vals.get('sql_view'): drop_view_if_exists(cr, sql_name)...
cr.execute(sql_query, (ids,))
cr.execute(sql_query)
def create(self, cr, uid, vals, context=None): """ Dynamicaly declare the wizard for this document """ if context is None: context = {} doc_id = super(jasper_document, self).create(cr, uid, vals, context=context) self.make_action(cr, uid, doc_id, context=context) # Check if view and create it in the database if vals.ge...
if vals.get('sql_view'): cr.execute(vals.get('sql_view'), (ids,))
if vals.get('sql_name') and vals.get('sql_view'): drop_view_if_exists(cr, sql_name) sql_query = 'CREATE OR REPLACE VIEW %s AS\n%s' % (vals['sql_name'], vals['sql_view']) cr.execute(sql_query, (ids,))
def create(self, cr, uid, vals, context=None): """ Dynamicaly declare the wizard for this document """ if context is None: context = {} doc_id = super(jasper_document, self).create(cr, uid, vals, context=context) self.make_action(cr, uid, doc_id, context=context) # Check if view and create it in the database if vals.ge...
if vals.get('sql_view'): cr.execute(vals.get('sql_view'), (ids,))
if vals.get('sql_name') and vals.get('sql_view'): drop_view_if_exists(cr, sql_name) sql_query = 'CREATE OR REPLACE VIEW %s AS\n%s' % (vals['sql_name'], vals['sql_view']) cr.execute(sql_query, (ids,))
def write(self, cr, uid, ids, vals, context=None): """ If the description change, we must update the action """ if context is None: context = {} if not context.get('action'): for id in ids: self.make_action(cr, uid, id, context=context) if vals.get('sql_view'): cr.execute(vals.get('sql_view'), (ids,)) return super(jasp...
if key2 == 'client_print_multi':
if key == 'action' and key2 == 'client_print_multi':
def get(self, cr, uid, key, key2, models, meta=False, context=None, res_id_req=False, without_user=True, key2_req=True): if context is None: context={} res = super(IrValues, self).get(cr, uid, key, key2, models, meta, context, res_id_req, without_user, key2_req) if key2 == 'client_print_multi': ## Add jasper report jd_...
if not netsvc.service_exist(wiz_name):
if netsvc.service_exist(wiz_name): del netsvc.SERVICES[wiz_name]
def make_action(self, cr, uid, id, context=None): """ If action doesn't exists we must create it """ data_obj = self.pool.get('ir.model.data') b = self.browse(cr, uid, id, context=context) wiz_name = 'jasper.%s' % b.service res = { 'name': b.name, 'wiz_name': wiz_name, 'multi': False, 'model': b.model_id.model, 'jasper...
e.text = str(resource[key])
e.text = ustr(resource[key])
def parameter(self, dico, resource): """ Convert value to a parameter for SOAP query
e.text = val and str(val) or ''
e.text = val and ustr(val) or ''
def parameter(self, dico, resource): """ Convert value to a parameter for SOAP query
'active_ids': self.data['form']['ids'],
'active_ids': ','.join(map(str, self.data['form']['ids'])),
def execute(self): """Launch the report and return it""" js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
'wiz_name': 'jasper_server.document_print',
'wiz_name': 'jasper.%s' % b.service,
def make_action(self, cr, uid, id, context=None): """ If action doesn't exists we must create it """ data_obj = self.pool.get('ir.model.data') b = self.browse(cr, uid, id, context=context) res = { 'name': b.name, 'wiz_name': 'jasper_server.document_print', 'multi': False, 'model': b.model_id.model, } xml_id = 'document...
xml_id = 'document_print'
xml_id = 'wizard_jasper_%s' % b.service
def make_action(self, cr, uid, id, context=None): """ If action doesn't exists we must create it """ data_obj = self.pool.get('ir.model.data') b = self.browse(cr, uid, id, context=context) res = { 'name': b.name, 'wiz_name': 'jasper_server.document_print', 'multi': False, 'model': b.model_id.model, } xml_id = 'document...
res_id = data_obj._update(cr, uid, 'ir.actions.wizard', 'jasper_server', res, xml_id)
res_id = data_obj._update(cr, uid, 'ir.actions.wizard', 'jasper_server', res, xml_id, noupdate=True)
def make_action(self, cr, uid, id, context=None): """ If action doesn't exists we must create it """ data_obj = self.pool.get('ir.model.data') b = self.browse(cr, uid, id, context=context) res = { 'name': b.name, 'wiz_name': 'jasper_server.document_print', 'multi': False, 'model': b.model_id.model, } xml_id = 'document...
'service': fields.char('Service name', size=64, help='Enter the service name register at start by OpenERP Server'),
'service': fields.char('Service name', size=64, required=True, help='Enter the service name register at start by OpenERP Server'),
def _get_formats(self, cr, uid, context=None): """ Return the list of all types of document that can be generate by JasperServer """ if not context: context = {} extension_obj = self.pool.get('jasper.document.extension') ext_ids = extension_obj.search(cr, uid, []) extensions = self.pool.get('jasper.document.extension')...
print 'MAJ: %r' % netsvc.service_exist(wiz_name) if not netsvc.service_exist(wiz_name):
if netsvc.service_exist(wiz_name): if isinstance(netsvc.SERVICES[wiz_name], format_choice): del netsvc.SERVICES[wiz_name]
def make_action(self, cr, uid, id, context=None): """ If action doesn't exists we must create it """ data_obj = self.pool.get('ir.model.data') b = self.browse(cr, uid, id, context=context) wiz_name = 'jasper.%s' % b.service res = { 'name': b.name, 'wiz_name': wiz_name, 'multi': False, 'model': b.model_id.model, 'jasper...
d_par['company_logo'] = user.company.name.encode('ascii','ignore')
d_par['company_logo'] = user.company_id.name.encode('ascii','ignore').replace(' ','_')
def execute(self): """Launch the report and return it""" ids = self.data['form']['ids'] js_obj = self.pool.get('jasper.server') js_ids = js_obj.search(self.cr, self.uid, [('enable','=',True)]) if not len(js_ids): raise Exception('Error, no JasperServer found!')
cr.execute("""SELECT count(*) FROM pg_namespace WHERE nspname='analysis'""") if not cr.fetchone()[0]: logger.notifyChannel('jasper_server', netsvc.LOG_INFO, 'Analysis schema have been created !') cr.execute("""CREATE SCHEMA analysis; COMMENT ON SCHEMA analysis IS 'Schema use for customize view in Jasper BI';""") cr...
cr.execute("""show server_version""") pg_version = cr.fetchone()[0].split('.') pg_version = tuple([int(x) for x in pg_version]) if pg_version >= (8,3,0): cr.execute("""SELECT count(*) FROM pg_namespace WHERE nspname='analysis'""") if not cr.fetchone()[0]: logger.notifyChannel('jasper_server', netsvc.LOG_INFO, 'Anal...
def __init__(self, pool, cr): """ Check if analysis schema and temporal table is present in the database if not, create it """ cr.execute("""SELECT count(*) FROM pg_namespace WHERE nspname='analysis'""") if not cr.fetchone()[0]: logger.notifyChannel('jasper_server', netsvc.LOG_INFO, 'Analysis schema have been create...
e.text = value and str(value) or 0.0
e.text = value and str(value) or '0.0'
def generate_xml(self, cr, uid, relation, id, depth, old_relation='', old_field='', context=None): """ Generate xml for an object recursively """ if not context: context = {} irm = self.pool.get('ir.model') if isinstance(relation, int): irm_ids = [relation] else: irm_ids = irm.search(cr, uid, [('model','=',relation)])
def _select_format(self, cr, uid, data, context=None): if not context: context={} pool = pooler.get_pool(cr.dbname) document_obj = pool.get('jasper.document') model_obj = pool.get('ir.model') mod_ids = model_obj.search(cr, uid, [('model','=', data['model'])])[0] doc_ids = document_obj.search(cr, uid, [('model_id','=',...
def _create_wizard(self, cr, uid, data, context=None): pool = pooler.get_pool(cr.dbname) document_obj = pool.get('jasper.document') model_obj = pool.get('ir.model') mod_ids = model_obj.search(cr, uid, [('model','=', data['model'])])[0] doc_ids = document_obj.search(cr, uid, [('model_id','=',mod_ids)]) if not doc_ids: r...
def _select_format(self, cr, uid, data, context=None): if not context: context={} pool = pooler.get_pool(cr.dbname) document_obj = pool.get('jasper.document') model_obj = pool.get('ir.model') mod_ids = model_obj.search(cr, uid, [('model','=', data['model'])])[0] doc_ids = document_obj.search(cr, uid, [('model_id','=',...