protected ClientKeyBlock encode(
     ObjectContainer container, ClientContext context, boolean calledByCB) throws InsertException {
   if (persistent) {
     container.activate(sourceData, 1);
     container.activate(cb, 1);
   }
   ClientKeyBlock block;
   boolean shouldSend;
   synchronized (this) {
     if (finished) return null;
     if (sourceData == null) {
       Logger.error(this, "Source data is null on " + this + " but not finished!");
       return null;
     }
     block = innerEncode(context.random, container);
     shouldSend = (resultingURI == null);
     resultingURI = block.getClientKey().getURI();
   }
   if (logMINOR)
     Logger.minor(
         this,
         "Encoded "
             + resultingURI
             + " for "
             + this
             + " shouldSend="
             + shouldSend
             + " dontSendEncoded="
             + dontSendEncoded);
   if (shouldSend && !dontSendEncoded) cb.onEncode(block.getClientKey(), this, container, context);
   if (shouldSend && persistent) container.store(this);
   if (persistent && !calledByCB) container.deactivate(cb, 1);
   return block;
 }
 public void schedule(ObjectContainer container, ClientContext context) throws InsertException {
   synchronized (this) {
     if (finished) {
       if (logMINOR) Logger.minor(this, "Finished already: " + this);
       return;
     }
   }
   if (getCHKOnly) {
     boolean deactivateCB = false;
     if (persistent) {
       deactivateCB = !container.ext().isActive(cb);
       if (deactivateCB) container.activate(cb, 1);
       container.activate(parent, 1);
     }
     ClientKeyBlock block = encode(container, context, true);
     cb.onEncode(block.getClientKey(), this, container, context);
     parent.completedBlock(false, container, context);
     cb.onSuccess(this, container, context);
     finished = true;
     if (persistent) {
       container.store(this);
       if (deactivateCB) container.deactivate(cb, 1);
     }
   } else {
     getScheduler(context).registerInsert(this, persistent, true, container);
   }
 }
Пример #3
0
 @Override
 protected FCPMessage persistentTagMessage(ObjectContainer container) {
   if (persistenceType == PERSIST_FOREVER) {
     container.activate(uri, 5);
     container.activate(fctx, 1);
     container.activate(client, 1);
     container.activate(targetFile, 5);
     container.activate(tempFile, 5);
   }
   return new PersistentGet(
       identifier,
       uri,
       verbosity,
       priorityClass,
       returnType,
       persistenceType,
       targetFile,
       tempFile,
       clientToken,
       client.isGlobalQueue,
       started,
       fctx.maxNonSplitfileRetries,
       binaryBlob,
       fctx.maxOutputLength);
 }
 protected ClientKeyBlock innerEncode(RandomSource random, ObjectContainer container)
     throws InsertException {
   if (persistent) {
     container.activate(uri, 1);
     container.activate(sourceData, 1);
   }
   try {
     return innerEncode(
         random,
         uri,
         sourceData,
         isMetadata,
         compressionCodec,
         sourceLength,
         ctx.compressorDescriptor);
   } catch (KeyEncodeException e) {
     Logger.error(SingleBlockInserter.class, "Caught " + e, e);
     throw new InsertException(InsertException.INTERNAL_ERROR, e, null);
   } catch (MalformedURLException e) {
     throw new InsertException(InsertException.INVALID_URI, e, null);
   } catch (IOException e) {
     Logger.error(SingleBlockInserter.class, "Caught " + e + " encoding data " + sourceData, e);
     throw new InsertException(InsertException.BUCKET_ERROR, e, null);
   } catch (InvalidCompressionCodecException e) {
     throw new InsertException(InsertException.INTERNAL_ERROR, e, null);
   }
 }
Пример #5
0
  private void trySendDataFoundOrGetFailed(
      FCPConnectionOutputHandler handler, ObjectContainer container) {
    FCPMessage msg;

    // Don't need to lock. succeeded is only ever set, never unset.
    // and succeeded and getFailedMessage are both atomic.
    if (succeeded) {
      msg = new DataFoundMessage(foundDataLength, foundDataMimeType, identifier, global);
    } else {
      msg = getFailedMessage;
      if (persistenceType == PERSIST_FOREVER) container.activate(msg, 5);
    }

    if (handler == null && persistenceType == PERSIST_CONNECTION)
      handler = origHandler.outputHandler;
    if (handler != null) handler.queue(msg);
    else client.queueClientRequestMessage(msg, 0, container);
    if (postFetchProtocolErrorMessage != null) {
      if (persistenceType == PERSIST_FOREVER) container.activate(postFetchProtocolErrorMessage, 5);
      if (handler != null) handler.queue(postFetchProtocolErrorMessage);
      else {
        if (persistenceType == PERSIST_FOREVER) container.activate(client, 1);
        client.queueClientRequestMessage(postFetchProtocolErrorMessage, 0, container);
      }
    }
  }
