@Override
 public void executeInObjectContainer(ObjectContainer objectContainer) {
   ObjectSet<Training> trainings = objectContainer.query(Training.class);
   while (trainings.hasNext()) {
     objectContainer.delete(trainings.next());
   }
 }
Esempio n. 2
0
  protected static void showAgglomerationsInfoFromDeparment(ObjectContainer bd, String depId) {

    ObjectSet<Departement> oc =
        bd.query(
            new Predicate<Departement>() {
              public boolean match(Departement d) {
                return true;
              }
            });
    for (Departement d : oc) {
      if (d.getNom() == depId) {
        for (Agglomeration ag : d.agglomerations) {
          System.out.println(
              "codePostal: "
                  + ag.codePostal
                  + " nom: "
                  + ag.nom
                  + " descritpion: "
                  + ag.description
                  + " nbHabit: "
                  + ag.description
                  + " surface: "
                  + d.surface);
        }
      }
    }
  }
  public static boolean deleteRegistration(final RegisterContextRequest rcrNew) {

    List<RegisterContextRequest> results;
    final String updateRegId = rcrNew.getRegistrationId();

    results =
        db.query(
            new Predicate<RegisterContextRequest>() {
              public boolean match(RegisterContextRequest req) {
                String storedRegID = req.getRegistrationId();
                if (storedRegID.equals(updateRegId)) {
                  return true;
                }
                return false;
              }
            });

    if (results.size() > 0) {
      RegisterContextRequest found = results.get(0);
      System.out.println("Deleting registration");
      db.delete(found);
      db.commit();
      return true;
    }
    return false;
  }
 public long size(ObjectContainer container) {
   Query query = container.query();
   query.constrain(PersistentCooldownQueueItem.class);
   query.descend("parent").constrain(this).identity();
   ObjectSet<PersistentCooldownQueueItem> results = query.execute();
   return results.size();
 }
Esempio n. 5
0
  static void init(USKManager manager, ObjectContainer container, final ClientContext context) {
    ObjectSet<USKFetcherTag> set =
        container.query(
            new Predicate<USKFetcherTag>() {
              private static final long serialVersionUID = 9150637337019063048L;

              @Override
              public boolean match(USKFetcherTag tag) {
                if (tag.nodeDBHandle != context.nodeDBHandle) return false;
                if (tag.isFinished()) return false;
                return true;
              }
            });
    while (set.hasNext()) {
      try {
        set.next().start(manager, context, container);
      } catch (Throwable t) {
        Logger.error(
            USKManagerPersistent.class,
            "USKFetcherTag failed to start - partially removed??? : " + t,
            t);
        System.err.println("USKFetcherTag failed to start - partially removed??? : " + t);
        t.printStackTrace();
      }
    }
  }
  public static List<RegisterContextRequest> getRegByEntityType(final String entityType) {

    List<RegisterContextRequest> results;

    results =
        db.query(
            new Predicate<RegisterContextRequest>() {
              public boolean match(RegisterContextRequest req) {

                final int contRegListSize = req.getContextRegistration().size();
                //                System.out.println("contRegListSize: " + contRegListSize);
                for (int i = 0; i < contRegListSize; i++) {

                  final int entityIdListSize =
                      req.getContextRegistration().get(i).getEntityId().size();
                  //                    System.out.println("entityidListSize: " + entityIdListSize);

                  for (int j = 0; j < entityIdListSize; j++) {

                    String storedEType =
                        req.getContextRegistration().get(i).getEntityId().get(j).getType();

                    // return storedEType.equals(entityType);
                    if (storedEType.equals(entityType)) {
                      return true;
                    }
                  }
                } // contRegList loop
                return false;
              }
            });

    return results;
  }
  public List<Persona> recuperarPersonaAvanzada() {
    List<Persona> listaAvanzada = new ArrayList<Persona>();
    int edad = 30;
    String dni = "20";
    String letraF = "o";

    try {
      ObjectSet<Persona> set =
          bbdd.query(
              new Predicate<Persona>() {
                public boolean match(Persona p) {
                  return p.getNombre().endsWith(letraF)
                      || p.getDni().startsWith(dni)
                      || p.getEdad() > edad;
                }
              });

      for (Persona p : set) {
        p.print();
        listaAvanzada.add(p);
      }

    } finally {
      bbdd.close();
    }

    return listaAvanzada;
  }
 private boolean expect(ObjectContainer container, String[] names) {
   Collection4 expected = new Collection4(names);
   ObjectSet actual = container.query(CrashData.class);
   while (actual.hasNext()) {
     CrashData current = (CrashData) actual.next();
     if (!expected.remove(current._name)) {
       return false;
     }
   }
   return expected.isEmpty();
 }
