@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;
    }
  @Test
  public void testOrderByRid() {
    List<ODocument> qResult =
        db.command(new OCommandSQL("select from ridsorttest order by @rid ASC")).execute();
    assertTrue(qResult.size() > 0);

    ODocument prev = qResult.get(0);
    for (int i = 1; i < qResult.size(); i++) {
      assertTrue(prev.getIdentity().compareTo(qResult.get(i).getIdentity()) <= 0);
      prev = qResult.get(i);
    }

    qResult = db.command(new OCommandSQL("select from ridsorttest order by @rid DESC")).execute();
    assertTrue(qResult.size() > 0);

    prev = qResult.get(0);
    for (int i = 1; i < qResult.size(); i++) {
      assertTrue(prev.getIdentity().compareTo(qResult.get(i).getIdentity()) >= 0);
      prev = qResult.get(i);
    }

    qResult =
        db.command(new OCommandSQL("select from ridsorttest where name > 3 order by @rid DESC"))
            .execute();
    assertTrue(qResult.size() > 0);

    prev = qResult.get(0);
    for (int i = 1; i < qResult.size(); i++) {
      assertTrue(prev.getIdentity().compareTo(qResult.get(i).getIdentity()) >= 0);
      prev = qResult.get(i);
    }
  }
  @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;
  }