Пример #6
0
  @Override
  public void sendPendingMessages(
      FCPConnectionOutputHandler handler,
      boolean includePersistentRequest,
      boolean includeData,
      boolean onlyData,
      ObjectContainer container) {
    if (persistenceType == ClientRequest.PERSIST_CONNECTION) {
      Logger.error(this, "WTF? persistenceType=" + persistenceType, new Exception("error"));
      return;
    }
    if (!onlyData) {
      if (includePersistentRequest) {
        FCPMessage msg = persistentTagMessage(container);
        handler.queue(msg);
      }
      if (progressPending != null) {
        if (persistenceType == PERSIST_FOREVER) container.activate(progressPending, 5);
        handler.queue(progressPending);
      }
      if (sentToNetwork) handler.queue(new SendingToNetworkMessage(identifier, global));
      if (finished) trySendDataFoundOrGetFailed(handler, container);
    }

    if (onlyData && allDataPending == null) {
      Logger.error(this, "No data pending !");
    }

    if (includeData && (allDataPending != null)) {
      if (persistenceType == PERSIST_FOREVER) container.activate(allDataPending, 5);
      handler.queue(allDataPending);
    }
  }
Пример #7
0
 public void removeFrom(ObjectContainer container) {
   container.activate(data, 1);
   data.removeFrom(container);
   container.activate(targetURI, 5);
   targetURI.removeFrom(container);
   container.delete(this);
 }
  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;
  }
 @Override
 public ClientKey getKey(Object token, ObjectContainer container) {
   if (persistent) {
     container.activate(this, 1);
     container.activate(segment, 1);
   }
   synchronized (segment) {
     if (cancelled) {
       if (logMINOR)
         Logger.minor(this, "Segment is finishing when getting key " + token + " on " + this);
       return null;
     }
     ClientKey key = segment.getBlockKey(((MySendableRequestItem) token).x, container);
     if (key == null) {
       if (segment.isFinished(container)) {
         Logger.error(this, "Segment finished but didn't tell us! " + this);
       } else if (segment.isFinishing(container)) {
         Logger.error(this, "Segment finishing but didn't tell us! " + this);
       } else {
         Logger.error(
             this,
             "Segment not finishing yet still returns null for getKey()!: "
                 + token
                 + " for "
                 + this,
             new Exception("debug"));
       }
     }
     return key;
   }
 }
Пример #10
0
 @Override
 public void requeueAfterCooldown(
     Key key, long time, ObjectContainer container, ClientContext context) {
   MyCooldownTrackerItem tracker = makeCooldownTrackerItem(container, context);
   if (tracker.cooldownWakeupTime > time) {
     if (logMINOR) Logger.minor(this, "Not requeueing as deadline has not passed yet");
     return;
   }
   if (isEmpty(container)) {
     if (logMINOR) Logger.minor(this, "Not requeueing as cancelled or finished");
     return;
   }
   if (persistent) container.activate(this.key, 5);
   if (!(key.equals(this.key.getNodeKey(false)))) {
     Logger.error(
         this,
         "Got requeueAfterCooldown for wrong key: "
             + key
             + " but mine is "
             + this.key.getNodeKey(false)
             + " for "
             + this.key);
     return;
   }
   if (logMINOR) Logger.minor(this, "Requeueing after cooldown " + key + " for " + this);
   reschedule(container, context);
   if (persistent) container.deactivate(this.key, 5);
 }
 @Override
 public void executeInObjectContainer(ObjectContainer objectContainer) {
   ObjectSet<Training> trainings = objectContainer.query(Training.class);
   while (trainings.hasNext()) {
     objectContainer.delete(trainings.next());
   }
 }
  public static synchronized boolean StopTransaction() {
    if (Opened && !isCanceled()) {
      try {
        session.store(transaction);
        session.commit();

      } catch (Exception e) {
        CancelTransaction("Finishing transaction error", "error in storing transaction");
        Opened = false;
        return false;
      }

      for (Command c : transaction.getCommands())
        if (c.getTargetLayer().toString().equals(CommandTargetLayer.VIEW.toString()))
          ((ModelMusts) c.getSource())
              .notifyObjectListener(
                  c.getSource(),
                  c.getType(),
                  c.getoldObjectID(),
                  c.getoldObject(),
                  c.getObject(),
                  c.getoldNeiborID(),
                  c.getOldNeibor(),
                  c.getNeibor());

      Opened = false;
      return true;

    } else Opened = false;
    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);
 }
  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;
  }