Esempio n. 9
0
 @SuppressWarnings("rawtypes")
 public ArrayList<Usuario> recuperarUsuario() {
   ObjectContainer usuarioBD =
       Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "../usuarios.db4o");
   List usuariosBanco = usuarioBD.query(Usuario.class);
   ArrayList<Usuario> lista = new ArrayList<Usuario>();
   for (Object i : usuariosBanco) {
     lista.add((Usuario) i);
   }
   usuarioBD.close();
   return lista;
 }
  public List<Cliente> BuscarClientes(final String filtro) {

    ObjectContainer db = DBController.getInstance().getDB();
    return db.query(
        new Predicate<Cliente>() {
          @Override
          public boolean match(Cliente cliente) {
            return cliente.getNombres().toUpperCase().contains(filtro.toUpperCase())
                || cliente.getApellidos().contains(filtro.toUpperCase());
          }
        });
  }
Esempio n. 11
0
  /**
   * Realiza pesquisa de objetos com base em sua classe e ordenada pelo atributo informado.
   *
   * @param classe tipo do objeto pesquisado
   * @param nomeAtributoOrdenacao o nome do atributo que será utilizado para ordenar a pesquisa
   * @param tipoOrdenacao o tipo de ordenação desejada ('1 - crescente' e '2 - decrescente')
   * @return a lista ordenada de objetos da classe especificada @
   */
  public List pesquisarOrdenado(Class classe, String nomeAtributoOrdenacao, int tipoOrdenacao) {

    // Configura os filtros/critérios de pesquisa:
    Query query = bd.query();
    query.constrain(classe);

    // Configura a ordenação do resultado da pesquisa:
    configurarOrdenacao(query, nomeAtributoOrdenacao, tipoOrdenacao);

    // Executa a pesquisa e retorna o resultado:
    return efetivarPesquisar(query);
  }
Esempio n. 12
0
  public List filtrar(Class classe, Evaluation filtro, String campoOrdem, int ordem) {
    Query query = bd.query();
    query.constrain(classe);
    query.constrain(filtro);

    if (ORDENACAO_CRESCENTE == ordem) {
      query.descend(campoOrdem).orderAscending();
    } else {
      query.descend(campoOrdem).orderDescending();
    }

    return query.execute();
  }
Esempio n. 13
0
 public void salvarUsuario(Usuario user) {
   ObjectContainer usuarioBD =
       Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "../usuarios.db4o");
   boolean adicionar = true;
   List<Usuario> usuariosBanco = usuarioBD.query(Usuario.class);
   for (Usuario i : usuariosBanco) {
     if (i.matches(user.getNome())) {
       adicionar = false;
     }
   }
   if (adicionar) {
     usuarioBD.store(user);
     JOptionPane.showMessageDialog(null, "Adicionado com Sucesso");
   }
   usuarioBD.close();
 }
