예제 #1
0
  @Override
  public void requestWasRemoved(ObjectContainer container, ClientContext context) {
    // if request is still running, send a GetFailed with code=cancelled
    if (!finished) {
      synchronized (this) {
        succeeded = false;
        finished = true;
        FetchException cancelled = new FetchException(FetchException.CANCELLED);
        getFailedMessage = new GetFailedMessage(cancelled, identifier, global);
      }
      trySendDataFoundOrGetFailed(null, container);
    }
    // notify client that request was removed
    FCPMessage msg = new PersistentRequestRemovedMessage(getIdentifier(), global);
    if (persistenceType != PERSIST_CONNECTION) {
      if (persistenceType == PERSIST_FOREVER) container.activate(client, 1);
      client.queueClientRequestMessage(msg, 0, container);
    }

    freeData(container);

    if (persistenceType == PERSIST_FOREVER) {
      container.activate(fctx, 1);
      if (fctx.allowedMIMETypes != null) {
        container.activate(fctx.allowedMIMETypes, 5);
        container.delete(fctx.allowedMIMETypes);
      }
      fctx.removeFrom(container);
      getter.removeFrom(container, context);
      if (targetFile != null) container.delete(targetFile);
      if (tempFile != null) container.delete(tempFile);
      if (getFailedMessage != null) {
        container.activate(getFailedMessage, 5);
        getFailedMessage.removeFrom(container);
      }
      if (postFetchProtocolErrorMessage != null) {
        container.activate(postFetchProtocolErrorMessage, 5);
        postFetchProtocolErrorMessage.removeFrom(container);
      }
      if (allDataPending != null) {
        container.activate(allDataPending, 5);
        allDataPending.removeFrom(container);
      }
      if (progressPending != null) {
        container.activate(progressPending, 5);
        progressPending.removeFrom(container);
      }
    }
    super.requestWasRemoved(container, context);
  }
  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;
  }
 /**
  * Terminate a subsegment. Called by the segment, which will have already removed the subsegment
  * from the list. Will delete the object from the database if persistent.
  */
 public void kill(
     ObjectContainer container,
     ClientContext context,
     boolean dontDeactivateSeg,
     boolean cancelledAlready) {
   if (persistent) {
     container.activate(segment, 1);
     container.activate(blockNums, 1);
   }
   if (logMINOR) Logger.minor(this, "Killing " + this);
   // Do unregister() first so can get and unregister each key and avoid a memory leak
   unregister(container, context, getPriorityClass(container));
   Integer[] oldNums = null;
   synchronized (segment) {
     if (cancelledAlready) {
       if (!cancelled) {
         Logger.error(this, "Should be cancelled already! " + this, new Exception("error"));
         cancelled = true;
       }
       if (!blockNums.isEmpty())
         Logger.error(
             this, "Block nums not empty! on " + this + " : " + blockNums, new Exception("error"));
     } else {
       if (cancelled) return;
       cancelled = true;
     }
     if (persistent) oldNums = blockNums.toArray(new Integer[blockNums.size()]);
     blockNums.clear();
   }
   if (persistent && oldNums != null && oldNums.length > 0) {
     for (Integer i : oldNums) container.delete(i);
   }
   if (persistent) removeFrom(container, context, dontDeactivateSeg);
 }
예제 #4
0
 public void test() {
   ObjectContainer oc = Test.objectContainer();
   ObjectSet objectSet = oc.queryByExample(new CallbackCanDelete("p1", null));
   CallbackCanDelete ccd = (CallbackCanDelete) objectSet.next();
   oc.deactivate(ccd, Integer.MAX_VALUE);
   oc.delete(ccd);
 }
예제 #5
0
 public void removeFrom(ObjectContainer container) {
   container.activate(data, 1);
   data.removeFrom(container);
   container.activate(targetURI, 5);
   targetURI.removeFrom(container);
   container.delete(this);
 }
 @Override
 public void executeInObjectContainer(ObjectContainer objectContainer) {
   ObjectSet<Training> trainings = objectContainer.query(Training.class);
   while (trainings.hasNext()) {
     objectContainer.delete(trainings.next());
   }
 }