Пример #15
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);
 }
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String oidStr = request.getParameter("oid");
   if (oidStr == null || oidStr.trim().isEmpty()) throw new ServletException("unexpected request");
   Long oid = Long.valueOf(request.getParameter("oid").trim());
   // accessDb4o
   ObjectContainer db =
       Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), ActionManager.DB4OFILENAME);
   try {
     TIISubmission sub = db.ext().getByID(oid);
     db.activate(sub, 10);
     if (sub == null)
       response.sendRedirect(ActionManager.getErrorCallbackURL(9999, "oid not found"));
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.write(
         "<HTML>"
             + "<HEAD>"
             + "<TITLE>Dummy Originality Report</TITLE>"
             + "</HEAD>"
             + "<BODY>"
             + "<h2>Originality Report of OID: "
             + oid
             + "</h2>"
             + "<p>Score: "
             + sub.getReportScore()
             + "</p>"
             + "</BODY>"
             + "</HTML>");
     out.close();
   } finally {
     db.close();
   }
 }
Пример #17
0
 public static void loadKeyListeners(final ObjectContainer container, ClientContext context) {
   ObjectSet<HasKeyListener> results = Db4oBugs.query(container, HasKeyListener.class);
   for (HasKeyListener l : results) {
     container.activate(l, 1);
     try {
       if (l.isCancelled(container)) continue;
       KeyListener listener = l.makeKeyListener(container, context, true);
       if (listener != null) {
         if (listener.isSSK())
           context.getSskFetchScheduler(listener.isRealTime()).addPersistentPendingKeys(listener);
         else
           context.getChkFetchScheduler(listener.isRealTime()).addPersistentPendingKeys(listener);
         if (logMINOR)
           Logger.minor(
               ClientRequestScheduler.class,
               "Loaded request key listener: " + listener + " for " + l);
       }
     } catch (KeyListenerConstructionException e) {
       System.err.println("FAILED TO LOAD REQUEST BLOOM FILTERS:");
       e.printStackTrace();
       Logger.error(
           ClientRequestSchedulerCore.class, "FAILED TO LOAD REQUEST BLOOM FILTERS: " + e, e);
     } catch (Throwable t) {
       // Probably an error on last startup???
       Logger.error(ClientRequestSchedulerCore.class, "FAILED TO LOAD REQUEST: " + t, t);
       System.err.println("FAILED TO LOAD REQUEST: " + t);
       t.printStackTrace();
     }
     container.deactivate(l, 1);
   }
 }
Пример #18
0
 public void store(Object o) {
   ObjectContainer db = getDB();
   try {
     db.store(o);
   } finally {
     db.commit();
   }
 }
  public static synchronized void addSpecialCommand(Command command) {
    AndroidTransaction transaction = new AndroidTransaction();
    transaction.getCommands().add(command);

    ObjectContainer sess = Database.OpenDB();
    sess.store(transaction);
    sess.commit();
  }
