def saved_searches_factory_helper(splunk_connection_info): """Return a valid splunklib.client.SavedSearches object kwargs: - see splunklib.client.connect() """ if not ISplunkConnectionInfo.providedBy(splunk_connection_info): DoesNotImplement('argument did not provide expected interface') service = connect(**splunk_connection_info) saved_searches = service.saved_searches for s in saved_searches: logger.debug("Found Splunk saved search with name %s" % s.name) return saved_searches
def __init__(self, brand=None, model=None, device=None, config_file=None, *args, **kwargs): BasePrinter.__init__(self, brand, model, device, config_file, *args, **kwargs) if IChequePrinter not in providedBy(self._driver): raise DoesNotImplement("The driver %r doesn't implements the " "IChequePrinter interface" % self._driver) self._charset = self._driver.cheque_printer_charset
def validate(self, xml_doc): if not IXmlDoc.providedBy(xml_doc): raise DoesNotImplement(IXmlDoc) doc = xml_doc.getXml_doc() try: self.schema.assertValid(doc) except AttributeError: valid = self.schema.validate(doc) if not valid: msg = "Could not validate document." raise SeisHubError(msg) except etree.DocumentInvalid, e: msg = "Could not validate document. (%s)" raise InvalidObjectError(msg % str(e))
def verify_storage(storage): """ :param storage: :return: """ if not IProtocolStogareInterface.providedBy(storage): raise DoesNotImplement( 'A storage {} does not implement IProtocolStogareInterface'. format(storage)) else: return storage
def store(self, *objs, **kwargs): """ Store a (list of) Serializable object(s) into specified DB table if objs is a list, all objects in list will be stored within the same transaction. @keyword cascading: If True, also underlying related objects are stored, default is False. @type cascading: bool """ if hasattr(self, 'debug') and self.debug: start = time.time() cascading = kwargs.get('cascading', False) update = kwargs.get('update', False) if cascading: casc_objs = list() for o in objs: casc_objs.extend(self._get_children(o)) objs = casc_objs db = self.getDb() conn = db.connect() txn = conn.begin() try: for o in objs: if not ISerializable.providedBy(o): raise DoesNotImplement(ISerializable) table = o.db_table kwargs = self._to_kwargs(o) if not update or not o._id: r = conn.execute(table.insert(), **kwargs) try: # SQLAlchemy >= 0.6.x o._id = r.inserted_primary_key[0] except: # SQLAlchemy < 0.6.x o._id = r.last_inserted_ids()[0] else: w = (table.c[o.db_mapping['_id']] == o._id) r = conn.execute(table.update(w), **kwargs) # inform new children about object id by setting it again o._id = o._id txn.commit() except IntegrityError, e: txn.rollback() raise DbError("Error storing an object.", e)
def _checkConsistency(richInputs, fsm, inputContext): """ Verify that the outputs that can be generated by fsm have their requirements satisfied by the given rich inputs. @param richInputs: A L{list} of all of the types which will serve as rich inputs to an L{IFiniteStateMachine}. @type richInputs: L{list} of L{IRichInput} providers @param fsm: The L{IFiniteStateMachine} to which these rich inputs are to be delivered. @param inputContext: A L{dict} mapping output symbols to L{Interface} subclasses. Rich inputs which result in these outputs being produced by C{fsm} must provide the corresponding interface. @raise DoesNotImplement: If any of the rich input types fails to implement the interfaces required by the outputs C{fsm} can produce when they are received. """ for richInput in richInputs: for state in fsm: for input in fsm[state]: if richInput.symbol() == input: # This rich input will be supplied to represent this input # symbol in this state. Check to see if it satisfies the # output requirements. outputs = fsm[state][input].output for output in outputs: try: required = inputContext[output] except KeyError: continue # Consider supporting non-interface based checking in # the future: extend this to also allow # issubclass(richInput, required) if required.implementedBy(richInput): continue raise DoesNotImplement( "%r not implemented by %r, " "required by %r in state %r" % (required, richInput, input, state))
def query(self, xpath): """ Query the catalog. @param xpath: xpath query to be performed @type xpath: L{seishub.xmldb.interfaces.IXPathQuery} @return: result set containing uris of resources this xpath applies to @rtype: list of strings """ if not IXPathQuery.providedBy(xpath): raise DoesNotImplement(IXPathQuery) # evaluate XPath query location_path = xpath.getLocationPath() predicates = xpath.getPredicates() order_by = xpath.getOrderBy() or list() limit = xpath.getLimit() offset = xpath.getOffset() # default columns: document_id, package, resourcetype, resource_name, # size, uid, datetime columns = [ document_tab.c['id'].label("document_id"), packages_tab.c['name'].label("package_id"), resourcetypes_tab.c['name'].label("resourcetype_id"), resource_tab.c['name'].label("resource_name"), document_tab.c['revision'].label("revision"), document_meta_tab.c['size'].label('meta_size'), document_meta_tab.c['uid'].label('meta_uid'), document_meta_tab.c['datetime'].label('meta_datetime') ] pkg, rt = location_path[0:2] # join default columns oncl = (resource_tab.c['id'] == document_tab.c['resource_id']) joins = document_tab.join(resource_tab, onclause=oncl) oncl = resourcetypes_tab.c['id'] == resource_tab.c['resourcetype_id'] if rt: oncl = sql.and_(oncl, resourcetypes_tab.c['name'] == rt) joins = joins.join(resourcetypes_tab, onclause=oncl) oncl = resourcetypes_tab.c['package_id'] == packages_tab.c['id'] if pkg: oncl = sql.and_(oncl, packages_tab.c['name'] == pkg) joins = joins.join(packages_tab, onclause=oncl) oncl = (document_tab.c['id'] == document_meta_tab.c['id']) joins = joins.join(document_meta_tab, onclause=oncl) # parse predicates query = select(columns, use_labels=True, distinct=True) if predicates: query, joins, w = self._process_predicates(predicates, query, joins) if w is not None: query = query.where(w) # order by if order_by: query, joins = self._process_order_by(order_by, query, joins) else: # default order by document id query = query.order_by(document_tab.c['id']) query = query.select_from(joins) # limit and offset if limit: query = query.limit(limit) if offset: query = query.offset(offset) # query res = self._db.execute(query) results = self._process_results(res) res.close() return results
def _verify(iface, candidate, tentative=0, vtype=None): """Verify that 'candidate' might correctly implements 'iface'. This involves: o Making sure the candidate defines all the necessary methods o Making sure the methods have the correct signature o Making sure the candidate asserts that it implements the interface Note that this isn't the same as verifying that the class does implement the interface. If optional tentative is true, suppress the "is implemented by" test. """ if vtype == 'c': tester = iface.implementedBy else: tester = iface.providedBy if not tentative and not tester(candidate): raise DoesNotImplement(iface) # Here the `desc` is either an `Attribute` or `Method` instance for name, desc in iface.namesAndDescriptions(1): try: attr = getattr(candidate, name) except AttributeError: if (not isinstance(desc, Method)) and vtype == 'c': # We can't verify non-methods on classes, since the # class may provide attrs in it's __init__. continue raise BrokenImplementation(iface, name) if not isinstance(desc, Method): # If it's not a method, there's nothing else we can test continue if isinstance(attr, FunctionType): if sys.version_info[0] >= 3 and isinstance(candidate, type) and vtype == 'c': # This is an "unbound method" in Python 3. # Only unwrap this if we're verifying implementedBy; # otherwise we can unwrap @staticmethod on classes that directly # provide an interface. meth = fromFunction(attr, iface, name=name, imlevel=1) else: # Nope, just a normal function meth = fromFunction(attr, iface, name=name) elif (isinstance(attr, MethodTypes) and type(attr.__func__) is FunctionType): meth = fromMethod(attr, iface, name) elif isinstance(attr, property) and vtype == 'c': # We without an instance we cannot be sure it's not a # callable. continue else: if not callable(attr): raise BrokenMethodImplementation(name, "Not a method") # sigh, it's callable, but we don't know how to introspect it, so # we have to give it a pass. continue # Make sure that the required and implemented method signatures are # the same. desc = desc.getSignatureInfo() meth = meth.getSignatureInfo() mess = _incompat(desc, meth) if mess: raise BrokenMethodImplementation(name, mess) return True
def get_sibling_group_by_id(self, state_id): """Tare definition of SitePlugin method.""" raise DoesNotImplement("Skeleton only.")
def _verify(iface, candidate, tentative=0, vtype=None): """Verify that 'candidate' might correctly implements 'iface'. This involves: o Making sure the candidate defines all the necessary methods o Making sure the methods have the correct signature o Making sure the candidate asserts that it implements the interface Note that this isn't the same as verifying that the class does implement the interface. If optional tentative is true, suppress the "is implemented by" test. """ if vtype == 'c': tester = iface.implementedBy else: tester = iface.providedBy violations = [] def format(e): return " " + str(e).strip() + "\n" if not tentative and not tester(candidate): violations.append(format(DoesNotImplement(iface))) # Here the `desc` is either an `Attribute` or `Method` instance for name, desc in iface.namesAndDescriptions(1): if not hasattr(candidate, name): if (not isinstance(desc, Method)) and vtype == 'c': # We can't verify non-methods on classes, since the # class may provide attrs in it's __init__. continue if isinstance(desc, Method): violations.append(" The %r method was not provided.\n" % (name,)) else: violations.append(" The %r attribute was not provided.\n" % (name,)) continue attr = getattr(candidate, name) if not isinstance(desc, Method): # If it's not a method, there's nothing else we can test continue if isinstance(attr, FunctionType): # should never get here, since classes should not provide functions meth = fromFunction(attr, iface, name=name) elif (isinstance(attr, MethodTypes) and type(attr.im_func) is FunctionType): meth = fromMethod(attr, iface, name) else: if not callable(attr): violations.append(format(BrokenMethodImplementation(name, "Not a method"))) # sigh, it's callable, but we don't know how to intrspect it, so # we have to give it a pass. continue # Make sure that the required and implemented method signatures are # the same. desc = desc.getSignatureInfo() meth = meth.getSignatureInfo() mess = _incompat(desc, meth) if mess: violations.append(format(BrokenMethodImplementation(name, mess))) if violations: raise Exception("".join(violations)) return True
def get_sibling_group_count(self): """Return the number of SiblingGroup objects in the database.""" raise DoesNotImplement("Skeleton only.")
def get_children_count(self): """Return the number of Child objects in the database.""" raise DoesNotImplement("Skeleton only.")
def pickup(self, cls, **keys): """ Read Serializable objects with given keys from database. @param cls: Object type to be retrieved. @keyword _order_by: dictionary of the form: {'attribute':'ASC'|'DESC', ...} @keyword _limit: result limit @keyword _offset: result offset (used in combination with limit) @param **keys: kwarg list of the form: - attribute_name = value or for relational attributes: - attribute_name = Object - attribute_name = {'attribute_name' : 'value'} In a to-many relation DB_LIMIT_MIN and DB_LIMIT_MAX may be used to select only one single related object providing the maximum (or minimum) for the given attribute: - relation_name = DB_LIMIT_MAX('attribute_name') Use DB_NULL as a value to force a column to be None; attribute_name = None will be ignored: - attribute_name = DB_NULL """ if hasattr(self, 'debug') and self.debug: start = time.time() if not ISerializable.implementedBy(cls): raise DoesNotImplement(ISerializable) order_by = keys.get('_order_by', dict()) limit = keys.get('_limit', None) offset = keys.get('_offset', None) table = cls.db_table map = cls.db_mapping # generate query q = table.select(use_labels=True) q, join_list = self._generate_query(q, table, map, keys, order_by=order_by, joins=list()) if join_list and len(join_list) >= 2: left_tab = join_list[0][1][0] joins = left_tab.outerjoin(join_list[1][0], onclause=or_(*join_list[1][1])) del join_list[:2] for j in join_list: joins = joins.outerjoin(j[0], onclause=or_(*j[1])) q = q.select_from(joins) q = self._order_by(q, table, map, order_by) q = q.offset(offset).limit(limit) # execute query # XXX: query only from read only user db = self.getDb() query = db.execute(q) if self._is_sqlite(): # SQLite does not support multiple open connections; In particular # it is not possible to commit inserts while keeping an open cursor results = query.fetchall() else: results = query # create objects from results objs = {cls: list()} for res in results: objs = self._generate_objs(cls, res, objs) query.close() if hasattr(self, 'debug') and self.debug: print "DBUTIL: Loaded %i object(-tree)s in %s seconds." % \ (len(objs[cls]), time.time() - start) return self._to_list(objs[cls])