예제 #7
0
 public void realRemoveFrom(ObjectContainer container) {
   synchronized (this) {
     if (reallyRemoved) Logger.error(this, "Calling realRemoveFrom() twice on " + this);
     reallyRemoved = true;
   }
   bucket.removeFrom(container);
   container.delete(this);
 }
 @Override
 public boolean hasValidKeys(
     KeysFetchingLocally keys, ObjectContainer container, ClientContext context) {
   if (persistent) {
     container.activate(this, 1);
     container.activate(blockNums, 1);
     container.activate(segment, 1);
   }
   boolean hasSet = false;
   boolean retval = false;
   synchronized (segment) {
     for (int i = 0; i < 10; i++) {
       Integer ret;
       int x;
       if (blockNums.isEmpty()) {
         break;
       }
       x = context.random.nextInt(blockNums.size());
       ret = blockNums.get(x);
       int block = ret;
       Key key = segment.getBlockNodeKey(block, container);
       if (key == null) {
         if (segment.isFinishing(container) || segment.isFinished(container)) return false;
         if (segment.haveBlock(block, container))
           Logger.error(
               this,
               "Already have block "
                   + ret
                   + " but was in blockNums on "
                   + this
                   + " in hasValidKeys");
         else
           Logger.error(
               this, "Key is null for block " + ret + " for " + this + " in hasValidKeys");
         blockNums.remove(x);
         if (persistent) {
           container.delete(ret);
           if (!hasSet) {
             hasSet = true;
             container.store(blockNums);
           }
         }
         continue;
       }
       if (keys.hasKey(key)) {
         continue;
       }
       retval = true;
       break;
     }
   }
   if (persistent) {
     container.deactivate(blockNums, 5);
     container.deactivate(segment, 1);
   }
   return retval;
 }
예제 #9
0
 public void freeData(ObjectContainer container, boolean persistForever) {
   if (data != null) {
     if (persistForever) container.activate(data, 1);
     data.free();
     if (persistForever) data.removeFrom(container);
     data = null;
   }
   if (persistForever) container.delete(this);
 }
 public void deleteTemplates() {
   openTemplateDb();
   ObjectSet<Request> objectList = dbTemplateContainer.queryByExample(null);
   while (objectList.hasNext()) {
     Request r = (Request) objectList.next();
     dbTemplateContainer.delete(r);
   }
   closeTemplateDb();
 }
 public void deleteRequests() {
   openRequestDb();
   Request req = new Request();
   ObjectSet<Request> objectList = dbRequestContainer.queryByExample(req);
   while (objectList.hasNext()) {
     Request r = (Request) objectList.next();
     dbRequestContainer.delete(r);
   }
   closeRequestDb();
 }
 public void removeFrom(
     ObjectContainer container, ClientContext context, boolean dontDeactivateSeg) {
   container.activate(segment, 1);
   container.activate(blockNums, 1);
   synchronized (segment) {
     if (!cancelled) {
       Logger.error(this, "Removing when not cancelled! on " + this, new Exception("error"));
       cancelled = true;
     }
     if (!blockNums.isEmpty()) {
       Logger.error(this, "Removing when blockNums not empty! on " + this, new Exception("error"));
       for (Integer i : blockNums) container.delete(i);
       blockNums.clear();
     }
   }
   container.delete(blockNums);
   container.delete(this);
   if (!dontDeactivateSeg) container.deactivate(segment, 1);
   // We do not need to call SendableGet as it has no internal data structures that need deleting.
 }
예제 #13
0
  public void test() {

    ObjectContainer con = Test.objectContainer();
    Test.deleteAllInstances(this);

    IsStored isStored = new IsStored();
    isStored.myString = "isStored";
    con.store(isStored);
    Test.ensure(con.ext().isStored(isStored));
    Test.ensure(Test.occurrences(this) == 1);
    con.delete(isStored);
    Test.ensure(!con.ext().isStored(isStored));
    Test.ensure(Test.occurrences(this) == 0);
    con.commit();
    if (con.ext().isStored(isStored)) {

      // this will fail in CS due to locally cached references
      if (!Test.clientServer) {
        Test.error();
      }
    }
    Test.ensure(Test.occurrences(this) == 0);
    con.store(isStored);
    Test.ensure(con.ext().isStored(isStored));
    Test.ensure(Test.occurrences(this) == 1);
    con.commit();
    Test.ensure(con.ext().isStored(isStored));
    Test.ensure(Test.occurrences(this) == 1);
    con.delete(isStored);
    Test.ensure(!con.ext().isStored(isStored));
    Test.ensure(Test.occurrences(this) == 0);
    con.commit();
    if (con.ext().isStored(isStored)) {

      // this will fail in CS due to locally cached references
      if (!Test.clientServer) {
        Test.error();
      }
    }
    Test.ensure(Test.occurrences(this) == 0);
  }
