@Test
  public void test5CacheUpdatedMultipleDbs() {
    database1 = new ODatabaseDocumentTx(url).open("admin", "admin");
    database2 = new ODatabaseDocumentTx(url).open("admin", "admin");

    // Create docA in db1
    database1.begin(TXTYPE.OPTIMISTIC);
    ODocument vDocA_db1 = database1.newInstance();
    vDocA_db1.field(NAME, "docA");
    database1.save(vDocA_db1);
    database1.commit();

    // Keep the ID.
    ORID vDocA_Rid = vDocA_db1.getIdentity().copy();

    // Update docA in db2
    database2.begin(TXTYPE.OPTIMISTIC);
    ODocument vDocA_db2 = database2.load(vDocA_Rid);
    vDocA_db2.field(NAME, "docA_v2");
    database2.save(vDocA_db2);
    database2.commit();

    // Later... read docA with db1.
    database1.begin(TXTYPE.OPTIMISTIC);
    ODocument vDocA_db1_later = database1.load(vDocA_Rid, null, true);
    Assert.assertEquals(vDocA_db1_later.field(NAME), "docA_v2");
    database1.commit();

    database1.close();
    database2.close();
  }
  @SuppressWarnings("unchecked")
  @Test
  public void loadRecordTest() {
    ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
    db.open("admin", "admin");

    try {
      db.begin();

      ODocument kim = new ODocument("Profile").field("name", "Kim").field("surname", "Bauer");
      ODocument teri = new ODocument("Profile").field("name", "Teri").field("surname", "Bauer");
      ODocument jack = new ODocument("Profile").field("name", "Jack").field("surname", "Bauer");
      ODocument chloe = new ODocument("Profile").field("name", "Chloe").field("surname", "O'Brien");

      ((HashSet<ODocument>) jack.field("following", new HashSet<ODocument>()).field("following"))
          .add(kim);
      ((HashSet<ODocument>) kim.field("following", new HashSet<ODocument>()).field("following"))
          .add(teri);
      ((HashSet<ODocument>) teri.field("following", new HashSet<ODocument>()).field("following"))
          .add(jack);
      ((HashSet<ODocument>) teri.field("following")).add(kim);
      ((HashSet<ODocument>) chloe.field("following", new HashSet<ODocument>()).field("following"))
          .add(jack);
      ((HashSet<ODocument>) chloe.field("following")).add(teri);
      ((HashSet<ODocument>) chloe.field("following")).add(kim);

      int profileClusterId = db.getClusterIdByName("Profile");

      jack.save();
      Assert.assertEquals(jack.getIdentity().getClusterId(), profileClusterId);

      kim.save();
      Assert.assertEquals(kim.getIdentity().getClusterId(), profileClusterId);

      teri.save();
      Assert.assertEquals(teri.getIdentity().getClusterId(), profileClusterId);

      chloe.save();
      Assert.assertEquals(chloe.getIdentity().getClusterId(), profileClusterId);

      db.commit();

      Assert.assertEquals(jack.getIdentity().getClusterId(), profileClusterId);
      Assert.assertEquals(kim.getIdentity().getClusterId(), profileClusterId);
      Assert.assertEquals(teri.getIdentity().getClusterId(), profileClusterId);
      Assert.assertEquals(chloe.getIdentity().getClusterId(), profileClusterId);

      db.close();
      db.open("admin", "admin");

      ODocument loadedChloe = db.load(chloe.getIdentity());
      System.out.println(loadedChloe);
    } finally {
      db.close();
    }
  }
  @SuppressWarnings("unchecked")
  @Test
  public void createLinkInTx() {
    ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
    db.open("admin", "admin");

    OClass profile =
        db.getMetadata()
            .getSchema()
            .createClass("MyProfile", db.addCluster("myprofile", OStorage.CLUSTER_TYPE.PHYSICAL));
    OClass edge =
        db.getMetadata()
            .getSchema()
            .createClass("MyEdge", db.addCluster("myedge", OStorage.CLUSTER_TYPE.PHYSICAL));
    profile
        .createProperty("name", OType.STRING)
        .setMin("3")
        .setMax("30")
        .createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    profile.createProperty("surname", OType.STRING).setMin("3").setMax("30");
    profile.createProperty("in", OType.LINKSET, edge);
    profile.createProperty("out", OType.LINKSET, edge);
    edge.createProperty("in", OType.LINK, profile);
    edge.createProperty("out", OType.LINK, profile);

    db.begin();

    ODocument kim = new ODocument("MyProfile").field("name", "Kim").field("surname", "Bauer");
    ODocument teri = new ODocument("MyProfile").field("name", "Teri").field("surname", "Bauer");
    ODocument jack = new ODocument("MyProfile").field("name", "Jack").field("surname", "Bauer");

    ODocument myedge = new ODocument("MyEdge").field("in", kim).field("out", jack);
    myedge.save();
    ((HashSet<ODocument>) kim.field("out", new HashSet<ORID>()).field("out")).add(myedge);
    ((HashSet<ODocument>) jack.field("in", new HashSet<ORID>()).field("in")).add(myedge);

    jack.save();
    kim.save();
    teri.save();

    db.commit();

    db.close();

    db.open("admin", "admin");
    List<ODocument> result =
        db.command(new OSQLSynchQuery<ODocument>("select from MyProfile ")).execute();

    Assert.assertTrue(result.size() != 0);

    db.close();
  }
  @Test
  public void test3RollbackWithCopyCacheStrategy() throws IOException {
    database1 = new ODatabaseDocumentTx(url).open("admin", "admin");
    database2 = new ODatabaseDocumentTx(url).open("admin", "admin");

    database1.getLevel2Cache().setStrategy(STRATEGY.COPY_RECORD);

    // Create docA.
    ODocument vDocA_db1 = database1.newInstance();
    vDocA_db1.field(NAME, "docA");
    database1.save(vDocA_db1);

    // Keep the IDs.
    ORID vDocA_Rid = vDocA_db1.getIdentity().copy();

    database2.begin(TXTYPE.OPTIMISTIC);
    try {
      // Get docA and update in db2 transaction context
      ODocument vDocA_db2 = database2.load(vDocA_Rid);
      vDocA_db2.field(NAME, "docA_v2");
      database2.save(vDocA_db2);

      database1.begin(TXTYPE.OPTIMISTIC);
      try {
        vDocA_db1.field(NAME, "docA_v3");
        database1.save(vDocA_db1);
        database1.commit();
      } catch (OConcurrentModificationException e) {
        Assert.fail("Should not failed here...");
      }
      Assert.assertEquals(vDocA_db1.field(NAME), "docA_v3");

      // Will throw OConcurrentModificationException
      database2.commit();
      Assert.fail("Should throw OConcurrentModificationException");
    } catch (OConcurrentModificationException e) {
      database2.rollback();
    }

    // Force reload all (to be sure it is not a cache problem)
    database1.close();
    database2.close();
    database2 = new ODatabaseDocumentTx(url).open("admin", "admin");

    // docB should be in the last state : "docA_v3"
    ODocument vDocB_db2 = database2.load(vDocA_Rid);
    Assert.assertEquals(vDocB_db2.field(NAME), "docA_v3");

    database1.close();
    database2.close();
  }
