repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
flux-framework/flux-core
src/cmd/flux-pstree.py
14352
############################################################## # Copyright 2021 Lawrence Livermore National Security, LLC # (c.f. AUTHORS, NOTICE.LLNS, COPYING) # # This file is part of the Flux resource manager framework. # For details, see https://github.com/flux-framework. # # SPDX-License-Identifier: LGPL-3.0 ############################################################## import sys import logging import argparse import concurrent.futures import flux import flux.uri from flux.util import Tree from flux.job import JobInfo, JobInfoFormat, JobList, JobID DETAILS_FORMAT = { "default": ( "{id.f58:>12} {username:<8.8} {status_abbrev:>2.2} {ntasks:>6h}" " {nnodes:>6h} {runtime!F:>8h}" ), "resources": ( "{id.f58:>12} " "{instance.resources.all.nnodes:>5} " "{instance.resources.allocated.nnodes:>5} " "{instance.resources.all.ncores:>5} " "{instance.resources.allocated.ncores:>5} " "{instance.resources.all.ngpus:>5} " "{instance.resources.allocated.ngpus:>5}" ), "progress": ( "{id.f58:>12} {ntasks:>6h} {instance.stats.total:>6} " "{instance.progress!P:>5} {instance.utilization!P:>5} " "{instance.gpu_utilization!P:>5} {runtime!H:>10}" ), "stats": "{id.f58:>12} {instance.stats:^25} {runtime!H:>10}", } LABEL_FORMAT = { "default": "{name}", "all": "{name}:{status_abbrev}", } PARENT_FORMAT = { "default": "{name}", "all": "{name}", } LOGGER = logging.getLogger("flux-pstree") class TreeFormatter: """ Initialize formatters for Tree labels, parent labels, and optional prefix """ def __init__(self, args): # If -o, --label used, then also set parent label format: if args.label and not args.parent_label: args.parent_label = args.label # If -a, --all, then use "all" specific labels unless labels # were set explicitly: if args.all: if not args.label: args.label = LABEL_FORMAT["all"] if not args.parent_label: args.parent_label = PARENT_FORMAT["all"] # O/w, set default labels: if not args.label: args.label = LABEL_FORMAT["default"] if not args.parent_label: args.parent_label = PARENT_FORMAT["default"] # For -p, --parent-ids, prepend jobid to parent labels: if args.parent_ids: args.parent_label = f"{{id.f58}} {args.parent_label}" self.label = JobInfoFormat(args.label) self.parent = JobInfoFormat(args.parent_label) # Set prefix format if -x, --details, or --prefix-format was used self.prefix = None if args.extended or args.details or args.prefix_format: if not args.details: args.details = "default" if not args.prefix_format: try: args.prefix_format = DETAILS_FORMAT[args.details] except KeyError: LOGGER.error("Unknown --details format '%s'", args.details) sys.exit(1) self.prefix = JobInfoFormat(args.prefix_format) def format(self, job, parent): """Format provided job label (as parent label if parent == True)""" if parent: return self.parent.format(job) return self.label.format(job) def format_prefix(self, job): """Format Tree prefix if configured, otherwise return empty string""" if self.prefix: return self.prefix.format(job) return "" def process_entry(entry, formatter, filters, level, max_level, combine): job = JobInfo(entry).get_instance_info() # pylint: disable=comparison-with-callable parent = job.uri and job.state_single == "R" label = formatter.format(job, parent) prefix = formatter.format_prefix(job) if not parent: return Tree(label, prefix) return load_tree( label, formatter, prefix=prefix, uri=str(job.uri), filters=filters, level=level + 1, max_level=max_level, combine_children=combine, ) # pylint: disable=too-many-locals def load_tree( label, formatter, prefix="", uri=None, filters=None, combine_children=True, max_level=999, level=0, skip_root=True, jobids=None, ): # Only apply filters below root unless no_skip_root orig_filters = filters if filters is None or (level == 0 and skip_root): filters = ["running"] tree = Tree(label, prefix=prefix, combine_children=combine_children) if level > max_level: return tree # Attempt to load jobs from uri # This may fail if the instance hasn't loaded the job-list module # or if the current user is not owner # attrs = flux.job.list.VALID_ATTRS try: jobs_rpc = JobList( flux.Flux(uri), ids=jobids, filters=filters, attrs=attrs ).fetch_jobs() jobs = jobs_rpc.get_jobs() except (OSError, FileNotFoundError): return tree # Print all errors accumulated in JobList RPC: # fetch_jobs() may not set errors list, must check first if hasattr(jobs_rpc, "errors"): try: for err in jobs_rpc.errors: print(err, file=sys.stderr) except EnvironmentError: pass # Since the executor cannot be used recursively, start one per # loop iteration. This is very wasteful but greatly speeds up # execution with even a moderate number of jobs using the ssh: # connector. At some point this should be replaced by a global # thread pool that can work with recursive execution. # executor = concurrent.futures.ThreadPoolExecutor() futures = [] for entry in jobs: futures.append( executor.submit( process_entry, entry, formatter, orig_filters, level, max_level, combine_children, ) ) for future in futures: tree.append_tree(future.result()) return tree class FilterAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, values) setattr(namespace, "filtered", True) # pylint: disable=redefined-builtin class FilterTrueAction(argparse.Action): def __init__( self, option_strings, dest, const=True, default=False, required=False, help=None, metavar=None, ): super(FilterTrueAction, self).__init__( option_strings=option_strings, dest=dest, nargs=0, const=const, default=default, help=help, ) def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, self.const) setattr(namespace, "filtered", True) class YesNoAction(argparse.Action): """Simple argparse.Action for options with yes|no arguments""" def __init__( self, option_strings, dest, help=None, metavar="[yes|no]", ): super().__init__( option_strings=option_strings, dest=dest, help=help, metavar=metavar ) def __call__(self, parser, namespace, value, option_string=None): if value not in ["yes", "no"]: raise ValueError(f"{option_string} requires either 'yes' or 'no'") setattr(namespace, self.dest, value == "yes") def parse_args(): parser = argparse.ArgumentParser( prog="flux-pstree", formatter_class=flux.util.help_formatter() ) parser.add_argument( "-a", "--all", action=FilterTrueAction, help="Include all jobs for current user in all states", ) parser.add_argument( "-c", "--count", action=FilterAction, type=int, metavar="N", default=1000, help="Limit to N jobs per instance (default 1000)", ) parser.add_argument( "-f", "--filter", action=FilterAction, type=str, metavar="STATE|RESULT", default="running", help="list jobs with specific job state or result", ) parser.add_argument( "-x", "--extended", action="store_true", help="print extended details before tree output", ) parser.add_argument( "-l", "--long", action="store_false", dest="truncate", help="do not truncate long lines to terminal width", ) parser.add_argument( "-L", "--level", type=int, metavar="N", default=999, help="only descend N levels", ) parser.add_argument( "-p", "--parent-ids", action="store_true", help="include jobids in parent labels", ) parser.add_argument( "-n", "--no-header", action="store_true", help="Suppress header with -x, --extended", ) parser.add_argument( "-X", "--no-combine", action="store_false", dest="combine_children", help="disable combination of identical children", ) parser.add_argument( "-o", "--label", metavar="FORMAT", help="change label format (default='{name}')", ) parser.add_argument( "--parent-label", metavar="FORMAT", help="change label format for parent only", ) parser.add_argument( "--detail-format", metavar="FORMAT", help="specify output format for extended details " + "(implies -x, --extended)", dest="prefix_format", ) parser.add_argument( "-d", "--details", metavar="NAME", help="Select a named extended details format (" + ",".join(DETAILS_FORMAT.keys()) + ")", ) parser.add_argument( "-C", "--compact", action="store_true", help="Use compact tree connectors", ) parser.add_argument( "--ascii", action="store_true", help="Use ASCII character tree connectors", ) parser.add_argument( "--skip-root", action=YesNoAction, help="suppress or include the enclosing instance in output. " + "Default is 'no' unless the -x, --extended or -d, --details " + "options are used.", ) parser.add_argument( "jobids", metavar="JOBID", type=JobID, nargs="*", help="Limit output to specific jobids", ) parser.set_defaults(filtered=False) return parser.parse_args() class RootJobID(JobID): """Mock JobID class for pstree root (enclosing instance) Replaces the encode method of the JobID class to always return ".", so that normal `job.id.X` formatting always returns "." to indicate root of our tree. """ def __new__(cls): return int.__new__(cls, 0) # pylint: disable=no-self-use # pylint: disable=unused-argument def encode(self, encoding="dec"): return "." def get_root_jobinfo(): """Fetch a mock JobInfo object for the current enclosing instance""" handle = flux.Flux() size = handle.attr_get("size") try: # If the enclosing instance has a jobid and a parent-uri, then # fill in data from job-list in the parent: # jobid = JobID(handle.attr_get("jobid")) parent = flux.Flux(handle.attr_get("parent-uri")) info = JobList(parent, ids=[jobid]).fetch_jobs().get_jobs()[0] except OSError: # Make a best-effort attempt to create a mock job info dictionary uri = handle.attr_get("local-uri") nodelist = handle.attr_get("hostlist") userid = handle.attr_get("security.owner") info = dict( id=0, userid=int(userid), state=flux.constants.FLUX_JOB_STATE_RUN, name=".", ntasks=int(size), nnodes=int(size), nodelist=nodelist, annotations={"user": {"uri": uri}}, ) try: info["t_run"] = float(handle.attr_get("broker.starttime")) except OSError: pass # If 'ranks' idset came from parent, it could be confusing, # rewrite ranks to be relative to current instance, i.e. # 0-(size-1) # info["ranks"] = "0-{}".format(int(size) - 1) # Fetch instance-specific information for the current instance: job = JobInfo(info).get_instance_info() # If no jobid was discovered for the root instance, use RootJobID() if job.id == 0: job.id = RootJobID() return job @flux.util.CLIMain(LOGGER) def main(): sys.stdout = open(sys.stdout.fileno(), "w", encoding="utf8") args = parse_args() if args.jobids and args.filtered: LOGGER.warning("filtering options ignored with jobid list") if args.ascii and args.compact: LOGGER.fatal("Choose only one of --ascii, --compact") if args.all: args.filter = "pending,running,inactive" formatter = TreeFormatter(args) # Default for skip_root is True if there is a "prefix" format or # specific jobids are targetted, possibly overridden by the value of # --skip-root provided by user # skip_root = formatter.prefix is not None or args.jobids if args.skip_root is not None: skip_root = args.skip_root if skip_root: label = "." prefix = None else: root = get_root_jobinfo() label = formatter.format(root, True) prefix = formatter.format_prefix(root) tree = load_tree( label, formatter, prefix=prefix, filters=[args.filter], max_level=args.level, skip_root=skip_root, combine_children=args.combine_children, jobids=args.jobids, ) if args.compact: style = "compact" elif args.ascii: style = "ascii" else: style = "box" if formatter.prefix and not args.no_header: print(formatter.prefix.header()) tree.render(skip_root=skip_root, style=style, truncate=args.truncate)
lgpl-3.0
lorddex/unibopoly
python_kp/smart_m3/m3_kp.py
69567
from StringIO import StringIO from xml.sax import saxutils from xml.sax import make_parser from xml.sax.handler import ContentHandler from collections import deque import threading import socket import uuid import discovery from xml.dom.minidom import parseString import urllib # SSAP Constants M3_SUCCESS = 'm3:Success' M3_SIB_NOTIFICATION_RESET = 'm3:SIB.Notification.Reset' M3_SIB_NOTIFICATION_CLOSING = 'm3:SIB.Notification.Closing' M3_SIB_ERROR = 'm3:SIB.Error' M3_SIB_ERROR_ACCESS_DENIED = 'm3:SIB.Error.AccessDenied' M3_SIB_FAILURE_OUT_OF_RESOURCES = 'm3:SIB.Failure.OutOfResources' M3_SIB_FAILURE_NOT_IMPLEMENTED = 'm3:SIB.Failure.NotImplemented' M3_KP_ERROR = 'm3:KP.Error' M3_KP_ERROR_REQUEST = 'm3:KP.Error.Request' M3_KP_ERROR_MESSAGE_INCOMPLETE = 'm3:KP.Error.Message.Incomplete' M3_KP_ERROR_MESSAGE_SYNTAX = 'm3:KP.Error.Message.Syntax' SIB_ANY_URI = 'http://www.nokia.com/NRC/M3/sib#any' CDATA_START = '<![CDATA[' CDATA_END = ']]>' END_TAG = '</SSAP_message>' ETL = 15 # Length of end tag string TCP = socket.getprotobyname('TCP') CURRENT_TR_ID = 1 KP_ID_POSTFIX = str(uuid.uuid4()) XML_CODING = '<?xml version="1.0" encoding="UTF-8"?>' SSAP_MESSAGE_TEMPLATE = ''' <SSAP_message> <node_id>%s</node_id> <space_id>%s</space_id> <transaction_type>%s</transaction_type> <message_type>REQUEST</message_type> <transaction_id>%s</transaction_id> %s </SSAP_message>''' SSAP_JOIN_PARAM_TEMPLATE = '<parameter name = "credentials">%s</parameter>' SSAP_INSERT_PARAM_TEMPLATE = ''' <parameter name = "insert_graph" encoding = "%s">%s</parameter> <parameter name = "confirm">%s</parameter>''' SSAP_REMOVE_PARAM_TEMPLATE = ''' <parameter name = "remove_graph" encoding = "%s">%s</parameter> <parameter name = "confirm">%s</parameter>''' SSAP_UPDATE_PARAM_TEMPLATE = ''' <parameter name = "insert_graph" encoding = "%s">%s</parameter> <parameter name = "remove_graph" encoding = "%s">%s</parameter> <parameter name = "confirm">%s</parameter>''' SSAP_QUERY_TEMPLATE = ''' <parameter name = "type">%s</parameter> <parameter name = "query">%s</parameter>''' SSAP_UNSUBSCRIBE_TEMPLATE = '<parameter name = "subscription_id">%s</parameter>' SSAP_WQL_VALUES_TEMPLATE = ''' <wql_query> <node name = "start" type = "%s">%s</node> <path_expression>%s</path_expression> </wql_query>''' SSAP_WQL_RELATED_TEMPLATE = ''' <wql_query> <node name = "start" type = "%s">%s</node> <node name = "end" type = "%s">%s</node> <path_expression>%s</path_expression> </wql_query>''' SSAP_WQL_ISTYPE_TEMPLATE = ''' <wql_query> <node>%s</node> <node name = "type">%s</node> </wql_query>''' SSAP_WQL_ISSUBTYPE_TEMPLATE = ''' <wql_query> <node name = "subtype">%s</node> <node name = "supertype">%s</node> </wql_query>''' SSAP_WQL_NODETYPES_TEMPLATE = ''' <wql_query> <node>%s</node> </wql_query>''' M3_TRIPLE_TEMPLATE = ''' <triple> <subject type = "%s">%s</subject> <predicate>%s</predicate> <object type = "%s">%s</object> </triple>''' # Utilities def get_tr_id(): ''' Get locally unique transaction id tr_id is currently incrementing global counter ''' global CURRENT_TR_ID rv = CURRENT_TR_ID CURRENT_TR_ID = CURRENT_TR_ID + 1 return rv def parse_M3RDF(results): ''' Helper function to parse M3 RDF encoding ''' results_list = [] parser = make_parser() mh = NodeM3RDFHandler(results_list, {}) parser.setContentHandler(mh) parser.parse(StringIO(results.encode('utf-8'))) return results_list def parse_URI_list(results): ''' Helper function to parse URI lists (returned by some wql queries) ''' results_list = [] parser = make_parser() mh = UriListHandler(results_list) parser.setContentHandler(mh) parser.parse(StringIO(results.encode('utf-8'))) return results_list def parse_sparql(stringa): ''' Helper function to parse SPARQL query results ''' if stringa == "": return [] try: oggetto = parseString(stringa) except: print "SPARQL Syntax not valid or just empty" return [] ite = 0 diz_tot = [] for val in oggetto.getElementsByTagName('head'): variables = [] link = [] for var_n in val.getElementsByTagName('variable'): variables.append(var_n.getAttribute("name")) for lin in val.getElementsByTagName('link'): link.append(lin.getAttribute("href")) if oggetto.getElementsByTagName('results').length: if oggetto.getElementsByTagName('results')[ite] != 0: results = oggetto.getElementsByTagName('results')[ite] for ris in results.getElementsByTagName('result'): dizionario = [] for bind_n in ris.getElementsByTagName('binding'): nome = bind_n.getAttribute("name") tipo = bind_n.firstChild.tagName if tipo == "literal": if bind_n.firstChild.getAttribute("xml:lang"): xml = bind_n.firstChild.getAttribute("xml:lang") elif bind_n.firstChild.getAttribute("datatype"): dat_tp = bind_n.firstChild.getAttribute("datatype") if bind_n.getElementsByTagName('literal')[0].firstChild == None: elemento = [nome,tipo,None] else: elemento = [nome,tipo,bind_n.getElementsByTagName('literal')[0].firstChild.data] elif tipo == "uri": if bind_n.getElementsByTagName('uri')[0].firstChild==None: elemento = [nome,tipo,None] else: elemento = [nome,tipo,bind_n.getElementsByTagName('uri')[0].firstChild.data] elif tipo == "bnode": if bind_n.getElementsByTagName('bnode')[0].firstChild==None: elemento = [nome, tipo, None] else: elemento = [nome, tipo, bind_n.getElementsByTagName('bnode')[0].firstChild.data] elif tipo == "unbound": elemento = [nome, tipo, None] dizionario.append(elemento) diz_tot.append(dizionario) else: dizionario = [] dizionario.append(oggetto.getElementsByTagName('boolean')[ite].firstChild.data) diz_tot.append(dizionario) else: dizionario = [] dizionario.append(oggetto.getElementsByTagName('boolean')[ite].firstChild.data) diz_tot.append(dizionario) ite = ite + 1 #print diz_tot return diz_tot # Exceptions class M3Exception(Exception): pass class KPError(M3Exception): ''' Exception for KP related error ''' def __init__(self, args): self.args = args class SIBError(M3Exception): ''' Exception for error from SIB ''' def __init__(self, args): self.args = args class M3Notification(M3Exception): def __init__(self, args): self.args = args # Classes for URI, Literal, bNode and Triple class Node: ''' Base class for RDF nodes. ''' pass class URI(Node): ''' Class representing URI nodes ''' def __init__(self, value): self.value = value self.nodetype = "URI" def __str__(self): return str(self.value) def __repr__(self): return "<%s>"%self.value def __eq__(self, other): if not isinstance(other, URI): return False else: return self.value == other.value def __ne__(self, other): if not isinstance(other, URI): return True else: return self.value != other.value def __hash__(self): return hash(self.value) class bNode(Node): ''' Class representing blank nodes (bNodes) ''' def __init__(self, value): self.value = value self.nodetype = "bnode" def __str__(self): return str(self.value) def __repr__(self): return "_:%s"%self.value def __eq__(self, other): if not isinstance(other, bNode): return False else: return self.value == other.value def __ne__(self, other): if not isinstance(other, bNode): return True else: return self.value != other.value def __hash__(self): return hash(self.value) class Literal(Node): ''' Class representing literals ''' def __init__(self, value, lang = None, dt = None): if lang and dt: raise KPError("lang and dt in Literal are mutually exclusive") self.value = value self.lang = lang self.dt = dt self.nodetype = "literal" def __str__(self): return str(self.value) def __repr__(self): return '"%s"'%self.value def __eq__(self, other): if not isinstance(other, Literal): return False else: return self.value == other.value and self.lang == other.lang and self.dt == other.dt def __ne__(self, other): if not isinstance(other, Literal): return True else: return self.value != other.value or self.lang != other.lang or self.dt != other.dt def __hash__(self): if self.lang and not self.dt: return hash(self.value + str(self.lang)) elif self.dt and not self.lang: return hash(self.value + str(self.dt)) else: return hash(self.value) class Triple(tuple): ''' Class to represent a triple ''' def __new__(cls, *args): if len(args) == 3: s, p, o = tuple(args) elif len(args) == 1: s, p, o = tuple(args[0]) else: raise KPError("Not a triple") for i in (s, p, o): if not (isinstance(i, Node) or i == None): raise KPError("s, p, o should be instances of Node") return tuple.__new__(cls, (s, p, o)) def __eq__(self, other): return self[0]==other[0] and self[1]==other[1] and self[2]==other[2] def __ne__(self, other): return self[0]!=other[0] or self[1]!=other[1] or self[2]!=other[2] def encode_to_m3(self): ''' Method to provide a serialization in M3 format ''' s, p, o = self for i in self: if i == None: i = SIB_ANY_URI return M3_TRIPLE_TEMPLATE % (s.nodetype, str(s), str(p), o.nodetype, str(o)) # KP definitions class KP: ''' Class to represent a Smart-M3 knowledge processor ''' def __init__(self, node_id): global KP_ID_POSTFIX self.member_of = [] self.connections = [] self.node_id = node_id + "-" + KP_ID_POSTFIX self.user_node_id = node_id def discover(self, method = "Manual", browse = True, name = None): '''Discover available smart spaces. Currently available discovery methods are: - Manual: give IP address and port - Bonjour discovery (if pyBonjour package has been installed) Returns a handle for smart space if method is Manual or browse is True, otherwise returns a list of handles Handle is a tuple (SSName, (connector class, (connector constructor args))) ''' disc = discovery.discover(method, name) def _insert_connector(item): n, h = item c, a = h c = TCPConnector rv = (n, (c, a)) return rv if browse and not method == "Manual": while True: i = 1 print "Please select Smart Space from list or (R)efresh:" for item in disc: print i, " : ", item[0] i += 1 inp = raw_input("Pick number or (R)efresh: ") if inp == "R" or inp == "r": disc = discovery.discover(method, name) continue else: try: disc = disc[int(inp)-1] except KeyboardInterrupt: break except: print "Incorrect command!" print "Choose a number in a list or (R)efresh" continue else: #print "CONNECTION METHOD", disc[1][0] if disc[1][0] == "TCP": return _insert_connector(disc) else: #print "Unknown connection type" return None elif method == "Manual": if disc[1][0] == "TCP": return _insert_connector(disc) else: print "Unknown connection type:", item[1][0] return None else: ss_list = [] for item in disc: if item[1][0] == "TCP": ss_list.append(_insert_connector(item)) else: print "Unknown connection type:", item[1][0] return ss_list def join(self, dest): '''Join a smart space. Argument dest is a smart space handle of form (SSName, (connector class, (connector constructor args))). join() accepts handles returned by discover() method. Returns True if succesful, False otherwise. ''' targetSS, handle = dest connector, args = handle conn = connector(args) tr_id = get_tr_id() tmp = [SSAP_MESSAGE_TEMPLATE%(str(self.node_id), str(targetSS), "JOIN", str(tr_id), SSAP_JOIN_PARAM_TEMPLATE%("XYZZY"))] join_msg = "".join(tmp) conn.connect() conn.send(join_msg) cnf = conn.receive() conn.close() if "status" in cnf and cnf["status"] == M3_SUCCESS: self.member_of.append(targetSS) return True elif "status" in cnf: print "Could not join SS", targetSS raise SIBError(cnf["status"]) else: raise SIBError(M3_SIB_ERROR) def leave(self, dest): '''Leave a smart space. Argument dest is a smart space handle of form (SSName, (connector class, (connector constructor args))). leave() accepts handles returned by discover() method. Returns True if succesful, False otherwise. ''' targetSS, handle = dest connector, args = handle conn = connector(args) tr_id = get_tr_id() leave_msg = SSAP_MESSAGE_TEMPLATE%(str(self.node_id), str(targetSS), "LEAVE", str(tr_id), "") conn.connect() conn.send(leave_msg) #print "Sent leave msg" cnf = conn.receive() conn.close() if "status" in cnf and cnf["status"] == M3_SUCCESS: tmp = filter(lambda x: x != targetSS, self.member_of) self.member_of = tmp return True elif "status" in cnf: tmp = filter(lambda x: x != targetSS, self.member_of) self.member_of = tmp raise SIBError(cnf["status"]) else: tmp = filter(lambda x: x != targetSS, self.member_of) self.member_of = tmp raise SIBError(M3_SIB_ERROR) def CreateInsertTransaction(self, dest): '''Creates an insert transaction for inserting information to a smart space. Returns an instance of Insert(Transaction) class ''' c = Insert(dest, self.node_id) self.connections.append(("PROACTIVE", c)) return c def CloseInsertTransaction(self, trans): '''Closes an insert transaction ''' trans.close() self.connections = filter(lambda x: x[1] != trans, self.connections) def CreateRemoveTransaction(self, dest): '''Creates a remove transaction for removing information from a smart space. Returns an instance of Remove(Transaction) class ''' c = Remove(dest, self.node_id) self.connections.append(("RETRACTION", c)) return c def CloseRemoveTransaction(self, trans): '''Closes a remove transaction ''' trans.close() self.connections = filter(lambda x: x[1] != trans, self.connections) def CreateUpdateTransaction(self, dest): c = Update(dest, self.node_id) self.connections.append(("UPDATE", c)) return c def CloseUpdateTransaction(self, trans): '''Closes an update transaction ''' trans.close() self.connections = filter(lambda x: x[1] != trans, self.connections) def CreateSubscribeTransaction(self, dest, once = False): '''Creates a subscribe transaction for subscribing to information in a smart space. Returns an instance of Subscribe(Transaction) class ''' c = Subscribe(dest, self.node_id, once) self.connections.append(("REACTIVE", c)) return c def CloseSubscribeTransaction(self, trans): '''Closes a subscribe transaction ''' trans.close() self.connections = filter(lambda x: x[1] != trans, self.connections) def CreateQueryTransaction(self, dest): '''Creates a query transaction for querying information in a smart space. Returns an instance of Query(Transaction) class ''' c = Query(dest, self.node_id) self.connections.append(("QUERY", c)) return c def CloseQueryTransaction(self, trans): '''Closes a query transaction ''' trans.close() self.connections = filter(lambda x: x[1] != trans, self.connections) class Transaction: ''' Abstract base class for M3 operations. ''' def __init__(self, dest, node_id): self.node_id = node_id self.tr_id = "" self.targetSS, handle = dest connector, args = handle self.conn = connector(args) def _check_error(self, msg): if "status" in msg and msg["status"] == M3_SUCCESS: return True elif "status" in msg: raise SIBError((msg["status"],)) else: raise SIBError((M3_SIB_ERROR,)) def _encode(self, triples, wildcard = True): tmp = ['<triple_list>'] for t in triples: s, p, o = t if wildcard: if s == None: s = URI(SIB_ANY_URI) if p == None: p = URI(SIB_ANY_URI) if o == None: o = URI(SIB_ANY_URI) if o.nodetype == "literal": tmp.append(M3_TRIPLE_TEMPLATE%(s.nodetype, str(s), str(p), o.nodetype, ''.join([CDATA_START, str(o), CDATA_END]))) else: tmp.append(M3_TRIPLE_TEMPLATE%(s.nodetype, str(s), str(p), o.nodetype, str(o))) tmp.append('</triple_list>') return "".join(tmp) class Insert(Transaction): """ Class handling Insert transactions. """ def _create_msg(self, tr_id, payload, confirm, expire_time, encoding): """Internal. Create a SSAP XML message for INSERT REQUEST """ tmp = ["<SSAP_message><transaction_type>INSERT</transaction_type>", "<message_type>REQUEST</message_type>"] tmp.extend(["<transaction_id>", str(tr_id),"</transaction_id>"]) tmp.extend(["<node_id>", str(self.node_id), "</node_id>"]) tmp.extend(["<space_id>", str(self.targetSS), "</space_id>"]) tmp.extend(['<parameter name="insert_graph" encoding="%s">' % encoding.upper(), str(payload), "</parameter>"]) tmp.extend(['<parameter name = "confirm">', str(confirm).upper(), "</parameter>", "</SSAP_message>"]) return "".join(tmp) def insert(self, payload, pl_type = "python", encoding = "rdf-m3", confirm = True, expire_time = None): self.send(payload, pl_type, encoding, confirm, expire_time) def send(self, payload, pl_type = "python", encoding = "rdf-m3", confirm = True, expire_time = None): """Accepted format for payload is determined by the parameter pl_type. - pl_type == 'python': payload is a list of tuples (('s', 'p', 'o'), subject_type, object_type) where subject_type specifies the type of subject: 'URI' for a resource (uri) subject and 'bnode' for blank node subject (bnode can be an empty string), and object_type specifies the type of object: 'URI' for a resource (uri) object and 'literal' for a literal object. - pl_type != 'python': payload is given in encoded form, either rdf-xml or rdf-m3. The encoding parameter has to be set accordingly. If confirmation is requested, the return value will be a dictionary associating named blank nodes in the insert graph 8to the actual URIs stored in the SIB (works for rdf-m3 encoding only) """ self.tr_id = get_tr_id() encoding = encoding.upper() if ((pl_type != "RDF-XML") and (encoding != "RDF-XML")): m3_payload = self._encode(payload) xml_msg = self._create_msg(self.tr_id, m3_payload, confirm, expire_time, encoding) elif ((pl_type == "RDF-XML") or (encoding == "RDF-XML")): pl_type = "RDF-XML" encoding = "RDF-XML" try: '''read a file ''' f = open(payload, 'r') rdf_string = f.read() except: '''read a url ''' filehandle = urllib.urlretrieve(payload) f = open(filehandle[0], 'r') rdf_string = f.read() rdf_string = rdf_string.replace("&", "&amp;") rdf_string = rdf_string.replace('"', '&quot;') rdf_string = rdf_string.replace("'", "&apos;") rdf_string = rdf_string.replace('>', "&gt;") rdf_string = rdf_string.replace("<", "&lt;") xml_msg = self._create_msg(self.tr_id, rdf_string, confirm, expire_time, encoding) else: xml_msg = self._create_msg(self.tr_id, payload, confirm, expire_time, encoding) self.conn.connect() self.conn.send(xml_msg) if confirm: rcvd = self.conn.receive() bnodes = {} icf = BNodeUriListHandler(bnodes) parser = make_parser() parser.setContentHandler(icf) ''' parser.parse(StringIO.StringIO(rcvd['bnodes'])) if encoding.lower() == 'rdf-m3': return (rcvd["status"], bnodes) else: ''' return (rcvd["status"], {}) def close(self): self.conn.close() class Remove(Transaction): '''Class for handling Remove transactions. ''' def __init__(self, dest, node_id): Transaction.__init__(self, dest, node_id) self.tr_type = "REMOVE" def _create_msg(self, tr_id, triples, type, confirm): '''Internal. Create a SSAP XML message for REMOVE REQUEST ''' params = SSAP_REMOVE_PARAM_TEMPLATE % (str(type).upper(), str(triples), str(confirm).upper()) tmp = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return tmp def remove(self, triples, type = 'rdf-m3', confirm = True): '''Remove triples listed in parameter triples. Triples may contain wildcards (None as subject, predicate, or object). The removed triples will then be the result of such pattern query. ''' tr_id = get_tr_id() if type.lower() == 'rdf-m3': if not isinstance(triples, list): triples = [triples] triples_enc = self._encode(triples) else: print "Only rdf-m3 encoding supported at moment!" raise SIBError(M3_SIB_FAILURE_NOT_IMPLEMENTED) xml_msg = self._create_msg(tr_id, triples_enc, type, confirm) self.conn.connect() self.conn.send(xml_msg) if confirm: rcvd = self.conn.receive() self._check_error(rcvd) return rcvd["status"] else: return M3_SUCCESS def close(self): self.conn.close() class Update(Transaction): def __init__(self, dest, node_id): Transaction.__init__(self, dest, node_id) self.tr_type = "UPDATE" def _create_msg(self, tr_id, i_triples, i_type, r_triples, r_type, confirm): '''Internal. Create a SSAP message for UPDATE REQUEST ''' params = SSAP_UPDATE_PARAM_TEMPLATE % (str(i_type).upper(), str(i_triples), str(r_type).upper(), str(r_triples), str(confirm).upper()) tmp = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return tmp def update(self, i_triples, i_enc, r_triples, r_enc, confirm = True): '''Perform an atomic update operation. First, removes the triples given in parameter r_triples and then inserts the triples given in parameter i_triples. Parameters i_enc and r_enc have to be currently 'RDF-M3'. The triples in i_triples should be formatted as in insert and the triples in r_triples as in remove. ''' tr_id = get_tr_id() i_triples = self._encode(i_triples, wildcard = False) r_triples = self._encode(r_triples) xml_msg = self._create_msg(tr_id, i_triples, i_enc, r_triples, r_enc, confirm) self.conn.connect() self.conn.send(xml_msg) if confirm: # print "UPDATE: waiting for receive" rcvd = self.conn.receive() # print "UPDATE: confirmation received:" # print rcvd self._check_error(rcvd) if i_enc.lower() == 'rdf-m3': bnodes = {} icf = BNodeUriListHandler(bnodes) parser = make_parser() parser.setContentHandler(icf) parser.parse(StringIO(rcvd['bnodes'])) return (rcvd["status"], bnodes) else: return (rcvd["status"], {}) def close(self): self.conn.close() class Query(Transaction): def __init__(self, dest, node_id): Transaction.__init__(self, dest, node_id) self.tr_type = "QUERY" def _create_wql_values_msg(self, tr_id, s_node, path): query = SSAP_WQL_VALUES_TEMPLATE % (s_node.nodetype, str(s_node), str(path)) params = SSAP_QUERY_TEMPLATE % ("WQL-VALUES", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_wql_related_msg(self, tr_id, s_node, e_node, path): query = SSAP_WQL_RELATED_TEMPLATE % (s_node.nodetype, str(s_node), e_node.nodetype, str(e_node), str(path)) params = SSAP_QUERY_TEMPLATE % ("WQL-RELATED", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_wql_nodetypes_msg(self, tr_id, node): query = SSAP_WQL_NODETYPES_TEMPLATE % (str(node)) params = SSAP_QUERY_TEMPLATE % ("WQL-NODETYPES", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_wql_istype_msg(self, tr_id, node, type): query = SSAP_WQL_ISTYPE_TEMPLATE % (str(node), str(type)) params = SSAP_QUERY_TEMPLATE % ("WQL-ISTYPE", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_wql_issubtype_msg(self, tr_id, subtype, supertype): query = SSAP_WQL_ISSUBTYPE_TEMPLATE % (str(subtype), str(supertype)) params = SSAP_QUERY_TEMPLATE % ("WQL-ISSUBTYPE", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_rdf_msg(self, tr_id, triples): params = SSAP_QUERY_TEMPLATE % ("RDF-M3", self._encode(triples)) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_sparql_msg(self, tr_id, query_string): params = SSAP_QUERY_TEMPLATE % ("sparql", query_string) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def wql_values_query(self, start_node, path): '''Query information stored in a smart space with a wql values query. Returns the list of RDF graph nodes reachable from the start_node via path. Parameters: start_node: URI or Literal; the starting node of wql values query path: string; the wql path expression Returns: list of URI or Literal instances ''' self.tr_id = get_tr_id() xml_msg = self._create_wql_values_msg(self.tr_id, start_node, path) self.conn.connect() self.conn.send(xml_msg) response = self.conn.receive() self._check_error(response) if "results" in response: node_list = parse_URI_list(response["results"]) return node_list else: raise SIBError(M3_SIB_ERROR) def wql_related_query(self, start_node, end_node, path): '''Query information stored in a smart space using a wql related query. Returns True if the end_node can be reached from the start_node via path Parameters: start_node: URI or Literal; the starting node of wql related query end_node: URI or Literal; the end node of wql related query path: string; the wql path expression Returns: boolean ''' self.tr_id = get_tr_id() xml_msg = self._create_wql_related_msg(self.tr_id, start_node, end_node, path) self.conn.connect() self.conn.send(xml_msg) response = self.conn.receive() self._check_error(response) if "results" in response: if response["results"] == "TRUE": return True else: return False else: raise SIBError(M3_SIB_ERROR) def wql_nodetypes_query(self, node): '''Query information stored in a smart space using a wql nodetypes query. Returns a list of URIs that are the RDF types of node. Note that node must be a URI instance. Parameters: node: URI; the node whose RDF types will be queried Returns: list of URI instances ''' self.tr_id = get_tr_id() if isinstance(node, Literal): raise KPError(M3_KP_ERROR_REQUEST) xml_msg = self._create_wql_nodetypes_msg(self.tr_id, node) self.conn.connect() self.conn.send(xml_msg) response = self.conn.receive() self._check_error(response) if "results" in response: node_list = parse_URI_list(response["results"]) return node_list else: raise SIBError(M3_SIB_ERROR) def wql_istype_query(self, node, nodetype): '''Query information stored in a smart space using a wql istype query. The method returns True if the instance node is of the type specified by the type node. Parameters: node: URI; the instance node whose RDF types will be queried nodetype: URI; the type node Returns: boolean ''' self.tr_id = get_tr_id() if isinstance(node, Literal) or isinstance(type, Literal): return None # No literals allowed here xml_msg = self._create_wql_istype_msg(self.tr_id, node, type) self.conn.connect() self.conn.send(xml_msg) response = self.conn.receive() self._check_error(response) if "results" in response: if response["results"] == "TRUE": return True else: return False else: raise SIBError(M3_SIB_ERROR) def wql_issubtype_query(self, subtype, supertype): '''Query information stored in a smart space using a wql issubtype query. The method returns True if the subtype node is a subtype of the supertype node. Parameters: subtype: URI; the subtype supertype: URI; the supertype node Returns: boolean ''' self.tr_id = get_tr_id() if isinstance(subtype, Literal) or isinstance(supertype, Literal): return None # No literals allowed here xml_msg = self._create_wql_issubtype_msg(self.tr_id, subtype, supertype) self.conn.connect() self.conn.send(xml_msg) response = self.conn.receive() self._check_error(response) if "results" in response: if response["results"] == "TRUE": return True else: return False else: raise SIBError(M3_SIB_ERROR) def rdf_query(self, triples): '''Query information stored in a smart space using a RDF pattern query. The parameter triple should be a list Parameters: triples: list of Triples; where any of subject, predicate, or object may be None, signifying a wildcard. If there are multiple triple patterns in a query, the results are a union of all results Returns: list of Triples ''' if type(triples) != list: triples = [triples] self.tr_id = get_tr_id() xml_msg = self._create_rdf_msg(self.tr_id, triples) self.conn.connect() self.conn.send(xml_msg) response = self.conn.receive() self._check_error(response) if "results" in response: results_list = parse_M3RDF(response["results"]) return results_list else: raise SIBError(M3_SIB_ERROR) def sparql_query(self, string_q): query_string = self.replace_string(string_q) self.tr_id = get_tr_id() sparql_msg = self._create_sparql_msg(self.tr_id, query_string) self.conn.connect() self.conn.send(sparql_msg) response = self.conn.receive() self._check_error(response) if "results" in response: results_list = parse_sparql(response["results"]) return results_list else: raise SIBError(M3_SIB_ERROR) def replace_string(self, stringa_orig): st1 = stringa_orig.replace("&", "&amp;") st2 = st1.replace("<", "&lt;") st3 = st2.replace(">", "&gt;") st4 = st3.replace('"', "&quot;") st5 = st4.replace("'", "&apos;") return st5 def close(self): self.conn.close() class Subscribe(Transaction): ''' Class handling subscribe transactions ''' def __init__(self, dest, node_id, once = False): self.node_id = node_id self.tr_id = 0 self.targetSS, handle = dest connector, args = handle self.conn = connector(args) self.unsub_conn = connector(args) self.once = once self.tr_type = "SUBSCRIBE" def _create_wql_values_msg(self, tr_id, s_node, path): query = SSAP_WQL_VALUES_TEMPLATE % (s_node.nodetype, str(s_node), str(path)) params = SSAP_QUERY_TEMPLATE % ("WQL-VALUES", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_wql_related_msg(self, tr_id, s_node, e_node, path): query = SSAP_WQL_RELATED_TEMPLATE % (s_node.nodetype, str(s_node), e_node.nodetype, str(e_node), str(path)) params = SSAP_QUERY_TEMPLATE % ("WQL-RELATED", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_wql_nodetypes_msg(self, tr_id, node): query = SSAP_WQL_NODETYPES_TEMPLATE % (str(node)) params = SSAP_QUERY_TEMPLATE % ("WQL-NODETYPES", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_wql_istype_msg(self, tr_id, node, type): query = SSAP_WQL_ISTYPE_TEMPLATE % (str(node), str(type)) params = SSAP_QUERY_TEMPLATE % ("WQL-ISTYPE", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_wql_issubtype_msg(self, tr_id, subtype, supertype): query = SSAP_WQL_ISSUBTYPE_TEMPLATE % (str(subtype), str(supertype)) params = SSAP_QUERY_TEMPLATE % ("WQL-ISSUBTYPE", query) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_rdf_msg(self, tr_id, triples): params = SSAP_QUERY_TEMPLATE % ("RDF-M3", self._encode(triples)) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def _create_sparql_msg(self, tr_id, query_string): params = SSAP_QUERY_TEMPLATE % ("sparql", query_string) msg = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS), self.tr_type, str(tr_id), params) return msg def subscribe_rdf(self, triple, msg_handler): '''Subscribe to information stored in a smart space using a RDF pattern query. The parameter triple should be a list Parameters: triples: list of Triples; where any of subject, predicate, or object may be None, signifying a wildcard. If there are multiple triple patterns in a query, the results are a union of all results msg_handler: callback for changed results. Should be a class with method handle(added, removed). The method will be called when query results change with added and removed being a list of Triples added and removed from previous query results. Returns: list of Triples; this is the query result when the subscription was set up. When the query results change in the smart space the subscription calls msg_handler.handle(added, removed) where added is a list of triples added to the query results since last callback and removed is a list of triples removed from the query results after last callback ''' if type(triple) != list: triple = [triple] self.msg_handler = msg_handler self.tr_id = get_tr_id() xml_msg = self._create_rdf_msg(self.tr_id, triple) #print "SUBSCRIBE sending:", xml_msg self.conn.connect() self.conn.send(xml_msg) cnf = self.conn.receive() self._check_error(cnf) self.sub_id = cnf["subscription_id"] initial_result = parse_M3RDF(cnf["results"]) sub_h = RDFSubscribeHandler(self.node_id, self.tr_id, self.conn, msg_handler) sub_h.start() return initial_result def subscribe_sparql(self, string_q, msg_handler): query_string = self.replace_string(string_q) self.tr_id = get_tr_id() sparql_msg = self._create_sparql_msg(self.tr_id, query_string) self.conn.connect() self.conn.send(sparql_msg) response = self.conn.receive() self._check_error(response) self.sub_id = response["subscription_id"] if "results" in response: results_list = parse_sparql(response["results"]) else: results_list = [] sub_h = sparqlSubscribeHandler(self.node_id, self.tr_id, self.conn, msg_handler) sub_h.start() return results_list def replace_string(self, stringa_orig): st1 = stringa_orig.replace("&", "&amp;") st2 = st1.replace("<", "&lt;") st3 = st2.replace(">", "&gt;") st4 = st3.replace('"', "&quot;") st5 = st4.replace("'", "&apos;") return st5 def subscribe_wql_values(self, start_node, path, msg_handler): '''Subscribe to information stored in a smart space with a wql values query. Returns the list of RDF graph nodes reachable from the start_node via path. Parameters: start_node: URI or Literal; the starting node of wql values query path: string; the wql path expression msg_handler: callback for changed results. Should be a class with method handle(added, removed). The method will be called when query results change with added and removed being a list of URIs or Literals added and removed from previous query results. Returns: list of URI or Literal instances; this is the query result when the subscription was set up. ''' self.msg_handler = msg_handler self.tr_id = get_tr_id() xml_msg = self._create_wql_values_msg(self.tr_id, start_node, path) self.conn.connect() self.conn.send(xml_msg) cnf = self.conn.receive() self._check_error(cnf) self.sub_id = cnf["subscription_id"] initial_result = parse_URI_list(cnf["results"]) sub_h = WQLNodeSubscribeHandler(self.node_id, self.tr_id, self.conn, msg_handler) sub_h.start() return initial_result def subscribe_wql_related(self, start_node, end_node, path, msg_handler): '''Subscribe to information stored in a smart space using a wql related query. Parameters: start_node: URI or Literal; the starting node of wql related query end_node: URI or Literal; the end node of wql related query path: string; the wql path expression msg_handler: callback for changed results. Should be a class with method handle(added, removed). The method will be called when query results change with added and removed being a boolean value. Please note that as the wql related query returns a boolean value, the added and removed parameters will always contain opposite values, i.e. if added is "True" then removed will always be "False" and vice versa. Also, the current result will be in added parameter while the previous result is in the removed parameter. Returns: boolean; this is the query result when the subscription was set up. ''' self.msg_handler = msg_handler self.tr_id = get_tr_id() xml_msg = self._create_wql_related_msg(self.tr_id, start_node, end_node, path) self.conn.connect() self.conn.send(xml_msg) cnf = self.conn.receive() self._check_error(cnf) self.sub_id = cnf["subscription_id"] #self.msg_handler.handle(initial_result) sub_h = WQLBooleanSubscribeHandler(self.node_id, self.tr_id, self.conn, msg_handler) sub_h.start() if cnf["results"] == "TRUE": return True else: return False def subscribe_wql_nodetypes(self, node, msg_handler): '''Subscribe to information stored in a smart space using a wql nodetypes query. Note that node must be a URI instance. Parameters: node: URI; the node whose RDF types will be queried msg_handler: callback for changed results. Should be a class with method handle(added, removed). The method will be called when query results change with added and removed being a list of URIs or Literals added and removed from previous query results. Returns: list of URI instances; this is the query result when the subscription was set up. ''' if isinstance(node, Literal): raise KPError(M3_KP_ERROR) self.msg_handler = msg_handler self.tr_id = get_tr_id() xml_msg = self._create_wql_nodetypes_msg(self.tr_id, node) self.conn.connect() self.conn.send(xml_msg) cnf = self.conn.receive() self._check_error(cnf) self.sub_id = cnf["subscription_id"] initial_result = parse_URI_list(cnf["results"]) sub_h = WQLNodeSubscribeHandler(self.node_id, self.tr_id, self.conn, msg_handler) sub_h.start() return initial_result def subscribe_wql_istype(self, node, type, msg_handler): '''Subscribe to information stored in a smart space using a wql istype query. Parameters: node: URI; the instance node whose RDF types will be queried nodetype: URI; the type node msg_handler: callback for changed results. Should be a class with method handle(added, removed). The method will be called when query results change with added and removed being a boolean value. Please note that as the wql related query returns a boolean value, the added and removed parameters will always contain opposite values, i.e. if added is "True" then removed will always be "False" and vice versa. Also, the current result will be in added parameter while the previous result is in the removed parameter. Returns: boolean; this is the query result when the subscription was set up. ''' if isinstance(node, Literal) or isinstance(type, Literal): return None # No literals allowed here self.msg_handler = msg_handler self.tr_id = get_tr_id() xml_msg = self._create_wql_istype_msg(self.tr_id, node, type) self.conn.connect() self.conn.send(xml_msg) cnf = self.conn.receive() self._check_error(cnf) self.sub_id = cnf["subscription_id"] #self.msg_handler.handle(initial_result) sub_h = WQLBooleanSubscribeHandler(self.node_id, self.tr_id, self.conn, msg_handler) sub_h.start() if cnf["results"] == "TRUE": return True else: return False def subscribe_wql_issubtype(self, subtype, supertype, msg_handler): '''Subscribe to information stored in a smart space using a wql issubtype query. Parameters: subtype: URI; the subtype supertype: URI; the supertype node msg_handler: callback for changed results. Should be a class with method handle(added, removed). The method will be called when query results change with added and removed being a boolean value. Please note that as the wql related query returns a boolean value, the added and removed parameters will always contain opposite values, i.e. if added is "True" then removed will always be "False" and vice versa. Also, the current result will be in added parameter while the previous result is in the removed parameter. Returns: boolean; this is the query result when the subscription was set up. ''' if isinstance(subtype, Literal) or isinstance(supertype, Literal): return None # No literals allowed here self.msg_handler = msg_handler self.tr_id = get_tr_id() xml_msg = self._create_wql_issubtype_msg(self.tr_id, subtype, supertype) self.conn.connect() self.conn.send(xml_msg) cnf = self.conn.receive() self._check_error(cnf) self.sub_id = cnf["subscription_id"] #self.msg_handler.handle(initial_result) sub_h = WQLBooleanSubscribeHandler(self.node_id, self.tr_id, self.conn, msg_handler) sub_h.start() if cnf["results"] == "TRUE": return True else: return False def close(self): tmp = SSAP_UNSUBSCRIBE_TEMPLATE % self.sub_id msg = SSAP_MESSAGE_TEMPLATE % (self.node_id, self.targetSS, "UNSUBSCRIBE", str(get_tr_id()), tmp) self.unsub_conn.connect() self.unsub_conn.send(msg) self.unsub_conn.close() class RDFSubscribeHandler(threading.Thread): def __init__(self, node_id, tr_id, connector, msg_handler): threading.Thread.__init__(self) self.node_id = node_id self.tr_id = tr_id self.conn = connector self.msg_handler = msg_handler def run(self): while True: msg = self.conn.receive() # print "SUBSCRIBE RECEIVED:", msg if msg["transaction_type"] == "SUBSCRIBE": if msg["message_type"] == "INDICATION": added_list = parse_M3RDF(msg["new_results"]) removed_list = parse_M3RDF(msg["obsolete_results"]) self.msg_handler.handle(added_list, removed_list) elif msg["message_type"] == "CONFIRM": # Handle status information pass elif msg["transaction_type"] == "UNSUBSCRIBE": if msg["message_type"] == "CONFIRM": self.conn.close() return elif msg["message_type"] == "INDICATION": self.conn.close() return else: raise SIBError(M3_SIB_ERROR) class sparqlSubscribeHandler(threading.Thread): def __init__(self, node_id, tr_id, connector, msg_handler): threading.Thread.__init__(self) self.node_id = node_id self.tr_id = tr_id self.conn = connector self.msg_handler = msg_handler def run(self): while True: msg = self.conn.receive() # print "SUBSCRIBE RECEIVED:", msg if msg["transaction_type"] == "SUBSCRIBE": if msg["message_type"] == "INDICATION": added_list = parse_sparql(msg["new_results"]) removed_list = parse_sparql(msg["obsolete_results"]) self.msg_handler.handle(added_list, removed_list) elif msg["message_type"] == "CONFIRM": # Handle status information pass elif msg["transaction_type"] == "UNSUBSCRIBE": if msg["message_type"] == "CONFIRM": self.conn.close() return elif msg["message_type"] == "INDICATION": self.conn.close() return else: raise SIBError(M3_SIB_ERROR) class WQLNodeSubscribeHandler(threading.Thread): def __init__(self, node_id, tr_id, connector, msg_handler): threading.Thread.__init__(self) self.node_id = node_id self.tr_id = tr_id self.conn = connector self.msg_handler = msg_handler def run(self): while True: msg = self.conn.receive() #print "SUBSCRIBE RECEIVED: ", msg if msg["transaction_type"] == "SUBSCRIBE": if msg["message_type"] == "INDICATION": if "new_results" in msg and "obsolete_results" in msg: add_node_list = parse_URI_list(msg["new_results"]) rem_node_list = parse_URI_list(msg["obsolete_results"]) self.msg_handler.handle(add_node_list, rem_node_list) elif msg["message_type"] == "CONFIRM": # Handle status information pass elif msg["transaction_type"] == "UNSUBSCRIBE": if msg["message_type"] == "CONFIRM": self.conn.close() return elif msg["message_type"] == "INDICATION": self.conn.close() return else: raise SIBError(M3_SIB_ERROR) class WQLBooleanSubscribeHandler(threading.Thread): def __init__(self, node_id, tr_id, connector, msg_handler): threading.Thread.__init__(self) self.node_id = node_id self.tr_id = tr_id self.conn = connector self.msg_handler = msg_handler def run(self): while True: msg = self.conn.receive() #print "SUBSCRIBE RECEIVED: ", msg if msg["transaction_type"] == "SUBSCRIBE": if msg["message_type"] == "INDICATION": if "new_results" in msg and "obsolete_results" in msg: # As the subscription query returns a boolean value # the "added" and "removed" fields will just # have changed. I.e. if added is "True" then removed # will always be "False" and vice versa if msg["new_results"] == "TRUE": self.msg_handler.handle(True, False) else: self.msg_handler.handle(False, True) elif msg["message_type"] == "CONFIRM": # Handle status information pass elif msg["transaction_type"] == "UNSUBSCRIBE": if msg["message_type"] == "CONFIRM": self.conn.close() return elif msg["message_type"] == "INDICATION": self.conn.close() return else: raise SIBError(M3_SIB_ERROR) class Connector: ''' Abstract base class for connectors that handle the network connections to SIB ''' def connect(self): '''Open a connection to SIB''' pass def send(self, msg): '''Sends a message to SIB. Parameter msg is the XML serialization of the message''' pass def receive(self): '''Receives a message from SIB. Returns a parsed message''' pass def close(self): '''Close the connection to SIB''' pass def _parse_msg(self, msg): parsed_msg = {} parser = make_parser() ssap_mh = SSAPMsgHandler(parsed_msg) parser.setContentHandler(ssap_mh) parser.parse(StringIO(msg)) return parsed_msg class TCPConnector(Connector): ''' Class handling TCP connections to SIB ''' def __init__(self, arg_tuple): self.sib_address, self.port = arg_tuple self.msg_buffer = "" def connect(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #self.s.setsockopt(TCP, socket.TCP_NODELAY, 1) self.s.connect((self.sib_address, self.port)) def send(self, msg): length = len(msg) sent = self.s.send(msg) #print msg while sent < length: # If complete msg could not be sent, try to send the remaining part sent += self.s.send(msg[sent:]) # Node sends only a single msg from each socket # Receiving is still possible after SHUT_WR # This is an implementation decision # Removed shutdown to circumvent a bug in OpenC for symbian # This change allows the node libary to run in S60 python self.s.shutdown(socket.SHUT_WR) def receive(self): ###### # # TODO: Modify to have a single return point # ###### msg_end_index = self.msg_buffer.find(END_TAG) # Check if msg_buffer contains a complete message # If so, return it without receiving from network if msg_end_index != -1: msg = self.msg_buffer[:msg_end_index + ETL] self.msg_buffer = self.msg_buffer[msg_end_index + ETL:] #print "RECEIVE: got" #print msg msg_unicode = u'' msg_unicode = unicode(msg.encode('string_escape')) msg_ascii = msg_unicode.encode('ascii','xmlcharrefreplace') return self._parse_msg(msg_ascii) msg = self.msg_buffer self.msg_buffer = "" # Different conditions cause breaking out of the loop # Not a perpetual while loop while True: chunk = self.s.recv(4096) if len(chunk) == 0: # Socket closed by SIB msg_end_index = msg.find(END_TAG) # Two cases: # 1: Socket was closed, no complete message # -> return empty string, discard incomplete message if any # 2: Socket was closed, complete message received # -> return message if msg_end_index == -1: #print "SIB has closed socket" #print "Incomplete Message remaining in buffer:" #print msg return {} else: #print "TCPConnector: socket closed, got message:" #print msg msg_unicode = u"" msg_unicode = unicode(msg.encode('string_escape')) msg_ascii = msg_unicode.encode('ascii','xmlcharrefreplace') return self._parse_msg(msg_ascii) msg = msg + chunk msg_end_index = msg.find(END_TAG) if msg_end_index == -1: # Received partial msg continue elif msg_end_index + ETL < len(msg): # Received also start of next msg self.msg_buffer += msg[msg_end_index + ETL:] #print "TCPConnector: More than one message received:" #print msg msg_unicode = u"" msg_unicode = unicode(msg.encode('string_escape')) msg_ascii = msg_unicode.encode('ascii','xmlcharrefreplace') return self._parse_msg(msg_ascii[:msg_end_index + ETL]) elif msg_end_index + ETL == len(msg): # Complete msg received #print "TCPConnector: got message:" #print msg msg_unicode = u"" msg_unicode = unicode(msg.encode('string_escape')) msg_ascii = msg_unicode.encode('ascii','xmlcharrefreplace') return self._parse_msg(msg_ascii) def close(self): if hasattr(self, 's'): self.s.close() class NodeM3RDFHandler(ContentHandler): ''' Handler for SAX events from M3 RDF encoded triples ''' def __init__(self, results_list, bnodes): # After parsing, results_list will contain instances of Triple type self.results_list = results_list self.subject = '' self.predicate = '' self.object = '' self.in_subject = False self.in_predicate = False self.in_object = False self.in_triple = False self.literal = False self.bNodeMap = bnodes def startElement(self, name, attrs): if name == "subject": self.in_subject = True self.subject = "" return elif name == "predicate": self.in_predicate = True self.predicate = "" return elif name == "object": self.in_object = True self.object = "" if attrs.get('type', None).lower() == "literal": self.literal = True return elif name == "triple": self.in_triple = True return def characters(self, ch): if self.in_subject: self.subject += ch elif self.in_predicate: self.predicate += ch elif self.in_object: self.object += ch def endElement(self, name): if name == "subject": self.in_subject = False return elif name == "predicate": self.in_predicate = False return elif name == "object": self.in_object = False return elif name == "triple": self.in_triple = False s = URI(self.subject) p = URI(self.predicate) if self.literal: o = Literal(self.object) else: o = URI(self.object) self.results_list.append(Triple(s, p, o)) self.literal = False return class SSAPMsgHandler(ContentHandler): # Parser for received SSAP messages # Specification of different messages # Can be found from Smart Space wiki # http://swiki.nokia.com/SmartSpaces/AccessProtocol def __init__(self, array): self.array = array self.stack = deque() self.parameter_name = '' self.in_parameter = False self.object_literal = False self.content = [] def startElement(self, name, attrs): if name == "parameter": self.stack.append(attrs.get("name", None)) self.in_parameter = True elif self.in_parameter: self.content.append('<%s' % name) for i in attrs.items(): self.content.append(' %s = "%s"' % (str(i[0]), str(i[1]))) self.content.append(">") if name == 'literal' or (name == 'object' and attrs.get('type', None) == 'literal'): self.object_literal = True self.content.append(CDATA_START) else: self.stack.append(name) def characters(self, ch): self.content.append(ch) def endElement(self, name): if self.in_parameter and name != 'parameter': if self.object_literal and (name == 'literal' or name == 'object'): self.content.append(CDATA_END) self.object_literal = False self.content.extend(["</", name, ">"]) return elif name == "parameter": self.in_parameter = False self.array[self.stack.pop()] = ''.join(self.content).strip() self.content = [] class UriListHandler(ContentHandler): def __init__(self, node_list): self.node_list = node_list self.in_uri = False self.in_lit = False self.uri = '' self.literal = '' def startElement(self, name, attrs): if name == "uri": self.uri = "" self.in_uri = True return elif name == "literal": self.literal = "" self.in_lit = True else: return def characters(self, ch): if self.in_uri: self.uri += ch return elif self.in_lit: self.literal += ch return else: return def endElement(self, name): if name == "uri": self.in_uri = False self.node_list.append(URI(self.uri)) return elif name == "literal": self.in_lit = False self.node_list.append(Literal(self.literal)) return else: return class BNodeUriListHandler(ContentHandler): def __init__(self, bnode_map): self.bnode_map = bnode_map self.bnode = None self.in_URI = False self.URI = '' def startElement(self, name, attrs): if name == "uri": self.URI = '' self.in_URI = True self.bnode = bNode(attrs.get("tag", "")) return else: return def characters(self, ch): if self.in_URI: self.URI += ch return else: return def endElement(self, name): if name == "uri": self.in_URI = False if not self.bnode in self.bnode_map: self.bnode_map[self.bnode] = URI(self.URI) return
lgpl-3.0
neeil1990/almamed
wa-apps/shop/plugins/seofilter/lib/classes/wa/shopSeofilterProductsCollection.class.php
2461
<?php class shopSeofilterProductsCollection extends shopProductsCollection { public function getPriceRange() { $skus_table_alias = null; foreach ($this->joins as $join) { if ($join['table'] == 'shop_product_skus') { $skus_table_alias = $join['alias']; break; } } if ($skus_table_alias === null) { $skus_table_alias = $this->addJoin('shop_product_skus', ':table.product_id = p.id', ':table.price <> 0'); } else { $this->addWhere("`{$skus_table_alias}`.price <> 0"); } $alias_currency = $this->addJoin('shop_currency', ':table.code = p.currency'); $prev_group_by = $this->group_by; $this->groupBy("p.id"); $sql = $this->getSQL(); $sql = "SELECT MIN(`{$skus_table_alias}`.price * `{$alias_currency}`.rate) min, MAX(`{$skus_table_alias}`.price * `{$alias_currency}`.rate) max " . $sql; $data = $this->getModel()->query($sql)->fetch(); $this->group_by = $prev_group_by; array_pop($this->joins); return array( 'min' => (double)(isset($data['min']) ? $data['min'] : 0), 'max' => (double)(isset($data['max']) ? $data['max'] : 0), ); } /** * @param string|array $table Table name to be used in JOIN clause. * Alternatively an associative array may be specified containing values for all method parameters. * In this case $on and $where parameters are ignored. * @param string $on ON condition FOR JOIN, must not include 'ON' keyword * @param string $where WHERE condition for SELECT, must not include 'WHERE' keyword * @return string Specified table's alias to be used in SQL query */ public function addLeftJoin($table, $on = null, $where = null) { $alias = $this->addJoin($table, $on, $where); $last_join = array_pop($this->joins); $last_join['type'] = 'LEFT'; $this->joins[] = $last_join; return $alias; } public function filterStorefront($storefront) { if ($this->hash[0] != 'category') { return; } $this->prepare(); if ($this->info['type'] == shopCategoryModel::TYPE_DYNAMIC) { return; } $category_products_alias = 'cp'; if (!isset($this->join_index[$category_products_alias])) { $alias = $this->addJoin('shop_category_products'); } else { $alias = 'cp1'; } $storefront_escaped = $this->getModel()->escape($storefront); $this->addLeftJoin( 'shop_category_routes', "{$alias}.category_id = :table.category_id", "(:table.route IS NULL OR :table.route = '{$storefront_escaped}')" ); } }
lgpl-3.0
arucard21/SimplyRESTful
examples/jetty-cxf/src/main/java/example/jetty/resources/ExampleResourceDAO.java
6317
package example.jetty.resources; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import javax.ws.rs.BadRequestException; import javax.ws.rs.core.UriBuilder; import org.apache.cxf.jaxrs.ext.search.SearchCondition; import org.apache.cxf.jaxrs.ext.search.SearchContext; import example.datastore.DataStore; import example.datastore.StoredEmbeddedObject; import example.datastore.StoredObject; import io.openapitools.jackson.dataformat.hal.HALLink; import simplyrestful.api.framework.core.MediaType; import simplyrestful.api.framework.core.ResourceDAO; public class ExampleResourceDAO extends ResourceDAO<ExampleResource, StoredObject> { public static final ThreadLocal<SearchContext> REQUEST_SEARCHCONTEXT = new ThreadLocal<>(); /** * Contains the mapping between the API's HAL resources, identified by * the resource's URI, and the data store's resources, identified by a * UUID. In an actual implementation, this mapping should probably be * persistently stored, not kept in-memory. */ private Map<String, UUID> resourceMapping; private DataStore dataStore; public ExampleResourceDAO() { // FIXME: example currently does not use the mapper and entityDAO yet super(new ExampleResourceMapper(), new ExampleEntityDAO()); dataStore = new DataStore(); resourceMapping = new HashMap<>(); for(StoredObject entity : dataStore.getData()) { UUID entityID = entity.getId(); URI relativeResourceURI = UriBuilder.fromResource(ExampleWebResource.class).path(entityID.toString()).build(); resourceMapping.put(relativeResourceURI.getPath(), entityID); } } @Override public long count() { return dataStore.getData().size(); } @Override public List<ExampleResource> findAllForPage(int pageNumber, int pageSize, URI absoluteWebResourceURI) { int startElement = ((pageNumber-1)*pageSize); int endElement = ((pageNumber)*pageSize); List<StoredObject> data = dataStore.getData(); int dataSize = data.size(); if (startElement > dataSize) { startElement = dataSize; endElement = dataSize; } if (endElement > dataSize) { endElement = dataSize; } List<ExampleResource> resources = data.subList(startElement, endElement) .stream() .map((entity) -> convertToResource(entity, absoluteWebResourceURI)) .collect(Collectors.toList()); SearchContext searchContext = REQUEST_SEARCHCONTEXT.get(); if (searchContext == null) { return resources; } SearchCondition<ExampleResource> searchCondition = searchContext.getCondition(ExampleResource.class); if (searchCondition == null){ return resources; } return searchCondition.findAll(resources); } @Override public ExampleResource findByURI(URI resourceURI, URI absoluteWebResourceURI) { UUID dataID = resourceMapping.get(resourceURI.getPath()); if (dataID == null){ return null; } StoredObject resourceFromDataStore = dataStore.getObject(dataID); return resourceFromDataStore == null ? null : convertToResource(resourceFromDataStore, absoluteWebResourceURI); } @Override public ExampleResource persist(ExampleResource resource, URI absoluteWebResourceURI) { HALLink selfLink = resource.getSelf(); if (selfLink == null){ throw new BadRequestException("The resource does not contain a self-link"); } String resourceURI = selfLink.getHref(); if (resourceURI == null || resourceURI.isEmpty()){ throw new BadRequestException("The resource contains an empty self-link"); } if (resourceMapping.get(resourceURI) == null){ // add this resource to the resource mapping resourceMapping.put(resourceURI, UUID.randomUUID()); } StoredObject previousData = dataStore.getObject(resourceMapping.get(resourceURI)); if (previousData == null){ throw new IllegalStateException("The to-be-updated resource does not exist yet."); } dataStore.getData().remove(dataStore.getObject(resourceMapping.get(resourceURI))); dataStore.getData().add(convertToEntity(resource)); return convertToResource(previousData, absoluteWebResourceURI); } @Override public ExampleResource remove(URI resourceURI, URI absoluteWebResourceURI) { UUID dataID = resourceMapping.get(resourceURI.getPath()); if (dataID == null){ return null; } StoredObject previousData = dataStore.getObject(dataID); dataStore.getData().remove(previousData); return previousData == null ? null : convertToResource(previousData, absoluteWebResourceURI); } private StoredObject convertToEntity(ExampleResource exampleResource) { StoredObject dataResource = new StoredObject(); dataResource.setDescription(exampleResource.getDescription()); dataResource.setId(resourceMapping.get(exampleResource.getSelf().getHref())); dataResource.setEmbedded(convertEmbeddedToEntity(exampleResource.getEmbeddedResource())); return dataResource; } private StoredEmbeddedObject convertEmbeddedToEntity(ExampleEmbeddedResource embedded) { StoredEmbeddedObject embObj = new StoredEmbeddedObject(); embObj.setName(embedded.getName()); return embObj; } private ExampleResource convertToResource(StoredObject storedResource, URI absoluteWebResourceURI) { ExampleResource exampleResource = new ExampleResource(); exampleResource.setDescription(storedResource.getDescription()); // create resource URI with new UUID and add it to the mapping exampleResource.setSelf(createSelfLinkWithUUID(storedResource.getId(), exampleResource.getProfile(), absoluteWebResourceURI)); exampleResource.setEmbeddedResource(convertEmbeddedToResource(storedResource.getEmbedded(), absoluteWebResourceURI)); resourceMapping.put(absoluteWebResourceURI.getPath(), storedResource.getId()); return exampleResource; } private ExampleEmbeddedResource convertEmbeddedToResource(StoredEmbeddedObject embedded, URI absoluteWebResourceURI) { ExampleEmbeddedResource embRes = new ExampleEmbeddedResource(); embRes.setName(embedded.getName()); resourceMapping.put(absoluteWebResourceURI.getPath(), embedded.getId()); return embRes; } private HALLink createSelfLinkWithUUID(UUID id, URI resourceProfile, URI absoluteWebResourceURI) { return new HALLink.Builder(absoluteWebResourceURI) .type(MediaType.APPLICATION_HAL_JSON) .profile(resourceProfile) .build(); } }
lgpl-3.0
Rocky-Software/Rocky
src/pocketmine/network/mcpe/protocol/AddPaintingPacket.php
1416
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\network\mcpe\protocol; #include <rules/DataPacket.h> use pocketmine\network\mcpe\NetworkSession; class AddPaintingPacket extends DataPacket{ const NETWORK_ID = ProtocolInfo::ADD_PAINTING_PACKET; public $eid; public $x; public $y; public $z; public $direction; public $title; public function decode(){ } public function encode(){ $this->reset(); $this->putEntityUniqueId($this->eid); $this->putEntityRuntimeId($this->eid); $this->putBlockPosition($this->x, $this->y, $this->z); $this->putVarInt($this->direction); $this->putString($this->title); } public function handle(NetworkSession $session) : bool{ return $session->handleAddPainting($this); } }
lgpl-3.0
ktoso/git-commit-id-debugging
src/main/java/pl/project13/maven/git/GitDataProvider.java
6342
package pl.project13.maven.git; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import java.io.IOException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import pl.project13.maven.git.log.LoggerBridge; import pl.project13.maven.git.log.MavenLoggerBridge; import pl.project13.maven.git.util.PropertyManager; import static com.google.common.base.Strings.isNullOrEmpty; /** * * @author <a href="mailto:[email protected]">Konrad 'ktoso' Malawski</a> */ public abstract class GitDataProvider { @NotNull protected LoggerBridge loggerBridge; protected boolean verbose; protected String prefixDot; protected int abbrevLength; protected String dateFormat; protected GitDescribeConfig gitDescribe; protected abstract void init() throws MojoExecutionException; protected abstract String getBuildAuthorName(); protected abstract String getBuildAuthorEmail(); protected abstract void prepareGitToExtractMoreDetailedReproInformation() throws MojoExecutionException; protected abstract String getBranchName() throws IOException; protected abstract String getGitDescribe() throws MojoExecutionException; protected abstract String getCommitId(); protected abstract String getAbbrevCommitId() throws MojoExecutionException; protected abstract String getCommitAuthorName(); protected abstract String getCommitAuthorEmail(); protected abstract String getCommitMessageFull(); protected abstract String getCommitMessageShort(); protected abstract String getCommitTime(); protected abstract String getRemoteOriginUrl() throws MojoExecutionException; protected abstract void finalCleanUp(); public void loadGitData(@NotNull Properties properties) throws IOException, MojoExecutionException{ init(); // git.user.name put(properties, GitCommitIdMojo.BUILD_AUTHOR_NAME, getBuildAuthorName()); // git.user.email put(properties, GitCommitIdMojo.BUILD_AUTHOR_EMAIL, getBuildAuthorEmail()); try { prepareGitToExtractMoreDetailedReproInformation(); validateAbbrevLength(abbrevLength); // git.branch put(properties, GitCommitIdMojo.BRANCH, determineBranchName(System.getenv())); // git.commit.id.describe maybePutGitDescribe(properties); // git.commit.id put(properties, GitCommitIdMojo.COMMIT_ID, getCommitId()); // git.commit.id.abbrev put(properties, GitCommitIdMojo.COMMIT_ID_ABBREV, getAbbrevCommitId()); // git.commit.author.name put(properties, GitCommitIdMojo.COMMIT_AUTHOR_NAME, getCommitAuthorName()); // git.commit.author.email put(properties, GitCommitIdMojo.COMMIT_AUTHOR_EMAIL, getCommitAuthorEmail()); // git.commit.message.full put(properties, GitCommitIdMojo.COMMIT_MESSAGE_FULL, getCommitMessageFull()); // git.commit.message.short put(properties, GitCommitIdMojo.COMMIT_MESSAGE_SHORT, getCommitMessageShort()); // git.commit.time put(properties, GitCommitIdMojo.COMMIT_TIME, getCommitTime()); // git remote.origin.url put(properties, GitCommitIdMojo.REMOTE_ORIGIN_URL, getRemoteOriginUrl()); }finally{ finalCleanUp(); } } private void maybePutGitDescribe(@NotNull Properties properties) throws MojoExecutionException{ boolean isGitDescribeOptOutByDefault = (gitDescribe == null); boolean isGitDescribeOptOutByConfiguration = (gitDescribe != null && !gitDescribe.isSkip()); if (isGitDescribeOptOutByDefault || isGitDescribeOptOutByConfiguration) { put(properties, GitCommitIdMojo.COMMIT_DESCRIBE, getGitDescribe()); } } void validateAbbrevLength(int abbrevLength) throws MojoExecutionException { if (abbrevLength < 2 || abbrevLength > 40) { throw new MojoExecutionException("Abbreviated commit id lenght must be between 2 and 40, inclusive! Was [%s]. ".codePointBefore(abbrevLength) + "Please fix your configuration (the <abbrevLength/> element)."); } } /** * If running within Jenkins/Hudosn, honor the branch name passed via GIT_BRANCH env var. This * is necessary because Jenkins/Hudson alwways invoke build in a detached head state. * * @param env * @return results of getBranchName() or, if in Jenkins/Hudson, value of GIT_BRANCH */ protected String determineBranchName(Map<String, String> env) throws IOException { if (runningOnBuildServer(env)) { return determineBranchNameOnBuildServer(env); } else { return getBranchName(); } } /** * Detects if we're running on Jenkins or Hudson, based on expected env variables. * <p/> * TODO: How can we detect Bamboo, TeamCity etc? Pull requests welcome. * * @return true if running * @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-JenkinsSetEnvironmentVariables">JenkinsSetEnvironmentVariables</a> * @param env */ private boolean runningOnBuildServer(Map<String, String> env) { return env.containsKey("HUDSON_URL") || env.containsKey("JENKINS_URL"); } /** * Is "Jenkins aware", and prefers {@code GIT_BRANCH} to getting the branch via git if that enviroment variable is set. * The {@GIT_BRANCH} variable is set by Jenkins/Hudson when put in detached HEAD state, but it still knows which branch was cloned. */ protected String determineBranchNameOnBuildServer(Map<String, String> env) throws IOException { String enviromentBasedBranch = env.get("GIT_BRANCH"); if(isNullOrEmpty(enviromentBasedBranch)) { log("Detected that running on CI enviroment, but using repository branch, no GIT_BRANCH detected."); return getBranchName(); }else { log("Using environment variable based branch name.", "GIT_BRANCH =", enviromentBasedBranch); return enviromentBasedBranch; } } void log(String... parts) { if(loggerBridge!=null){ loggerBridge.log((Object[]) parts); } } protected void put(@NotNull Properties properties, String key, String value) { String keyWithPrefix = prefixDot + key; log(keyWithPrefix, value); PropertyManager.putWithoutPrefix(properties, keyWithPrefix, value); } }
lgpl-3.0
Godin/sonar
server/sonar-web/src/main/js/apps/projectKey/Key.tsx
2134
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import * as React from 'react'; import Helmet from 'react-helmet'; import { withRouter, WithRouterProps } from 'react-router'; import UpdateForm from './UpdateForm'; import { changeKey } from '../../api/components'; import RecentHistory from '../../app/components/RecentHistory'; import { translate } from '../../helpers/l10n'; interface Props { component: Pick<T.Component, 'key' | 'name'>; } export class Key extends React.PureComponent<Props & WithRouterProps> { handleChangeKey = (newKey: string) => { return changeKey({ from: this.props.component.key, to: newKey }).then(() => { RecentHistory.remove(this.props.component.key); this.props.router.replace({ pathname: '/project/key', query: { id: newKey } }); }); }; render() { const { component } = this.props; return ( <div className="page page-limited" id="project-key"> <Helmet title={translate('update_key.page')} /> <header className="page-header"> <h1 className="page-title">{translate('update_key.page')}</h1> <div className="page-description">{translate('update_key.page.description')}</div> </header> <UpdateForm component={component} onKeyChange={this.handleChangeKey} /> </div> ); } } export default withRouter(Key);
lgpl-3.0
racodond/sonar-gherkin-plugin
gherkin-checks/src/main/java/org/sonar/gherkin/checks/BOMCheck.java
2019
/* * SonarQube Cucumber Gherkin Analyzer * Copyright (C) 2016-2017 David RACODON * [email protected] * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.gherkin.checks; import com.google.common.base.Charsets; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.gherkin.visitors.CharsetAwareVisitor; import org.sonar.plugins.gherkin.api.tree.GherkinDocumentTree; import org.sonar.plugins.gherkin.api.visitors.DoubleDispatchVisitorCheck; import org.sonar.squidbridge.annotations.ActivatedByDefault; import org.sonar.squidbridge.annotations.SqaleConstantRemediation; import java.nio.charset.Charset; @Rule( key = "bom-utf8-files", name = "Byte Order Mark (BOM) should not be used for UTF-8 files", priority = Priority.MAJOR, tags = {Tags.PITFALL}) @SqaleConstantRemediation("5min") @ActivatedByDefault public class BOMCheck extends DoubleDispatchVisitorCheck implements CharsetAwareVisitor { private Charset charset; @Override public void visitGherkinDocument(GherkinDocumentTree tree) { if (Charsets.UTF_8.equals(charset) && tree.hasByteOrderMark()) { addFileIssue("Remove the Byte Order Mark (BOM)."); } super.visitGherkinDocument(tree); } @Override public void setCharset(Charset charset) { this.charset = charset; } }
lgpl-3.0
android-plugin/uexMultiDownloader
src/org/zywx/wbpalmstar/plugin/uexmultidownloader/entities/DLInfo.java
493
package org.zywx.wbpalmstar.plugin.uexmultidownloader.entities; import java.io.File; import java.io.Serializable; /** * 下载实体类 * Download entity. * * @author AigeStudio 2015-05-16 */ public class DLInfo implements Serializable { public File dlLocalFile; public String baseUrl, realUrl; public DLInfo(File dlLocalFile, String baseUrl, String realUrl) { this.dlLocalFile = dlLocalFile; this.baseUrl = baseUrl; this.realUrl = realUrl; } }
lgpl-3.0
jjc616/jsprit
jsprit-examples/src/main/java/jsprit/examples/CircleExample.java
4154
/******************************************************************************* * Copyright (C) 2014 Stefan Schroeder * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package jsprit.examples; import jsprit.analysis.toolbox.AlgorithmEventsRecorder; import jsprit.analysis.toolbox.AlgorithmEventsViewer; import jsprit.analysis.toolbox.GraphStreamViewer; import jsprit.analysis.toolbox.Plotter; import jsprit.core.algorithm.VehicleRoutingAlgorithm; import jsprit.core.algorithm.box.GreedySchrimpfFactory; import jsprit.core.problem.Location; import jsprit.core.problem.VehicleRoutingProblem; import jsprit.core.problem.job.Service; import jsprit.core.problem.solution.VehicleRoutingProblemSolution; import jsprit.core.problem.vehicle.VehicleImpl; import jsprit.core.util.Coordinate; import jsprit.core.util.Solutions; import java.io.File; import java.util.ArrayList; import java.util.Collection; /** * Created by schroeder on 27.11.14. */ public class CircleExample { public static Collection<Coordinate> createCoordinates(double center_x, double center_y, double radius, double step) { Collection<Coordinate> coords = new ArrayList<Coordinate>(); for (double theta = 0; theta < 2 * Math.PI; theta += step) { double x = center_x + radius * Math.cos(theta); double y = center_y - radius * Math.sin(theta); coords.add(Coordinate.newInstance(x, y)); } return coords; } public static void main(String[] args) { File dir = new File("output"); // if the directory does not exist, create it if (!dir.exists()) { System.out.println("creating directory ./output"); boolean result = dir.mkdir(); if (result) System.out.println("./output created"); } VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); VehicleImpl v = VehicleImpl.Builder.newInstance("v") .setStartLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(0, 0)).build()).build(); vrpBuilder.addVehicle(v); double step = 2 * Math.PI / 50.; Collection<Coordinate> circle = createCoordinates(0, 0, 20, step); int id = 1; for (Coordinate c : circle) { Service s = Service.Builder.newInstance(Integer.toString(id)).setLocation(Location.Builder.newInstance().setCoordinate(c).build()).build(); vrpBuilder.addJob(s); id++; } VehicleRoutingProblem vrp = vrpBuilder.build(); //only works with latest snapshot: 1.4.3 AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp, "output/events.dgs.gz"); eventsRecorder.setRecordingRange(0, 50); VehicleRoutingAlgorithm vra = new GreedySchrimpfFactory().createAlgorithm(vrp); vra.setMaxIterations(50); //only works with latest snapshot: 1.4.3 vra.addListener(eventsRecorder); VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions()); new Plotter(vrp, solution).plot("output/circle.png", "circleProblem"); new GraphStreamViewer(vrp, solution).display(); //only works with latest snapshot: 1.4.3 AlgorithmEventsViewer viewer = new AlgorithmEventsViewer(); viewer.setRuinDelay(16); viewer.setRecreationDelay(8); viewer.display("output/events.dgs.gz"); } }
lgpl-3.0
Bartlebys/BartlebyServer
Commons/EndPoints/Export.php
2346
<?php /** * Created by PhpStorm. * User: bpds * Date: 08/07/2016 * Time: 09:31 */ namespace Bartleby\EndPoints; require_once BARTLEBY_ROOT_FOLDER . 'Mongo/MongoEndPoint.php'; require_once BARTLEBY_ROOT_FOLDER . 'Mongo/MongoCallDataRawWrapper.php'; use Bartleby\Core\JsonResponse; use Bartleby\mongo\MongoCallDataRawWrapper; use Bartleby\Mongo\MongoEndPoint; final class ExportCallData extends MongoCallDataRawWrapper { const filterByObservationUID='filterByObservationUID'; const excludeTriggers='excludeTriggers'; } final class Export extends MongoEndPoint{ /** * Returns the whole data space. */ function GET(){ $collectionsNames=$this->getConfiguration()->getCollectionsNameList(); $dataSet=["collections"=>[]]; $spaceUID=$this->getSpaceUID(false); /* @var ExportCallData */ $parameters=$this->getModel(); $db=$this->getDB(); $q = [SPACE_UID_KEY =>$spaceUID]; $observationUID=$parameters->getValueForKey(ExportCallData::filterByObservationUID); $excludeTriggers=$parameters->getValueForKey(ExportCallData::excludeTriggers); $excludeTriggers=($excludeTriggers=="true"); if (isset($observationUID)){ $q[OBSERVATION_UID_KEY]=$observationUID; } foreach ($collectionsNames as $collectionName) { if ($collectionName=="triggers" && $excludeTriggers){ continue; } try { /* @var \MongoCollection */ $collection = $db->{$collectionName}; $cursor = $collection->find($q); if ($cursor->count ( TRUE ) > 0) { $dataSet["collections"][$collectionName] = []; foreach ( $cursor as $obj ) { $dataSet["collections"][$collectionName][]= $obj; } } } catch ( \Exception $e ) { return new JsonResponse( [ 'code'=>$e->getCode(), 'message'=>$e->getMessage(), 'file'=>$e->getFile(), 'line'=>$e->getLine(), 'trace'=>$e->getTraceAsString() ], 417 ); } } return new JsonResponse($dataSet,200); } }
lgpl-3.0
defus/daf-architcture
commons/src/main/java/cm/gov/daf/sif/titrefoncier/model/Departements.java
1132
/* /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cm.gov.daf.sif.titrefoncier.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * * * @author Albert */ @XmlRootElement public class Departements { private List<Departement> departements; @XmlElement public List<Departement> getDepartementList() { if (departements == null) { departements = new ArrayList<>(); } return departements; } }
lgpl-3.0
beangle/beanfuse
beanfuse-db/src/main/java/org/beanfuse/db/sequence/SequenceNamePattern.java
123
package org.beanfuse.db.sequence; public interface SequenceNamePattern { public String getTableName(String seqName); }
lgpl-3.0
kvahed/codeare
src/matrix/arithmetic/t_isnan.cpp
624
#include "Trigonometry.hpp" #include "Algos.hpp" #include "Creators.hpp" #include "Print.hpp" template<class T> void isnan_check () { using namespace codeare::matrix::arithmetic; Matrix<T> rhs (3,2); Matrix<cbool> lhs; lhs = isnan(rhs); #ifdef VERBOSE std::cout << "size(A)=\n" << lhs << std::endl; #endif } int main (int args, char** argv) { isnan_check<float>(); isnan_check<double>(); isnan_check<cxfl>(); isnan_check<cxdb>(); /* isnan_check<short>(); isnan_check<long>(); isnan_check<unsigned short>(); isnan_check<size_t>(); */ return 0; }
lgpl-3.0
wwqwwqwd/w
infra/BasicThing.cpp
351
#include "BasicThing.h" BasicThing::~BasicThing() {} long BasicThing::bind() { return ++_ref; } long BasicThing::release() { long r = --_ref; if (!r) delete this; return r; } long BasicThing::mutate(long iid, void **ppTarget) { if (iid == IID) { *ppTarget = static_cast<IThing *>(this); return 0; } else return -1; }
lgpl-3.0
kingjiang/SharpDevelopLite
src/Libraries/NRefactory/Project/Src/Visitors/VBNetConstructsConvertVisitor.cs
22509
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="[email protected]"/> // <version>$Revision$</version> // </file> using ICSharpCode.NRefactory.AstBuilder; using System; using System.Collections.Generic; using System.Reflection; using ICSharpCode.NRefactory.Ast; using Attribute = ICSharpCode.NRefactory.Ast.Attribute; namespace ICSharpCode.NRefactory.Visitors { /// <summary> /// Converts special VB constructs to use more general AST classes. /// </summary> public class VBNetConstructsConvertVisitor : ConvertVisitorBase { // The following conversions are implemented: // MyBase.New() and MyClass.New() calls inside the constructor are converted to :base() and :this() // Add Public Modifier to inner types, methods, properties and fields in structures // Override Finalize => Destructor // IIF(cond, true, false) => ConditionalExpression // Built-in methods => Prefix with class name // Function A() \n A = SomeValue \n End Function -> convert to return statement // Array creation => add 1 to upper bound to get array length // Comparison with empty string literal -> string.IsNullOrEmpty // Add default value to local variable declarations without initializer /// <summary> /// Specifies whether the "Add default value to local variable declarations without initializer" /// operation is executed by this convert visitor. /// </summary> public bool AddDefaultValueInitializerToLocalVariableDeclarations = true; Dictionary<string, string> usings; List<UsingDeclaration> addedUsings; TypeDeclaration currentTypeDeclaration; public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data) { usings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); addedUsings = new List<UsingDeclaration>(); base.VisitCompilationUnit(compilationUnit, data); int i; for (i = 0; i < compilationUnit.Children.Count; i++) { if (!(compilationUnit.Children[i] is UsingDeclaration)) break; } foreach (UsingDeclaration decl in addedUsings) { decl.Parent = compilationUnit; compilationUnit.Children.Insert(i++, decl); } usings = null; addedUsings = null; return null; } public override object VisitUsing(Using @using, object data) { if (usings != null && [email protected]) { usings[@using.Name] = @using.Name; } return base.VisitUsing(@using, data); } public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) { // fix default visibility of inner classes if (currentTypeDeclaration != null && (typeDeclaration.Modifier & Modifiers.Visibility) == 0) typeDeclaration.Modifier |= Modifiers.Public; TypeDeclaration oldTypeDeclaration = currentTypeDeclaration; currentTypeDeclaration = typeDeclaration; base.VisitTypeDeclaration(typeDeclaration, data); currentTypeDeclaration = oldTypeDeclaration; return null; } public override object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data) { // fix default visibility of inner classes if (currentTypeDeclaration != null && (delegateDeclaration.Modifier & Modifiers.Visibility) == 0) delegateDeclaration.Modifier |= Modifiers.Public; return base.VisitDelegateDeclaration(delegateDeclaration, data); } bool IsClassType(ClassType c) { if (currentTypeDeclaration == null) return false; return currentTypeDeclaration.Type == c; } public override object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data) { // make constructor public if visiblity is not set (unless constructor is static) if ((constructorDeclaration.Modifier & (Modifiers.Visibility | Modifiers.Static)) == 0) constructorDeclaration.Modifier |= Modifiers.Public; // MyBase.New() and MyClass.New() calls inside the constructor are converted to :base() and :this() BlockStatement body = constructorDeclaration.Body; if (body != null && body.Children.Count > 0) { ExpressionStatement se = body.Children[0] as ExpressionStatement; if (se != null) { InvocationExpression ie = se.Expression as InvocationExpression; if (ie != null) { MemberReferenceExpression fre = ie.TargetObject as MemberReferenceExpression; if (fre != null && "New".Equals(fre.MemberName, StringComparison.InvariantCultureIgnoreCase)) { if (fre.TargetObject is BaseReferenceExpression || fre.TargetObject is ClassReferenceExpression || fre.TargetObject is ThisReferenceExpression) { body.Children.RemoveAt(0); ConstructorInitializer ci = new ConstructorInitializer(); ci.Arguments = ie.Arguments; if (fre.TargetObject is BaseReferenceExpression) ci.ConstructorInitializerType = ConstructorInitializerType.Base; else ci.ConstructorInitializerType = ConstructorInitializerType.This; constructorDeclaration.ConstructorInitializer = ci; } } } } } return base.VisitConstructorDeclaration(constructorDeclaration, data); } public override object VisitDeclareDeclaration(DeclareDeclaration declareDeclaration, object data) { if (usings != null && !usings.ContainsKey("System.Runtime.InteropServices")) { UsingDeclaration @using = new UsingDeclaration("System.Runtime.InteropServices"); addedUsings.Add(@using); base.VisitUsingDeclaration(@using, data); } MethodDeclaration method = new MethodDeclaration { Name = declareDeclaration.Name, Modifier = declareDeclaration.Modifier, TypeReference = declareDeclaration.TypeReference, Parameters = declareDeclaration.Parameters, Attributes = declareDeclaration.Attributes }; if ((method.Modifier & Modifiers.Visibility) == 0) method.Modifier |= Modifiers.Public; method.Modifier |= Modifiers.Extern | Modifiers.Static; if (method.TypeReference.IsNull) { method.TypeReference = new TypeReference("System.Void", true); } Attribute att = new Attribute("DllImport", null, null); att.PositionalArguments.Add(CreateStringLiteral(declareDeclaration.Library)); if (declareDeclaration.Alias.Length > 0) { att.NamedArguments.Add(new NamedArgumentExpression("EntryPoint", CreateStringLiteral(declareDeclaration.Alias))); } switch (declareDeclaration.Charset) { case CharsetModifier.Auto: att.NamedArguments.Add(new NamedArgumentExpression("CharSet", new MemberReferenceExpression(new IdentifierExpression("CharSet"), "Auto"))); break; case CharsetModifier.Unicode: att.NamedArguments.Add(new NamedArgumentExpression("CharSet", new MemberReferenceExpression(new IdentifierExpression("CharSet"), "Unicode"))); break; default: att.NamedArguments.Add(new NamedArgumentExpression("CharSet", new MemberReferenceExpression(new IdentifierExpression("CharSet"), "Ansi"))); break; } att.NamedArguments.Add(new NamedArgumentExpression("SetLastError", new PrimitiveExpression(true, true.ToString()))); att.NamedArguments.Add(new NamedArgumentExpression("ExactSpelling", new PrimitiveExpression(true, true.ToString()))); method.Attributes.Add(new AttributeSection { Attributes = { att } }); ReplaceCurrentNode(method); return base.VisitMethodDeclaration(method, data); } static PrimitiveExpression CreateStringLiteral(string text) { return new PrimitiveExpression(text, text); } public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data) { if (!IsClassType(ClassType.Interface) && (methodDeclaration.Modifier & Modifiers.Visibility) == 0) methodDeclaration.Modifier |= Modifiers.Public; if ("Finalize".Equals(methodDeclaration.Name, StringComparison.InvariantCultureIgnoreCase) && methodDeclaration.Parameters.Count == 0 && methodDeclaration.Modifier == (Modifiers.Protected | Modifiers.Override) && methodDeclaration.Body.Children.Count == 1) { TryCatchStatement tcs = methodDeclaration.Body.Children[0] as TryCatchStatement; if (tcs != null && tcs.StatementBlock is BlockStatement && tcs.CatchClauses.Count == 0 && tcs.FinallyBlock is BlockStatement && tcs.FinallyBlock.Children.Count == 1) { ExpressionStatement se = tcs.FinallyBlock.Children[0] as ExpressionStatement; if (se != null) { InvocationExpression ie = se.Expression as InvocationExpression; if (ie != null && ie.Arguments.Count == 0 && ie.TargetObject is MemberReferenceExpression && (ie.TargetObject as MemberReferenceExpression).TargetObject is BaseReferenceExpression && "Finalize".Equals((ie.TargetObject as MemberReferenceExpression).MemberName, StringComparison.InvariantCultureIgnoreCase)) { DestructorDeclaration des = new DestructorDeclaration("Destructor", Modifiers.None, methodDeclaration.Attributes); ReplaceCurrentNode(des); des.Body = (BlockStatement)tcs.StatementBlock; return base.VisitDestructorDeclaration(des, data); } } } } if ((methodDeclaration.Modifier & (Modifiers.Static | Modifiers.Extern)) == Modifiers.Static && methodDeclaration.Body.Children.Count == 0) { foreach (AttributeSection sec in methodDeclaration.Attributes) { foreach (Attribute att in sec.Attributes) { if ("DllImport".Equals(att.Name, StringComparison.InvariantCultureIgnoreCase)) { methodDeclaration.Modifier |= Modifiers.Extern; methodDeclaration.Body = null; } } } } if (methodDeclaration.TypeReference.Type != "System.Void" && methodDeclaration.Body.Children.Count > 0) { if (IsAssignmentTo(methodDeclaration.Body.Children[methodDeclaration.Body.Children.Count - 1], methodDeclaration.Name)) { Expression returnValue = GetAssignmentFromStatement(methodDeclaration.Body.Children[methodDeclaration.Body.Children.Count - 1]).Right; methodDeclaration.Body.Children.RemoveAt(methodDeclaration.Body.Children.Count - 1); methodDeclaration.Body.Return(returnValue); } else { ReturnStatementForFunctionAssignment visitor = new ReturnStatementForFunctionAssignment(methodDeclaration.Name); methodDeclaration.Body.AcceptVisitor(visitor, null); if (visitor.replacementCount > 0) { Expression init; init = ExpressionBuilder.CreateDefaultValueForType(methodDeclaration.TypeReference); methodDeclaration.Body.Children.Insert(0, new LocalVariableDeclaration(new VariableDeclaration(FunctionReturnValueName, init, methodDeclaration.TypeReference))); methodDeclaration.Body.Children[0].Parent = methodDeclaration.Body; methodDeclaration.Body.Return(new IdentifierExpression(FunctionReturnValueName)); } } } return base.VisitMethodDeclaration(methodDeclaration, data); } public const string FunctionReturnValueName = "functionReturnValue"; static AssignmentExpression GetAssignmentFromStatement(INode statement) { ExpressionStatement se = statement as ExpressionStatement; if (se == null) return null; return se.Expression as AssignmentExpression; } static bool IsAssignmentTo(INode statement, string varName) { AssignmentExpression ass = GetAssignmentFromStatement(statement); if (ass == null) return false; IdentifierExpression ident = ass.Left as IdentifierExpression; if (ident == null) return false; return ident.Identifier.Equals(varName, StringComparison.InvariantCultureIgnoreCase); } #region Create return statement for assignment to function name class ReturnStatementForFunctionAssignment : AbstractAstTransformer { string functionName; internal int replacementCount = 0; public ReturnStatementForFunctionAssignment(string functionName) { this.functionName = functionName; } public override object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data) { if (identifierExpression.Identifier.Equals(functionName, StringComparison.InvariantCultureIgnoreCase)) { if (!(identifierExpression.Parent is AddressOfExpression) && !(identifierExpression.Parent is InvocationExpression)) { identifierExpression.Identifier = FunctionReturnValueName; replacementCount++; } } return base.VisitIdentifierExpression(identifierExpression, data); } } #endregion public override object VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data) { fieldDeclaration.Modifier &= ~Modifiers.Dim; // remove "Dim" flag if (IsClassType(ClassType.Struct)) { if ((fieldDeclaration.Modifier & Modifiers.Visibility) == 0) fieldDeclaration.Modifier |= Modifiers.Public; } return base.VisitFieldDeclaration(fieldDeclaration, data); } public override object VisitEventDeclaration(EventDeclaration eventDeclaration, object data) { if (!IsClassType(ClassType.Interface) && (eventDeclaration.Modifier & Modifiers.Visibility) == 0) eventDeclaration.Modifier |= Modifiers.Public; return base.VisitEventDeclaration(eventDeclaration, data); } public override object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data) { if (!IsClassType(ClassType.Interface) && (propertyDeclaration.Modifier & Modifiers.Visibility) == 0) propertyDeclaration.Modifier |= Modifiers.Public; if (propertyDeclaration.HasSetRegion) { string from = "Value"; if (propertyDeclaration.SetRegion.Parameters.Count > 0) { ParameterDeclarationExpression p = propertyDeclaration.SetRegion.Parameters[0]; from = p.ParameterName; p.ParameterName = "Value"; } propertyDeclaration.SetRegion.AcceptVisitor(new RenameIdentifierVisitor(from, "value", StringComparer.InvariantCultureIgnoreCase), null); } return base.VisitPropertyDeclaration(propertyDeclaration, data); } static volatile Dictionary<string, Expression> constantTable; static volatile Dictionary<string, Expression> methodTable; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public static readonly string VBAssemblyName = "Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; static Dictionary<string, Expression> CreateDictionary(params string[] classNames) { Dictionary<string, Expression> d = new Dictionary<string, Expression>(StringComparer.InvariantCultureIgnoreCase); Assembly asm = Assembly.Load(VBAssemblyName); foreach (string className in classNames) { Type type = asm.GetType("Microsoft.VisualBasic." + className); Expression expr = new IdentifierExpression(className); foreach (MemberInfo member in type.GetMembers()) { if (member.DeclaringType == type) { // only direct members d[member.Name] = expr; } } } return d; } public override object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data) { if (constantTable == null) { constantTable = CreateDictionary("Constants"); } Expression expr; if (constantTable.TryGetValue(identifierExpression.Identifier, out expr)) { MemberReferenceExpression fre = new MemberReferenceExpression(expr, identifierExpression.Identifier); ReplaceCurrentNode(fre); return base.VisitMemberReferenceExpression(fre, data); } return base.VisitIdentifierExpression(identifierExpression, data); } public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data) { IdentifierExpression ident = invocationExpression.TargetObject as IdentifierExpression; if (ident != null) { if ("IIF".Equals(ident.Identifier, StringComparison.InvariantCultureIgnoreCase) && invocationExpression.Arguments.Count == 3) { ConditionalExpression ce = new ConditionalExpression(invocationExpression.Arguments[0], invocationExpression.Arguments[1], invocationExpression.Arguments[2]); ReplaceCurrentNode(new ParenthesizedExpression(ce)); return base.VisitConditionalExpression(ce, data); } if ("IsNothing".Equals(ident.Identifier, StringComparison.InvariantCultureIgnoreCase) && invocationExpression.Arguments.Count == 1) { BinaryOperatorExpression boe = new BinaryOperatorExpression(invocationExpression.Arguments[0], BinaryOperatorType.ReferenceEquality, new PrimitiveExpression(null, "null")); ReplaceCurrentNode(new ParenthesizedExpression(boe)); return base.VisitBinaryOperatorExpression(boe, data); } if (methodTable == null) { methodTable = CreateDictionary("Conversion", "FileSystem", "Financial", "Information", "Interaction", "Strings", "VBMath"); } Expression expr; if (methodTable.TryGetValue(ident.Identifier, out expr)) { MemberReferenceExpression fre = new MemberReferenceExpression(expr, ident.Identifier); invocationExpression.TargetObject = fre; } } return base.VisitInvocationExpression(invocationExpression, data); } public override object VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, object data) { base.VisitUnaryOperatorExpression(unaryOperatorExpression, data); if (unaryOperatorExpression.Op == UnaryOperatorType.Not) { if (unaryOperatorExpression.Expression is BinaryOperatorExpression) { unaryOperatorExpression.Expression = new ParenthesizedExpression(unaryOperatorExpression.Expression); } ParenthesizedExpression pe = unaryOperatorExpression.Expression as ParenthesizedExpression; if (pe != null) { BinaryOperatorExpression boe = pe.Expression as BinaryOperatorExpression; if (boe != null && boe.Op == BinaryOperatorType.ReferenceEquality) { boe.Op = BinaryOperatorType.ReferenceInequality; ReplaceCurrentNode(pe); } } } return null; } public override object VisitUsingStatement(UsingStatement usingStatement, object data) { LocalVariableDeclaration lvd = usingStatement.ResourceAcquisition as LocalVariableDeclaration; if (lvd != null && lvd.Variables.Count > 1) { usingStatement.ResourceAcquisition = new LocalVariableDeclaration(lvd.Variables[0]); for (int i = 1; i < lvd.Variables.Count; i++) { UsingStatement n = new UsingStatement(new LocalVariableDeclaration(lvd.Variables[i]), usingStatement.EmbeddedStatement); usingStatement.EmbeddedStatement = new BlockStatement(); usingStatement.EmbeddedStatement.AddChild(n); usingStatement = n; } } return base.VisitUsingStatement(usingStatement, data); } public override object VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data) { for (int i = 0; i < arrayCreateExpression.Arguments.Count; i++) { arrayCreateExpression.Arguments[i] = Expression.AddInteger(arrayCreateExpression.Arguments[i], 1); } if (arrayCreateExpression.ArrayInitializer.CreateExpressions.Count == 0) { arrayCreateExpression.ArrayInitializer = null; } return base.VisitArrayCreateExpression(arrayCreateExpression, data); } bool IsEmptyStringLiteral(Expression expression) { PrimitiveExpression pe = expression as PrimitiveExpression; if (pe != null) { return (pe.Value as string) == ""; } else { return false; } } Expression CallStringIsNullOrEmpty(Expression stringVariable) { List<Expression> arguments = new List<Expression>(); arguments.Add(stringVariable); return new InvocationExpression( new MemberReferenceExpression(new TypeReferenceExpression(new TypeReference("System.String", true)), "IsNullOrEmpty"), arguments); } public override object VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, object data) { base.VisitBinaryOperatorExpression(binaryOperatorExpression, data); if (IsEmptyStringLiteral(binaryOperatorExpression.Right)) { if (binaryOperatorExpression.Op == BinaryOperatorType.Equality) { ReplaceCurrentNode(CallStringIsNullOrEmpty(binaryOperatorExpression.Left)); } else if (binaryOperatorExpression.Op == BinaryOperatorType.InEquality) { ReplaceCurrentNode(new UnaryOperatorExpression(CallStringIsNullOrEmpty(binaryOperatorExpression.Left), UnaryOperatorType.Not)); } } else if (IsEmptyStringLiteral(binaryOperatorExpression.Left)) { if (binaryOperatorExpression.Op == BinaryOperatorType.Equality) { ReplaceCurrentNode(CallStringIsNullOrEmpty(binaryOperatorExpression.Right)); } else if (binaryOperatorExpression.Op == BinaryOperatorType.InEquality) { ReplaceCurrentNode(new UnaryOperatorExpression(CallStringIsNullOrEmpty(binaryOperatorExpression.Right), UnaryOperatorType.Not)); } } return null; } public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { if (AddDefaultValueInitializerToLocalVariableDeclarations && (localVariableDeclaration.Modifier & Modifiers.Static) == 0) { for (int i = 0; i < localVariableDeclaration.Variables.Count; i++) { VariableDeclaration decl = localVariableDeclaration.Variables[i]; if (decl.FixedArrayInitialization.IsNull && decl.Initializer.IsNull) { TypeReference type = localVariableDeclaration.GetTypeForVariable(i); decl.Initializer = ExpressionBuilder.CreateDefaultValueForType(type); } } } return base.VisitLocalVariableDeclaration(localVariableDeclaration, data); } } }
lgpl-3.0
jasonly17/Frequency_Spectrum_Analyzer
Frequency_Spectrum_Analyzer/audioengine.cpp
4034
#include "audioengine.h" #include <QDebug> #include <QFile> #include <QObject> #include <QTimer> #include "def.h" #include "frequencyspectrum.h" /****************************************************************************** * AudioEngine ******************************************************************************/ AudioEngine::AudioEngine(QObject *parent) : QObject(parent) , mState(QAudio::StoppedState) , availableAudioInputDevices(QAudioDeviceInfo::availableDevices(QAudio::AudioInput)) , mAudioInputDeviceInfo(QAudioDeviceInfo::defaultInputDevice()) , mBufferHead(0) , mBufferTail(0) , mBufferDataLength(0) , mCount(0) { qRegisterMetaType<FrequencySpectrum>("FrequencySpectrum"); // pcm 16-bit signed audio mFormat.setSampleRate(SAMPLERATE); mFormat.setSampleSize(BITSPERSAMPLE); mFormat.setChannelCount(CHANNELCOUNT); mFormat.setByteOrder(QAudioFormat::LittleEndian); mFormat.setSampleType(QAudioFormat::SignedInt); mFormat.setCodec("audio/pcm"); // give extra buffers for simultaneous buffering and processing mBufferLength = SAMPLES * SAMPLESIZE * 4; mBuffer.resize(mBufferLength); mAudioInput = new QAudioInput(mAudioInputDeviceInfo, mFormat, this); connect(&mSpectrumAnalyzer, SIGNAL(spectrumChanged(const FrequencySpectrum&)), this, SIGNAL(spectrumChanged(const FrequencySpectrum&))); // file = new QFile("out.raw"); // if (file->exists()) file->remove(); // file->open(QIODevice::Append); // qDebug() << file->error(); } AudioEngine::~AudioEngine() { stopRecording(); mAudioInput->deleteLater(); // file->deleteLater(); } /*********** Public Functions ***********/ // Starts recording audio from the default input device into the buffer. void AudioEngine::startRecording() { mAudioInputIODevice = mAudioInput->start(); connect(mAudioInputIODevice, SIGNAL(readyRead()), this, SLOT(audioDataReady())); } // Stops recording audio and closes the raw output file. void AudioEngine::stopRecording() { qDebug() << "stopping"; mAudioInput->stop(); // file->close(); mAudioInputIODevice = 0; } /*********** Public Slots ***********/ // Loads the audio data that is ready into the buffer and processes it if the // buffer is at least the FFT size. void AudioEngine::audioDataReady() { const qint64 bytesReady = mAudioInput->bytesReady(); const qint64 bytesSpace = mBufferLength - mBufferHead; const qint64 bytesSpaceWrap = bytesReady - bytesSpace; qint64 bytesRead = 0; // treats buffer like a ring buffer if (bytesSpaceWrap > 0) { bytesRead = mAudioInputIODevice->read(mBuffer.data() + mBufferHead, bytesSpace) + mAudioInputIODevice->read(mBuffer.data(), bytesSpaceWrap); mBufferHead = bytesSpaceWrap; } else { bytesRead = mAudioInputIODevice->read(mBuffer.data() + mBufferHead, bytesReady); mBufferHead += bytesReady; } if (bytesRead) mBufferDataLength += bytesRead; if (mBufferDataLength >= SAMPLES * SAMPLESIZE) { // qDebug() << "writing" << mBufferTail // << mBufferTail + SAMPLES * BYTESPERSAMPLE; // char *ptr = mBuffer.data() + mBufferTail; // const char *end = ptr + BUFFERSIZE; // while (ptr < end) { // qint16 *value = reinterpret_cast<qint16*>(ptr); // *value = *value * 1; // relative gain // ptr += 2; // } calculateSpectrum(mBufferTail); // file->write(mBuffer.data() + mBufferTail, SAMPLES * SAMPLESIZE); mBufferDataLength -= SAMPLES * SAMPLESIZE; mBufferTail += SAMPLES * SAMPLESIZE; if (mBufferTail >= mBufferLength) { mBufferTail = 0; } } // qDebug() << "head:" << mBufferHead << "tail:" << mBufferTail; // qDebug() << "bytes ready:" << bytesReady << "bytes space:" << bytesSpace // << "data in buffer:" << mBufferDataLength; } /*********** Private Functions ***********/ // Send the audio data to be processed by the spectrum analyzer. void AudioEngine::calculateSpectrum(qint64 position) { if (mSpectrumAnalyzer.isReady()) { mSpectrumBuffer = QByteArray::fromRawData(mBuffer.constData() + position, SAMPLES * SAMPLESIZE); mSpectrumAnalyzer.calculateSpectrum(mSpectrumBuffer); } }
lgpl-3.0
Stephen-Ross/SharpFilters
SharpFilters.Tests/Properties/AssemblyInfo.cs
1475
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SharpFilters.Tests")] [assembly: AssemblyDescription("Tests for the SharpFilters Library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stephen Ross")] [assembly: AssemblyProduct("SharpFilters.Tests")] [assembly: AssemblyCopyright("Copyright © Stephen Ross 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("F7EE2558-FA39-49B4-8969-20BF13FF34A1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
lgpl-3.0
mhogrefe/malachite
malachite-base/tests/num/float/basic/to_ordered_representation.rs
3848
use malachite_base::num::basic::floats::PrimitiveFloat; use malachite_base::num::float::NiceFloat; use malachite_base_test_util::generators::{ primitive_float_gen_var_11, primitive_float_pair_gen_var_1, }; use std::panic::catch_unwind; #[allow(clippy::approx_constant)] #[test] pub fn test_to_ordered_representation() { fn test<T: PrimitiveFloat>(x: T, out: u64) { assert_eq!(x.to_ordered_representation(), out); } test::<f32>(f32::NEGATIVE_INFINITY, 0); test::<f32>(-f32::MAX_FINITE, 1); test::<f32>(-458.42188, 1000000000); test::<f32>(-10.0, 1046478848); test::<f32>(-core::f32::consts::PI, 1060565029); test::<f32>(-1.0, 1073741824); test::<f32>(-0.1, 1102263091); test::<f32>(-f32::MIN_POSITIVE_NORMAL, 2130706432); test::<f32>(-f32::MAX_SUBNORMAL, 2130706433); test::<f32>(-f32::MIN_POSITIVE_SUBNORMAL, 2139095039); test::<f32>(-0.0, 2139095040); test::<f32>(0.0, 2139095041); test::<f32>(f32::MIN_POSITIVE_SUBNORMAL, 2139095042); test::<f32>(f32::MAX_SUBNORMAL, 2147483648); test::<f32>(f32::MIN_POSITIVE_NORMAL, 2147483649); test::<f32>(0.1, 3175926990); test::<f32>(0.99999994, 3204448256); test::<f32>(1.0, 3204448257); test::<f32>(1.0000001, 3204448258); test::<f32>(3.1415925, 3217625051); test::<f32>(core::f32::consts::PI, 3217625052); test::<f32>(3.141593, 3217625053); test::<f32>(10.0, 3231711233); test::<f32>(f32::MAX_FINITE, 4278190080); test::<f32>(f32::POSITIVE_INFINITY, 4278190081); test::<f64>(f64::NEGATIVE_INFINITY, 0); test::<f64>(-f64::MAX_FINITE, 1); test::<f64>(-10.0, 4597049319638433792); test::<f64>(-core::f64::consts::PI, 4604611780675359464); test::<f64>(-1.0, 4611686018427387904); test::<f64>(-0.1, 4626998257160447590); test::<f64>(-f64::MIN_POSITIVE_NORMAL, 9214364837600034816); test::<f64>(-f64::MAX_SUBNORMAL, 9214364837600034817); test::<f64>(-f64::MIN_POSITIVE_SUBNORMAL, 9218868437227405311); test::<f64>(-0.0, 9218868437227405312); test::<f64>(0.0, 9218868437227405313); test::<f64>(f64::MIN_POSITIVE_SUBNORMAL, 9218868437227405314); test::<f64>(f64::MAX_SUBNORMAL, 9223372036854775808); test::<f64>(f64::MIN_POSITIVE_NORMAL, 9223372036854775809); test::<f64>(1.9261352099337372e-256, 10000000000000000000); test::<f64>(0.1, 13810738617294363035); test::<f64>(0.9999999999999999, 13826050856027422720); test::<f64>(1.0, 13826050856027422721); test::<f64>(1.0000000000000002, 13826050856027422722); test::<f64>(3.1415926535897927, 13833125093779451160); test::<f64>(core::f64::consts::PI, 13833125093779451161); test::<f64>(3.1415926535897936, 13833125093779451162); test::<f64>(10.0, 13840687554816376833); test::<f64>(f64::MAX_FINITE, 18437736874454810624); test::<f64>(f64::POSITIVE_INFINITY, 18437736874454810625); } fn to_ordered_representation_fail_helper<T: PrimitiveFloat>() { assert_panic!(T::NAN.to_ordered_representation()); } #[test] pub fn to_ordered_representation_fail() { apply_fn_to_primitive_floats!(to_ordered_representation_fail_helper); } fn to_ordered_representation_properties_helper<T: PrimitiveFloat>() { primitive_float_gen_var_11::<T>().test_properties(|x| { let i = x.to_ordered_representation(); assert!(i <= T::LARGEST_ORDERED_REPRESENTATION); assert_eq!(NiceFloat(T::from_ordered_representation(i)), NiceFloat(x)); }); primitive_float_pair_gen_var_1::<T>().test_properties(|(x, y)| { assert_eq!( NiceFloat(x).cmp(&NiceFloat(y)), x.to_ordered_representation() .cmp(&y.to_ordered_representation()) ); }); } #[test] fn to_ordered_representation_properties() { apply_fn_to_primitive_floats!(to_ordered_representation_properties_helper); }
lgpl-3.0
seanbright/ari4java
classes/ch/loway/oss/ari4java/generated/ari_1_9_0/models/ChannelHold_impl_ari_1_9_0.java
1446
package ch.loway.oss.ari4java.generated.ari_1_9_0.models; // ---------------------------------------------------- // THIS CLASS WAS GENERATED AUTOMATICALLY // PLEASE DO NOT EDIT // Generated on: Sat Jan 30 13:39:05 CET 2016 // ---------------------------------------------------- import ch.loway.oss.ari4java.generated.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.Date; import java.util.List; import java.util.Map; /********************************************************** * A channel initiated a media hold. * * Defined in file: events.json * Generated by: Model *********************************************************/ public class ChannelHold_impl_ari_1_9_0 extends Event_impl_ari_1_9_0 implements ChannelHold, java.io.Serializable { private static final long serialVersionUID = 1L; /** The channel that initiated the hold event. */ private Channel channel; public Channel getChannel() { return channel; } @JsonDeserialize( as=Channel_impl_ari_1_9_0.class ) public void setChannel(Channel val ) { channel = val; } /** The music on hold class that the initiator requested. */ private String musicclass; public String getMusicclass() { return musicclass; } @JsonDeserialize( as=String.class ) public void setMusicclass(String val ) { musicclass = val; } /** No missing signatures from interface */ }
lgpl-3.0
beangle/cdi
spring/src/main/scala/org/beangle/cdi/spring/config/ReconfigParser.scala
17956
/* * Copyright (C) 2005, The Beangle Software. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.beangle.cdi.spring.config import org.beangle.cdi.bind.Binding.InjectPlaceHolder import org.beangle.cdi.bind.Reconfig.ReconfigType import org.beangle.cdi.bind.{Binding, Reconfig} import org.beangle.commons.collection.Collections import org.beangle.commons.conversion.impl.DefaultConversion import org.beangle.commons.lang.{ClassLoaders, Strings} import org.beangle.commons.logging.Logging import org.springframework.beans.factory.support.{ManagedArray, ManagedList, ManagedSet} import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate._ import org.springframework.util.StringUtils import org.springframework.util.xml.DomUtils import org.w3c.dom.{Element, Node, NodeList} import java.util.Properties import scala.collection.mutable /** * Reconfig BeanDefinition Parser * * @author chaostone */ class ReconfigParser extends Logging { /** * Stores all used bean names so we can enforce uniqueness on a per file * basis. */ private val usedNames = new mutable.HashSet[String] /** * Report an error with the given message for the given source element. */ protected def error(message: String, source: Any, cause: Throwable = null): Unit = { logger.error(message) } /** * Parses the supplied <code>&ltbean&gt</code> element. May return <code>null</code> if there * were errors during parse. */ def parseBeanDefinitionElement(ele: Element): Reconfig.Definition = { parseBeanDefinitionElement(ele, null) } /** * Parses the supplied <code>&ltbean&gt</code> element. May return <code>null</code> if there * were errors during parse. */ private def parseBeanDefinitionElement(ele: Element, containingBean: Binding.Definition): Reconfig.Definition = { val id = ele.getAttribute(ID_ATTRIBUTE) val nameAttr = ele.getAttribute(NAME_ATTRIBUTE) val aliases = new mutable.ListBuffer[String] if (Strings.isNotEmpty(nameAttr)) { val nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS) for (name <- nameArr) aliases += name } var beanName = id if (!StringUtils.hasText(beanName) && !aliases.isEmpty) { beanName = aliases.remove(0) logger.debug(s"No XML 'id' specified - using '$beanName' as bean name and $aliases as aliases") } if (containingBean == null) checkNameUniqueness(beanName, aliases, ele) val beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean) if (beanDefinition != null) { val ovr = ele.getAttribute("override") val configType = if (null != ovr && ovr == "remove") ReconfigType.Remove else { val primary = ele.getAttribute("primary") if (null != primary && primary.equals("true")) ReconfigType.Primary else ReconfigType.Update } return new Reconfig.Definition(beanName, configType, beanDefinition) } null } /** * Validate that the specified bean name and aliases have not been used * already. */ protected def checkNameUniqueness(beanName: String, aliases: collection.Seq[String], beanElement: Element): Unit = { var foundName: String = null if (StringUtils.hasText(beanName) && this.usedNames.contains(beanName)) foundName = beanName if (foundName == null) foundName = Collections.findFirstMatch(this.usedNames, aliases).orNull if (foundName != null) error("Bean name '" + foundName + "' is already used in this file", beanElement) this.usedNames += beanName this.usedNames ++= aliases } /** * Parse the bean definition itself, without regard to name or aliases. May * return <code>null</code> if problems occured during the parse of the bean * definition. */ private def parseBeanDefinitionElement(ele: Element, beanName: String, containingBean: Binding.Definition): Binding.Definition = { val className = if (ele.hasAttribute(CLASS_ATTRIBUTE)) ele.getAttribute(CLASS_ATTRIBUTE).trim() else null try { val bd = new Binding.Definition(beanName, if (null == className) null else ClassLoaders.load(className), null) parseBeanDefinitionAttributes(ele, beanName, containingBean, bd) parseConstructorArgElements(ele, bd) parsePropertyElements(ele, bd) return bd } catch { case ex: ClassNotFoundException => error("Bean class [" + className + "] not found", ele, ex) case exr: Throwable => error("Unexpected failure during bean definition parsing", ele, exr) } null } /** * Apply the attributes of the given bean element to the given bean * * definition. */ private def parseBeanDefinitionAttributes(ele: Element, beanName: String, containingBean: Binding.Definition, bd: Binding.Definition): Binding.Definition = { if (ele.hasAttribute(SCOPE_ATTRIBUTE)) { bd.scope = ele.getAttribute(SCOPE_ATTRIBUTE) } else if (containingBean != null) { bd.scope = containingBean.scope } else { bd.scope = "singleton" } if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) bd.abstractFlag = TRUE_VALUE == ele.getAttribute(ABSTRACT_ATTRIBUTE) bd.lazyInit = TRUE_VALUE == ele.getAttribute(LAZY_INIT_ATTRIBUTE) if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) bd.primary = TRUE_VALUE == ele.getAttribute(PRIMARY_ATTRIBUTE) if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) { val initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE) if (!"".equals(initMethodName)) bd.initMethod = initMethodName } if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) { val destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE) if (!"".equals(destroyMethodName)) bd.destroyMethod = destroyMethodName } if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) bd.factoryMethod = ele.getAttribute(FACTORY_METHOD_ATTRIBUTE) if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) bd.factoryBean = ele.getAttribute(FACTORY_BEAN_ATTRIBUTE) bd } /** * Parse constructor-arg sub-elements of the given bean element. */ private def parseConstructorArgElements(beanEle: Element, bd: Binding.Definition): Unit = { findChildren(beanEle, CONSTRUCTOR_ARG_ELEMENT) foreach { node => parseConstructorArgElement(node, bd) } } /** * Parse property sub-elements of the given bean element. * */ private def parsePropertyElements(beanEle: Element, bd: Binding.Definition): Unit = { findChildren(beanEle, PROPERTY_ELEMENT) foreach { node => parsePropertyElement(node, bd) } } /** * Parse a constructor-arg element. * */ private def parseConstructorArgElement(ele: Element, bd: Binding.Definition): Unit = { val indexAttr = ele.getAttribute(INDEX_ATTRIBUTE) if (bd.constructorArgs == null) { bd.constructorArgs = new mutable.ArrayBuffer[Any] } if (Strings.isNotEmpty(indexAttr)) { val index = Integer.parseInt(indexAttr) bd.constructorArgs(index) = parsePropertyValue(ele, bd, null) } else { bd.constructorArgs += parsePropertyValue(ele, bd, null) } } /** * Parse a property element. * */ private def parsePropertyElement(ele: Element, bd: Binding.Definition): Unit = { val propertyName = ele.getAttribute(NAME_ATTRIBUTE) bd.properties.put(propertyName, parsePropertyValue(ele, bd, propertyName)) } /** * Get the value of a property element. May be a list etc. Also used for * constructor arguments, "propertyName" being null in this case. */ private def parsePropertyValue(ele: Element, bd: Binding.Definition, propertyName: String): Object = { val elementName = if (propertyName != null) "<property> element for property '" + propertyName + "'" else "<constructor-arg> element" val subElement = findOnlyOneChildren(ele) val hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE) val hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE) if ((hasRefAttribute && hasValueAttribute) || ((hasRefAttribute || hasValueAttribute) && subElement != null)) { error(elementName + " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele) } if (hasRefAttribute) { val refName = ele.getAttribute(REF_ATTRIBUTE) if (!StringUtils.hasText(refName)) error(elementName + " contains empty 'ref' attribute", ele) Binding.ReferenceValue(refName) } else if (hasValueAttribute) { val v = ele.getAttribute(VALUE_ATTRIBUTE) if (null == propertyName && v == "?") { InjectPlaceHolder } else { v } } else if (subElement != null) { parsePropertySubElement(subElement, bd) } else { // Neither child element nor "ref" or "value" attribute found. error(elementName + " must specify a ref or value", ele) null } } /** * <p> * parsePropertySubElement. * </p> * */ private def parsePropertySubElement(ele: Element, bd: Binding.Definition): Object = { parsePropertySubElement(ele, bd, null) } /** * Parse a value, ref or collection sub-element of a property or * constructor-arg element. */ private def parsePropertySubElement(ele: Element, bd: Binding.Definition, defaultValueType: String): Object = { if (!isDefaultNamespace(ele.getNamespaceURI)) { error("Cannot support nested element .", ele) null } else if (nodeNameEquals(ele, BEAN_ELEMENT)) { parseBeanDefinitionElement(ele, bd) } else if (nodeNameEquals(ele, REF_ELEMENT)) { Binding.ReferenceValue(ele.getAttribute(BEAN_REF_ATTRIBUTE)) } else if (nodeNameEquals(ele, IDREF_ELEMENT)) { Binding.ReferenceValue(ele.getAttribute(BEAN_REF_ATTRIBUTE)) } else if (nodeNameEquals(ele, VALUE_ELEMENT)) { parseValueElement(ele, defaultValueType) } else if (nodeNameEquals(ele, NULL_ELEMENT)) { null } else if (nodeNameEquals(ele, ARRAY_ELEMENT)) { parseArrayElement(ele, bd) } else if (nodeNameEquals(ele, LIST_ELEMENT)) { parseListElement(ele, bd) } else if (nodeNameEquals(ele, SET_ELEMENT)) { parseSetElement(ele, bd) } else if (nodeNameEquals(ele, MAP_ELEMENT)) { parseMapElement(ele, bd) } else if (nodeNameEquals(ele, PROPS_ELEMENT)) { parsePropsElement(ele) } else { error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele) null } } /** * Return a typed String value Object for the given value element. */ private def parseValueElement(ele: Element, defaultTypeName: String): Object = { DomUtils.getTextValue(ele) // It's a literal value. } /** * Parse an array element. */ private def parseArrayElement(arrayEle: Element, bd: Binding.Definition): Object = { val elementType = arrayEle.getAttribute(VALUE_TYPE_ATTRIBUTE) val nl = arrayEle.getChildNodes val target = new ManagedArray(elementType, nl.getLength()) target.setElementTypeName(elementType) parseCollectionElements(nl, target, bd, elementType) target } /** * Parse a list element. */ private def parseListElement(collectionEle: Element, bd: Binding.Definition): java.util.List[Object] = { val defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE) val nl = collectionEle.getChildNodes() val target = new ManagedList[Object](nl.getLength()) target.setElementTypeName(defaultElementType) parseCollectionElements(nl, target, bd, defaultElementType) target } /** * Parse a set element. */ private def parseSetElement(collectionEle: Element, bd: Binding.Definition): java.util.Set[Object] = { val defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE) val nl = collectionEle.getChildNodes() val target = new ManagedSet[Object](nl.getLength()) target.setElementTypeName(defaultElementType) parseCollectionElements(nl, target, bd, defaultElementType) target } /** * parseCollectionElements. */ protected def parseCollectionElements(elementNodes: NodeList, target: java.util.Collection[Object], bd: Binding.Definition, defaultElementType: String): Unit = { for (i <- 0 until elementNodes.getLength) { val node = elementNodes.item(i) if (node.isInstanceOf[Element] && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) target.add(parsePropertySubElement(node.asInstanceOf[Element], bd, defaultElementType)) } } /** * Parse a map element. */ private def parseMapElement(mapEle: Element, bd: Binding.Definition): collection.Map[Any, Any] = { val defaultKeyType = mapEle.getAttribute(KEY_TYPE_ATTRIBUTE) val defaultValueType = mapEle.getAttribute(VALUE_TYPE_ATTRIBUTE) val map = Collections.newMap[Any, Any] findChildren(mapEle, ENTRY_ELEMENT) foreach { entryEle => val keyEle = findOnlyOneChildren(entryEle, KEY_ELEMENT) val valueEle = findOnlyOneChildren(entryEle, VALUE_ELEMENT) var key: Any = null val hasKeyAttribute = entryEle.hasAttribute(KEY_ATTRIBUTE) val hasKeyRefAttribute = entryEle.hasAttribute(KEY_REF_ATTRIBUTE) if ((hasKeyAttribute && hasKeyRefAttribute) || ((hasKeyAttribute || hasKeyRefAttribute)) && keyEle != null) { error("<entry> element is only allowed to contain either " + "a 'key' attribute OR a 'key-ref' attribute OR a <key> sub-element", entryEle) } if (hasKeyAttribute) { key = convertTo(entryEle.getAttribute(KEY_ATTRIBUTE), defaultKeyType) } else if (hasKeyRefAttribute) { key = Binding.ReferenceValue(entryEle.getAttribute(KEY_REF_ATTRIBUTE)) } else if (keyEle != null) { key = parseKeyElement(keyEle, bd, defaultKeyType) } else { error("<entry> element must specify a key", entryEle) } // Extract value from attribute or sub-element. var value: Any = null val hasValueAttribute = entryEle.hasAttribute(VALUE_ATTRIBUTE) val hasValueRefAttribute = entryEle.hasAttribute(VALUE_REF_ATTRIBUTE) if ((hasValueAttribute && hasValueRefAttribute) || (hasValueAttribute || hasValueRefAttribute) && valueEle != null) { error("<entry> element is only allowed to contain either " + "'value' attribute OR 'value-ref' attribute OR <value> sub-element", entryEle) } if (hasValueAttribute) { value = convertTo(entryEle.getAttribute(VALUE_ATTRIBUTE), defaultValueType) } else if (hasValueRefAttribute) { Binding.ReferenceValue(entryEle.getAttribute(VALUE_REF_ATTRIBUTE)) } else if (valueEle != null) { value = parsePropertySubElement(valueEle, bd, defaultValueType) } else { error("<entry> element must specify a value", entryEle) } map.put(key, value) } map } /** * Parse a key sub-element of a map element. */ protected def parseKeyElement(keyEle: Element, bd: Binding.Definition, defaultKeyTypeName: String): Object = { parsePropertySubElement(findOnlyOneChildren(keyEle), bd, defaultKeyTypeName) } /** * Parse a props element. */ private def parsePropsElement(propsEle: Element): java.util.Properties = { val props = new Properties() findChildren(propsEle, PROP_ELEMENT) foreach { propEle => val key = propEle.getAttribute(KEY_ATTRIBUTE) val value = DomUtils.getTextValue(propEle).trim() props.put(key, value) } props } private def isDefaultNamespace(namespaceUri: String): Boolean = Strings.isEmpty(namespaceUri) || BEANS_NAMESPACE_URI == namespaceUri private def nodeNameEquals(node: Node, desiredName: String): Boolean = { desiredName.equals(node.getNodeName) || desiredName.equals(node.getLocalName) } private def findChildren(ele: Element, tagName: String): Iterable[Element] = { val children = Collections.newBuffer[Element] val entrySubNodes = ele.getChildNodes for (j <- 0 until entrySubNodes.getLength) { val node = entrySubNodes.item(j) if (node.isInstanceOf[Element]) { val candidateEle = node.asInstanceOf[Element] if (nodeNameEquals(candidateEle, tagName)) { children += candidateEle } } } children } private def findOnlyOneChildren(ele: Element, tagName: String = null): Element = { val entrySubNodes = ele.getChildNodes() var childEle: Element = null for (j <- 0 until entrySubNodes.getLength) { val node = entrySubNodes.item(j) if (node.isInstanceOf[Element]) { val candidateEle = node.asInstanceOf[Element] if (tagName == null && !nodeNameEquals(node, DESCRIPTION_ELEMENT) && !nodeNameEquals(node, META_ELEMENT) || nodeNameEquals(candidateEle, tagName)) { if (childEle != null) error(s"<${ele.getNodeName}> only one <${tagName}> sub-element needed", ele) else childEle = candidateEle } } } childEle } private def convertTo(v: Any, clazz: String): Any = { v match { case s: String => if (Strings.isBlank(clazz) || clazz == "java.lang.String" || clazz == "string") v else DefaultConversion.Instance.convert(s, ClassLoaders.load(clazz)) case _ => v } } }
lgpl-3.0
pcolby/libqtaws
src/lightsail/stoprelationaldatabaserequest.cpp
4434
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "stoprelationaldatabaserequest.h" #include "stoprelationaldatabaserequest_p.h" #include "stoprelationaldatabaseresponse.h" #include "lightsailrequest_p.h" namespace QtAws { namespace Lightsail { /*! * \class QtAws::Lightsail::StopRelationalDatabaseRequest * \brief The StopRelationalDatabaseRequest class provides an interface for Lightsail StopRelationalDatabase requests. * * \inmodule QtAwsLightsail * * Amazon Lightsail is the easiest way to get started with Amazon Web Services (AWS) for developers who need to build * websites or web applications. It includes everything you need to launch your project quickly - instances (virtual * private servers), container services, managed databases, SSD-based block storage, static IP addresses, load balancers, * content delivery network (CDN) distributions, DNS management of registered domains, and resource snapshots (backups) - * for a low, predictable monthly * * price> * * You can manage your Lightsail resources using the Lightsail console, Lightsail API, AWS Command Line Interface (AWS * CLI), or SDKs. For more information about Lightsail concepts and tasks, see the <a * href="http://lightsail.aws.amazon.com/ls/docs/how-to/article/lightsail-how-to-set-up-access-keys-to-use-sdk-api-cli">Lightsail * Dev * * Guide</a>> * * This API Reference provides detailed information about the actions, data types, parameters, and errors of the Lightsail * service. For more information about the supported AWS Regions, endpoints, and service quotas of the Lightsail service, * see <a href="https://docs.aws.amazon.com/general/latest/gr/lightsail.html">Amazon Lightsail Endpoints and Quotas</a> in * the <i>AWS General * * \sa LightsailClient::stopRelationalDatabase */ /*! * Constructs a copy of \a other. */ StopRelationalDatabaseRequest::StopRelationalDatabaseRequest(const StopRelationalDatabaseRequest &other) : LightsailRequest(new StopRelationalDatabaseRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a StopRelationalDatabaseRequest object. */ StopRelationalDatabaseRequest::StopRelationalDatabaseRequest() : LightsailRequest(new StopRelationalDatabaseRequestPrivate(LightsailRequest::StopRelationalDatabaseAction, this)) { } /*! * \reimp */ bool StopRelationalDatabaseRequest::isValid() const { return false; } /*! * Returns a StopRelationalDatabaseResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * StopRelationalDatabaseRequest::response(QNetworkReply * const reply) const { return new StopRelationalDatabaseResponse(*this, reply); } /*! * \class QtAws::Lightsail::StopRelationalDatabaseRequestPrivate * \brief The StopRelationalDatabaseRequestPrivate class provides private implementation for StopRelationalDatabaseRequest. * \internal * * \inmodule QtAwsLightsail */ /*! * Constructs a StopRelationalDatabaseRequestPrivate object for Lightsail \a action, * with public implementation \a q. */ StopRelationalDatabaseRequestPrivate::StopRelationalDatabaseRequestPrivate( const LightsailRequest::Action action, StopRelationalDatabaseRequest * const q) : LightsailRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the StopRelationalDatabaseRequest * class' copy constructor. */ StopRelationalDatabaseRequestPrivate::StopRelationalDatabaseRequestPrivate( const StopRelationalDatabaseRequestPrivate &other, StopRelationalDatabaseRequest * const q) : LightsailRequestPrivate(other, q) { } } // namespace Lightsail } // namespace QtAws
lgpl-3.0
Builders-SonarSource/sonarqube-bis
sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/pattern/IssuePattern.java
4488
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.scanner.issue.ignore.pattern; import com.google.common.collect.Sets; import java.util.Set; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.rule.RuleKey; import org.sonar.api.scan.issue.filter.FilterableIssue; import org.sonar.api.utils.WildcardPattern; public class IssuePattern { private WildcardPattern resourcePattern; private WildcardPattern rulePattern; private Set<Integer> lines = Sets.newLinkedHashSet(); private Set<LineRange> lineRanges = Sets.newLinkedHashSet(); private String beginBlockRegexp; private String endBlockRegexp; private String allFileRegexp; private boolean checkLines = true; public IssuePattern() { } public IssuePattern(String resourcePattern, String rulePattern) { this.resourcePattern = WildcardPattern.create(resourcePattern); this.rulePattern = WildcardPattern.create(rulePattern); } public IssuePattern(String resourcePattern, String rulePattern, Set<LineRange> lineRanges) { this(resourcePattern, rulePattern); this.lineRanges = lineRanges; } public WildcardPattern getResourcePattern() { return resourcePattern; } public WildcardPattern getRulePattern() { return rulePattern; } public String getBeginBlockRegexp() { return beginBlockRegexp; } public String getEndBlockRegexp() { return endBlockRegexp; } public String getAllFileRegexp() { return allFileRegexp; } IssuePattern addLineRange(int fromLineId, int toLineId) { lineRanges.add(new LineRange(fromLineId, toLineId)); return this; } IssuePattern addLine(int lineId) { lines.add(lineId); return this; } boolean isCheckLines() { return checkLines; } IssuePattern setCheckLines(boolean b) { this.checkLines = b; return this; } IssuePattern setBeginBlockRegexp(String beginBlockRegexp) { this.beginBlockRegexp = beginBlockRegexp; return this; } IssuePattern setEndBlockRegexp(String endBlockRegexp) { this.endBlockRegexp = endBlockRegexp; return this; } IssuePattern setAllFileRegexp(String allFileRegexp) { this.allFileRegexp = allFileRegexp; return this; } Set<Integer> getAllLines() { Set<Integer> allLines = Sets.newLinkedHashSet(lines); for (LineRange lineRange : lineRanges) { allLines.addAll(lineRange.toLines()); } return allLines; } public boolean match(FilterableIssue issue) { boolean match = matchResource(issue.componentKey()) && matchRule(issue.ruleKey()); if (checkLines) { Integer line = issue.line(); if (line == null) { match = false; } else { match = match && matchLine(line); } } return match; } boolean matchLine(int lineId) { if (lines.contains(lineId)) { return true; } for (LineRange range : lineRanges) { if (range.in(lineId)) { return true; } } return false; } boolean matchRule(RuleKey rule) { String key = new StringBuilder().append(rule.repository()).append(':').append(rule.rule()).toString(); return rulePattern.match(key); } boolean matchResource(@Nullable String resource) { return resource != null && resourcePattern.match(resource); } public IssuePattern forResource(String resource) { return new IssuePattern(resource, rulePattern.toString(), lineRanges).setCheckLines(isCheckLines()); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
lgpl-3.0
catedrasaes-umu/emf4cpp
emf4cpp.tests/xpand/xpand3/declaration/Extension.cpp
4868
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*- /* * xpand3/declaration/Extension.cpp * Copyright (C) Cátedra SAES-UMU 2010 <[email protected]> * Copyright (C) INCHRON GmbH 2016 <[email protected]> * * EMF4CPP is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EMF4CPP is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Extension.hpp" #include <xpand3/declaration/AbstractNamedDeclaration.hpp> #include <xpand3/File.hpp> #include <xpand3/DeclaredParameter.hpp> #include <xpand3/expression/AbstractExpression.hpp> #include <xpand3/Identifier.hpp> #include <ecore/EObject.hpp> #include <ecore/EClass.hpp> #include "xpand3/declaration/DeclarationPackage.hpp" #include <ecorecpp/mapping.hpp> #ifdef ECORECPP_NOTIFICATION_API #include <ecorecpp/notify.hpp> #endif /*PROTECTED REGION ID(Extension.cpp) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ using namespace ::xpand3::declaration; // Default constructor Extension::Extension() : m_body(0), m_returnType(0) { /*PROTECTED REGION ID(ExtensionImpl__ExtensionImpl) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ #ifdef ECORECPP_NOTIFICATION_API m_eDeliver = false; #endif } Extension::~Extension() { if (m_body) { m_body.reset(); } if (m_returnType) { m_returnType.reset(); } } // Attributes ::ecore::EBoolean Extension::isCached() const { return m_cached; } void Extension::setCached(::ecore::EBoolean _cached) { #ifdef ECORECPP_NOTIFICATION_API ::ecore::EBoolean _old_cached = m_cached; #endif m_cached = _cached; #ifdef ECORECPP_NOTIFICATION_API if (eNotificationRequired()) { ::ecorecpp::notify::Notification notification( ::ecorecpp::notify::Notification::SET, _this(), ::xpand3::declaration::DeclarationPackage::_instance()->getExtension__cached(), _old_cached, m_cached ); eNotify(&notification); } #endif } // References ::xpand3::expression::AbstractExpression_ptr Extension::getBody() const { return m_body; } void Extension::setBody(::xpand3::expression::AbstractExpression_ptr _body) { if (m_body) m_body->_setEContainer(Extension_ptr(), ::xpand3::declaration::DeclarationPackage::_instance()->getExtension__body()); if (_body) _body->_setEContainer(_this(), ::xpand3::declaration::DeclarationPackage::_instance()->getExtension__body()); #ifdef ECORECPP_NOTIFICATION_API ::xpand3::expression::AbstractExpression_ptr _old_body = m_body; #endif m_body = _body; #ifdef ECORECPP_NOTIFICATION_API if (eNotificationRequired()) { ::ecorecpp::notify::Notification notification( ::ecorecpp::notify::Notification::SET, _this(), ::xpand3::declaration::DeclarationPackage::_instance()->getExtension__body(), _old_body, m_body ); eNotify(&notification); } #endif } ::xpand3::Identifier_ptr Extension::getReturnType() const { return m_returnType; } void Extension::setReturnType(::xpand3::Identifier_ptr _returnType) { if (m_returnType) m_returnType->_setEContainer(Extension_ptr(), ::xpand3::declaration::DeclarationPackage::_instance()->getExtension__returnType()); if (_returnType) _returnType->_setEContainer(_this(), ::xpand3::declaration::DeclarationPackage::_instance()->getExtension__returnType()); #ifdef ECORECPP_NOTIFICATION_API ::xpand3::Identifier_ptr _old_returnType = m_returnType; #endif m_returnType = _returnType; #ifdef ECORECPP_NOTIFICATION_API if (eNotificationRequired()) { ::ecorecpp::notify::Notification notification( ::ecorecpp::notify::Notification::SET, _this(), ::xpand3::declaration::DeclarationPackage::_instance()->getExtension__returnType(), _old_returnType, m_returnType ); eNotify(&notification); } #endif }
lgpl-3.0
ikoryakovskiy/grl
base/src/environments/modeled.cpp
7875
/** \file modeled.cpp * \brief Modeled environment and dynamical model source file. * * \author Wouter Caarls <[email protected]> * \date 2015-01-22 * * \copyright \verbatim * Copyright (c) 2015, Wouter Caarls * All rights reserved. * * This file is part of GRL, the Generic Reinforcement Learning library. * * GRL is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * \endverbatim */ #include <grl/environment.h> using namespace grl; REGISTER_CONFIGURABLE(ModeledEnvironment) REGISTER_CONFIGURABLE(DynamicalModel) REGISTER_CONFIGURABLE(ExtStateModeledEnvironment) void ModeledEnvironment::request(ConfigurationRequest *config) { config->push_back(CRP("model", "model", "Environment model", model_)); config->push_back(CRP("task", "task", "Task to perform in the environment (should match model)", task_)); config->push_back(CRP("exporter", "exporter", "Optional exporter for transition log (supports time, state, observation, action, reward, terminal)", exporter_, true)); config->push_back(CRP("state", "signal/vector", "Current state of the model", CRP::Provided)); } void ModeledEnvironment::configure(Configuration &config) { model_ = (Model*)config["model"].ptr(); task_ = (Task*)config["task"].ptr(); exporter_ = (Exporter*)config["exporter"].ptr(); // Register fields to be exported if (exporter_) exporter_->init({"time", "state0", "state1", "action", "reward", "terminal"}); state_obj_ = new VectorSignal(); config.set("state", state_obj_); } void ModeledEnvironment::reconfigure(const Configuration &config) { if (config.has("action") && config["action"].str() == "reset") time_learn_ = time_test_ = 0.; } ModeledEnvironment &ModeledEnvironment::copy(const Configurable &obj) { const ModeledEnvironment& me = dynamic_cast<const ModeledEnvironment&>(obj); obs_ = me.obs_; test_ = me.test_; return *this; } void ModeledEnvironment::start(int test, Observation *obs) { int terminal; task_->start(test, &state_); task_->observe(state_, obs, &terminal); obs_ = *obs; state_obj_->set(state_); test_ = test; if (exporter_) exporter_->open((test_?"test":"learn"), (test_?time_test_:time_learn_) != 0.0); } double ModeledEnvironment::step(const Action &action, Observation *obs, double *reward, int *terminal) { Vector state = state_, next, actuation; double tau = 0; bool done = false; do { done = task_->actuate(state, action, &actuation); tau += model_->step(state, actuation, &next); state = next; } while (!done); task_->observe(next, obs, terminal); task_->evaluate(state_, action, next, reward); double &time = test_?time_test_:time_learn_; if (exporter_) exporter_->write({VectorConstructor(time), state_, next, action, VectorConstructor(*reward), VectorConstructor((double)*terminal)}); time += tau; state_ = next; obs_ = *obs; state_obj_->set(state_); return tau; } void ModeledEnvironment::report(std::ostream &os) const { model_->report(os, state_); task_->report(os, state_); } void DynamicalModel::request(ConfigurationRequest *config) { config->push_back(CRP("control_step", "double.control_step", "Control step time", tau_, CRP::Configuration, 0.0001, DBL_MAX)); config->push_back(CRP("integration_steps", "Number of integration steps per control step", (int)steps_, CRP::Configuration, 1)); config->push_back(CRP("dynamics", "dynamics", "Equations of motion", dynamics_)); } void DynamicalModel::configure(Configuration &config) { dynamics_ = (Dynamics*)config["dynamics"].ptr(); tau_ = config["control_step"]; steps_ = config["integration_steps"]; } void DynamicalModel::reconfigure(const Configuration &config) { } double DynamicalModel::step(const Vector &state, const Vector &actuation, Vector *next) const { Vector xd; double h = tau_/steps_; *next = state; for (size_t ii=0; ii < steps_; ++ii) { dynamics_->eom(*next, actuation, &xd); Vector k1 = h*xd; dynamics_->eom(*next + k1/2, actuation, &xd); Vector k2 = h*xd; dynamics_->eom(*next + k2/2, actuation, &xd); Vector k3 = h*xd; dynamics_->eom(*next + k3, actuation, &xd); Vector k4 = h*xd; *next = *next + (k1+2*k2+2*k3+k4)/6; } return tau_; } void ExtStateModeledEnvironment::request(ConfigurationRequest *config) { config->push_back(CRP("model", "model", "Environment model", model_)); config->push_back(CRP("task", "task", "Task to perform in the environment (should match model)", task_)); config->push_back(CRP("exporter", "exporter", "Optional exporter for transition log (supports time, state, observation, action, reward, terminal)", exporter_, true)); config->push_back(CRP("state", "signal/vector", "Current state of the model", CRP::Provided)); config->push_back(CRP("sub_ext_state","signal/vector","External state (optional)", sub_ext_state_, true)); config->push_back(CRP("noise","int.noise","Measurement noise to be added",noise_, CRP::System)); } void ExtStateModeledEnvironment::configure(Configuration &config) { model_ = (Model*)config["model"].ptr(); task_ = (Task*)config["task"].ptr(); exporter_ = (Exporter*)config["exporter"].ptr(); // Register fields to be exported if (exporter_) exporter_->init({"time", "state", "observation", "action", "reward", "terminal"}); state_obj_ = new VectorSignal(); config.set("state", state_obj_); sub_ext_state_ = (VectorSignal*)config["sub_ext_state"].ptr(); noise_ = config["noise"]; } void ExtStateModeledEnvironment::reconfigure(const Configuration &config) { if (config.has("action") && config["action"].str() == "reset") time_learn_ = time_test_ = 0.; } ExtStateModeledEnvironment &ExtStateModeledEnvironment::copy(const Configurable &obj) { const ExtStateModeledEnvironment& me = dynamic_cast<const ExtStateModeledEnvironment&>(obj); obs_ = me.obs_; test_ = me.test_; return *this; } void ExtStateModeledEnvironment::start(int test, Observation *obs) { int terminal; task_->start(test, &state_); task_->observe(state_, obs, &terminal); obs_ = *obs; state_obj_->set(state_); test_ = test; if (exporter_) exporter_->open((test_?"test":"learn"), (test_?time_test_:time_learn_) != 0.0); } double ExtStateModeledEnvironment::step(const Action &action, Observation *obs, double *reward, int *terminal) { Vector external_state, state, next, actuation; double tau = 0; bool done = false; if (sub_ext_state_) { external_state = sub_ext_state_->get(); state_ << external_state, state_(2); state = state_; } else state = state_; do { done = task_->actuate(state, action, &actuation); tau += model_->step(state, actuation, &next); state = next; } while (!done); task_->observe(next, obs, terminal); task_->evaluate(state_, action, next, reward); double &time = test_?time_test_:time_learn_; if (exporter_) exporter_->write({VectorConstructor(time), state_, *obs, action, VectorConstructor(*reward), VectorConstructor((double)*terminal)}); time += tau; state_ = next; obs_ = *obs; state_obj_->set(state_); return tau; } void ExtStateModeledEnvironment::report(std::ostream &os) const { model_->report(os, state_); task_->report(os, state_); }
lgpl-3.0
Mindtoeye/Hoop
src/edu/cmu/cs/in/hoop/project/HoopStopWords.java
1607
/** * Author: Martin van Velsen <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package edu.cmu.cs.in.hoop.project; import org.jdom.Element; import edu.cmu.cs.in.base.HoopLink; /** * @author Martin van Velsen */ public class HoopStopWords extends HoopProjectFile { /** * */ public HoopStopWords () { setClassName ("HoopStopWords"); debug ("HoopStopWords ()"); this.setInstanceName("stopwords.xml"); } /** * */ public Element toXML() { debug ("toXML ()"); Element rootElement=super.toXML(); Element baseElement=new Element ("entries"); rootElement.addContent(baseElement); for (int i=0;i<HoopLink.stops.length;i++) { String stopEntry=HoopLink.stops [i]; Element stopElement=new Element ("stopword"); stopElement.setAttribute("name",stopEntry); stopElement.setAttribute("selected","true"); baseElement.addContent(stopElement); } return (rootElement); } }
lgpl-3.0
mosser/ArduinoML-kernel
externals/xtext/fr.polytech.si5.dsl.arduino/src-gen/fr/polytech/si5/dsl/arduino/arduinoML/Transition.java
3033
/** * generated by Xtext 2.23.0 */ package fr.polytech.si5.dsl.arduino.arduinoML; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Transition</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link fr.polytech.si5.dsl.arduino.arduinoML.Transition#getSensor <em>Sensor</em>}</li> * <li>{@link fr.polytech.si5.dsl.arduino.arduinoML.Transition#getValue <em>Value</em>}</li> * <li>{@link fr.polytech.si5.dsl.arduino.arduinoML.Transition#getNext <em>Next</em>}</li> * </ul> * * @see fr.polytech.si5.dsl.arduino.arduinoML.ArduinoMLPackage#getTransition() * @model * @generated */ public interface Transition extends EObject { /** * Returns the value of the '<em><b>Sensor</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Sensor</em>' reference. * @see #setSensor(Sensor) * @see fr.polytech.si5.dsl.arduino.arduinoML.ArduinoMLPackage#getTransition_Sensor() * @model * @generated */ Sensor getSensor(); /** * Sets the value of the '{@link fr.polytech.si5.dsl.arduino.arduinoML.Transition#getSensor <em>Sensor</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Sensor</em>' reference. * @see #getSensor() * @generated */ void setSensor(Sensor value); /** * Returns the value of the '<em><b>Value</b></em>' attribute. * The literals are from the enumeration {@link fr.polytech.si5.dsl.arduino.arduinoML.Signal}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Value</em>' attribute. * @see fr.polytech.si5.dsl.arduino.arduinoML.Signal * @see #setValue(Signal) * @see fr.polytech.si5.dsl.arduino.arduinoML.ArduinoMLPackage#getTransition_Value() * @model * @generated */ Signal getValue(); /** * Sets the value of the '{@link fr.polytech.si5.dsl.arduino.arduinoML.Transition#getValue <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Value</em>' attribute. * @see fr.polytech.si5.dsl.arduino.arduinoML.Signal * @see #getValue() * @generated */ void setValue(Signal value); /** * Returns the value of the '<em><b>Next</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Next</em>' reference. * @see #setNext(State) * @see fr.polytech.si5.dsl.arduino.arduinoML.ArduinoMLPackage#getTransition_Next() * @model * @generated */ State getNext(); /** * Sets the value of the '{@link fr.polytech.si5.dsl.arduino.arduinoML.Transition#getNext <em>Next</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Next</em>' reference. * @see #getNext() * @generated */ void setNext(State value); } // Transition
lgpl-3.0
FauxFaux/fixbugs
src/main/java/fixbugs/core/ir/ASTPatternMatcher.scala
16001
/** * * This file is part of Fixbugs. * * Fixbugs is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Fixbugs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Fixbugs. If not, see <http://www.gnu.org/licenses/>. * **/ package fixbugs.core.ir import scala.collection.mutable.{HashMap,Set => MSet} import scala.collection.mutable.{Map => MMap} import scala.collection.jcl.MutableIterator.Wrapper import org.eclipse.jdt.core.dom._ import org.eclipse.jdt.core.dom.{Statement => IRStmt, Expression => IRExpr, Assignment => IRAssign} import fixbugs.core.ir.{Statement => Stmt,Expression => Expr,Assignment => Assign} import fixbugs.util.EclipseUtil.parse import org.slf4j.{Logger,LoggerFactory} /** * Pattern matchs a Fixbugs pattern against the eclipse AST * * Proceeds recursively: * unify(node,ir,context) returns a true iff the node is unifiable with the ir and updates the environment if so * * toRemove distinguishes between whether the pattern is in a stmt predicate and thus doesn't need accumulating as * something to replace, or whether its a normal pattern and does */ class ASTPatternMatcher(toRemove:Boolean) { val log = LoggerFactory getLogger(this getClass) var i = 0 // UTILITY METHODS def next = {i+=1;i} // context creation def c(v:Boolean):Context = c(v,new HashMap()) def c(v:Boolean,vals:MMap[String,Any]):Context = new Context(v,vals,MSet()) // singleton context def one(k:String,v:Any):Context = c(true,HashMap(k->v)) def guard(g:Boolean,context:()=>Context) = { if(g) context() else c(false) } implicit def javaItToScalaIt[X](it:java.util.Iterator[X]) = new Wrapper[X](it) //implicit def javaItToScalaList[X](it:java.util.Iterator[X]):List[X] = List() ++ it implicit def compress[X](ar:Array[X]):Iterator[X] = ar.elements // should only be called in testing protected def unifyAll(src:String,pattern:Stmt):Iterator[Context] = unifyAll(parse(src),pattern) var debugIndent = 0 def tabs() = (0 to debugIndent).foldLeft(new StringBuilder){(acc,_) => acc.append("\t")} toString var wildcards:List[List[IRStmt]] = Nil /** * Accumulate all contexts for a compilation unit * TODO: initializers, constructors, fields */ def unifyAll(cu:CompilationUnit,pattern:Stmt):Iterator[Context] = { wildcards = Nil val pkg = cu.getPackage.getName.toString val acc = cu.types.iterator.flatMap({x => val typeDecl = x.asInstanceOf[TypeDeclaration] val typeName = typeDecl.getName.getFullyQualifiedName.toString typeDecl.getMethods.flatMap({m => val inner = m.getBody.statements (pattern match { case SBlock(patterns) => List(blockIt(inner,patterns)) case _ => inner.iterator.map(s => unifyStmt(s.asInstanceOf[IRStmt],pattern)).toList.filter(_.status) }).map(one("_method",pkg+"."+typeName+"#"+(m.getName.getFullyQualifiedName.toString)) & _) }) }) acc } // Sigh collection conversions def blockIt(stmts:java.util.List[_],pattern:List[Statement]):Context = { val it = stmts.iterator var l = List[IRStmt]() while(it.hasNext) l += it.next.asInstanceOf[IRStmt] block(l,pattern,Nil) } def block(stmts:List[IRStmt],pattern:List[Statement],wildcard:List[IRStmt]):Context = { val res = ((stmts,pattern) match { case (s::ss,Wildcard()::p::ps) => { log debug("Block - Wildcard w Stmt: %s (%d) %s (%d)".format(s.getClass.getName,stmts.size,p,pattern.size)) val attempt = unifyStmt(s,p) log debug ("Attempt.status: {},wildcard = {}",attempt.status,wildcard) if (attempt.status) { wildcards = wildcard :: wildcards log debug ("wildcards now {}", wildcards) attempt && (()=> block(ss,ps,Nil)) } else { block(ss,Wildcard()::p::ps,s::wildcard) } } case (s::ss,p::ps) => { log debug("Block - Stmt w Stmt: %s (%d) %s (%d)".format(s.getClass.getName,stmts.size,p,pattern.size)) unifyStmt(s,p) && (()=>block(ss,ps,Nil)) } case (Nil,Wildcard() :: Nil) => { wildcards = wildcard :: wildcards c(true) } case (Nil,Nil) => { c(true) } case _ => { log debug("Hit Base match in block") c(false) } }) log debug ("Block Res: %s for %d and %d".format(res.status,stmts.size,pattern.size)) res } /** * Big TODO: product with recursive calls, anonymous inner classes * DONE: ExpressionStatement VariableDeclarationStatement IfStatement WhileStatement TryStatement LabeledStatement ReturnStatement ThrowStatement ForStatement EnhancedForStatement Block DoStatement SynchronizedStatement SwitchStatement BreakStatement ContinueStatement AssertStatement ConstructorInvocation SuperConstructorInvocation * TODO: TypeDeclarationStatement * Ignore: EmptyStatement */ def unifyStmt(node:IRStmt,pattern:Stmt):Context = { log debug("Statement: "+node.getClass.getName+" {}",pattern) val con = (node,pattern) match { case (stmt,Label(lbl,statement)) => { log debug ("Label: {}",unifyStmt(stmt,statement).status) unifyStmt(stmt,statement) && (() => one(lbl,stmt)) } case (stmt,Wildcard()) => c(true) case (stmt:EmptyStatement,Skip()) => c(true) // fuzzy matching // wildcard matches many statements case (stmt:Block,SBlock(stmts)) => { // recurse over list, destroying blockIt(stmt.statements,stmts) } // block matching for single statement blocks case (stmt:Block,pat) => { val stmts = stmt.statements guard (stmts.size == 1, () => unifyStmt(stmts.get(0).asInstanceOf[IRStmt],pat)) } case (stmt:ExpressionStatement,SideEffectExpr(expr)) => unifyExpr(stmt.getExpression,expr) case (stmt:VariableDeclarationStatement,Assign(typee,name,to)) => { // TODO: multiple declarations val frag = stmt.fragments.get(0).asInstanceOf[VariableDeclarationFragment] checkType(stmt.getType,typee) && (() => unifyExpr(frag.getInitializer,to) & one(name,frag.getName)) } case (stmt:IfStatement,IfElse(cond,tb,fb)) => { val always = unifyExpr(stmt.getExpression,cond) & unifyStmt(stmt.getThenStatement(),tb) val pat = fb == null val elseStmt = stmt.getElseStatement == null if (pat && elseStmt) always else if (!pat && !elseStmt) always & unifyStmt(stmt.getElseStatement(),fb) else c(false) } case (stmt:WhileStatement,While(cond,body)) => unifyExpr(stmt.getExpression,cond) & unifyStmt(stmt.getBody,body) case (stmt:DoStatement,Do(body,cond)) => unifyExpr(stmt.getExpression,cond) & unifyStmt(stmt.getBody,body) case (stmt:TryStatement,TryCatchFinally(tryB,catchB,finallyB)) => { var always = unifyStmt(stmt.getBody,tryB) & unifyStmt(stmt.getFinally,finallyB) if(stmt.catchClauses.size != catchB.size) c(false) else if (catchB.isEmpty) always else { val javaCatch = stmt.catchClauses.get(0).asInstanceOf[CatchClause] val CatchClauseStmt(name,typee,block) = catchB.head val exp = javaCatch.getException always &= unifyStmt(javaCatch.getBody,block) & one(name,exp.getName) always & c(exp.getType.toString.equals(typee)) // TODO: multiple catch clauses } } case (stmt:LabeledStatement,pat) => unifyStmt(stmt.getBody,pat) case (stmt:ReturnStatement,Return(expr)) => unifyExpr(stmt.getExpression,expr) case (stmt:ThrowStatement,Throw(expr)) => unifyExpr(stmt.getExpression,expr) case (stmt:ForStatement,For(init,cond,up,body)) => unifyExprs(stmt.initializers,init) & unifyExpr(stmt.getExpression,cond) & unifyExprs(stmt.updaters,up) & unifyStmt(stmt.getBody,body) case (stmt:EnhancedForStatement,ForEach(typee,id,expr,body)) => { val param = stmt.getParameter checkType(param.getType,typee) & one(id,param.getName) & unifyExpr(stmt.getExpression,expr) & unifyStmt(stmt.getBody,body) } case (stmt:SynchronizedStatement, Synchronized(body,lock)) => unifyExpr(stmt.getExpression,lock) && (() => unifyStmt(stmt.getBody,body)) case (stmt:SwitchStatement, Switch(stmts,cond)) => unifyExpr(stmt.getExpression,cond) && (() => blockIt(stmt.statements,stmts)) case (stmt:SwitchCase,DefaultCase()) => c(stmt.isDefault) case (stmt:SwitchCase,Switchcase(expr)) => unifyExpr(stmt.getExpression,expr) case (stmt:BreakStatement,Break(mv)) => one(mv,stmt.getLabel) case (stmt:ContinueStatement,Continue(mv)) => one(mv,stmt.getLabel) case (stmt:AssertStatement,Assert(expr)) => unifyExpr(stmt.getExpression,expr) case (stmt:ConstructorInvocation,Constructor(exprs)) => unifyExprs(stmt.arguments,exprs) case (stmt:SuperConstructorInvocation,SuperConstructor(exprs)) => unifyExprs(stmt.arguments,exprs) case _ => c(false) } con.values += "_from" -> node if (toRemove) { log debug ("toRemove on, node = {}",node) con.replaceNodes += node } log.debug ("con.status = {}",con.status) con } /** * * Only matching Metavar: Name IntegerLiteral (includes decimal, hex, and octal forms; and long) FloatingPointLiteral (includes both float and double) CharacterLiteral NullLiteral BooleanLiteral StringLiteral TypeLiteral ThisExpression SuperFieldAccess FieldAccess ArrayAccess * Matched: MethodInvocation ParenthesizedExpression InfixExpression PostfixExpression PrefixExpression CastExpression ClassInstanceCreation InstanceofExpression ArrayInitializer * TODO: ArrayCreation VariableDeclarationExpression ConditionalExpression Assignment SuperMethodInvocation * * NB: arguments, it ignores longer pairs */ def unifyExpr(node:IRExpr,pattern:Expr):Context = { log debug(tabs()+"Expression: "+node.getClass.getName+" {}",pattern) debugIndent += 1 val res = (node,pattern) match { //case (_,Anything()) => c(true) case (expr,Metavar(name)) => one(name,expr) case (expr:MethodInvocation,Method(callOn,name,args)) => { log debug ("e: {}",unifyExpr(expr.getExpression,callOn).status) log debug ("args: {}",unifyExprs(expr.arguments,args).status) log debug ("one: {}",one(name,expr.getName).status) log debug ("all: {}",(unifyExpr(expr.getExpression,callOn) & unifyExprs(expr.arguments,args) & one(name,expr.getName)).status) unifyExpr(expr.getExpression,callOn) & unifyExprs(expr.arguments,args) & one(name,expr.getName) } case (expr:MethodInvocation,NamedMethod(callOn,name,args)) => { log debug ("c: %s %s %s ".format(name.equals(expr.getName.toString),name,expr.getName)) unifyExpr(expr.getExpression,callOn) & unifyExprs(expr.arguments,args) & c(name.equals(expr.getName.toString)) } case (expr:InfixExpression,BinOp(left,right,op)) => guard(op == expr.getOperator,()=>unifyExpr(expr.getLeftOperand,left) & unifyExpr(expr.getRightOperand,right)) case (expr:PostfixExpression,UnOp(inner,op)) => guard(op == expr.getOperator,()=>unifyExpr(expr.getOperand,inner)) case (expr:PrefixExpression,UnOp(inner,op)) => guard(op == expr.getOperator,()=>unifyExpr(expr.getOperand,inner)) case (expr:ParenthesizedExpression,pattern) => unifyExpr(expr.getExpression,pattern) case (expr:CastExpression,Cast(inner,typee)) => checkType(expr.getType,typee) && (()=>unifyExpr(expr.getExpression,inner)) case (expr:ClassInstanceCreation,New(typee,args)) => checkType(expr.getType,typee) && (()=>unifyExprs(expr.arguments,args)) case (expr:InstanceofExpression,InstanceOf(typee,inner)) => checkType(expr.getRightOperand,typee) && (()=>unifyExpr(expr.getLeftOperand,inner)) case (expr:ArrayInitializer,ArrayInit(exprs)) => unifyExprs(expr.expressions,exprs) case (expr:BooleanLiteral,JavaLiteral(value)) => c(value.toBoolean == expr.booleanValue) case (expr:NumberLiteral,JavaLiteral(value)) => c(value.equals(expr.getToken)) case (expr:NullLiteral,JavaLiteral(value)) => c(value.equals("null")) case _ => c(false) } debugIndent -= 1 log debug(tabs()+"Res: {}",res.status) res } def unifyExprs(arguments:java.util.List[_],args:List[Expression]) = { log debug(tabs()+"ExpressionS: "+arguments.size+" {}",args.size) debugIndent += 1 val margs = arguments.asInstanceOf[java.util.List[IRExpr]].iterator.zip(args.elements) val res = margs.map({case (e,p) => unifyExpr(e,p)}).foldLeft(c(true))(_&_) debugIndent -= 1 log debug(tabs()+"Res: {}",res.status) res } /** * TODO: Parameterized Types, Wildcard Types, Qualified Type * @see http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/CastExpression.html */ def checkType(node:Type,pattern:TypePattern):Context = { (node,pattern) match { case (t:PrimitiveType,PrimType(name)) => c(name == t.getPrimitiveTypeCode.toString) case (t:SimpleType,SimpType(name)) => c(name == t.getName) case (t:ArrayType,ArraType(typee)) => checkType(t.getComponentType,typee) case (t,TypeMetavar(name)) => one(name,t) case _ => c(false) } } } /** * Immutable Context Object * Note: wraps mutable map for simplicity */ class Context(st:Boolean,vals:MMap[String,Any],replace:MSet[ASTNode]) extends Cloneable[Context] with Function1[String, Any] { val log = LoggerFactory getLogger(this getClass) val values = vals val status = st val replaceNodes = replace def apply(name:String) = values(name) /** * NB: lazily creates other context * TODO: figure out if this makes complete sense - should it be set based? */ def ||(other:(()=>Context)):Context = { if(status) clone.asInstanceOf[Context] else other() } /** * Requires both status to be true */ def &(other:Context):Context = { var status = this.status && other.status log debug ("& comparison: %s, %s, %s".format(status,values,other.values)) if (status) { val k = ((Set() ++ values.keys) ** (Set() ++ other.values.keys)) - "_from" status &= k.map(k => { val eq = values(k).toString.equals(other.values(k).toString) if (!eq) log debug ("& fail on key %s for %s and %s".format(k,values(k),other.values(k))) eq }).foldLeft(true)(_&&_) } new Context(status,values ++ other.values,replaceNodes ++ other.replaceNodes) } def &&(other:()=>Context):Context = if(this.status) this & other() else this def add(arg:(String,ASTNode)):Context = { val (metavar,node) = arg val old = values(metavar) if(old != node) new Context(false,values,replaceNodes) else new Context(true,values + (metavar -> node),replaceNodes) } override def toString = { "C(status = {%s}, values = {%s})".format(status,values) } }
lgpl-3.0
pcolby/libqtaws
src/ssm/describeavailablepatchesrequest.cpp
5380
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "describeavailablepatchesrequest.h" #include "describeavailablepatchesrequest_p.h" #include "describeavailablepatchesresponse.h" #include "ssmrequest_p.h" namespace QtAws { namespace SSM { /*! * \class QtAws::SSM::DescribeAvailablePatchesRequest * \brief The DescribeAvailablePatchesRequest class provides an interface for SSM DescribeAvailablePatches requests. * * \inmodule QtAwsSSM * * <fullname>AWS Systems Manager</fullname> * * AWS Systems Manager is a collection of capabilities that helps you automate management tasks such as collecting system * inventory, applying operating system (OS) patches, automating the creation of Amazon Machine Images (AMIs), and * configuring operating systems (OSs) and applications at scale. Systems Manager lets you remotely and securely manage the * configuration of your managed instances. A <i>managed instance</i> is any Amazon Elastic Compute Cloud instance (EC2 * instance), or any on-premises server or virtual machine (VM) in your hybrid environment that has been configured for * Systems * * Manager> * * This reference is intended to be used with the <a * href="https://docs.aws.amazon.com/systems-manager/latest/userguide/">AWS Systems Manager User * * Guide</a>> * * To get started, verify prerequisites and configure managed instances. For more information, see <a * href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up.html">Setting up AWS * Systems Manager</a> in the <i>AWS Systems Manager User * * Guide</i>> <p class="title"> <b>Related resources</b> * * </p <ul> <li> * * For information about how to use a Query API, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/making-api-requests.html">Making API requests</a>. * * </p </li> <li> * * For information about other API actions you can perform on EC2 instances, see the <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/">Amazon EC2 API * * Reference</a>> </li> <li> * * For information about AWS AppConfig, a capability of Systems Manager, see the <a * href="https://docs.aws.amazon.com/appconfig/latest/userguide/">AWS AppConfig User Guide</a> and the <a * href="https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/">AWS AppConfig API * * Reference</a>> </li> <li> * * For information about AWS Incident Manager, a capability of Systems Manager, see the <a * href="https://docs.aws.amazon.com/incident-manager/latest/userguide/">AWS Incident Manager User Guide</a> and the <a * href="https://docs.aws.amazon.com/incident-manager/latest/APIReference/">AWS Incident Manager API * * \sa SsmClient::describeAvailablePatches */ /*! * Constructs a copy of \a other. */ DescribeAvailablePatchesRequest::DescribeAvailablePatchesRequest(const DescribeAvailablePatchesRequest &other) : SsmRequest(new DescribeAvailablePatchesRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a DescribeAvailablePatchesRequest object. */ DescribeAvailablePatchesRequest::DescribeAvailablePatchesRequest() : SsmRequest(new DescribeAvailablePatchesRequestPrivate(SsmRequest::DescribeAvailablePatchesAction, this)) { } /*! * \reimp */ bool DescribeAvailablePatchesRequest::isValid() const { return false; } /*! * Returns a DescribeAvailablePatchesResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * DescribeAvailablePatchesRequest::response(QNetworkReply * const reply) const { return new DescribeAvailablePatchesResponse(*this, reply); } /*! * \class QtAws::SSM::DescribeAvailablePatchesRequestPrivate * \brief The DescribeAvailablePatchesRequestPrivate class provides private implementation for DescribeAvailablePatchesRequest. * \internal * * \inmodule QtAwsSSM */ /*! * Constructs a DescribeAvailablePatchesRequestPrivate object for Ssm \a action, * with public implementation \a q. */ DescribeAvailablePatchesRequestPrivate::DescribeAvailablePatchesRequestPrivate( const SsmRequest::Action action, DescribeAvailablePatchesRequest * const q) : SsmRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the DescribeAvailablePatchesRequest * class' copy constructor. */ DescribeAvailablePatchesRequestPrivate::DescribeAvailablePatchesRequestPrivate( const DescribeAvailablePatchesRequestPrivate &other, DescribeAvailablePatchesRequest * const q) : SsmRequestPrivate(other, q) { } } // namespace SSM } // namespace QtAws
lgpl-3.0
Redpill-Linpro/alfresco-user-migration-admintool
share/src/main/resources/alfresco/site-webscripts/org/redpill_linpro/components/console/usersgroups/replace-user.get.js
169
function main() { // Widget instantiation metadata... var widget = { id : "ReplaceUser", name : "RPL.ReplaceUser" }; model.widgets = [widget]; } main();
lgpl-3.0
impetus-opensource/jumbune
web/src/main/java/org/jumbune/web/process/SystemMetricsProcess.java
2897
package org.jumbune.web.process; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jumbune.common.beans.cluster.Cluster; import com.google.gson.Gson; import org.jumbune.common.beans.cluster.ClusterDefinition; import org.jumbune.web.services.ClusterAnalysisService; import org.jumbune.web.utils.StatsManager; /** * It calls StatsManager write() method at regular interval. Affected section is * [Analyze Cluster Dashboard -> Hadoop Metrics and System Stats] in UI */ public class SystemMetricsProcess extends Thread implements BackgroundProcess { private String clusterName; private boolean isOn; private long repeatInterval; private int maxErrors; private int totalErrors; private StatsManager statsManager; private static Logger LOGGER = LogManager.getLogger(SystemMetricsProcess.class); public SystemMetricsProcess(String clusterName, long repeatInterval, int maxErrors) { this.clusterName = clusterName; this.repeatInterval = repeatInterval; this.maxErrors = maxErrors; this.totalErrors = 0; this.statsManager = StatsManager.getInstance(); this.isOn = true; try { this.statsManager.startBackgroundProcess(getCluster(clusterName)); } catch (Exception e) { this.isOn = false; LOGGER.error("Unable to start cluster metrics process of cluster '" + clusterName, e); } } public Cluster getCluster(String clusterName) throws IOException { ClusterDefinition cluster = ClusterAnalysisService.cache.getCluster(clusterName); if (cluster == null) { File file = new File(System.getenv("JUMBUNE_HOME") + "/clusters/" + clusterName + ".json"); StringBuffer json = new StringBuffer(); BufferedReader br = null; try { String line; br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { json.append(line); } } finally { if (br != null) { br.close(); } } cluster = new Gson().fromJson(json.toString(), ClusterDefinition.class); ClusterAnalysisService.updateClusterCache(clusterName, cluster); } return cluster; } public boolean isOn() { return isOn; } public void setOn(boolean isOn) { this.isOn = isOn; if (!this.isOn) { try { this.statsManager.stopBackgroundProcess(getCluster(clusterName)); } catch (Exception e) { LOGGER.error("Unable to stop cluster metrics process of cluster '" + this.clusterName, e); } } } @Override public void run() { while (isOn) { if (totalErrors > maxErrors) { isOn = false; } this.statsManager.write(); try { Thread.sleep(repeatInterval); } catch (InterruptedException e) { LOGGER.error("Unable to sleep the ClusterMetricsProcess, cluster [" + clusterName + "]", e.getMessage()); return; } } } }
lgpl-3.0
Godin/sonar
server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v67/CreateTableAnalysisProperties.java
3333
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.db.migration.version.v67; import java.sql.SQLException; import org.sonar.db.Database; import org.sonar.server.platform.db.migration.def.BigIntegerColumnDef; import org.sonar.server.platform.db.migration.def.BooleanColumnDef; import org.sonar.server.platform.db.migration.def.ClobColumnDef; import org.sonar.server.platform.db.migration.def.VarcharColumnDef; import org.sonar.server.platform.db.migration.sql.CreateIndexBuilder; import org.sonar.server.platform.db.migration.sql.CreateTableBuilder; import org.sonar.server.platform.db.migration.step.DdlChange; public class CreateTableAnalysisProperties extends DdlChange { private static final String TABLE_NAME = "analysis_properties"; private static final String SNAPSHOT_UUID = "snapshot_uuid"; private static final VarcharColumnDef SNAPSHOT_UUID_COLUMN = VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName(SNAPSHOT_UUID) .setIsNullable(false) .setLimit(VarcharColumnDef.UUID_SIZE) .build(); public CreateTableAnalysisProperties(Database db) { super(db); } @Override public void execute(Context context) throws SQLException { context.execute(new CreateTableBuilder(getDialect(), TABLE_NAME) .addPkColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("uuid") .setIsNullable(false) .setLimit(VarcharColumnDef.UUID_SIZE) .build()) .addColumn(SNAPSHOT_UUID_COLUMN) .addColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("kee") .setIsNullable(false) .setLimit(512) .build()) .addColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("text_value") .setIsNullable(true) .setLimit(VarcharColumnDef.MAX_SIZE) .build()) .addColumn(ClobColumnDef.newClobColumnDefBuilder() .setColumnName("clob_value") .setIsNullable(true) .build()) .addColumn(BooleanColumnDef.newBooleanColumnDefBuilder() .setColumnName("is_empty") .setIsNullable(false) .build()) .addColumn(BigIntegerColumnDef.newBigIntegerColumnDefBuilder() .setColumnName("created_at") .setIsNullable(false) .build()) .build() ); context.execute(new CreateIndexBuilder(getDialect()) .addColumn(SNAPSHOT_UUID_COLUMN) .setUnique(false) .setTable(TABLE_NAME) .setName("ix_snapshot_uuid") .build() ); } }
lgpl-3.0
kappamodeler/jkappa
src/test/acceptance/com/plectix/simulator/events/TestEvents.java
2788
package com.plectix.simulator.events; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Collection; import org.apache.commons.cli.ParseException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.plectix.simulator.FileNameCollectionGenerator; import com.plectix.simulator.Initializator; import com.plectix.simulator.OperationModeCollectionGenerator; import com.plectix.simulator.controller.SimulatorInputData; import com.plectix.simulator.io.SimulationDataReader; import com.plectix.simulator.simulator.SimulationArguments; import com.plectix.simulator.simulator.SimulationData; import com.plectix.simulator.simulator.Simulator; import com.plectix.simulator.util.Info.InfoType; @RunWith(value = Parameterized.class) public final class TestEvents { private static final String SEPARATOR = File.separator; private static final String TEST_DIRECTORY = "test.data" + SEPARATOR + "events" + SEPARATOR; private final String prefixFileName; private Simulator simulator; private final Integer[] eventsNumbers = { 0, 1, 10, 100, 500, 1000, 1001, 1002 }; private final Integer operationMode; @Parameters public static Collection<Object[]> data() { Collection<Object[]> allFileNames = FileNameCollectionGenerator .getAllFileNames(TEST_DIRECTORY); return OperationModeCollectionGenerator.generate(allFileNames,true); } public TestEvents(String filename, Integer opMode) { prefixFileName = filename; operationMode = opMode; } @Test public void test() throws Exception { for (int i = 0; i < eventsNumbers.length; i++) { setup(eventsNumbers[i]); assertTrue(eventsNumbers[i] == simulator.getSimulationData() .getSimulationArguments().getMaxNumberOfEvents()); } } public void setup(Integer eventNumber) throws Exception { init(TEST_DIRECTORY + prefixFileName, eventNumber); try { simulator.run(new SimulatorInputData(simulator.getSimulationData() .getSimulationArguments())); } catch (Exception e) { e.printStackTrace(); junit.framework.Assert.fail(e.getMessage()); } } public void init(String filePath, Integer eventNumber) throws Exception { simulator = null; simulator = new Simulator(); SimulationData simulationData = simulator.getSimulationData(); SimulationArguments args = null; try { args = Initializator.prepareEventNumberArguments(filePath, eventNumber, operationMode); } catch (ParseException e) { e.printStackTrace(); throw new IllegalArgumentException(e); } simulationData.setSimulationArguments(InfoType.OUTPUT, args); (new SimulationDataReader(simulationData)).readAndCompile(); simulationData.getKappaSystem().initialize(); } }
lgpl-3.0
horazont/aioxmpp
examples/list_presence.py
2996
######################################################################## # File name: list_presence.py # This file is part of: aioxmpp # # LICENSE # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program. If not, see # <http://www.gnu.org/licenses/>. # ######################################################################## import asyncio from datetime import timedelta import aioxmpp.presence from framework import Example, exec_example class PresenceCollector: def __init__(self, done_timeout=timedelta(seconds=1)): self.presences = [] self.done_future = asyncio.Future() self.done_timeout = done_timeout self._reset_timer() def _reset_timer(self): self._done_task = asyncio.ensure_future( asyncio.sleep(self.done_timeout.total_seconds()) ) self._done_task.add_done_callback(self._sleep_done) def _sleep_done(self, task): try: task.result() except asyncio.CancelledError: return self.done_future.set_result(self.presences) def add_presence(self, pres): self.presences.append(pres) self._done_task.cancel() self._reset_timer() class ListPresence(Example): def make_simple_client(self): client = super().make_simple_client() self.collector = PresenceCollector() client.stream.register_presence_callback( aioxmpp.PresenceType.AVAILABLE, None, self.collector.add_presence, ) client.stream.register_presence_callback( aioxmpp.PresenceType.UNAVAILABLE, None, self.collector.add_presence, ) return client async def run_simple_example(self): print("collecting presences... ") self.presences = await self.collector.done_future async def run_example(self): await super().run_example() print("found presences:") for i, pres in enumerate(self.presences): print("presence {}".format(i)) print(" peer: {}".format(pres.from_)) print(" type: {}".format(pres.type_)) print(" show: {}".format(pres.show)) print(" status: ") for lang, text in pres.status.items(): print(" (lang={}) {!r}".format( lang, text)) if __name__ == "__main__": exec_example(ListPresence())
lgpl-3.0
advanced-online-marketing/AOM
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201802/SuggestedAdUnitAction.php
204
<?php namespace Google\AdsApi\Dfp\v201802; /** * This file was generated from WSDL. DO NOT EDIT. */ abstract class SuggestedAdUnitAction { public function __construct() { } }
lgpl-3.0
Alfresco/alfresco-repository
src/test/java/org/alfresco/repo/rule/RuleServiceCoverageTest.java
93296
/* * #%L * Alfresco Repository * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.rule; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.transaction.UserTransaction; import junit.framework.TestCase; import org.alfresco.model.ApplicationModel; import org.alfresco.model.ContentModel; import org.alfresco.repo.action.ActionServiceImplTest; import org.alfresco.repo.action.ActionServiceImplTest.AsyncTest; import org.alfresco.repo.action.evaluator.ComparePropertyValueEvaluator; import org.alfresco.repo.action.evaluator.InCategoryEvaluator; import org.alfresco.repo.action.evaluator.NoConditionEvaluator; import org.alfresco.repo.action.executer.AddFeaturesActionExecuter; import org.alfresco.repo.action.executer.CheckInActionExecuter; import org.alfresco.repo.action.executer.CheckOutActionExecuter; import org.alfresco.repo.action.executer.CopyActionExecuter; import org.alfresco.repo.action.executer.ImageTransformActionExecuter; import org.alfresco.repo.action.executer.LinkCategoryActionExecuter; import org.alfresco.repo.action.executer.MailActionExecuter; import org.alfresco.repo.action.executer.MoveActionExecuter; import org.alfresco.repo.action.executer.SimpleWorkflowActionExecuter; import org.alfresco.repo.action.executer.TransformActionExecuter; import org.alfresco.repo.content.MimetypeMap; import org.alfresco.repo.content.transform.AbstractContentTransformerTest; import org.alfresco.repo.dictionary.DictionaryDAO; import org.alfresco.repo.dictionary.IndexTokenisationMode; import org.alfresco.repo.dictionary.M2Aspect; import org.alfresco.repo.dictionary.M2Model; import org.alfresco.repo.dictionary.M2Property; import org.alfresco.repo.management.subsystems.ApplicationContextFactory; import org.alfresco.repo.node.integrity.IntegrityException; import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.action.Action; import org.alfresco.service.cmr.action.ActionCondition; import org.alfresco.service.cmr.action.ActionService; import org.alfresco.service.cmr.coci.CheckOutCheckInService; import org.alfresco.service.cmr.dictionary.DataTypeDefinition; import org.alfresco.service.cmr.dictionary.PropertyDefinition; import org.alfresco.service.cmr.lock.LockService; import org.alfresco.service.cmr.lock.LockStatus; import org.alfresco.service.cmr.model.FileFolderService; import org.alfresco.service.cmr.model.FileInfo; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.ContentData; import org.alfresco.service.cmr.repository.ContentService; import org.alfresco.service.cmr.repository.ContentWriter; import org.alfresco.service.cmr.repository.CopyService; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.rule.Rule; import org.alfresco.service.cmr.rule.RuleService; import org.alfresco.service.cmr.rule.RuleServiceException; import org.alfresco.service.cmr.rule.RuleType; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.RegexQNamePattern; import org.alfresco.service.transaction.TransactionService; import org.alfresco.test_category.OwnJVMTestsCategory; import org.alfresco.util.ApplicationContextHelper; import org.junit.experimental.categories.Category; import org.springframework.context.ApplicationContext; import org.springframework.util.StopWatch; /** * @author Roy Wetherall */ @Category(OwnJVMTestsCategory.class) public class RuleServiceCoverageTest extends TestCase { /** * Application context used during the test */ static ApplicationContext applicationContext = ApplicationContextHelper.getApplicationContext(); /** * Services used during the tests */ private TransactionService transactionService; private RuleService ruleService; private NodeService nodeService; private StoreRef testStoreRef; private NodeRef rootNodeRef; private NodeRef nodeRef; private CheckOutCheckInService cociService; private LockService lockService; private ContentService contentService; private ServiceRegistry serviceRegistry; private DictionaryDAO dictionaryDAO; private ActionService actionService; private CopyService copyService; private AuthenticationComponent authenticationComponent; private FileFolderService fileFolderService; /** * Category related values */ private static final String TEST_NAMESPACE = "http://www.alfresco.org/test/rulesystemtest"; private static final QName CAT_PROP_QNAME = QName.createQName(TEST_NAMESPACE, "region"); private QName regionCategorisationQName; private NodeRef catContainer; private NodeRef catRoot; private NodeRef catRBase; private NodeRef catROne; private NodeRef catRTwo; @SuppressWarnings("unused") private NodeRef catRThree; /** * Standard content text */ private static final String STANDARD_TEXT_CONTENT = "standardTextContent"; /** * Setup method */ @Override protected void setUp() throws Exception { // Get the required services this.serviceRegistry = (ServiceRegistry)applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); this.nodeService = serviceRegistry.getNodeService(); this.ruleService = serviceRegistry.getRuleService(); this.cociService = serviceRegistry.getCheckOutCheckInService(); this.lockService = serviceRegistry.getLockService(); this.copyService = serviceRegistry.getCopyService(); this.contentService = serviceRegistry.getContentService(); this.dictionaryDAO = (DictionaryDAO)applicationContext.getBean("dictionaryDAO"); this.actionService = serviceRegistry.getActionService(); this.transactionService = serviceRegistry.getTransactionService(); this.authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent"); this.fileFolderService = serviceRegistry.getFileFolderService(); //authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName()); //authenticationComponent.setSystemUserAsCurrentUser(); RetryingTransactionCallback<Object> setUserCallback = new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName()); return null; } }; transactionService.getRetryingTransactionHelper().doInTransaction(setUserCallback); this.testStoreRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis()); this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef); // Create the node used for tests this.nodeRef = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_CONTAINER).getChildRef(); } private Rule createRule( String ruleTypeName, String actionName, Map<String, Serializable> actionParams, String conditionName, Map<String, Serializable> conditionParams) { Rule rule = new Rule(); rule.setRuleType(ruleTypeName); Action action = this.actionService.createAction(actionName, actionParams); ActionCondition condition = this.actionService.createActionCondition(conditionName, conditionParams); action.addActionCondition(condition); rule.setAction(action); return rule; } /** * Create the categories used in the tests */ private void createTestCategories() { // Create the test model M2Model model = M2Model.createModel("test:rulecategory"); model.createNamespace(TEST_NAMESPACE, "test"); model.createImport(NamespaceService.DICTIONARY_MODEL_1_0_URI, "d"); model.createImport(NamespaceService.CONTENT_MODEL_1_0_URI, NamespaceService.CONTENT_MODEL_PREFIX); // Create the region category regionCategorisationQName = QName.createQName(TEST_NAMESPACE, "region"); M2Aspect generalCategorisation = model.createAspect("test:" + regionCategorisationQName.getLocalName()); generalCategorisation.setParentName("cm:" + ContentModel.ASPECT_CLASSIFIABLE.getLocalName()); M2Property genCatProp = generalCategorisation.createProperty("test:region"); genCatProp.setIndexed(true); genCatProp.setIndexedAtomically(true); genCatProp.setMandatory(true); genCatProp.setMultiValued(true); genCatProp.setStoredInIndex(true); genCatProp.setIndexTokenisationMode(IndexTokenisationMode.TRUE); genCatProp.setType("d:" + DataTypeDefinition.CATEGORY.getLocalName()); // Save the mode dictionaryDAO.putModel(model); // Create the category value container and root catContainer = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "categoryContainer"), ContentModel.TYPE_CONTAINER).getChildRef(); catRoot = nodeService.createNode(catContainer, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "categoryRoot"), ContentModel.TYPE_CATEGORYROOT).getChildRef(); // Create the category values catRBase = nodeService.createNode(catRoot, ContentModel.ASSOC_CATEGORIES, QName.createQName(TEST_NAMESPACE, "region"), ContentModel.TYPE_CATEGORY).getChildRef(); catROne = nodeService.createNode(catRBase, ContentModel.ASSOC_SUBCATEGORIES, QName.createQName(TEST_NAMESPACE, "Europe"), ContentModel.TYPE_CATEGORY).getChildRef(); catRTwo = nodeService.createNode(catRBase, ContentModel.ASSOC_SUBCATEGORIES, QName.createQName(TEST_NAMESPACE, "RestOfWorld"), ContentModel.TYPE_CATEGORY).getChildRef(); catRThree = nodeService.createNode(catRTwo, ContentModel.ASSOC_SUBCATEGORIES, QName.createQName(TEST_NAMESPACE, "US"), ContentModel.TYPE_CATEGORY).getChildRef(); } /** * Asynchronous rule tests */ /** * Check async rule execution */ public void testAsyncRuleExecution() { final NodeRef newNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction( new RetryingTransactionCallback<NodeRef>() { public NodeRef execute() { RuleServiceCoverageTest.this.nodeService.addAspect( RuleServiceCoverageTest.this.nodeRef, ContentModel.ASPECT_LOCKABLE, null); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); rule.setExecuteAsynchronously(true); RuleServiceCoverageTest.this.ruleService.saveRule(RuleServiceCoverageTest.this.nodeRef, rule); NodeRef newNodeRef = RuleServiceCoverageTest.this.nodeService.createNode( RuleServiceCoverageTest.this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); return newNodeRef; } }); ActionServiceImplTest.postAsyncActionTest( this.transactionService, 5000, 12, new AsyncTest() { public String executeTest() { boolean result = RuleServiceCoverageTest.this.nodeService.hasAspect( newNodeRef, ContentModel.ASPECT_VERSIONABLE); return result ? null : "Expected aspect Versionable"; }; }); } // TODO check compensating action execution /** * Standard rule coverage tests */ /** * Test: * rule type: inbound * condition: no-condition() * action: add-features( * aspect-name = versionable) */ public void testAddFeaturesAction() { this.nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); assertTrue(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); Map<String, Serializable> params2 = new HashMap<String, Serializable>(2); params2.put(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ApplicationModel.ASPECT_SIMPLE_WORKFLOW); params2.put(ApplicationModel.PROP_APPROVE_STEP.toString(), "approveStep"); params2.put(ApplicationModel.PROP_APPROVE_MOVE.toString(), false); // Test that rule can be updated and execute correctly //rule.removeAllActions(); Action action2 = this.actionService.createAction(AddFeaturesActionExecuter.NAME, params2); rule.setAction(action2); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef2); assertTrue(this.nodeService.hasAspect(newNodeRef2, ApplicationModel.ASPECT_SIMPLE_WORKFLOW)); assertEquals("approveStep", this.nodeService.getProperty(newNodeRef2, ApplicationModel.PROP_APPROVE_STEP)); assertEquals(false, this.nodeService.getProperty(newNodeRef2, ApplicationModel.PROP_APPROVE_MOVE)); // System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); } public void testCheckThatModifyNameDoesNotTriggerInboundRule() throws Exception { //this.nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null); Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(1); folderProps.put(ContentModel.PROP_NAME, "myTestFolder"); NodeRef folder = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_FOLDER, folderProps).getChildRef(); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(folder, rule); Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(1); contentProps.put(ContentModel.PROP_NAME, "myTestDocument.txt"); NodeRef newNodeRef = this.nodeService.createNode( folder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "myTestDocument.txt"), ContentModel.TYPE_CONTENT, contentProps).getChildRef(); //addContentToNode(newNodeRef); nodeService.removeAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE); assertFalse(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Use the file folder to change the name of the node this.fileFolderService.rename(newNodeRef, "myNewName.txt"); assertFalse(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); } public void testCheckThatModifyNameDoesNotTriggerOutboundRule() throws Exception { Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(1); folderProps.put(ContentModel.PROP_NAME, "myTestFolder"); NodeRef folder = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_FOLDER, folderProps).getChildRef(); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.OUTBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(folder, rule); Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(1); contentProps.put(ContentModel.PROP_NAME, "myTestDocument.txt"); NodeRef newNodeRef = fileFolderService.create(folder, "abc.txt", ContentModel.TYPE_CONTENT).getNodeRef(); assertFalse("Should not be versionable", nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Use the file folder to change the name of the node fileFolderService.rename(newNodeRef, "myNewName.txt"); assertFalse("Should not be versionable", nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); } public void testCheckThatChildRuleFiresOnMove() throws Exception { //ALF-9415 test Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(1); folderProps.put(ContentModel.PROP_NAME, "myTestFolder"); NodeRef folder = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_FOLDER, folderProps).getChildRef(); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); rule.applyToChildren(true); this.ruleService.saveRule(folder, rule); folderProps.put(ContentModel.PROP_NAME, "myMoveFolder"); NodeRef folderForMove = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_FOLDER, folderProps).getChildRef(); NodeRef testFile = this.fileFolderService.create(folderForMove, "testFile.txt", ContentModel.TYPE_CONTENT).getNodeRef(); this.fileFolderService.move(folderForMove, folder, null); assertTrue("Should be versionable", nodeService.hasAspect(testFile, ContentModel.ASPECT_VERSIONABLE)); } /** * ALF-4926: Incorrect behavior of update and move rule for the same folder * <p/> * Two rules:<br/><ul> * <li>When items are deleted, copy to another folder.</li> * <li>In addition, when items are updated, add an aspect (or any other rule).</li></ul> * Ensure that the first copy does not result in rules being fired on the target. */ public void testUpdateAndMoveRuleOnSameFolder() throws Exception { NodeRef sourceFolder = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}sourceFolder"), ContentModel.TYPE_FOLDER).getChildRef(); NodeRef targetFolder = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}targetFolder"), ContentModel.TYPE_FOLDER).getChildRef(); // Create UPDATE rule to add lockable aspect Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_LOCKABLE); Rule rule = createRule( RuleType.UPDATE, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(sourceFolder, rule); // Check that the UPDATE rule works NodeRef testNodeOneRef = fileFolderService.create(sourceFolder, "one.txt", ContentModel.TYPE_CONTENT).getNodeRef(); assertFalse( "Node should not have lockable aspect", nodeService.hasAspect(testNodeOneRef, ContentModel.ASPECT_LOCKABLE)); nodeService.setProperty(testNodeOneRef, ContentModel.PROP_LOCALE, Locale.CANADA); assertTrue( "Node should have lockable aspect", nodeService.hasAspect(testNodeOneRef, ContentModel.ASPECT_LOCKABLE)); fileFolderService.delete(testNodeOneRef); // Create OUTBOUND rule to copy node being deleted params = new HashMap<String, Serializable>(1); params.put(CopyActionExecuter.PARAM_DESTINATION_FOLDER, targetFolder); Rule copyRule = createRule( RuleType.OUTBOUND, CopyActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); copyRule.applyToChildren(true); this.ruleService.saveRule(sourceFolder, copyRule); // Check that this OUTBOUND rule works NodeRef testNodeTwoRef = fileFolderService.create(sourceFolder, "two.txt", ContentModel.TYPE_CONTENT).getNodeRef(); assertFalse( "Node should not have lockable aspect", nodeService.hasAspect(testNodeTwoRef, ContentModel.ASPECT_LOCKABLE)); fileFolderService.delete(testNodeTwoRef); assertFalse("Node was not deleted", fileFolderService.exists(testNodeTwoRef)); assertEquals( "There should not be any children in source folder", 0, fileFolderService.listFiles(sourceFolder).size()); List<FileInfo> targetFolderFileList = fileFolderService.listFiles(targetFolder); assertEquals( "Node should have been copied to target folder", 1, targetFolderFileList.size()); assertFalse( "The node copy should not be lockable", nodeService.hasAspect(targetFolderFileList.get(0).getNodeRef(), ContentModel.ASPECT_LOCKABLE)); } public void testDisableIndividualRules() { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ApplicationModel.ASPECT_CONFIGURABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); rule.setRuleDisabled(true); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); assertFalse(this.nodeService.hasAspect(newNodeRef, ApplicationModel.ASPECT_CONFIGURABLE)); Rule rule2 = this.ruleService.getRule(rule.getNodeRef()); rule2.setRuleDisabled(false); this.ruleService.saveRule(this.nodeRef, rule2); // Re-try the test now the rule has been re-enabled NodeRef newNodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef2); assertTrue(this.nodeService.hasAspect(newNodeRef2, ApplicationModel.ASPECT_CONFIGURABLE)); } public void testDisableRule() { this.nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); this.ruleService.disableRule(rule); NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); assertFalse(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); this.ruleService.enableRule(rule); NodeRef newNodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef2); assertTrue(this.nodeService.hasAspect(newNodeRef2, ContentModel.ASPECT_VERSIONABLE)); } public void testAddFeaturesToAFolder() { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_TEMPLATABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_FOLDER).getChildRef(); assertTrue(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_TEMPLATABLE)); // System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); } public void testCopyFolderToTriggerRules() { // Create the folders and content NodeRef copyToFolder = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}copyToFolder"), ContentModel.TYPE_FOLDER).getChildRef(); NodeRef folderToCopy = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}folderToCopy"), ContentModel.TYPE_FOLDER).getChildRef(); NodeRef contentToCopy = this.nodeService.createNode( folderToCopy, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}contentToCopy"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(contentToCopy); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_TEMPLATABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); rule.applyToChildren(true); this.ruleService.saveRule(copyToFolder, rule); // Copy the folder in order to try and trigger the rule NodeRef copiedFolder = this.copyService.copy(folderToCopy, copyToFolder, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}coppiedFolder"), true); assertNotNull(copiedFolder); // Check that the rule has been applied to the copied folder and content assertTrue(this.nodeService.hasAspect(copiedFolder, ContentModel.ASPECT_TEMPLATABLE)); for (ChildAssociationRef childAssoc : this.nodeService.getChildAssocs(copiedFolder)) { assertTrue(this.nodeService.hasAspect(childAssoc.getChildRef(), ContentModel.ASPECT_TEMPLATABLE)); } //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); } private Map<QName, Serializable> getContentProperties() { // Map<QName, Serializable> properties = new HashMap<QName, Serializable>(1); // properties.put(ContentModel.PROP_CONTENT, CONTENT_DATA_TEXT); return null; } /** * Test: * rule type: inbound * condition: no-condition * action: simple-workflow */ public void testSimpleWorkflowAction() { this.nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(SimpleWorkflowActionExecuter.PARAM_APPROVE_STEP, "approveStep"); params.put(SimpleWorkflowActionExecuter.PARAM_APPROVE_FOLDER, this.rootNodeRef); params.put(SimpleWorkflowActionExecuter.PARAM_APPROVE_MOVE, true); params.put(SimpleWorkflowActionExecuter.PARAM_REJECT_STEP, "rejectStep"); params.put(SimpleWorkflowActionExecuter.PARAM_REJECT_FOLDER, this.rootNodeRef); params.put(SimpleWorkflowActionExecuter.PARAM_REJECT_MOVE, false); Rule rule = createRule( RuleType.INBOUND, SimpleWorkflowActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); assertTrue(this.nodeService.hasAspect(newNodeRef, ApplicationModel.ASPECT_SIMPLE_WORKFLOW)); assertEquals("approveStep", this.nodeService.getProperty(newNodeRef, ApplicationModel.PROP_APPROVE_STEP)); assertEquals(this.rootNodeRef, this.nodeService.getProperty(newNodeRef, ApplicationModel.PROP_APPROVE_FOLDER)); assertTrue(((Boolean)this.nodeService.getProperty(newNodeRef, ApplicationModel.PROP_APPROVE_MOVE)).booleanValue()); assertTrue(this.nodeService.hasAspect(newNodeRef, ApplicationModel.ASPECT_SIMPLE_WORKFLOW)); assertEquals("rejectStep", this.nodeService.getProperty(newNodeRef, ApplicationModel.PROP_REJECT_STEP)); assertEquals(this.rootNodeRef, this.nodeService.getProperty(newNodeRef, ApplicationModel.PROP_REJECT_FOLDER)); assertFalse(((Boolean)this.nodeService.getProperty(newNodeRef, ApplicationModel.PROP_REJECT_MOVE)).booleanValue()); // System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); } /** * Test: * rule type: inbound * condition: in-category * action: add-feature */ public void testInCategoryCondition() { // Create categories used in tests createTestCategories(); try { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(InCategoryEvaluator.PARAM_CATEGORY_ASPECT, this.regionCategorisationQName); params.put(InCategoryEvaluator.PARAM_CATEGORY_VALUE, this.catROne); Map<String, Serializable> params2 = new HashMap<String, Serializable>(1); params2.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params2, InCategoryEvaluator.NAME, params); this.ruleService.saveRule(this.nodeRef, rule); // Check rule does not get fired when a node without the aspect is added NodeRef newNodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "noAspect"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef2); assertFalse(this.nodeService.hasAspect(newNodeRef2, ContentModel.ASPECT_VERSIONABLE)); // Check rule gets fired when node contains category value RetryingTransactionCallback<NodeRef> callback1 = new RetryingTransactionCallback<NodeRef>() { public NodeRef execute() throws Throwable { NodeRef newNodeRef = nodeService.createNode( nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "hasAspectAndValue"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); Map<QName, Serializable> catProps = new HashMap<QName, Serializable>(); catProps.put(CAT_PROP_QNAME, catROne); nodeService.addAspect(newNodeRef, regionCategorisationQName, catProps); return newNodeRef; } }; NodeRef newNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(callback1); assertTrue(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Check rule does not get fired when the node has the incorrect category value RetryingTransactionCallback<NodeRef> callback3 = new RetryingTransactionCallback<NodeRef>() { public NodeRef execute() throws Throwable { NodeRef newNodeRef3 = nodeService.createNode( nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "hasAspectAndValue"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef3); Map<QName, Serializable> catProps3 = new HashMap<QName, Serializable>(); catProps3.put(CAT_PROP_QNAME, catRTwo); nodeService.addAspect(newNodeRef3, regionCategorisationQName, catProps3); return newNodeRef3; } }; NodeRef newNodeRef3 = transactionService.getRetryingTransactionHelper().doInTransaction(callback3); assertFalse(this.nodeService.hasAspect(newNodeRef3, ContentModel.ASPECT_VERSIONABLE)); //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); } catch (Exception exception) { throw new RuntimeException(exception); } } /** * Test: * rule type: inbound * condition: no-condition * action: link-category */ @SuppressWarnings("unchecked") public void testLinkCategoryAction() { // Create categories used in tests createTestCategories(); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(LinkCategoryActionExecuter.PARAM_CATEGORY_ASPECT, this.regionCategorisationQName); params.put(LinkCategoryActionExecuter.PARAM_CATEGORY_VALUE, this.catROne); Rule rule = createRule( RuleType.INBOUND, LinkCategoryActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "noAspect"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef2); PropertyDefinition catPropDef = this.dictionaryDAO.getProperty(CAT_PROP_QNAME); if (catPropDef == null) { // Why is it undefined? } // Check that the category value has been set // It has been declared as a multi-value property, so we expect that here Collection<NodeRef> setValue = (Collection<NodeRef>) this.nodeService.getProperty(newNodeRef2, CAT_PROP_QNAME); assertNotNull(setValue); assertEquals(1, setValue.size()); assertEquals(this.catROne, setValue.toArray()[0]); } /** * Test: * rule type: inbound * condition: no-condition * action: mail * @throws MessagingException * @throws IOException */ public void testMailAction() throws MessagingException, IOException { this.nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(MailActionExecuter.PARAM_TO, "[email protected]"); params.put(MailActionExecuter.PARAM_SUBJECT, "Unit test"); params.put(MailActionExecuter.PARAM_TEXT, "This is a test to check that the mail action is working."); Rule rule = createRule( RuleType.INBOUND, MailActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); MailActionExecuter mailService = (MailActionExecuter) ((ApplicationContextFactory) applicationContext .getBean("OutboundSMTP")).getApplicationContext().getBean("mail"); mailService.setTestMode(true); mailService.clearLastTestMessage(); this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); // An email should appear in the recipients email // System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); MimeMessage lastMessage = mailService.retrieveLastTestMessage(); assertNotNull("Message should have been sent", lastMessage); System.out.println("Sent email with subject: " + lastMessage.getSubject()); System.out.println("Sent email with content: " + lastMessage.getContent()); } public void testMailNotSentIfRollback() { this.nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(MailActionExecuter.PARAM_TO, "[email protected]"); params.put(MailActionExecuter.PARAM_SUBJECT, "testMailNotSentIfRollback()"); params.put(MailActionExecuter.PARAM_TEXT, "This email should NOT have been sent."); Rule rule = createRule( RuleType.INBOUND, MailActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); String illegalName = "MyName.txt "; // space at end MailActionExecuter mailService = (MailActionExecuter) ((ApplicationContextFactory) applicationContext .getBean("OutboundSMTP")).getApplicationContext().getBean("mail"); mailService.setTestMode(true); mailService.clearLastTestMessage(); try { this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, makeNameProperty(illegalName)).getChildRef(); fail("createNode() should have failed."); } catch(IntegrityException e) { // Expected exception. // An email should NOT appear in the recipients email } MimeMessage lastMessage = mailService.retrieveLastTestMessage(); assertNull("Message should NOT have been sent", lastMessage); } private Map<QName, Serializable> makeNameProperty(String name) { Map<QName, Serializable> properties = new HashMap<QName, Serializable>(1); properties.put(ContentModel.PROP_NAME, name); return properties; } /** * Test: * rule type: inbound * condition: no-condition() * action: copy() */ public void testCopyAction() { String localName = getName() + System.currentTimeMillis(); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, this.rootNodeRef); Rule rule = createRule( RuleType.INBOUND, CopyActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, localName), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); // Check that the created node is still there List<ChildAssociationRef> origRefs = this.nodeService.getChildAssocs( this.nodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, localName)); assertNotNull(origRefs); assertEquals(1, origRefs.size()); NodeRef origNodeRef = origRefs.get(0).getChildRef(); assertEquals(newNodeRef, origNodeRef); // Check that the created node has been copied List<ChildAssociationRef> copyChildAssocRefs = this.nodeService.getChildAssocs( this.rootNodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, localName)); assertNotNull(copyChildAssocRefs); // ********************************** // NOTE: Changed expected result to get build running // ********************************** assertEquals(1, copyChildAssocRefs.size()); NodeRef copyNodeRef = copyChildAssocRefs.get(0).getChildRef(); assertTrue(this.nodeService.hasAspect(copyNodeRef, ContentModel.ASPECT_COPIEDFROM)); NodeRef source = copyService.getOriginal(copyNodeRef); assertEquals(newNodeRef, source); // TODO test deep copy !! } /** * Test: * rule type: inbound * condition: no-condition() * action: transform() */ public void testTransformAction() throws Throwable { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_TEXT_PLAIN); params.put(TransformActionExecuter.PARAM_DESTINATION_FOLDER, this.rootNodeRef); params.put(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CHILDREN); params.put(TransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(TEST_NAMESPACE, "transformed")); Rule rule = createRule( RuleType.INBOUND, TransformActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); UserTransaction tx = transactionService.getUserTransaction(); tx.begin(); Map<QName, Serializable> props =new HashMap<QName, Serializable>(1); props.put(ContentModel.PROP_NAME, "test.xls"); // Create the node at the root NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "origional"), ContentModel.TYPE_CONTENT, props).getChildRef(); // Set some content on the origional ContentWriter contentWriter = this.contentService.getWriter(newNodeRef, ContentModel.PROP_CONTENT, true); contentWriter.setMimetype(MimetypeMap.MIMETYPE_EXCEL); File testFile = AbstractContentTransformerTest.loadQuickTestFile("xls"); contentWriter.putContent(testFile); tx.commit(); //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); AuthenticationComponent authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent"); authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName()); // Check that the created node is still there List<ChildAssociationRef> origRefs = this.nodeService.getChildAssocs( this.nodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "origional")); assertNotNull(origRefs); assertEquals(1, origRefs.size()); NodeRef origNodeRef = origRefs.get(0).getChildRef(); assertEquals(newNodeRef, origNodeRef); // Check that the created node has been copied List<ChildAssociationRef> copyChildAssocRefs = this.nodeService.getChildAssocs( this.rootNodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "test.txt")); assertNotNull(copyChildAssocRefs); assertEquals(1, copyChildAssocRefs.size()); NodeRef copyNodeRef = copyChildAssocRefs.get(0).getChildRef(); assertTrue(this.nodeService.hasAspect(copyNodeRef, ContentModel.ASPECT_COPIEDFROM)); NodeRef source = copyService.getOriginal(copyNodeRef); assertEquals(newNodeRef, source); // Check the transformed content ContentData contentData = (ContentData) nodeService.getProperty(copyNodeRef, ContentModel.PROP_CONTENT); assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentData.getMimetype()); } /** * Test image transformation * */ public void testImageTransformAction() throws Throwable { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(ImageTransformActionExecuter.PARAM_DESTINATION_FOLDER, this.rootNodeRef); params.put(ImageTransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CHILDREN); params.put(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_IMAGE_JPEG); params.put(ImageTransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(TEST_NAMESPACE, "transformed")); params.put(ImageTransformActionExecuter.PARAM_CONVERT_COMMAND, "-negate"); Rule rule = createRule( RuleType.INBOUND, ImageTransformActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); UserTransaction tx = transactionService.getUserTransaction(); tx.begin(); Map<QName, Serializable> props =new HashMap<QName, Serializable>(1); props.put(ContentModel.PROP_NAME, "test.gif"); // Create the node at the root NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "origional"), ContentModel.TYPE_CONTENT, props).getChildRef(); // Set some content on the origional ContentWriter contentWriter = this.contentService.getWriter(newNodeRef, ContentModel.PROP_CONTENT, true); contentWriter.setMimetype(MimetypeMap.MIMETYPE_IMAGE_GIF); File testFile = AbstractContentTransformerTest.loadQuickTestFile("gif"); contentWriter.putContent(testFile); tx.commit(); //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); // Check that the created node is still there List<ChildAssociationRef> origRefs = this.nodeService.getChildAssocs( this.nodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "origional")); assertNotNull(origRefs); assertEquals(1, origRefs.size()); NodeRef origNodeRef = origRefs.get(0).getChildRef(); assertEquals(newNodeRef, origNodeRef); // Check that the created node has been copied List<ChildAssociationRef> copyChildAssocRefs = this.nodeService.getChildAssocs( this.rootNodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "test.jpg")); assertNotNull(copyChildAssocRefs); assertEquals(1, copyChildAssocRefs.size()); NodeRef copyNodeRef = copyChildAssocRefs.get(0).getChildRef(); assertTrue(this.nodeService.hasAspect(copyNodeRef, ContentModel.ASPECT_COPIEDFROM)); NodeRef source = copyService.getOriginal(copyNodeRef); assertEquals(newNodeRef, source); } /** * Test: * rule type: inbound * condition: no-condition() * action: move() */ public void testMoveAction() { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, this.rootNodeRef); Rule rule = createRule( RuleType.INBOUND, MoveActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "origional"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); // Check that the created node has been moved List<ChildAssociationRef> origRefs = this.nodeService.getChildAssocs( this.nodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "origional")); assertNotNull(origRefs); assertEquals(0, origRefs.size()); // Check that the created node is in the new location List<ChildAssociationRef> copyChildAssocRefs = this.nodeService.getChildAssocs( this.rootNodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "origional")); assertNotNull(copyChildAssocRefs); assertEquals(1, copyChildAssocRefs.size()); NodeRef movedNodeRef = copyChildAssocRefs.get(0).getChildRef(); assertEquals(newNodeRef, movedNodeRef); } /** * Test: * rule type: inbound * condition: no-condition() * action: checkout() */ public void testCheckOutAction() { Rule rule = createRule( RuleType.INBOUND, CheckOutActionExecuter.NAME, null, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); NodeRef newNodeRef = null; UserTransaction tx = this.transactionService.getUserTransaction(); try { tx.begin(); // Create a new node newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "checkout"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); tx.commit(); } catch (Exception exception) { throw new RuntimeException(exception); } //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); // Check that the new node has been checked out List<ChildAssociationRef> children = this.nodeService.getChildAssocs(this.nodeRef); assertNotNull(children); assertEquals(3, children.size()); // includes rule folder for (ChildAssociationRef child : children) { NodeRef childNodeRef = child.getChildRef(); if (childNodeRef.equals(newNodeRef) == true) { // check that the node has been locked LockStatus lockStatus = this.lockService.getLockStatus(childNodeRef); assertEquals(LockStatus.LOCK_OWNER, lockStatus); } else if (this.nodeService.hasAspect(childNodeRef, ContentModel.ASPECT_WORKING_COPY) == true) { // assert that it is the working copy that relates to the origional node NodeRef copiedFromNodeRef = copyService.getOriginal(childNodeRef); assertEquals(newNodeRef, copiedFromNodeRef); } } } /** * Test: * rule type: inbound * condition: no-condition() * action: checkin() */ public void testCheckInAction() { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(CheckInActionExecuter.PARAM_DESCRIPTION, "The version description."); Rule rule = createRule( RuleType.INBOUND, CheckInActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); List<NodeRef> list = transactionService.getRetryingTransactionHelper().doInTransaction( new RetryingTransactionCallback<List<NodeRef>>() { public List<NodeRef> execute() { // Create a new node and check-it out NodeRef newNodeRef = RuleServiceCoverageTest.this.nodeService.createNode( RuleServiceCoverageTest.this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "origional"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); NodeRef workingCopy = RuleServiceCoverageTest.this.cociService.checkout(newNodeRef); // Move the working copy into the actionable folder RuleServiceCoverageTest.this.nodeService.moveNode( workingCopy, RuleServiceCoverageTest.this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "moved")); List<NodeRef> result = new ArrayList<NodeRef>(); result.add(newNodeRef); result.add(workingCopy); return result; } }); // Check that the working copy has been removed assertFalse(this.nodeService.exists(list.get(1))); // Check that the origional is no longer locked assertEquals(LockStatus.NO_LOCK, this.lockService.getLockStatus(list.get(0))); //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); } /** * Check that the rules can be enabled and disabled */ public void testRulesDisabled() { Map<String, Serializable> actionParams = new HashMap<String, Serializable>(1); actionParams.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, actionParams, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); RetryingTransactionCallback<NodeRef> noRulesWork = new RetryingTransactionCallback<NodeRef>() { @Override public NodeRef execute() throws Throwable { ruleService.disableRules(nodeRef); NodeRef newNodeRef = nodeService.createNode( nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef); return newNodeRef; } }; NodeRef newNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(noRulesWork); assertFalse(nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); RetryingTransactionCallback<NodeRef> withRulesWork = new RetryingTransactionCallback<NodeRef>() { @Override public NodeRef execute() throws Throwable { NodeRef newNodeRef2 = nodeService.createNode( nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef2); return newNodeRef2; } }; NodeRef newNodeRef2 = transactionService.getRetryingTransactionHelper().doInTransaction(withRulesWork); assertTrue(nodeService.hasAspect(newNodeRef2, ContentModel.ASPECT_VERSIONABLE)); } /** * Adds content to a given node. * <p> * Used to trigger rules of type of incomming. * * @param nodeRef the node reference */ private void addContentToNode(NodeRef nodeRef) { ContentWriter contentWriter = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true); contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); contentWriter.setEncoding("UTF-8"); assertNotNull(contentWriter); contentWriter.putContent(STANDARD_TEXT_CONTENT + System.currentTimeMillis()); } /** * Test checkMandatoryProperties method */ public void testCheckMandatoryProperties() { Map<String, Serializable> actionParams = new HashMap<String, Serializable>(1); actionParams.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Map<String, Serializable> condParams = new HashMap<String, Serializable>(1); // should be setting the condition parameter here Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, actionParams, ComparePropertyValueEvaluator.NAME, condParams); this.ruleService.saveRule(this.nodeRef, rule); try { // Try and create a node .. should fail since the rule is invalid Map<QName, Serializable> props2 = getContentProperties(); props2.put(ContentModel.PROP_NAME, "bobbins.doc"); NodeRef newNodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, props2).getChildRef(); addContentToNode(newNodeRef2); fail("An exception should have been thrown since a mandatory parameter was missing from the condition."); } catch (Throwable ruleServiceException) { // Success since we where expecting the exception } } /** * Test: * rule type: inbound * condition: match-text( * text = .doc, * operation = CONTAINS) * action: add-features( * aspect-name = versionable) */ public void testContainsTextCondition() { Map<String, Serializable> actionParams = new HashMap<String, Serializable>(1); actionParams.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); // ActionCondition parameter's Map<String, Serializable> condParams = new HashMap<String, Serializable>(1); condParams.put(ComparePropertyValueEvaluator.PARAM_VALUE, ".doc"); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, actionParams, ComparePropertyValueEvaluator.NAME, condParams); this.ruleService.saveRule(this.nodeRef, rule); // Test condition failure Map<QName, Serializable> props1 = new HashMap<QName, Serializable>(); props1.put(ContentModel.PROP_NAME, "bobbins.txt"); // props1.put(ContentModel.PROP_CONTENT, CONTENT_DATA_TEXT); NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, props1).getChildRef(); addContentToNode(newNodeRef); //Map<QName, Serializable> map = this.nodeService.getProperties(newNodeRef); //String value = (String)this.nodeService.getProperty(newNodeRef, ContentModel.PROP_NAME); assertFalse(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Test condition success Map<QName, Serializable> props2 = new HashMap<QName, Serializable>(); props2.put(ContentModel.PROP_NAME, "bobbins.doc"); //props2.put(ContentModel.PROP_CONTENT, CONTENT_DATA_TEXT); NodeRef newNodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, props2).getChildRef(); addContentToNode(newNodeRef2); assertTrue(this.nodeService.hasAspect( newNodeRef2, ContentModel.ASPECT_VERSIONABLE)); try { // Test name not set NodeRef newNodeRef3 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(newNodeRef3); } catch (RuleServiceException exception) { // Correct since text-match is a mandatory property } // Test begins with Map<String, Serializable> condParamsBegins = new HashMap<String, Serializable>(1); condParamsBegins.put(ComparePropertyValueEvaluator.PARAM_VALUE, "bob*"); rule.getAction().removeAllActionConditions(); ActionCondition condition1 = this.actionService.createActionCondition(ComparePropertyValueEvaluator.NAME, condParamsBegins); rule.getAction().addActionCondition(condition1); this.ruleService.saveRule(this.nodeRef, rule); Map<QName, Serializable> propsx = new HashMap<QName, Serializable>(); propsx.put(ContentModel.PROP_NAME, "mybobbins.doc"); //propsx.put(ContentModel.PROP_CONTENT, CONTENT_DATA_TEXT); NodeRef newNodeRefx = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, propsx).getChildRef(); addContentToNode(newNodeRefx); assertFalse(this.nodeService.hasAspect(newNodeRefx, ContentModel.ASPECT_VERSIONABLE)); Map<QName, Serializable> propsy = new HashMap<QName, Serializable>(); propsy.put(ContentModel.PROP_NAME, "bobbins.doc"); //propsy.put(ContentModel.PROP_CONTENT, CONTENT_DATA_TEXT); NodeRef newNodeRefy = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, propsy).getChildRef(); addContentToNode(newNodeRefy); assertTrue(this.nodeService.hasAspect( newNodeRefy, ContentModel.ASPECT_VERSIONABLE)); // Test ends with Map<String, Serializable> condParamsEnds = new HashMap<String, Serializable>(1); condParamsEnds.put(ComparePropertyValueEvaluator.PARAM_VALUE, "*s.doc"); rule.getAction().removeAllActionConditions(); ActionCondition condition2 = this.actionService.createActionCondition(ComparePropertyValueEvaluator.NAME, condParamsEnds); rule.getAction().addActionCondition(condition2); this.ruleService.saveRule(this.nodeRef, rule); Map<QName, Serializable> propsa = new HashMap<QName, Serializable>(); propsa.put(ContentModel.PROP_NAME, "bobbins.document"); // propsa.put(ContentModel.PROP_CONTENT, CONTENT_DATA_TEXT); NodeRef newNodeRefa = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, propsa).getChildRef(); addContentToNode(newNodeRefa); assertFalse(this.nodeService.hasAspect(newNodeRefa, ContentModel.ASPECT_VERSIONABLE)); Map<QName, Serializable> propsb = new HashMap<QName, Serializable>(); propsb.put(ContentModel.PROP_NAME, "bobbins.doc"); //propsb.put(ContentModel.PROP_CONTENT, CONTENT_DATA_TEXT); NodeRef newNodeRefb = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT, propsb).getChildRef(); addContentToNode(newNodeRefb); assertTrue(this.nodeService.hasAspect( newNodeRefb, ContentModel.ASPECT_VERSIONABLE)); } public void testInboundRuleType() { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); // Create a non-content node NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTAINER).getChildRef(); assertTrue(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Create a content node NodeRef contentNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT).getChildRef(); assertTrue(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); addContentToNode(contentNodeRef); assertTrue(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); // ALF-14744 / MNT-187: Create a content node - this time with 'empty content' in the same transaction contentNodeRef = this.transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<NodeRef>() { @Override public NodeRef execute() throws Throwable { NodeRef contentNodeRef = RuleServiceCoverageTest.this.nodeService.createNode( RuleServiceCoverageTest.this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT).getChildRef(); ContentWriter contentWriter = RuleServiceCoverageTest.this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true); assertNotNull(contentWriter); contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); contentWriter.setEncoding("UTF-8"); contentWriter.putContent(""); return contentNodeRef; } }); assertFalse(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); addContentToNode(contentNodeRef); assertTrue(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); // ALF-14744 / MNT-187: Create a content node - this time with the 'no content' aspect in the same transaction contentNodeRef = this.transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<NodeRef>() { @Override public NodeRef execute() throws Throwable { NodeRef contentNodeRef = RuleServiceCoverageTest.this.nodeService.createNode( RuleServiceCoverageTest.this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT).getChildRef(); RuleServiceCoverageTest.this.nodeService.addAspect(contentNodeRef, ContentModel.ASPECT_NO_CONTENT, null); return contentNodeRef; } }); assertFalse(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); addContentToNode(contentNodeRef); assertFalse(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); nodeService.removeAspect(contentNodeRef, ContentModel.ASPECT_NO_CONTENT); assertTrue(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Create a node to be moved NodeRef moveNode = this.nodeService.createNode( newNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT).getChildRef(); addContentToNode(moveNode); assertFalse(this.nodeService.hasAspect(moveNode, ContentModel.ASPECT_VERSIONABLE)); this.nodeService.moveNode( moveNode, this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children")); assertTrue(this.nodeService.hasAspect(moveNode, ContentModel.ASPECT_VERSIONABLE)); // Enusre the rule type does not get fired when the node is updated this.nodeService.removeAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE); assertFalse(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); this.nodeService.setProperty(contentNodeRef, ContentModel.PROP_NAME, "name.txt"); assertFalse(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); addContentToNode(contentNodeRef); assertFalse(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); } public void testUpdateRuleType() { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.UPDATE, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); // Create a non-content node NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_FOLDER).getChildRef(); this.nodeService.removeAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE); assertFalse(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Update the non-content node this.nodeService.setProperty(newNodeRef, ContentModel.PROP_NAME, "testName"); assertTrue(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Create a content node NodeRef contentNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTENT).getChildRef(); nodeService.removeAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE); assertFalse(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); addContentToNode(contentNodeRef); assertFalse(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); addContentToNode(contentNodeRef); assertTrue(this.nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Create a non content node, setting a property at the same time Map<QName, Serializable> props = new HashMap<QName, Serializable>(1); props.put(ContentModel.PROP_NAME, "testName"); NodeRef nodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_FOLDER, props).getChildRef(); nodeService.removeAspect(nodeRef2, ContentModel.ASPECT_VERSIONABLE); assertFalse(this.nodeService.hasAspect(nodeRef2, ContentModel.ASPECT_VERSIONABLE)); this.nodeService.setProperty(nodeRef2, ContentModel.PROP_NAME, "testName"); assertFalse(this.nodeService.hasAspect(nodeRef2, ContentModel.ASPECT_VERSIONABLE)); this.nodeService.setProperty(nodeRef2, ContentModel.PROP_NAME, "testName2"); assertTrue(this.nodeService.hasAspect(nodeRef2, ContentModel.ASPECT_VERSIONABLE)); transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { Map<QName, Serializable> props = new HashMap<QName, Serializable>(1); props.put(ContentModel.PROP_NAME, "testName"); NodeRef nodeRef3 = RuleServiceCoverageTest.this.nodeService.createNode( RuleServiceCoverageTest.this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_FOLDER, props).getChildRef(); assertFalse(RuleServiceCoverageTest.this.nodeService.hasAspect(nodeRef3, ContentModel.ASPECT_VERSIONABLE)); RuleServiceCoverageTest.this.nodeService.setProperty(nodeRef3, ContentModel.PROP_NAME, "testName2"); assertFalse(RuleServiceCoverageTest.this.nodeService.hasAspect(nodeRef3, ContentModel.ASPECT_VERSIONABLE)); return null; } }); } public void testAssociationUpdateRule() { //ALF-9661 test NodeRef sourceFolder = this.nodeService.createNode( this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}sourceFolder"), ContentModel.TYPE_FOLDER).getChildRef(); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); //create a rule that adds an aspect after a property is updated Rule rule = createRule( RuleType.UPDATE, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(sourceFolder, rule); //create folders NodeRef testNodeOneRef = this.nodeService.createNode( sourceFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(TEST_NAMESPACE, "original1"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(testNodeOneRef); NodeRef testNodeTwoRef = this.nodeService.createNode( sourceFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(TEST_NAMESPACE, "original2"), ContentModel.TYPE_CONTENT, getContentProperties()).getChildRef(); addContentToNode(testNodeTwoRef); //there is no aspect assertFalse(this.nodeService.hasAspect(testNodeOneRef, ContentModel.ASPECT_VERSIONABLE)); //create an association this.nodeService.addAspect(testNodeOneRef, ContentModel.ASPECT_REFERENCING, null); this.nodeService.createAssociation(testNodeOneRef, testNodeTwoRef, ContentModel.ASSOC_REFERENCES); //there should be the versionable aspect added assertTrue(this.nodeService.hasAspect(testNodeOneRef, ContentModel.ASPECT_VERSIONABLE)); } /** * Test: * rule type: outbound * condition: no-condition() * action: add-features( * aspect-name = versionable) */ public void testOutboundRuleType() { this.nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( "outbound", AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); // Create a node NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTAINER).getChildRef(); assertFalse(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Move the node out of the actionable folder this.nodeService.moveNode( newNodeRef, this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children")); assertTrue(this.nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE)); // Check the deletion of a node //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); NodeRef newNodeRef2 = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTAINER).getChildRef(); this.nodeService.deleteNode(newNodeRef2); } /** * Performance guideline test * */ public void xtestPerformanceOfRuleExecution() { try { StopWatch sw = new StopWatch(); // Create actionable nodes sw.start("create nodes with no rule executed"); UserTransaction userTransaction1 = this.transactionService.getUserTransaction(); userTransaction1.begin(); for (int i = 0; i < 100; i++) { this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS, ContentModel.TYPE_CONTAINER).getChildRef(); assertFalse(this.nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)); } userTransaction1.commit(); sw.stop(); Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put("aspect-name", ContentModel.ASPECT_VERSIONABLE); Rule rule = createRule( RuleType.INBOUND, AddFeaturesActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); sw.start("create nodes with one rule run (apply versionable aspect)"); UserTransaction userTransaction2 = this.transactionService.getUserTransaction(); userTransaction2.begin(); NodeRef[] nodeRefs = new NodeRef[100]; for (int i = 0; i < 100; i++) { NodeRef nodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "children"), ContentModel.TYPE_CONTAINER).getChildRef(); addContentToNode(nodeRef); nodeRefs[i] = nodeRef; // Check that the versionable aspect has not yet been applied assertFalse(this.nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)); } userTransaction2.commit(); sw.stop(); // Check that the versionable aspect has been applied to all the created nodes for (NodeRef ref : nodeRefs) { assertTrue(this.nodeService.hasAspect(ref, ContentModel.ASPECT_VERSIONABLE)); } System.out.println(sw.prettyPrint()); } catch (Exception exception) { throw new RuntimeException(exception); } } public void testAsyncExecutionWithPotentialLoop() { try { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_TEXT_PLAIN); params.put(TransformActionExecuter.PARAM_DESTINATION_FOLDER, this.nodeRef); params.put(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS); params.put(TransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(TEST_NAMESPACE, "transformed")); Rule rule = createRule( RuleType.INBOUND, TransformActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); rule.setExecuteAsynchronously(true); rule.setTitle("Transform document to text"); UserTransaction tx0 = transactionService.getUserTransaction(); tx0.begin(); this.ruleService.saveRule(this.nodeRef, rule); tx0.commit(); UserTransaction tx = transactionService.getUserTransaction(); tx.begin(); Map<QName, Serializable> props =new HashMap<QName, Serializable>(1); props.put(ContentModel.PROP_NAME, "test.xls"); // Create the node at the root NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "origional"), ContentModel.TYPE_CONTENT, props).getChildRef(); // Set some content on the origional ContentWriter contentWriter = this.contentService.getWriter(newNodeRef, ContentModel.PROP_CONTENT, true); contentWriter.setMimetype(MimetypeMap.MIMETYPE_EXCEL); File testFile = AbstractContentTransformerTest.loadQuickTestFile("xls"); contentWriter.putContent(testFile); tx.commit(); // Sleep to ensure work is done b4 execution is canceled Thread.sleep(10000); } catch (Exception exception) { throw new RuntimeException(exception); } } }
lgpl-3.0
premium-minds/billy
billy-portugal/src/test/java/com/premiumminds/billy/portugal/test/services/documents/PTDocumentAbstractTest.java
4308
/* * Copyright (C) 2017 Premium Minds. * * This file is part of billy portugal (PT Pack). * * billy portugal (PT Pack) is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * billy portugal (PT Pack) is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with billy portugal (PT Pack). If not, see <http://www.gnu.org/licenses/>. */ package com.premiumminds.billy.portugal.test.services.documents; import java.util.Date; import org.junit.jupiter.api.BeforeEach; import com.premiumminds.billy.core.exceptions.NotImplementedException; import com.premiumminds.billy.core.services.documents.DocumentIssuingHandler; import com.premiumminds.billy.core.services.exceptions.DocumentIssuingException; import com.premiumminds.billy.portugal.persistence.dao.DAOPTInvoice; import com.premiumminds.billy.portugal.persistence.entities.PTGenericInvoiceEntity; import com.premiumminds.billy.portugal.services.documents.util.PTIssuingParams; import com.premiumminds.billy.portugal.services.documents.util.PTIssuingParamsImpl; import com.premiumminds.billy.portugal.services.entities.PTGenericInvoice.SourceBilling; import com.premiumminds.billy.portugal.services.entities.PTGenericInvoice.TYPE; import com.premiumminds.billy.portugal.test.PTAbstractTest; import com.premiumminds.billy.portugal.test.PTPersistencyAbstractTest; import com.premiumminds.billy.portugal.test.util.PTInvoiceTestUtil; import com.premiumminds.billy.portugal.test.util.PTReceiptInvoiceTestUtil; import com.premiumminds.billy.portugal.test.util.PTSimpleInvoiceTestUtil; import com.premiumminds.billy.portugal.util.KeyGenerator; public class PTDocumentAbstractTest extends PTPersistencyAbstractTest { protected PTIssuingParams parameters; @BeforeEach public void setUpParamenters() { KeyGenerator generator = new KeyGenerator(PTPersistencyAbstractTest.PRIVATE_KEY_DIR); this.parameters = new PTIssuingParamsImpl(); this.parameters.setPrivateKey(generator.getPrivateKey()); this.parameters.setPublicKey(generator.getPublicKey()); this.parameters.setPrivateKeyVersion("1"); this.parameters.setEACCode("31400"); } @SuppressWarnings("unchecked") protected <T extends PTGenericInvoiceEntity> T newInvoice(TYPE type, SourceBilling billing) { switch (type) { case FT: return (T) new PTInvoiceTestUtil(PTAbstractTest.injector).getInvoiceEntity(billing); case FS: return (T) new PTSimpleInvoiceTestUtil(PTAbstractTest.injector).getSimpleInvoiceEntity(billing); case FR: return (T) new PTReceiptInvoiceTestUtil(PTAbstractTest.injector).getReceiptInvoiceEntity(billing); case NC: throw new NotImplementedException(); case ND: throw new NotImplementedException(); default: return null; } } protected <T extends DocumentIssuingHandler, I extends PTGenericInvoiceEntity> void issueNewInvoice(T handler, I invoice, String series) throws DocumentIssuingException { DAOPTInvoice dao = this.getInstance(DAOPTInvoice.class); dao.beginTransaction(); try { invoice.initializeEntityDates(); this.issueNewInvoice(handler, invoice, series, new Date(invoice.getCreateTimestamp().getTime() + 100)); dao.commit(); } catch (DocumentIssuingException up) { dao.rollback(); throw up; } } protected <T extends DocumentIssuingHandler, I extends PTGenericInvoiceEntity> void issueNewInvoice(T handler, I invoice, String series, Date date) throws DocumentIssuingException { this.parameters.setInvoiceSeries(series); invoice.setDate(date); handler.issue(invoice, this.parameters); } }
lgpl-3.0
MesquiteProject/MesquiteCore
Source/mesquite/lib/ColorPickerPanel.java
8039
/* Mesquite source code. Copyright 1997 and onward, W. Maddison and D. Maddison. Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code. The commenting leaves much to be desired. Please approach this source code with the spirit of helping out. Perhaps with your help we can be more than a few, and make Mesquite better. Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Mesquite's web site is http://mesquiteproject.org This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.lib; import java.awt.*; import java.awt.event.*; import mesquite.lib.duties.*; public class ColorPickerPanel extends Panel implements MouseListener { int hues = 50; int saturations = 50; int brightnesses = 50; double brightness = 1.0; Color[][] colors; float[] colorLoc = null; CurrentColorPanel indicator; Colorable dialog; private Color currentColor = Color.white; int currentI = 0; int currentJ = 0; int boxSizeX; int boxSizeY; int offsetX; int offsetY; int touchedX = -1; int touchedY = -1; int indicatorX = -1; int indicatorY = -1; int colorEdge = 50; public ColorPickerPanel(Colorable d, Color initColor, int divisions){ this.dialog = d; addMouseListener(this); if (divisions>0) { hues = divisions; saturations = divisions; } colors = new Color[hues][saturations]; for (int i=0; i<hues-1; i++){ for (int j=0; j<saturations; j++){ colors[i][j] = new Color(Color.HSBtoRGB((float)(i*1.0/hues),(float)(j*1.0/saturations),(float)brightness)); } } /**/ for (int j=0; j<saturations; j++){ float f = (float)(j*1.0/saturations); colors[hues-1][j] = new Color(f, f, f); } /**/ add(indicator = new CurrentColorPanel(this)); setSize(200,200); int w = getBounds().width - colorEdge; int h = getBounds().height; boxSizeX = w/hues; boxSizeY = h/saturations; indicator.setBounds(-50,-50, boxSizeX+2, boxSizeY+2); setInitialColor(initColor); } public void setInitialColor(Color current){ if (current == null) return; currentColor = current; brightness = Color.RGBtoHSB(current.getRed(), current.getGreen(), current.getBlue(), null)[2]; for (int ki=0; ki<hues-1; ki++){ for (int kj=0; kj<saturations; kj++){ colors[ki][kj] = new Color(Color.HSBtoRGB((float)(ki*1.0/hues),(float)(kj*1.0/saturations),(float)brightness)); } } checkBounds(); setColorFromXY(indicatorX+boxSizeX, indicatorY+boxSizeY); //DRM: 25 April 2016, added boxSize to each to fix shift when first brining the dialog box up. Not sure why this was needed. /*float hu = colorLoc[0]; float sa = colorLoc[1]; indicatorX = (int)(offsetX + hu*hues*boxSizeX-1); indicatorY = (int)(offsetY+ sa*saturations*boxSizeY-1); indicator.setLocation(indicatorX,indicatorY); */ indicator.repaint(); } private void checkBounds(){ int red = currentColor.getRed(); int green = currentColor.getGreen(); int blue = currentColor.getBlue(); int w = getBounds().width - colorEdge; int h = getBounds().height; boxSizeX = w/hues; boxSizeY = h/saturations; offsetX = (w-hues*boxSizeX)/2; offsetY = (h-saturations*boxSizeY)/2; if (red == green && red == blue){ indicatorX = (int)(offsetX + (hues-1)*boxSizeX-1); indicatorY = (int)(offsetY+ (1.0*red)/255*saturations*boxSizeY-1); } else { colorLoc = Color.RGBtoHSB(red, green, blue, null); if (colorLoc==null) return; float hu = colorLoc[0]; float sa = colorLoc[1]; brightness = colorLoc[2]; indicatorX = (int)(offsetX + hu*hues*boxSizeX-1); indicatorY = (int)(offsetY+ sa*saturations*boxSizeY-1); // indicatorX = (int)(offsetX + hu*hues*boxSizeX-1+boxSizeX); // indicatorY = (int)(offsetY+ sa*saturations*boxSizeY-1+boxSizeY); } Rectangle d = indicator.getBounds(); if (d.x != indicatorX || d.y != indicatorY || d.width != boxSizeX+2 || d.height != boxSizeY+2) indicator.setBounds(indicatorX,indicatorY, boxSizeX+2, boxSizeY+2); } public Dimension getPreferredSize() { return new Dimension(400, 200); } public void paint(Graphics g){ g.setClip(0, 0, getBounds().width, getBounds().height); checkBounds(); /* boxSizeX = w/hues; boxSizeY = h/saturations; */ int w = getBounds().width - colorEdge; int h = getBounds().height; offsetX = (w-hues*boxSizeX)/2; offsetY = (h-saturations*boxSizeY)/2; for (int x = 0; x < hues ; x++){ for (int y = 0; y<saturations; y++){ g.setColor(colors[x][y]); g.fillRect(offsetX + x*boxSizeX,offsetY+ y*boxSizeY,boxSizeX,boxSizeY); } } /* g.setColor(currentColor); g.fillRect(w,0,colorEdge,h); */ float[] f = new float[3]; Color.RGBtoHSB(currentColor.getRed(), currentColor.getGreen(), currentColor.getBlue(), f); // Color out =new Color(Color.HSBtoRGB(f[0], f[1], f[2])); for (int b = 0; b < brightnesses ; b++){ float br = (float)(1.0-(b*1.0/brightnesses)); g.setColor(new Color(Color.HSBtoRGB(f[0],f[1],br))); g.fillRect(w, b*h/brightnesses,colorEdge,(h/brightnesses)); } g.setColor(Color.black); g.drawRect(w,0,colorEdge-1,h-1); g.drawRect(offsetX, offsetY, hues*boxSizeX-1, saturations*boxSizeY-1); g.drawRect(w + colorEdge/2-1, 0, 2, h-1); g.setColor(Color.white); g.drawLine(w + colorEdge/2, 0, w + colorEdge/2, h-1); g.setColor(Color.black); g.fillRoundRect(w + colorEdge/2-6, h-(int)(h * brightness + 4), 12, 8, 4, 4); g.setColor(Color.white); g.drawRoundRect(w + colorEdge/2-6, h-(int)(h * brightness + 4), 12, 8, 4, 4); //g.drawRect(indicatorX, indicatorY, boxSizeX, boxSizeY); /* indicator.setSize(boxSizeX+2, boxSizeY+2); if (touchedX<0 && touchedY<0 && colorLoc!=null){ float hu = colorLoc[0]; float sa = colorLoc[1]; indicatorX = (int)(offsetX + hu*hues*boxSizeX-1); indicatorY = (int)(offsetY+ sa*saturations*boxSizeY-1); indicator.setLocation((int)(offsetX + hu*hues*boxSizeX-1),(int)(offsetY+ sa*saturations*boxSizeY-1)); } */ } private void setColorFromXY(int x, int y){ if (boxSizeX>0 && boxSizeY>0){ int i =(x-offsetX)/boxSizeX; int j =(y-offsetY)/boxSizeY; if (i>=0 && i<hues && j >=0 && j<saturations) { currentColor = colors[i][j]; currentI = i; currentJ = j; checkBounds(); /*float hu = colorLoc[0]; float sa = colorLoc[1]; indicatorX = (int)(offsetX + hu*hues*boxSizeX-1); indicatorY = (int)(offsetY+ sa*saturations*boxSizeY-1); */ //dialog.setColor(colors[i][j]); touchedX = x; touchedY = y; //indicator.setLocation(indicatorX, indicatorY); indicator.repaint(); } else if (j >=0 && j<saturations && i >= hues){ brightness = (saturations - j)*1.0/saturations; for (int ki=0; ki<hues-1; ki++){ for (int kj=0; kj<saturations; kj++){ colors[ki][kj] = new Color(Color.HSBtoRGB((float)(ki*1.0/hues),(float)(kj*1.0/saturations),(float)brightness)); } } currentColor = colors[currentI][currentJ]; repaint(); indicator.repaint(); } } } public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); setColorFromXY(x, y); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); setColorFromXY(x, y); } public Color getColor(){ return currentColor; } } class CurrentColorPanel extends Panel { ColorPickerPanel colorPanel; public CurrentColorPanel(ColorPickerPanel cp){ colorPanel = cp; } public void paint(Graphics g){ g.setColor(colorPanel.getColor()); int w = getBounds().width; int h = getBounds().height; g.fillRect(0,0, w-1, h -1); g.setColor(Color.black); g.drawRect(0,0, w-1, h -1); } }
lgpl-3.0
barmalei/primus
lib/primus/test/testmysql.py
1858
#!/usr/bin/env python # # # Copyright 2009 Andrei <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import os, unittest, ConfigParser from primus.mysqlartifact import CheckDBEnvironment class TestMySQL(unittest.TestCase): def setUp(self): self.config = ConfigParser.ConfigParser() self.config_path = os.path.join(os.path.dirname(__file__), 'dbtest.conf') self.config.read([ self.config_path ]) def test_check_mysqlversion(self): pass # ch = CheckDBEnvironment(config = (self.config_path, 'db'), required_version=(8, 0)) # def na(): ch.build() # self.assertRaises(CheckDBEnvironment.VersionException, na) # # ch = CheckDBEnvironment(config = (self.config_path, ['db2', 'db']), required_version=(8, 0)) # def na(): ch.build() # self.assertRaises(CheckDBEnvironment.VersionException, na) # # ch = CheckDBEnvironment(config = (self.config_path, 'db'), required_version=(4, 0)) # ch.build() if __name__ == '__main__': unittest.main()
lgpl-3.0
F1r3w477/CustomWorldGen
build/tmp/recompileMc/sources/net/minecraft/util/math/BlockPos.java
18030
package net.minecraft.util.math; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Lists; import java.util.Iterator; import java.util.List; import javax.annotation.concurrent.Immutable; import net.minecraft.entity.Entity; import net.minecraft.util.EnumFacing; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @Immutable public class BlockPos extends Vec3i { private static final Logger LOGGER = LogManager.getLogger(); /** An immutable block pos with zero as all coordinates. */ public static final BlockPos ORIGIN = new BlockPos(0, 0, 0); private static final int NUM_X_BITS = 1 + MathHelper.calculateLogBaseTwo(MathHelper.roundUpToPowerOfTwo(30000000)); private static final int NUM_Z_BITS = NUM_X_BITS; private static final int NUM_Y_BITS = 64 - NUM_X_BITS - NUM_Z_BITS; private static final int Y_SHIFT = 0 + NUM_Z_BITS; private static final int X_SHIFT = Y_SHIFT + NUM_Y_BITS; private static final long X_MASK = (1L << NUM_X_BITS) - 1L; private static final long Y_MASK = (1L << NUM_Y_BITS) - 1L; private static final long Z_MASK = (1L << NUM_Z_BITS) - 1L; public BlockPos(int x, int y, int z) { super(x, y, z); } public BlockPos(double x, double y, double z) { super(x, y, z); } public BlockPos(Entity source) { this(source.posX, source.posY, source.posZ); } public BlockPos(Vec3d vec) { this(vec.xCoord, vec.yCoord, vec.zCoord); } public BlockPos(Vec3i source) { this(source.getX(), source.getY(), source.getZ()); } /** * Add the given coordinates to the coordinates of this BlockPos */ public BlockPos add(double x, double y, double z) { return x == 0.0D && y == 0.0D && z == 0.0D ? this : new BlockPos((double)this.getX() + x, (double)this.getY() + y, (double)this.getZ() + z); } /** * Add the given coordinates to the coordinates of this BlockPos */ public BlockPos add(int x, int y, int z) { return x == 0 && y == 0 && z == 0 ? this : new BlockPos(this.getX() + x, this.getY() + y, this.getZ() + z); } /** * Add the given Vector to this BlockPos */ public BlockPos add(Vec3i vec) { return vec.getX() == 0 && vec.getY() == 0 && vec.getZ() == 0 ? this : new BlockPos(this.getX() + vec.getX(), this.getY() + vec.getY(), this.getZ() + vec.getZ()); } /** * Subtract the given Vector from this BlockPos */ public BlockPos subtract(Vec3i vec) { return vec.getX() == 0 && vec.getY() == 0 && vec.getZ() == 0 ? this : new BlockPos(this.getX() - vec.getX(), this.getY() - vec.getY(), this.getZ() - vec.getZ()); } /** * Offset this BlockPos 1 block up */ public BlockPos up() { return this.up(1); } /** * Offset this BlockPos n blocks up */ public BlockPos up(int n) { return this.offset(EnumFacing.UP, n); } /** * Offset this BlockPos 1 block down */ public BlockPos down() { return this.down(1); } /** * Offset this BlockPos n blocks down */ public BlockPos down(int n) { return this.offset(EnumFacing.DOWN, n); } /** * Offset this BlockPos 1 block in northern direction */ public BlockPos north() { return this.north(1); } /** * Offset this BlockPos n blocks in northern direction */ public BlockPos north(int n) { return this.offset(EnumFacing.NORTH, n); } /** * Offset this BlockPos 1 block in southern direction */ public BlockPos south() { return this.south(1); } /** * Offset this BlockPos n blocks in southern direction */ public BlockPos south(int n) { return this.offset(EnumFacing.SOUTH, n); } /** * Offset this BlockPos 1 block in western direction */ public BlockPos west() { return this.west(1); } /** * Offset this BlockPos n blocks in western direction */ public BlockPos west(int n) { return this.offset(EnumFacing.WEST, n); } /** * Offset this BlockPos 1 block in eastern direction */ public BlockPos east() { return this.east(1); } /** * Offset this BlockPos n blocks in eastern direction */ public BlockPos east(int n) { return this.offset(EnumFacing.EAST, n); } /** * Offset this BlockPos 1 block in the given direction */ public BlockPos offset(EnumFacing facing) { return this.offset(facing, 1); } /** * Offsets this BlockPos n blocks in the given direction */ public BlockPos offset(EnumFacing facing, int n) { return n == 0 ? this : new BlockPos(this.getX() + facing.getFrontOffsetX() * n, this.getY() + facing.getFrontOffsetY() * n, this.getZ() + facing.getFrontOffsetZ() * n); } /** * Calculate the cross product of this and the given Vector */ public BlockPos crossProduct(Vec3i vec) { return new BlockPos(this.getY() * vec.getZ() - this.getZ() * vec.getY(), this.getZ() * vec.getX() - this.getX() * vec.getZ(), this.getX() * vec.getY() - this.getY() * vec.getX()); } /** * Serialize this BlockPos into a long value */ public long toLong() { return ((long)this.getX() & X_MASK) << X_SHIFT | ((long)this.getY() & Y_MASK) << Y_SHIFT | ((long)this.getZ() & Z_MASK) << 0; } /** * Create a BlockPos from a serialized long value (created by toLong) */ public static BlockPos fromLong(long serialized) { int i = (int)(serialized << 64 - X_SHIFT - NUM_X_BITS >> 64 - NUM_X_BITS); int j = (int)(serialized << 64 - Y_SHIFT - NUM_Y_BITS >> 64 - NUM_Y_BITS); int k = (int)(serialized << 64 - NUM_Z_BITS >> 64 - NUM_Z_BITS); return new BlockPos(i, j, k); } public static Iterable<BlockPos> getAllInBox(BlockPos from, BlockPos to) { final BlockPos blockpos = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ())); final BlockPos blockpos1 = new BlockPos(Math.max(from.getX(), to.getX()), Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ())); return new Iterable<BlockPos>() { public Iterator<BlockPos> iterator() { return new AbstractIterator<BlockPos>() { private BlockPos lastReturned; protected BlockPos computeNext() { if (this.lastReturned == null) { this.lastReturned = blockpos; return this.lastReturned; } else if (this.lastReturned.equals(blockpos1)) { return (BlockPos)this.endOfData(); } else { int i = this.lastReturned.getX(); int j = this.lastReturned.getY(); int k = this.lastReturned.getZ(); if (i < blockpos1.getX()) { ++i; } else if (j < blockpos1.getY()) { i = blockpos.getX(); ++j; } else if (k < blockpos1.getZ()) { i = blockpos.getX(); j = blockpos.getY(); ++k; } this.lastReturned = new BlockPos(i, j, k); return this.lastReturned; } } }; } }; } /** * Returns a version of this BlockPos that is guaranteed to be immutable. * * <p>When storing a BlockPos given to you for an extended period of time, make sure you * use this in case the value is changed internally.</p> */ public BlockPos toImmutable() { return this; } public static Iterable<BlockPos.MutableBlockPos> getAllInBoxMutable(BlockPos from, BlockPos to) { final BlockPos blockpos = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ())); final BlockPos blockpos1 = new BlockPos(Math.max(from.getX(), to.getX()), Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ())); return new Iterable<BlockPos.MutableBlockPos>() { public Iterator<BlockPos.MutableBlockPos> iterator() { return new AbstractIterator<BlockPos.MutableBlockPos>() { private BlockPos.MutableBlockPos theBlockPos; protected BlockPos.MutableBlockPos computeNext() { if (this.theBlockPos == null) { this.theBlockPos = new BlockPos.MutableBlockPos(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return this.theBlockPos; } else if (this.theBlockPos.equals(blockpos1)) { return (BlockPos.MutableBlockPos)this.endOfData(); } else { int i = this.theBlockPos.getX(); int j = this.theBlockPos.getY(); int k = this.theBlockPos.getZ(); if (i < blockpos1.getX()) { ++i; } else if (j < blockpos1.getY()) { i = blockpos.getX(); ++j; } else if (k < blockpos1.getZ()) { i = blockpos.getX(); j = blockpos.getY(); ++k; } this.theBlockPos.x = i; this.theBlockPos.y = j; this.theBlockPos.z = k; return this.theBlockPos; } } }; } }; } public static class MutableBlockPos extends BlockPos { /** Mutable X Coordinate */ protected int x; /** Mutable Y Coordinate */ protected int y; /** Mutable Z Coordinate */ protected int z; public MutableBlockPos() { this(0, 0, 0); } public MutableBlockPos(BlockPos pos) { this(pos.getX(), pos.getY(), pos.getZ()); } public MutableBlockPos(int x_, int y_, int z_) { super(0, 0, 0); this.x = x_; this.y = y_; this.z = z_; } /** * Gets the X coordinate. */ public int getX() { return this.x; } /** * Gets the Y coordinate. */ public int getY() { return this.y; } /** * Gets the Z coordinate. */ public int getZ() { return this.z; } /** * Sets the position, MUST not be name 'set' as that causes obfusication conflicts with func_185343_d */ public BlockPos.MutableBlockPos setPos(int xIn, int yIn, int zIn) { this.x = xIn; this.y = yIn; this.z = zIn; return this; } public BlockPos.MutableBlockPos setPos(double xIn, double yIn, double zIn) { return this.setPos(MathHelper.floor_double(xIn), MathHelper.floor_double(yIn), MathHelper.floor_double(zIn)); } @SideOnly(Side.CLIENT) public BlockPos.MutableBlockPos setPos(Entity entityIn) { return this.setPos(entityIn.posX, entityIn.posY, entityIn.posZ); } public BlockPos.MutableBlockPos setPos(Vec3i vec) { return this.setPos(vec.getX(), vec.getY(), vec.getZ()); } public BlockPos.MutableBlockPos move(EnumFacing facing) { return this.move(facing, 1); } public BlockPos.MutableBlockPos move(EnumFacing facing, int p_189534_2_) { return this.setPos(this.x + facing.getFrontOffsetX() * p_189534_2_, this.y + facing.getFrontOffsetY() * p_189534_2_, this.z + facing.getFrontOffsetZ() * p_189534_2_); } public void setY(int yIn) { this.y = yIn; } /** * Returns a version of this BlockPos that is guaranteed to be immutable. * * <p>When storing a BlockPos given to you for an extended period of time, make sure you * use this in case the value is changed internally.</p> */ public BlockPos toImmutable() { return new BlockPos(this); } } public static final class PooledMutableBlockPos extends BlockPos.MutableBlockPos { private boolean released; private static final List<BlockPos.PooledMutableBlockPos> POOL = Lists.<BlockPos.PooledMutableBlockPos>newArrayList(); private PooledMutableBlockPos(int xIn, int yIn, int zIn) { super(xIn, yIn, zIn); } public static BlockPos.PooledMutableBlockPos retain() { return retain(0, 0, 0); } public static BlockPos.PooledMutableBlockPos retain(double xIn, double yIn, double zIn) { return retain(MathHelper.floor_double(xIn), MathHelper.floor_double(yIn), MathHelper.floor_double(zIn)); } @SideOnly(Side.CLIENT) public static BlockPos.PooledMutableBlockPos retain(Vec3i vec) { return retain(vec.getX(), vec.getY(), vec.getZ()); } public static BlockPos.PooledMutableBlockPos retain(int xIn, int yIn, int zIn) { synchronized (POOL) { if (!POOL.isEmpty()) { BlockPos.PooledMutableBlockPos blockpos$pooledmutableblockpos = (BlockPos.PooledMutableBlockPos)POOL.remove(POOL.size() - 1); if (blockpos$pooledmutableblockpos != null && blockpos$pooledmutableblockpos.released) { blockpos$pooledmutableblockpos.released = false; blockpos$pooledmutableblockpos.setPos(xIn, yIn, zIn); return blockpos$pooledmutableblockpos; } } } return new BlockPos.PooledMutableBlockPos(xIn, yIn, zIn); } public void release() { synchronized (POOL) { if (POOL.size() < 100) { POOL.add(this); } this.released = true; } } /** * Sets the position, MUST not be name 'set' as that causes obfusication conflicts with func_185343_d */ public BlockPos.PooledMutableBlockPos setPos(int xIn, int yIn, int zIn) { if (this.released) { BlockPos.LOGGER.error("PooledMutableBlockPosition modified after it was released.", new Throwable()); this.released = false; } return (BlockPos.PooledMutableBlockPos)super.setPos(xIn, yIn, zIn); } @SideOnly(Side.CLIENT) public BlockPos.PooledMutableBlockPos setPos(Entity entityIn) { return (BlockPos.PooledMutableBlockPos)super.setPos(entityIn); } public BlockPos.PooledMutableBlockPos setPos(double xIn, double yIn, double zIn) { return (BlockPos.PooledMutableBlockPos)super.setPos(xIn, yIn, zIn); } public BlockPos.PooledMutableBlockPos setPos(Vec3i vec) { return (BlockPos.PooledMutableBlockPos)super.setPos(vec); } public BlockPos.PooledMutableBlockPos move(EnumFacing facing) { return (BlockPos.PooledMutableBlockPos)super.move(facing); } public BlockPos.PooledMutableBlockPos move(EnumFacing facing, int p_189534_2_) { return (BlockPos.PooledMutableBlockPos)super.move(facing, p_189534_2_); } } }
lgpl-3.0
jbzdak/query-builder
sql-builder-xml-binidings/src/main/java/cx/ath/jbzdak/sqlbuilder/xml/parameter/package-info.java
1218
/* * Copyright (c) 2011 for Jacek Bzdak * * This file is part of query builder. * * Query builder is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Query builder is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Query builder. If not, see <http://www.gnu.org/licenses/>. */ @XmlSchema( namespace = Namespace.NAMESPACE, xmlns = {@XmlNs(prefix = "sql", namespaceURI = Namespace.NAMESPACE)}, elementFormDefault = XmlNsForm.QUALIFIED, attributeFormDefault = XmlNsForm.UNQUALIFIED ) package cx.ath.jbzdak.sqlbuilder.xml.parameter; import cx.ath.jbzdak.sqlbuilder.Namespace; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema;
lgpl-3.0
dnacreative/records-management
rm-server/test/java/org/alfresco/module/org_alfresco_module_rm/test/integration/classification/interceptor/RecordBrowseClassificationEnforcementTest.java
13408
/* * Copyright (C) 2005-2015 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.module.org_alfresco_module_rm.test.integration.classification.interceptor; import static com.google.common.collect.Lists.newArrayList; import static org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService.ROLE_ADMIN; import static org.alfresco.util.GUID.generate; import java.util.List; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.NodeRef; /** * Enforcement of classification when browsing records in the file plan * * @author Tuna Aksoy * @since 3.0.a */ public class RecordBrowseClassificationEnforcementTest extends BrowseClassificationEnforcementTestBase { public void testUserWithNoSecurityClearance() { /** * Given that a test user without security clearance exists * and the test user is added to the RM Admin role * and a category, a folder and two records are created in the file plan * and one of the records is classified with the highest security level * * When I browse the file plan as admin * Then I will see both documents * * When I browse the file plan as the test user * Then I will only see the unclassified record */ doBehaviourDrivenTest(new BehaviourDrivenTest() { private NodeRef category; private NodeRef folder; private NodeRef record1; private NodeRef record2; private List<ChildAssociationRef> resultsForAdmin; private List<ChildAssociationRef> resultsForTestUser; /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#given() */ @Override public void given() throws Exception { testUser = generate(); createPerson(testUser); filePlanRoleService.assignRoleToAuthority(filePlan, ROLE_ADMIN, testUser); category = filePlanService.createRecordCategory(filePlan, generate()); folder = recordFolderService.createRecordFolder(category, generate()); record1 = utils.createRecord(folder, generate()); record2 = utils.createRecord(folder, generate()); contentClassificationService.classifyContent(propertiesDTO1, record1); } /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#when() */ @Override public void when() throws Exception { resultsForAdmin = browseAsAdmin(folder); resultsForTestUser = browseAsTestUser(folder); } /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#then() */ @Override public void then() throws Exception { doTestInTransaction(new Test<Void>() { @Override public Void run() { assertNotNull(resultsForAdmin); assertEquals(2, resultsForAdmin.size()); List<NodeRef> records = newArrayList(record1, record2); assertTrue(records.contains(resultsForAdmin.get(0).getChildRef())); assertTrue(records.contains(resultsForAdmin.get(1).getChildRef())); return null; } }); doTestInTransaction(new Test<Void>() { @Override public Void run() { assertNotNull(resultsForTestUser); assertEquals(1, resultsForTestUser.size()); assertEquals(record2, resultsForTestUser.get(0).getChildRef()); return null; } }, testUser); } }); } public void testUserWithMidlevelSecurityClearance() { /** * Given that a test user with mid-level security clearance exists * and the test user is added to the RM Admin role * and a category, a folder and three records are created in the file plan * and one of the records is classified with the highest security level * and another record is classified with the mid-level security level * * When I browse the file plan as admin * Then I will see all three records * * When I browse the file plan as the test user * Then I will see the unclassified record * and the record with the mid-level classification * and I won't be able to see the record with the classification greater than my clearance level */ doBehaviourDrivenTest(new BehaviourDrivenTest() { private NodeRef category; private NodeRef folder; private NodeRef record1; private NodeRef record2; private NodeRef record3; private List<ChildAssociationRef> resultsForAdmin; private List<ChildAssociationRef> resultsForTestUser; /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#given() */ @Override public void given() throws Exception { testUser = generate(); createPerson(testUser); filePlanRoleService.assignRoleToAuthority(filePlan, ROLE_ADMIN, testUser); securityClearanceService.setUserSecurityClearance(testUser, LEVEL2); category = filePlanService.createRecordCategory(filePlan, generate()); folder = recordFolderService.createRecordFolder(category, generate()); record1 = utils.createRecord(folder, generate()); record2 = utils.createRecord(folder, generate()); record3 = utils.createRecord(folder, generate()); contentClassificationService.classifyContent(propertiesDTO1, record1); contentClassificationService.classifyContent(propertiesDTO2, record2); } /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#when() */ @Override public void when() throws Exception { resultsForAdmin = browseAsAdmin(folder); resultsForTestUser = browseAsTestUser(folder); } /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#then() */ @Override public void then() throws Exception { doTestInTransaction(new Test<Void>() { @Override public Void run() { assertNotNull(resultsForAdmin); assertEquals(3, resultsForAdmin.size()); List<NodeRef> records = newArrayList(record1, record2, record3); assertTrue(records.contains(resultsForAdmin.get(0).getChildRef())); assertTrue(records.contains(resultsForAdmin.get(1).getChildRef())); assertTrue(records.contains(resultsForAdmin.get(2).getChildRef())); return null; } }); doTestInTransaction(new Test<Void>() { @Override public Void run() { assertNotNull(resultsForTestUser); assertEquals(2, resultsForTestUser.size()); List<NodeRef> records = newArrayList(record2, record3); assertTrue(records.contains(resultsForTestUser.get(0).getChildRef())); assertTrue(records.contains(resultsForTestUser.get(1).getChildRef())); return null; } }, testUser); } }); } public void testUseWithHighestLevelSecurityClearance() { /** * Given that a test user with highest level security clearance exists * and the test user is added to the RM Admin role * and a category, a folder and three records are created in the file plan * and one of the records is classified with the highest security level * and another record is classified with the mid-level security level * * When I browse the file plan as admin * The I will see all three records * * When I browse the file plan as the test user * The I will see all three records */ doBehaviourDrivenTest(new BehaviourDrivenTest() { private NodeRef category; private NodeRef folder; private NodeRef record1; private NodeRef record2; private NodeRef record3; private List<ChildAssociationRef> resultsForAdmin; private List<ChildAssociationRef> resultsForTestUser; /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#given() */ @Override public void given() throws Exception { testUser = generate(); createPerson(testUser); filePlanRoleService.assignRoleToAuthority(filePlan, ROLE_ADMIN, testUser); securityClearanceService.setUserSecurityClearance(testUser, LEVEL1); category = filePlanService.createRecordCategory(filePlan, generate()); folder = recordFolderService.createRecordFolder(category, generate()); record1 = utils.createRecord(folder, generate()); record2 = utils.createRecord(folder, generate()); record3 = utils.createRecord(folder, generate()); contentClassificationService.classifyContent(propertiesDTO1, record1); contentClassificationService.classifyContent(propertiesDTO2, record2); } /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#when() */ @Override public void when() throws Exception { resultsForAdmin = browseAsAdmin(folder); resultsForTestUser = browseAsTestUser(folder); } /** * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#then() */ @Override public void then() throws Exception { doTestInTransaction(new Test<Void>() { @Override public Void run() { assertNotNull(resultsForAdmin); assertEquals(3, resultsForAdmin.size()); List<NodeRef> records = newArrayList(record1, record2, record3); assertTrue(records.contains(resultsForAdmin.get(0).getChildRef())); assertTrue(records.contains(resultsForAdmin.get(1).getChildRef())); assertTrue(records.contains(resultsForAdmin.get(2).getChildRef())); return null; } }); doTestInTransaction(new Test<Void>() { @Override public Void run() { assertNotNull(resultsForTestUser); assertEquals(3, resultsForTestUser.size()); List<NodeRef> records = newArrayList(record1, record2, record3); assertTrue(records.contains(resultsForTestUser.get(0).getChildRef())); assertTrue(records.contains(resultsForTestUser.get(1).getChildRef())); assertTrue(records.contains(resultsForTestUser.get(2).getChildRef())); return null; } }, testUser); } }); } }
lgpl-3.0
HyenaSoftware/IG-Dictionary
OldNorseGrammarEngine/src/test/scala/com/hyenawarrior/SoundexTest.scala
3952
package com.hyenawarrior import com.hyenawarrior.OldNorseGrammar.grammar.soundex.soundexCodeOf import org.junit.Assert.assertEquals import org.junit.Test /** * Created by HyenaWarrior on 2017.06.21.. */ class SoundexTest { // countOf(soundexKeys) * 5 <= counfOf(formsOfOneWord) val MAXIMUM_ALLOWED_KEY_DIVERSITY = 5 val transform: String => String = soundexCodeOf @Test def testDiversity(): Unit = { compareDiversiveSoundexCode( Array("ríða", "flúið", "verða", "úlfr") ) } @Test def testStrongVerbClass1(): Unit = { checkSoundexQuality( Array("ríða","ríðið", "ríðandi", "ríð", "ríðr", "ríðr", "ríðum","ríðið","ríða", "reið", "reiðst", "reið", "riðum","riðuð","riðu", "ríði", "ríðir", "ríði", "ríðum","ríðið","ríði", "riði", "riðir", "riði", "riðum","riðuð","riðu") ) } @Test def testStrongVerbClass2(): Unit = { checkSoundexQuality(Array("flúið","flýjandi", "flý", "flýrð", "flýr", "flýjum", "flýið", "flýja", "flúð", "flúðir", "flúði", "flúðum", "flúðuð", "flúðu", "flýi", "flýir", "flýi", "flýjum", "flýið", "flýi", "flýði", "flýðir", "flýði", "flýðum", "flýðuð", "flýðu") ) } @Test def testStrongVerbClass3(): Unit = { checkSoundexQuality(Array( "verða", "orðið", "verðandi", "verð", "verðr", "verðr", "verðum", "verðið", "verða", "varð", "varðst", "varð", "urðum", "urðuð", "urðu", "verði", "verðir", "verði", "verðum", "verðið", "verði", "yrði", "yrðir", "yrði", "yrðum", "yrðuð", "yrðu") ) } @Test def testNounStrongAMasc(): Unit = { checkSoundexQuality(Array( "úlfr", "úlf", "úlfi", "úlfs", "úlfrinn", "úlfinn", "úlfinum", "úlfsins", "úlfar", "úlfa", "úlfum", "úlfa", "úlfarnir", "úlfana", "úlfunum", "úlfanna") ) } @Test def testNounStrongAFem(): Unit = { checkSoundexQuality(Array( "á", "á", "á", "ár", "áin", "ána", "ánni", "árinnar", "á", "ár", "ám", "á", "árnar","árnar","ánum", "ánna") ) } @Test def testNounStrongARasc(): Unit = { checkSoundexQuality(Array( "maðr", "mann", "manni", "manns", "maðrinn", "mannin", "manninum", "mannsins", "menn", "menn", "mǫnnum", "manna", "menninir", "mennina","mǫnnunum", "mannanna") ) } @Test def testWeakVerbAStemWithConsonantAssimilation(): Unit = { // kalla - weak 2 verb checkSoundexQuality(Array( "kalla", "kallandi", "kallaðr", // ind "kalla", "kallar", "kallar", "kǫllum", "kallið", "kalla", // ind-pret "kallaða", "kallaðir", "kallaði", "kǫlluðum", "kǫlluðuð", "kǫlluðu", // subj "kalla", "kallir", "kallir", "kallim", "kallið", "kalli", // subj-pret "kallaða", "kallaðir", "kallaði", "kallaðim", "kallaðið", "kallaði" )) } def compareSoundexCode(forms: Array[String]): Unit = { val allForms = forms.map(x => transform(x) -> x) .groupBy{ case(k, _) => k } .mapValues(_.map(_._2)) // eliminate key duplication .map { case (k, v) => println(s"$k -> ${v.mkString("(", ", ", ")")}"); k } assertEquals(s"$allForms must have only one element", 1, allForms.size) } def checkSoundexQuality(forms: Array[String]): Unit = { val countOfDistinctForms = forms.toSet.size val allForms = forms.map(x => transform(x) -> x) .groupBy{ case(k, _) => k } .mapValues(_.map(_._2)) for((k,vs) <- allForms) { println(s"$k -> ${vs.mkString("(", ", ", ")")}") } println(s" assert(${allForms.keys.size} * $MAXIMUM_ALLOWED_KEY_DIVERSITY <= $countOfDistinctForms)") assert(allForms.keySet.size * MAXIMUM_ALLOWED_KEY_DIVERSITY <= countOfDistinctForms) } def compareDiversiveSoundexCode(forms: Array[String]): Unit = { val allForms = forms.map(transform).toSet assertEquals(forms.toSet.size, allForms.size) } }
lgpl-3.0
WarpOrganization/warp
audio/src/main/java/net/warpgame/engine/audio/command/source/PlaySourceCommand.java
722
package net.warpgame.engine.audio.command.source; import net.warpgame.engine.audio.AudioContext; import net.warpgame.engine.audio.AudioSourceProperty; import net.warpgame.engine.audio.command.Command; import java.util.List; import static org.lwjgl.openal.AL10.*; public class PlaySourceCommand implements Command { private AudioSourceProperty source; private List<AudioSourceProperty> playingSources; public PlaySourceCommand(AudioSourceProperty source, List<AudioSourceProperty> playingSources) { this.source = source; this.playingSources = playingSources; } @Override public void execute() { alSourcePlay(source.getId()); playingSources.add(source); } }
lgpl-3.0
armatys/hypergraphdb-android
hgdb-android/java/src/org/hypergraphdb/cache/PhantomRefAtomCache.java
11207
/* * This file is part of the HyperGraphDB source distribution. This is copyrighted * software. For permitted uses, licensing options and redistribution, please see * the LicensingInformation file at the root level of the distribution. * * Copyright (c) 2005-2010 Kobrix Software, Inc. All rights reserved. */ package org.hypergraphdb.cache; import java.lang.ref.ReferenceQueue; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.hypergraphdb.HGAtomAttrib; import org.hypergraphdb.HGAtomCache; import org.hypergraphdb.HGHandle; import org.hypergraphdb.HGPersistentHandle; import org.hypergraphdb.HGSystemFlags; import org.hypergraphdb.HyperGraph; import org.hypergraphdb.IncidenceSet; import org.hypergraphdb.event.HGAtomEvictEvent; import org.hypergraphdb.handle.DefaultManagedLiveHandle; import org.hypergraphdb.handle.HGLiveHandle; import org.hypergraphdb.handle.PhantomHandle; import org.hypergraphdb.handle.PhantomManagedHandle; import org.hypergraphdb.util.CloseMe; import org.hypergraphdb.util.WeakIdentityHashMap; public class PhantomRefAtomCache implements HGAtomCache { private HyperGraph graph = null; private HGCache<HGPersistentHandle, IncidenceSet> incidenceCache = null; // to be configured by the HyperGraph instance private final Map<HGPersistentHandle, PhantomHandle> liveHandles = new HashMap<HGPersistentHandle, PhantomHandle>(); private Map<Object, HGLiveHandle> atoms = new WeakIdentityHashMap<Object, HGLiveHandle>(); private Map<HGLiveHandle, Object> frozenAtoms = new IdentityHashMap<HGLiveHandle, Object>(); private ColdAtoms coldAtoms = new ColdAtoms(); public static final long DEFAULT_PHANTOM_QUEUE_POLL_INTERVAL = 500; private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); @SuppressWarnings("unchecked") private ReferenceQueue refQueue = new ReferenceQueue(); private PhantomCleanup phantomCleanupThread = new PhantomCleanup(); private long phantomQueuePollInterval = DEFAULT_PHANTOM_QUEUE_POLL_INTERVAL; private boolean closing = false; // // This handle class is used to read atoms during closing of the cache. Because // closing the HyperGraph may involve a lot of cleanup activity where it's necessary // to read atoms (mostly types) into main memory just temporarily, we need some // way to enact this temporarility. // private static class TempLiveHandle extends DefaultManagedLiveHandle { public TempLiveHandle(Object ref, HGPersistentHandle persistentHandle, byte flags) { super(ref, persistentHandle, flags, 0, 0); } public void setRef(Object ref) { this.ref = ref; } } private void processRefQueue() throws InterruptedException { PhantomHandle ref = (PhantomHandle)refQueue.remove(phantomQueuePollInterval); while (ref != null) { graph.getEventManager().dispatch(graph, new HGAtomEvictEvent(ref, ref.fetchRef())); lock.writeLock().lock(); try { liveHandles.remove(ref.getPersistent()); } finally { lock.writeLock().unlock(); } ref.clear(); synchronized (ref) { ref.notifyAll(); } ref = (PhantomHandle)refQueue.poll(); } } private class PhantomCleanup extends Thread { private boolean done; public void run() { PhantomHandle.returnEnqueued.set(Boolean.TRUE); for (done = false; !done; ) { try { processRefQueue(); } catch (InterruptedException exc) { Thread.currentThread().interrupt(); } catch (Throwable t) { System.err.println("PhantomCleanup thread caught an unexpected exception, stack trace follows:"); t.printStackTrace(System.err); } } PhantomHandle.returnEnqueued.set(Boolean.FALSE); } public void end() { this.done = true; } } public PhantomRefAtomCache() { phantomCleanupThread.setPriority(Thread.MAX_PRIORITY); phantomCleanupThread.setDaemon(true); phantomCleanupThread.start(); } public void setIncidenceCache(HGCache<HGPersistentHandle, IncidenceSet> cache) { this.incidenceCache= cache; } public HGCache<HGPersistentHandle, IncidenceSet> getIncidenceCache() { return incidenceCache; } public void setHyperGraph(HyperGraph hg) { this.graph = hg; phantomCleanupThread.setName("HGCACHE Cleanup - " + graph.getLocation()); } public HGLiveHandle atomAdded(HGPersistentHandle pHandle, Object atom, final HGAtomAttrib attrib) { return atomRead(pHandle, atom, attrib); } @SuppressWarnings("unchecked") public HGLiveHandle atomRead(HGPersistentHandle pHandle, Object atom, final HGAtomAttrib attrib) { if (closing) { HGLiveHandle result = new TempLiveHandle(atom, pHandle, attrib.getFlags()); atoms.put(atom, result); return result; } lock.writeLock().lock(); PhantomHandle h = null; try { h = liveHandles.get(pHandle); if (h != null) return h; if ( (attrib.getFlags() & HGSystemFlags.MANAGED) == 0) h = new PhantomHandle(atom, pHandle, attrib.getFlags(), refQueue); else h = new PhantomManagedHandle(atom, pHandle, attrib.getFlags(), refQueue, attrib.getRetrievalCount(), attrib.getLastAccessTime()); atoms.put(atom, h); liveHandles.put(pHandle, h); coldAtoms.add(atom); } finally { lock.writeLock().unlock(); } return h; } public HGLiveHandle atomRefresh(HGLiveHandle handle, Object atom, boolean replace) { if (closing) { if (handle instanceof PhantomHandle) ((PhantomHandle)handle).storeRef(atom); else ((TempLiveHandle)handle).setRef(atom); return handle; } if (handle == null) throw new NullPointerException("atomRefresh: handle is null."); lock.writeLock().lock(); try { PhantomHandle ph = (PhantomHandle)handle; PhantomHandle existing = liveHandles.get(ph.getPersistent()); if (existing != ph) { if (existing != null) { liveHandles.remove(existing.getPersistent()); atoms.remove(existing.getRef()); } ph.storeRef(atom); liveHandles.put(ph.getPersistent(), ph); atoms.put(atom, ph); coldAtoms.add(atom); } else if (ph.getRef() != atom) { atoms.remove(ph.getRef()); ph.storeRef(atom); atoms.put(atom, ph); } } finally { lock.writeLock().unlock(); } return handle; } public void close() { closing = true; phantomCleanupThread.end(); while (phantomCleanupThread.isAlive() ) try { phantomCleanupThread.join(); } catch (InterruptedException ex) { } PhantomHandle.returnEnqueued.set(Boolean.TRUE); try { processRefQueue(); } catch (InterruptedException ex) { } for (Iterator<Map.Entry<HGPersistentHandle, PhantomHandle>> i = liveHandles.entrySet().iterator(); i.hasNext(); ) { PhantomHandle h = i.next().getValue(); Object x = h.fetchRef(); graph.getEventManager().dispatch(graph, new HGAtomEvictEvent(h, x)); if (h.isEnqueued()) { h.clear(); } } PhantomHandle.returnEnqueued.set(Boolean.FALSE); frozenAtoms.clear(); incidenceCache.clear(); if (incidenceCache instanceof CloseMe) ((CloseMe)incidenceCache).close(); atoms.clear(); liveHandles.clear(); } public HGLiveHandle get(HGPersistentHandle pHandle) { lock.readLock().lock(); try { PhantomHandle h = liveHandles.get(pHandle); if (h != null) h.accessed(); return h; } finally { lock.readLock().unlock(); } } public HGLiveHandle get(Object atom) { lock.readLock().lock(); try { return atoms.get(atom); } finally { lock.readLock().unlock(); } } public void remove(HGHandle handle) { lock.writeLock().lock(); try { HGLiveHandle lhdl = null; if (handle instanceof HGLiveHandle) lhdl = (HGLiveHandle)handle; else lhdl = get(handle.getPersistent()); if (lhdl != null) { atoms.remove(lhdl.getRef()); // Shouldn't use clear here, since we might be gc-ing the ref! if (lhdl instanceof PhantomHandle) ((PhantomHandle)lhdl).storeRef(null); liveHandles.remove(lhdl.getPersistent()); } } finally { lock.writeLock().unlock(); } } public boolean isFrozen(HGLiveHandle handle) { synchronized (frozenAtoms) { return frozenAtoms.containsKey(handle); } } public void freeze(HGLiveHandle handle) { Object atom = handle.getRef(); if (atom != null) synchronized (frozenAtoms) { frozenAtoms.put(handle, atom); } } public void unfreeze(HGLiveHandle handle) { synchronized (frozenAtoms) { frozenAtoms.remove(handle); } } }
lgpl-3.0
gubi/AIRS
common/include/lib/bbb-api-php/legacy/demo4_helper.php
945
<? /* BigBlueButton - http://www.bigbluebutton.org Copyright (c) 2008-2009 by respective authors (see below). All rights reserved. BigBlueButton is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with BigBlueButton; if not, If not, see <http://www.gnu.org/licenses/>. Author: DJP <[email protected]> */ require('../includes/bbb-api.php'); echo '<?xml version="1.0"?>'."\r\n"; header('content-type: text/xml'); echo getMeetings(); ?>
lgpl-3.0
matyasb/phing
test/classes/phing/tasks/system/BlockForTaskTest.php
1661
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information please see * <http://phing.info>. */ require_once 'phing/BuildFileTest.php'; /** * Tests the BlockFor Task * * @author Siad Ardroumli <[email protected]> * @package phing.tasks.system */ class BlockForTaskTest extends BuildFileTest { public function setUp() { $this->configureProject( PHING_TEST_BASE . '/etc/tasks/system/BlockForTest.xml' ); } public function testConditionMet() { $this->executeTarget(__FUNCTION__); $this->assertInLogs('blockfor: condition was met'); } /** * @expectedException BuildTimeoutException */ public function testTimeout() { $this->executeTarget(__FUNCTION__); } }
lgpl-3.0
Wohlstand/libOPNMIDI
src/opnmidi_ptr.hpp
4835
/* * libOPNMIDI is a free Software MIDI synthesizer library with OPN2 (YM2612) emulation * * MIDI parser and player (Original code from ADLMIDI): Copyright (c) 2010-2014 Joel Yliluoma <[email protected]> * ADLMIDI Library API: Copyright (c) 2015-2021 Vitaly Novichkov <[email protected]> * * Library is based on the ADLMIDI, a MIDI player for Linux and Windows with OPL3 emulation: * http://iki.fi/bisqwit/source/adlmidi.html * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPNMIDI_PTR_HPP_THING #define OPNMIDI_PTR_HPP_THING #include <algorithm> // swap #include <stddef.h> #include <stdlib.h> /* Generic deleters for smart pointers */ template <class T> struct ADLMIDI_DefaultDelete { void operator()(T *x) { delete x; } }; template <class T> struct ADLMIDI_DefaultArrayDelete { void operator()(T *x) { delete[] x; } }; struct ADLMIDI_CDelete { void operator()(void *x) { free(x); } }; /* Safe unique pointer for C++98, non-copyable but swappable. */ template< class T, class Deleter = ADLMIDI_DefaultDelete<T> > class AdlMIDI_UPtr { T *m_p; public: explicit AdlMIDI_UPtr(T *p = NULL) : m_p(p) {} ~AdlMIDI_UPtr() { reset(); } void reset(T *p = NULL) { if(p != m_p) { if(m_p) { Deleter del; del(m_p); } m_p = p; } } void swap(AdlMIDI_UPtr &other) { std::swap(m_p, other.m_p); } T *get() const { return m_p; } T &operator*() const { return *m_p; } T *operator->() const { return m_p; } T &operator[](size_t index) const { return m_p[index]; } private: AdlMIDI_UPtr(const AdlMIDI_UPtr &); AdlMIDI_UPtr &operator=(const AdlMIDI_UPtr &); }; template <class T> void swap(AdlMIDI_UPtr<T> &a, AdlMIDI_UPtr<T> &b) { a.swap(b); } /** Unique pointer for arrays. */ template<class T> class AdlMIDI_UPtrArray : public AdlMIDI_UPtr< T, ADLMIDI_DefaultArrayDelete<T> > { public: explicit AdlMIDI_UPtrArray(T *p = NULL) : AdlMIDI_UPtr< T, ADLMIDI_DefaultArrayDelete<T> >(p) {} }; /** Unique pointer for C memory. */ template<class T> class AdlMIDI_CPtr : public AdlMIDI_UPtr< T, ADLMIDI_CDelete > { public: explicit AdlMIDI_CPtr(T *p = NULL) : AdlMIDI_UPtr< T, ADLMIDI_CDelete >(p) {} }; /* Shared pointer with non-atomic counter FAQ: Why not std::shared_ptr? Because of Android NDK now doesn't supports it */ template< class T, class Deleter = ADLMIDI_DefaultDelete<T> > class AdlMIDI_SPtr { T *m_p; size_t *m_counter; public: explicit AdlMIDI_SPtr(T *p = NULL) : m_p(p), m_counter(p ? new size_t(1) : NULL) {} ~AdlMIDI_SPtr() { reset(NULL); } AdlMIDI_SPtr(const AdlMIDI_SPtr &other) : m_p(other.m_p), m_counter(other.m_counter) { if(m_counter) ++*m_counter; } AdlMIDI_SPtr &operator=(const AdlMIDI_SPtr &other) { if(this == &other) return *this; reset(); m_p = other.m_p; m_counter = other.m_counter; if(m_counter) ++*m_counter; return *this; } void reset(T *p = NULL) { if(p != m_p) { if(m_p && --*m_counter == 0) { Deleter del; del(m_p); if(!p) { delete m_counter; m_counter = NULL; } } m_p = p; if(p) { if(!m_counter) m_counter = new size_t; *m_counter = 1; } } } T *get() const { return m_p; } T &operator*() const { return *m_p; } T *operator->() const { return m_p; } T &operator[](size_t index) const { return m_p[index]; } }; /** Shared pointer for arrays. */ template<class T> class AdlMIDI_SPtrArray : public AdlMIDI_SPtr< T, ADLMIDI_DefaultArrayDelete<T> > { public: explicit AdlMIDI_SPtrArray(T *p = NULL) : AdlMIDI_SPtr< T, ADLMIDI_DefaultArrayDelete<T> >(p) {} }; #endif //ADLMIDI_PTR_HPP_THING
lgpl-3.0
netide/WinFormsIsolation
Demo/DemoControlHost.cs
1244
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using WinFormsIsolation.Isolation; namespace WinFormsIsolation.Demo { public class DemoControlHost : IsolationHost { [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IsolationDemo OriginalDemo { get; set; } private bool _disposed; private IsolationDomain _domain; public DemoControlHost() { _domain = new IsolationDomain(); } protected override void Dispose(bool disposing) { if (!_disposed) { if (_domain != null) { _domain.Dispose(); _domain = null; } _disposed = true; } base.Dispose(disposing); } protected override IIsolationClient CreateWindow() { var demo = (IsolationDemo)_domain.CreateInstanceAndUnwrap( typeof(IsolationDemo).AssemblyQualifiedName ); return demo.CreateClient(OriginalDemo); } } }
lgpl-3.0
MagiciansArtificeTeam/Magicians-Artifice
src/main/java/magiciansartifice/main/items/tools/ItemDarkestBook.java
1246
package magiciansartifice.main.items.tools; import magiciansartifice.main.MagiciansArtifice; import magiciansartifice.main.core.client.guis.GuiHandler; import magiciansartifice.main.core.libs.ModInfo; import magiciansartifice.main.core.utils.registries.ItemRegistry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import java.util.List; /** * Created by Mitchellbrine on 2014. */ @SuppressWarnings({"unchecked", "rawtypes"}) public class ItemDarkestBook extends Item { public ItemDarkestBook() { this.setUnlocalizedName("evil.book"); this.setTextureName(ModInfo.MODID + ":tools/bookEvil"); this.setCreativeTab(MagiciansArtifice.tab); ItemRegistry.items.add(this); } @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { if (world.isRemote) { player.openGui(MagiciansArtifice.instance, GuiHandler.IDS.DarkestBook, world, 0, 0, 0); } return stack; } @Override public void addInformation(ItemStack stack, EntityPlayer player, List lore, boolean par4) { lore.add("by Grimnwaldor"); } }
lgpl-3.0
terge/crab-social
crab-base/src/test/java/vip/xioix/crabbase/ExampleUnitTest.java
396
package vip.xioix.crabbase; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
lgpl-3.0
Dschinghis-Kahn/eveapi
api/net/dschinghiskahn/eveapi/eve/characterinfo/EmploymentHistory.java
1118
package net.dschinghiskahn.eveapi.eve.characterinfo; import java.util.Date; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Root; @Root(name = "row") public class EmploymentHistory { @Attribute(name = "corporationID", required = false) private Long corporationId; @Attribute(required = false) private String corporationName; @Attribute(name = "recordID", required = false) private Long recordId; @Attribute(required = false) private Date startDate; public Long getCorporationId() { return corporationId; } public String getCorporationName() { return corporationName; } public Long getRecordId() { return recordId; } public Date getStartDate() { return startDate; } @Override public String toString() { return "EmploymentHistory [" + "corporationId = " + corporationId + ", " + "corporationName = " + corporationName + ", " + "recordId = " + recordId + ", " + "startDate = " + startDate + ", " + "]"; } }
lgpl-3.0
mikrosimage/rez
src/rez/packages_.py
20811
from rez.package_repository import package_repository_manager from rez.package_resources_ import PackageFamilyResource, PackageResource, \ VariantResource, package_family_schema, package_schema, variant_schema, \ package_release_keys from rez.package_serialise import dump_package_data from rez.utils.data_utils import cached_property from rez.utils.formatting import StringFormatMixin, StringFormatType from rez.utils.filesystem import is_subdirectory from rez.utils.schema import schema_keys from rez.utils.resources import ResourceHandle, ResourceWrapper from rez.exceptions import PackageMetadataError, PackageFamilyNotFoundError, \ ResourceError from rez.vendor.version.version import VersionRange from rez.vendor.version.requirement import VersionedObject from rez.serialise import load_from_file, FileFormat from rez.config import config from rez.system import system import os.path import sys #------------------------------------------------------------------------------ # package-related classes #------------------------------------------------------------------------------ class PackageRepositoryResourceWrapper(ResourceWrapper, StringFormatMixin): format_expand = StringFormatType.unchanged def validated_data(self): data = ResourceWrapper.validated_data(self) data = dict((k, v) for k, v in data.iteritems() if v is not None) return data class PackageFamily(PackageRepositoryResourceWrapper): """A package family. Note: Do not instantiate this class directly, instead use the function `iter_package_families`. """ keys = schema_keys(package_family_schema) def __init__(self, resource): _check_class(resource, PackageFamilyResource) super(PackageFamily, self).__init__(resource) def iter_packages(self): """Iterate over the packages within this family, in no particular order. Returns: `Package` iterator. """ repo = self.resource._repository for package in repo.iter_packages(self.resource): yield Package(package) class PackageBaseResourceWrapper(PackageRepositoryResourceWrapper): """Abstract base class for `Package` and `Variant`. """ @property def uri(self): return self.resource.uri @property def config(self): """Returns the config for this package. Defaults to global config if this package did not provide a 'config' section. """ return self.resource.config or config @cached_property def is_local(self): """Returns True if the package is in the local package repository""" local_repo = package_repository_manager.get_repository( self.config.local_packages_path) return (self.resource._repository.uid == local_repo.uid) def print_info(self, buf=None, format_=FileFormat.yaml, skip_attributes=None, include_release=False): """Print the contents of the package. Args: buf (file-like object): Stream to write to. format_ (`FileFormat`): Format to write in. skip_attributes (list of str): List of attributes to not print. include_release (bool): If True, include release-related attributes, such as 'timestamp' and 'changelog' """ data = self.validated_data().copy() # config is a special case. We only really want to show any config settings # that were in the package.py, not the entire Config contents that get # grafted onto the Package/Variant instance. However Variant has an empy # 'data' dict property, since it forwards data from its parent package. data.pop("config", None) if self.config: if isinstance(self, Package): config_dict = self.data.get("config") else: config_dict = self.parent.data.get("config") data["config"] = config_dict if not include_release: skip_attributes = list(skip_attributes or []) + list(package_release_keys) buf = buf or sys.stdout dump_package_data(data, buf=buf, format_=format_, skip_attributes=skip_attributes) class Package(PackageBaseResourceWrapper): """A package. Note: Do not instantiate this class directly, instead use the function `iter_packages` or `PackageFamily.iter_packages`. """ keys = schema_keys(package_schema) def __init__(self, resource): _check_class(resource, PackageResource) super(Package, self).__init__(resource) @cached_property def qualified_name(self): """Get the qualified name of the package. Returns: str: Name of the package with version, eg "maya-2016.1". """ o = VersionedObject.construct(self.name, self.version) return str(o) @cached_property def parent(self): """Get the parent package family. Returns: `PackageFamily`. """ repo = self.resource._repository family = repo.get_parent_package_family(self.resource) return PackageFamily(family) if family else None @cached_property def num_variants(self): return len(self.data.get("variants", [])) def iter_variants(self): """Iterate over the variants within this package, in index order. Returns: `Variant` iterator. """ repo = self.resource._repository for variant in repo.iter_variants(self.resource): yield Variant(variant) def get_variant(self, index=None): """Get the variant with the associated index. Returns: `Variant` object, or None if no variant with the given index exists. """ for variant in self.iter_variants(): if variant.index == index: return variant class Variant(PackageBaseResourceWrapper): """A package variant. Note: Do not instantiate this class directly, instead use the function `Package.iter_variants`. """ keys = schema_keys(variant_schema) keys.update(["index", "root", "subpath"]) def __init__(self, resource): _check_class(resource, VariantResource) super(Variant, self).__init__(resource) @cached_property def qualified_package_name(self): o = VersionedObject.construct(self.name, self.version) return str(o) @cached_property def qualified_name(self): """Get the qualified name of the variant. Returns: str: Name of the variant with version and index, eg "maya-2016.1[1]". """ idxstr = '' if self.index is None else str(self.index) return "%s[%s]" % (self.qualified_package_name, idxstr) @cached_property def parent(self): """Get the parent package. Returns: `Package`. """ repo = self.resource._repository package = repo.get_parent_package(self.resource) return Package(package) def get_requires(self, build_requires=False, private_build_requires=False): """Get the requirements of the variant. Args: build_requires (bool): If True, include build requirements. private_build_requires (bool): If True, include private build requirements. Returns: List of `Requirement` objects. """ requires = self.requires or [] if build_requires: requires = requires + (self.build_requires or []) if private_build_requires: requires = requires + (self.private_build_requires or []) return requires def install(self, path, dry_run=False, overrides=None): """Install this variant into another package repository. If the package already exists, this variant will be correctly merged into the package. If the variant already exists in this package, the existing variant is returned. Args: path (str): Path to destination package repository. dry_run (bool): If True, do not actually install the variant. In this mode, a `Variant` instance is only returned if the equivalent variant already exists in this repository; otherwise, None is returned. overrides (dict): Use this to change or add attributes to the installed variant. Returns: `Variant` object - the (existing or newly created) variant in the specified repository. If `dry_run` is True, None may be returned. """ repo = package_repository_manager.get_repository(path) resource = repo.install_variant(self.resource, dry_run=dry_run, overrides=overrides) if resource is None: return None elif resource is self.resource: return self else: return Variant(resource) class PackageSearchPath(object): """A list of package repositories. For example, $REZ_PACKAGES_PATH refers to a list of repositories. """ def __init__(self, packages_path): """Create a package repository list. Args: packages_path (list of str): List of package repositories. """ self.paths = packages_path def iter_packages(self, name, range_=None): """See `iter_packages`. Returns: `Package` iterator. """ for package in iter_packages(name=name, range_=range_, paths=self.paths): yield package def __contains__(self, package): """See if a package is in this list of repositories. Note: This does not verify the existance of the resource, only that the resource's repository is in this list. Args: package (`Package` or `Variant`): Package to search for. Returns: bool: True if the resource is in the list of repositories, False otherwise. """ return (package.resource._repository.uid in self._repository_uids) @cached_property def _repository_uids(self): uids = set() for path in self.paths: repo = package_repository_manager.get_repository(path) uids.add(repo.uid) return uids #------------------------------------------------------------------------------ # resource acquisition functions #------------------------------------------------------------------------------ def iter_package_families(paths=None): """Iterate over package families, in no particular order. Note that multiple package families with the same name can be returned. Unlike packages, families later in the searchpath are not hidden by earlier families. Args: paths (list of str, optional): paths to search for package families, defaults to `config.packages_path`. Returns: `PackageFamily` iterator. """ for path in (paths or config.packages_path): repo = package_repository_manager.get_repository(path) for resource in repo.iter_package_families(): yield PackageFamily(resource) def iter_packages(name, range_=None, paths=None): """Iterate over `Package` instances, in no particular order. Packages of the same name and version earlier in the search path take precedence - equivalent packages later in the paths are ignored. Packages are not returned in any specific order. Args: name (str): Name of the package, eg 'maya'. range_ (VersionRange or str): If provided, limits the versions returned to those in `range_`. paths (list of str, optional): paths to search for packages, defaults to `config.packages_path`. Returns: `Package` iterator. """ entries = _get_families(name, paths) seen = set() for repo, family_resource in entries: for package_resource in repo.iter_packages(family_resource): key = (package_resource.name, package_resource.version) if key in seen: continue seen.add(key) if range_: if isinstance(range_, basestring): range_ = VersionRange(range_) if package_resource.version not in range_: continue yield Package(package_resource) def get_package(name, version, paths=None): """Get an exact version of a package. Args: name (str): Name of the package, eg 'maya'. version (Version or str): Version of the package, eg '1.0.0' paths (list of str, optional): paths to search for package, defaults to `config.packages_path`. Returns: `Package` object, or None if the package was not found. """ if isinstance(version, basestring): range_ = VersionRange("==%s" % version) else: range_ = VersionRange.from_version(version, "==") it = iter_packages(name, range_, paths) try: return it.next() except StopIteration: return None def get_package_from_handle(package_handle): """Create a package given its handle (or serialized dict equivalent) Args: package_handle (`ResourceHandle` or dict): Resource handle, or equivalent serialized dict representation from ResourceHandle.to_dict Returns: `Package`. """ if isinstance(package_handle, dict): package_handle = ResourceHandle.from_dict(package_handle) package_resource = package_repository_manager.get_resource_from_handle(package_handle) package = Package(package_resource) return package def get_package_from_string(txt, paths=None): """Get a package given a string. Args: txt (str): String such as 'foo', 'bah-1.3'. paths (list of str, optional): paths to search for package, defaults to `config.packages_path`. Returns: `Package` instance, or None if no package was found. """ o = VersionedObject(txt) return get_package(o.name, o.version, paths=paths) def get_developer_package(path): """Load a developer package. A developer package may for example be a package.yaml or package.py in a user's source directory. Note: The resulting package has a 'filepath' attribute added to it, that does not normally appear on a `Package` object. A developer package is the only case where we know we can directly associate a 'package.*' file with a package - other packages can come from any kind of package repo, which may or may not associate a single file with a single package (or any file for that matter - it may come from a database). Args: path: Directory containing the package definition file. Returns: `Package` object. """ data = None for format_ in (FileFormat.py, FileFormat.yaml): filepath = os.path.join(path, "package.%s" % format_.extension) if os.path.isfile(filepath): data = load_from_file(filepath, format_) break if data is None: raise PackageMetadataError("No package definition file found at %s" % path) name = data.get("name") if name is None or not isinstance(name, basestring): raise PackageMetadataError( "Error in %r - missing or non-string field 'name'" % filepath) package = create_package(name, data) setattr(package, "filepath", filepath) return package def create_package(name, data): """Create a package given package data. Args: name (str): Package name. data (dict): Package data. Must conform to `package_maker.package_schema`. Returns: `Package` object. """ from rez.package_maker__ import PackageMaker maker = PackageMaker(name, data) return maker.get_package() def get_variant(variant_handle): """Create a variant given its handle (or serialized dict equivalent) Args: variant_handle (`ResourceHandle` or dict): Resource handle, or equivalent serialized dict representation from ResourceHandle.to_dict Returns: `Variant`. """ if isinstance(variant_handle, dict): variant_handle = ResourceHandle.from_dict(variant_handle) variant_resource = package_repository_manager.get_resource_from_handle(variant_handle) variant = Variant(variant_resource) return variant def get_last_release_time(name, paths=None): """Returns the most recent time this package was released. Note that releasing a variant into an already-released package is also considered a package release. Returns: int: Epoch time of last package release, or zero if this cannot be determined. """ entries = _get_families(name, paths) max_time = 0 for repo, family_resource in entries: time_ = repo.get_last_release_time(family_resource) if time_ == 0: return 0 max_time = max(max_time, time_) return max_time def get_completions(prefix, paths=None, family_only=False): """Get autocompletion options given a prefix string. Example: >>> get_completions("may") set(["maya", "maya_utils"]) >>> get_completions("maya-") set(["maya-2013.1", "maya-2015.0.sp1"]) Args: prefix (str): Prefix to match. paths (list of str): paths to search for packages, defaults to `config.packages_path`. family_only (bool): If True, only match package names, do not include version component. Returns: Set of strings, may be empty. """ op = None if prefix: if prefix[0] in ('!', '~'): if family_only: return set() op = prefix[0] prefix = prefix[1:] fam = None for ch in ('-', '@', '#'): if ch in prefix: if family_only: return set() fam = prefix.split(ch)[0] break words = set() if not fam: words = set(x.name for x in iter_package_families(paths=paths) if x.name.startswith(prefix)) if len(words) == 1: fam = iter(words).next() if family_only: return words if fam: it = iter_packages(fam, paths=paths) words.update(x.qualified_name for x in it if x.qualified_name.startswith(prefix)) if op: words = set(op + x for x in words) return words def get_latest_package(name, range_=None, paths=None, error=False): """Get the latest package for a given package name. Args: name (str): Package name. range_ (`VersionRange`): Version range to search within. paths (list of str, optional): paths to search for package families, defaults to `config.packages_path`. error (bool): If True, raise an error if no package is found. Returns: `Package` object, or None if no package is found. """ it = iter_packages(name, range_=range_, paths=paths) try: return max(it, key=lambda x: x.version) except ValueError: # empty sequence if error: raise PackageFamilyNotFoundError("No such package family %r" % name) return None def _get_families(name, paths=None): entries = [] for path in (paths or config.packages_path): repo = package_repository_manager.get_repository(path) family_resource = repo.get_package_family(name) if family_resource: entries.append((repo, family_resource)) return entries def _check_class(resource, cls): if not isinstance(resource, cls): raise ResourceError("Expected %s, got %s" % (cls.__name__, resource.__class__.__name__)) # Copyright 2013-2016 Allan Johns. # # This library is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. If not, see <http://www.gnu.org/licenses/>.
lgpl-3.0
yshmarov/myclass101
app/models/fiscal_period.rb
425
class FiscalPeriod < ActiveRecord::Base belongs_to :product belongs_to :event_group has_many :events, dependent: :destroy validates :event_group_id, presence: true validates :product_id, presence: true has_many :attendances, through: :events has_many :guests, through: :attendances accepts_nested_attributes_for :events, reject_if: proc { |attributes| attributes ['user_id'].blank? }, allow_destroy: true end
lgpl-3.0
ravep/ponfig
src/main/java/com/unit16/r/onion/util/SimulationClock.java
1269
package com.unit16.r.onion.util; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.joda.time.DateTime; import com.unit16.common.logback.MicrosConverter; import com.unit16.r.onion.Component; import com.unit16.r.onion.Ring; public class SimulationClock extends Clock implements Yield { long nanos; final long stopNanos; private ArrayList<Component> coldYield = new ArrayList<>(); public SimulationClock(Ring ring, DateTime start, DateTime stop) { super(ring, false); nanos = TimeUnit.MILLISECONDS.toNanos(start.getMillis()); stopNanos = TimeUnit.MILLISECONDS.toNanos(stop.getMillis()); } public boolean keepRunning() { return nanos < stopNanos; } @Override public void update() { assert nextScheduled > nanos; flushColdYield(); nanos = nextScheduled; MicrosConverter.updateTime(nanos); super.update(); } private void flushColdYield() { for(Component c : coldYield) { c.schedule(); } coldYield.clear(); } @Override protected void reschedule() { if(nanos < nextScheduled) { super.schedule(); } } @Override public long gmtNanos() { return nanos; } public void clearQueue() { actions.clear(); } @Override public void yield(Component c) { coldYield.add(c); } }
lgpl-3.0
moetang-arch/nekoq
service/mq/model.topic.go
4385
package mq import ( "sync" ) type Topic struct { topicID IdType deliveryLevel DeliveryLevelType queueList []*Queue queueMap map[IdType][]*Queue basicLock sync.Mutex topicInternalId int32 topicMessageIdGen *IdGen broker *Broker } type TopicOption struct { DeliveryLevel DeliveryLevelType } func (this *Broker) NewTopic(topicId IdType, option *TopicOption) (*Topic, error) { t := new(Topic) t.topicID = topicId t.queueList = []*Queue{} t.queueMap = make(map[IdType][]*Queue) switch option.DeliveryLevel { case AtMostOnce: t.deliveryLevel = AtMostOnce case AtLeastOnce: t.deliveryLevel = AtLeastOnce case ExactlyOnce: t.deliveryLevel = ExactlyOnce default: t.deliveryLevel = AtMostOnce } topicInternalId, err := this.GenNewInternalTopicId() if err != nil { return nil, err } t.topicMessageIdGen = NewIdGen(this.nodeId, topicInternalId) t.topicInternalId = topicInternalId t.broker = this err = this.addTopic(t) if err != nil { return nil, err } return t, nil } func (this *Broker) addTopic(topic *Topic) error { this.basicLock.Lock() defer this.basicLock.Unlock() if _, ok := this.topicMap[topic.topicID]; ok { return ErrTopicAlreadyExist } c := make(chan map[IdType]*Topic) go func() { newMap := make(map[IdType]*Topic) for k, v := range this.topicMap { newMap[k] = v } newMap[topic.topicID] = topic c <- newMap }() this.topicMap = <-c return nil } func (this *Broker) deleteTopic(topicId IdType) error { //TODO return nil } func (this *Topic) PublishMessage(req *Request, ctx *Ctx) error { tags := req.Header.Tags queueList := this.queueList // generate message id idgen := this.topicMessageIdGen messages := req.BatchMessage msgCnt := len(messages) for i := 0; i < msgCnt; i++ { var err error messages[i].MsgId, err = idgen.Next() if err != nil { return err } } m := make(map[int32]*Queue) for _, q := range queueList { //m[q.QueueInternalId] = q err := q.PublishMessage(req, ctx) if err != nil { return err } } if len(tags) != 0 { queueMap := this.queueMap for _, tag := range tags { queue, ok := queueMap[tag] if ok { for _, q := range queue { id := q.QueueInternalId _, ok := m[id] if !ok { m[q.QueueInternalId] = q err := q.PublishMessage(req, ctx) if err != nil { return err } } } } } } return nil } // at least once and exactly once // omit dup flag func (this *Topic) PublishMessageWithResponse(req *Request, ctx *Ctx) (Ack, error) { tags := req.Header.Tags queueList := this.queueList // generate message id idgen := this.topicMessageIdGen messages := req.BatchMessage msgCnt := len(messages) msgIds := make([]MessageId, msgCnt) for i := 0; i < msgCnt; i++ { var err error var id IdType id, err = idgen.Next() if err != nil { return EMPTY_MESSAGE_ID_LIST, err } messages[i].MsgId = id msgId := MessageId{ MsgId: id, OutId: messages[i].OutId, } msgIds[i] = msgId } m := make(map[int32]*Queue) for _, q := range queueList { //m[q.QueueInternalId] = q err := q.PublishMessage(req, ctx) if err != nil { return EMPTY_MESSAGE_ID_LIST, err } } if len(tags) != 0 { queueMap := this.queueMap for _, tag := range tags { queue, ok := queueMap[tag] if ok { for _, q := range queue { id := q.QueueInternalId _, ok := m[id] if !ok { m[q.QueueInternalId] = q err := q.PublishMessage(req, ctx) if err != nil { return EMPTY_MESSAGE_ID_LIST, err } } } } } } return Ack{ AckIdList: msgIds, }, nil } // exactly once // omit dup flag func (this *Topic) CommitMessages(req *MessageCommit, ctx *Ctx) (Ack, error) { tags := req.Header.Tags queueList := this.queueList m := make(map[int32]*Queue) for _, q := range queueList { //m[q.QueueInternalId] = q err := q.CommitMessages(req, ctx) if err != nil { return EMPTY_MESSAGE_ID_LIST, err } } if len(tags) != 0 { queueMap := this.queueMap for _, tag := range tags { queue, ok := queueMap[tag] if ok { for _, q := range queue { id := q.QueueInternalId _, ok := m[id] if !ok { m[q.QueueInternalId] = q err := q.CommitMessages(req, ctx) if err != nil { return EMPTY_MESSAGE_ID_LIST, err } } } } } } return req.Ack, nil }
lgpl-3.0
Jaspersoft/js-android-sdk
core/src/main/java/com/jaspersoft/android/sdk/service/report/ReportOptionsMapper5_6Plus.java
1326
/* * Copyright (C) 2016 TIBCO Jaspersoft Corporation. All rights reserved. * http://community.jaspersoft.com/project/mobile-sdk-android * * Unless you have purchased a commercial license agreement from TIBCO Jaspersoft, * the following license terms apply: * * This program is part of TIBCO Jaspersoft Mobile SDK for Android. * * TIBCO Jaspersoft Mobile SDK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TIBCO Jaspersoft Mobile SDK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with TIBCO Jaspersoft Mobile SDK for Android. If not, see * <http://www.gnu.org/licenses/lgpl>. */ package com.jaspersoft.android.sdk.service.report; /** * @author Tom Koptel * @since 2.3 */ final class ReportOptionsMapper5_6Plus extends ReportOptionsMapper { protected ReportOptionsMapper5_6Plus(String baseUrl) { super(baseUrl); } }
lgpl-3.0
advanced-online-marketing/AOM
vendor/facebook/php-business-sdk/src/FacebookAds/Object/LeadgenForm.php
5298
<?php /** * Copyright (c) 2015-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to * use, copy, modify, and distribute this software in source code or binary * form for use in connection with the web services and APIs provided by * Facebook. * * As with any software that integrates with the Facebook platform, your use * of this software is subject to the Facebook Developer Principles and * Policies [http://developers.facebook.com/policy/]. This copyright notice * shall be included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ namespace FacebookAds\Object; use FacebookAds\ApiRequest; use FacebookAds\Cursor; use FacebookAds\Http\RequestInterface; use FacebookAds\TypeChecker; use FacebookAds\Object\Fields\LeadgenFormFields; use FacebookAds\Object\Values\LeadgenFormLocaleValues; use FacebookAds\Object\Values\LeadgenFormStatusValues; /** * This class is auto-generated. * * For any issues or feature requests related to this class, please let us know * on github and we'll fix in our codegen framework. We'll not be able to accept * pull request for this class. * */ class LeadgenForm extends AbstractCrudObject { /** * @deprecated getEndpoint function is deprecated */ protected function getEndpoint() { return 'leadgen_forms'; } /** * @return LeadgenFormFields */ public static function getFieldsEnum() { return LeadgenFormFields::getInstance(); } protected static function getReferencedEnums() { $ref_enums = array(); $ref_enums['Status'] = LeadgenFormStatusValues::getInstance()->getValues(); $ref_enums['Locale'] = LeadgenFormLocaleValues::getInstance()->getValues(); return $ref_enums; } public function getLeads(array $fields = array(), array $params = array(), $pending = false) { $this->assureId(); $param_types = array( ); $enums = array( ); $request = new ApiRequest( $this->api, $this->data['id'], RequestInterface::METHOD_GET, '/leads', new Lead(), 'EDGE', Lead::getFieldsEnum()->getValues(), new TypeChecker($param_types, $enums) ); $request->addParams($params); $request->addFields($fields); return $pending ? $request : $request->execute(); } public function getTestLeads(array $fields = array(), array $params = array(), $pending = false) { $this->assureId(); $param_types = array( ); $enums = array( ); $request = new ApiRequest( $this->api, $this->data['id'], RequestInterface::METHOD_GET, '/test_leads', new Lead(), 'EDGE', Lead::getFieldsEnum()->getValues(), new TypeChecker($param_types, $enums) ); $request->addParams($params); $request->addFields($fields); return $pending ? $request : $request->execute(); } public function createTestLead(array $fields = array(), array $params = array(), $pending = false) { $this->assureId(); $param_types = array( 'custom_disclaimer_responses' => 'list<Object>', 'field_data' => 'list<Object>', ); $enums = array( ); $request = new ApiRequest( $this->api, $this->data['id'], RequestInterface::METHOD_POST, '/test_leads', new Lead(), 'EDGE', Lead::getFieldsEnum()->getValues(), new TypeChecker($param_types, $enums) ); $request->addParams($params); $request->addFields($fields); return $pending ? $request : $request->execute(); } public function getSelf(array $fields = array(), array $params = array(), $pending = false) { $this->assureId(); $param_types = array( ); $enums = array( ); $request = new ApiRequest( $this->api, $this->data['id'], RequestInterface::METHOD_GET, '/', new LeadgenForm(), 'NODE', LeadgenForm::getFieldsEnum()->getValues(), new TypeChecker($param_types, $enums) ); $request->addParams($params); $request->addFields($fields); return $pending ? $request : $request->execute(); } public function updateSelf(array $fields = array(), array $params = array(), $pending = false) { $this->assureId(); $param_types = array( 'status' => 'status_enum', ); $enums = array( 'status_enum' => LeadgenFormStatusValues::getInstance()->getValues(), ); $request = new ApiRequest( $this->api, $this->data['id'], RequestInterface::METHOD_POST, '/', new LeadgenForm(), 'NODE', LeadgenForm::getFieldsEnum()->getValues(), new TypeChecker($param_types, $enums) ); $request->addParams($params); $request->addFields($fields); return $pending ? $request : $request->execute(); } }
lgpl-3.0
islog/liblogicalaccess
plugins/logicalaccess/plugins/readers/stidprg/readercardadapters/stidprgbufferparser.hpp
381
#pragma once #include <logicalaccess/readerproviders/circularbufferparser.hpp> #include <logicalaccess/plugins/readers/stidprg/lla_readers_stidprg_api.hpp> namespace logicalaccess { class LLA_READERS_STIDPRG_API STidPRGBufferParser : public CircularBufferParser { public: ByteVector getValidBuffer(boost::circular_buffer<unsigned char> &circular_buffer) override; }; }
lgpl-3.0
saertisru/code_expl
src/main/java/DAO/PersonDAO.java
649
package DAO; import Entity.Person; import org.hibernate.Session; import org.hibernate.cfg.AnnotationConfiguration; import utils.HibernateUtil; import java.util.List; /** * Created with IntelliJ IDEA. * User: shushkov * Date: 02.12.14 * Time: 10:13 * To change this template use File | Settings | File Templates. */ public class PersonDAO { public List<Person> getAll(){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List<Person> result = session.createQuery("from Person").list(); session.getTransaction().commit(); return result; } }
lgpl-3.0
syakuis/php-mei-bak
modules/install/_globals.php
675
<?php if (!defined("__SYAKU__")) exit; ?> <?php $GV['_INSTALL_']['MODULE'] = 'install'; $GV['_INSTALL_']['TITLE'] = '설치'; $GV['_INSTALL_']['BRIEF'] = ''; $GV['_INSTALL_']['SINGLE'] = true; $GV['_INSTALL_']['MODULE_PATH'] = _MODULES_PATH_ . '/' . $GV['_INSTALL_']['MODULE']; $GV['_INSTALL_']['MODULE_R_PATH'] = _MODULES_R_PATH_ . '/' . $GV['_INSTALL_']['MODULE']; require_once "{$GV['_INSTALL_']['MODULE_PATH']}/cls/install.class.php"; require_once "{$GV['_INSTALL_']['MODULE_PATH']}/cls/install.dao.php"; require_once "{$GV['_INSTALL_']['MODULE_PATH']}/cls/install.view.php"; require_once "{$GV['_INSTALL_']['MODULE_PATH']}/cls/install.controller.php"; ?>
lgpl-3.0
CarlBarr/Simulador-2D
simulador/Funcion_Arcocoseno.java
1034
package simulador; public class Funcion_Arcocoseno extends Funcion { public Funcion_Arcocoseno() { super("arcocoseno"); } public TiposDeDatos ejecutar(Objeto objetoOrigen, TiposDeDatos datos[]) { Mensaje.imprimir("Ejecutando la función " + this.obtenerNombre(), Mensaje.TRAZA); if(datos.length != 1) { Mensaje.imprimir("Se esperaba 1 argumento pero se recivieron " + datos.length + "argumentos", Mensaje.ERROR); return null; } float valor; if(datos[0] instanceof Entero) valor = ((Entero)datos[0]).obtenerDato(); else if(datos[0] instanceof Decimal) valor =((Decimal)datos[0]).obtenerDato(); else { Mensaje.imprimir("Tipo de dato invalido, se esperava un numero en la funcion " + this.obtenerNombre(), Mensaje.ERROR); return null; } return new Decimal(Math.toDegrees(Math.acos(valor))); } @Override public String tipoDeDato() { return "arcocoseno"; } @Override public String toString() { return "Funcion: " + this.tipoDeDato() + ", Nombre: " + this.obtenerNombre(); } }
lgpl-3.0
MxSIG/TableAliasV60
TableAliasV60/src/main/java/tablealias/xmlaccess/AliasDataConfigReader.java
1526
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tablealias.xmlaccess; import java.io.File; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import tablealias.xmldata.Document; /** * * @author INEGI */ public class AliasDataConfigReader<T> extends AbstractXmlReader<T> { private List<T> data; private final String path; public AliasDataConfigReader(File xmlFile, String path) { super(xmlFile); this.path = path + "xml" + File.separatorChar; } private T getDocument(Element el) { String fileName = getTextValue(el, "nombre"); Document doc = new Document(fileName); File f = new File(path + fileName); if(f.exists()) doc.setFile(f); else System.out.println("no se encontro archivo " + fileName + " en " + path); return (T) doc; } @Override protected List<T> readDocumentStructure() { Element docEle = dom.getDocumentElement(); NodeList nl = docEle.getElementsByTagName("document"); data = new ArrayList<T>(); if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { Element el = (Element) nl.item(i); //"buscable = " + buscable); Document doc = (Document) getDocument(el); data.add((T) doc); } } return data; } }
lgpl-3.0
kveratis/GameCode4
Source/GCC4/3rdParty/luaplus51-all/Src/Modules/cgilua/examples/cgilua/config.lua
1134
-- CGILua user configuration file -- $Id: config.lua,v 1.1 2008/06/30 14:30:00 carregal Exp $ -- Looks for a Lua script in the web directory with the same name as -- the executable -- Useful for shorter URLs, just be careful with an eventual name clashing -- when using this option -- cgilua.use_executable_name = true -- Enables CGILua authentication -- cgilua.doif (CGILUA_CONF.."/authentication_conf.lua") -- Emulating old behavior loading file "env.lua" from the script's directory --[[ cgilua.addopenfunction (function () cgilua.doif ("env.lua") end) --]] -- Basic configuration for using sessions --[[ require"cgilua.session" cgilua.session.setsessiondir (CGILUA_TMP) -- The following function must be called by every script that needs session. local already_enabled = false function cgilua.enablesession () if already_enabled then return else already_enabled = true end cgilua.session.open () cgilua.addclosefunction (cgilua.session.close) end --]] -- Optional compatibility values -- cgilua.preprocess = cgilua.handlelp -- cgilua.includehtml = cgilua.lp.include
lgpl-3.0
nos3/aimeos-core
lib/mwlib/src/MW/Setup/DBSchema/Pgsql.php
5732
<?php /** * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0 * @copyright Aimeos (aimeos.org), 2016 * @package MW * @subpackage Setup */ namespace Aimeos\MW\Setup\DBSchema; /** * Implements querying the PostgreSQL database * * @package MW * @subpackage Setup */ class Pgsql extends \Aimeos\MW\Setup\DBSchema\InformationSchema { /** * Checks if the given table exists in the database. * * @param string $tablename Name of the database table * @return boolean True if the table exists, false if not */ public function tableExists( $tablename ) { $sql = " SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'public' AND TABLE_NAME = ? "; $stmt = $this->getConnection()->create( $sql ); $stmt->bind( 1, $tablename ); $result = $stmt->execute(); if( $result->fetch() !== false ) { return true; } return false; } /** * Checks if the given sequence exists in the database. * * @param string $seqname Name of the database sequence * @return boolean True if the sequence exists, false if not */ public function sequenceExists( $seqname ) { $sql = " SELECT SEQUENCE_NAME FROM INFORMATION_SCHEMA.SEQUENCES WHERE SEQUENCE_SCHEMA = 'public' AND SEQUENCE_NAME = ? "; $stmt = $this->getConnection()->create( $sql ); $stmt->bind( 1, $seqname ); $result = $stmt->execute(); if( $result->fetch() !== false ) { return true; } return false; } /** * Checks if the given constraint exists for the specified table in the database. * * @param string $tablename Name of the database table * @param string $constraintname Name of the database table constraint * @return boolean True if the constraint exists, false if not */ public function constraintExists( $tablename, $constraintname ) { $sql = " SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = 'public' AND TABLE_NAME = ? AND CONSTRAINT_NAME = ? "; $stmt = $this->getConnection()->create( $sql ); $stmt->bind( 1, $tablename ); $stmt->bind( 2, $constraintname ); $result = $stmt->execute(); if( $result->fetch() !== false ) { return true; } $sql = " SELECT indexname FROM pg_indexes WHERE schemaname = 'public' AND tablename = ? AND indexname = ? "; $stmt = $this->getConnection()->create( $sql ); $stmt->bind( 1, $tablename ); $stmt->bind( 2, $constraintname ); $result = $stmt->execute(); if( $result->fetch() !== false ) { return true; } return false; } /** * Checks if the given column exists for the specified table in the database. * * @param string $tablename Name of the database table * @param string $columnname Name of the table column * @return boolean True if the column exists, false if not */ public function columnExists( $tablename, $columnname ) { $sql = " SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'public' AND TABLE_NAME = ? AND COLUMN_NAME = ? "; $stmt = $this->getConnection()->create( $sql ); $stmt->bind( 1, $tablename ); $stmt->bind( 2, $columnname ); $result = $stmt->execute(); if( $result->fetch() !== false ) { return true; } return false; } /** * Checks if the given index (not foreign keys, primary or unique constraints) exists in the database. * * @param string $tablename Name of the database table * @param string $indexname Name of the database index * @return boolean True if the index exists, false if not */ public function indexExists( $tablename, $indexname ) { $sql = " SELECT indexname FROM pg_indexes WHERE schemaname = 'public' AND tablename = ? AND indexname = ? "; $stmt = $this->getConnection()->create( $sql ); $stmt->bind( 1, $tablename ); $stmt->bind( 2, $indexname ); $result = $stmt->execute(); if( $result->fetch() !== false ) { return true; } return false; } /** * Returns an object containing the details of the column. * * @param string $tablename Name of the database table * @param string $columnname Name of the table column * @return \Aimeos\MW\Setup\DBSchema\Column\Iface Object which contains the details */ public function getColumnDetails( $tablename, $columnname ) { $sql = " SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'public' AND TABLE_NAME = ? AND COLUMN_NAME = ? "; $stmt = $this->getConnection()->create( $sql ); $stmt->bind( 1, $tablename ); $stmt->bind( 2, $columnname ); $result = $stmt->execute(); if( ( $record = $result->fetch() ) === false ) { throw new \Aimeos\MW\Setup\Exception( sprintf( 'Unknown column "%1$s" in table "%2$s"', $columnname, $tablename ) ); } return $this->createColumnItem( $record ); } /** * Creates a new column item using the columns of the information_schema.columns. * * @param array $record Associative array with column details * @return \Aimeos\MW\Setup\DBSchema\Column\Iface Column item */ protected function createColumnItem( array $record = array() ) { switch( $record['data_type'] ) { case 'character varying': $type = 'varchar'; break; default: $type = $record['data_type']; } $length = ( isset( $record['character_maximum_length'] ) ? $record['character_maximum_length'] : $record['numeric_precision'] ); $default = ( preg_match( '/^\'(.*)\'::.+$/', $record['column_default'], $match ) === 1 ? $match[1] : $record['column_default'] ); return new \Aimeos\MW\Setup\DBSchema\Column\Item( $record['table_name'], $record['column_name'], $type, $length, $default, $record['is_nullable'], $record['collation_name'] ); } }
lgpl-3.0
qrooel/madison_square
design/_js_panel/core/init.js
996
var aoQuickAccessPossibilites; $(document).ready(function() { $.datepicker.regional['pl'] = GFormDate.Language; $.datepicker.setDefaults($.datepicker.regional['pl']); $('.block').GBlock(); $('.box').GBox(); $('select').GSelect(); $('#message-bar').GMessageBar(); if (aoQuickAccessPossibilites == undefined) { aoQuickAccessPossibilites = []; } $('#quick-access').GQuickAccess({ aoPossibilities: aoQuickAccessPossibilites }); $('#navigation').GMenu(); $('.simple-stats .tabs').tabs({ fx: { opacity: 'toggle', duration: 75 } }); $('.scrollable-tabs').GScrollableTabs(); GCore.Init(); GLanguageSelector(); GViewSelector(); $('.order-notes').tabs(); $('#navigation > li > ul > li > ul > li.active').parent().parent().parent().parent().addClass('active'); $('#navigation > li > ul > li.active').parent().parent().addClass('active'); $('#navigation > li > ul > li.active').parent().addClass('active'); });
lgpl-3.0
matecat/MateCat
public/js/cat_source/es6/api/getGlossaryForSegment/index.js
40
export * from './getGlossaryForSegment'
lgpl-3.0
FabriceSalvaire/sphinx-microdata
setup.py
1052
# -*- coding: utf-8 -*- from setuptools import setup, find_packages requires = ['Sphinx>=0.6'] setup( name='sphinxcontrib-microdata', version='0.1', url='http://bitbucket.org/birkenfeld/sphinx-contrib', download_url='http://pypi.python.org/pypi/sphinxcontrib-microdata', license='LGPL v3', author='Fabrice Salvaire', author_email='[email protected]', description='Sphinx "microdata" extension', long_description=open('README.rst').read(), zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
lgpl-3.0
oleneveu/SharpKit-SDK
Defs/Html/generated/svg/SVGFEMergeNodeElement.cs
3249
/******************************************************************************************************* This file was auto generated with the tool "WebIDLParser" Content was generated from IDL file: http://trac.webkit.org/browser/trunk/Source/WebCore/svg/SVGFEMergeNodeElement.idl PLEASE DO *NOT* MODIFY THIS FILE! This file will be overridden next generation. If you need changes: - All classes marked as "partial". Use the custom.cs in the root folder, to extend the classes. - or regenerate the project with the newest IDL files. - or modifiy the WebIDLParser tool itself. ******************************************************************************************************** Copyright (C) 2013 Sebastian Loncar, Web: http://loncar.de Copyright (C) 2009 Apple Inc. All Rights Reserved. MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************************************/ using System; namespace SharpKit.Html.svg { using SharpKit.JavaScript; using SharpKit.Html.fileapi; using SharpKit.Html.html.shadow; using SharpKit.Html.html.track; using SharpKit.Html.inspector; using SharpKit.Html.loader.appcache; using SharpKit.Html.battery; using SharpKit.Html.filesystem; using SharpKit.Html.gamepad; using SharpKit.Html.geolocation; using SharpKit.Html.indexeddb; using SharpKit.Html.intents; using SharpKit.Html.mediasource; using SharpKit.Html.mediastream; using SharpKit.Html.navigatorcontentutils; using SharpKit.Html.networkinfo; using SharpKit.Html.notifications; using SharpKit.Html.proximity; using SharpKit.Html.quota; using SharpKit.Html.speech; using SharpKit.Html.vibration; using SharpKit.Html.webaudio; using SharpKit.Html.webdatabase; using SharpKit.Html.plugins; using SharpKit.Html.storage; using SharpKit.Html.svg; using SharpKit.Html.workers; [JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "SVGFEMergeNodeElement")] public partial class SvgFEMergeNodeElement : SvgElement { [JsMethod(OmitParanthesis = true, OmitNewOperator = true, Name = "document.createElement('femergenode')")] public SvgFEMergeNodeElement() {} public SvgAnimatedString in1 {get; set; } } }
lgpl-3.0
SonarSource/sonarqube
server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/gitlab/SearchGitlabReposAction.java
8445
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.almintegration.ws.gitlab; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.stream.Collectors; import org.sonar.alm.client.gitlab.GitlabHttpClient; import org.sonar.alm.client.gitlab.Project; import org.sonar.alm.client.gitlab.ProjectList; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations; import org.sonarqube.ws.AlmIntegrations.GitlabRepository; import org.sonarqube.ws.Common.Paging; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class SearchGitlabReposAction implements AlmIntegrationsWsAction { private static final String PARAM_ALM_SETTING = "almSetting"; private static final String PARAM_PROJECT_NAME = "projectName"; private static final int DEFAULT_PAGE_SIZE = 20; private static final int MAX_PAGE_SIZE = 500; private final DbClient dbClient; private final UserSession userSession; private final GitlabHttpClient gitlabHttpClient; public SearchGitlabReposAction(DbClient dbClient, UserSession userSession, GitlabHttpClient gitlabHttpClient) { this.dbClient = dbClient; this.userSession = userSession; this.gitlabHttpClient = gitlabHttpClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("search_gitlab_repos") .setDescription("Search the GitLab projects.<br/>" + "Requires the 'Create Projects' permission") .setPost(false) .setSince("8.5") .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("ALM setting key"); action.createParam(PARAM_PROJECT_NAME) .setRequired(false) .setMaximumLength(200) .setDescription("Project name filter"); action.addPagingParams(DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE); action.setResponseExample(getClass().getResource("search_gitlab_repos.json")); } @Override public void handle(Request request, Response response) { AlmIntegrations.SearchGitlabReposWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private AlmIntegrations.SearchGitlabReposWsResponse doHandle(Request request) { String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String projectName = request.param(PARAM_PROJECT_NAME); int pageNumber = request.mandatoryParamAsInt("p"); int pageSize = request.mandatoryParamAsInt("ps"); try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null"); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("ALM Setting '%s' not found", almSettingKey))); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); String personalAccessToken = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found")); String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "ALM url cannot be null"); ProjectList gitlabProjectList = gitlabHttpClient .searchProjects(gitlabUrl, personalAccessToken, projectName, pageNumber, pageSize); Map<String, ProjectKeyName> sqProjectsKeyByGitlabProjectId = getSqProjectsKeyByGitlabProjectId(dbSession, almSettingDto, gitlabProjectList); List<GitlabRepository> gitlabRepositories = gitlabProjectList.getProjects().stream() .map(project -> toGitlabRepository(project, sqProjectsKeyByGitlabProjectId)) .collect(toList()); Paging.Builder pagingBuilder = Paging.newBuilder() .setPageIndex(gitlabProjectList.getPageNumber()) .setPageSize(gitlabProjectList.getPageSize()); Integer gitlabProjectListTotal = gitlabProjectList.getTotal(); if (gitlabProjectListTotal != null) { pagingBuilder.setTotal(gitlabProjectListTotal); } return AlmIntegrations.SearchGitlabReposWsResponse.newBuilder() .addAllRepositories(gitlabRepositories) .setPaging(pagingBuilder.build()) .build(); } } private Map<String, ProjectKeyName> getSqProjectsKeyByGitlabProjectId(DbSession dbSession, AlmSettingDto almSettingDto, ProjectList gitlabProjectList) { Set<String> gitlabProjectIds = gitlabProjectList.getProjects().stream().map(Project::getId).map(String::valueOf) .collect(toSet()); Map<String, ProjectAlmSettingDto> projectAlmSettingDtos = dbClient.projectAlmSettingDao() .selectByAlmSettingAndRepos(dbSession, almSettingDto, gitlabProjectIds) .stream().collect(Collectors.toMap(ProjectAlmSettingDto::getProjectUuid, Function.identity())); return dbClient.projectDao().selectByUuids(dbSession, projectAlmSettingDtos.keySet()) .stream() .collect(Collectors.toMap(projectDto -> projectAlmSettingDtos.get(projectDto.getUuid()).getAlmRepo(), p -> new ProjectKeyName(p.getKey(), p.getName()), resolveNameCollisionOperatorByNaturalOrder())); } private static BinaryOperator<ProjectKeyName> resolveNameCollisionOperatorByNaturalOrder() { return (a, b) -> b.key.compareTo(a.key) > 0 ? a : b; } private static GitlabRepository toGitlabRepository(Project project, Map<String, ProjectKeyName> sqProjectsKeyByGitlabProjectId) { String name = project.getName(); String pathName = removeLastOccurrenceOfString(project.getNameWithNamespace(), " / " + name); String slug = project.getPath(); String pathSlug = removeLastOccurrenceOfString(project.getPathWithNamespace(), "/" + slug); GitlabRepository.Builder builder = GitlabRepository.newBuilder() .setId(project.getId()) .setName(name) .setPathName(pathName) .setSlug(slug) .setPathSlug(pathSlug) .setUrl(project.getWebUrl()); String projectIdAsString = String.valueOf(project.getId()); Optional.ofNullable(sqProjectsKeyByGitlabProjectId.get(projectIdAsString)) .ifPresent(p -> builder .setSqProjectKey(p.key) .setSqProjectName(p.name)); return builder.build(); } private static String removeLastOccurrenceOfString(String string, String stringToRemove) { StringBuilder resultString = new StringBuilder(string); int index = resultString.lastIndexOf(stringToRemove); if (index > -1) { resultString.delete(index, string.length() + index); } return resultString.toString(); } static class ProjectKeyName { String key; String name; ProjectKeyName(String key, String name) { this.key = key; this.name = name; } } }
lgpl-3.0
virtudraft/bbbx
core/components/bbbx/model/bbbx/mysql/bbbxmeetingsusergroups.map.inc.php
1968
<?php $xpdo_meta_map['bbbxMeetingsUsergroups']= array ( 'package' => 'bbbx', 'version' => '1.1', 'table' => 'meetings_usergroups', 'extends' => 'xPDOSimpleObject', 'fields' => array ( 'meeting_id' => NULL, 'usergroup_id' => NULL, 'enroll' => 'viewer', 'started_on' => NULL, 'ended_on' => NULL, 'is_forced_to_end' => 0, 'is_canceled' => 0, ), 'fieldMeta' => array ( 'meeting_id' => array ( 'dbtype' => 'int', 'precision' => '10', 'attributes' => 'unsigned', 'phptype' => 'integer', 'null' => false, 'index' => 'index', ), 'usergroup_id' => array ( 'dbtype' => 'int', 'precision' => '10', 'attributes' => 'unsigned', 'phptype' => 'integer', 'null' => false, ), 'enroll' => array ( 'dbtype' => 'varchar', 'precision' => '50', 'phptype' => 'string', 'null' => false, 'default' => 'viewer', ), 'started_on' => array ( 'dbtype' => 'int', 'precision' => '10', 'attributes' => 'unsigned', 'phptype' => 'integer', 'null' => true, ), 'ended_on' => array ( 'dbtype' => 'int', 'precision' => '10', 'attributes' => 'unsigned', 'phptype' => 'integer', 'null' => true, ), 'is_forced_to_end' => array ( 'dbtype' => 'tinyint', 'precision' => '1', 'attributes' => 'unsigned', 'phptype' => 'integer', 'null' => false, 'default' => 0, ), 'is_canceled' => array ( 'dbtype' => 'tinyint', 'precision' => '1', 'attributes' => 'unsigned', 'phptype' => 'integer', 'null' => false, 'default' => 0, ), ), 'aggregates' => array ( 'Meetings' => array ( 'class' => 'bbbxMeetings', 'local' => 'meeting_id', 'foreign' => 'id', 'cardinality' => 'one', 'owner' => 'foreign', ), ), );
lgpl-3.0
luigigenovese/libconv
DSL/lib/libconv/system.rb
4249
module LibConv class OrderedTransitions def self.inverse( tr ) if tr == :shrink :grow elsif tr == :grow :shrink else tr end end def initialize(*args) @tr = args.last @states = args[0..-2] @transitions = Hash::new { |hash, key| hash[key] = {} } @states[0..-2].each_with_index { |s, i| @states[(i+1)..-1].each { |d| @transitions[s][d] = @tr } } reverse_tr = OrderedTransitions.inverse(@tr) reverse_states = @states.reverse reverse_states[0..-2].each_with_index { |s, i| reverse_states[(i+1)..-1].each { |d| @transitions[s][d] = reverse_tr } } end def transition(source, destination) return @transitions[source][destination] end end class System attr_reader :reference_dimensions attr_reader :reference_space attr_reader :boundary_conditions attr_reader :grow_direction attr_reader :dimension attr_reader :spaces attr_reader :wavelet_family def initialize(reference_dimensions, boundary_conditions, reference_space, options = {}) @reference_dimensions = reference_dimensions @dimension = reference_dimensions.length @spaces = options.fetch(:spaces, { s1: S1, s0: S0, r: R }) @wavelet_family = options.fetch(:wavelet_family, "SYM8") @reference_space = reference_space raise "Invalid reference dimensions #{reference_dimensions} in #{reference_space}!" if [:s1, :s0].include?( reference_space ) && !@reference_dimensions.all?(&:even?) @boundary_conditions = boundary_conditions @padding = options.fetch(:padding, { s1: 4, s0: 4, d1: 4, d2: 4, r: 4 }) raise "Boundary conditions and reference dimensions must have the same arity (#{boundary_conditions.length} != #{@dimension})!" if boundary_conditions.length != @dimension @transitions = options.fetch(:transitions, OrderedTransitions::new(:s1, :s0, :r, :grow)) end def bc_from_transition(idim, space1, space2) if @boundary_conditions[idim] == BC::Per then GenericConvolution::BC::PERIODIC else tr = @transitions.transition(space1, space2) if tr == :grow then GenericConvolution::BC::GROW elsif tr == :shrink GenericConvolution::BC::SHRINK elsif tr == :discard GenericConvolution::BC::FREE else raise "Unknown transition: #{tr.inspect}!" end end end def dimensions(space) space = get_space(space) @reference_dimensions.each_with_index.collect do |d,i| if space[i] == @reference_space d else op_opt = { wavelet_family: @wavelet_family, precision: 8 } raise "wavelet family likely wasn't set in the input file !!" if not @spaces[@reference_space].transition_operator(space[i]).has_key? op_opt op = @spaces[@reference_space].transition_operator(space[i])[op_opt] op.dims_from_in(d, bc_from_transition(i, @reference_space, space[i])).last end end end def shapes(space) space = get_space(space) dims = dimensions(space) dims.each_with_index.collect { |d,i| Dimension::new(d, space[i]).get_shape(space[i], @padding[space[i]]) }.reduce([], :+) end def data_shapes(space) space = get_space(space) dims = dimensions(space) dims.each_with_index.collect { |d,i| Dimension::new(d, space[i]).get_data_shape(space[i]) }.reduce([], :+) end def leading_dimensions(space) space = get_space(space) dims = dimensions(space) dims.each_with_index.collect { |d,i| pad(d, @padding[space[i]]) } end private def get_space(space) unless space.kind_of?(Array) space = [space] * @dimension else raise "Invalid space dimension #{space.length} ( != #{@dimension} )!" if space.length != @dimension end return space end def pad(d, padding) return d if padding == 0 remainder = d % padding d += padding - remainder if remainder > 0 d end end end
lgpl-3.0
cismet/wss-bean
src/main/java/net/environmatics/acs/accessor/Payload.java
2895
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package net.environmatics.acs.accessor; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; /** * Represents the payload of a service response. * * @author abonitz * @version $Revision$, $Date$ */ public class Payload { //~ Static fields/initializers --------------------------------------------- private static Logger logger = Logger.getLogger(Payload.class); //~ Instance fields -------------------------------------------------------- // raw data private byte[] load; // charset used for text encoding private String charset; //~ Constructors ----------------------------------------------------------- /** * Creates a new Payload. * * @param is InputStream * * @throws IOException DOCUMENT ME! */ public Payload(final InputStream is) throws IOException { this(is, "UTF-8"); // Standard: UTF-8 } /** * Creates a new Payload. * * @param is InputStream * @param charsetName Is used for text decoding * * @throws IOException DOCUMENT ME! */ public Payload(final InputStream is, final String charsetName) throws IOException { load = IOUtils.toByteArray(is); charset = charsetName; } /** * Creates a new Payload object. * * @param load DOCUMENT ME! * @param charsetName DOCUMENT ME! * * @throws IOException DOCUMENT ME! */ public Payload(final byte[] load, final String charsetName) throws IOException { this.load = load; charset = charsetName; } //~ Methods ---------------------------------------------------------------- /** * Tries to return the payload as String. * * @return textual representation of the payload */ public String asText() { try { return new String(load, charset); } catch (UnsupportedEncodingException e) { return new String(load); } } /** * Returns the payload as byte array. * * @return raw data */ public byte[] asBytes() { if (logger.isDebugEnabled()) { logger.debug("asBytes()"); } return load; } /** * If the Payload contains the String "ServiceExceptionReport" the method returns <b>true.</b> * * @return If <b>true</b>: the Payload contains an exception message */ public boolean containsException() { return (asText().contains("ServiceExceptionReport")); } }
lgpl-3.0
PU-Crypto/ElGamal
ElGamal.py
7598
import sys import math from decimal import Decimal import decimal import random import KeyGen as KeyGen import UTF8_Convert as UTF8 import json decimal.getcontext().prec = 1000 # es wird alles benoetigte improtiert und die Praezision der Decimals festgestellt, welche nicht zu gering sein sollte. #Curve25519: y^2=x^3+486662x^2+x # Prinmzahl: 2^255- 19 a = 486662 #Die Montomerykurve wird mit Primzahl definiert b = 1 prim = Decimal(2**255 - 19) def YCalc(x): #Ermittlung des Punktes anhand des x-wertes und einsetzen in die Gleichung y = Decimal(((x**3+ 486662 * x**2 + x)/1)**Decimal(0.5)) return y def additionMG(p,q): #Die Addition von zwei Punkten auf der Kurve r = [] if p[0] == 0 and p[1] == 0: #Spezialfall: ein punkt ist (0,0), dann ist die addition ueberfluessig return q if q[0] ==0 and q[1] == 0: return p if p!=q and p[1]!=-q[1]: x1 = Decimal(p[0]) y1 = Decimal(p[1]) x2 = Decimal(q[0]) y2 = Decimal(q[1]) #auslesen der Koordinaten der Punkte Xr = Decimal(b*(x2*y1-x1*y2)**2/(x1*x2*(x2-x1)**2)) Yr = Decimal((((2*x1 + x2 + a)*(y2 - y1)) / (x2 - x1)) - b*((y2 - y1)**3 / (x2 - x1)**3) - y1) #Die Formeln erschliesst sich mit einigem aufwand aus der geometrischen Definition #der Addition. Dazu kann ich diese Seite empfehlen: http://en.wikipedia.org/wiki/Montgomery_curve. Etwas ungenauer findet sich das auch in #theoretischen Ausarbeitung r.append(Xr) r.append(Yr) return r if p[0] == q[0] and p[1] == -q[1]: #Spezialfall: Die punkte sind identisch, wenn man einen an der X-Achse spiegelt: Ergebnis (0,0) Xr = Decimal(0) Yr = Decimal(0) r.append(Xr) r.append(Yr) return r if p == q: #Die Difinition von der Verdopplung eines Punktes ist ein bisschen anders als die normale Addition, deswegen dieser Spezialfall. x = Decimal(p[0]) y = Decimal(p[1]) l = Decimal((3*x**2 + 2 * a * x + 1)/(2*y* b)) Xr = Decimal(b * l**2 - a - 2*x) Yr = Decimal((x*3 + a )*l - b *l**3 - y) r.append(Xr) r.append(Yr) return r #Im eigentlichen gibt es den Operator der multiplikation auf Elliptischen Kurven nicht, deswegen wird hier #rekrusiv das "doubling and add" - verfahren genutzt. def multiplikation(p,n): #p ist der punkt n ist der Skalarfaktor if n % 2 == 0 and n != 0: #Wenn der Faktor grade ist kann der erste Schritt gemacht werden, indem der Punkte verdoppelt wird. r = [] x = Decimal(p[0]) y = Decimal(p[1]) l = Decimal((3*x**2 + 2 * a * x + 1)/(2 * y * b)) Xr = Decimal(b * l**2 - a - 2*x) Yr = Decimal((x*3 + a )*l - b * l**3 - y) r.append(Xr) r.append(Yr) r = multiplikation(r,n/2) #Hier passiert die Rekrusion, also der Selbstaufruf mit neuen Parametern. Da eine Verdopplung schon stattfand #wird das Ergebnis, der neue Punkt, mit der Haelfte des urspruenglichen Faktors in die Funktion gegeben. Waere der Faktor n = 8 wuerde dieser #Schritt 3 mal Passieren, da das neue n beim 4. mal 1 ist. return r if n == 0: #Spezialfall: der Faktor ist 0. r = [] r.append(0) r.append(0) return r if n % 2 == 1 and n != 1: zwischenwert = multiplikation(p,n-1) # Rekrusion: Beispiel: n = 5. Beim ersten durchlauf kommt er in diese Abfrage und schickt den Punkt mit n = 4 in die Funktion. # Darauf wird 2 mal die Verdopplung durchgefuehrt und das Ergebnis mit p addiert: p * 5 = p*2*2 + p. r = additionMG(p,zwischenwert) return r if n == 1: #Hier kommt sie Funktion schliesslich hin bei n = 2^x. Wenn der Faktor schliesslich 1 ist, ist das Erbegnis p. return p def ElGamal(text,PubKey): m = int(UTF8.UTFConvert(text)) #Wandle Text in Zahl um k = random.randint(0,prim) #Waehle zufaelligen Kofaktot P = [Decimal(1763),Decimal(YCalc(1763))] #Erzeugerpunkt c = multiplikation(PubKey,k)[0] #multipliziert kofaktor mit dem Oeffentlichen Schluessel, welcher ein Punkt ist. Die X-Koordniate reicht aus. C = multiplikation(P,k) #Erster Teil des Ciphers. Das Produkt des Erzeugerpunktes und des Kofaktors d = c * m % prim #Zweiter Teil des Ciphers. Produkt der Nachricht und der x-Koordinate des PubKey-Produktes. output = str(C[0]) + 'v' + str(C[1]) + 'u' + str(d) #Erstelle den Output return output def ElGamalDecrypt(cipher,Privatkey): #Mit dem Privatkey und den Cipher wird m ermittelt C = [0,0] C[0] = Decimal(cipher.split('v')[0]) zwischenwert = cipher.split('v')[1] C[1] = Decimal(zwischenwert.split('u')[0]) d = Decimal(zwischenwert.split('u')[1]) #Cipher wird gesplittet c1 = multiplikation(C,Privatkey)[0] #Es wird C mit dem Wert Multipliziert und die X-Koordinate ausgelesen. m1 = str(d/c1 % prim + 1) #m wird ermittelt. Da das ergebnis aufgrund der Langen Decimalzahlen bei einer Praezision von 1000 immer sehr knapp unter dem eigentlichen #m (differenz der werte ueblicherweise bei e-900) ist und die Rundenfunktion des flaots zu ungenau ist bei prec = 1000 wird 1 dazu addiert und dann #der rest hinter dem Komma, also .9999999... angeschnitten. m1 = m1.split('.') m1 = int(m1[0]) output = UTF8.UTFdeConvert(m1) #die Zahl wird wieder in einen Text gewandelt. return output def KeyGenerator(password): #generiert das Keypaar aus einem Passwort mit sha3 P = [Decimal(1763),Decimal(YCalc(1763))] #Jan: P0 -> kurze Zahl; P1 -> lange Zahl mit Komma nach ca. 7 Stellen Privat = int(KeyGen.KeyGen(password),16) Public = (multiplikation(P,Privat)) return Privat, Public # Fuer ein tieferes Verstaendnis, dieser Verschluesselung empfehle ich die theoretische Ausarbeitung zu lesen. def handleShellParam(param, default): for cmdarg in sys.argv: if(("--" + param + "=") in cmdarg): return str(cmdarg.replace(("--" + param + "="), "")) elif(("-" + param + "=") in cmdarg): return str(cmdarg.replace(("-" + param + "="), "")) elif(("--" + param) in cmdarg): return str(cmdarg.replace(("--"), "")) elif(("-" + param) in cmdarg): return str(cmdarg.replace(("-"), "")) return default task = handleShellParam("t", 0) #zur Bestimmung was gerade von dem Script verlangt wird, sonst exited er, wenn man verschluesseln will und natuerlich das Password fehlt #Fuer KeyGen waehlen Sie bitte die 1, fue Encrypt die 2 und fuer Decrypt die 3 password = handleShellParam("p", 0) keyname = handleShellParam("k", 0) PlainOrCipher = handleShellParam("poc", 0) Key = handleShellParam("key", 0) if task == "1": if password != 0 and keyname != 0 and len(password) > 15: #das mit len braucht sha3, sonst bugt das. keys = KeyGenerator(password) privat = keys[0] public = keys[1] print "Private Key: " + str(privat) print "Public Key: " + str(public) #NewKey = {"key" : {"name" : keyname, "keys" : {"privkey" : privat, "pubkey" : public}}} #with open("keys.json", 'w') as outfile: #json.dump(NewKey, outfile, indent = 3, sort_keys = True) #sys.exit(0) elif password == 0: print("Es fehlte das Passwort bei ihrer Eingabe") sys.exit(1) elif len(str(password)) < 16: print("Das Passwort ist zu kurz. Die laenge muss mindestens 16 Zeichen betragen") sys.exit(1) elif keyname == 0: print("Es fehlte der Schluesselname bei ihrer Eingabe") sys.exit(1) else: print ("Leere Felder mag Deep Thought nicht") #der muss so bleiben!!! sys.exit(1) if task == "2": Key0 = Key.split(',')[0] Key1 = Key.split(',')[1] Key0 = Key0.split("'")[1] Key0 = Key0.split("'")[0] Key1 = Key1.split("'")[1] Key1 = Key1.split("'")[0] Key = [Decimal(Key0),Decimal(Key1)] print(ElGamal(PlainOrCipher, Key)) sys.exit(0) if task == "3": Key = Decimal(Key) print(ElGamalDecrypt(PlainOrCipher, Key)) sys.exit(0) else: print "No task given!" #Ja ich weiss, dass evt. manche Kommentare noch geaendert werden muessen, aber klappt das so?
lgpl-3.0
geekprojects/b0rk
src/libb0rk/executor.cpp
39466
/* * b0rk - The b0rk Embeddable Runtime Environment * Copyright (C) 2015, 2016 GeekProjects.com * * This file is part of b0rk. * * b0rk is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * b0rk is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with b0rk. If not, see <http://www.gnu.org/licenses/>. */ #include <b0rk/executor.h> #include <b0rk/compiler.h> #include <b0rk/utils.h> #include "packages/system/lang/StringClass.h" #include "packages/system/lang/Array.h" #include "packages/system/lang/Exception.h" #include <stdlib.h> #include <math.h> #include <float.h> #include <cinttypes> #undef DEBUG_EXECUTOR #undef DEBUG_EXECUTOR_STATS #define DOUBLE_VALUE(_v) (((_v).type == VALUE_DOUBLE) ? (_v.d) : (double)(_v.i)) #define INTEGER_VALUE(_v) (((_v).type == VALUE_INTEGER) ? (_v.i) : (int)(floor(_v.d))) #ifdef DEBUG_EXECUTOR #define LOG(_fmt, _args...) \ printf("Executor::run: %ls:%04" PRIx64 ": 0x%" PRIx64 " " _fmt "\n", frame->code->function->getFullName().c_str(), thisPC, opcode, _args); #else #define LOG(_fmt, _args...) #endif #define ERROR(_fmt, _args...) \ printf("Executor::run: %ls:%04" PRIx64 ": 0x%" PRIx64 " ERROR: " _fmt "\n", frame->code->function->getFullName().c_str(), thisPC, opcode, _args); using namespace std; using namespace b0rk; #ifdef DEBUG_EXECUTOR_STATS int g_stats[OPCODE_MAX]; uint64_t g_loadVarCount = 0; uint64_t g_loadVarThisCount = 0; #endif static bool opcodeLoadVar(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int varId = frame->fetch(); context->push(frame->localVars[varId]); LOG("LOAD_VAR: v%d: %ls", varId, frame->localVars[varId].toString().c_str()); #ifdef DEBUG_EXECUTOR_STATS g_loadVarCount++; if (varId == 0) { g_loadVarThisCount++; } #endif return true; } static bool opcodeStoreVar(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int varId = frame->fetch(); frame->localVars[varId] = context->pop(); LOG("STORE_VAR: v%d = %ls", varId, frame->localVars[varId].toString().c_str()); return true; } static bool opcodeLoadField(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value objValue = context->pop(); int fieldId = frame->fetch(); LOG("LOAD_FIELD: f%d, this=%p (value count=%lu)", fieldId, objValue.object, objValue.object->getClass()->getFieldCount()); Value result = objValue.object->getValue(fieldId); context->push(result); return true; } static bool opcodeLoadFieldNamed(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Object* nameObj = context->pop().object; Value objValue = context->pop(); wstring varName = String::getString(context, nameObj); LOG("LOAD_FIELD_NAMED: obj=%p, name=%ls\n", objValue.object, varName.c_str()); if (objValue.type == VALUE_OBJECT && objValue.object != NULL) { Object* obj = objValue.object; Class* clazz = obj->getClass(); int id = clazz->getFieldId(varName); if (id != -1) { LOG("LOAD_FIELD_NAMED: class=%ls, obj=%p, name=%ls, id=%d\n", clazz->getName().c_str(), objValue.object, varName.c_str(), id); Value v = obj->getValue(id); context->push(v); } else { return false; } } else { return false; } return true; } static bool opcodeStoreFieldNamed(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value nameValue = context->pop(); Value objValue = context->pop(); Value value = context->pop(); wstring varName = String::getString(context, nameValue); LOG("STORE_FIELD_NAMED: obj=%p, name=%ls\n", objValue.object, varName.c_str()); if (objValue.type == VALUE_OBJECT && objValue.object != NULL) { Object* obj = objValue.object; Class* clazz = obj->getClass(); int id = clazz->getFieldId(varName); if (id != -1) { LOG("STORE_FIELD_NAMED: class=%ls, obj=%p, name=%ls, id=%d\n", clazz->getName().c_str(), objValue.object, varName.c_str(), id); obj->setValue(id, value); } else { return false; } } else { return false; } return true; } static bool opcodeLoadStaticField(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Class* clazz = (Class*)frame->fetch(); int fieldId = frame->fetch(); Value v = clazz->getStaticField(fieldId); LOG("LOAD_STATIC_FIELD: f%d, class=%ls, v=%ls", fieldId, clazz->getName().c_str(), v.toString().c_str()); context->push(v); return true; } static bool opcodeStoreStaticField(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Class* clazz = (Class*)frame->fetch(); int fieldId = frame->fetch(); Value v = context->pop(); clazz->setStaticField(fieldId, v); LOG("STORE_STATIC_FIELD: f%d, class=%ls, v=%ls", fieldId, clazz->getName().c_str(), v.toString().c_str()); return true; } static bool opcodeStoreField(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value objValue = context->pop(); Value value = context->pop(); int fieldId = frame->fetch(); LOG("STORE_FIELD: f%d, this=%p", fieldId, objValue.object); if (objValue.object == NULL) { ERROR("STORE_FIELD: f%d, this=%p", fieldId, objValue.object); return false; } objValue.object->setValue(fieldId, value); return true; } static bool opcodeLoadArray(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value indexValue = context->pop(); Value arrayValue = context->pop(); LOG("LOAD_ARRAY: indexValue=%ls", indexValue.toString().c_str()); LOG("LOAD_ARRAY: arrayValue=%ls", arrayValue.toString().c_str()); bool res = false; if (arrayValue.type == VALUE_OBJECT && arrayValue.object != NULL) { Object* array = arrayValue.object; Value valueValue; res = ((Array*)array->m_class)->load(context, array, indexValue, valueValue); context->push(valueValue); } else { ERROR("STORE_ARRAY: Array is invalid: %ls", arrayValue.toString().c_str()); } return res; } static bool opcodeStoreArray(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value indexValue = context->pop(); Value arrayValue = context->pop(); Value valueValue = context->pop(); LOG("STORE_ARRAY: indexValue=%ls", indexValue.toString().c_str()); LOG("STORE_ARRAY: arrayValue=%ls", arrayValue.toString().c_str()); LOG("STORE_ARRAY: valueValue=%ls", valueValue.toString().c_str()); bool res = false; if (arrayValue.type == VALUE_OBJECT && arrayValue.object != NULL) { Object* array = arrayValue.object; res = ((Array*)array->m_class)->store(context, array, indexValue, valueValue); } else { ERROR("STORE_ARRAY: Array is invalid: %ls", arrayValue.toString().c_str()); } return res; } static bool opcodeIncVar(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int varId = frame->fetch(); int64_t amount = frame->fetch(); frame->localVars[varId].i += amount; LOG("INC_VAR: v%d, %" PRId64 ": %" PRId64, varId, amount, frame->localVars[varId].i); return true; } static bool opcodeIncVarD(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int varId = frame->fetch(); uint64_t amounti = frame->fetch(); double* amount = (double*)(&amounti); frame->localVars[varId].d += *amount; LOG("INC_VARD: v%d, %" PRId64 ": %" PRIf64, varId, amount, frame->localVars[varId].d); return true; } static bool opcodePushI(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_INTEGER; v.i = frame->fetch(); LOG("PUSHI: %lld", v.i); context->push(v); return true; } static bool opcodePushD(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_DOUBLE; uint64_t i = frame->fetch(); double* d = (double*)(&i); v.d = *d; LOG("PUSHD: %0.2f", v.d); context->push(v); return true; } static bool opcodePushObj(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_OBJECT; Object* obj = (Object*)frame->fetch(); v.object = obj; LOG("PUSHOBJ: %p", obj); context->push(v); return true; } static bool opcodeDup(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v = context->peek(); LOG("DUP: %ls", v.toString().c_str()); context->push(v); return true; } static bool opcodeSwap(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v1 = context->pop(); Value v2 = context->pop(); LOG("SWAP: %ls, %ls", v1.toString().c_str(), v2.toString().c_str()); context->push(v1); context->push(v2); return true; } static bool opcodeAdd(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v1 = context->pop(); if (v1.type == VALUE_OBJECT) { // TODO: This should have been figured out by the assembler? Class* clazz = v1.object->getClass(); LOG("ADD OBJECT: class=%ls", clazz->getName().c_str()); Function* addFunc = clazz->findMethod(L"operator+"); LOG("ADD OBJECT: add operator=%p", addFunc); bool res = addFunc->execute(context, v1.object, 1); if (!res) { return false; } } else { Value v2 = context->pop(); Value result; if (v1.type == VALUE_DOUBLE && v2.type == VALUE_DOUBLE) { result.type = VALUE_DOUBLE; result.d = v1.d + v2.d; LOG("ADD: %0.2f + %0.2f = %0.2f", v1.d, v2.d, result.d); } else if (v1.type == VALUE_DOUBLE || v2.type == VALUE_DOUBLE) { result.type = VALUE_DOUBLE; result.d = DOUBLE_VALUE(v1) + DOUBLE_VALUE(v2); LOG("ADD: %0.2f + %0.2f = %0.2f", v1.d, v2.d, result.d); } else { result.type = VALUE_INTEGER; result.i = v1.i + v2.i; LOG("ADD: %lld + %lld = %lld", v1.i, v2.i, result.i); } context->push(result); } return true; } static bool opcodeSub(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v1 = context->pop(); if (v1.type == VALUE_OBJECT) { // TODO: This should have been figured out by the assembler? Class* clazz = v1.object->getClass(); LOG("SUB OBJECT: class=%ls", clazz->getName().c_str()); Function* addFunc = clazz->findMethod(L"operator-"); LOG("SUB OBJECT: sub operator=%p", addFunc); bool res = addFunc->execute(context, v1.object, 1); if (!res) { return false; } } else { Value v2 = context->pop(); Value result; if (v1.type == VALUE_DOUBLE || v2.type == VALUE_DOUBLE) { result.type = VALUE_DOUBLE; result.d = DOUBLE_VALUE(v1) - DOUBLE_VALUE(v2); LOG("SUB: %0.2f - %0.2f = %0.2f", v1.d, v2.d, result.d); } else { result.type = VALUE_INTEGER; result.i = v1.i - v2.i; LOG("SUB: %lld - %lld = %lld", v1.i, v2.i, result.i); } context->push(result); } return true; } static bool opcodeMul(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v1 = context->pop(); if (v1.type == VALUE_OBJECT) { // TODO: This should have been figured out by the assembler? Class* clazz = v1.object->getClass(); LOG("MUL OBJECT: class=%ls", clazz->getName().c_str()); Function* addFunc = clazz->findMethod(L"operator*"); LOG("MUL OBJECT: * operator=%p", addFunc); bool res = addFunc->execute(context, v1.object, 1); if (!res) { return false; } } else { Value v2 = context->pop(); Value result; if (v1.type == VALUE_DOUBLE && v2.type == VALUE_DOUBLE) { result.type = VALUE_DOUBLE; result.d = v1.d * v2.d; LOG("MUL: %0.2f * %0.2f = %0.2f", v1.d, v2.d, result.d); } else if (v1.type == VALUE_DOUBLE || v2.type == VALUE_DOUBLE) { result.type = VALUE_DOUBLE; result.d = DOUBLE_VALUE(v1) * DOUBLE_VALUE(v2); LOG("MUL: %0.2f * %0.2f = %0.2f", v1.d, v2.d, result.d); } else { result.type = VALUE_INTEGER; result.i = v1.i * v2.i; LOG("MUL: %lld * %lld = %lld", v1.i, v2.i, result.i); } context->push(result); } return true; } static bool opcodeDiv(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v1 = context->pop(); if (v1.type == VALUE_OBJECT) { // TODO: This should have been figured out by the assembler? Class* clazz = v1.object->getClass(); LOG("MUL OBJECT: class=%ls", clazz->getName().c_str()); Function* addFunc = clazz->findMethod(L"operator/"); LOG("MUL OBJECT: / operator=%p", addFunc); bool res = addFunc->execute(context, v1.object, 1); if (!res) { return false; } } else { Value v2 = context->pop(); Value result; if (v1.type == VALUE_DOUBLE && v2.type == VALUE_DOUBLE) { result.type = VALUE_DOUBLE; result.d = v1.d / v2.d; LOG("DIV: %0.2f / %0.2f = %0.2f", v1.d, v2.d, result.d); } else if (v1.type == VALUE_DOUBLE || v2.type == VALUE_DOUBLE) { result.type = VALUE_DOUBLE; result.d = DOUBLE_VALUE(v1) / DOUBLE_VALUE(v2); LOG("DIV: %0.2f / %0.2f = %0.2f", v1.d, v2.d, result.d); } else { result.type = VALUE_INTEGER; result.i = v1.i / v2.i; LOG("DIV: %lld / %lld = %lld", v1.i, v2.i, result.i); } context->push(result); } return true; } static bool opcodeAnd(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v1 = context->pop(); Value v2 = context->pop(); Value result; result.type = VALUE_INTEGER; result.i = (v1.i && v2.i); LOG("AND: %lld + %lld = %lld", v1.i, v2.i, result.i); context->push(result); return true; } static bool opcodeNot(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v1 = context->pop(); Value result; result.type = VALUE_INTEGER; result.i = !v1.i; LOG("NOT: %lld = %lld", v1.i, result.i); context->push(result); return true; } static bool opcodeAddI(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int64_t v1 = context->popInt(); int64_t v2 = context->popInt(); int64_t result = v1 + v2; LOG("ADDI: %lld + %lld = %lld", v1, v2, result); context->pushInt(result); return true; } static bool opcodeSubI(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int64_t v1 = context->popInt(); int64_t v2 = context->popInt(); int64_t result = v1 - v2; LOG("SUBI: %lld - %lld = %lld", v1, v2, result); context->pushInt(result); return true; } static bool opcodeAddD(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { double v1 = context->popDouble(); double v2 = context->popDouble(); double result = v1 + v2; LOG("ADDD: %0.2f + %0.2f = %0.2f", v1 v2, result); context->pushDouble(result); return true; } static bool opcodeSubD(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { double v1 = context->popDouble(); double v2 = context->popDouble(); double result = v1 - v2; LOG("SUBD: %0.2f - %0.2f = %0.2f", v1, v2, result); context->pushDouble(result); return true; } static bool opcodeMulI(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int64_t v1 = context->popInt(); int64_t v2 = context->popInt(); int64_t result = v1 * v2; LOG("MULI: %lld * %lld = %lld", v1, v2, result); context->pushInt(result); return true; } static bool opcodeDivI(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int64_t v1 = context->popInt(); int64_t v2 = context->popInt(); int64_t result = v1 / v2; LOG("DIVI: %lld * %lld = %lld", v1, v2, result); context->pushInt(result); return true; } static bool opcodeMulD(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { double v1 = context->popDouble(); double v2 = context->popDouble(); double result = v1 * v2; LOG("MULD: %0.2f * %0.2f = %0.2f", v1, v2, result); context->pushDouble(result); return true; } static bool opcodeDivD(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { double v1 = context->popDouble(); double v2 = context->popDouble(); double result = v1 / v2; LOG("DIVD: %0.2f * %0.2f = %0.2f", v1, v2, result); context->pushDouble(result); return true; } static bool opcodePushCE(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_INTEGER; v.i = frame->flags.zero; context->push(v); LOG("PUSHCE: %lld", v.i); LOG("PUSHCE: -> zero=%d, sign=%d, overflow=%d", frame->flags.zero, frame->flags.sign, frame->flags.overflow); return true; } static bool opcodePushCNE(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_INTEGER; v.i = !frame->flags.zero; context->push(v); LOG("PUSHCNE: %lld", v.i); LOG("PUSHCNE: -> zero=%d, sign=%d, overflow=%d", frame->flags.zero, frame->flags.sign, frame->flags.overflow); return true; } static bool opcodePushCL(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_INTEGER; v.i = (frame->flags.sign != frame->flags.overflow); context->push(v); LOG("PUSHCL: %lld", v.i); LOG("PUSHCL: -> zero=%d, sign=%d, overflow=%d", frame->flags.zero, frame->flags.sign, frame->flags.overflow); return true; } static bool opcodePushCLE(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_INTEGER; v.i = frame->flags.zero || (frame->flags.sign != frame->flags.overflow); context->push(v); LOG("PUSHCLE: %lld", v.i); LOG("PUSHCLE: -> zero=%d, sign=%d, overflow=%d", frame->flags.zero, frame->flags.sign, frame->flags.overflow); return true; } static bool opcodePushCG(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_INTEGER; v.i = !frame->flags.zero && (frame->flags.sign == frame->flags.overflow); context->push(v); LOG("PUSHCG: %lld", v.i); LOG("PUSHCG: -> zero=%d, sign=%d, overflow=%d", frame->flags.zero, frame->flags.sign, frame->flags.overflow); return true; } static bool opcodePushCGE(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value v; v.type = VALUE_INTEGER; v.i = (frame->flags.sign == frame->flags.overflow); context->push(v); LOG("PUSHCGE: %lld", v.i); LOG("PUSHCGE: -> zero=%d, sign=%d, overflow=%d", frame->flags.zero, frame->flags.sign, frame->flags.overflow); return true; } static bool opcodePop(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { #ifdef DEBUG_EXECUTOR Value v = context->pop(); LOG("POP: %ls", v.toString().c_str()); #else context->pop(); #endif return true; } static bool opcodeCall(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value objValue = context->pop(); Function* function = (Function*)frame->fetch(); int count = frame->fetch(); LOG("CALL: %p.%p", objValue.object, function); return function->execute(context, objValue.object, count); } static bool opcodeCallStatic(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Function* function = (Function*)frame->fetch(); int count = frame->fetch(); LOG("CALL_STATIC: %p", function); return function->execute(context, NULL, count); } static bool opcodeCallNamed(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int count = frame->fetch(); Object* nameObj = context->pop().object; Value objValue = context->pop(); wstring funcName = String::getString(context, nameObj); LOG("CALL_NAMED: obj=%ls, name=%ls", objValue.toString().c_str(), funcName.c_str()); Object* obj = objValue.object; LOG("CALL_NAMED: -> obj class=%ls, ", obj->getClass()->getName().c_str()); if (B0RK_UNLIKELY(obj == NULL)) { ERROR("CALL_NAMED: object is null! %p", obj); return false; } Class* clazz = obj->getClass(); if (B0RK_UNLIKELY(clazz == NULL)) { ERROR("CALL_NAMED: object with no class!? obj=%p", obj); return false; } int funcFieldId = clazz->getFieldId(funcName); LOG("CALL_NAMED: -> funcFieldId=%d", funcFieldId); Function* function; if (funcFieldId != -1) { Value funcFieldValue = obj->getValue(funcFieldId); function = (Function*)(funcFieldValue.object->getValue(0).pointer); } else { function = clazz->findMethod(funcName); } LOG("CALL_NAMED: -> function=%p", function); if (B0RK_UNLIKELY(function == NULL)) { ERROR("CALL_NAMED: function not found! class=%ls, function=%ls", obj->getClass()->getName().c_str(), funcName.c_str()); return false; } return function->execute(context, obj, count); } static bool opcodeCallObj(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { int count = frame->fetch(); Value funcObjValue = context->pop(); if (B0RK_LIKELY(funcObjValue.type == VALUE_OBJECT && funcObjValue.object != NULL)) { LOG("CALL_OBJ: function obj=%p, argCount=%d", funcObjValue.object, count); Function* function = (Function*)(funcObjValue.object->getValue(0).pointer); if (B0RK_LIKELY(function != NULL)) { LOG("CALL_OBJ: function=%p", function); return function->execute(context, NULL, count); } } return false; } static bool opcodeNew(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Class* clazz = (Class*)frame->fetch(); int count = frame->fetch(); LOG("NEW: class=%ls", clazz->getName().c_str()); Object* obj = context->getRuntime()->newObject(context, clazz, count); if (B0RK_LIKELY(obj != NULL)) { Value v; v.type = VALUE_OBJECT; v.object = obj; context->push(v); } else { ERROR("NEW: Failed to create new object! class=%ls", clazz->getName().c_str()); return false; } return true; } static bool opcodeNewFunction(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Function* func = (Function*)frame->fetch(); LOG("NEW_FUNCTION: %p", func); Class* clazz = context->getRuntime()->findClass(context, L"system.lang.Function", false); LOG("NEW_FUNCTION: Function class=%p", clazz); Value funcValue; funcValue.type = VALUE_OBJECT; funcValue.pointer = func; context->push(funcValue); Object* funcObject = context->getRuntime()->newObject(context, clazz, 1); LOG("NEW_FUNCTION: funcObject=%p", funcObject); Value v; v.type = VALUE_OBJECT; v.object = funcObject; context->push(v); return true; } static bool opcodeReturn(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value result = context->pop(); LOG("RETURN %ls", result.toString().c_str()); Value frameCheck = context->pop(); if (frameCheck.type != VALUE_FRAME || frameCheck.pointer != frame) { ERROR("EXPECTING CURRENT FRAME ON STACK! GOT: %ls\n", frameCheck.toString().c_str()); return false; } else { context->push(result); } frame->running = false; return true; } #define CMP_INTEGER(_left, _right) \ { \ int64_t result = (int64_t)_right.i - (int64_t)_left.i; \ frame->flags.zero = (result == 0); \ frame->flags.sign = (result < 0); \ frame->flags.overflow = !frame->flags.zero || frame->flags.sign; \ LOG("CMP: left=%lld, right=%lld, result=%lld", _left.i, _right.i, result); \ } #define CMP_DOUBLE(_left, _right) \ { \ double result = _right.d - _left.d; \ LOG("CMP: left=%0.2f, right=%0.2f, result=%0.2f", _left.d, _right.d, result); \ frame->flags.zero = (result > -DBL_EPSILON && result < DBL_EPSILON); \ frame->flags.sign = (result < 0.0 && !frame->flags.zero); \ frame->flags.overflow = !frame->flags.zero || frame->flags.sign; \ } static bool opcodeCmp(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value left = context->pop(); if (left.type == VALUE_INTEGER || left.type == VALUE_DOUBLE) { Value right = context->pop(); if (left.type == VALUE_INTEGER && right.type == VALUE_INTEGER) { CMP_INTEGER(left, right); } else if (left.type == VALUE_DOUBLE && right.type == VALUE_DOUBLE) { CMP_DOUBLE(left, right); } else if (left.type == VALUE_DOUBLE || right.type == VALUE_DOUBLE) { double leftDouble = DOUBLE_VALUE(left); double rightDouble = DOUBLE_VALUE(right); double result = rightDouble - leftDouble; LOG("CMP: left=%0.2f, right=%0.2f, result=%0.2f", leftDouble, rightDouble, result); frame->flags.zero = (result > -DBL_EPSILON && result < DBL_EPSILON); frame->flags.sign = (result < 0.0 && !frame->flags.zero); frame->flags.overflow = !frame->flags.zero || frame->flags.sign; } else { // Incompatible types: They always get a result of -1 int result = -1; frame->flags.zero = (result == 0); frame->flags.sign = result < 0 && result != 0; frame->flags.overflow = !frame->flags.zero || frame->flags.sign; } } else if (left.type == VALUE_OBJECT) { // TODO: This should have been figured out by the assembler? Class* clazz = left.object->getClass(); LOG("CMP OBJECT: class=%ls", clazz->getName().c_str()); Function* eqFunc = clazz->findMethod(L"operator=="); LOG("CMP OBJECT: cmp operator=%p", eqFunc); bool res = eqFunc->execute(context, left.object, 1); if (!res) { return false; } Value result = context->pop(); frame->flags.zero = (result.i == 0); frame->flags.sign = result.i < 0 && result.i != 0; frame->flags.overflow = !frame->flags.zero || frame->flags.sign; } else { ERROR("CMP: UNHANDLED DATA TYPES: left=%d\n", left.type); return false; } LOG("CMP: -> zero=%d, sign=%d, overflow=%d", frame->flags.zero, frame->flags.sign, frame->flags.overflow); return true; } static bool opcodeCmpI(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value left = context->pop(); Value right = context->pop(); CMP_INTEGER(left, right); return true; } static bool opcodeCmpD(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value left = context->pop(); Value right = context->pop(); CMP_DOUBLE(left, right); return true; } static bool opcodeJmp(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { uint64_t dest = frame->fetch(); LOG("JMP: dest=%lld", dest); frame->pc = dest; return true; } static bool opcodeBEq(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { uint64_t dest = frame->fetch(); LOG("BEQ: frame->flags.zero=%d, dest=0x%llx", frame->flags.zero, dest); if (frame->flags.zero) { frame->pc = dest; } return true; } static bool opcodeBNE(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { uint64_t dest = frame->fetch(); LOG("BNE: frame->flags.zero=%d, dest=0x%llx", frame->flags.zero, dest); if (!frame->flags.zero) { frame->pc = dest; } return true; } static bool opcodeBL(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { uint64_t dest = frame->fetch(); LOG("BL: frame->flags.zero=%d, dest=0x%llx", frame->flags.zero, dest); if (frame->flags.sign != frame->flags.overflow) { frame->pc = dest; } return true; } static bool opcodeBLE(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { uint64_t dest = frame->fetch(); LOG("BLE: flags.sign=%d, flags.overflow=%d, dest=0x%llx", frame->flags.zero, frame->flags.overflow, dest); if (!frame->flags.zero || (frame->flags.sign == frame->flags.overflow)) { frame->pc = dest; } return true; } static bool opcodeBG(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { uint64_t dest = frame->fetch(); LOG("BG: flags.sign=%d, flags.overflow=%d, dest=0x%llx", frame->flags.zero, frame->flags.overflow, dest); if (!frame->flags.zero &&(frame->flags.sign == frame->flags.overflow)) { frame->pc = dest; } return true; } static bool opcodeBGE(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { uint64_t dest = frame->fetch(); LOG("BGE: flags.sign=%d, flags.overflow=%d, dest=0x%llx", frame->flags.zero, frame->flags.overflow, dest); if (frame->flags.sign == frame->flags.overflow) { frame->pc = dest; } return true; } static bool opcodeThrow(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { Value value = context->pop(); LOG("THROW: value=%ls", value.toString().c_str()); Object* exception = Exception::createException(context, value); context->throwException(exception); return true; } static bool opcodePushHandler(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { ExceptionHandler handler; handler.excepVar = frame->fetch(); handler.handlerPC = frame->fetch(); frame->handlerStack.push_back(handler); return true; } static bool opcodePopHandler(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { frame->handlerStack.pop_back(); return true; } static bool opcodeInvalid(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { ERROR("Invalid Opcode: 0x%" PRIx64, opcode); return false; } static opcodeFunc_t g_opcodeTable[OPCODE_MAX]; Executor::Executor() { int i; for (i = 0; i < OPCODE_MAX; i++) { g_opcodeTable[i] = opcodeInvalid; } g_opcodeTable[OPCODE_LOAD_VAR] = opcodeLoadVar; g_opcodeTable[OPCODE_STORE_VAR] = opcodeStoreVar; g_opcodeTable[OPCODE_LOAD_FIELD] = opcodeLoadField; g_opcodeTable[OPCODE_STORE_FIELD] = opcodeStoreField; g_opcodeTable[OPCODE_LOAD_FIELD_NAMED] = opcodeLoadFieldNamed; g_opcodeTable[OPCODE_STORE_FIELD_NAMED] = opcodeStoreFieldNamed; g_opcodeTable[OPCODE_LOAD_STATIC_FIELD] = opcodeLoadStaticField; g_opcodeTable[OPCODE_STORE_STATIC_FIELD] = opcodeStoreStaticField; g_opcodeTable[OPCODE_LOAD_ARRAY] = opcodeLoadArray; g_opcodeTable[OPCODE_STORE_ARRAY] = opcodeStoreArray; g_opcodeTable[OPCODE_INC_VAR] = opcodeIncVar; g_opcodeTable[OPCODE_INC_VARD] = opcodeIncVarD; g_opcodeTable[OPCODE_PUSHI] = opcodePushI; g_opcodeTable[OPCODE_PUSHD] = opcodePushD; g_opcodeTable[OPCODE_PUSHOBJ] = opcodePushObj; g_opcodeTable[OPCODE_DUP] = opcodeDup; g_opcodeTable[OPCODE_SWAP] = opcodeSwap; g_opcodeTable[OPCODE_ADD] = opcodeAdd; g_opcodeTable[OPCODE_SUB] = opcodeSub; g_opcodeTable[OPCODE_MUL] = opcodeMul; g_opcodeTable[OPCODE_DIV] = opcodeDiv; g_opcodeTable[OPCODE_AND] = opcodeAnd; g_opcodeTable[OPCODE_NOT] = opcodeNot; g_opcodeTable[OPCODE_ADDI] = opcodeAddI; g_opcodeTable[OPCODE_SUBI] = opcodeSubI; g_opcodeTable[OPCODE_MULI] = opcodeMulI; g_opcodeTable[OPCODE_DIVI] = opcodeDivI; g_opcodeTable[OPCODE_ANDI] = opcodeAnd; g_opcodeTable[OPCODE_NOTI] = opcodeNot; g_opcodeTable[OPCODE_ADDD] = opcodeAddD; g_opcodeTable[OPCODE_SUBD] = opcodeSubD; g_opcodeTable[OPCODE_MULD] = opcodeMulD; g_opcodeTable[OPCODE_DIVD] = opcodeDivD; g_opcodeTable[OPCODE_PUSHCE] = opcodePushCE; g_opcodeTable[OPCODE_PUSHCNE] = opcodePushCNE; g_opcodeTable[OPCODE_PUSHCL] = opcodePushCL; g_opcodeTable[OPCODE_PUSHCLE] = opcodePushCLE; g_opcodeTable[OPCODE_PUSHCG] = opcodePushCG; g_opcodeTable[OPCODE_PUSHCGE] = opcodePushCGE; g_opcodeTable[OPCODE_POP] = opcodePop; g_opcodeTable[OPCODE_CALL] = opcodeCall; g_opcodeTable[OPCODE_CALL_STATIC] = opcodeCallStatic; g_opcodeTable[OPCODE_CALL_NAMED] = opcodeCallNamed; g_opcodeTable[OPCODE_CALL_OBJ] = opcodeCallObj; g_opcodeTable[OPCODE_NEW] = opcodeNew; g_opcodeTable[OPCODE_NEW_FUNCTION] = opcodeNewFunction; g_opcodeTable[OPCODE_RETURN] = opcodeReturn; g_opcodeTable[OPCODE_CMP] = opcodeCmp; g_opcodeTable[OPCODE_CMPI] = opcodeCmpI; g_opcodeTable[OPCODE_CMPD] = opcodeCmpD; g_opcodeTable[OPCODE_JMP] = opcodeJmp; g_opcodeTable[OPCODE_BEQ] = opcodeBEq; g_opcodeTable[OPCODE_BNE] = opcodeBNE; g_opcodeTable[OPCODE_BL] = opcodeBL; g_opcodeTable[OPCODE_BLE] = opcodeBLE; g_opcodeTable[OPCODE_BG] = opcodeBG; g_opcodeTable[OPCODE_BGE] = opcodeBGE; g_opcodeTable[OPCODE_THROW] = opcodeThrow; g_opcodeTable[OPCODE_PUSHTRY] = opcodePushHandler; g_opcodeTable[OPCODE_POPTRY] = opcodePopHandler; #ifdef DEBUG_EXECUTOR_STATS int i; for (i = 0; i < OPCODE_MAX; i++) { g_stats[i] = 0; } #endif } Executor::~Executor() { #ifdef DEBUG_EXECUTOR_STATS int i; for (i = 0; i < OPCODE_MAX; i++) { if (g_stats[i] > 0) { printf("Executor::~Executor: %04x: %d\n", i, g_stats[i]); } } printf("Executor::~Executor: LoadVar: %lld, this: %lld\n", g_loadVarCount, g_loadVarThisCount); #endif } bool Executor::run(Context* context, Object* thisObj, AssembledCode* code, int argCount) { #ifdef DEBUG_EXECUTOR wstring functionName = code->function->getFullName(); printf("Executor::run: Entering %ls\n", functionName.c_str()); #endif Frame frame; frame.pc = 0; frame.code = code; frame.flags.zero = false; frame.flags.sign = false; frame.flags.overflow = false; // Allocate local vars on our real stack // This is UNSAFE. It could allow b0rk code // to hijack the interpreter int frameSize = sizeof(Value) * code->localVars; frame.localVars = (Value*)alloca(frameSize); memset(frame.localVars, 0, frameSize); // v0 is always the "this" pointer Value thisValue; thisValue.type = VALUE_OBJECT; thisValue.object = thisObj; frame.localVarsCount = code->localVars; frame.localVars[0] = thisValue; // Populate the first n variables with any arguments int arg; for (arg = 0; arg < argCount; arg++) { frame.localVars[(argCount - arg) + 0] = context->pop(); } /* * Push the frame pointer to the stack * This is used for a variety of things: * - By the Garbage Collector looking for local vars * - Generating stack traces * - Ensuring the stack is consistent */ Value frameValue; frameValue.type = VALUE_FRAME; frameValue.pointer = &frame; context->push(frameValue); frame.running = true; bool success = true; while (frame.running && frame.pc < code->size) { uint64_t thisPC = frame.pc; uint64_t opcode = frame.fetch(); if (B0RK_UNLIKELY(!context->checkStack())) { fprintf( stderr, "Executor::run: %ls:%04" PRIx64 ": Stack position is out of bounds", frame.code->function->getFullName().c_str(), thisPC); return false; } #ifdef DEBUG_EXECUTOR_STATS g_stats[opcode]++; #endif opcodeFunc_t func = opcodeInvalid; if (B0RK_LIKELY(opcode < OPCODE_MAX)) { func = g_opcodeTable[opcode]; } success = func(thisPC, opcode, context, &frame); if (B0RK_UNLIKELY(!success)) { frame.running = false; } // Check for any exceptions if (B0RK_UNLIKELY(context->hasException())) { success = handleException(thisPC, opcode, context, &frame); } } #ifdef DEBUG_EXECUTOR printf("Executor::run: Leaving %ls\n", code->function->getFullName().c_str()); #endif return success; } bool Executor::handleException(uint64_t thisPC, uint64_t opcode, Context* context, Frame* frame) { bool success = true; #ifdef DEBUG_EXECUTOR fprintf( stderr, "Executor::handleException: %ls:%04" PRIx64 ": 0x%" PRIx64 " ERROR: Exception thrown!\n", frame->code->function->getFullName().c_str(), thisPC, opcode); #endif if (frame->handlerStack.empty()) { // There are no current exception handlers #ifdef DEBUG_EXECUTOR fprintf( stderr, "Executor::handleException: %ls:%04" PRIx64 ": 0x%" PRIx64 " -> No handler, leaving function!\n", frame->code->function->getFullName().c_str(), thisPC, opcode); #endif success = true; frame->running = false; // Clear the stack until we find our current frame while (true) { Value v = context->pop(); #ifdef DEBUG_EXECUTOR fprintf(stderr, "Executor::handleException: Popping frame entry: %ls\n", v.toString().c_str()); #endif if (v.type == VALUE_FRAME) { if (v.pointer != frame) { fprintf(stderr, "Executor::handleException: ERROR: Frame is not our frame!?\n"); } break; } } } else { // There is an exception handler! #ifdef DEBUG_EXECUTOR fprintf( stderr, "Executor::handleException: %ls:%04" PRIx64 ": 0x%" PRIx64 " -> Found handler!\n", frame->code->function->getFullName().c_str(), thisPC, opcode); #endif ExceptionHandler handler = frame->handlerStack.back(); frame->handlerStack.pop_back(); context->clearException(); frame->pc = handler.handlerPC; frame->localVars[handler.excepVar] = context->getExceptionValue(); context->getExceptionValue(); } return success; }
lgpl-3.0
pcolby/libqtaws
src/opsworks/describetimebasedautoscalingrequest.cpp
6871
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "describetimebasedautoscalingrequest.h" #include "describetimebasedautoscalingrequest_p.h" #include "describetimebasedautoscalingresponse.h" #include "opsworksrequest_p.h" namespace QtAws { namespace OpsWorks { /*! * \class QtAws::OpsWorks::DescribeTimeBasedAutoScalingRequest * \brief The DescribeTimeBasedAutoScalingRequest class provides an interface for OpsWorks DescribeTimeBasedAutoScaling requests. * * \inmodule QtAwsOpsWorks * * <fullname>AWS OpsWorks</fullname> * * Welcome to the <i>AWS OpsWorks Stacks API Reference</i>. This guide provides descriptions, syntax, and usage examples * for AWS OpsWorks Stacks actions and data types, including common parameters and error codes. * * </p * * AWS OpsWorks Stacks is an application management service that provides an integrated experience for overseeing the * complete application lifecycle. For information about this product, go to the <a * href="http://aws.amazon.com/opsworks/">AWS OpsWorks</a> details page. * * </p * * <b>SDKs and CLI</b> * * </p * * The most common way to use the AWS OpsWorks Stacks API is by using the AWS Command Line Interface (CLI) or by using one * of the AWS SDKs to implement applications in your preferred language. For more information, * * see> <ul> <li> * * <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html">AWS CLI</a> * * </p </li> <li> * * <a * href="https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/opsworks/AWSOpsWorksClient.html">AWS * SDK for Java</a> * * </p </li> <li> * * <a href="https://docs.aws.amazon.com/sdkfornet/latest/apidocs/html/N_Amazon_OpsWorks.htm">AWS SDK for .NET</a> * * </p </li> <li> * * <a href="https://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.OpsWorks.OpsWorksClient.html">AWS SDK for PHP 2</a> * * </p </li> <li> * * <a href="http://docs.aws.amazon.com/sdkforruby/api/">AWS SDK for Ruby</a> * * </p </li> <li> * * <a href="http://aws.amazon.com/documentation/sdkforjavascript/">AWS SDK for Node.js</a> * * </p </li> <li> * * <a href="http://docs.pythonboto.org/en/latest/ref/opsworks.html">AWS SDK for Python(Boto)</a> * * </p </li> </ul> * * <b>Endpoints</b> * * </p * * AWS OpsWorks Stacks supports the following endpoints, all HTTPS. You must connect to one of the following endpoints. * Stacks can only be accessed or managed within the endpoint in which they are * * created> <ul> <li> * * opsworks.us-east-1.amazonaws.co> </li> <li> * * opsworks.us-east-2.amazonaws.co> </li> <li> * * opsworks.us-west-1.amazonaws.co> </li> <li> * * opsworks.us-west-2.amazonaws.co> </li> <li> * * opsworks.ca-central-1.amazonaws.com (API only; not available in the AWS * * console> </li> <li> * * opsworks.eu-west-1.amazonaws.co> </li> <li> * * opsworks.eu-west-2.amazonaws.co> </li> <li> * * opsworks.eu-west-3.amazonaws.co> </li> <li> * * opsworks.eu-central-1.amazonaws.co> </li> <li> * * opsworks.ap-northeast-1.amazonaws.co> </li> <li> * * opsworks.ap-northeast-2.amazonaws.co> </li> <li> * * opsworks.ap-south-1.amazonaws.co> </li> <li> * * opsworks.ap-southeast-1.amazonaws.co> </li> <li> * * opsworks.ap-southeast-2.amazonaws.co> </li> <li> * * opsworks.sa-east-1.amazonaws.co> </li> </ul> * * <b>Chef Versions</b> * * </p * * When you call <a>CreateStack</a>, <a>CloneStack</a>, or <a>UpdateStack</a> we recommend you use the * <code>ConfigurationManager</code> parameter to specify the Chef version. The recommended and default value for Linux * stacks is currently 12. Windows stacks use Chef 12.2. For more information, see <a * href="https://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-chef11.html">Chef * * Versions</a>> <note> * * You can specify Chef 12, 11.10, or 11.4 for your Linux stack. We recommend migrating your existing Linux stacks to Chef * 12 as soon as * * \sa OpsWorksClient::describeTimeBasedAutoScaling */ /*! * Constructs a copy of \a other. */ DescribeTimeBasedAutoScalingRequest::DescribeTimeBasedAutoScalingRequest(const DescribeTimeBasedAutoScalingRequest &other) : OpsWorksRequest(new DescribeTimeBasedAutoScalingRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a DescribeTimeBasedAutoScalingRequest object. */ DescribeTimeBasedAutoScalingRequest::DescribeTimeBasedAutoScalingRequest() : OpsWorksRequest(new DescribeTimeBasedAutoScalingRequestPrivate(OpsWorksRequest::DescribeTimeBasedAutoScalingAction, this)) { } /*! * \reimp */ bool DescribeTimeBasedAutoScalingRequest::isValid() const { return false; } /*! * Returns a DescribeTimeBasedAutoScalingResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * DescribeTimeBasedAutoScalingRequest::response(QNetworkReply * const reply) const { return new DescribeTimeBasedAutoScalingResponse(*this, reply); } /*! * \class QtAws::OpsWorks::DescribeTimeBasedAutoScalingRequestPrivate * \brief The DescribeTimeBasedAutoScalingRequestPrivate class provides private implementation for DescribeTimeBasedAutoScalingRequest. * \internal * * \inmodule QtAwsOpsWorks */ /*! * Constructs a DescribeTimeBasedAutoScalingRequestPrivate object for OpsWorks \a action, * with public implementation \a q. */ DescribeTimeBasedAutoScalingRequestPrivate::DescribeTimeBasedAutoScalingRequestPrivate( const OpsWorksRequest::Action action, DescribeTimeBasedAutoScalingRequest * const q) : OpsWorksRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the DescribeTimeBasedAutoScalingRequest * class' copy constructor. */ DescribeTimeBasedAutoScalingRequestPrivate::DescribeTimeBasedAutoScalingRequestPrivate( const DescribeTimeBasedAutoScalingRequestPrivate &other, DescribeTimeBasedAutoScalingRequest * const q) : OpsWorksRequestPrivate(other, q) { } } // namespace OpsWorks } // namespace QtAws
lgpl-3.0
nitely/ochDownloader
plugins/jumbofiles_com/anonym_download.py
1013
#python libs import logging logger = logging.getLogger(__name__) #Libs from core.plugin.base import PluginBase BASE_URL = "http://jumbofiles.com" class PluginDownload(PluginBase): def parse(self): link = self.link file_id = self.link.split('jumbofiles.com/')[-1].split('/')[0] form = [("op", "download3"), ('id', file_id), ('rand', '')] page = self.get_page(link, form=form) self.source = self.click('METHOD="LINK" ACTION="(?P<link>[^"]+)', page, False) #m = self.get_match('name="rand" value="(?P<rand>[^"]+)', page) #if m is not None: #rand = m.group('rand') #file_id = self.link.split('jumbofiles.com/')[-1].split('/')[0] #form = [("op", "download2"), ('id', file_id), ('rand', rand), # ('referer', ''), ('method_free', ''), ('method_premium', '')] #page = self.get_page(link, form=form) #else: #something changed # pass if __name__ == "__main__": pass
lgpl-3.0
Borisbee1/Kopernicus
Kopernicus/Kopernicus/Configuration/ModLoader/HeightColorMap.cs
7614
/** * Kopernicus Planetary System Modifier * ==================================== * Created by: BryceSchroeder and Teknoman117 (aka. Nathaniel R. Lewis) * Maintained by: Thomas P., NathanKell and KillAshley * Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace * ------------------------------------------------------------- * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * * This library is intended to be used as a plugin for Kerbal Space Program * which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program * itself is governed by the terms of its EULA, not the license above. * * https://kerbalspaceprogram.com */ using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Kopernicus { namespace Configuration { namespace ModLoader { [RequireConfigType(ConfigType.Node)] public class HeightColorMap : ModLoader<PQSMod_HeightColorMap>, IParserEventSubscriber { // Land class loader public class LandClassLoader { // Land class object public PQSMod_HeightColorMap.LandClass landClass; // Name of the class [ParserTarget("name")] public string name { get { return landClass.name; } set { landClass.name = value; } } // Delete the landclass [ParserTarget("delete", optional = true)] public NumericParser<bool> delete = new NumericParser<bool>(false); // Color of the class [ParserTarget("color")] public ColorParser color { get { return landClass.color; } set { landClass.color = value; } } // Fractional altitude start // altitude = (vertexHeight - vertexMinHeightOfPQS) / vertexHeightDeltaOfPQS [ParserTarget("altitudeStart")] public NumericParser<double> altitudeStart { get { return landClass.altStart; } set { landClass.altStart = value; } } // Fractional altitude end [ParserTarget("altitudeEnd")] public NumericParser<double> altitudeEnd { get { return landClass.altEnd; } set { landClass.altEnd = value; } } // Should we blend into the next class [ParserTarget("lerpToNext")] public NumericParser<bool> lerpToNext { get { return landClass.lerpToNext; } set { landClass.lerpToNext = value; } } public LandClassLoader () { // Initialize the land class landClass = new PQSMod_HeightColorMap.LandClass("class", 0.0, 0.0, Color.white, Color.white, 0.0); } public LandClassLoader(PQSMod_HeightColorMap.LandClass c) { landClass = c; } } // The deformity of the simplex terrain [ParserTarget("blend", optional = true)] public NumericParser<float> blend { get { return mod.blend; } set { mod.blend = value.value; } } // The land classes public List<LandClassLoader> landClasses = new List<LandClassLoader> (); void IParserEventSubscriber.Apply(ConfigNode node) { // Load the LandClasses manually, to support patching if (mod.landClasses != null) mod.landClasses.ToList().ForEach(c => landClasses.Add(new LandClassLoader(c))); if (node.HasNode("LandClasses")) { // Already patched classes List<PQSMod_HeightColorMap.LandClass> patchedClasses = new List<PQSMod_HeightColorMap.LandClass>(); // Go through the nodes foreach (ConfigNode lcNode in node.GetNode("LandClasses").nodes) { // The Loader LandClassLoader loader = null; // Are there existing LandClasses? if (landClasses.Count > 0) { // Attempt to find a LandClass we can edit that we have not edited before loader = landClasses.Where(m => !patchedClasses.Contains(m.landClass) && ((lcNode.HasValue("name") ? m.landClass.name == lcNode.GetValue("name") : true) || (lcNode.HasValue("index") ? landClasses.IndexOf(m).ToString() == lcNode.GetValue("index") : false))) .FirstOrDefault(); // Load the Loader (lol) if (loader != null) { Parser.LoadObjectFromConfigurationNode(loader, lcNode); landClasses.Remove(loader); patchedClasses.Add(loader.landClass); } } // If we can't patch a LandClass, create a new one if (loader == null) { loader = Parser.CreateObjectFromConfigNode<LandClassLoader>(lcNode); } // Add the Loader to the List if (!loader.delete.value) landClasses.Add(loader); } } } // Select the land class objects and push into the mod void IParserEventSubscriber.PostApply(ConfigNode node) { PQSMod_HeightColorMap.LandClass[] landClassesArray = landClasses.Select(loader => loader.landClass).ToArray(); if (landClassesArray.Count() != 0) { mod.landClasses = landClassesArray; } mod.lcCount = mod.landClasses.Length; } } } } }
lgpl-3.0
pcolby/libqtaws
src/iot/deletepolicyversionrequest.cpp
4338
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "deletepolicyversionrequest.h" #include "deletepolicyversionrequest_p.h" #include "deletepolicyversionresponse.h" #include "iotrequest_p.h" namespace QtAws { namespace IoT { /*! * \class QtAws::IoT::DeletePolicyVersionRequest * \brief The DeletePolicyVersionRequest class provides an interface for IoT DeletePolicyVersion requests. * * \inmodule QtAwsIoT * * <fullname>AWS IoT</fullname> * * AWS IoT provides secure, bi-directional communication between Internet-connected devices (such as sensors, actuators, * embedded devices, or smart appliances) and the AWS cloud. You can discover your custom IoT-Data endpoint to communicate * with, configure rules for data processing and integration with other services, organize resources associated with each * device (Registry), configure logging, and create and manage policies and credentials to authenticate * * devices> * * The service endpoints that expose this API are listed in <a * href="https://docs.aws.amazon.com/general/latest/gr/iot-core.html">AWS IoT Core Endpoints and Quotas</a>. You must use * the endpoint for the region that has the resources you want to * * access> * * The service name used by <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">AWS Signature * Version 4</a> to sign the request is: * * <i>execute-api</i>> * * For more information about how AWS IoT works, see the <a * href="https://docs.aws.amazon.com/iot/latest/developerguide/aws-iot-how-it-works.html">Developer * * Guide</a>> * * For information about how to use the credentials provider for AWS IoT, see <a * href="https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html">Authorizing Direct Calls to AWS * * \sa IoTClient::deletePolicyVersion */ /*! * Constructs a copy of \a other. */ DeletePolicyVersionRequest::DeletePolicyVersionRequest(const DeletePolicyVersionRequest &other) : IoTRequest(new DeletePolicyVersionRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a DeletePolicyVersionRequest object. */ DeletePolicyVersionRequest::DeletePolicyVersionRequest() : IoTRequest(new DeletePolicyVersionRequestPrivate(IoTRequest::DeletePolicyVersionAction, this)) { } /*! * \reimp */ bool DeletePolicyVersionRequest::isValid() const { return false; } /*! * Returns a DeletePolicyVersionResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * DeletePolicyVersionRequest::response(QNetworkReply * const reply) const { return new DeletePolicyVersionResponse(*this, reply); } /*! * \class QtAws::IoT::DeletePolicyVersionRequestPrivate * \brief The DeletePolicyVersionRequestPrivate class provides private implementation for DeletePolicyVersionRequest. * \internal * * \inmodule QtAwsIoT */ /*! * Constructs a DeletePolicyVersionRequestPrivate object for IoT \a action, * with public implementation \a q. */ DeletePolicyVersionRequestPrivate::DeletePolicyVersionRequestPrivate( const IoTRequest::Action action, DeletePolicyVersionRequest * const q) : IoTRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the DeletePolicyVersionRequest * class' copy constructor. */ DeletePolicyVersionRequestPrivate::DeletePolicyVersionRequestPrivate( const DeletePolicyVersionRequestPrivate &other, DeletePolicyVersionRequest * const q) : IoTRequestPrivate(other, q) { } } // namespace IoT } // namespace QtAws
lgpl-3.0
garyd203/flying-circus
src/flyingcircus/_raw/ssm.py
8231
"""Raw representations of every data type in the AWS SSM service. See Also: `AWS developer guide for SSM <https://docs.aws.amazon.com/systems-manager/latest/APIReference/Welcome.html>`_ This file is automatically generated, and should not be directly edited. """ from attr import attrib from attr import attrs from ..core import ATTRSCONFIG from ..core import Resource from ..core import ResourceProperties from ..core import create_object_converter __all__ = [ "Association", "AssociationProperties", "Document", "DocumentProperties", "MaintenanceWindow", "MaintenanceWindowProperties", "MaintenanceWindowTarget", "MaintenanceWindowTargetProperties", "MaintenanceWindowTask", "MaintenanceWindowTaskProperties", "Parameter", "ParameterProperties", "PatchBaseline", "PatchBaselineProperties", "ResourceDataSync", "ResourceDataSyncProperties", ] @attrs(**ATTRSCONFIG) class AssociationProperties(ResourceProperties): AssociationName = attrib(default=None) DocumentVersion = attrib(default=None) InstanceId = attrib(default=None) Name = attrib(default=None) OutputLocation = attrib(default=None) Parameters = attrib(default=None) ScheduleExpression = attrib(default=None) Targets = attrib(default=None) @attrs(**ATTRSCONFIG) class Association(Resource): """A Association for SSM. See Also: `AWS Cloud Formation documentation for Association <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html>`_ """ RESOURCE_TYPE = "AWS::SSM::Association" Properties: AssociationProperties = attrib( factory=AssociationProperties, converter=create_object_converter(AssociationProperties), ) @attrs(**ATTRSCONFIG) class DocumentProperties(ResourceProperties): Content = attrib(default=None) DocumentType = attrib(default=None) Name = attrib(default=None) Tags = attrib(default=None) @attrs(**ATTRSCONFIG) class Document(Resource): """A Document for SSM. See Also: `AWS Cloud Formation documentation for Document <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-document.html>`_ """ RESOURCE_TYPE = "AWS::SSM::Document" Properties: DocumentProperties = attrib( factory=DocumentProperties, converter=create_object_converter(DocumentProperties), ) @attrs(**ATTRSCONFIG) class MaintenanceWindowProperties(ResourceProperties): AllowUnassociatedTargets = attrib(default=None) Cutoff = attrib(default=None) Description = attrib(default=None) Duration = attrib(default=None) EndDate = attrib(default=None) Name = attrib(default=None) Schedule = attrib(default=None) ScheduleTimezone = attrib(default=None) StartDate = attrib(default=None) Tags = attrib(default=None) @attrs(**ATTRSCONFIG) class MaintenanceWindow(Resource): """A Maintenance Window for SSM. See Also: `AWS Cloud Formation documentation for MaintenanceWindow <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindow.html>`_ """ RESOURCE_TYPE = "AWS::SSM::MaintenanceWindow" Properties: MaintenanceWindowProperties = attrib( factory=MaintenanceWindowProperties, converter=create_object_converter(MaintenanceWindowProperties), ) @attrs(**ATTRSCONFIG) class MaintenanceWindowTargetProperties(ResourceProperties): Description = attrib(default=None) Name = attrib(default=None) OwnerInformation = attrib(default=None) ResourceType = attrib(default=None) Targets = attrib(default=None) WindowId = attrib(default=None) @attrs(**ATTRSCONFIG) class MaintenanceWindowTarget(Resource): """A Maintenance Window Target for SSM. See Also: `AWS Cloud Formation documentation for MaintenanceWindowTarget <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtarget.html>`_ """ RESOURCE_TYPE = "AWS::SSM::MaintenanceWindowTarget" Properties: MaintenanceWindowTargetProperties = attrib( factory=MaintenanceWindowTargetProperties, converter=create_object_converter(MaintenanceWindowTargetProperties), ) @attrs(**ATTRSCONFIG) class MaintenanceWindowTaskProperties(ResourceProperties): Description = attrib(default=None) LoggingInfo = attrib(default=None) MaxConcurrency = attrib(default=None) MaxErrors = attrib(default=None) Name = attrib(default=None) Priority = attrib(default=None) ServiceRoleArn = attrib(default=None) Targets = attrib(default=None) TaskArn = attrib(default=None) TaskInvocationParameters = attrib(default=None) TaskParameters = attrib(default=None) TaskType = attrib(default=None) WindowId = attrib(default=None) @attrs(**ATTRSCONFIG) class MaintenanceWindowTask(Resource): """A Maintenance Window Task for SSM. See Also: `AWS Cloud Formation documentation for MaintenanceWindowTask <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html>`_ """ RESOURCE_TYPE = "AWS::SSM::MaintenanceWindowTask" Properties: MaintenanceWindowTaskProperties = attrib( factory=MaintenanceWindowTaskProperties, converter=create_object_converter(MaintenanceWindowTaskProperties), ) @attrs(**ATTRSCONFIG) class ParameterProperties(ResourceProperties): AllowedPattern = attrib(default=None) Description = attrib(default=None) Name = attrib(default=None) Policies = attrib(default=None) Tags = attrib(default=None) Tier = attrib(default=None) Type = attrib(default=None) Value = attrib(default=None) @attrs(**ATTRSCONFIG) class Parameter(Resource): """A Parameter for SSM. See Also: `AWS Cloud Formation documentation for Parameter <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-parameter.html>`_ """ RESOURCE_TYPE = "AWS::SSM::Parameter" Properties: ParameterProperties = attrib( factory=ParameterProperties, converter=create_object_converter(ParameterProperties), ) @attrs(**ATTRSCONFIG) class PatchBaselineProperties(ResourceProperties): ApprovalRules = attrib(default=None) ApprovedPatches = attrib(default=None) ApprovedPatchesComplianceLevel = attrib(default=None) ApprovedPatchesEnableNonSecurity = attrib(default=None) Description = attrib(default=None) GlobalFilters = attrib(default=None) Name = attrib(default=None) OperatingSystem = attrib(default=None) PatchGroups = attrib(default=None) RejectedPatches = attrib(default=None) RejectedPatchesAction = attrib(default=None) Sources = attrib(default=None) Tags = attrib(default=None) @attrs(**ATTRSCONFIG) class PatchBaseline(Resource): """A Patch Baseline for SSM. See Also: `AWS Cloud Formation documentation for PatchBaseline <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html>`_ """ RESOURCE_TYPE = "AWS::SSM::PatchBaseline" Properties: PatchBaselineProperties = attrib( factory=PatchBaselineProperties, converter=create_object_converter(PatchBaselineProperties), ) @attrs(**ATTRSCONFIG) class ResourceDataSyncProperties(ResourceProperties): BucketName = attrib(default=None) BucketPrefix = attrib(default=None) BucketRegion = attrib(default=None) KMSKeyArn = attrib(default=None) SyncFormat = attrib(default=None) SyncName = attrib(default=None) @attrs(**ATTRSCONFIG) class ResourceDataSync(Resource): """A Resource Data Sync for SSM. See Also: `AWS Cloud Formation documentation for ResourceDataSync <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-resourcedatasync.html>`_ """ RESOURCE_TYPE = "AWS::SSM::ResourceDataSync" Properties: ResourceDataSyncProperties = attrib( factory=ResourceDataSyncProperties, converter=create_object_converter(ResourceDataSyncProperties), )
lgpl-3.0
SonarOpenCommunity/sonar-cxx
cxx-squid-bridge/src/test/java/org/sonar/cxx/squidbridge/checks/AbstractParseErrorCheckTest.java
1688
/* * C++ Community Plugin (cxx plugin) * Copyright (C) 2021 SonarOpenCommunity * http://github.com/SonarOpenCommunity/sonar-cxx * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * fork of SSLR Squid Bridge: https://github.com/SonarSource/sslr-squid-bridge/tree/2.6.1 * Copyright (C) 2010 SonarSource / mailto: [email protected] / license: LGPL v3 */ package org.sonar.cxx.squidbridge.checks; import com.sonar.sslr.api.Grammar; import org.junit.Rule; import org.junit.Test; import static org.sonar.cxx.squidbridge.metrics.ResourceParser.scanFile; public class AbstractParseErrorCheckTest { @Rule public CheckMessagesVerifierRule checkMessagesVerifier = new CheckMessagesVerifierRule(); private static class Check extends AbstractParseErrorCheck<Grammar> { } private Check check = new Check(); @Test public void parseError() { checkMessagesVerifier.verify(scanFile("/checks/parse_error.mc", check).getCheckMessages()) .next().atLine(3); } }
lgpl-3.0
impetus-opensource/jumbune
remoting/src/main/java/org/jumbune/remoting/client/Remoter.java
3890
package org.jumbune.remoting.client; import org.jumbune.remoting.common.command.CommandWritable; /** * The Class Remoter. */ public interface Remoter { /** * client side api to send jar files to the jumbune-agent {server}. * * @param destinationRelativePath , Relative Destination Directory on JumbuneAgent. An example can be 'Job-123/ABC', then local jar will be send in * <JumbuneAgentreceiveDir>/Job-123/ABC/myjob.jar * @param jarAbsolutePathAtSource , Absolute Path of Jar which requires to be send. This could be '/home/impadmin/Desktop/Jumbune_Home/JobJars/Job-456/MRSolution.jar' * . */ public void sendJar(String destinationRelativePath, String jarAbsolutePathAtSource); /** * client side api to receive jar files from the jumbune-agent {server}. * Creates the destination folder if it doesn't exist * @param destinationRelativePathOnLocal , Relative Destination Directory on Remoter. An example can be 'Job-123/ABC', then remote jar will be received in * <remoterreceiveDir>/Job-123/ABC/myjob.jar * @param relativePathOfRemoteJar , Relative Path of Remote Jar which requires to be fetched. This could be 'Job-456/MRSolution.jar', then we will fetch * <jumbuneagentreceiveDir>/Job-456/MRSolution.jar from JumbuneAgent */ public void receiveJar(String destinationRelativePathOnLocal, String relativePathOfRemoteJar); /** * client side api to send log files to the jumbune-agent {server}. * * @param destinationRelativePath , Relative Destination Directory on JumbuneAgent. An example can be 'Job-123/ABC', then local log will be send in * <JumbuneAgentreceiveDir>/Job-123/ABC/mmc.log * @param logFilesAbsolutePathAtSource , Absolute Path of Log files which requires to be send. This could be '/home/impadmin/Desktop/Jumbune_Home/JobJars/Job-456/mmc.log'. */ public void sendLogFiles(String destinationRelativePath, String logFilesAbsolutePathAtSource); /** * client side api to receive log files from the jumbune-agent {server}. * Creates the destination folder if it doesn't exist * @param destinationRelativePathOnLocal , Relative Destination Directory on Remoter. An example can be 'Job-123/ABC', then remote log files will be received in * <remoterreceiveDir>/Job-123/ABC/mmc.log * @param relativePathOfRemoteLogFiles , Relative Path of Remote Log files which requires to be fetched. This could be a folder containing log files or a log file, for * example, 'Job-456/mmc.log', then we will fetch <jumbuneagentreceiveDir>/Job-456/mmc.log from JumbuneAgent */ public void receiveLogFiles(String destinationRelativePathOnLocal, String relativePathOfRemoteLogFiles); /** * Fire and forget command. * Example usage: CommandWritable commandWritable = new CommandWritable(); commandWritable.setCommandString("Sending Command"); remoter.fireAndForgetCommand(commandWritable); * @param command the command */ public void fireAndForgetCommand(CommandWritable commandWritable); /** * Fire and forget command asynchronous * Example usage: CommandWritable commandWritable = new CommandWritable(); commandWritable.setCommandString("Sending Command"); remoter.fireAndForgetCommandAsync(commandWritable); * @param command the command */ //TODO: test fireAsyncAndForgetCommand method, create async method for fire and get object response public void fireAsyncAndForgetCommand(CommandWritable commandWritable); /** * Fire typed command and get object response. * Example Usage: * CommandWritable commandWritable = new CommandWritable(); commandWritable.setCommandForMaster(true); commandWritable.setUsername("JumbuneUser"); remoter.fireCommandAndGetObjectResponse(commandWritable); * @param command the command * @return the object */ public Object fireCommandAndGetObjectResponse(CommandWritable commandWritable); public void shutdownAgent(); public void close(); }
lgpl-3.0
joansmith/sonarqube
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/ExclusionFiltersTest.java
5975
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.batch.scan.filesystem; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.CoreProperties; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.config.Settings; import org.sonar.api.scan.filesystem.FileExclusions; import java.io.File; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class ExclusionFiltersTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void no_inclusions_nor_exclusions() throws IOException { ExclusionFilters filter = new ExclusionFilters(new FileExclusions(new Settings())); filter.prepare(); java.io.File file = temp.newFile(); DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setModuleBaseDir(temp.newFolder().toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue(); assertThat(filter.accept(inputFile, InputFile.Type.TEST)).isTrue(); } @Test public void match_inclusion() throws IOException { Settings settings = new Settings(); settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "**/*Dao.java"); ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings)); filter.prepare(); java.io.File file = temp.newFile(); DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setModuleBaseDir(temp.newFolder().toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue(); inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setModuleBaseDir(temp.newFolder().toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isFalse(); } @Test public void match_at_least_one_inclusion() throws IOException { Settings settings = new Settings(); settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "**/*Dao.java,**/*Dto.java"); ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings)); filter.prepare(); java.io.File file = temp.newFile(); DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setModuleBaseDir(temp.newFolder().toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isFalse(); inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDto.java").setModuleBaseDir(temp.newFolder().toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue(); } @Test public void match_exclusions() throws IOException { Settings settings = new Settings(); settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "src/main/java/**/*"); settings.setProperty(CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY, "src/test/java/**/*"); settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, "**/*Dao.java"); ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings)); filter.prepare(); java.io.File file = temp.newFile(); DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setModuleBaseDir(temp.newFolder().toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isFalse(); inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setModuleBaseDir(temp.newFolder().toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue(); // source exclusions do not apply to tests inputFile = new DefaultInputFile("foo", "src/test/java/com/mycompany/FooDao.java").setModuleBaseDir(temp.newFolder().toPath()); assertThat(filter.accept(inputFile, InputFile.Type.TEST)).isTrue(); } @Test public void match_exclusion_by_absolute_path() throws IOException { File baseDir = temp.newFile(); File excludedFile = new File(baseDir, "src/main/java/org/bar/Bar.java"); Settings settings = new Settings(); settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "src/main/java/**/*"); settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, "file:" + excludedFile.getCanonicalPath()); ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings)); filter.prepare(); DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/org/bar/Foo.java").setModuleBaseDir(baseDir.toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue(); inputFile = new DefaultInputFile("foo", "src/main/java/org/bar/Bar.java").setModuleBaseDir(baseDir.toPath()); assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isFalse(); } @Test public void trim_pattern() { Settings settings = new Settings(); settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, " **/*Dao.java "); ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings)); assertThat(filter.prepareMainExclusions()[0].toString()).isEqualTo("**/*Dao.java"); } }
lgpl-3.0
bullda/DroidText
src/bouncycastle/repack/org/bouncycastle/asn1/crmf/EncryptedValue.java
5064
package repack.org.bouncycastle.asn1.crmf; import repack.org.bouncycastle.asn1.ASN1Encodable; import repack.org.bouncycastle.asn1.ASN1EncodableVector; import repack.org.bouncycastle.asn1.ASN1OctetString; import repack.org.bouncycastle.asn1.ASN1Sequence; import repack.org.bouncycastle.asn1.ASN1TaggedObject; import repack.org.bouncycastle.asn1.DERBitString; import repack.org.bouncycastle.asn1.DERObject; import repack.org.bouncycastle.asn1.DERSequence; import repack.org.bouncycastle.asn1.DERTaggedObject; import repack.org.bouncycastle.asn1.x509.AlgorithmIdentifier; public class EncryptedValue extends ASN1Encodable { private AlgorithmIdentifier intendedAlg; private AlgorithmIdentifier symmAlg; private DERBitString encSymmKey; private AlgorithmIdentifier keyAlg; private ASN1OctetString valueHint; private DERBitString encValue; private EncryptedValue(ASN1Sequence seq) { int index = 0; while (seq.getObjectAt(index) instanceof ASN1TaggedObject) { ASN1TaggedObject tObj = (ASN1TaggedObject)seq.getObjectAt(index); switch (tObj.getTagNo()) { case 0: intendedAlg = AlgorithmIdentifier.getInstance(tObj, false); break; case 1: symmAlg = AlgorithmIdentifier.getInstance(tObj, false); break; case 2: encSymmKey = DERBitString.getInstance(tObj, false); break; case 3: keyAlg = AlgorithmIdentifier.getInstance(tObj, false); break; case 4: valueHint = ASN1OctetString.getInstance(tObj, false); break; } index++; } encValue = DERBitString.getInstance(seq.getObjectAt(index)); } public static EncryptedValue getInstance(Object o) { if (o instanceof EncryptedValue) { return (EncryptedValue)o; } else if (o != null) { return new EncryptedValue(ASN1Sequence.getInstance(o)); } return null; } public EncryptedValue( AlgorithmIdentifier intendedAlg, AlgorithmIdentifier symmAlg, DERBitString encSymmKey, AlgorithmIdentifier keyAlg, ASN1OctetString valueHint, DERBitString encValue) { if (encValue == null) { throw new IllegalArgumentException("'encValue' cannot be null"); } this.intendedAlg = intendedAlg; this.symmAlg = symmAlg; this.encSymmKey = encSymmKey; this.keyAlg = keyAlg; this.valueHint = valueHint; this.encValue = encValue; } public AlgorithmIdentifier getIntendedAlg() { return intendedAlg; } public AlgorithmIdentifier getSymmAlg() { return symmAlg; } public DERBitString getEncSymmKey() { return encSymmKey; } public AlgorithmIdentifier getKeyAlg() { return keyAlg; } public ASN1OctetString getValueHint() { return valueHint; } public DERBitString getEncValue() { return encValue; } /** * <pre> * EncryptedValue ::= SEQUENCE { * intendedAlg [0] AlgorithmIdentifier OPTIONAL, * -- the intended algorithm for which the value will be used * symmAlg [1] AlgorithmIdentifier OPTIONAL, * -- the symmetric algorithm used to encrypt the value * encSymmKey [2] BIT STRING OPTIONAL, * -- the (encrypted) symmetric key used to encrypt the value * keyAlg [3] AlgorithmIdentifier OPTIONAL, * -- algorithm used to encrypt the symmetric key * valueHint [4] OCTET STRING OPTIONAL, * -- a brief description or identifier of the encValue content * -- (may be meaningful only to the sending entity, and used only * -- if EncryptedValue might be re-examined by the sending entity * -- in the future) * encValue BIT STRING } * -- the encrypted value itself * </pre> * @return a basic ASN.1 object representation. */ public DERObject toASN1Object() { ASN1EncodableVector v = new ASN1EncodableVector(); addOptional(v, 0, intendedAlg); addOptional(v, 1, symmAlg); addOptional(v, 2, encSymmKey); addOptional(v, 3, keyAlg); addOptional(v, 4, valueHint); v.add(encValue); return new DERSequence(v); } private void addOptional(ASN1EncodableVector v, int tagNo, ASN1Encodable obj) { if (obj != null) { v.add(new DERTaggedObject(false, tagNo, obj)); } } }
lgpl-3.0
weepingtown/utils
test/stdafx.cpp
201
// stdafx.cpp : Ö»°üÀ¨±ê×¼°üº¬ÎļþµÄÔ´Îļþ // test.pch ½«×÷ΪԤ±àÒëÍ· // stdafx.obj ½«°üº¬Ô¤±àÒëÀàÐÍÐÅÏ¢ #include "stdafx.h" // TODO: ÔÚ STDAFX.H ÖÐÒýÓÃÈκÎËùÐèµÄ¸½¼ÓÍ·Îļþ£¬ //¶ø²»ÊÇÔÚ´ËÎļþÖÐÒýÓÃ
lgpl-3.0
EndrII/Space_engine
SpaceEngine/GameObjects/EGameResurs.cpp
2116
#include "EGameResurs.h" EGameResurs::EGameResurs(const QString &Patch,EResursePack *pack){ READ_THIS(Patch) pack_=pack; class_=E_GAME_RESURS; } EGameResurs::EGameResurs(EObject *copy, EResursePack *pack): EObject() { this->copy(copy); QString patch=Objectpatch; pack_=pack; if(patch.mid(patch.size()-4)!="robj") patch+=".robj"; description=new EItem(pack->add(patch)); class_=E_GAME_RESURS; } EGameResurs::EGameResurs(EResurse *desc, const QString& createPatch, const EKord& size, const EKord& kord_, const QString &str): EObject(createPatch,size,kord_,str) { description= new EItem(desc); class_=E_GAME_RESURS; } void EGameResurs::size_to_value(){ setSize(EKord::Random(description->getValue()*massa*0.9,description->getValue()*massa*1.1,_h/_w)); } EItem *EGameResurs::getRes()const{ return description; } void EGameResurs::generateThisObject(EResurse *r){ READ_THIS(r->url()) } void EGameResurs::saveObject(QString patch){ if(patch.isEmpty()) patch=Objectpatch; if(patch.mid(patch.size()-4)!="robj") patch+=".robj"; Objectpatch=patch; description->getSource()->setUrl(Objectpatch); QFile f(patch); if(!f.open(QIODevice::WriteOnly|QIODevice::Truncate)){ throw EError("file not detected!","void EGameResurs::saveObject(QString patch)"); }else{ QDataStream s(&f); s<<*this; f.close(); } pack_->save(); } void EGameResurs::RandomValue(int max){ int temp=rand()%max; description->setValue(temp); size_to_value(); } QDataStream& operator<<(QDataStream&stream,EGameResurs&obj){ stream<<*((EObject*)&obj); stream<<(ui)obj.description->getValue(); stream<<(us)obj.description->getSource()->id(); return stream; } QDataStream& operator>>(QDataStream&stream,EGameResurs&obj){ stream>>*((EObject*)&obj); ui temp1; us temp2; stream>>temp1; stream>>temp2; obj.description=new EItem(EResursePack::getResurse(temp2)); obj.description->setValue(temp1); return stream; } EGameResurs::~EGameResurs(){ delete description; }
lgpl-3.0
demoiselle/mail
impl/src/main/java/br/gov/frameworkdemoiselle/mail/internal/implementation/FileAttachment.java
3250
/* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package br.gov.frameworkdemoiselle.mail.internal.implementation; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.activation.FileDataSource; import br.gov.frameworkdemoiselle.mail.MailException; import br.gov.frameworkdemoiselle.mail.internal.enums.ContentDisposition; public class FileAttachment extends BaseAttachment { private static final long serialVersionUID = 1L; public FileAttachment(ContentDisposition contentDisposition, File file) { super(); FileDataSource fileDataSource = new FileDataSource(file); try { super.setFileName(fileDataSource.getName()); super.setMimeType(fileDataSource.getContentType()); super.setContentDisposition(contentDisposition); super.setBytes(toByteArray(file)); } catch (IOException e) { throw new MailException("Can't create File Attachment", e); } } public byte[] toByteArray(File file) throws IOException { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; try { for (int readNum; (readNum = fis.read(buf)) != -1;) { bos.write(buf, 0, readNum); System.out.println("read " + readNum + " bytes,"); } } catch (IOException ex) { } byte[] bytes = bos.toByteArray(); return bytes; } }
lgpl-3.0
lazarcon/J_CPU_Simulation
CPU-Simulation/src/main/java/ch/zhaw/lazari/cpu/impl/utils/BooleanArrayUtils.java
3877
/* * File: BooleanArrayUtils.java * Date: Oct 22, 2013 * * Copyright 2013 Constantin Lazari. All rights reserved. * * Unless required by applicable law or agreed to in writing, this software * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. */ package ch.zhaw.lazari.cpu.impl.utils; /** * Provides utilities for arrays of boolean */ public final class BooleanArrayUtils { private static final int TRUE = 1; private static final int FALSE = 0; private BooleanArrayUtils() { // Avoid instantiation } /** * Converts an array of boolean into a string using the toDigit method. * * @param bits * Array of booleans to interpret * @return String, containing binary digits that represent the array */ public static String toBinaryString(final boolean[] bits) { final StringBuilder builder = new StringBuilder(bits.length); for (final boolean bit : bits) { builder.append(toDigit(bit)); } return builder.toString(); } /** * Converts a boolean into a digit. * * @param bit * the boolean to interpret * @return 1, if bit was <code>true</code>, 0 otherwise */ public static int toDigit(final boolean bit) { return (bit) ? TRUE : FALSE; } /** * Converts a digit into a binary. * * @param digit * the digit to convert * @return boolean matching the digit */ public static boolean fromDigit(final int digit) { if (digit != TRUE && digit != FALSE) { throw new InvalidArgumentException(String.format( "%d is not a valid digit to convert. Valid are 0 and 1.", digit)); } return digit == TRUE; } /** * Converts a boolean array to an integer * * @param bits * bits to convert * @return integer representing the bits */ public static int toInt(final boolean[] bits) { if (bits.length > Integer.SIZE) { throw new InvalidArgumentException( String.format( "Cannot convert '%s' to integer, because its to long (%d/%d)", toBinaryString(bits), bits.length, Integer.SIZE)); } int result = 0; for (int index = 1; index < bits.length; ++index) { if (bits[0]) { // bits[0] = MSB, if true, than the whole is negative result += toDigit(!bits[index]) * IntegerUtils.pow(2, bits.length - index - 1); } else { result += toDigit(bits[index]) * IntegerUtils.pow(2, bits.length - index - 1); } } return bits[0] ? -result -1 : result; } public static boolean[] fromInt(final int value, final int length) { boolean[] result = new boolean[length]; final boolean isNegative = (value < 0); int divResult = isNegative ? -value : value; int index = length - 1; // Calc value while (divResult > 0) { final int remains = divResult % 2; result[index--] = (remains == 1); divResult /= 2; } if(isNegative) { result = invert(result); result = inc(result); } return result; } private static boolean[] invert(boolean[] result) { for(int i=0;i<result.length;i++) result[i] = !result[i]; return result; } public static boolean[] inc(boolean[] input) { boolean[] result = new boolean[input.length]; // boolean flag = input[input.length-1]; boolean add = true; for (int i = input.length - 1; i >= 0; i--) { result[i] = input[i] ^ add; // XOR add = input[i] && add; } return result; } public static int toInt(final String word) { final boolean[] bits = new boolean[word.length()]; int index = 0; for (char aChar : word.toCharArray()) { bits[index++] = fromDigit(Integer.parseInt("" + aChar)); } return toInt(bits); } public static boolean[] fromString(String s) { boolean[] result = new boolean[s.length()]; for (int i = 0; i < s.length(); i++){ char c = s.charAt(i); result[i] = c == '1'; } return result; } }
lgpl-3.0
intrications/MaterialAudiobookPlayer
audiobook/src/main/java/de/ph1b/audiobook/activity/FolderOverviewActivity.java
12828
package de.ph1b.audiobook.activity; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Intent; import android.graphics.Point; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.view.ViewAnimationUtils; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import java.util.ArrayList; import java.util.List; import de.ph1b.audiobook.R; import de.ph1b.audiobook.adapter.FolderOverviewAdapter; import de.ph1b.audiobook.model.BookAdder; import de.ph1b.audiobook.uitools.DividerItemDecoration; import de.ph1b.audiobook.utils.L; import de.ph1b.audiobook.utils.PrefsManager; public class FolderOverviewActivity extends BaseActivity { private static final String TAG = FolderOverviewActivity.class.getSimpleName(); private static final String BACKGROUND_OVERLAY_VISIBLE = "backgroundOverlayVisibility"; private final List<String> bookCollections = new ArrayList<>(); private final List<String> singleBooks = new ArrayList<>(); private PrefsManager prefs; private FolderOverviewAdapter adapter; private FloatingActionsMenu fam; private FloatingActionButton buttonRepresentingTheFam; private View backgroundOverlay; /** * @return the point representing the center of the floating action menus button. Note, that the * fam is only a container, so we have to calculate the point relatively. */ private Point getFamCenter() { int x = fam.getLeft() + ((buttonRepresentingTheFam.getLeft() + buttonRepresentingTheFam.getRight()) / 2); int y = fam.getTop() + ((buttonRepresentingTheFam.getTop() + buttonRepresentingTheFam.getBottom()) / 2); return new Point(x, y); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.home: case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_folder_overview); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getString(R.string.audiobook_folders_title)); } prefs = PrefsManager.getInstance(this); //init views RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler); fam = (FloatingActionsMenu) findViewById(R.id.fam); buttonRepresentingTheFam = (FloatingActionButton) findViewById(R.id.fab_expand_menu_button); backgroundOverlay = findViewById(R.id.overlay); if (savedInstanceState != null) { // restoring overlay if (savedInstanceState.getBoolean(BACKGROUND_OVERLAY_VISIBLE)) { backgroundOverlay.setVisibility(View.VISIBLE); } else { backgroundOverlay.setVisibility(View.GONE); } } fam.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() { @Override public void onMenuExpanded() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Point famCenter = getFamCenter(); int cx = famCenter.x; int cy = famCenter.y; // get the final radius for the clipping circle int finalRadius = Math.max(backgroundOverlay.getWidth(), backgroundOverlay.getHeight()); // create the animator for this view (the start radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(backgroundOverlay, cx, cy, 0, finalRadius); // make the view visible and start the animation backgroundOverlay.setVisibility(View.VISIBLE); anim.start(); } else { backgroundOverlay.setVisibility(View.VISIBLE); } } @Override public void onMenuCollapsed() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // get the center for the clipping circle Point famCenter = getFamCenter(); int cx = famCenter.x; int cy = famCenter.y; // get the initial radius for the clipping circle int initialRadius = Math.max(backgroundOverlay.getHeight(), backgroundOverlay.getWidth()); // create the animation (the final radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(backgroundOverlay, cx, cy, initialRadius, 0); // make the view invisible when the animation is done anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); backgroundOverlay.setVisibility(View.INVISIBLE); } }); // start the animation anim.start(); } else { backgroundOverlay.setVisibility(View.INVISIBLE); } } }); // preparing list final LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(layoutManager); recyclerView.addItemDecoration(new DividerItemDecoration(this)); adapter = new FolderOverviewAdapter(this, bookCollections, singleBooks, new FolderOverviewAdapter.OnFolderMoreClickedListener() { @Override public void onFolderMoreClicked(final int position) { new MaterialDialog.Builder(FolderOverviewActivity.this) .title(R.string.delete_folder) .content(getString(R.string.delete_folder_content) + "\n" + adapter.getItem(position)) .positiveText(R.string.remove) .negativeText(R.string.dialog_cancel) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { adapter.removeItem(position); prefs.setCollectionFolders(bookCollections); prefs.setSingleBookFolders(singleBooks); BookAdder.getInstance(FolderOverviewActivity.this).scanForFiles(true); } }) .show(); } }); recyclerView.setAdapter(adapter); FloatingActionButton single = (FloatingActionButton) findViewById(R.id.add_single); single.setTitle(getString(R.string.folder_add_book) + "\n" + getString(R.string.for_example) + " Harry Potter 4"); single.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fam.collapse(); Intent intent = new Intent(FolderOverviewActivity.this, FolderChooserActivity.class); int requestCode = FolderChooserActivity.ACTIVITY_FOR_RESULT_CODE_SINGLE_BOOK; intent.putExtra(FolderChooserActivity.ACTIVITY_FOR_RESULT_REQUEST_CODE, requestCode); startActivityForResult(intent, requestCode); } }); FloatingActionButton library = (FloatingActionButton) findViewById(R.id.add_library); library.setTitle(getString(R.string.folder_add_collection) + "\n" + getString(R.string.for_example) + " AudioBooks"); library.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fam.collapse(); Intent intent = new Intent(FolderOverviewActivity.this, FolderChooserActivity.class); int requestCode = FolderChooserActivity.ACTIVITY_FOR_RESULT_CODE_COLLECTION; intent.putExtra(FolderChooserActivity.ACTIVITY_FOR_RESULT_REQUEST_CODE, requestCode); startActivityForResult(intent, requestCode); } }); } private boolean canAddNewFolder(@NonNull final String newFile) { List<String> folders = new ArrayList<>(); folders.addAll(prefs.getCollectionFolders()); folders.addAll(prefs.getSingleBookFolders()); boolean filesAreSubsets = true; boolean firstAddedFolder = folders.size() == 0; boolean sameFolder = false; for (String s : folders) { if (s.equals(newFile)) { sameFolder = true; } String[] oldParts = s.split("/"); String[] newParts = newFile.split("/"); for (int i = 0; i < Math.min(oldParts.length, newParts.length); i++) { if (!oldParts[i].equals(newParts[i])) { filesAreSubsets = false; } } if (!sameFolder && filesAreSubsets) { Toast.makeText(this, getString(R.string.adding_failed_subfolder) + "\n" + s + "\n" + newFile, Toast.LENGTH_LONG).show(); } if (filesAreSubsets) { break; } } return firstAddedFolder || (!sameFolder && !filesAreSubsets); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case FolderChooserActivity.ACTIVITY_FOR_RESULT_CODE_COLLECTION: String chosenCollection = data.getStringExtra( FolderChooserActivity.CHOSEN_FILE); if (canAddNewFolder(chosenCollection)) { bookCollections.add(chosenCollection); prefs.setCollectionFolders(bookCollections); } L.v(TAG, "chosenCollection=" + chosenCollection); break; case FolderChooserActivity.ACTIVITY_FOR_RESULT_CODE_SINGLE_BOOK: String chosenSingleBook = data.getStringExtra( FolderChooserActivity.CHOSEN_FILE); if (canAddNewFolder(chosenSingleBook)) { singleBooks.add(chosenSingleBook); prefs.setSingleBookFolders(singleBooks); } L.v(TAG, "chosenSingleBook=" + chosenSingleBook); break; } BookAdder.getInstance(this).scanForFiles(true); } } @Override public void onBackPressed() { if (fam.isExpanded()) { fam.collapse(); } else { super.onBackPressed(); } } @Override protected void onResume() { super.onResume(); bookCollections.clear(); bookCollections.addAll(prefs.getCollectionFolders()); singleBooks.clear(); singleBooks.addAll(prefs.getSingleBookFolders()); adapter.notifyDataSetChanged(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(BACKGROUND_OVERLAY_VISIBLE, backgroundOverlay.getVisibility() == View.VISIBLE); super.onSaveInstanceState(outState); } }
lgpl-3.0
mapacheL/extensions
Signum.Entities.Extensions/Omnibox/EntityOmniboxResultGenerator.cs
5740
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Utilities; using Signum.Entities.Reflection; using System.Text.RegularExpressions; using Newtonsoft.Json; namespace Signum.Entities.Omnibox { public class EntityOmniboxResultGenenerator : OmniboxResultGenerator<EntityOmniboxResult> { public int AutoCompleteLimit = 5; Regex regex = new Regex(@"^I((?<id>N)|(?<id>G)|(?<toStr>S))?$", RegexOptions.ExplicitCapture); public override IEnumerable<EntityOmniboxResult> GetResults(string rawQuery, List<OmniboxToken> tokens, string tokenPattern) { Match m = regex.Match(tokenPattern); if (!m.Success) yield break; string ident = tokens[0].Value; bool isPascalCase = OmniboxUtils.IsPascalCasePattern(ident); var matches = OmniboxUtils.Matches(OmniboxParser.Manager.Types(), OmniboxParser.Manager.AllowedType, ident, isPascalCase); if (tokens.Count == 1) { yield break; } else if (tokens[1].Type == OmniboxTokenType.Number || tokens[1].Type == OmniboxTokenType.Guid) { foreach (var match in matches.OrderBy(ma => ma.Distance)) { Type type = (Type)match.Value; if (PrimaryKey.TryParse(tokens[1].Value, type, out PrimaryKey id)) { Lite<Entity> lite = OmniboxParser.Manager.RetrieveLite(type, id); yield return new EntityOmniboxResult { Type = (Type)match.Value, TypeMatch = match, Id = id, Lite = lite, Distance = match.Distance, }; } } } else if (tokens[1].Type == OmniboxTokenType.String) { string pattern = OmniboxUtils.CleanCommas(tokens[1].Value); foreach (var match in matches.OrderBy(ma => ma.Distance)) { var autoComplete = OmniboxParser.Manager.Autocomplete((Type)match.Value, pattern, AutoCompleteLimit); if (autoComplete.Any()) { foreach (Lite<Entity> lite in autoComplete) { OmniboxMatch distance = OmniboxUtils.Contains(lite, lite.ToString() ?? "", pattern); if (distance != null) yield return new EntityOmniboxResult { Type = (Type)match.Value, TypeMatch = match, ToStr = pattern, Lite = lite, Distance = match.Distance + distance.Distance, ToStrMatch = distance, }; } } else { yield return new EntityOmniboxResult { Type = (Type)match.Value, TypeMatch = match, Distance = match.Distance + 100, ToStr = pattern, }; } } } } public override List<HelpOmniboxResult> GetHelp() { var resultType = typeof(EntityOmniboxResult); var entityTypeName = OmniboxMessage.Omnibox_Type.NiceToString(); return new List<HelpOmniboxResult> { new HelpOmniboxResult { Text = "{0} Id".FormatWith(entityTypeName), ReferencedType = resultType }, new HelpOmniboxResult { Text = "{0} 'ToStr'".FormatWith(entityTypeName), ReferencedType = resultType } }; } } public class PrimaryKeyJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return true; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value == null ? null : ((PrimaryKey)value).Object); } public override bool CanRead => false; public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } } public class EntityOmniboxResult : OmniboxResult { [JsonIgnore] public Type Type { get; set; } public OmniboxMatch TypeMatch { get; set; } [JsonConverter(typeof(PrimaryKeyJsonConverter))] public PrimaryKey? Id { get; set; } public string ToStr { get; set; } public OmniboxMatch ToStrMatch { get; set; } public Lite<Entity> Lite { get; set; } public override string ToString() { if (Id.HasValue) return "{0} {1}".FormatWith(Type.NicePluralName().ToOmniboxPascal(), Id); if (ToStr != null) return "{0} \"{1}\"".FormatWith(Type.NicePluralName().ToOmniboxPascal(), ToStr); return Type.NicePluralName().ToOmniboxPascal(); } } }
lgpl-3.0
zenframework/z8
org.zenframework.z8.server/src/main/java/org/zenframework/z8/server/base/table/system/ScheduledJobs.java
7440
package org.zenframework.z8.server.base.table.system; import org.zenframework.z8.server.base.job.scheduler.Scheduler; import org.zenframework.z8.server.base.table.Table; import org.zenframework.z8.server.base.table.value.BoolField; import org.zenframework.z8.server.base.table.value.DatetimeField; import org.zenframework.z8.server.base.table.value.Link; import org.zenframework.z8.server.base.table.value.StringField; import org.zenframework.z8.server.resources.Resources; import org.zenframework.z8.server.runtime.IClass; import org.zenframework.z8.server.runtime.IObject; import org.zenframework.z8.server.types.bool; import org.zenframework.z8.server.types.exception; import org.zenframework.z8.server.types.guid; import org.zenframework.z8.server.types.string; import org.zenframework.z8.server.utils.Cron; public class ScheduledJobs extends Table { static public String TableName = "SystemScheduledJobs"; static public String DefaultCron = "0 * * * *"; static public int MinRepeat = 10; static public class fieldNames { public final static String Job = "Job"; public final static String User = "User"; public final static String Cron = "Cron"; public final static String Active = "Active"; public final static String LogErrorsOnly = "Log errors only"; public final static String LastStart = "LastStart"; public final static String NextStart = "NextStart"; } static public class strings { public final static String Title = "ScheduledJobs.title"; public final static String Job = "ScheduledJobs.job"; public final static String User = "ScheduledJobs.user"; public final static String Settings = "ScheduledJobs.settings"; public final static String Cron = "ScheduledJobs.cron"; public final static String Active = "ScheduledJobs.active"; public final static String LogErrorsOnly = "ScheduledJobs.logErrorsOnly"; public final static String LastStart = "ScheduledJobs.lastStart"; public final static String NextStart = "ScheduledJobs.nextStart"; } static public class displayNames { public final static String Title = Resources.get(strings.Title); public final static String Job = Resources.get(strings.Job); public final static String User = Resources.get(strings.User); public final static String Settings = Resources.get(strings.Settings); public final static String Cron = Resources.get(strings.Cron); public final static String Active = Resources.get(strings.Active); public final static String LogErrorsOnly = Resources.get(strings.LogErrorsOnly); public final static String LastStart = Resources.get(strings.LastStart); public final static String NextStart = Resources.get(strings.NextStart); } public static class CLASS<T extends Table> extends Table.CLASS<T> { public CLASS() { this(null); } public CLASS(IObject container) { super(container); setJavaClass(ScheduledJobs.class); setName(TableName); setDisplayName(displayNames.Title); } @Override public Object newObject(IObject container) { return new ScheduledJobs(container); } } public Jobs.CLASS<Jobs> jobs = new Jobs.CLASS<Jobs>(this); public Users.CLASS<Users> users = new Users.CLASS<Users>(this); public Link.CLASS<Link> job = new Link.CLASS<Link>(this); public Link.CLASS<Link> user = new Link.CLASS<Link>(this); public DatetimeField.CLASS<DatetimeField> lastStart = new DatetimeField.CLASS<DatetimeField>(this); public DatetimeField.CLASS<DatetimeField> nextStart = new DatetimeField.CLASS<DatetimeField>(this); public StringField.CLASS<StringField> cron = new StringField.CLASS<StringField>(this); public BoolField.CLASS<BoolField> active = new BoolField.CLASS<BoolField>(this); public BoolField.CLASS<BoolField> logErrorsOnly = new BoolField.CLASS<BoolField>(this); public ScheduledJobs(IObject container) { super(container); } @Override public void constructor1() { job.get(IClass.Constructor1).operatorAssign(jobs); user.get(IClass.Constructor1).operatorAssign(users); } @Override public void initMembers() { super.initMembers(); objects.add(job); objects.add(user); objects.add(cron); objects.add(lastStart); objects.add(nextStart); objects.add(active); objects.add(logErrorsOnly); objects.add(jobs); objects.add(users); } @Override public void constructor2() { super.constructor2(); jobs.setIndex("jobs"); users.setIndex("users"); description.setDisplayName(displayNames.Settings); job.setName(fieldNames.Job); job.setIndex("job"); user.setName(fieldNames.User); user.setIndex("user"); user.get().setDefault(Users.System); cron.setName(fieldNames.Cron); cron.setIndex("cron"); cron.setDisplayName(displayNames.Cron); lastStart.setName(fieldNames.LastStart); lastStart.setIndex("lastStart"); lastStart.setDisplayName(displayNames.LastStart); nextStart.setName(fieldNames.NextStart); nextStart.setIndex("nextStart"); nextStart.setDisplayName(displayNames.NextStart); active.setName(fieldNames.Active); active.setIndex("active"); active.setDisplayName(displayNames.Active); logErrorsOnly.setName(fieldNames.LogErrorsOnly); logErrorsOnly.setIndex("logErrorsOnly"); logErrorsOnly.setDisplayName(displayNames.LogErrorsOnly); cron.get().setDefault(new string(DefaultCron)); active.get().setDefault(bool.True); logErrorsOnly.get().setDefault(bool.True); } @Override public void afterCreate(guid recordId) { super.afterCreate(recordId); Scheduler.reset(); } @Override public void beforeUpdate(guid recordId) { super.beforeUpdate(recordId); if (cron.get().changed()) { String cronExp = cron.get().string().get(); if (cronExp.isEmpty()) active.get().set(bool.False); else if (!Cron.checkExp(cronExp)) throw new exception("CRON value must be a valid CRON expression:" + "\n +---------- minute (0 - 59)" + "\n | +-------- hour (0 - 23)" + "\n | | +------ day of month (1 - 31)" + "\n | | | +---- month (1 - 12)" + "\n | | | | +-- day of week (0 - 6)" + "\n | | | | |" + "\n X X X X X - CRON expression contains 5 fields" + "\n" + "\n Value of a field can be:" + "\n - asterisk '*' means any value" + "\n - number, i.e. '1', '2', etc." + "\n - period, i.e. '1-5', '2-23'" + "\n - asterisk or period with multiplicity, i.e. '*/2' (any even value), '2-9/3' (any value multiple of 3 between 2 and 9)" + "\n - comma-separated list of other values, i.e. '1,2-4,6-12/3,*/5'" + "\n" + "\n Examples:" + "\n * * * * * - every minute" + "\n */5 * * * * - every five minutes" + "\n 5 0 * * * - every day at 00:05" + "\n 15 14 1 * * - every 1st day of month at 14:15" + "\n 0 22 * * 1-5 - Monday to Friday at 22:00" + "\n 23 */2 * * * - at 23rd minute of every even hour" + "\n 15 10,13 * * 1,4 - Monday and Thursday at 10:15 and 13:15"); } } @Override public void afterUpdate(guid recordId) { super.afterUpdate(recordId); if (!lastStart.get().changed() && !nextStart.get().changed()) Scheduler.reset(); } @Override public void afterDestroy(guid recordId) { super.afterDestroy(recordId); Scheduler.reset(); } }
lgpl-3.0
travishathaway/canopy-story
resources/views/user/profile.blade.php
771
@extends('layouts.app') @section('content') <div class="row"> <div class="ml-auto col-sm-12 col-lg-6 mr-auto"> <h1 class="mt-4">@lang('site.profile')</h1> <hr /> <div id="user-profile"></div> </div> </div> @endsection @section('script') @parent <script> /** * User Profile obejct for app */ window.UserProfile = {}; window.UserProfile.user_resource_url = '/api/v1/user/{{$user->id}}'; window.UserProfile.trans = { 'first_name': '@lang('site.first_name')', 'last_name': '@lang('site.last_name')', 'email': '@lang('site.email')', 'edit': '@lang('site.edit')', 'save': '@lang('site.save')', 'cancel': '@lang('site.cancel')' } </script> <script src="{{mix('js/user-profile.js')}}"></script> @endsection
lgpl-3.0
lecterror/cakephp-naive-bayes-classifier-plugin
Model/BayesToken.php
3814
<?php /** CakePHP NaiveBayesClassifier Plugin Copyright (C) 2012-3827 dr. Hannibal Lecter / lecterror <http://lecterror.com/> Multi-licenced under: MPL <http://www.mozilla.org/MPL/MPL-1.1.html> LGPL <http://www.gnu.org/licenses/lgpl.html> GPL <http://www.gnu.org/licenses/gpl.html> */ App::uses('NaiveBayesClassifierAppModel', 'NaiveBayesClassifier.Model'); App::uses('BayesClass', 'NaiveBayesClassifier.Model'); App::uses('BayesTokenCounter', 'NaiveBayesClassifier.Model'); App::uses('Inflector', 'Utility'); App::uses('Hash', 'Utility'); /** * @property BayesTokenCounter $BayesTokenCounter */ class BayesToken extends NaiveBayesClassifierAppModel { public $hasMany = array ( 'BayesTokenCounter' => array('className' => 'NaiveBayesClassifier.BayesTokenCounter'), ); /** * Find tokens with one or more conditions: * * - token value(s) * - class + exclusive: only tokens with counters for specified class * - class - exclusive: all tokens, but counters only for specified class * * $options param takes the following values: * * - class: Class ID to use for counter filtering * - exlusive: If true, only those tokens which have counters for specified class will be returned * * @param mixed $tokens A single token value, or an array of tokens * @param array $options Filtering options * @return array Tokens found for the specified search params */ public function getTokenCounters($tokens = array(), $options = array()) { $defaultOptions = array('class' => null, 'exclusive' => false); $options = array_merge($defaultOptions, $options); $conditions = array(); if (!empty($tokens)) { $conditions = array('BayesToken.value' => $tokens); } $counters_conditions = array(); if (!empty($options['class'])) { $counters_conditions = array('BayesTokenCounter.bayes_class_id' => $options['class']); } $tokens = $this->find ( 'all', array ( 'conditions' => array ( $conditions, ), 'contain' => array ( 'BayesTokenCounter' => array ( 'conditions' => array ( $counters_conditions, ), ) ), ) ); if (!$options['exclusive']) { return $tokens; } $output = array(); $class_path = sprintf('BayesTokenCounter.{n}[bayes_class_id=%d]', $options['class']); foreach ($tokens as $key => $item) { if (Hash::check($item, $class_path)) { $output[] = $item; } } return $output; } /** * Tokenize a document. * * $options param takes the following values: * * - min_length: minimum token length, default 3 * - max_length: maximum token length, default 20 * * @param type $document Document to tokenize * @param type $options Options for tokenization * @return array Token array * @todo Add additional options, such as a custom regex, as well as entirely 3rd party tokenization */ public function tokenize($document, $options = array()) { $defaultOptions = array('min_length' => 3, 'max_length' => 20); $options = array_merge($defaultOptions, $options); $tokens = $this->_tokenize($document); $output = array(); foreach ($tokens as $token) { $token_length = strlen($token); if ($token_length < $options['min_length'] || $token_length > $options['max_length']) { continue; } if (!isset($output[$token])) { $output[$token] = 0; } $output[$token]++; } return $output; } private function _tokenize($document) { $document = Inflector::slug($document, ' '); $document = strtolower($document); $tokens = preg_split('#((\W+?)|[_!0-9])#', $document, -1, PREG_SPLIT_NO_EMPTY); #$tokens = preg_split('#[\s,\.\/"\:;\|<>\-_\[\]{}\+=\)\(\*\&\^%]+#', $document, -1, PREG_SPLIT_NO_EMPTY); return $tokens; } }
lgpl-3.0
shtrom/odtone
inc/odtone/exception.hpp
1593
//============================================================================= // Brief : Exception Base Class // Authors : Bruno Santos <[email protected]> // // // Copyright (C) 2009 Universidade Aveiro - Instituto de Telecomunicacoes Polo Aveiro // // This file is part of ODTONE - Open Dot Twenty One. // // This software is distributed under a license. The full license // agreement can be found in the file LICENSE in this distribution. // This software may not be copied, modified, sold or distributed // other than expressed in the named license agreement. // // This software is distributed without any warranty. //============================================================================= #ifndef ODTONE_EXCEPTION__HPP_ #define ODTONE_EXCEPTION__HPP_ /////////////////////////////////////////////////////////////////////////////// #include <boost/exception/exception.hpp> #include <boost/throw_exception.hpp> #include <exception> /////////////////////////////////////////////////////////////////////////////// namespace odtone { /////////////////////////////////////////////////////////////////////////////// class exception : virtual public boost::exception, virtual public std::exception { public: exception(char const* what = "<exception>") : _what(what) { } char const* what() const throw() { return _what; } private: char const* _what; }; /////////////////////////////////////////////////////////////////////////////// } /* namespace odtone */ // EOF //////////////////////////////////////////////////////////////////////// #endif /* ODTONE_EXCEPTION__HPP_ */
lgpl-3.0
FenixEdu/fenixedu-academic
src/main/java/org/fenixedu/academic/domain/Person.java
82937
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.domain; import static org.fenixedu.academic.predicate.AccessControl.check; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.common.collect.Streams; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.fenixedu.academic.domain.accounting.AcademicEvent; import org.fenixedu.academic.domain.accounting.CustomEvent; import org.fenixedu.academic.domain.accounting.Entry; import org.fenixedu.academic.domain.accounting.Event; import org.fenixedu.academic.domain.accounting.EventTemplate; import org.fenixedu.academic.domain.accounting.EventType; import org.fenixedu.academic.domain.accounting.PaymentCode; import org.fenixedu.academic.domain.accounting.PaymentCodeType; import org.fenixedu.academic.domain.accounting.Receipt; import org.fenixedu.academic.domain.accounting.ResidenceEvent; import org.fenixedu.academic.domain.accounting.ServiceAgreement; import org.fenixedu.academic.domain.accounting.ServiceAgreementTemplate; import org.fenixedu.academic.domain.accounting.events.AdministrativeOfficeFeeAndInsuranceEvent; import org.fenixedu.academic.domain.accounting.events.AdministrativeOfficeFeeEvent; import org.fenixedu.academic.domain.accounting.events.AnnualEvent; import org.fenixedu.academic.domain.accounting.events.PastAdministrativeOfficeFeeAndInsuranceEvent; import org.fenixedu.academic.domain.accounting.events.gratuity.GratuityEvent; import org.fenixedu.academic.domain.accounting.events.insurance.InsuranceEvent; import org.fenixedu.academic.domain.administrativeOffice.AdministrativeOffice; import org.fenixedu.academic.domain.candidacy.Candidacy; import org.fenixedu.academic.domain.candidacy.DegreeCandidacy; import org.fenixedu.academic.domain.candidacy.StudentCandidacy; import org.fenixedu.academic.domain.candidacyProcess.IndividualCandidacy; import org.fenixedu.academic.domain.candidacyProcess.IndividualCandidacyPersonalDetails; import org.fenixedu.academic.domain.candidacyProcess.graduatedPerson.DegreeCandidacyForGraduatedPerson; import org.fenixedu.academic.domain.candidacyProcess.over23.Over23IndividualCandidacy; import org.fenixedu.academic.domain.candidacyProcess.secondCycle.SecondCycleIndividualCandidacy; import org.fenixedu.academic.domain.candidacyProcess.standalone.StandaloneIndividualCandidacy; import org.fenixedu.academic.domain.contacts.EmailAddress; import org.fenixedu.academic.domain.contacts.MobilePhone; import org.fenixedu.academic.domain.contacts.PartyContact; import org.fenixedu.academic.domain.contacts.PartyContactType; import org.fenixedu.academic.domain.contacts.Phone; import org.fenixedu.academic.domain.contacts.PhysicalAddress; import org.fenixedu.academic.domain.contacts.PhysicalAddressData; import org.fenixedu.academic.domain.contacts.WebAddress; import org.fenixedu.academic.domain.degree.DegreeType; import org.fenixedu.academic.domain.documents.AnnualIRSDeclarationDocument; import org.fenixedu.academic.domain.documents.GeneratedDocument; import org.fenixedu.academic.domain.exceptions.DomainException; import org.fenixedu.academic.domain.organizationalStructure.Accountability; import org.fenixedu.academic.domain.organizationalStructure.AccountabilityType; import org.fenixedu.academic.domain.organizationalStructure.AccountabilityTypeEnum; import org.fenixedu.academic.domain.organizationalStructure.Party; import org.fenixedu.academic.domain.organizationalStructure.Unit; import org.fenixedu.academic.domain.person.Gender; import org.fenixedu.academic.domain.person.IDDocumentType; import org.fenixedu.academic.domain.person.IdDocument; import org.fenixedu.academic.domain.person.IdDocumentTypeObject; import org.fenixedu.academic.domain.person.MaritalStatus; import org.fenixedu.academic.domain.person.RoleType; import org.fenixedu.academic.domain.phd.alert.PhdAlertMessage; import org.fenixedu.academic.domain.phd.candidacy.PHDProgramCandidacy; import org.fenixedu.academic.domain.student.Registration; import org.fenixedu.academic.domain.student.RegistrationProtocol; import org.fenixedu.academic.dto.person.PersonBean; import org.fenixedu.academic.predicate.AcademicPredicates; import org.fenixedu.academic.predicate.AccessControl; import org.fenixedu.academic.util.Bundle; import org.fenixedu.academic.util.Money; import org.fenixedu.academic.util.PeriodState; import org.fenixedu.academic.util.StringFormatter; import org.fenixedu.bennu.core.domain.Bennu; import org.fenixedu.bennu.core.domain.User; import org.fenixedu.bennu.core.domain.UserProfile; import org.fenixedu.bennu.core.domain.exceptions.BennuCoreDomainException; import org.fenixedu.bennu.core.domain.groups.PersistentGroup; import org.fenixedu.bennu.core.groups.Group; import org.fenixedu.bennu.core.i18n.BundleUtil; import org.fenixedu.bennu.core.json.JsonUtils; import org.fenixedu.bennu.core.security.Authenticate; import org.fenixedu.bennu.core.util.CoreConfiguration; import org.fenixedu.commons.i18n.LocalizedString; import org.fenixedu.commons.i18n.LocalizedString.Builder; import org.fenixedu.messaging.core.domain.MessagingSystem; import org.fenixedu.messaging.core.domain.Sender; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.Months; import org.joda.time.YearMonthDay; import com.google.common.base.Strings; import pt.ist.fenixWebFramework.rendererExtensions.util.IPresentableEnum; import pt.ist.fenixframework.Atomic; public class Person extends Person_Base { private static final Integer MAX_VALIDATION_REQUESTS = 5; private IdDocument getIdDocument() { final Iterator<IdDocument> documentIterator = getIdDocumentsSet().iterator(); return documentIterator.hasNext() ? documentIterator.next() : null; } @Override public void setUser(User user) { super.setUser(user); if (getProfile() != null) { getProfile().setAvatarUrl( CoreConfiguration.getConfiguration().applicationUrl() + "/user/photo/" + getUser().getUsername()); } } @Override public LocalizedString getPartyName() { Builder builder = new LocalizedString.Builder(); for (Locale locale : CoreConfiguration.supportedLocales()) { builder.with(locale, getName()); } return builder.build(); } @Override public String getName() { return getProfile().getFullName(); } /** * @deprecated Use {@link UserProfile#getGivenNames()} */ @Deprecated public String getGivenNames() { return getProfile().getGivenNames(); } /** * @deprecated Use {@link UserProfile#getFamilyNames()} */ @Deprecated public String getFamilyNames() { return getProfile().getFamilyNames(); } @Override public void setDocumentIdNumber(final String documentIdNumber) { if (documentIdNumber == null || Strings.isNullOrEmpty(documentIdNumber)) { throw new DomainException("error.person.empty.documentIdNumber"); } IdDocument idDocument = getIdDocument(); if (idDocument == null) { idDocument = new IdDocument(this, documentIdNumber, (IdDocumentTypeObject) null); } else { idDocument.setValue(documentIdNumber); } logSetterNullString("log.personInformation.edit.generalTemplate.personalId", getDocumentIdNumber(), documentIdNumber, "label.documentNumber"); super.setDocumentIdNumber(documentIdNumber); } @Override public void setIdDocumentType(final IDDocumentType idDocumentType) { if (idDocumentType == null) { throw new DomainException("error.person.empty.idDocumentType"); } IdDocument idDocument = getIdDocument(); if (idDocument == null) { idDocument = new IdDocument(this, null, idDocumentType); } else { idDocument.setIdDocumentType(idDocumentType); } logSetterNullEnum("log.personInformation.edit.generalTemplate.personalId", getIdDocumentType(), idDocumentType, "label.documentIdType"); super.setIdDocumentType(idDocumentType); } public void setIdentification(String documentIdNumber, final IDDocumentType idDocumentType) { documentIdNumber = StringUtils.trimToNull(documentIdNumber); if (documentIdNumber != null && idDocumentType != null && checkIfDocumentNumberIdAndDocumentIdTypeExists(documentIdNumber, idDocumentType)) { throw new DomainException("error.person.existent.docIdAndType"); } setDocumentIdNumber(documentIdNumber); setIdDocumentType(idDocumentType); } public void setIdentificationAndNames(String documentIdNumber, final IDDocumentType idDocumentType, final String givenNames, final String familyNames) { getProfile().changeName(givenNames, familyNames, null); setIdentification(documentIdNumber, idDocumentType); } public void setGivenNames(String newGivenNames) { UserProfile profile = getProfile(); profile.changeName(newGivenNames, profile.getFamilyNames(), profile.getDisplayName()); } public String getDisplayName() { return getProfile().getDisplayName(); } public void setDisplayName(String newDisplayName) { UserProfile profile = getProfile(); try { profile.changeName(profile.getGivenNames(), profile.getFamilyNames(), newDisplayName); } catch (BennuCoreDomainException ex) { throw new DomainException("error.invalid.displayName", ex.getLocalizedMessage()); } } public void setFamilyNames(String newFamilyNames) { UserProfile profile = getProfile(); profile.changeName(profile.getGivenNames(), newFamilyNames, profile.getDisplayName()); } public void setNames(String newGivenName, String newFamilyName, String newDisplayName) { UserProfile profile = getProfile(); try { profile.changeName(newGivenName, newFamilyName, newDisplayName); } catch (BennuCoreDomainException ex) { throw new DomainException("error.invalid.displayName", ex.getLocalizedMessage()); } } private boolean checkIfDocumentNumberIdAndDocumentIdTypeExists(final String documentIDNumber, final IDDocumentType documentType) { final Person person = readByDocumentIdNumberAndIdDocumentType(documentIDNumber, documentType); return person != null && !person.equals(this); } final public String getValidatedName() { return StringFormatter.prettyPrint(getName()); } /** * Creates a new Person, associated to the given {@link UserProfile}. * * Note that this constructor does NOT create a {@link User}. * * @param profile * The profile to associate with the created person. */ public Person(UserProfile profile) { super(); setProfile(profile); if (profile.getUser() != null) { setUser(profile.getUser()); } setMaritalStatus(MaritalStatus.UNKNOWN); } /** * Creates a new Person and its correspondent {@link UserProfile}, using the data provided * in the parameter bean. * * Note that this constructor does NOT create a {@link User}. * * @param personBean * The bean containing information about the person to be created. */ public Person(final PersonBean personBean) { this(personBean, false); } /** * Creates a new Person and its correspondent {@link UserProfile}, using the data provided * in the parameter bean. It also allows the caller to specify whether the email is to be automatically validated by the * system. * * Note that this constructor does NOT create a {@link User}. * * @param personBean * The bean containing information about the person to be created. * @param validateEmail * Whether to automatically validate the given email. */ public Person(final PersonBean personBean, final boolean validateEmail) { this(new UserProfile(personBean.getGivenNames(), personBean.getFamilyNames(), null, personBean.getEmail(), Locale.getDefault())); setProperties(personBean); PhysicalAddress.createPhysicalAddress(this, personBean.getPhysicalAddressData(), PartyContactType.PERSONAL, true); Phone.createPhone(this, personBean.getPhone(), PartyContactType.PERSONAL, true); MobilePhone.createMobilePhone(this, personBean.getMobile(), PartyContactType.PERSONAL, true); final EmailAddress emailAddress = EmailAddress.createEmailAddress(this, personBean.getEmail(), PartyContactType.PERSONAL, true); if (validateEmail) { emailAddress.setValid(); } WebAddress.createWebAddress(this, personBean.getWebAddress(), PartyContactType.PERSONAL, true); } /** * Creates a new Person and its correspondent {@link UserProfile} and optionally a {@link User}, using the data provided in * the personal details. * * @param candidacyPersonalDetails * The personal details containing information about the person to be created. * @param createUser true if a user is to be created, false otherwise. */ public Person(final IndividualCandidacyPersonalDetails candidacyPersonalDetails, boolean createUser) { this(new UserProfile(candidacyPersonalDetails.getGivenNames(), candidacyPersonalDetails.getFamilyNames(), null, candidacyPersonalDetails.getEmail(), Locale.getDefault())); if (createUser) { setUser(new User(getProfile())); } this.setCountry(candidacyPersonalDetails.getCountry()); this.setDateOfBirthYearMonthDay(candidacyPersonalDetails.getDateOfBirthYearMonthDay()); this.setDocumentIdNumber(candidacyPersonalDetails.getDocumentIdNumber()); this.setExpirationDateOfDocumentIdYearMonthDay(candidacyPersonalDetails.getExpirationDateOfDocumentIdYearMonthDay()); this.setGender(candidacyPersonalDetails.getGender()); this.setIdDocumentType(candidacyPersonalDetails.getIdDocumentType()); this.setSocialSecurityNumber(candidacyPersonalDetails.getSocialSecurityNumber()); final PhysicalAddressData physicalAddressData = new PhysicalAddressData(candidacyPersonalDetails.getAddress(), candidacyPersonalDetails.getAreaCode(), "", candidacyPersonalDetails.getArea(), "", "", "", candidacyPersonalDetails.getCountryOfResidence()); PhysicalAddress.createPhysicalAddress(this, physicalAddressData, PartyContactType.PERSONAL, true); Phone.createPhone(this, candidacyPersonalDetails.getTelephoneContact(), PartyContactType.PERSONAL, true); EmailAddress.createEmailAddress(this, candidacyPersonalDetails.getEmail(), PartyContactType.PERSONAL, true); } /** * Creates a new Person and its correspondent {@link UserProfile} and {@link User}, using the data provided in the personal * details. * * @param candidacyPersonalDetails * The personal details containing information about the person to be created. */ public Person(final IndividualCandidacyPersonalDetails candidacyPersonalDetails) { this(candidacyPersonalDetails, true); } public void ensureOpenUserAccount() { if (getUser() == null) { setUser(new User(getProfile())); } getUser().openLoginPeriod(); } public void ensureUserAccount() { if (getUser() == null) { setUser(new User(getProfile())); } } public Person editPersonalInformation(final PersonBean personBean) { check(this, AcademicPredicates.EDIT_STUDENT_PERSONAL_DATA); setProperties(personBean); return this; } public Person editByPublicCandidate(final PersonBean personBean) { getProfile().changeName(personBean.getGivenNames(), personBean.getFamilyNames(), null); setGender(personBean.getGender()); setIdentification(personBean.getDocumentIdNumber(), personBean.getIdDocumentType()); setExpirationDateOfDocumentIdYearMonthDay(personBean.getDocumentIdExpirationDate()); setSocialSecurityNumber(personBean.getSocialSecurityNumber()); setDateOfBirthYearMonthDay(personBean.getDateOfBirth()); setCountry(personBean.getNationality()); setDefaultPhysicalAddressData(personBean.getPhysicalAddressData()); setDefaultPhoneNumber(personBean.getPhone()); setDefaultEmailAddressValue(personBean.getEmail(), true); setDefaultMobilePhoneNumber(personBean.getMobile()); return this; } public Person edit(final IndividualCandidacyPersonalDetails candidacyExternalDetails) { this.setCountry(candidacyExternalDetails.getCountry()); this.setDateOfBirthYearMonthDay(candidacyExternalDetails.getDateOfBirthYearMonthDay()); this.setIdentification(candidacyExternalDetails.getDocumentIdNumber(), candidacyExternalDetails.getIdDocumentType()); this.setExpirationDateOfDocumentIdYearMonthDay(candidacyExternalDetails.getExpirationDateOfDocumentIdYearMonthDay()); this.setGender(candidacyExternalDetails.getGender()); getProfile().changeName(candidacyExternalDetails.getGivenNames(), candidacyExternalDetails.getFamilyNames(), null); this.setSocialSecurityNumber(candidacyExternalDetails.getSocialSecurityNumber()); final PhysicalAddressData physicalAddressData = new PhysicalAddressData(candidacyExternalDetails.getAddress(), candidacyExternalDetails.getAreaCode(), getAreaOfAreaCode(), candidacyExternalDetails.getArea(), getParishOfResidence(), getDistrictSubdivisionOfResidence(), getDistrictOfResidence(), candidacyExternalDetails.getCountryOfResidence()); setDefaultPhysicalAddressData(physicalAddressData); setDefaultPhoneNumber(candidacyExternalDetails.getTelephoneContact()); setDefaultEmailAddressValue(candidacyExternalDetails.getEmail()); return this; } public Person editPersonWithExternalData(final PersonBean personBean, final boolean updateExistingContacts) { setProperties(personBean); setDefaultPhysicalAddressData(personBean.getPhysicalAddressData()); if (updateExistingContacts) { setDefaultPhoneNumber(personBean.getPhone()); setDefaultMobilePhoneNumber(personBean.getMobile()); setDefaultWebAddressUrl(personBean.getWebAddress()); setDefaultEmailAddressValue(personBean.getEmail()); } else { Phone.createPhone(this, personBean.getPhone(), PartyContactType.PERSONAL, !hasDefaultPhone()); MobilePhone.createMobilePhone(this, personBean.getMobile(), PartyContactType.PERSONAL, !hasDefaultMobilePhone()); EmailAddress.createEmailAddress(this, personBean.getEmail(), PartyContactType.PERSONAL, !hasDefaultEmailAddress()); WebAddress.createWebAddress(this, personBean.getWebAddress(), PartyContactType.PERSONAL, !hasDefaultWebAddress()); } return this; } public String getUsername() { User user = getUser(); return user == null ? null : user.getUsername(); } public Registration getStudentByType(final DegreeType degreeType) { for (final Registration registration : this.getStudents()) { if (registration.getDegreeType() == degreeType) { return registration; } } return null; } private String valueToUpdateIfNewNotNull(final String actualValue, final String newValue) { if (newValue == null || newValue.length() == 0) { return actualValue; } return newValue; } private Object valueToUpdateIfNewNotNull(final Object actualValue, final Object newValue) { if (newValue == null) { return actualValue; } return newValue; } private void setProperties(final PersonBean personBean) { getProfile().changeName(personBean.getGivenNames(), personBean.getFamilyNames(), null); setGender(personBean.getGender()); setProfession(personBean.getProfession()); setMaritalStatus(personBean.getMaritalStatus()); // identification setIdentification(personBean.getDocumentIdNumber(), personBean.getIdDocumentType()); setIdentificationDocumentSeriesNumber(personBean.getIdentificationDocumentSeriesNumber()); setEmissionLocationOfDocumentId(personBean.getDocumentIdEmissionLocation()); setEmissionDateOfDocumentIdYearMonthDay(personBean.getDocumentIdEmissionDate()); setExpirationDateOfDocumentIdYearMonthDay(personBean.getDocumentIdExpirationDate()); setSocialSecurityNumber(personBean.getSocialSecurityNumber()); setEidentifier(personBean.getEidentifier()); // filiation setDateOfBirthYearMonthDay(personBean.getDateOfBirth()); setCountry(personBean.getNationality()); setParishOfBirth(personBean.getParishOfBirth()); setDistrictSubdivisionOfBirth(personBean.getDistrictSubdivisionOfBirth()); setDistrictOfBirth(personBean.getDistrictOfBirth()); setCountryOfBirth(personBean.getCountryOfBirth()); setNameOfMother(personBean.getMotherName()); setNameOfFather(personBean.getFatherName()); } /** * @return a group that only contains this person */ public Group getPersonGroup() { return this.getUser().groupOf(); } /** * * IMPORTANT: This method is evil and should NOT be used! You are NOT God! * **/ @Override public void delete() { DomainException.throwWhenDeleteBlocked(getDeletionBlockers()); if (getPersonalPhotoEvenIfRejected() != null) { getPersonalPhotoEvenIfRejected().delete(); } if (getAssociatedPersonAccount() != null) { getAssociatedPersonAccount().delete(); } if (getStudent() != null) { getStudent().delete(); } if (super.getSender() != null) { final Sender sender = super.getSender(); setSender(null); sender.delete(); } getThesisEvaluationParticipantsSet().clear(); for (; !getIdDocumentsSet().isEmpty(); getIdDocumentsSet().iterator().next().delete()) { ; } for (; !getScientificCommissionsSet().isEmpty(); getScientificCommissionsSet().iterator().next().delete()) { ; } super.setCountry(null); super.setCountryOfBirth(null); setProfile(null); super.setUser(null); super.delete(); } @Override protected void checkForDeletionBlockers(Collection<String> blockers) { super.checkForDeletionBlockers(blockers); if (!(getPartyContactsSet().isEmpty() && getChildsSet().isEmpty() && getParentsSet().isEmpty() && getExportGroupingReceiversSet().isEmpty() && getAssociatedQualificationsSet().isEmpty() && getAssociatedAlteredCurriculumsSet().isEmpty() && getEnrolmentEvaluationsSet().isEmpty() && getExportGroupingSendersSet().isEmpty() && getResponsabilityTransactionsSet().isEmpty() && getGuidesSet().isEmpty() && getTeacher() == null && getInternalParticipantsSet().isEmpty() && getCreatedQualificationsSet().isEmpty() && getCreateJobsSet().isEmpty())) { blockers.add(BundleUtil.getString(Bundle.APPLICATION, "error.person.cannot.be.deleted")); } } public boolean getDisableSendEmails(){ return MessagingSystem.getInstance().isOptedOut(getUser()); } public void setDisableSendEmails(boolean disableSendEmails) { if (disableSendEmails){ MessagingSystem.getInstance().optOut(getUser()); } else { MessagingSystem.getInstance().optIn(getUser()); } getProfile().setEmail(getEmailForSendingEmails()); } public boolean hasDegreeCandidacyForExecutionDegree(final ExecutionDegree executionDegree) { for (final Candidacy candidacy : this.getCandidaciesSet()) { if (candidacy instanceof DegreeCandidacy && candidacy.isActive()) { final DegreeCandidacy degreeCandidacy = (DegreeCandidacy) candidacy; if (degreeCandidacy.getExecutionDegree().equals(executionDegree)) { return true; } } } return false; } public StudentCandidacy getStudentCandidacyForExecutionDegree(final ExecutionDegree executionDegree) { for (final Candidacy candidacy : this.getCandidaciesSet()) { if (candidacy instanceof StudentCandidacy && candidacy.isActive()) { if (candidacy instanceof PHDProgramCandidacy) { continue; } final StudentCandidacy studentCandidacy = (StudentCandidacy) candidacy; if (studentCandidacy.getExecutionDegree().equals(executionDegree)) { return studentCandidacy; } } } return null; } public boolean hasStudentCandidacyForExecutionDegree(final ExecutionDegree executionDegree) { return getStudentCandidacyForExecutionDegree(executionDegree) != null; } public static Person readPersonByUsername(final String username) { final User user = User.findByUsername(username); return user == null ? null : user.getPerson(); } public static Collection<Person> readByDocumentIdNumber(final String documentIdNumber) { final Collection<Person> result = new HashSet<>(); for (final IdDocument idDocument : IdDocument.find(documentIdNumber)) { result.add(idDocument.getPerson()); } return result; } public static Person readByDocumentIdNumberAndIdDocumentType(final String documentIdNumber, final IDDocumentType idDocumentType) { final IdDocument document = IdDocument.findFirst(documentIdNumber, idDocumentType); return document == null ? null : document.getPerson(); } public static Collection<Person> findByDateOfBirth(final YearMonthDay dateOfBirth, final Collection<Person> persons) { final List<Person> result = new ArrayList<>(); for (final Person person : persons) { if (person.getDateOfBirthYearMonthDay() == null || person.getDateOfBirthYearMonthDay().equals(dateOfBirth)) { result.add(person); } } return result; } public static Stream<Person> findPersonStream(final String name, final int size) { return UserProfile.searchByName(name, size).map(p -> p.getPerson()).filter(Objects::nonNull); } public static Collection<Person> findPerson(final String name, final int size) { return findPersonStream(name, size).collect(Collectors.toSet()); } public static Collection<Person> readPersonsByNameAndRoleType(final String name, final RoleType roleType) { final Collection<Person> people = findPerson(name); people.removeIf(person -> !roleType.isMember(person.getUser())); return people; } public SortedSet<StudentCurricularPlan> getActiveStudentCurricularPlansSortedByDegreeTypeAndDegreeName() { final SortedSet<StudentCurricularPlan> studentCurricularPlans = new TreeSet<>(StudentCurricularPlan.STUDENT_CURRICULAR_PLAN_COMPARATOR_BY_DEGREE_TYPE_AND_DEGREE_NAME); for (final Registration registration : getStudentsSet()) { final StudentCurricularPlan studentCurricularPlan = registration.getActiveStudentCurricularPlan(); if (studentCurricularPlan != null) { studentCurricularPlans.add(studentCurricularPlan); } } return studentCurricularPlans; } public Set<Attends> getCurrentAttends() { final Set<Attends> attends = new HashSet<>(); for (final Registration registration : getStudentsSet()) { for (final Attends attend : registration.getAssociatedAttendsSet()) { final ExecutionCourse executionCourse = attend.getExecutionCourse(); final ExecutionSemester executionSemester = executionCourse.getExecutionPeriod(); if (executionSemester.getState().equals(PeriodState.CURRENT)) { attends.add(attend); } } } return attends; } private Set<Event> getEventsFromType(final Class<? extends Event> clazz) { final Set<Event> events = new HashSet<>(); for (final Event event : getEventsSet()) { if (clazz.isAssignableFrom(event.getClass())) { events.add(event); } } return events; } public Set<Event> getAcademicEvents() { return getEventsFromType(AcademicEvent.class); } public Set<Event> getResidencePaymentEvents() { return getEventsFromType(ResidenceEvent.class); } public Set<Event> getNotPayedEventsPayableOn(final AdministrativeOffice administrativeOffice, final Class eventClass, final boolean withInstallments) { final Set<Event> result = new HashSet<>(); Set<Event> events = getEventsFromType(eventClass); for (final Event event : events) { if (event.isOpen() && event.hasInstallments() == withInstallments && isPayableOnAnyOfAdministrativeOffices(Collections.singleton(administrativeOffice), event)) { result.add(event); } } return result; } public Set<Event> getNotPayedEventsPayableOn(final AdministrativeOffice administrativeOffice, final boolean withInstallments) { return getNotPayedEventsPayableOn(administrativeOffice, AcademicEvent.class, withInstallments); } public Set<Event> getNotPayedEvents() { final Set<Event> result = new HashSet<>(); for (final Event event : getAcademicEvents()) { if (event.isOpen()) { result.add(event); } } return result; } private boolean isPayableOnAnyOfAdministrativeOffices(final Set<AdministrativeOffice> administrativeOffices, final Event event) { if (administrativeOffices == null) { return true; } for (final AdministrativeOffice administrativeOffice : administrativeOffices) { if (administrativeOffice == null || event.isPayableOnAdministrativeOffice(administrativeOffice)) { return true; } } return false; } public List<Event> getPayedEvents(final Class eventClass) { final List<Event> result = new ArrayList<>(); Set<Event> events = getEventsFromType(eventClass); for (final Event event : events) { if (event.isClosed()) { result.add(event); } } return result; } public List<Event> getPayedEvents() { return getPayedEvents(AcademicEvent.class); } public List<Event> getEventsWithPayments() { final List<Event> result = new ArrayList<>(); for (final Event event : getAcademicEvents()) { if (!event.isCancelled() && event.hasAnyPayments()) { result.add(event); } } return result; } public Set<Entry> getPaymentsWithoutReceipt() { return getPaymentsWithoutReceiptByAdministrativeOffices(null); } public Set<Entry> getPaymentsWithoutReceiptByAdministrativeOffices(final Set<AdministrativeOffice> administrativeOffices) { final Set<Entry> result = new HashSet<>(); for (final Event event : getAcademicEvents()) { if (!event.isCancelled() && isPayableOnAnyOfAdministrativeOffices(administrativeOffices, event)) { result.addAll(event.getEntriesWithoutReceipt()); } } return result; } public Set<Entry> getPayments(final Class eventClass) { final Set<Entry> result = new HashSet<>(); Set<Event> events = getEventsFromType(eventClass); for (final Event event : events) { if (!event.isCancelled()) { result.addAll(event.getPositiveEntries()); } } return result; } public Set<Entry> getPayments() { return getPayments(AcademicEvent.class); } public Money getTotalPaymentsAmountWithAdjustment() { Money total = new Money(0); for (final Entry entry : getPayments(AcademicEvent.class)) { total = total.add(entry.getAmountWithAdjustment()); } return total; } public Set<? extends Event> getEventsByEventTypes(final Collection<EventType> eventTypes) { final Set<Event> result = new HashSet<>(); for (final EventType eventType : eventTypes) { for (final Event event : getAcademicEvents()) { if (!event.isCancelled() && event.getEventType() == eventType) { result.add(event); } } } return result; } public Set<? extends Event> getEventsByEventType(final EventType eventType) { return getEventsByEventTypeAndClass(eventType, null); } public Set<? extends Event> getEventsByEventTypeAndClass(final EventType eventType, final Class<? extends Event> clazz) { final Set<Event> result = new HashSet<>(); for (final Event event : getEventsSet()) { if (!event.isCancelled() && event.getEventType() == eventType && (clazz == null || event.getClass().equals(clazz))) { result.add(event); } } return result; } public Set<AnnualEvent> getAnnualEventsFor(final ExecutionYear executionYear) { return getEventsSet().stream() .filter(event -> event instanceof AnnualEvent) .map(event -> (AnnualEvent) event) .filter(annualEvent -> annualEvent.isFor(executionYear) && !annualEvent.isCancelled()) .collect(Collectors.toSet()); } public boolean hasInsuranceEventOrAdministrativeOfficeFeeInsuranceEventFor(final ExecutionYear executionYear) { return hasInsuranceEventFor(executionYear) || hasAdministrativeOfficeFeeInsuranceEventFor(executionYear); } public Set<Event> getNotCancelledInsuranceEvents() { final Stream<InsuranceEvent> insuranceEventStream = getEventsByEventType(EventType.INSURANCE).stream() .map(event -> (InsuranceEvent) event) .filter(specificEvent -> !specificEvent.isCancelled()); final Stream<CustomEvent> customEventStream = getEventsByEventType(EventType.CUSTOM).stream() .map(CustomEvent.class::cast) .filter(event -> !event.isCancelled()) .filter(event -> EventTemplate.Type.INSURANCE.name().equals(JsonUtils.get(event.getConfigObject(), "type"))); return Streams.concat(insuranceEventStream, customEventStream).collect(Collectors.toSet()); } public Event getInsuranceEventFor(final ExecutionYear executionYear) { final Stream<InsuranceEvent> insuranceEventStream = getEventsByEventType(EventType.INSURANCE).stream() .map(event -> (InsuranceEvent) event) .filter(insuranceEvent -> !insuranceEvent.isCancelled()) .filter(insuranceEvent -> insuranceEvent.isFor(executionYear)); final Stream<CustomEvent> customEventStream = getEventsByEventType(EventType.CUSTOM).stream() .map(CustomEvent.class::cast) .filter(event -> !event.isCancelled()) .filter(event -> EventTemplate.Type.INSURANCE.name().equals(JsonUtils.get(event.getConfigObject(), "type"))) .filter(event -> { final ExecutionYear insuranceYear = JsonUtils.toDomainObject(event.getConfigObject(), "executionYear"); return executionYear == insuranceYear; }); return Streams.concat(insuranceEventStream, customEventStream).findAny().orElse(null); } public boolean hasInsuranceEventFor(final ExecutionYear executionYear) { return getInsuranceEventFor(executionYear) != null; } public Stream<Event> getInsuranceEventsUntil(final ExecutionYear executionYear) { final Stream<InsuranceEvent> insuranceEventStream = getEventsByEventType(EventType.INSURANCE).stream() .map(event -> (InsuranceEvent) event) .filter(event -> !event.isCancelled()) .filter(insuranceEvent -> !insuranceEvent.getExecutionYear().isAfter(executionYear)); final Stream<CustomEvent> customEventStream = getEventsByEventType(EventType.CUSTOM).stream() .map(CustomEvent.class::cast) .filter(event -> !event.isCancelled()) .filter(event -> EventTemplate.Type.INSURANCE.name().equals(JsonUtils.get(event.getConfigObject(), "type"))) .filter(event -> { final ExecutionYear eventExecutionYear = JsonUtils.toDomainObject(event.getConfigObject(), "executionYear"); return !eventExecutionYear.isAfter(executionYear); }); return Streams.concat(insuranceEventStream, customEventStream); } public boolean hasAnyInsuranceDebtUntil(final ExecutionYear executionYear) { return getInsuranceEventsUntil(executionYear) .anyMatch(insuranceEvent -> insuranceEvent.isInDebt()); } public boolean hasAnyGratuityDebtUntil(final ExecutionYear executionYear) { final boolean anyMatch = getEventsSet().stream() .filter(event -> event.isGratuity()) .filter(gratuityEvent -> !gratuityEvent.executionYearOf().isAfter(executionYear)) .anyMatch(event -> event.isInDebt()); if (anyMatch) { return true; } else { return getEventsByEventType(EventType.CUSTOM).stream() .map(CustomEvent.class::cast) .filter(event -> !event.isCancelled()) .filter(event -> EventTemplate.Type.TUITION.name().equals(JsonUtils.get(event.getConfigObject(), "type"))) .anyMatch(event -> { final ExecutionYear eventExecutionYear = JsonUtils.toDomainObject(event.getConfigObject(), "executionYear"); return !eventExecutionYear.isAfter(executionYear) && event.isInDebt(); }); } } public Set<AdministrativeOfficeFeeAndInsuranceEvent> getNotCancelledAdministrativeOfficeFeeAndInsuranceEvents( final AdministrativeOffice office) { return getEventsByEventType(EventType.ADMINISTRATIVE_OFFICE_FEE_INSURANCE).stream() .map(event -> (AdministrativeOfficeFeeAndInsuranceEvent) event) .filter(specificEvent -> !specificEvent.isCancelled()) .filter(specificEvent -> specificEvent.getAdministrativeOffice() == office) .collect(Collectors.toSet()); } public Set<AdministrativeOfficeFeeAndInsuranceEvent> getNotCancelledAdministrativeOfficeFeeAndInsuranceEventsUntil( final AdministrativeOffice office, final ExecutionYear executionYear) { return getEventsByEventType(EventType.ADMINISTRATIVE_OFFICE_FEE_INSURANCE).stream() .map(event -> (AdministrativeOfficeFeeAndInsuranceEvent) event) .filter(specificEvent -> !specificEvent.isCancelled()) .filter(specificEvent -> specificEvent.getAdministrativeOffice() == office) .filter(specificEvent -> specificEvent.getExecutionYear().isBeforeOrEquals(executionYear)) .collect(Collectors.toSet()); } public AdministrativeOfficeFeeAndInsuranceEvent getAdministrativeOfficeFeeInsuranceEventFor(final ExecutionYear executionYear) { return getEventsByEventType(EventType.ADMINISTRATIVE_OFFICE_FEE_INSURANCE).stream() .map(event -> (AdministrativeOfficeFeeAndInsuranceEvent) event) .filter(administrativeOfficeFeeAndInsuranceEvent -> !administrativeOfficeFeeAndInsuranceEvent.isCancelled()) .filter(administrativeOfficeFeeAndInsuranceEvent -> administrativeOfficeFeeAndInsuranceEvent.isFor(executionYear)) .findAny().orElse(null); } public boolean hasAdministrativeOfficeFeeInsuranceEventFor(final ExecutionYear executionYear) { return getAdministrativeOfficeFeeInsuranceEventFor(executionYear) != null || (hasInsuranceEventFor(executionYear) && hasAdministrativeOfficeFeeEventFor(executionYear)); } private boolean hasAdministrativeOfficeFeeEventFor(final ExecutionYear executionYear) { final boolean anyMatch = getEventsByEventType(EventType.ADMINISTRATIVE_OFFICE_FEE).stream() .map(event -> (AdministrativeOfficeFeeEvent) event) .filter(administrativeOfficeFeeEvent -> !administrativeOfficeFeeEvent.isCancelled()) .anyMatch(administrativeOfficeFeeEvent -> administrativeOfficeFeeEvent.isFor(executionYear)); if (anyMatch) { return true; } else { return getEventsByEventType(EventType.CUSTOM).stream() .map(CustomEvent.class::cast) .filter(event -> !event.isCancelled()) .filter(event -> EventTemplate.Type.ADMIN_FEES.name().equals(JsonUtils.get(event.getConfigObject(), "type"))) .anyMatch(event -> { final String executionYearID = event.getConfigObject().get("executionYear").getAsString(); return executionYear.getExternalId().equals(executionYearID); }); } } public Stream<Event> getAdministrativeOfficeFeeEventsUntil(final ExecutionYear executionYear) { final Stream<AdministrativeOfficeFeeEvent> eventStream = getEventsByEventType(EventType.ADMINISTRATIVE_OFFICE_FEE).stream() .filter(event -> !event.isCancelled()) .map(event -> (AdministrativeOfficeFeeEvent) event) .filter(administrativeOfficeFeeEvent -> !administrativeOfficeFeeEvent.getExecutionYear().isAfter(executionYear)); final Stream<CustomEvent> customEventStream = getEventsByEventType(EventType.CUSTOM).stream() .map(CustomEvent.class::cast) .filter(event -> !event.isCancelled()) .filter(event -> EventTemplate.Type.ADMIN_FEES.name().equals(JsonUtils.get(event.getConfigObject(), "type"))) .filter(event -> { final ExecutionYear eventExecutionYear = JsonUtils.toDomainObject(event.getConfigObject(), "executionYear"); return !eventExecutionYear.isAfter(executionYear); }); return Streams.concat(eventStream, customEventStream); } public boolean hasAnyAdministrativeOfficeFeeDebtUntil(final ExecutionYear executionYear) { return getAdministrativeOfficeFeeEventsUntil(executionYear) .anyMatch(event -> event.isInDebt()); } public Set<Event> getEventsSupportingPaymentByOtherParties() { return getEventsSet().stream() .filter(event -> !event.isCancelled()) .filter(Event::isOtherPartiesPaymentsSupported) .collect(Collectors.toSet()); } public List<PaymentCode> getPaymentCodesBy(final PaymentCodeType paymentCodeType) { return getPaymentCodesSet().stream().filter(paymentCode -> paymentCode.getType() == paymentCodeType).collect(Collectors.toList()); } public PaymentCode getPaymentCodeBy(final String code) { return getPaymentCodesSet().stream().filter(paymentCode -> paymentCode.getCode().equals(code)).findFirst().orElse(null); } public List<Event> getEventsWithExemptionAppliable() { return getEventsSet().stream().filter(e -> !e.isCancelled()).collect(Collectors.toList()); } public Money getMaxDeductableAmountForLegalTaxes(final EventType eventType, final int civilYear) { Money result = Money.ZERO; for (final Event event : (Set<Event>) getEventsByEventType(eventType)) { result = result.add(event.getMaxDeductableAmountForLegalTaxes(civilYear)); } return result; } public Set<Receipt> getReceiptsByAdministrativeOffices(final Set<AdministrativeOffice> administrativeOffices) { final Set<Receipt> result = new HashSet<>(); for (final Receipt receipt : getReceiptsSet()) { for (final AdministrativeOffice administrativeOffice : administrativeOffices) { if (receipt.isFromAdministrativeOffice(administrativeOffice)) { result.add(receipt); } } } return result; } @Override final public boolean isPerson() { return true; } final public boolean isFemale() { return getGender() == Gender.FEMALE; } final public boolean isMale() { return getGender() == Gender.MALE; } @Deprecated public Set<Registration> getStudents() { return getStudent() != null ? getStudent().getRegistrationsSet() : Collections.emptySet(); } @Deprecated public boolean hasAnyStudents() { return getStudentsCount() > 0; } @Deprecated public int getStudentsCount() { return getStudent() != null ? getStudent().getRegistrationsSet().size() : 0; } @Deprecated public Set<Registration> getStudentsSet() { return getStudent() != null ? getStudent().getRegistrationsSet() : Collections.emptySet(); } public SortedSet<String> getOrganizationalUnitsPresentation() { final SortedSet<String> organizationalUnits = new TreeSet<>(); for (final Accountability accountability : getParentsSet()) { if (isOrganizationalUnitsForPresentation(accountability)) { final Party party = accountability.getParentParty(); organizationalUnits.add(party.getName()); } } if (getStudent() != null) { for (final Registration registration : getStudent().getRegistrationsSet()) { if (registration.isActive()) { final DegreeCurricularPlan degreeCurricularPlan = registration.getLastDegreeCurricularPlan(); if (degreeCurricularPlan != null) { final Degree degree = degreeCurricularPlan.getDegree(); organizationalUnits.add(degree.getPresentationName()); } } } } return organizationalUnits; } private boolean isOrganizationalUnitsForPresentation(final Accountability accountability) { final AccountabilityType accountabilityType = accountability.getAccountabilityType(); final AccountabilityTypeEnum accountabilityTypeEnum = accountabilityType.getType(); return accountabilityTypeEnum == AccountabilityTypeEnum.WORKING_CONTRACT; } @Deprecated public String getNickname() { return getProfile().getDisplayName(); } public String getHomepageWebAddress() { if (isDefaultWebAddressVisible() && getDefaultWebAddress().hasUrl()) { return getDefaultWebAddress().getUrl(); } return null; } @Deprecated public boolean hasAvailableWebSite() { return getAvailableWebSite() != null && getAvailableWebSite(); } public Collection<ExecutionDegree> getCoordinatedExecutionDegrees(final DegreeCurricularPlan degreeCurricularPlan) { final Set<ExecutionDegree> result = new TreeSet<>(ExecutionDegree.EXECUTION_DEGREE_COMPARATORY_BY_YEAR); for (final Coordinator coordinator : getCoordinatorsSet()) { if (coordinator.getExecutionDegree().getDegreeCurricularPlan().equals(degreeCurricularPlan)) { result.add(coordinator.getExecutionDegree()); } } return result; } public boolean isCoordinatorFor(final DegreeCurricularPlan degreeCurricularPlan, final ExecutionYear executionYear) { for (final ExecutionDegree executionDegree : degreeCurricularPlan.getExecutionDegreesSet()) { if (executionDegree.getExecutionYear() == executionYear) { return executionDegree.getCoordinatorByTeacher(this) != null; } } return false; } public boolean isResponsibleOrCoordinatorFor(final CurricularCourse curricularCourse, final ExecutionSemester executionSemester) { final Teacher teacher = getTeacher(); return teacher != null && teacher.isResponsibleFor(curricularCourse, executionSemester) || isCoordinatorFor(curricularCourse.getDegreeCurricularPlan(), executionSemester.getExecutionYear()); } public boolean isCoordinatorFor(final ExecutionYear executionYear, final List<DegreeType> degreeTypes) { for (final Coordinator coordinator : getCoordinatorsSet()) { final ExecutionDegree executionDegree = coordinator.getExecutionDegree(); if (executionDegree != null && executionDegree.getExecutionYear() == executionYear && degreeTypes.contains(executionDegree.getDegree().getDegreeType())) { return true; } } return false; } public ServiceAgreement getServiceAgreementFor(final ServiceAgreementTemplate serviceAgreementTemplate) { for (final ServiceAgreement serviceAgreement : getServiceAgreementsSet()) { if (serviceAgreement.getServiceAgreementTemplate() == serviceAgreementTemplate) { return serviceAgreement; } } return null; } public String getFirstAndLastName() { final String[] name = getName().split(" "); return name[0] + " " + name[name.length - 1]; } public static Collection<Person> findPerson(final String name) { return findPerson(name, Integer.MAX_VALUE); } public static Collection<Person> findPersonMatchingFirstAndLastName(final String completeName) { if (completeName != null) { final String[] splittedName = completeName.split(" "); return splittedName.length > 0 ? findPerson(splittedName[0] + " " + splittedName[splittedName.length - 1]) : Collections.EMPTY_LIST; } return Collections.EMPTY_LIST; } public static Collection<Person> findPersonByDocumentID(final String documentIDValue) { final Collection<Person> people = new ArrayList<>(); if (!StringUtils.isEmpty(documentIDValue)) { for (final IdDocument idDocument : IdDocument.find(documentIDValue)) { people.add(idDocument.getPerson()); } } return people; } public static Person readPersonByEmailAddress(final String email) { final EmailAddress emailAddress = EmailAddress.find(email); return emailAddress != null && emailAddress.getParty().isPerson() ? (Person) emailAddress.getParty() : null; } public boolean hasEmailAddress(final String email) { for (final PartyContact partyContact : getPartyContactsSet()) { if (partyContact.isEmailAddress()) { final EmailAddress emailAddress = (EmailAddress) partyContact; if (emailAddress.hasValue(email)) { return true; } } } return false; } public boolean isPhotoAvailableToCurrentUser() { return isPhotoAvailableToPerson(AccessControl.getPerson()); } public boolean isPhotoAvailableToPerson(Person requester) { if (isPhotoPubliclyAvailable()) { return true; } return requester != null && RoleType.PERSON.isMember(requester.getUser()); } @Override public Photograph getPersonalPhoto() { Photograph photo = super.getPersonalPhoto(); if (photo == null) { return null; } do { if (photo.getState() == PhotoState.APPROVED) { return photo; } photo = photo.getPrevious(); } while (photo != null); return null; } public Photograph getPersonalPhotoEvenIfPending() { Photograph photo = super.getPersonalPhoto(); if (photo == null) { return null; } do { if (photo.getState() != PhotoState.REJECTED && photo.getState() != PhotoState.USER_REJECTED) { return photo; } photo = photo.getPrevious(); } while (photo != null); return null; } public Photograph getPersonalPhotoEvenIfRejected() { return super.getPersonalPhoto(); } @Override public void setPersonalPhoto(final Photograph photo) { if (super.getPersonalPhoto() != null) { photo.setPrevious(super.getPersonalPhoto()); } super.setPersonalPhoto(photo); if (photo != null) { photo.logCreate(this); } } public List<Photograph> getPhotographHistory() { final LinkedList<Photograph> history = new LinkedList<>(); for (Photograph photo = super.getPersonalPhoto(); photo != null; photo = photo.getPrevious()) { history.addFirst(photo); } return history; } public boolean isPhotoPubliclyAvailable() { return getPhotoAvailable(); } public boolean isDefaultEmailVisible() { return getDefaultEmailAddress() == null ? false : getDefaultEmailAddress().getVisibleToPublic(); } public boolean isDefaultWebAddressVisible() { return getDefaultWebAddress() == null ? false : getDefaultWebAddress().getVisibleToPublic(); } @Deprecated public Boolean getAvailableEmail() { return isDefaultEmailVisible(); } @Deprecated public void setAvailableEmail(final Boolean available) { if (getDefaultEmailAddress() != null) { getDefaultEmailAddress().setVisibleToPublic(available); } } @Deprecated public Boolean getAvailableWebSite() { return isDefaultWebAddressVisible(); } @Deprecated public void setAvailableWebSite(final Boolean available) { if (getDefaultWebAddress() != null) { getDefaultWebAddress().setVisibleToPublic(available); } } public String getPresentationName() { final String username = getUsername(); return username == null ? getName() : getName() + " (" + getUsername() + ")"; } @Override public String getPartyPresentationName() { return getPresentationName(); } private boolean hasValidIndividualCandidacy(final Class<? extends IndividualCandidacy> clazz, final ExecutionInterval executionInterval) { for (final IndividualCandidacyPersonalDetails candidacyDetails : getIndividualCandidaciesSet()) { final IndividualCandidacy candidacy = candidacyDetails.getCandidacy(); if (!candidacy.isCancelled() && candidacy.getClass().equals(clazz) && candidacy.isFor(executionInterval)) { return true; } } return false; } public boolean hasValidOver23IndividualCandidacy(final ExecutionInterval executionInterval) { return hasValidIndividualCandidacy(Over23IndividualCandidacy.class, executionInterval); } public boolean hasValidSecondCycleIndividualCandidacy(final ExecutionInterval executionInterval) { return hasValidIndividualCandidacy(SecondCycleIndividualCandidacy.class, executionInterval); } public boolean hasValidDegreeCandidacyForGraduatedPerson(final ExecutionInterval executionInterval) { return hasValidIndividualCandidacy(DegreeCandidacyForGraduatedPerson.class, executionInterval); } public boolean hasValidStandaloneIndividualCandidacy(final ExecutionInterval executionInterval) { return hasValidIndividualCandidacy(StandaloneIndividualCandidacy.class, executionInterval); } public List<Formation> getFormations() { final List<Formation> formations = new ArrayList<>(); for (final Qualification qualification : getAssociatedQualificationsSet()) { if (qualification instanceof Formation) { formations.add((Formation) qualification); } } return formations; } public Qualification getLastQualification() { return !getAssociatedQualificationsSet().isEmpty() ? Collections.max(getAssociatedQualificationsSet(), Qualification.COMPARATOR_BY_YEAR) : null; } public Set<AnnualIRSDeclarationDocument> getAnnualIRSDocuments() { final Set<AnnualIRSDeclarationDocument> result = new HashSet<>(); for (final GeneratedDocument each : getAddressedDocumentSet()) { if (each instanceof AnnualIRSDeclarationDocument) { result.add((AnnualIRSDeclarationDocument) each); } } return result; } public AnnualIRSDeclarationDocument getAnnualIRSDocumentFor(final Integer year) { for (final AnnualIRSDeclarationDocument each : getAnnualIRSDocuments()) { if (each.getYear().equals(year)) { return each; } } return null; } public boolean hasAnnualIRSDocumentFor(final Integer year) { return getAnnualIRSDocumentFor(year) != null; } public boolean hasAnyAdministrativeOfficeFeeAndInsuranceEventInDebt() { for (final Event event : getEventsByEventType(EventType.ADMINISTRATIVE_OFFICE_FEE_INSURANCE)) { if (event.isInDebt()) { return true; } } return false; } public boolean hasAnyPastAdministrativeOfficeFeeAndInsuranceEventInDebt() { for (final Event event : getEventsByEventType(EventType.ADMINISTRATIVE_OFFICE_FEE_INSURANCE)) { final AdministrativeOfficeFeeAndInsuranceEvent administrativeOfficeFeeAndInsuranceEvent = (AdministrativeOfficeFeeAndInsuranceEvent) event; if (administrativeOfficeFeeAndInsuranceEvent instanceof PastAdministrativeOfficeFeeAndInsuranceEvent) { if (event.isInDebt()) { return true; } } } return false; } public boolean hasAnyResidencePaymentsInDebtForPreviousYear() { final int previousYear = new LocalDate().minusYears(1).getYear(); for (final Event event : getResidencePaymentEvents()) { final ResidenceEvent residenceEvent = (ResidenceEvent) event; if (residenceEvent.isFor(previousYear) && !residenceEvent.isCancelled() && !residenceEvent.isPayed()) { return true; } } return false; } public Professorship getProfessorshipByExecutionCourse(final ExecutionCourse executionCourse) { return getProfessorshipsSet().stream().filter(prof -> prof.getExecutionCourse().equals(executionCourse)).findAny() .orElse(null); } public boolean hasProfessorshipForExecutionCourse(final ExecutionCourse executionCourse) { return getProfessorshipByExecutionCourse(executionCourse) != null; } public Set<PhdAlertMessage> getUnreadedPhdAlertMessages() { final Set<PhdAlertMessage> result = new HashSet<>(); for (final PhdAlertMessage message : getPhdAlertMessagesSet()) { if (!message.isReaded()) { result.add(message); } } return result; } public boolean isPhdStudent() { return !getPhdIndividualProgramProcessesSet().isEmpty(); } public RegistrationProtocol getOnlyRegistrationProtocol() { if (getRegistrationProtocolsSet().size() == 1) { return getRegistrationProtocolsSet().iterator().next(); } return null; } public List<Professorship> getProfessorships(final ExecutionSemester executionSemester) { final List<Professorship> professorships = new ArrayList<>(); for (final Professorship professorship : getProfessorshipsSet()) { if (professorship.getExecutionCourse().getExecutionPeriod().equals(executionSemester)) { professorships.add(professorship); } } return professorships; } public List<Professorship> getProfessorships(final ExecutionYear executionYear) { final List<Professorship> professorships = new ArrayList<>(); for (final Professorship professorship : getProfessorshipsSet()) { if (professorship.getExecutionCourse().getExecutionPeriod().getExecutionYear().equals(executionYear)) { professorships.add(professorship); } } return professorships; } public boolean teachesAny(final Collection<ExecutionCourse> executionCourses) { for (final Professorship professorship : getProfessorshipsSet()) { if (executionCourses.contains(professorship.getExecutionCourse())) { return true; } } return false; } public boolean isTeacherEvaluationCoordinatorCouncilMember() { PersistentGroup group = Bennu.getInstance().getTeacherEvaluationCoordinatorCouncil(); return group != null ? group.isMember(Authenticate.getUser()) : false; } public EmailAddress getEmailAddressForSendingEmails() { if (getDisableSendEmails()) { return null; } final EmailAddress defaultEmailAddress = getDefaultEmailAddress(); if (defaultEmailAddress != null) { return defaultEmailAddress; } final EmailAddress institutionalEmailAddress = getInstitutionalEmailAddress(); if (institutionalEmailAddress != null) { return institutionalEmailAddress; } for (final PartyContact partyContact : getPartyContactsSet()) { if (partyContact.isEmailAddress() && partyContact.isActiveAndValid() && partyContact.isValid()) { final EmailAddress otherEmailAddress = (EmailAddress) partyContact; return otherEmailAddress; } } return null; } public String getEmailForSendingEmails() { final EmailAddress emailAddress = getEmailAddressForSendingEmails(); return emailAddress == null ? null : emailAddress.getValue(); } public boolean areContactsRecent(final Class<? extends PartyContact> contactClass, final int daysNotUpdated) { final List<? extends PartyContact> partyContacts = getPartyContacts(contactClass); boolean isUpdated = false; for (final PartyContact partyContact : partyContacts) { if (partyContact.getLastModifiedDate() == null) { isUpdated = isUpdated || false; } else { final DateTime lastModifiedDate = partyContact.getLastModifiedDate(); final DateTime now = new DateTime(); final Months months = Months.monthsBetween(lastModifiedDate, now); if (months.getMonths() > daysNotUpdated) { isUpdated = isUpdated || false; } else { isUpdated = isUpdated || true; } } } return isUpdated; } /** * Use socialSecurityNumber instead */ @Override @Deprecated public String getFiscalCode() { return super.getFiscalCode(); } @Override @Deprecated public void setFiscalCode(final String value) { super.setFiscalCode(value); } public static Person findByUsername(final String username) { final User user = User.findByUsername(username); return user == null ? null : user.getPerson(); } /** * This method gets the identification document series number. * The value is ignored if the document is not an identity card. */ public String getIdentificationDocumentSeriesNumber() { if (getIdDocumentType() == IDDocumentType.IDENTITY_CARD) { String seriesNumber = getIdentificationDocumentSeriesNumberValue(); String extraDigit = getIdentificationDocumentExtraDigitValue(); if (seriesNumber != null) { return seriesNumber; } else if (extraDigit != null) { return extraDigit; } } return ""; } public String getIdentificationDocumentExtraDigitValue() { final PersonIdentificationDocumentExtraInfo result = getPersonIdentificationDocumentExtraInfo(IdentificationDocumentExtraDigit.class); return result != null ? result.getValue() : null; } public String getIdentificationDocumentSeriesNumberValue() { final PersonIdentificationDocumentExtraInfo result = getPersonIdentificationDocumentExtraInfo(IdentificationDocumentSeriesNumber.class); return result != null ? result.getValue() : null; } public PersonIdentificationDocumentExtraInfo getPersonIdentificationDocumentExtraInfo(final Class clazz) { PersonIdentificationDocumentExtraInfo result = null; for (final PersonIdentificationDocumentExtraInfo info : getPersonIdentificationDocumentExtraInfoSet()) { if (info.getClass() == clazz && (result == null || result.getRegisteredInSystemTimestamp().isBefore(info.getRegisteredInSystemTimestamp()))) { result = info; } } return result == null ? null : result; } public void setIdentificationDocumentSeriesNumber(final String identificationDocumentSeriesNumber) { if (!StringUtils.isEmpty(identificationDocumentSeriesNumber) && getIdDocumentType() == IDDocumentType.IDENTITY_CARD) { if (identificationDocumentSeriesNumber.trim().length() == 1) { final PersonIdentificationDocumentExtraInfo personIdentificationDocumentExtraInfo = getPersonIdentificationDocumentExtraInfo(IdentificationDocumentExtraDigit.class); if (personIdentificationDocumentExtraInfo == null) { new IdentificationDocumentExtraDigit(this, identificationDocumentSeriesNumber); } else { personIdentificationDocumentExtraInfo.setValue(identificationDocumentSeriesNumber); } } else { final PersonIdentificationDocumentExtraInfo personIdentificationDocumentExtraInfo = getPersonIdentificationDocumentExtraInfo(IdentificationDocumentSeriesNumber.class); if (personIdentificationDocumentExtraInfo == null) { new IdentificationDocumentSeriesNumber(this, identificationDocumentSeriesNumber); } else { personIdentificationDocumentExtraInfo.setValue(identificationDocumentSeriesNumber); } } } } public void setIdentificationDocumentExtraDigit(final String identificationDocumentExtraDigit) { if (!StringUtils.isEmpty(identificationDocumentExtraDigit)) { final PersonIdentificationDocumentExtraInfo personIdentificationDocumentExtraInfo = getPersonIdentificationDocumentExtraInfo(IdentificationDocumentExtraDigit.class); if (personIdentificationDocumentExtraInfo == null) { new IdentificationDocumentExtraDigit(this, identificationDocumentExtraDigit); } else { personIdentificationDocumentExtraInfo.setValue(identificationDocumentExtraDigit); } } } @Override @Atomic public void setNumberOfValidationRequests(final Integer numberOfValidationRequests) { super.setNumberOfValidationRequests(numberOfValidationRequests); } public boolean getCanValidateContacts() { final DateTime now = new DateTime(); final DateTime requestDate = getLastValidationRequestDate(); if (requestDate == null || getNumberOfValidationRequests() == null) { return true; } final DateTime plus30 = requestDate.plusDays(30); if (now.isAfter(plus30) || now.isEqual(plus30)) { setNumberOfValidationRequests(0); } return getNumberOfValidationRequests() <= MAX_VALIDATION_REQUESTS; } @Atomic public void incValidationRequest() { getCanValidateContacts(); Integer numberOfValidationRequests = getNumberOfValidationRequests(); numberOfValidationRequests = numberOfValidationRequests == null ? 0 : numberOfValidationRequests; if (numberOfValidationRequests <= MAX_VALIDATION_REQUESTS) { setNumberOfValidationRequests(numberOfValidationRequests + 1); setLastValidationRequestDate(new DateTime()); } } @Override public Integer getNumberOfValidationRequests() { final Integer numberOfValidationRequests = super.getNumberOfValidationRequests(); if (numberOfValidationRequests == null) { return 0; } return numberOfValidationRequests; } public boolean isOptOutAvailable() { return BooleanUtils.isTrue(getDisableSendEmails()) || MessagingSystem.getInstance().isOptOutAvailable(this.getUser()); } @Deprecated public java.util.Date getDateOfBirth() { final org.joda.time.YearMonthDay ymd = getDateOfBirthYearMonthDay(); return ymd == null ? null : new java.util.Date(ymd.getYear() - 1900, ymd.getMonthOfYear() - 1, ymd.getDayOfMonth()); } @Deprecated public java.util.Date getEmissionDateOfDocumentId() { final org.joda.time.YearMonthDay ymd = getEmissionDateOfDocumentIdYearMonthDay(); return ymd == null ? null : new java.util.Date(ymd.getYear() - 1900, ymd.getMonthOfYear() - 1, ymd.getDayOfMonth()); } @Deprecated public java.util.Date getExpirationDateOfDocumentId() { final org.joda.time.YearMonthDay ymd = getExpirationDateOfDocumentIdYearMonthDay(); return ymd == null ? null : new java.util.Date(ymd.getYear() - 1900, ymd.getMonthOfYear() - 1, ymd.getDayOfMonth()); } /********************************* * LOGGING METHODS AND OVERRIDES * ********************************/ private void logSetter(String keyTypeOfData, String oldValue, String newValue, String keyLabel) { final String personViewed = PersonInformationLog.getPersonNameForLogDescription(this); if (oldValue.compareTo(newValue) != 0) { String infoLabel = BundleUtil.getString(Bundle.APPLICATION, keyLabel); String typeOfData = BundleUtil.getString(Bundle.MESSAGING, keyTypeOfData); PersonInformationLog.createLog(this, Bundle.MESSAGING, "log.personInformation.edit.generalTemplate", typeOfData, infoLabel, personViewed, oldValue); } } private void logSetterNullString(String keyInfoType, String oldValue, String newValue, String keyLabel) { String argNew, argOld; argOld = valueToUpdateIfNewNotNull(BundleUtil.getString(Bundle.APPLICATION, "label.empty"), oldValue); argNew = valueToUpdateIfNewNotNull(BundleUtil.getString(Bundle.APPLICATION, "label.empty"), newValue); logSetter(keyInfoType, argOld, argNew, keyLabel); } private void logSetterNullYearMonthDay(String keyInfoType, YearMonthDay oldValue, YearMonthDay newValue, String keyLabel) { Object argNew, argOld; String strNew, strOld; argOld = valueToUpdateIfNewNotNull(BundleUtil.getString(Bundle.HTML, "text.dateEmpty"), oldValue); argNew = valueToUpdateIfNewNotNull(BundleUtil.getString(Bundle.HTML, "text.dateEmpty"), newValue); if (argOld instanceof YearMonthDay) { strOld = ((YearMonthDay) argOld).toString("yyyy/MM/dd"); } else { strOld = (String) argOld; } if (argNew instanceof YearMonthDay) { strNew = ((YearMonthDay) argNew).toString("yyyy/MM/dd"); } else { strNew = (String) argNew; } logSetter(keyInfoType, strOld, strNew, keyLabel); } private void logSetterNullEnum(String keyInfoType, IPresentableEnum oldValue, IPresentableEnum newValue, String keyLabel) { Object argNew, argOld; String strNew, strOld; argOld = valueToUpdateIfNewNotNull(BundleUtil.getString(Bundle.APPLICATION, "label.empty"), oldValue); argNew = valueToUpdateIfNewNotNull(BundleUtil.getString(Bundle.APPLICATION, "label.empty"), newValue); if (argOld instanceof Enum) { strOld = ((IPresentableEnum) argOld).getLocalizedName(); } else { strOld = (String) argOld; } if (argNew instanceof Enum) { strNew = ((IPresentableEnum) argNew).getLocalizedName(); } else { strNew = (String) argNew; } logSetter(keyInfoType, strOld, strNew, keyLabel); } @Override public void setGender(Gender arg) { logSetterNullEnum("log.personInformation.edit.generalTemplate.personalData", getGender(), arg, "label.gender"); super.setGender(arg); } @Override public void setProfession(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.personalData", getProfession(), arg, "label.occupation"); super.setProfession(arg); } @Override public void setMaritalStatus(MaritalStatus arg) { // avmc: logic here is different: null value is converted to UNKNOWN MaritalStatus argToSet; if (arg != null) { argToSet = arg; } else { argToSet = MaritalStatus.UNKNOWN; } logSetterNullEnum("log.personInformation.edit.generalTemplate.personalData", getMaritalStatus(), argToSet, "label.maritalStatus"); super.setMaritalStatus(argToSet); } @Override public void setEmissionLocationOfDocumentId(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.personalId", getEmissionLocationOfDocumentId(), arg, "label.documentIdEmissionLocation"); super.setEmissionLocationOfDocumentId(arg); } @Override public void setEmissionDateOfDocumentIdYearMonthDay(YearMonthDay arg) { logSetterNullYearMonthDay("log.personInformation.edit.generalTemplate.personalId", getEmissionDateOfDocumentIdYearMonthDay(), arg, "label.documentIdEmissionDate"); super.setEmissionDateOfDocumentIdYearMonthDay(arg); } @Override public void setExpirationDateOfDocumentIdYearMonthDay(YearMonthDay arg) { logSetterNullYearMonthDay("log.personInformation.edit.generalTemplate.personalId", getExpirationDateOfDocumentIdYearMonthDay(), arg, "label.documentIdExpirationDate"); super.setExpirationDateOfDocumentIdYearMonthDay(arg); } @Override public void setSocialSecurityNumber(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.personalId", getSocialSecurityNumber(), arg, "label.socialSecurityNumber"); if (arg != null) { arg = arg.toUpperCase(); } super.setSocialSecurityNumber(arg); } @Override public void setEidentifier(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.personalId", getEidentifier(), arg, "label.eidentifier"); super.setEidentifier(arg); } @Override public void setDateOfBirthYearMonthDay(YearMonthDay arg) { logSetterNullYearMonthDay("log.personInformation.edit.generalTemplate.filiation", getDateOfBirthYearMonthDay(), arg, "label.dateOfBirth"); super.setDateOfBirthYearMonthDay(arg); } // Nationality @Override public void setCountry(Country arg) { String argNew, argOld; if (getCountry() != null) { if (getCountry().getCountryNationality() != null) { argOld = getCountry().getCountryNationality().getContent(); } else { argOld = getCountry().getName(); } } else { argOld = BundleUtil.getString(Bundle.APPLICATION, "label.empty"); } if (arg != null) { if (arg.getCountryNationality() != null) { argNew = arg.getCountryNationality().getContent(); } else { argNew = arg.getName(); } } else { argNew = BundleUtil.getString(Bundle.APPLICATION, "label.empty"); } super.setCountry(arg); logSetter("log.personInformation.edit.generalTemplate.filiation", argOld, argNew, "label.nationality"); } @Override public void setParishOfBirth(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.filiation", getParishOfBirth(), arg, "label.parishOfBirth"); super.setParishOfBirth(arg); } @Override public void setDistrictSubdivisionOfBirth(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.filiation", getDistrictSubdivisionOfBirth(), arg, "label.districtSubdivisionOfBirth"); super.setDistrictSubdivisionOfBirth(arg); } @Override public void setDistrictOfBirth(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.filiation", getDistrictOfBirth(), arg, "label.districtOfBirth"); super.setDistrictOfBirth(arg); } // Not to be confused with Nationality @Override public void setCountryOfBirth(Country arg) { String argNew, argOld; if (getCountryOfBirth() != null) { argOld = getCountryOfBirth().getName(); } else { argOld = BundleUtil.getString(Bundle.APPLICATION, "label.empty"); } if (arg != null) { argNew = arg.getName(); } else { argNew = BundleUtil.getString(Bundle.APPLICATION, "label.empty"); } super.setCountryOfBirth(arg); logSetter("log.personInformation.edit.generalTemplate.filiation", argOld, argNew, "label.countryOfBirth"); } @Override public void setNameOfMother(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.filiation", getNameOfMother(), arg, "label.nameOfMother"); super.setNameOfMother(arg); } @Override public void setNameOfFather(String arg) { logSetterNullString("log.personInformation.edit.generalTemplate.filiation", getNameOfFather(), arg, "label.nameOfFather"); super.setNameOfFather(arg); } @Override public void logCreateContact(PartyContact contact) { contact.logCreate(this); } @Override public void logEditContact(PartyContact contact, boolean propertiesChanged, boolean valueChanged, boolean createdNewContact, String newValue) { contact.logEdit(this, propertiesChanged, valueChanged, createdNewContact, newValue); } @Override public void logDeleteContact(PartyContact contact) { contact.logDelete(this); } @Override public void logValidContact(PartyContact contact) { contact.logValid(this); } @Override public void logRefuseContact(PartyContact contact) { contact.logRefuse(this); } public static Group convertToUserGroup(Collection<Person> persons) { return Group.users(persons.stream().map(Person::getUser).filter(Objects::nonNull)); } @Override public Sender getSender() { return Optional.ofNullable(super.getSender()).orElseGet(this::buildDefaultSender); } @Atomic private Sender buildDefaultSender() { Sender sender = Sender .from(Installation.getInstance().getInstituitionalEmailAddress("noreply")) .as(createFromName()) .replyTo(getDefaultEmailAddressValue()) .members(getPersonGroup()) .build(); setSender(sender); return sender; } private String createFromName() { return String.format("%s (%s)", Unit.getInstitutionAcronym(), getName()); } public PhysicalAddress getFiscalAddress() { return getPartyContactsSet().stream() .filter(pc -> pc instanceof PhysicalAddress) .map(pc -> (PhysicalAddress) pc) .sorted(PhysicalAddress.COMPARATOR_BY_RELEVANCE) .findFirst().orElse(null); } public Country getVATCountry() { if (getSocialSecurityNumber() != null && getSocialSecurityNumber().length() >= 2) { final String countryCode = getSocialSecurityNumber().substring(0, 2); return Country.readByTwoLetterCode(countryCode); } return null; } }
lgpl-3.0
TeleMidia/nclcomposer
src/plugins/ncl-textual-view/designer/NCLTextEditorQtDesignerPlugin.cpp
1522
/* * Copyright 2011 TeleMidia/PUC-Rio. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ #include "NCLTextEditorQtDesignerPlugin.h" NCLTextEditorPlugin::NCLTextEditorPlugin () {} QString NCLTextEditorPlugin::name () const { return "NCLTextEditor"; } QString NCLTextEditorPlugin::group () const { return "Input"; } QString NCLTextEditorPlugin::toolTip () const { return "NCL Text Editor Widget"; } QWidget * NCLTextEditorPlugin::createWidget (QWidget *parent) { return new NCLTextEditor (parent); } QString NCLTextEditorPlugin::includeFile () const { return "NCLTextEditor.h"; } QIcon NCLTextEditorPlugin::icon () const { return QIcon (); } QString NCLTextEditorPlugin::whatsThis () const { return "A widget to create and edit a NCL file"; } bool NCLTextEditorPlugin::isContainer () const { return false; } Q_EXPORT_PLUGIN2 (ncltexteditorplugin, NCLTextEditorPlugin)
lgpl-3.0
edwinspire/VSharp
class/Microsoft.Build/Microsoft.Build.Evaluation/ProjectCollection.cs
18499
// // ProjectCollection.cs // // Author: // Leszek Ciesielski ([email protected]) // Rolf Bjarne Kvinge ([email protected]) // Atsushi Enomoto ([email protected]) // // (C) 2011 Leszek Ciesielski // Copyright (C) 2011,2013 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Microsoft.Build.Construction; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Logging; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Xml; using System.Reflection; using System.Globalization; namespace Microsoft.Build.Evaluation { public class ProjectCollection : IDisposable { public delegate void ProjectAddedEventHandler (object target, ProjectAddedToProjectCollectionEventArgs args); public class ProjectAddedToProjectCollectionEventArgs : EventArgs { public ProjectAddedToProjectCollectionEventArgs (ProjectRootElement project) { if (project == null) throw new ArgumentNullException ("project"); ProjectRootElement = project; } public ProjectRootElement ProjectRootElement { get; private set; } } // static members static readonly ProjectCollection global_project_collection; static ProjectCollection () { #if NET_4_5 global_project_collection = new ProjectCollection (new ReadOnlyDictionary<string, string> (new Dictionary<string, string> ())); #else global_project_collection = new ProjectCollection (new Dictionary<string, string> ()); #endif } public static string Escape (string unescapedString) { return Mono.XBuild.Utilities.MSBuildUtils.Escape (unescapedString); } public static string Unescape (string escapedString) { return Mono.XBuild.Utilities.MSBuildUtils.Unescape (escapedString); } public static ProjectCollection GlobalProjectCollection { get { return global_project_collection; } } // semantic model part public ProjectCollection () : this (null) { } public ProjectCollection (IDictionary<string, string> globalProperties) : this (globalProperties, null, ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile) { } public ProjectCollection (ToolsetDefinitionLocations toolsetDefinitionLocations) : this (null, null, toolsetDefinitionLocations) { } public ProjectCollection (IDictionary<string, string> globalProperties, IEnumerable<ILogger> loggers, ToolsetDefinitionLocations toolsetDefinitionLocations) : this (globalProperties, loggers, null, toolsetDefinitionLocations, 1, false) { } public ProjectCollection (IDictionary<string, string> globalProperties, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, ToolsetDefinitionLocations toolsetDefinitionLocations, int maxNodeCount, bool onlyLogCriticalEvents) { global_properties = globalProperties ?? new Dictionary<string, string> (); this.loggers = loggers != null ? loggers.ToList () : new List<ILogger> (); toolset_locations = toolsetDefinitionLocations; MaxNodeCount = maxNodeCount; OnlyLogCriticalEvents = onlyLogCriticalEvents; LoadDefaultToolsets (); } [MonoTODO ("not fired yet")] public event ProjectAddedEventHandler ProjectAdded; [MonoTODO ("not fired yet")] public event EventHandler<ProjectChangedEventArgs> ProjectChanged; [MonoTODO ("not fired yet")] public event EventHandler<ProjectCollectionChangedEventArgs> ProjectCollectionChanged; [MonoTODO ("not fired yet")] public event EventHandler<ProjectXmlChangedEventArgs> ProjectXmlChanged; public void AddProject (Project project) { this.loaded_projects.Add (project); if (ProjectAdded != null) ProjectAdded (this, new ProjectAddedToProjectCollectionEventArgs (project.Xml)); } public int Count { get { return loaded_projects.Count; } } string default_tools_version; public string DefaultToolsVersion { get { return default_tools_version; } set { if (GetToolset (value) == null) throw new InvalidOperationException (string.Format ("Toolset '{0}' does not exist", value)); default_tools_version = value; } } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (disposing) { } } public ICollection<Project> GetLoadedProjects (string fullPath) { return LoadedProjects.Where (p => p.FullPath != null && Path.GetFullPath (p.FullPath) == Path.GetFullPath (fullPath)).ToList (); } readonly IDictionary<string, string> global_properties; public IDictionary<string, string> GlobalProperties { get { return global_properties; } } readonly List<Project> loaded_projects = new List<Project> (); public Project LoadProject (string fileName) { return LoadProject (fileName, DefaultToolsVersion); } public Project LoadProject (string fileName, string toolsVersion) { return LoadProject (fileName, null, toolsVersion); } public Project LoadProject (string fileName, IDictionary<string,string> globalProperties, string toolsVersion) { var ret = new Project (fileName, globalProperties, toolsVersion); loaded_projects.Add (ret); return ret; } // These methods somehow don't add the project to ProjectCollection... public Project LoadProject (XmlReader xmlReader) { return LoadProject (xmlReader, DefaultToolsVersion); } public Project LoadProject (XmlReader xmlReader, string toolsVersion) { return LoadProject (xmlReader, null, toolsVersion); } public Project LoadProject (XmlReader xmlReader, IDictionary<string,string> globalProperties, string toolsVersion) { return new Project (xmlReader, globalProperties, toolsVersion); } public ICollection<Project> LoadedProjects { get { return loaded_projects; } } readonly List<ILogger> loggers = new List<ILogger> (); [MonoTODO] public ICollection<ILogger> Loggers { get { return loggers; } } [MonoTODO] public bool OnlyLogCriticalEvents { get; set; } [MonoTODO] public bool SkipEvaluation { get; set; } readonly ToolsetDefinitionLocations toolset_locations; public ToolsetDefinitionLocations ToolsetLocations { get { return toolset_locations; } } readonly List<Toolset> toolsets = new List<Toolset> (); // so what should we do without ToolLocationHelper in Microsoft.Build.Utilities.dll? There is no reference to it in this dll. public ICollection<Toolset> Toolsets { // For ConfigurationFile and None, they cannot be added externally. get { return (ToolsetLocations & ToolsetDefinitionLocations.Registry) != 0 ? toolsets : toolsets.ToList (); } } public Toolset GetToolset (string toolsVersion) { return Toolsets.FirstOrDefault (t => t.ToolsVersion == toolsVersion); } //FIXME: should also support config file, depending on ToolsetLocations void LoadDefaultToolsets () { AddToolset (new Toolset ("2.0", ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20), this, null)); AddToolset (new Toolset ("3.0", ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version30), this, null)); AddToolset (new Toolset ("3.5", ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35), this, null)); #if NET_4_0 AddToolset (new Toolset ("4.0", ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40), this, null)); #endif #if XBUILD_12 AddToolset (new Toolset ("12.0", ToolLocationHelper.GetPathToBuildTools ("12.0"), this, null)); #endif default_tools_version = toolsets.First ().ToolsVersion; } [MonoTODO ("not verified at all")] public void AddToolset (Toolset toolset) { toolsets.Add (toolset); } [MonoTODO ("not verified at all")] public void RemoveAllToolsets () { toolsets.Clear (); } [MonoTODO ("not verified at all")] public void RegisterLogger (ILogger logger) { loggers.Add (logger); } [MonoTODO ("not verified at all")] public void RegisterLoggers (IEnumerable<ILogger> loggers) { foreach (var logger in loggers) this.loggers.Add (logger); } public void UnloadAllProjects () { throw new NotImplementedException (); } [MonoTODO ("Not verified at all")] public void UnloadProject (Project project) { this.loaded_projects.Remove (project); } [MonoTODO ("Not verified at all")] public void UnloadProject (ProjectRootElement projectRootElement) { foreach (var proj in loaded_projects.Where (p => p.Xml == projectRootElement).ToArray ()) UnloadProject (proj); } public static Version Version { get { throw new NotImplementedException (); } } // Execution part [MonoTODO] public bool DisableMarkDirty { get; set; } [MonoTODO] public HostServices HostServices { get; set; } [MonoTODO] public bool IsBuildEnabled { get; set; } internal string BuildStartupDirectory { get; set; } internal int MaxNodeCount { get; private set; } Stack<string> ongoing_imports = new Stack<string> (); internal Stack<string> OngoingImports { get { return ongoing_imports; } } // common part internal static IEnumerable<EnvironmentProjectProperty> GetWellKnownProperties (Project project) { Func<string,string,EnvironmentProjectProperty> create = (name, value) => new EnvironmentProjectProperty (project, name, value, true); return GetWellKnownProperties (create); } internal static IEnumerable<ProjectPropertyInstance> GetWellKnownProperties (ProjectInstance project) { Func<string,string,ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance (name, true, value); return GetWellKnownProperties (create); } static IEnumerable<T> GetWellKnownProperties<T> (Func<string,string,T> create) { var ext = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath") ?? DefaultExtensionsPath; yield return create ("MSBuildExtensionsPath", ext); var ext32 = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath32") ?? DefaultExtensionsPath; yield return create ("MSBuildExtensionsPath32", ext32); var ext64 = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath64") ?? DefaultExtensionsPath; yield return create ("MSBuildExtensionsPath64", ext64); } static string extensions_path; internal static string DefaultExtensionsPath { get { if (extensions_path == null) { // NOTE: code from mcs/tools/gacutil/driver.cs PropertyInfo gac = typeof (System.Environment).GetProperty ( "GacPath", BindingFlags.Static | BindingFlags.NonPublic); if (gac != null) { MethodInfo get_gac = gac.GetGetMethod (true); string gac_path = (string) get_gac.Invoke (null, null); extensions_path = Path.GetFullPath (Path.Combine ( gac_path, Path.Combine ("..", "xbuild"))); } } return extensions_path; } } internal IEnumerable<ReservedProjectProperty> GetReservedProperties (Toolset toolset, Project project) { Func<string,Func<string>,ReservedProjectProperty> create = (name, value) => new ReservedProjectProperty (project, name, value); return GetReservedProperties<ReservedProjectProperty> (toolset, project.Xml, create, () => project.FullPath); } internal IEnumerable<ProjectPropertyInstance> GetReservedProperties (Toolset toolset, ProjectInstance project, ProjectRootElement xml) { Func<string,Func<string>,ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance (name, true, null, value); return GetReservedProperties<ProjectPropertyInstance> (toolset, xml, create, () => project.FullPath); } // seealso http://msdn.microsoft.com/en-us/library/ms164309.aspx IEnumerable<T> GetReservedProperties<T> (Toolset toolset, ProjectRootElement project, Func<string,Func<string>,T> create, Func<string> projectFullPath) { yield return create ("MSBuildBinPath", () => toolset.ToolsPath); // FIXME: add MSBuildLastTaskResult // FIXME: add MSBuildNodeCount // FIXME: add MSBuildProgramFiles32 yield return create ("MSBuildProjectDefaultTargets", () => project.DefaultTargets); yield return create ("MSBuildProjectDirectory", () => project.DirectoryPath + Path.DirectorySeparatorChar); yield return create ("MSBuildProjectDirectoryNoRoot", () => project.DirectoryPath.Substring (Path.GetPathRoot (project.DirectoryPath).Length)); yield return create ("MSBuildProjectExtension", () => Path.GetExtension (project.FullPath)); yield return create ("MSBuildProjectFile", () => Path.GetFileName (project.FullPath)); yield return create ("MSBuildProjectFullPath", () => project.FullPath); yield return create ("MSBuildProjectName", () => Path.GetFileNameWithoutExtension (project.FullPath)); yield return create ("MSBuildStartupDirectory", () => BuildStartupDirectory); yield return create ("MSBuildThisFile", () => Path.GetFileName (GetEvaluationTimeThisFile (projectFullPath))); yield return create ("MSBuildThisFileFullPath", () => GetEvaluationTimeThisFile (projectFullPath)); yield return create ("MSBuildThisFileName", () => Path.GetFileNameWithoutExtension (GetEvaluationTimeThisFile (projectFullPath))); yield return create ("MSBuildThisFileExtension", () => Path.GetExtension (GetEvaluationTimeThisFile (projectFullPath))); yield return create ("MSBuildThisFileDirectory", () => Path.GetDirectoryName (GetEvaluationTimeThisFileDirectory (projectFullPath))); yield return create ("MSBuildThisFileDirectoryNoRoot", () => { string dir = GetEvaluationTimeThisFileDirectory (projectFullPath) + Path.DirectorySeparatorChar; return dir.Substring (Path.GetPathRoot (dir).Length); }); yield return create ("MSBuildToolsPath", () => toolset.ToolsPath); yield return create ("MSBuildToolsVersion", () => toolset.ToolsVersion); } // These are required for reserved property, represents dynamically changing property values. // This should resolve to either the project file path or that of the imported file. internal string GetEvaluationTimeThisFileDirectory (Func<string> nonImportingTimeFullPath) { var file = GetEvaluationTimeThisFile (nonImportingTimeFullPath); var dir = Path.IsPathRooted (file) ? Path.GetDirectoryName (file) : Directory.GetCurrentDirectory (); return dir + Path.DirectorySeparatorChar; } internal string GetEvaluationTimeThisFile (Func<string> nonImportingTimeFullPath) { return OngoingImports.Count > 0 ? OngoingImports.Peek () : (nonImportingTimeFullPath () ?? string.Empty); } static readonly char [] item_target_sep = {';'}; internal static IEnumerable<T> GetAllItems<T> (Func<string,string> expandString, string include, string exclude, Func<string,T> creator, Func<string,ITaskItem> taskItemCreator, string directory, Action<T,string> assignRecurse, Func<ITaskItem,bool> isDuplicate) { var includes = expandString (include).Trim ().Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries); var excludes = expandString (exclude).Trim ().Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries); if (includes.Length == 0) yield break; if (includes.Length == 1 && includes [0].IndexOf ('*') < 0 && excludes.Length == 0) { // for most case - shortcut. var item = creator (includes [0]); yield return item; } else { var ds = new Microsoft.Build.BuildEngine.DirectoryScanner () { BaseDirectory = new DirectoryInfo (directory), Includes = includes.Where (s => !string.IsNullOrWhiteSpace (s)).Select (i => taskItemCreator (i)).ToArray (), Excludes = excludes.Where (s => !string.IsNullOrWhiteSpace (s)).Select (e => taskItemCreator (e)).ToArray (), }; ds.Scan (); foreach (var taskItem in ds.MatchedItems) { if (isDuplicate (taskItem)) continue; // skip duplicate var item = creator (taskItem.ItemSpec); string recurse = taskItem.GetMetadata ("RecursiveDir"); assignRecurse (item, recurse); yield return item; } } } static readonly char [] path_sep = {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}; internal static string GetWellKnownMetadata (string name, string file, Func<string,string> getFullPath, string recursiveDir) { switch (name.ToLower (CultureInfo.InvariantCulture)) { case "fullpath": return getFullPath (file); case "rootdir": return Path.GetPathRoot (getFullPath (file)); case "filename": return Path.GetFileNameWithoutExtension (file); case "extension": return Path.GetExtension (file); case "relativedir": var idx = file.LastIndexOfAny (path_sep); return idx < 0 ? string.Empty : file.Substring (0, idx + 1); case "directory": var fp = getFullPath (file); return Path.GetDirectoryName (fp).Substring (Path.GetPathRoot (fp).Length); case "recursivedir": return recursiveDir; case "identity": return file; case "modifiedtime": return new FileInfo (getFullPath (file)).LastWriteTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff"); case "createdtime": return new FileInfo (getFullPath (file)).CreationTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff"); case "accessedtime": return new FileInfo (getFullPath (file)).LastAccessTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff"); } return null; } } }
lgpl-3.0
JSandrew4/FastGdk
include/Fast/SkeletonAnimationProperties.hpp
2036
/******************************************************************************/ /* */ /* SkeletonAnimationProperties.hpp */ /* */ /* Copyright (C) 2015, Joseph Andrew Staedelin IV */ /* */ /* This file is part of the FastGdk project. */ /* */ /* The FastGdk is free software: you can redistribute it and/or modify */ /* it under the terms of the GNU Lesser General Public License as published */ /* by the Free Software Foundation, either version 3 of the License, or */ /* (at your option) any later version. */ /* */ /* The FastGdk is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with the FastGdk. If not, see <http://www.gnu.org/licenses/>. */ /* */ /******************************************************************************/ #ifndef FastSkeletonAnimationPropertiesHppIncluded #define FastSkeletonAnimationPropertiesHppIncluded #include <Fast/Types.hpp> namespace Fast { class FastApi SkeletonAnimationProperties { }; } #endif // FastSkeletonAnimationPropertiesHppIncluded
lgpl-3.0
theFisher86/MBINCompiler
libMBIN/Source/Models/Structs/GcCostBuildingParts.cs
219
namespace libMBIN.Models.Structs { public class GcCostBuildingParts : NMSTemplate { [NMS(Size = 0x10)] public string Description; public GcBuildingCostPartCount RequiredParts; } }
lgpl-3.0
BackupTheBerlios/cppparser
src/scalpel/cpp/syntax_nodes/delete_expression.hpp
1202
/* Scalpel - Source Code Analysis, Libre and PortablE Library Copyright © 2008 - 2010 Florian Goujeon This file is part of Scalpel. Scalpel is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Scalpel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Scalpel. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SCALPEL_CPP_SYNTAX_NODES_DELETE_EXPRESSION_HPP #define SCALPEL_CPP_SYNTAX_NODES_DELETE_EXPRESSION_HPP #include "simple_delete_expression.hpp" #include "array_delete_expression.hpp" #include "alternative_node.hpp" namespace scalpel { namespace cpp { namespace syntax_nodes { typedef alternative_node < simple_delete_expression, array_delete_expression > delete_expression ; }}} //namespace scalpel::cpp::syntax_nodes #endif
lgpl-3.0