예제 #14
0
 /**
  * Apaga um objeto armazenado no banco de dados, após verificar que ele realmente está armazenado
  * (os atributos devem ter valores idênticos).
  *
  * @param objeto objeto que será apagado do banco de dados @
  */
 public void apagar(Object objeto) {
   if (objeto != null) {
     List resultado = bd.queryByExample(objeto);
     if (resultado.size() > 0) {
       bd.delete(objeto);
     } else {
       throw new RuntimeException("[apagar] Objeto não encontrado no banco de dados.");
     }
   } else {
     System.out.println("[apagar] Erro: objeto nulo.");
   }
 }
예제 #15
0
 @Override
 public KeyListener makeKeyListener(
     ObjectContainer container, ClientContext context, boolean onStartup) {
   if (persistent) {
     container.activate(key, 5);
     container.activate(parent, 1);
     container.activate(ctx, 1);
   }
   synchronized (this) {
     if (finished) return null;
     if (cancelled) return null;
   }
   if (key == null) {
     Logger.error(
         this,
         "Key is null - left over BSSF? on " + this + " in makeKeyListener()",
         new Exception("error"));
     if (persistent) container.delete(this);
     return null;
   }
   Key newKey = key.getNodeKey(true);
   if (parent == null) {
     Logger.error(
         this,
         "Parent is null on "
             + this
             + " persistent="
             + persistent
             + " key="
             + key
             + " ctx="
             + ctx);
     if (container != null)
       Logger.error(
           this,
           "Stored = "
               + container.ext().isStored(this)
               + " active = "
               + container.ext().isActive(this));
     return null;
   }
   short prio = parent.getPriorityClass();
   KeyListener ret = new SingleKeyListener(newKey, this, prio, persistent, realTimeFlag);
   if (persistent) {
     container.deactivate(key, 5);
     container.deactivate(parent, 1);
     container.deactivate(ctx, 1);
   }
   return ret;
 }
  public void onGotKey(Key key, KeyBlock block, ObjectContainer container, ClientContext context) {
    if (persistent) {
      container.activate(this, 1);
      container.activate(segment, 1);
      container.activate(blockNums, 1);
    }
    if (logMINOR) Logger.minor(this, "onGotKey(" + key + ")");
    // Find and remove block if it is on this subsegment. However it may have been
    // removed already.
    int blockNo;
    synchronized (segment) {
      for (int i = 0; i < blockNums.size(); i++) {
        Integer token = blockNums.get(i);
        int num = token;
        Key k = segment.getBlockNodeKey(num, container);
        if (k != null && k.equals(key)) {
          blockNums.remove(i);
          if (persistent) container.delete(token);
          break;
        }
      }
      blockNo = segment.getBlockNumber(key, container);
    }
    if (blockNo == -1) {
      Logger.minor(this, "No block found for key " + key + " on " + this);
      return;
    }
    Integer token = Integer.valueOf(blockNo);
    ClientCHK ckey = segment.getBlockKey(blockNo, container);
    ClientCHKBlock cb;
    try {
      cb = new ClientCHKBlock((CHKBlock) block, ckey);
    } catch (CHKVerifyException e) {
      onFailure(
          new FetchException(FetchException.BLOCK_DECODE_ERROR, e), token, container, context);
      return;
    }
    Bucket data = extract(cb, token, container, context);
    if (data == null) return;

    if (!cb.isMetadata()) {
      onSuccess(data, false, token, (token).intValue(), cb, container, context);
    } else {
      onFailure(
          new FetchException(FetchException.INVALID_METADATA, "Metadata where expected data"),
          token,
          container,
          context);
    }
  }
예제 #17
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());
   }
 }
예제 #18
0
 public void removeFrom(ObjectContainer container, ClientContext context) {
   if (logMINOR) Logger.minor(this, "removeFrom() on " + this);
   container.activate(uri, 5);
   uri.removeFrom(container);
   if (resultingURI != null) {
     container.activate(resultingURI, 5);
     resultingURI.removeFrom(container);
   }
   // cb, parent are responsible for removing themselves
   // ctx is passed in and unmodified - usually the ClientPutter removes it
   container.activate(errors, 5);
   errors.removeFrom(container);
   if (freeData && sourceData != null && container.ext().isStored(sourceData)) {
     Logger.error(this, "Data not removed!");
     container.activate(sourceData, 1);
     sourceData.removeFrom(container);
   }
   container.delete(this);
 }
 private void cleanBlockNums(ObjectContainer container) {
   synchronized (segment) {
     int initSize = blockNums.size();
     Integer prev = null;
     for (int i = 0; i < blockNums.size(); i++) {
       Integer x = blockNums.get(i);
       if (x == prev || x.equals(prev)) {
         blockNums.remove(i);
         i--;
         if (persistent) container.delete(x);
       } else prev = x;
     }
     if (blockNums.size() < initSize) {
       Logger.error(
           this,
           "Cleaned block number list duplicates: was " + initSize + " now " + blockNums.size());
     }
   }
 }
 public boolean removeBlockNum(
     int blockNum, ObjectContainer container, boolean callerActivatesAndSets) {
   if (logMINOR) Logger.minor(this, "Removing block " + blockNum + " from " + this);
   if (persistent && !callerActivatesAndSets) container.activate(blockNums, 2);
   boolean found = false;
   synchronized (segment) {
     for (int i = 0; i < blockNums.size(); i++) {
       Integer token = blockNums.get(i);
       int num = token;
       if (num == blockNum) {
         blockNums.remove(i);
         if (persistent) container.delete(token);
         if (logMINOR) Logger.minor(this, "Removed block " + blockNum + " from " + this);
         found = true;
         break;
       }
     }
   }
   if (persistent && !callerActivatesAndSets) {
     container.store(blockNums);
     container.deactivate(blockNums, 2);
   }
   return found;
 }