Esempio n. 14
0
 private void populate(ObjectContainer container) {
   for (int i = 0; i < 10; i++) {
     container.store(new Item("delme"));
   }
   CrashData one = new CrashData(null, "one");
   CrashData two = new CrashData(one, "two");
   CrashData three = new CrashData(one, "three");
   container.store(one);
   container.store(two);
   container.store(three);
   container.commit();
   ObjectSet objectSet = container.query(Item.class);
   while (objectSet.hasNext()) {
     container.delete(objectSet.next());
   }
 }
  @Override
  public boolean removeKey(
      final Key key, final SendableGet client, final long time, ObjectContainer container) {
    boolean found = false;
    final String keyAsBytes = HexUtil.bytesToHex(key.getFullKey());
    Query query = container.query();
    query.constrain(PersistentCooldownQueueItem.class);
    query.descend("keyAsBytes").constrain(keyAsBytes);
    // The result from parent will be huge, and client may be huge too.
    // Don't bother with a join, just check in the evaluation.
    //		query.descend("client").constrain(client);
    //		query.descend("parent").constrain(this);
    Evaluation eval =
        new Evaluation() {
          private static final long serialVersionUID = 1537102695504880276L;

          @Override
          public void evaluate(Candidate candidate) {
            PersistentCooldownQueueItem item = (PersistentCooldownQueueItem) candidate.getObject();
            if (item.client != client) {
              candidate.include(false);
              return;
            }
            if (item.parent != PersistentCooldownQueue.this) {
              candidate.include(false);
              return;
            }
            Key k = item.key;
            candidate.objectContainer().activate(k, 5);
            if (k.equals(key)) candidate.include(true);
            else {
              candidate.include(false);
              candidate.objectContainer().deactivate(k, 5);
            }
          }
        };
    query.constrain(eval);
    ObjectSet<PersistentCooldownQueueItem> results = query.execute();

    while (results.hasNext()) {
      found = true;
      PersistentCooldownQueueItem i = (PersistentCooldownQueueItem) results.next();
      i.delete(container);
      itemsFromLastTime.remove(i);
    }
    return found;
  }
  public List<Persona> recuperarPersonaPorInicial(String ini) {
    List<Persona> listaIniciales = new ArrayList<Persona>();

    try {
      Query q = bbdd.query();
      q.constrain(Persona.class);
      q.descend("nombre").constrain(ini).startsWith(true);

      ObjectSet<Persona> res = q.execute();
      for (Persona p : res) {
        p.print();
        listaIniciales.add(p);
      }
    } finally {
      bbdd.close();
    }

    return listaIniciales;
  }
  public List<Persona> recuperarPersonaPorNombre(String n) {
    List<Persona> listaNombre = new ArrayList<Persona>();

    try {
      Query q = bbdd.query();
      q.constrain(Persona.class);
      q.descend("nombre").constrain(n);

      ObjectSet<Persona> res = q.execute();
      for (Persona p : res) {
        p.print();
        listaNombre.add(p);
      }
    } finally {
      bbdd.close();
    }

    return listaNombre;
  }
  public List<Persona> recuperarPersonaPorDni(String dni) {
    List<Persona> listaDni = new ArrayList<Persona>();

    try {
      Query q = bbdd.query();
      q.constrain(Persona.class);
      q.descend("dni").constrain(dni);

      ObjectSet<Persona> res = q.execute();
      for (Persona p : res) {
        p.print();
        listaDni.add(p);
      }
    } finally {
      bbdd.close();
    }

    return listaDni;
  }
  public List<Persona> recuperarPersonaPorEdad(int menor, int mayor) {
    List<Persona> listaEdad = new ArrayList<Persona>();

    try {
      Query q = bbdd.query();
      q.constrain(Persona.class);
      q.descend("edad").constrain(menor).greater();
      q.descend("edad").constrain(mayor).smaller();

      ObjectSet<Persona> res = q.execute();
      for (Persona p : res) {
        p.print();
        listaEdad.add(p);
      }
    } finally {
      bbdd.close();
    }

    return listaEdad;
  }
Esempio n. 20
0
  /**
   * Realiza pesquisa de objetos com base em vários valores de um atributo específico (disjunção OR)
   * e ordenada pelo outro atributo informado.
   *
   * @param classe tipo do objeto pesquisado
   * @param nomeAtributoFiltro nome do atributo utilizado para filtrar a pesquisa
   * @param valoresAtributoFiltro conjunto de valores do atributo utilizados para filtrar a pesquisa
   * @param nomeAtributoOrdenacao o nome do atributo que será utilizado para ordenar a pesquisa
   * @param tipoOrdenacao o tipo de ordenação desejada ('1 - crescente' e '2 - decrescente')
   * @return a lista ordenada de objetos que correspondem aos valores do atributo utilizado para
   *     filtrar a pesquisa @
   */
  public List pesquisarOrdenado(
      Class classe,
      String nomeAtributoFiltro,
      List valoresAtributoFiltro,
      String nomeAtributoOrdenacao,
      int tipoOrdenacao) {

    // Configura os filtros/critérios de pesquisa:
    Query query = bd.query();
    query.constrain(classe);
    Constraint constr = query.descend(nomeAtributoFiltro).constrain(valoresAtributoFiltro.get(0));
    for (int i = 1; i < valoresAtributoFiltro.size(); i++) {
      constr = constr.or(query.descend(nomeAtributoFiltro).constrain(valoresAtributoFiltro.get(i)));
    }

    // Configura a ordenação do resultado da pesquisa:
    configurarOrdenacao(query, nomeAtributoOrdenacao, tipoOrdenacao);

    // Executa a pesquisa e retorna o resultado:
    return efetivarPesquisar(query);
  }