Exemplo n.º 4
0
  @Test(dependsOnMethods = {"testTransactionalUsageWorks"})
  public void testTransactionalUsageBreaks2() {
    OIndex<?> index = getIndex();
    database.begin(OTransaction.TXTYPE.OPTIMISTIC);
    ComparableBinary key7 =
        new ComparableBinary(
            new byte[] {
              0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8,
              9, 0, 7
            });
    ODocument doc1 = new ODocument().field("k", "key7");
    index.put(key7, doc1);

    ComparableBinary key8 =
        new ComparableBinary(
            new byte[] {
              0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8,
              9, 0, 8
            });
    ODocument doc2 = new ODocument().field("k", "key8");
    index.put(key8, doc2);

    database.commit();

    Assert.assertEquals(index.get(key7), doc1);
    Assert.assertEquals(index.get(key8), doc2);
  }
  /**
   * 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();
      }
    }
  }
Exemplo n.º 6
0
  public void testTransactionalUsageWorks() {
    database.begin(OTransaction.TXTYPE.OPTIMISTIC);
    // OIndex<?> index = getManualIndex();
    ComparableBinary key3 =
        new ComparableBinary(
            new byte[] {
              0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8,
              9, 0, 3
            });
    ODocument doc1 = new ODocument().field("k", "key3");

    final OIndex index = getIndex();
    index.put(key3, doc1);

    ComparableBinary key4 =
        new ComparableBinary(
            new byte[] {
              0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8,
              9, 0, 4
            });
    ODocument doc2 = new ODocument().field("k", "key4");
    index.put(key4, doc2);

    database.commit();

    Assert.assertEquals(index.get(key3), doc1);
    Assert.assertEquals(index.get(key4), doc2);
  }
Exemplo n.º 7
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
    //
    //		}
  }
  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();
  }
Exemplo n.º 9
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();
    }
  }
 @Test
 public void testSelectFromClusterNumber() {
   OClass clazz = db.getMetadata().getSchema().getClass("DistinctLimit");
   int firstCluster = clazz.getClusterIds()[0];
   OSQLSynchQuery sql = new OSQLSynchQuery("select from cluster:" + firstCluster + " limit 1");
   List<ODocument> results = db.query(sql);
   assertEquals(results.size(), 1);
 }
Exemplo n.º 11
0
 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();
   }
 }
 @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();
 }
Exemplo n.º 13
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();
    }
  }
 public Iterator<T> iterator() {
   final ODatabaseDocumentTx rawGraph = this.graph.getRawGraph();
   return new OrientElementIterator<T>(
       this.graph,
       new ORecordIteratorClass<ORecordInternal<?>>(
           rawGraph,
           (ODatabaseRecordAbstract) rawGraph.getUnderlying(),
           elementClass,
           polymorphic));
 }
Exemplo n.º 15
0
  @Test
  public void testLiveInsert() {
    OLiveCommandExecutorSQLFactory.init();

    ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:OLiveQueryTest");
    db.activateOnCurrentThread();
    db.create();
    db.registerHook(new OLiveQueryHook(db));
    try {
      db.getMetadata().getSchema().createClass("test");
      db.getMetadata().getSchema().createClass("test2");
      MyLiveQueryListener listener = new MyLiveQueryListener();

      db.query(new OLiveQuery<ODocument>("live select from test", listener));

      db.command(new OCommandSQL("insert into test set name = 'foo', surname = 'bar'")).execute();
      db.command(new OCommandSQL("insert into test set name = 'foo', surname = 'baz'")).execute();
      db.command(new OCommandSQL("insert into test2 set name = 'foo'"));

      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Assert.assertEquals(listener.ops.size(), 2);
      for (ORecordOperation doc : listener.ops) {
        Assert.assertEquals(doc.type, ORecordOperation.CREATED);
        Assert.assertEquals(((ODocument) doc.record).field("name"), "foo");
      }
    } finally {

      db.drop();
    }
  }
Exemplo n.º 16
0
  /**
   * 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();
      }
    }
  }
Exemplo n.º 17
0
  /**
   * 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();
      }
    }
  }
  @After
  public void tearDown() {
    testDocumentTx.activateOnCurrentThread();
    testDocumentTx.drop();

    baseDocumentTx.activateOnCurrentThread();
    baseDocumentTx.drop();

    OFileUtils.deleteRecursively(buildDir);
    Assert.assertFalse(buildDir.exists());
  }
 private void initDatesSet(ODatabaseDocumentTx db) {
   db.command(new OCommandSQL("create class OCommandExecutorSQLSelectTest_datesSet")).execute();
   db.command(
           new OCommandSQL(
               "create property OCommandExecutorSQLSelectTest_datesSet.foo embeddedlist date"))
       .execute();
   db.command(
           new OCommandSQL(
               "insert into OCommandExecutorSQLSelectTest_datesSet set foo = ['2015-10-21']"))
       .execute();
 }
 @Test
 public void testParamWithMatchesQuoteRegex() {
   // issue #5229
   Map<String, Object> params = new HashMap<String, Object>();
   params.put("param1", ".*admin[name].*"); // will not work
   OSQLSynchQuery sql = new OSQLSynchQuery("select from matchesstuff where name matches :param1");
   List<ODocument> results = db.query(sql, params);
   assertEquals(results.size(), 0);
   params.put("param1", Pattern.quote("admin[name]") + ".*"); // should work
   results = db.query(sql, params);
   assertEquals(results.size(), 1);
 }
Exemplo n.º 21
0
  @Test
  public static void main(String[] args) {
    database = new ODatabaseDocumentTx("local:/tmp/secmask/secmask");
    if (database.exists()) database.open("admin", "admin");
    else {
      database.create();
      create();
    }

    // insert();
    query();
  }
Exemplo n.º 22
0
 public List<Comment> getCommentsByCaseId(String caseId) {
   String request = "SELECT FROM Comment WHERE case = ? ORDER BY createDate asc";
   try (ODatabaseDocumentTx database = getODatabaseDocumentTx()) {
     List<ODocument> docs = database.query(new OSQLSynchQuery<Comment>(request), caseId);
     List<Comment> comments = new ArrayList<>(docs.size());
     for (ODocument doc : docs) {
       Comment comment = oDocumentToComment(doc);
       comments.add(comment);
     }
     return comments;
   }
 }
Exemplo n.º 23
0
  @BeforeClass
  public void beforeClass() {
    database = new ODatabaseDocumentTx(url);

    if (database.isClosed()) database.open("admin", "admin");

    final OSchema schema = database.getMetadata().getSchema();
    final OClass oClass = schema.createClass("SQLDropIndexTestClass");
    oClass.createProperty("prop1", EXPECTED_PROP1_TYPE);
    oClass.createProperty("prop2", EXPECTED_PROP2_TYPE);

    schema.save();
  }
Exemplo n.º 24
0
  @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();
    }
  }
Exemplo n.º 25
0
 public Comment saveComment(Comment comment) {
   try (ODatabaseDocumentTx database = getODatabaseDocumentTx()) {
     ODocument doc = new ODocument("Comment");
     doc.field("body", comment.getBody());
     doc.field("parent", comment.getParent() != null ? new ORecordId(comment.getParent()) : null);
     doc.field("case", comment.getCase() != null ? new ORecordId(comment.getCase()) : null);
     doc.field("task", comment.getTask() != null ? new ORecordId(comment.getTask()) : null);
     doc.field("createDate", new Date());
     doc.field("creator", user.getId());
     doc = doc.save();
     database.commit();
     return oDocumentToComment(doc);
   }
 }
  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();
      }
    }
  }
Exemplo n.º 27
0
 private int deleteRecords() throws Throwable {
   ODatabaseDocumentTx database = null;
   try {
     database = ODatabaseDocumentPool.global().acquire(getDatabaseURL(), "admin", "admin");
     int numRetries = 0;
     int numDeleted = 0;
     while (numRetries < NUM_RETRIES) {
       database.begin();
       try {
         OCommandSQL cmd =
             new OCommandSQL("DELETE from ExceptionRecordVersion where username='******'");
         database.command(cmd).execute((Object[]) null);
         cmd = new OCommandSQL("DELETE from ExceptionRecord where username='******'");
         numDeleted = database.command(cmd).execute((Object[]) null);
         database.commit();
         break;
       } catch (Throwable e) {
         database.rollback();
         logger.log(Level.SEVERE, "********************************");
         logger.log(Level.SEVERE, "Delete Iteration=" + numRetries + ", " + e.toString(), e);
         logger.log(Level.SEVERE, "********************************");
         if (numRetries++ == NUM_RETRIES) {
           throw e;
         }
       }
     }
     return numDeleted;
   } 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
  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();
    }
  }
Exemplo n.º 30
0
  @Override
  public boolean execute(final OHttpRequest iRequest) throws Exception {
    String[] urlParts =
        checkSyntax(
            iRequest.url,
            3,
            "Syntax error: class/<database>/<class-name>[/<limit>]<br/>Limit is optional and is setted to 20 by default. Set expressely to 0 to have no limits.");

    iRequest.data.commandInfo = "Browse class";
    iRequest.data.commandDetail = urlParts[2];

    ODatabaseDocumentTx db = null;

    try {
      db = getProfiledDatabaseInstance(iRequest);

      if (db.getMetadata().getSchema().getClass(urlParts[2]) == null)
        throw new IllegalArgumentException("Invalid class '" + urlParts[2] + "'");

      final int limit = urlParts.length > 3 ? Integer.parseInt(urlParts[3]) : 20;

      final List<ORecord<?>> response = new ArrayList<ORecord<?>>();
      for (ORecord<?> rec : db.browseClass(urlParts[2])) {
        if (limit > 0 && response.size() >= limit) break;

        response.add(rec);
      }

      if (response != null && response.size() > 0) {
        sendRecordsContent(iRequest, response);
      } else {
        final StringWriter buffer = new StringWriter();
        final OJSONWriter json = new OJSONWriter(buffer, JSON_FORMAT);
        json.beginObject();
        exportClassSchema(db, json, db.getMetadata().getSchema().getClass(urlParts[2]));
        json.endObject();
        sendTextContent(
            iRequest,
            OHttpUtils.STATUS_OK_CODE,
            "OK",
            null,
            OHttpUtils.CONTENT_JSON,
            buffer.toString());
      }
    } finally {
      if (db != null) OSharedDocumentDatabase.release(db);
    }
    return false;
  }