Пример #20
0
 /**
  * Verifica se o objeto está armazenado no banco de dados e, caso não esteja (isso é, não seja
  * idêntico), o armazena.
  *
  * @param objeto objeto que será verificado e armazenado no banco de dados @
  */
 public void armazenarVerificar(Object objeto) {
   ObjectSet<Object> resultado = bd.queryByExample(objeto);
   if (resultado == null || resultado.size() == 0) {
     bd.store(objeto);
   } else {
     throw new RuntimeException("[armazenar] Objeto existente no banco de dados.");
   }
 }
 /** Just those keys which are eligible to be started now. */
 @Override
 public long countSendableKeys(ObjectContainer container, ClientContext context) {
   if (persistent) {
     container.activate(this, 1);
     container.activate(blockNums, 1);
   }
   cleanBlockNums(container);
   return blockNums.size();
 }
 @Override
 public long getCooldownWakeup(Object token, ObjectContainer container) {
   if (persistent) {
     container.activate(this, 1);
     container.activate(segment, 1);
   }
   long ret = segment.getCooldownWakeup(((MySendableRequestItem) token).x);
   return ret;
 }
 public void removeBlockNums(int[] blockNos, ObjectContainer container) {
   if (persistent) container.activate(blockNums, 2);
   boolean store = false;
   for (int i = 0; i < blockNos.length; i++) store |= removeBlockNum(blockNos[i], container, true);
   if (persistent) {
     if (store) container.store(blockNums);
     container.deactivate(blockNums, 2);
   }
 }
Пример #24
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);
 }
Пример #25
0
 //	Constructors and Operations:
 public static void main(String[] arg) {
   ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), DB.TAXI);
   System.out.println("Datenbank " + DB.TAXI + " wurde geöffnet.");
   try {
     //	Hier tun wir etwas mit der Datenbank.
   } finally {
     db.close();
   }
 }
 public void deleteTemplates() {
   openTemplateDb();
   ObjectSet<Request> objectList = dbTemplateContainer.queryByExample(null);
   while (objectList.hasNext()) {
     Request r = (Request) objectList.next();
     dbTemplateContainer.delete(r);
   }
   closeTemplateDb();
 }
 public boolean isEmpty(ObjectContainer container) {
   if (persistent) {
     container.activate(this, 1);
     container.activate(blockNums, 1);
   }
   synchronized (segment) {
     return cancelled || blockNums.isEmpty();
   }
 }
 public long add(Key key, SendableGet client, ObjectContainer container) {
   assert (cooldownTime != 0);
   long removeTime = System.currentTimeMillis() + cooldownTime;
   container.activate(key, 5);
   PersistentCooldownQueueItem persistentCooldownQueueItem =
       new PersistentCooldownQueueItem(client, key.cloneKey(), removeTime, this);
   container.store(persistentCooldownQueueItem);
   return removeTime;
 }
Пример #29
0
 private void createFile(Configuration config, String fileName) throws IOException {
   ObjectContainer oc = Db4o.openFile(config, fileName);
   try {
     populate(oc);
   } finally {
     oc.close();
   }
   File4.copy(fileName, fileName + "0");
 }
Пример #30
0
  public void registerInsert(
      final SendableRequest req, boolean persistent, boolean regmeOnly, ObjectContainer container) {
    if (!isInsertScheduler)
      throw new IllegalArgumentException("Adding a SendableInsert to a request scheduler!!");
    if (persistent) {
      if (regmeOnly) {
        long bootID = 0;
        boolean queueFull = jobRunner.getQueueSize(NativeThread.NORM_PRIORITY) >= QUEUE_THRESHOLD;
        if (!queueFull) bootID = this.node.bootID;
        final RegisterMe regme =
            new RegisterMe(req, req.getPriorityClass(container), schedCore, null, bootID);
        container.store(regme);
        if (logMINOR) Logger.minor(this, "Added insert RegisterMe: " + regme);
        if (!queueFull) {
          try {
            jobRunner.queue(
                new DBJob() {

                  @Override
                  public boolean run(ObjectContainer container, ClientContext context) {
                    container.delete(regme);
                    if (req.isCancelled(container)) {
                      if (logMINOR) Logger.minor(this, "Request already cancelled");
                      return false;
                    }
                    if (container.ext().isActive(req))
                      Logger.error(this, "ALREADY ACTIVE: " + req + " in delayed insert register");
                    container.activate(req, 1);
                    registerInsert(req, true, false, container);
                    container.deactivate(req, 1);
                    return true;
                  }

                  @Override
                  public String toString() {
                    return "registerInsert";
                  }
                },
                NativeThread.NORM_PRIORITY,
                false);
          } catch (DatabaseDisabledException e) {
            // Impossible, we are already on the database thread.
          }
        } else {
          schedCore.rerunRegisterMeRunner(jobRunner);
        }
        container.deactivate(req, 1);
        return;
      }
      schedCore.innerRegister(req, random, container, clientContext, null);
      starter.wakeUp();
    } else {
      schedTransient.innerRegister(req, random, null, clientContext, null);
      starter.wakeUp();
    }
  }