Esempio n. 21
0
  /**
   * Realiza pesquisa de objetos com base em vários atributos e seus respectivos valores (conjunção
   * ou disjunção) e ordenada pelo outro atributo informado.
   *
   * @param classe tipo do objeto pesquisado
   * @param nomesAtributosFiltro conjunto de atributos utilizados para filtrar a pesquisa
   * @param valoresAtributosFiltro conjunto de valores dos atributos utilizados para filtrar a
   *     pesquisa
   * @param juncao o tipo de junção desejada entre os filtros ('1 - and' e '2 - or')
   * @param nomeAtributoOrdenacao o nome do atributo que será utilizado para ordenar a pesquisa
   * @param tipoOrdenacao o tipo de ordenação desejada ('1 - crescente' e '2 - decrescente')
   * @return a lista ordenada de objetos que correspondem aos valores dos atributos utilizados para
   *     filtrar a pesquisa @
   */
  public List pesquisarOrdenado(
      Class classe,
      List<String> nomesAtributosFiltro,
      List valoresAtributosFiltro,
      int juncao,
      String nomeAtributoOrdenacao,
      int tipoOrdenacao) {

    // Configura os filtros/critérios de pesquisa:
    Query query = bd.query();
    query.constrain(classe);
    Constraint constr =
        query.descend(nomesAtributosFiltro.get(0)).constrain(valoresAtributosFiltro.get(0));
    if (juncao == JUNCAO_AND) {
      for (int i = 1; i < valoresAtributosFiltro.size(); i++) {
        constr =
            constr.and(
                query
                    .descend(nomesAtributosFiltro.get(i))
                    .constrain(valoresAtributosFiltro.get(i)));
      }
    } else if (juncao == JUNCAO_OR) {
      for (int i = 1; i < valoresAtributosFiltro.size(); i++) {
        constr =
            constr.or(
                query
                    .descend(nomesAtributosFiltro.get(i))
                    .constrain(valoresAtributosFiltro.get(i)));
      }
    } else {
      throw new RuntimeException(
          "[pesquisar] Os tipos validos de junção são '1 - AND' e '2 - OR'.");
    }

    // Configura a ordenação do resultado da pesquisa:
    configurarOrdenacao(query, nomeAtributoOrdenacao, tipoOrdenacao);

    // Executa a pesquisa e retorna o resultado:
    return efetivarPesquisar(query);
  }
Esempio n. 22
0
  public void test() {

    Test.store(new Parent1(new Child1()));

    ObjectContainer container = Test.reOpen();
    container
        .ext()
        .configure()
        .addAlias(new TypeAlias("com.db4o.test.aliases.Parent1", "com.db4o.test.aliases.Parent2"));
    container
        .ext()
        .configure()
        .addAlias(new TypeAlias("com.db4o.test.aliases.Child1", "com.db4o.test.aliases.Child2"));

    ObjectSet os = container.query(Parent2.class);

    Test.ensure(os.size() > 0);

    Parent2 p2 = (Parent2) os.next();

    Test.ensure(p2.child != null);
  }
  public static boolean checkRegIdUsed(final String idGenerated) {

    // openDb4o();
    List<RegisterContextRequest> results;
    // final String updateRegId = rcrNew.getRegistrationId();
    results =
        db.query(
            new Predicate<RegisterContextRequest>() {
              public boolean match(RegisterContextRequest req) {
                String storedRegID = req.getRegistrationId();
                if (storedRegID.equals(idGenerated)) {
                  return true;
                }
                return false;
              }
            });

    if (results.size() > 0) {
      // closeDb4o();
      return true;
    }
    // closeDb4o();
    return false;
  }