Example #5
0
  @SuppressWarnings("unchecked")
  @Test
  public void test1() {

    db =
        new ODatabaseDocumentTx(
            "local:C:/work/dev/orientechnologies/orientdb/temp/danny/library/library");

    try {
      db.create();

      master = db.getMetadata().getSchema().createClass("Master");
      master.createProperty("type", OType.STRING);
      master.createProperty("master", OType.LONG);

      dependents = db.getMetadata().getSchema().createClass("Dependents");
      dependents.createProperty("type", OType.STRING);
      dependents.createProperty("dependents", OType.EMBEDDEDLIST, master);

      db.close();

      db.open("admin", "admin");
      dependents = db.getMetadata().getSchema().getClass("Dependents");
      master = db.getMetadata().getSchema().getClass("Master");

      // CREATE NEW DOC
      new ODocument(db, "Dependents")
          .field(
              "dependents",
              new ODocument[] {
                new ODocument(db, "Master")
                    .field("mastertype", "Title")
                    .field("master", 4151788013272153098L)
              })
          .save();
      db.close();

      db.open("admin", "admin");

      // LOAD IT AND CHECK THE LONG VALUE
      for (ODocument doc : db.browseClass("Dependents")) {
        System.out.println(doc);
        for (ODocument emb : (Iterable<ODocument>) doc.field("dependents"))
          Assert.assertEquals(emb.field("master"), 4151788013272153098L);
      }
      db.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    @Override
    public Void call() throws Exception {
      baseDB.open("admin", "admin");
      testDB.open("admin", "admin");

      try {
        while (true) {
          long id = idGen.getAndIncrement();
          long ts = System.currentTimeMillis();

          ODatabaseRecordThreadLocal.INSTANCE.set(baseDB);

          ODocument doc = new ODocument();
          doc.field("ts", ts);
          doc.save();

          baseDB
              .command(
                  new OCommandSQL(
                      "insert into index:mi (key, rid) values ("
                          + id
                          + ", "
                          + doc.getIdentity()
                          + ")"))
              .execute();

          ODatabaseRecordThreadLocal.INSTANCE.set(testDB);
          doc = new ODocument();
          doc.field("ts", ts);
          doc.save();

          testDB
              .command(
                  new OCommandSQL(
                      "insert into index:mi (key, rid) values ("
                          + id
                          + ", "
                          + doc.getIdentity()
                          + ")"))
              .execute();
        }
      } finally {
        baseDB.activateOnCurrentThread();
        baseDB.close();

        testDB.activateOnCurrentThread();
        testDB.close();
      }
    }
  public static void main(String[] args) {

    /**
     * Document API
     *
     * <p>ODatabaseDocumentTx是非线程安全的,所以在多线程使用的时候,需要初始化多个实例instances;
     */
    String database = "remote:localhost/mengka";
    ODatabaseDocumentTx db = new ODatabaseDocumentTx(database).open("admin", "admin");

    /** 例一: 插入第一行数据 */
    ODocument aaDocument = new ODocument("Person");
    aaDocument.field("name", "Luke");
    aaDocument.field("surname", "Skywalker");
    aaDocument.field("city", new ODocument("City").field("name", "Rome").field("country", "Italy"));
    aaDocument.save();

    /**
     * 例二: 插入第二行数据
     *
     * <p>外键:City-北京
     */
    ODocument out_bbDocument = new ODocument("City");
    out_bbDocument.field("name", "北京");
    out_bbDocument.field("country", "中国");
    ODocument bbDocument = new ODocument("Person");
    bbDocument.field("name", "白菜");
    bbDocument.field("surname", "司马");
    bbDocument.field("city", out_bbDocument);
    bbDocument.save();

    /** 释放资源 */
    db.close();
  }
 private int updateRecords() throws Throwable {
   ODatabaseDocumentTx database = null;
   try {
     database = ODatabaseDocumentPool.global().acquire(getDatabaseURL(), "admin", "admin");
     int numRetries = 0;
     int numUpdated = 0;
     while (numRetries < NUM_RETRIES) {
       database.begin();
       try {
         OCommandSQL cmd =
             new OCommandSQL("UPDATE ExceptionRecord set jobId='2' where username='******'");
         numUpdated = database.command(cmd).execute((Object[]) null);
         database.commit();
         break;
       } catch (Throwable e) {
         database.rollback();
         logger.log(Level.SEVERE, "********************************");
         logger.log(Level.SEVERE, "Update Iteration=" + numRetries + ", " + e.toString(), e);
         logger.log(Level.SEVERE, "********************************");
         if (numRetries++ == NUM_RETRIES) {
           throw e;
         }
       }
     }
     return numUpdated;
   } finally {
     if (database != null && !database.isClosed()) {
       database.close();
     }
   }
 }
  @Test
  public void testExceptionManagement() {
    // issue #5244
    OLiveCommandExecutorSQLFactory.init();

    ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:ONonBlockingQueryTest");
    db.activateOnCurrentThread();
    db.create();

    db.getMetadata().getSchema().createClass("test");
    MyResultListener listener = new MyResultListener();
    try {
      db.command(new OCommandSQL("insert into test set name = 'foo', surname = 'bar'")).execute();

      db.query(new OSQLNonBlockingQuery<Object>("select from test bla blu", listener));
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Assert.assertEquals(listener.finished, true);

      listener = new MyResultListener();
      db.query(new OSQLNonBlockingQuery<Object>("select from test", listener));

    } finally {
      db.close();
    }
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    Assert.assertEquals(listener.numResults, 1);
  }
  @Override
  public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
    final String[] urlParts =
        checkSyntax(iRequest.url, 3, "Syntax error: index/<database>/<index-name>/<key>/[<value>]");

    iRequest.data.commandInfo = "Index remove";

    ODatabaseDocumentTx db = null;

    try {
      db = getProfiledDatabaseInstance(iRequest);

      final OIndex<?> index = db.getMetadata().getIndexManager().getIndex(urlParts[2]);
      if (index == null)
        throw new IllegalArgumentException("Index name '" + urlParts[2] + "' not found");

      final boolean found;
      if (urlParts.length > 4) found = index.remove(urlParts[3], new ORecordId(urlParts[3]));
      else found = index.remove(urlParts[3]);

      if (found)
        iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, null, null);
      else
        iResponse.send(
            OHttpUtils.STATUS_NOTFOUND_CODE,
            OHttpUtils.STATUS_NOTFOUND_DESCRIPTION,
            OHttpUtils.CONTENT_TEXT_PLAIN,
            null,
            null);
    } finally {
      if (db != null) db.close();
    }
    return false;
  }
  @Override
  protected void executeTest() throws Exception {

    ODatabaseDocumentTx db =
        new ODatabaseDocumentTx("plocal:target/server0/databases/" + getDatabaseName());
    db.open("admin", "admin");

    try {
      db.command(new OCommandSQL("INSERT into Item (name) values ('foo')")).execute();

      Iterable<ODocument> result =
          db.command(new OCommandSQL("select set(name) as names from Item")).execute();
      Assert.assertEquals(Collections.singleton("foo"), result.iterator().next().field("names"));

      result = db.command(new OCommandSQL("select list(name) as names from Item")).execute();
      Assert.assertEquals(
          Collections.singletonList("foo"), result.iterator().next().field("names"));

      db.command(new OCommandSQL("INSERT into Item (map) values ({'a':'b'}) return @this"))
          .execute();

      result = db.command(new OCommandSQL("select map(map) as names from Item")).execute();
      Assert.assertEquals(
          Collections.singletonMap("a", "b"), result.iterator().next().field("names"));

    } finally {
      db.close();
    }
  }