예제 #21
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();
   }
 }
예제 #22
0
    /** @sharpen.remove */
    public void test() throws IOException {

      boolean cached = USE_CACHE.value().booleanValue();
      boolean useLogFile = USE_LOGFILE.value().booleanValue();
      boolean writeTrash = WRITE_TRASH.value().booleanValue();

      if (cached && writeTrash) {
        System.err.println(
            "DISABLED CrashSimulatingTestCase: combination of write trash and cache");
        // The cache may touch more bytes than the ones we modified.
        // We should be safe even if we don't get this test to pass.
        return;
      }

      if (useLogFile && writeTrash) {
        System.err.println(
            "DISABLED CrashSimulatingTestCase: combination of write trash and use log file");

        // The log file is not a public API yet anyway.
        // It's only needed for the PointerBasedIdSystem
        // With the new BTreeIdSystem it's not likely to become important
        // so we can safely ignore the failing write trash case.
        return;
      }

      if (Platform4.needsLockFileThread()) {
        System.out.println(
            "CrashSimulatingTestCase is ignored on platforms with lock file thread.");
        return;
      }

      String path = Path4.combine(Path4.getTempPath(), "crashSimulate");
      String fileName = Path4.combine(path, "cs");

      File4.delete(fileName);
      File4.mkdirs(path);

      createFile(baseConfig(useLogFile), fileName);

      CrashSimulatingStorage crashSimulatingStorage =
          new CrashSimulatingStorage(new FileStorage(), fileName);
      Storage storage =
          cached ? (Storage) new CachingStorage(crashSimulatingStorage) : crashSimulatingStorage;

      Configuration recordConfig = baseConfig(useLogFile);
      recordConfig.storage(storage);

      ObjectContainer oc = Db4o.openFile(recordConfig, fileName);

      ObjectSet objectSet = oc.queryByExample(new CrashData(null, "three"));
      oc.delete(objectSet.next());

      oc.store(new CrashData(null, "four"));
      oc.store(new CrashData(null, "five"));
      oc.store(new CrashData(null, "six"));
      oc.store(new CrashData(null, "seven"));
      oc.store(new CrashData(null, "eight"));
      oc.store(new CrashData(null, "nine"));
      oc.store(new CrashData(null, "10"));
      oc.store(new CrashData(null, "11"));
      oc.store(new CrashData(null, "12"));
      oc.store(new CrashData(null, "13"));
      oc.store(new CrashData(null, "14"));

      oc.commit();

      Query q = oc.query();
      q.constrain(CrashData.class);
      objectSet = q.execute();
      while (objectSet.hasNext()) {
        CrashData cData = (CrashData) objectSet.next();
        if (!(cData._name.equals("10") || cData._name.equals("13"))) {
          oc.delete(cData);
        }
      }

      oc.commit();

      oc.close();

      int count = crashSimulatingStorage._batch.writeVersions(fileName, writeTrash);

      checkFiles(useLogFile, fileName, "R", crashSimulatingStorage._batch.numSyncs());
      checkFiles(useLogFile, fileName, "W", count);
      if (VERBOSE) {
        System.out.println("Total versions: " + count);
      }
    }
예제 #23
0
 public void objectOnDelete(ObjectContainer container) {
   container.delete(parent);
 }
 public void removeFrom(ObjectContainer container) {
   container.delete(this);
 }
