Reads all hunt objects from the database.
967820
def ReadHuntObjects(self,
                      offset,
                      count,
                      with_creator=None,
                      created_after=None,
                      with_description_match=None):
    """"""
    filter_fns = []
    if with_creator is not None:
      filter_fns.append(lambda h: h.creator == with_creator)
    if created_after is not None:
      filter_fns.append(lambda h: h.create_time > created_after)
    if with_description_match is not None:
      filter_fns.append(lambda h: with_description_match in h.description)
    filter_fn = lambda h: all(f(h) for f in filter_fns)

    result = [self._DeepCopy(h) for h in self.hunts.values() if filter_fn(h)]
    return sorted(
        result, key=lambda h: h.create_time,
        reverse=True)[offset:offset + (count or db.MAX_COUNT)]
1189317
public Collection getAllObjects(Class target)
    {
        PersistenceBroker broker = getBroker();
        Collection result;
        try
        {
            Query q = new QueryByCriteria(target);
            result = broker.getCollectionByQuery(q);
        }
        finally
        {
            if (broker != null) broker.close();
        }
        return result;
    }
800060
def WriteHuntObject(self, hunt_obj, cursor=None):
    """"""
    query = """
    INSERT INTO hunts (hunt_id, creator, description, duration_micros,
                       hunt_state,
                       client_rate, client_limit,
                       hunt)
    VALUES (%(hunt_id)s, %(creator)s, %(description)s, %(duration_micros)s,
            %(hunt_state)s,
            %(client_rate)s, %(client_limit)s,
            %(hunt)s)
    """

    args = {
        "hunt_id": db_utils.HuntIDToInt(hunt_obj.hunt_id),
        "creator": hunt_obj.creator,
        "description": hunt_obj.description,
        "duration_micros": hunt_obj.duration.microseconds,
        "hunt_state": int(rdf_hunt_objects.Hunt.HuntState.PAUSED),
        "client_rate": hunt_obj.client_rate,
        "client_limit": hunt_obj.client_limit,
        "hunt": hunt_obj.SerializeToString(),
    }

    try:
      cursor.execute(query, args)
    except MySQLdb.IntegrityError as error:
      raise db.DuplicatedHuntError(hunt_id=hunt_obj.hunt_id, cause=error)
1013222
def retrieve_all(self):
        
        with sqlite3.connect(self.dbname) as carddb:
            for row in carddb.execute("SELECT code FROM CARDS"):
                yield self.load_card(row[0])
514999
def getAll(self):
        
        objs = []
        for obj in self.model.db:
            objs.append(self._cast_model(obj))

        return objs
1130653
def list_objects(self):
        '''  '''
        for i in self._execute('select * from objects'):
            _id, code = i
            yield _id, code, self.deserialize(code)