Example #12
0
  public void login() {

    if (DataUser.getUsr() == null) {
      LoginDialog form = new LoginDialog();
      ODatabaseDocumentTx db = App.getDbd();
      ODatabaseRecordThreadLocal.INSTANCE.set(db);
      form.buildComponent(db);
      db.close();
      JDialog d = new JDialog(frame);
      d.setModalityType(ModalityType.APPLICATION_MODAL);
      d.getContentPane().add(form.getPanel());
      d.pack();
      setCenterDialog(d);
      d.setVisible(true);
    } else {
      // logout
      DataUser.setUsr(null);
      DataUser.setGrp(null);
      closeAllWindow();
    }
    DataUser.setAkses();
    for (HakAksesListener hakAksesListener : cangeHakAkses) {
      hakAksesListener.changeHakAkses();
    }
    //		if (DataUser.usr != null) {
    //			// open default like welcome
    //
    //		}
  }
  /**
   * The object will contain metadata properties, including object identifier {@code _id}, and
   * object version {@code _rev} to enable optimistic concurrency supported by OrientDB and OpenIDM.
   *
   * @param request the identifier of the object to retrieve from the object set.
   * @throws NotFoundException if the specified object could not be found.
   * @throws ForbiddenException if access to the object is forbidden.
   * @throws BadRequestException if the passed identifier is invalid
   * @return the requested object.
   */
  @Override
  public ResourceResponse read(ReadRequest request) throws ResourceException {
    if (request.getResourcePathObject().size() < 2) {
      throw new NotFoundException(
          "The object identifier did not include sufficient information to determine the object type and identifier of the object to read: "
              + request.getResourcePath());
    }

    final String type = request.getResourcePathObject().parent().toString();
    final String localId = request.getResourcePathObject().leaf();
    ResourceResponse result = null;
    ODatabaseDocumentTx db = getConnection();
    try {
      ODocument doc = predefinedQueries.getByID(localId, type, db);
      if (doc == null) {
        throw new NotFoundException("Object " + localId + " not found in " + type);
      }
      result = DocumentUtil.toResource(doc);
      logger.trace("Completed get for id: {} result: {}", request.getResourcePath(), result);
      return result;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
Example #14
0
  /*
   * private method to invoke the xbel network exporter
   */
  private void exportNetwork() throws Exception {
    this.taskStatus = Status.PROCESSING;
    this.startTask();
    String exportFilename =
        this.resolveFilename(
            Configuration.getInstance().getNdexRoot() + "/exported-networks/",
            this.XBEL_FILE_EXTENSION);

    ODatabaseDocumentTx db = null;
    try {
      db = NdexDatabase.getInstance().getAConnection();
      NdexTaskModelService modelService = new NdexJVMDataModelService(db);
      XbelNetworkExporter exporter =
          new XbelNetworkExporter(
              this.getTask().getTaskOwnerId().toString(),
              this.networkId,
              modelService,
              exportFilename);
      exporter.exportNetwork();
      this.taskStatus = Status.COMPLETED;
      this.updateTaskStatus(this.taskStatus);
    } finally {
      if (db != null) db.close();
    }
  }
    @Override
    public Void call() {
      for (int i = 0; i < CYCLES; i++) {
        ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
        try {
          for (int retry = 0; retry < MAX_RETRIES; ++retry) {
            try {
              db.command(new OCommandSQL("select from Concurrent")).execute();

              counter.incrementAndGet();
              totalRetries.addAndGet(retry);
              break;
            } catch (ONeedRetryException e) {
              try {
                Thread.sleep(retry * 10);
              } catch (InterruptedException e1) {
                throw new RuntimeException(e1);
              }
            }
          }
        } finally {
          db.close();
        }
      }
      return null;
    }
Example #16
0
 @AfterClass
 public void afterClass() throws Exception {
   if (database.isClosed()) database.open("admin", "admin");
   database.command(new OCommandSQL("delete from SQLDropIndexTestClass")).execute();
   database.command(new OCommandSQL("drop class SQLDropIndexTestClass")).execute();
   database.reload();
   database.close();
 }
  @SuppressWarnings("unchecked")
  @Test
  public void checkVersionsInConnectedDocuments() {
    ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
    db.open("admin", "admin");

    db.begin();

    ODocument kim = new ODocument("Profile").field("name", "Kim").field("surname", "Bauer");
    ODocument teri = new ODocument("Profile").field("name", "Teri").field("surname", "Bauer");
    ODocument jack = new ODocument("Profile").field("name", "Jack").field("surname", "Bauer");

    ((HashSet<ODocument>) jack.field("following", new HashSet<ODocument>()).field("following"))
        .add(kim);
    ((HashSet<ODocument>) kim.field("following", new HashSet<ODocument>()).field("following"))
        .add(teri);
    ((HashSet<ODocument>) teri.field("following", new HashSet<ODocument>()).field("following"))
        .add(jack);

    jack.save();

    db.commit();

    db.close();
    db.open("admin", "admin");

    ODocument loadedJack = db.load(jack.getIdentity());

    ORecordVersion jackLastVersion = loadedJack.getRecordVersion().copy();
    db.begin();
    loadedJack.field("occupation", "agent");
    loadedJack.save();
    db.commit();
    Assert.assertTrue(!jackLastVersion.equals(loadedJack.getRecordVersion()));

    loadedJack = db.load(jack.getIdentity());
    Assert.assertTrue(!jackLastVersion.equals(loadedJack.getRecordVersion()));

    db.close();

    db.open("admin", "admin");
    loadedJack = db.load(jack.getIdentity());
    Assert.assertTrue(!jackLastVersion.equals(loadedJack.getRecordVersion()));
    db.close();
  }
 @AfterClass
 public void afterClass() throws Exception {
   if (db.isClosed()) {
     db.open("admin", "admin");
   }
   db.command(new OCommandSQL("drop class foo")).execute();
   db.getMetadata().getSchema().reload();
   db.close();
 }
 public void setPiutang(ODocument piutang) {
   if (piutang != null && piutang.field("@class").equals(App.getPiutangDao().getClassName())) {
     this.piutang = piutang;
     ODatabaseDocumentTx db = App.getDbd();
     ODatabaseRecordThreadLocal.INSTANCE.set(db);
     reload(db);
     db.close();
   }
 }
Example #20
0
  private void initializeExceptionRecordTable(String databaseUrl) {
    ODatabaseDocumentTx database = new ODatabaseDocumentTx(databaseUrl).create();
    OClass exceptionRecordClass = database.getMetadata().getSchema().createClass("ExceptionRecord");
    OClass exceptionVersionClass =
        database.getMetadata().getSchema().createClass("ExceptionRecordVersion");
    try {

      exceptionRecordClass.createProperty("id", OType.STRING);
      exceptionRecordClass.createProperty("status", OType.STRING);
      exceptionRecordClass.createProperty("approved", OType.BOOLEAN);
      exceptionRecordClass.createProperty("recordType", OType.STRING);
      exceptionRecordClass.createProperty("groupNonException", OType.BOOLEAN);
      exceptionRecordClass.createProperty("comment", OType.STRING);
      exceptionRecordClass.createProperty("jobId", OType.STRING);
      exceptionRecordClass.createProperty("dataflowName", OType.STRING);
      exceptionRecordClass.createProperty("username", OType.STRING);
      exceptionRecordClass.createProperty("timestamp", OType.LONG);
      exceptionRecordClass.createProperty("stageLabel", OType.STRING);
      exceptionRecordClass.createProperty("groupColumn", OType.STRING);
      exceptionRecordClass.createProperty("lastModifiedBy", OType.STRING);
      exceptionRecordClass.createProperty("lastModified", OType.LONG);
      exceptionRecordClass.createProperty("data", OType.STRING);

      exceptionVersionClass.createProperty("key-exceptionId", OType.STRING);
      exceptionVersionClass.createProperty("key-version", OType.STRING);
      exceptionVersionClass.createProperty("jobId", OType.STRING);
      exceptionVersionClass.createProperty("dataflowName", OType.STRING);

      exceptionRecordClass.createIndex("ExceptionRecord_pk", INDEX_TYPE.UNIQUE, "id");
      exceptionRecordClass.createIndex(
          "ExceptionRecord_idx",
          INDEX_TYPE.NOTUNIQUE,
          "status",
          "approved",
          "recordType",
          "groupNonException",
          "comment",
          "jobId",
          "dataflowName",
          "username",
          "timestamp",
          "stageLabel",
          "groupColumn",
          "lastModifiedBy",
          "lastModified");

      exceptionVersionClass.createIndex(
          "ExceptionVersion_Index",
          INDEX_TYPE.NOTUNIQUE,
          "key-exceptionId",
          "key-version",
          "jobId",
          "dataflowname");
    } finally {
      database.close();
    }
  }
  @After
  public void teardown() throws DBException {
    if (orientDBConnection != null) {
      orientDBConnection.close();
    }

    if (orientDBClient != null) {
      orientDBClient.cleanup();
    }
  }
  /**
   * Deletes the specified object from the object set.
   *
   * <p>{@inheritDoc}
   *
   * @throws NotFoundException if the specified object could not be found.
   * @throws ForbiddenException if access to the object is forbidden.
   * @throws ConflictException if version is required but is {@code null}.
   * @throws PreconditionFailedException if version did not match the existing object in the set.
   */
  @Override
  public ResourceResponse delete(DeleteRequest request) throws ResourceException {
    if (request.getResourcePathObject().size() < 2) {
      throw new NotFoundException(
          "The object identifier did not include sufficient information to determine the object type and identifier of the object to update: "
              + request.getResourcePath());
    }

    if (request.getRevision() == null || "".equals(request.getRevision())) {
      throw new ConflictException(
          "Object passed into delete does not have revision it expects set.");
    }

    final String type = request.getResourcePathObject().parent().toString();
    final String localId = request.getResourcePathObject().leaf();

    int ver =
        DocumentUtil.parseVersion(
            request.getRevision()); // This throws ConflictException if parse fails

    ODatabaseDocumentTx db = getConnection();
    try {
      ODocument existingDoc = predefinedQueries.getByID(localId, type, db);
      if (existingDoc == null) {
        throw new NotFoundException(
            "Object does not exist for delete on: " + request.getResourcePath());
      }

      db.delete(existingDoc.getIdentity(), new OSimpleVersion(ver));
      logger.debug("delete for id succeeded: {} revision: {}", localId, request.getRevision());
      return DocumentUtil.toResource(existingDoc);
    } catch (ODatabaseException ex) {
      // Without transaction the concurrent modification exception gets nested instead
      if (isCauseConcurrentModificationException(ex, 10)) {
        throw new PreconditionFailedException(
            "Delete rejected as current Object revision is different than expected by caller, the object has changed since retrieval. "
                + ex.getMessage(),
            ex);
      } else {
        throw ex;
      }

    } catch (OConcurrentModificationException ex) {
      throw new PreconditionFailedException(
          "Delete rejected as current Object revision is different than expected by caller, the object has changed since retrieval."
              + ex.getMessage(),
          ex);
    } catch (RuntimeException e) {
      throw e;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
  /**
   * Execute a database command according to the details in the action request.
   *
   * @param request the ActionRequest
   * @return the number of affected rows/records.
   * @throws ResourceException on failure to resolved query
   */
  public Object command(ActionRequest request) throws ResourceException {

    ODatabaseDocumentTx db = getConnection();
    try {
      return commands.query(request.getResourcePath(), request, db);
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
  protected void updateDocument(
      final int threadId,
      final int iCycle,
      final String dbUrl,
      final String className,
      final int iSkip) {
    final ODatabaseDocumentTx db = getDatabase(dbUrl);
    for (int retry = 0; retry < MAX_RETRY; ++retry) {
      ODocument doc = null;
      try {
        List<OIdentifiable> result =
            db.query(
                new OSQLSynchQuery<Object>(
                    "select from " + className + " skip " + iSkip + " limit 1"));

        if (result == null || result.isEmpty())
          log(threadId, iCycle, dbUrl, " update no item " + iSkip + " because out of range");
        else {
          doc = (ODocument) result.get(0);
          doc.field("updated", "" + (doc.getVersion() + 1));
          doc.save();
          log(threadId, iCycle, dbUrl, " updated item " + iSkip + " RID=" + result.get(0));
        }

        // OK
        break;

      } catch (OConcurrentModificationException e) {
        log(
            threadId,
            iCycle,
            dbUrl,
            " concurrent update against record "
                + doc
                + ", reload it and retry "
                + retry
                + "/"
                + MAX_RETRY
                + "...");
        if (doc != null) doc.reload(null, true);

      } catch (ORecordNotFoundException e) {
        log(threadId, iCycle, dbUrl, " update no item " + iSkip + " because not found");
        break;

      } finally {
        db.close();
      }
    }
  }
  @Override
  public List<ResourceResponse> query(final QueryRequest request) throws ResourceException {
    List<ResourceResponse> results = new ArrayList<ResourceResponse>();

    logger.trace(
        "Full id: {} Extracted type: {}", request.getResourcePath(), request.getResourcePath());
    // TODO: Statistics is not returned in result anymore
    // TODO: result is not needed in map form anymore
    Map<String, Object> result = new HashMap<String, Object>();
    ODatabaseDocumentTx db = getConnection();
    try {
      // List<Map<String, Object>> docs = new ArrayList<Map<String, Object>>();
      // result.put(QueryConstants.QUERY_RESULT, docs);
      long start = System.currentTimeMillis();
      List<ODocument> queryResult = queries.query(request.getResourcePath(), request, db);
      long end = System.currentTimeMillis();
      if (queryResult != null) {
        long convStart = System.currentTimeMillis();
        for (ODocument entry : queryResult) {
          Map<String, Object> convertedEntry = DocumentUtil.toMap(entry);
          // docs.add(convertedEntry);
          results.add(
              newResourceResponse(
                  (String) convertedEntry.get(DocumentUtil.TAG_ID),
                  (String) convertedEntry.get(DocumentUtil.TAG_REV),
                  new JsonValue(convertedEntry)));
        }
        long convEnd = System.currentTimeMillis();
        result.put(QueryConstants.STATISTICS_CONVERSION_TIME, Long.valueOf(convEnd - convStart));
      }
      result.put(QueryConstants.STATISTICS_QUERY_TIME, Long.valueOf(end - start));

      if (logger.isDebugEnabled()) {
        logger.debug(
            "Query result contains {} records, took {} ms and took {} ms to convert result.",
            new Object[] {
              results.size(),
              result.get(QueryConstants.STATISTICS_QUERY_TIME),
              result.get(QueryConstants.STATISTICS_CONVERSION_TIME)
            });
      }
      return results;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
 @Test
 public void testUpdateContent() throws Exception {
   final ODatabaseDocumentTx db =
       new ODatabaseDocumentTx("memory:OCommandExecutorSQLUpdateTestContent");
   db.create();
   try {
     db.command(new OCommandSQL("CREATE class V")).execute();
     db.command(new OCommandSQL("insert into V (name) values ('bar')")).execute();
     db.command(new OCommandSQL("UPDATE V content {\"value\":\"foo\"}")).execute();
     Iterable result = db.query(new OSQLSynchQuery<Object>("select from V"));
     ODocument doc = (ODocument) result.iterator().next();
     assertEquals(doc.field("value"), "foo");
   } finally {
     db.close();
   }
 }
  @Test
  public void concurrentCommands() throws Exception {
    OGlobalConfiguration.DB_POOL_MIN.setValue(1);
    OGlobalConfiguration.DB_POOL_MAX.setValue(MAX_CONNS);

    final Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
                try {
                  System.out.println("Start sleeping...");
                  db.command(new OCommandScript("SQL", "sleep 5000")).execute();
                  System.out.println("Sleeping done!");

                } finally {
                  db.close();
                }
              }
            },
            "Test long sleep");

    thread.start();

    Thread.sleep(1000);

    int commandExecuted = 0;
    int iterations = MAX_CONNS * 5;
    for (int i = 0; i < iterations; ++i) {
      System.out.println("Open database " + i);
      ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
      try {
        db.command(new OCommandSQL("select from OUser")).execute();
        System.out.println("Command executed " + i);
        commandExecuted++;
      } finally {
        db.close();
      }
    }

    System.out.println("Waiting for the sleeping thread...");
    thread.join();
    System.out.println("Done!");

    Assert.assertEquals(commandExecuted, iterations);
  }
    @Override
    public Void call() throws Exception {
      String name = Integer.toString(threadId);
      for (int i = 0; i < count; i++) {
        final ODatabaseDocumentTx database =
            poolFactory.get(databaseUrl, "admin", "admin").acquire();
        try {
          if ((i + 1) % 100 == 0)
            System.out.println(
                "\nWriter "
                    + threadId
                    + "("
                    + database.getURL()
                    + ") managed "
                    + (i + 1)
                    + "/"
                    + count
                    + " records so far");

          final ODocument person = createRecord(database, i);
          updateRecord(database, i);
          checkRecord(database, i);
          checkIndex(database, (String) person.field("name"), person.getIdentity());

          if (delayWriter > 0) Thread.sleep(delayWriter);

        } catch (InterruptedException e) {
          System.out.println("Writer received interrupt (db=" + database.getURL());
          Thread.currentThread().interrupt();
          break;
        } catch (Exception e) {
          System.out.println("Writer received exception (db=" + database.getURL());
          e.printStackTrace();
          break;
        } finally {
          database.close();
          runningWriters.countDown();
        }
      }

      System.out.println("\nWriter " + name + " END");
      return null;
    }
  protected void createDocument(
      final int threadId,
      final int iCycle,
      final String dbUrl,
      final String className,
      final int iProperties) {
    final ODatabaseDocumentTx db = getDatabase(dbUrl);
    try {
      log(threadId, iCycle, dbUrl, " creating document: class=" + className);

      ODocument doc = new ODocument(className);
      for (int i = 0; i < iProperties; ++i) {
        doc.field("prop" + i, "propValue" + i);
      }
      doc.save();
    } finally {
      db.close();
    }
  }
  @Test
  public void testUpdateMergeWithIndex() {
    final ODatabaseDocumentTx db =
        new ODatabaseDocumentTx("memory:OCommandExecutorSQLUpdateTestMergeWithIndex");
    db.create();
    try {
      db.command(new OCommandSQL("CREATE CLASS i_have_a_list ")).execute();
      db.command(new OCommandSQL("CREATE PROPERTY i_have_a_list.id STRING")).execute();
      db.command(new OCommandSQL("CREATE INDEX i_have_a_list.id ON i_have_a_list (id) UNIQUE"))
          .execute();
      db.command(new OCommandSQL("CREATE PROPERTY i_have_a_list.types EMBEDDEDLIST STRING"))
          .execute();
      db.command(
              new OCommandSQL(
                  "CREATE INDEX i_have_a_list.types ON i_have_a_list (types) NOTUNIQUE"))
          .execute();
      db.command(
              new OCommandSQL(
                  "INSERT INTO i_have_a_list CONTENT {\"id\": \"the_id\", \"types\": [\"aaa\", \"bbb\"]}"))
          .execute();

      Iterable result =
          db.query(new OSQLSynchQuery<Object>("SELECT * FROM i_have_a_list WHERE types = 'aaa'"));
      assertTrue(result.iterator().hasNext());

      db.command(
              new OCommandSQL(
                  "UPDATE i_have_a_list CONTENT {\"id\": \"the_id\", \"types\": [\"ccc\", \"bbb\"]} WHERE id = 'the_id'"))
          .execute();

      result =
          db.query(new OSQLSynchQuery<Object>("SELECT * FROM i_have_a_list WHERE types = 'ccc'"));
      assertTrue(result.iterator().hasNext());

      result =
          db.query(new OSQLSynchQuery<Object>("SELECT * FROM i_have_a_list WHERE types = 'aaa'"));
      assertFalse(result.iterator().hasNext());

    } finally {
      db.close();
    }
  }