Esempio n. 24
0
 private static void referentialIntegrity() {
   ObjectContainer container = Db4oEmbedded.openFile(DATABASE_FILE);
   // #example: Referential integrity
   final EventRegistry events = EventRegistryFactory.forObjectContainer(container);
   events
       .deleting()
       .addListener(
           new EventListener4<CancellableObjectEventArgs>() {
             @Override
             public void onEvent(
                 Event4<CancellableObjectEventArgs> events, CancellableObjectEventArgs eventArgs) {
               final Object toDelete = eventArgs.object();
               if (toDelete instanceof Pilot) {
                 final ObjectContainer container = eventArgs.objectContainer();
                 final ObjectSet<Car> cars =
                     container.query(
                         new Predicate<Car>() {
                           @Override
                           public boolean match(Car car) {
                             return car.getPilot() == toDelete;
                           }
                         });
                 if (cars.size() > 0) {
                   eventArgs.cancel();
                 }
               }
             }
           });
   // #end example
   try {
     Pilot pilot = container.query(Pilot.class).get(0);
     container.delete(pilot);
   } finally {
     container.close();
   }
 }
 public <C> List<C> getAllObjects(Class<C> componentType) {
   return db.query(componentType);
 }
Esempio n. 26
0
 public <T> List<? extends T> filtrar(
     Class<? extends T> classe, Predicate<T> filtro, Comparator<T> comparador) {
   return bd.query(filtro, comparador);
 }
 public static long[] allActivatableElementIds(ObjectContainer db) {
   Query q = db.query();
   q.constrain(ActivatableElement.class);
   ObjectSet<Object> objectSet = q.execute();
   return objectSet.ext().getIDs();
 }
  public static List<RegisterContextRequest> getRegByEntityID(
      final EntityId reqEntityId, final ArrayList<String> discAttrList) {

    List<RegisterContextRequest> results;

    String reqEId = reqEntityId.getId();

    if (reqEId.contentEquals(".*") && reqEntityId.isIsPattern()) {
      System.out.println("\".*\" specified");
      return getRegByEntityType(reqEntityId.getType());
    }

    System.out.println("\".*\" NOT specified");

    results =
        db.query(
            new Predicate<RegisterContextRequest>() {
              public boolean match(RegisterContextRequest req) {

                final int contRegListSize = req.getContextRegistration().size();

                for (int i = 0; i < contRegListSize; i++) {

                  final int reqEIdListSize =
                      req.getContextRegistration().get(i).getEntityId().size();

                  for (int j = 0; j < reqEIdListSize; j++) {

                    String storedId =
                        req.getContextRegistration().get(i).getEntityId().get(j).getId();

                    String storedIdType =
                        req.getContextRegistration().get(i).getEntityId().get(j).getType();

                    //                        String reqEId = reqEntityId.getId();
                    boolean reqIsPattern; // = false;
                    String reqIdType = "";

                    try {
                      if (reqEntityId.getType() != null) {
                        reqIdType = reqEntityId.getType();
                      }
                    } catch (NullPointerException npe) {
                      System.out.println("'type' field missing in request");
                    }
                    if (!reqIdType.isEmpty()) {

                      if (!reqIdType.equals(storedIdType)) {
                        continue;
                      }
                    }

                    try {
                      reqIsPattern = reqEntityId.isIsPattern();
                    } catch (NullPointerException npe) {
                      System.out.println("'isPattern' field missing in request");
                      reqIsPattern = false;
                    }

                    List<ContextRegistrationAttribute> contRegAttrlist =
                        req.getContextRegistration().get(i).getContextRegistrationAttribute();

                    boolean attrMatch = checkAttrMatch(contRegAttrlist, discAttrList);

                    if (reqIsPattern) {
                      if (reqEId.contains("*")) {
                        if (reqEId.startsWith("*")) {
                          String[] suffix = reqEId.split("\\*");
                          //                                       System.out.println("ends with:
                          // "+suffix[1]);
                          //                                       System.out.println("stored:
                          // "+storedId);
                          if ((storedId.endsWith(suffix[1]) && reqIdType.isEmpty())
                              || (storedId.endsWith(suffix[1])
                                  && storedIdType.equals(reqEntityId.getType()))) {
                            System.out.println("'isPattern'");
                            return true;
                          }
                        } else if (reqEId.endsWith(".*")) {
                          String[] suffix = reqEId.split("\\.*");
                          // System.out.println(suffix[0]);
                          if ((storedId.startsWith(suffix[0]) && reqIdType.isEmpty())
                              || (storedId.startsWith(suffix[0])
                                  && storedIdType.equals(reqEntityId.getType()))) {
                            return true;
                          }
                        }
                      }
                    } else {
                      if (reqIdType.isEmpty() && storedId.equals(reqEntityId.getId())) {
                        return true;
                      } else if (storedIdType.equals(reqEntityId.getType())
                          && storedId.equals(reqEntityId.getId())) {
                        return true;
                      }
                    } // if not regIsPattern
                  }
                } // loop until true or end
                return false;
              }
            });
    return results;
  }
  public static List<RegisterContextRequest> getAssociations(
      final EntityId eID, final String scopeValueType, final ArrayList<String> discAttrList) {

    List<RegisterContextRequest> results;

    results =
        db.query(
            new Predicate<RegisterContextRequest>() {
              public boolean match(RegisterContextRequest req) {

                final int contRegListSize = req.getContextRegistration().size();
                // System.out.println("contRegListSize: " + contRegListSize);
                for (int i = 0; i < contRegListSize; i++) {

                  final int contMetadataListSize =
                      req.getContextRegistration().get(i).getContextMetadata().size();
                  // System.out.println("entityidListSize: " + entityIdListSize);

                  if (contMetadataListSize < 1) {
                    return false;
                  }

                  for (int j = 0; j < contMetadataListSize; j++) {

                    String scopeValueEId = "";
                    ArrayList<String> scopeValueAttr = new ArrayList<>();
                    Value association =
                        (Value)
                            req.getContextRegistration()
                                .get(i)
                                .getContextMetadata()
                                .get(j)
                                .getValue();
                    int attrListSize = association.getAttributeAssociation().size();

                    // check if operation scope is "Association"
                    String scopeField =
                        req.getContextRegistration().get(i).getContextMetadata().get(j).getType();

                    if (scopeField.equalsIgnoreCase("Association")) {

                      if (scopeValueType.equalsIgnoreCase("SOURCES")) {

                        scopeValueEId =
                            association./*getEntityAssociation().*/ getTargetEntityId().getId();
                        //                                System.out.println("target eid is: " +
                        // scopeValueEId);
                        for (int k = 0; k < attrListSize; k++) {
                          String scopeValueAttrString =
                              association.getAttributeAssociation().get(k).getTargetAttribute();
                          scopeValueAttr.add(scopeValueAttrString);
                        }

                      } else if (scopeValueType.equalsIgnoreCase("TARGETS")) {

                        scopeValueEId =
                            association./*getEntityAssociation().*/ getSourceEntityId().getId();
                        //                                System.out.println("source eid is: " +
                        // scopeValueEId);
                        for (int k = 0; k < attrListSize; k++) {
                          String scopeValueAttrString =
                              association.getAttributeAssociation().get(k).getSourceAttribute();

                          scopeValueAttr.add(scopeValueAttrString);
                        }
                      }
                      // System.out.println("eid is: "+eID.getId());
                      // System.out.println("scope eid is: "+scopeValueEId);
                      if (scopeValueEId.equalsIgnoreCase(eID.getId())) {
                        //                                  System.out.println("eid is:
                        // "+eID.getId());
                        // int scopeValueAttrSize = scopeValueAttr.size();
                        int discAttrListSize = discAttrList.size();
                        if (discAttrListSize > 0) {
                          for (int m = 0; m < discAttrListSize; m++) {

                            if (scopeValueAttr.contains(discAttrList.get(m))) {
                              return true;
                            }
                          }

                        } else {
                          return true; // no attributes in request
                        }
                      } else {
                        return false;
                      }
                    }
                  }
                }
                return false;
              }
            });

    return results;
  }
  public Object removeKeyBefore(
      final long now,
      long dontCareAfterMillis,
      ObjectContainer container,
      int maxCount,
      PersistentCooldownQueue altQueue) {
    // Will be called repeatedly until no more keys are returned, so it doesn't
    // matter very much if they're not in order.

    // This query returns bogus results (cooldown items with times in the future).
    //		ObjectSet results = container.query(new Predicate() {
    //			public boolean match(PersistentCooldownQueueItem persistentCooldownQueueItem) {
    //				if(persistentCooldownQueueItem.time >= now) return false;
    //				if(persistentCooldownQueueItem.parent != PersistentCooldownQueue.this) return false;
    //				return true;
    //			}
    //		});

    ArrayList<Key> v = null;
    if (!itemsFromLastTime.isEmpty()) {
      if (v == null) v = new ArrayList<Key>(Math.min(maxCount, itemsFromLastTime.size()));
      Logger.normal(
          this,
          "Overflow handling in cooldown queue: reusing items from last time, now "
              + itemsFromLastTime.size());
      for (Iterator<PersistentCooldownQueueItem> it = itemsFromLastTime.iterator();
          it.hasNext() && v.size() < maxCount; ) {
        PersistentCooldownQueueItem i = it.next();
        container.activate(i, 1);
        if (i.parent != this && i.parent != altQueue) {
          container.deactivate(i, 1);
          continue;
        }
        if (i.time >= now) {
          container.deactivate(i, 1);
          if (v.isEmpty()) return i.time;
          return v.toArray(new Key[v.size()]);
        }

        container.activate(i.key, 5);
        if (i.client == null || !container.ext().isStored(i.client)) {
          Logger.normal(
              this,
              "Client has been removed but not the persistent cooldown queue item: time "
                  + i.time
                  + " for key "
                  + i.key);
        }
        if (i.key == null) {
          Logger.error(
              this,
              "Key is null on cooldown queue! i = "
                  + i
                  + " client="
                  + i.client
                  + " key as bytes = "
                  + i.keyAsBytes);
        } else {
          v.add(i.key.cloneKey());
          i.key.removeFrom(container);
        }
        i.delete(container);
        it.remove();
      }
    }
    if (v != null && v.size() == maxCount) return v.toArray(new Key[v.size()]);

    // Lets re-code it in SODA.
    long tStart = System.currentTimeMillis();
    Query query = container.query();
    query.constrain(PersistentCooldownQueueItem.class);
    // Don't constrain on parent.
    // parent index is humongous, so we get a huge memory spike, queries take ages.
    // Just check manually.
    query
        .descend("time")
        .orderAscending()
        .constrain(Long.valueOf(now + dontCareAfterMillis))
        .smaller();
    ObjectSet<PersistentCooldownQueueItem> results = query.execute();
    if (results.hasNext()) {
      long tEnd = System.currentTimeMillis();
      if (tEnd - tStart > 1000)
        Logger.error(this, "Query took " + (tEnd - tStart) + " for " + results.size());
      else if (logMINOR) Logger.minor(this, "Query took " + (tEnd - tStart));
      if (v == null) v = new ArrayList<Key>(Math.min(maxCount, results.size()));
      while (results.hasNext() && v.size() < maxCount) {
        PersistentCooldownQueueItem i = (PersistentCooldownQueueItem) results.next();
        if (i.parent != this && i.parent != altQueue) {
          continue;
        }
        if (i.time >= now) {
          if (v.isEmpty()) return i.time;
          break;
        }
        container.activate(i.key, 5);
        if (i.client == null || !container.ext().isStored(i.client)) {
          Logger.normal(
              this,
              "Client has been removed but not the persistent cooldown queue item: time "
                  + i.time
                  + " for key "
                  + i.key);
        }
        if (i.key == null) {
          Logger.error(
              this,
              "Key is null on cooldown queue! i = "
                  + i
                  + " client="
                  + i.client
                  + " key as bytes = "
                  + i.keyAsBytes);
        } else {
          v.add(i.key.cloneKey());
          i.key.removeFrom(container);
        }
        i.delete(container);
      }
      if (!v.isEmpty()) {
        while (results.hasNext() && itemsFromLastTime.size() < KEEP_ITEMS_FROM_LAST_TIME) {
          PersistentCooldownQueueItem i = (PersistentCooldownQueueItem) results.next();
          container.deactivate(i, 1);
          itemsFromLastTime.add(i);
        }
        Logger.normal(
            this,
            "Overflow handling in cooldown queue: added items, items from last time now "
                + itemsFromLastTime.size());
        return v.toArray(new Key[v.size()]);
      }
    } else {
      long tEnd = System.currentTimeMillis();
      if (tEnd - tStart > 1000) Logger.error(this, "Query took " + (tEnd - tStart));
      else if (logMINOR) Logger.minor(this, "Query took " + (tEnd - tStart));
      return null;
    }
    return null;
  }