731242
private void readAll() {
        final List<CompletableFuture<Void>> futures = new ArrayList<>();
        for(File file : directory.listFiles()) {
            
            final Runnable loadFile = () -> {
                if(file.getName().endsWith(SUFFIX)) {
                    try(FileReader reader = new FileReader(file)) {
                        Properties props = new Properties();
                        props.load(reader);
                        Map.Entry<Key,HttpCookie> entry = fromProperties(props);
                        if(entry != null) {
                            add(entry.getKey(), entry.getValue());
                        }
                        else {
                            file.delete();
                        }
                    }
                    catch(IOException ioe) {
                        throw new RuntimeException(ioe);
                    }
                } };

            futures.add(CompletableFuture.runAsync(loadFile, executor));
        }

        try {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();
        }
        catch(InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
509784
def CleanAff4Hunts(self):
    """"""

    hunts_ttl = config.CONFIG["DataRetention.hunts_ttl"]
    if not hunts_ttl:
      self.Log("TTL not set - nothing to do...")
      return

    exception_label = config.CONFIG["DataRetention.hunts_ttl_exception_label"]

    hunts_root = aff4.FACTORY.Open("aff4:/hunts", token=self.token)
    hunts_urns = list(hunts_root.ListChildren())

    deadline = rdfvalue.RDFDatetime.Now() - hunts_ttl

    hunts_deleted = 0

    hunts = aff4.FACTORY.MultiOpen(
        hunts_urns, aff4_type=implementation.GRRHunt, token=self.token)
    for hunt in hunts:
      if exception_label in hunt.GetLabelsNames():
        continue

      runner = hunt.GetRunner()
      if runner.context.create_time + runner.context.duration < deadline:
        aff4.FACTORY.Delete(hunt.urn, token=self.token)
        hunts_deleted += 1
        self.HeartBeat()
    self.Log("Deleted %d hunts." % hunts_deleted)
903305
def UpdateHunt(hunt_id, client_limit=None, client_rate=None, duration=None):
  """"""

  hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
  if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED:
    raise OnlyPausedHuntCanBeModifiedError(hunt_obj)

  data_store.REL_DB.UpdateHuntObject(
      hunt_id,
      client_limit=client_limit,
      client_rate=client_rate,
      duration=duration)
  return data_store.REL_DB.ReadHuntObject(hunt_id)
890242
def DeleteHuntObject(self, hunt_id, cursor=None):
    """"""
    query = "DELETE FROM hunts WHERE hunt_id = %s"
    hunt_id_int = db_utils.HuntIDToInt(hunt_id)

    rows_deleted = cursor.execute(query, [hunt_id_int])
    if rows_deleted == 0:
      raise db.UnknownHuntError(hunt_id)

    query = "DELETE FROM hunt_output_plugins_states WHERE hunt_id = %s"
    cursor.execute(query, [hunt_id_int])
182634
def read_all(self):
        
        result = self._data[self._position:]
        self._position = None  # ensure no subsequent read()
        return result
828645
def ReadHuntOutputPluginLogEntries(self,
                                     hunt_id,
                                     output_plugin_id,
                                     offset,
                                     count,
                                     with_type=None):
    """"""

    all_entries = []
    for flow_obj in self._GetHuntFlows(hunt_id):
      for entry in self.ReadFlowOutputPluginLogEntries(
          flow_obj.client_id,
          flow_obj.flow_id,
          output_plugin_id,
          0,
          sys.maxsize,
          with_type=with_type):
        all_entries.append(
            rdf_flow_objects.FlowOutputPluginLogEntry(
                hunt_id=hunt_id,
                client_id=flow_obj.client_id,
                flow_id=flow_obj.flow_id,
                output_plugin_id=output_plugin_id,
                log_entry_type=entry.log_entry_type,
                timestamp=entry.timestamp,
                message=entry.message))

    return sorted(all_entries, key=lambda x: x.timestamp)[offset:offset + count]
1050403
def ReadHuntObjects(self,
                      offset,
                      count,
                      with_creator=None,
                      created_after=None,
                      with_description_match=None,
                      cursor=None):
    """"""
    query = "SELECT {columns} FROM hunts ".format(columns=_HUNT_COLUMNS_SELECT)
    args = []

    components = []
    if with_creator is not None:
      components.append("creator = %s ")
      args.append(with_creator)

    if created_after is not None:
      components.append("create_timestamp > FROM_UNIXTIME(%s) ")
      args.append(mysql_utils.RDFDatetimeToTimestamp(created_after))

    if with_description_match is not None:
      components.append("description LIKE %s")
      args.append("%" + with_description_match + "%")

    if components:
      query += "WHERE " + " AND ".join(components)

    query += " ORDER BY create_timestamp DESC LIMIT %s OFFSET %s"
    args.append(count)
    args.append(offset)

    cursor.execute(query, args)
    return [self._HuntObjectFromRow(row) for row in cursor.fetchall()]
775015
@Override
    public List readDataByRange(String tableName, Class clazz, EntityMetadata m, byte[] startRow, byte[] endRow,
            String[] columns, FilterList f) throws IOException
    {
        List output = new ArrayList();
        HTableInterface hTable = null;
        Object entity = null;
        List<String> relationNames = m.getRelationNames();
        Filter filter = getFilter(m.getTableName());
        if (filter != null)
        {
            if (f == null)
            {
                f = new FilterList();
            }
            f.addFilter(filter);
        }
        // Load raw data from HBase
        hTable = gethTable(tableName);
        List<HBaseData> results = hbaseReader.loadAll(hTable, f, startRow, endRow, m.getTableName(), null, columns);
        output = onRead(tableName, clazz, m, output, hTable, entity, relationNames, results);

        return output;
    }
1048797
def fetch_object_from_db_by_pk(self,
                                   obj: Any,
                                   table: str,
                                   fieldlist: Sequence[str],
                                   pkvalue: Any) -> bool:
        """"""
        if pkvalue is None:
            blank_object(obj, fieldlist)
            return False
        row = self.fetchone(
            get_sql_select_all_non_pk_fields_by_pk(table, fieldlist,
                                                   self.get_delims()),
            pkvalue
        )
        if row is None:
            blank_object(obj, fieldlist)
            return False
        setattr(obj, fieldlist[0], pkvalue)  # set PK value of obj
        assign_from_list(obj, fieldlist[1:], row)  # set non-PK values of obj
        return True
701260
def process(self):
    
    print('Hunt to collect {0:d} items'.format(len(self.file_path_list)))
    print('Files to be collected: {0!s}'.format(self.file_path_list))
    hunt_action = flows_pb2.FileFinderAction(
        action_type=flows_pb2.FileFinderAction.DOWNLOAD)
    hunt_args = flows_pb2.FileFinderArgs(
        paths=self.file_path_list, action=hunt_action)
    return self._create_hunt('FileFinder', hunt_args)
1371958
def ReadHuntOutputPluginsStates(self, hunt_id, cursor=None):
    """"""

    columns = ", ".join(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS)

    query = ("SELECT {columns} FROM hunt_output_plugins_states "
             "WHERE hunt_id = %s".format(columns=columns))
    rows_returned = cursor.execute(query, [db_utils.HuntIDToInt(hunt_id)])
    if rows_returned > 0:
      states = []
      for row in cursor.fetchall():
        states.append(self._HuntOutputPluginStateFromRow(row))
      return states

    query = "SELECT hunt_id FROM hunts WHERE hunt_id = %s"
    rows_returned = cursor.execute(query, [db_utils.HuntIDToInt(hunt_id)])
    if rows_returned == 0:
      raise db.UnknownHuntError(hunt_id)

    return []