예제 #25
0
  void finishRegister(
      final SendableGet[] getters,
      boolean persistent,
      ObjectContainer container,
      final boolean anyValid,
      final DatastoreCheckerItem reg) {
    if (logMINOR)
      Logger.minor(
          this,
          "finishRegister for "
              + getters
              + " anyValid="
              + anyValid
              + " reg="
              + reg
              + " persistent="
              + persistent);
    if (isInsertScheduler) {
      IllegalStateException e = new IllegalStateException("finishRegister on an insert scheduler");
      for (int i = 0; i < getters.length; i++) {
        if (persistent) container.activate(getters[i], 1);
        getters[i].internalError(e, this, container, clientContext, persistent);
        if (persistent) container.deactivate(getters[i], 1);
      }
      throw e;
    }
    if (persistent) {
      // Add to the persistent registration queue
      if (!databaseExecutor.onThread()) {
        throw new IllegalStateException("Not on database thread!");
      }
      if (persistent) container.activate(getters, 1);
      if (logMINOR) Logger.minor(this, "finishRegister() for " + getters);
      if (anyValid) {
        boolean wereAnyValid = false;
        for (int i = 0; i < getters.length; i++) {
          SendableGet getter = getters[i];
          container.activate(getter, 1);
          // Just check isCancelled, we have already checked the cooldown.
          if (!(getter.isCancelled(container))) {
            wereAnyValid = true;
            if (!getter.preRegister(container, clientContext, true)) {
              schedCore.innerRegister(getter, random, container, clientContext, getters);
            }
          } else getter.preRegister(container, clientContext, false);
        }
        if (!wereAnyValid) {
          Logger.normal(this, "No requests valid: " + getters);
        }
      } else {
        Logger.normal(this, "No valid requests passed in: " + getters);
      }
      if (reg != null) container.delete(reg);
      queueFillRequestStarterQueue(true);
    } else {
      // Register immediately.
      for (int i = 0; i < getters.length; i++) {

        if ((!anyValid) || getters[i].isCancelled(null)) {
          getters[i].preRegister(container, clientContext, false);
          continue;
        } else {
          if (getters[i].preRegister(container, clientContext, true)) continue;
        }
        if (!getters[i].isCancelled(null))
          schedTransient.innerRegister(getters[i], random, null, clientContext, getters);
      }
      starter.wakeUp();
    }
  }
예제 #26
0
 @Override
 public void removeFrom(ObjectContainer container) {
   underlying.removeFrom(container);
   container.delete(this);
 }
예제 #27
0
 public void removeFrom(ObjectContainer container) {
   // All members are inline (arrays, ints etc), treated as values, so we can happily just call
   // delete(this).
   container.delete(this);
 }
  // MODIFICATO
  // delete teh contReg inside the RegContReq that match the
  // with one of the entityId inside teh entityIdList
  public static void deleteRegistrationEntID(final List<String> entityIdList) {

    // for each entId
    for (String entId : entityIdList) {

      List<RegisterContextRequest> results;

      final String updateEntId = entId;

      // results contains the RegContReq that contains in their list at
      // least one contReg that have an entId that match with updateEntId
      results =
          db.query(
              new Predicate<RegisterContextRequest>() {
                public boolean match(RegisterContextRequest req) {

                  // check in the contRegList if there is one
                  // with the entId that match the updateEntId

                  List<ContextRegistration> contRegList = req.getContextRegistration();

                  // for each contReg
                  for (ContextRegistration cr : contRegList) {

                    // for each entId in contReg
                    for (EntityId entId : cr.getEntityId()) {

                      if (entId.getId().contentEquals(updateEntId)) return true;
                    }
                  }

                  return false;
                }
              });

      if (results.size() > 0) {

        // for each RegContReq find out which
        // contReg hash the entityId that match
        // with updateEntId and remove it
        // store a backup copy of that
        // RegContReq because it must be delete
        // before writing the new one
        for (RegisterContextRequest regContReq : results) {

          // check in the contRegList if there is one
          // with the entId that match the updateEntId

          List<ContextRegistration> contRegList = regContReq.getContextRegistration();

          // for each contReg
          for (ContextRegistration cr : contRegList) {

            // for each entId in contReg
            for (EntityId id : cr.getEntityId()) {

              if (id.getId().contentEquals(updateEntId)) {

                // delete the RegisterContextReq with matching entId
                RegisterContextRequest found = regContReq;
                System.out.println("Deleting registration");
                db.delete(found);
                db.commit();

                // delete the contReg, inside the RegContReq, that have a
                // matching entId
                regContReq.getContextRegistration().remove(cr);

                // if the RegisterContextRequest is not empty
                // it must be re-store the contRegs inside
                // the RegisterContextRequest that haven't a match
                // with updateEntId
                if (!regContReq.getContextRegistration().isEmpty()) {

                  storeRegistration(regContReq);
                }
              }
            }

            if (contRegList.isEmpty()) {
              break;
            }
          }
        }
      }
    }
  }