Esempio n. 1
0
  public void testIndexMapRemoveItemInTx() throws Exception {
    final ODocument docOne = new ODocument();
    docOne.save();

    final ODocument docTwo = new ODocument();
    docTwo.save();

    final ODocument docThree = new ODocument();
    docThree.save();

    Map<String, ORID> map = new HashMap<String, ORID>();

    map.put("key1", docOne.getIdentity());
    map.put("key2", docTwo.getIdentity());
    map.put("key3", docThree.getIdentity());

    final ODocument document = new ODocument("LinkMapIndexTestClass");
    document.field("linkMap", map);
    document.save();

    try {
      database.begin();
      final ODocument loadedDocument = database.load(document.getIdentity());
      loadedDocument.<Map<String, ORID>>field("linkMap").remove("key2");
      loadedDocument.save();
      database.commit();
    } catch (Exception e) {
      database.rollback();
      throw e;
    }

    final List<ODocument> resultByKey =
        database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute();

    Assert.assertNotNull(resultByKey);
    Assert.assertEquals(resultByKey.size(), 2);
    for (ODocument d : resultByKey) {
      Assert.assertTrue(d.containsField("key"));
      Assert.assertTrue(d.containsField("rid"));

      if (!d.field("key").equals("key1") && !d.field("key").equals("key3")) {
        Assert.fail("Unknown key found: " + d.field("key"));
      }
    }

    final List<ODocument> resultByValue =
        database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute();

    Assert.assertNotNull(resultByValue);
    Assert.assertEquals(resultByValue.size(), 2);
    for (ODocument d : resultByValue) {
      Assert.assertTrue(d.containsField("key"));
      Assert.assertTrue(d.containsField("rid"));

      if (!d.field("key").equals(docOne.getIdentity())
          && !d.field("key").equals(docThree.getIdentity())) {
        Assert.fail("Unknown key found: " + d.field("key"));
      }
    }
  }
Esempio n. 2
0
  public void testIndexMapAddItem() {
    final ODocument docOne = new ODocument();
    docOne.save();

    final ODocument docTwo = new ODocument();
    docTwo.save();

    final ODocument docThree = new ODocument();
    docThree.save();

    Map<String, ORID> map = new HashMap<String, ORID>();

    map.put("key1", docOne.getIdentity());
    map.put("key2", docTwo.getIdentity());

    final ODocument document = new ODocument("LinkMapIndexTestClass");
    document.field("linkMap", map);
    document.save();

    database
        .command(
            new OCommandSQL(
                "UPDATE "
                    + document.getIdentity()
                    + " put linkMap = 'key3', "
                    + docThree.getIdentity()))
        .execute();

    final List<ODocument> resultByKey =
        database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute();

    Assert.assertNotNull(resultByKey);
    Assert.assertEquals(resultByKey.size(), 3);
    for (ODocument d : resultByKey) {
      Assert.assertTrue(d.containsField("key"));
      Assert.assertTrue(d.containsField("rid"));

      if (!d.field("key").equals("key1")
          && !d.field("key").equals("key2")
          && !d.field("key").equals("key3")) {
        Assert.fail("Unknown key found: " + d.field("key"));
      }
    }

    final List<ODocument> resultByValue =
        database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute();

    Assert.assertNotNull(resultByValue);
    Assert.assertEquals(resultByValue.size(), 3);
    for (ODocument d : resultByValue) {
      Assert.assertTrue(d.containsField("key"));
      Assert.assertTrue(d.containsField("rid"));

      if (!d.field("key").equals(docOne.getIdentity())
          && !d.field("key").equals(docTwo.getIdentity())
          && !d.field("key").equals(docThree.getIdentity())) {
        Assert.fail("Unknown key found: " + d.field("key"));
      }
    }
  }
Esempio n. 3
0
  public void testIndexMapRemove() {
    final ODocument docOne = new ODocument();
    docOne.save();

    final ODocument docTwo = new ODocument();
    docTwo.save();

    final ODocument docThree = new ODocument();
    docThree.save();

    Map<String, ORID> map = new HashMap<String, ORID>();

    map.put("key1", docOne.getIdentity());
    map.put("key2", docTwo.getIdentity());

    final ODocument document = new ODocument("LinkMapIndexTestClass");
    document.field("linkMap", map);
    document.save();
    document.delete();

    final List<ODocument> resultByKey =
        database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute();

    Assert.assertNotNull(resultByKey);
    Assert.assertEquals(resultByKey.size(), 0);

    final List<ODocument> resultByValue =
        database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute();

    Assert.assertNotNull(resultByValue);
    Assert.assertEquals(resultByValue.size(), 0);
  }
  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();
  }
Esempio n. 5
0
  @Test
  public void multipleDatabasesSameThread() throws IOException {
    OGraphDatabase db1 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");
    ODocument doc1 = db1.createVertex();

    doc1.field("key", "value");
    doc1.save();
    db1.close();

    OGraphDatabase db2 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");

    ODocument doc2 = db2.createVertex();
    doc2.field("key", "value");
    doc2.save();
    db2.close();

    db1 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");

    final List<?> result =
        db1.query(
            new OSQLSynchQuery<ODocument>(
                "select out[weight=3].size() from V where out.size() > 0"));

    doc1 = db1.createVertex();
    doc1.field("newkey", "newvalue");
    doc1.save();
    db1.close();
  }
Esempio n. 6
0
  /**
   * Saves the edge's document.
   *
   * @param iClusterName Cluster name or null to use the default "E"
   */
  public void save(final String iClusterName) {
    checkIfAttached();
    graph.setCurrentGraphInThreadLocal();

    if (rawElement instanceof ODocument)
      if (iClusterName != null) ((ODocument) rawElement).save(iClusterName);
      else ((ODocument) rawElement).save();
  }
  @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();
    }
  }
  @Test
  public void testFindByParent() throws Exception {
    ODocument parent1 =
        new ODocument("Node")
            .field("title", "ref1")
            .field("titleasc", "ref1")
            .field("description", "desc")
            .field("descriptionMarkup", "default")
            .field("created", 1L)
            .field("modified", 2L);
    parent1.save();
    ODocument parent2 =
        new ODocument("Node")
            .field("title", "ref2")
            .field("titleasc", "ref2")
            .field("description", "desc")
            .field("descriptionMarkup", "default")
            .field("created", 1L)
            .field("modified", 2L);
    parent2.save();

    String id1 = parent1.getIdentity().toString();
    String id2 = parent2.getIdentity().toString();

    IPeriod period1 = new Period();
    period1.setFromEntry("1.1585");
    period1.setToEntry("2.1585");
    period1.setCreated(1L);
    period1.setModified(2L);
    period1.setParentId(id1);
    repository.save(period1);

    IPeriod period2 = new Period();
    period2.setFromEntry("1929");
    period2.setToEntry("1930");
    period2.setCreated(1L);
    period2.setModified(2L);
    period2.setParentId(id1);
    repository.save(period2);

    IPeriod period3 = new Period();
    period3.setFromEntry("1.1.1700");
    period3.setToEntry("5.6.1702");
    period3.setCreated(1L);
    period3.setModified(2L);
    period3.setParentId(id1);
    repository.save(period3);

    List<IPeriod> periods = repository.findByParent(id1);

    assertTrue(periods.size() == 3);

    periods = repository.findByParent(id2);
    assertTrue(periods.size() == 0);
  }
  /** Execute the INSERT and return the ODocument object created. */
  public Object execute(final Map<Object, Object> iArgs) {
    if (newRecords == null && content == null)
      throw new OCommandExecutionException(
          "Cannot execute the command because it has not been parsed yet");

    final OCommandParameters commandParameters = new OCommandParameters(iArgs);
    if (indexName != null) {
      if (newRecords == null) throw new OCommandExecutionException("No key/value found");

      final OIndex<?> index = getDatabase().getMetadata().getIndexManager().getIndex(indexName);
      if (index == null)
        throw new OCommandExecutionException("Target index '" + indexName + "' not found");

      // BIND VALUES
      Map<String, Object> result = null;

      for (Map<String, Object> candidate : newRecords) {
        index.put(
            getIndexKeyValue(commandParameters, candidate),
            getIndexValue(commandParameters, candidate));
        result = candidate;
      }

      // RETURN LAST ENTRY
      return new ODocument(result);
    } else {

      // CREATE NEW DOCUMENTS
      final List<ODocument> docs = new ArrayList<ODocument>();
      if (newRecords != null) {
        for (Map<String, Object> candidate : newRecords) {
          final ODocument doc = className != null ? new ODocument(className) : new ODocument();
          OSQLHelper.bindParameters(doc, candidate, commandParameters, context);

          if (clusterName != null) {
            doc.save(clusterName);
          } else {
            doc.save();
          }
          docs.add(doc);
        }

        if (docs.size() == 1) return docs.get(0);
        else return docs;
      } else if (content != null) {
        final ODocument doc = className != null ? new ODocument(className) : new ODocument();
        doc.merge(content, true, false);
        doc.save();
        return doc;
      }
    }
    return null;
  }
  @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 testConvertToDocument() throws Exception {
    ODocument parent =
        new ODocument("Node")
            .field("title", "ref1")
            .field("titleasc", "ref1")
            .field("description", "desc")
            .field("descriptionMarkup", "default")
            .field("created", 1L)
            .field("modified", 2L);
    parent.save();

    IPeriod period = new Period();
    period.setFromEntry("1.1585");
    period.setToEntry("2.1585");
    period.setComment("comment");
    period.addFuzzyFromFlag('c');
    period.addFuzzyToFlag('?');
    period.setCreated(1L);
    period.setModified(2L);
    period.setParentId(parent.getIdentity().toString());
    period.setParentModel("Node");

    // first without id
    ODocument document = repository.convertToDocument(period);

    assertEquals("1.1585", document.field("fromEntry"));
    assertEquals("2.1585", document.field("toEntry"));
    assertEquals("G", document.field("fromEntryCalendar"));
    assertEquals("G", document.field("toEntryCalendar"));
    assertEquals("c", document.field("fromFuzzyFlags"));
    assertEquals("?", document.field("toFuzzyFlags"));
    assertEquals(new Long(2299970L), document.field("fromJD", Long.class));
    assertEquals(new Long(2300028L), document.field("toJD", Long.class));
    assertEquals("comment", document.field("comment"));
    assertEquals(new Long(1L), document.field("created", Long.class));
    assertEquals(new Long(2L), document.field("modified", Long.class));
    assertEquals(parent.getIdentity().toString(), document.field("parent", String.class));

    // save document to get id
    document.save();
    String id = document.getIdentity().toString();

    // set id and test conversion
    period.setId(id);

    ODocument newDocument = repository.convertToDocument(period);

    assertEquals(document.getIdentity().toString(), newDocument.getIdentity().toString());
    assertEquals(parent.getIdentity(), newDocument.field("parent", ORecordId.class));
  }
  private void initExpandSkipLimit(ODatabaseDocumentTx db) {
    db.getMetadata().getSchema().createClass("ExpandSkipLimit");

    for (int i = 0; i < 5; i++) {
      ODocument doc = new ODocument("ExpandSkipLimit");
      doc.field("nnum", i);
      doc.save();
      ODocument parent = new ODocument("ExpandSkipLimit");
      parent.field("parent", true);
      parent.field("num", i);
      parent.field("linked", doc);
      parent.save();
    }
  }
Esempio n. 13
0
  public static ODocument updateProfile(
      ODocument profile,
      JsonNode nonAppUserAttributes,
      JsonNode privateAttributes,
      JsonNode friendsAttributes,
      JsonNode appUsersAttributes)
      throws Exception {
    if (nonAppUserAttributes != null) {
      ODocument attrObj = profile.field(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
      if (attrObj == null) attrObj = new ODocument(UserDao.USER_ATTRIBUTES_CLASS);
      attrObj.fromJSON(nonAppUserAttributes.toString());
      PermissionsHelper.grantRead(
          attrObj, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
      PermissionsHelper.grantRead(attrObj, RoleDao.getRole(DefaultRoles.ANONYMOUS_USER.toString()));
      PermissionsHelper.grantRead(attrObj, RoleDao.getFriendRole());
      profile.field(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER, attrObj);
      attrObj.save();
    }
    if (privateAttributes != null) {
      ODocument attrObj = profile.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
      if (attrObj == null) attrObj = new ODocument(UserDao.USER_ATTRIBUTES_CLASS);
      attrObj.fromJSON(privateAttributes.toString());
      PermissionsHelper.grant(
          attrObj, Permissions.ALLOW, getOUserByUsername(getUsernameByProfile(profile)));
      profile.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER, attrObj);
      attrObj.save();
    }
    if (friendsAttributes != null) {
      ODocument attrObj = profile.field(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
      if (attrObj == null) attrObj = new ODocument(UserDao.USER_ATTRIBUTES_CLASS);
      attrObj.fromJSON(friendsAttributes.toString());
      PermissionsHelper.grantRead(attrObj, RoleDao.getFriendRole());
      profile.field(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER, attrObj);
      attrObj.save();
    }
    if (appUsersAttributes != null) {
      ODocument attrObj = profile.field(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);
      if (attrObj == null) attrObj = new ODocument(UserDao.USER_ATTRIBUTES_CLASS);
      attrObj.fromJSON(appUsersAttributes.toString());
      PermissionsHelper.grantRead(
          attrObj, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
      PermissionsHelper.grantRead(attrObj, RoleDao.getFriendRole());
      profile.field(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER, attrObj);
      attrObj.save();
    }

    profile.save();
    return profile;
  }
    @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();
      }
    }
  @Test
  public void testConvertToEntity() throws Exception {
    ODocument parent =
        new ODocument("Node")
            .field("title", "ref1")
            .field("titleasc", "ref1")
            .field("description", "desc")
            .field("descriptionMarkup", "default")
            .field("created", 1L)
            .field("modified", 2L);
    parent.save();

    ODocument document =
        new ODocument("Period")
            .field("fromEntryCalendar", "G")
            .field("toEntryCalendar", "G")
            .field("fromEntry", "1.1585")
            .field("toEntry", "2.1585")
            .field("from", 2299970L)
            .field("to", 2300028L)
            .field("type", "period")
            .field("comment", "comment")
            .field("fromFuzzyFlags", "x?")
            .field("toFuzzyFlags", "c?")
            .field("parent", parent)
            .field("created", 1L)
            .field("modified", 2L);
    // persist to database to create id
    document.save();

    IPeriod period = repository.convertToEntity(document);

    assertEquals("1.1585", period.getFromEntry());
    assertEquals("2.1585", period.getToEntry());
    assertEquals("G", period.getFromEntryCalendar());
    assertEquals("G", period.getToEntryCalendar());
    assertEquals("period", period.getType());
    assertEquals(new Long(2299970L), period.getFromJD());
    assertEquals(new Long(2300028L), period.getToJD());
    assertEquals("comment", period.getComment());
    assertArrayEquals(new char[] {'?'}, period.getFuzzyFromFlags());
    assertArrayEquals(new char[] {'c', '?'}, period.getFuzzyToFlags());
    assertEquals(new Long(1L), period.getCreated());
    assertEquals(new Long(2L), period.getModified());
    assertEquals(parent.getIdentity().toString(), period.getParentId());
    assertEquals("Node", period.getParentModel());
    assertEquals(document.getIdentity().toString(), period.getId());
  }
  @Test
  public void testConvertToDocument() throws Exception {
    IPictogram pictogram = new Pictogram();
    pictogram.setTitle("title");
    pictogram.setFileIdentifier("test.txt");

    ODocument document = repository.convertToDocument(pictogram);

    assertEquals("title", document.field("title"));
    assertEquals("test.txt", document.field("fileIdentifier"));

    // class name should be correct
    assertEquals("Pictogram", document.getClassName());

    // save document to get id
    document.save();
    String id = document.getIdentity().toString();

    // set id and test conversion
    pictogram.setId(id);

    ODocument newDocument = repository.convertToDocument(pictogram);

    assertEquals(document.getIdentity().toString(), newDocument.getIdentity().toString());
  }
  @Test
  public void testQueryIsolation() {
    OGraphDatabase db = new OGraphDatabase(url);
    db.open("admin", "admin");

    try {
      db.begin();

      ODocument v1 = db.createVertex();
      v1.field("purpose", "testQueryIsolation");
      v1.save();

      if (!url.startsWith("remote")) {
        List<OIdentifiable> result =
            db.query(
                new OSQLSynchQuery<Object>("select from V where purpose = 'testQueryIsolation'"));
        Assert.assertEquals(result.size(), 1);
      }

      db.commit();

      List<OIdentifiable> result =
          db.query(
              new OSQLSynchQuery<Object>("select from V where purpose = 'testQueryIsolation'"));
      Assert.assertEquals(result.size(), 1);

    } finally {
      db.close();
    }
  }
Esempio n. 18
0
  @Test
  public void testPagination() {
    Map<String, Object> fileContents = new HashMap<String, Object>();
    final int TOTAL_POSTS = 5;
    final int PER_PAGE = 2;

    for (int i = 1; i <= TOTAL_POSTS; i++) {
      fileContents.put("name", "dummyfile" + i);

      ODocument doc = new ODocument("post");
      doc.fields(fileContents);
      boolean cached =
          fileContents.get("cached") != null
              ? Boolean.valueOf((String) fileContents.get("cached"))
              : true;
      doc.field("cached", cached);
      doc.save();
    }

    int iterationCount = 0;
    int start = 0;
    db.setLimit(PER_PAGE);

    while (start < TOTAL_POSTS) {
      db.setStart(start);
      List<ODocument> posts = db.getAllContent("post");
      Assert.assertEquals(
          "dummyfile" + (1 + (PER_PAGE * iterationCount)), posts.get(0).field("name"));
      //            Assert.assertEquals("dummyfile" + (PER_PAGE + (PER_PAGE * iterationCount)),
      // posts.get(posts.size()-1).field("name"));
      iterationCount++;
      start += PER_PAGE;
    }
    Assert.assertEquals(Math.round(TOTAL_POSTS / (1.0 * PER_PAGE) + 0.4), iterationCount);
  }
Esempio n. 19
0
  @Test
  public void updateWithWildcardsOnSetAndWhere() {

    ODocument doc = new ODocument("Person");
    doc.field("name", "Raf");
    doc.field("city", "Torino");
    doc.field("gender", "fmale");
    doc.save();
    checkUpdatedDoc(database, "Raf", "Torino", "fmale");

    /* THESE COMMANDS ARE OK */
    OCommandSQL updatecommand =
        new OCommandSQL("update Person set gender = 'female' where name = 'Raf'");
    database.command(updatecommand).execute("Raf");
    checkUpdatedDoc(database, "Raf", "Torino", "female");

    updatecommand = new OCommandSQL("update Person set city = 'Turin' where name = ?");
    database.command(updatecommand).execute("Raf");
    checkUpdatedDoc(database, "Raf", "Turin", "female");

    updatecommand = new OCommandSQL("update Person set gender = ? where name = 'Raf'");
    database.command(updatecommand).execute("F");
    checkUpdatedDoc(database, "Raf", "Turin", "F");

    updatecommand = new OCommandSQL("update Person set gender = ?, city = ? where name = 'Raf'");
    database.command(updatecommand).execute("FEMALE", "TORINO");
    checkUpdatedDoc(database, "Raf", "TORINO", "FEMALE");

    updatecommand = new OCommandSQL("update Person set gender = ? where name = ?");
    database.command(updatecommand).execute("f", "Raf");
    checkUpdatedDoc(database, "Raf", "TORINO", "f");
  }
 private ODocument createPerson(final ODatabaseDocumentTx db) {
   ODocument doc = db.newInstance("Person");
   doc.field("name", "Luke");
   doc.field("surname", "Skywalker");
   doc.field("city", new ODocument("City").field("name", "Rome").field("country", "Italy"));
   doc.save();
   return doc;
 }
  @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();
  }
 @Override
 protected void _save() {
   final ODocument edge = getDocument();
   final List<Property> propertyList = GraphDBPropertyUtils.listProperties(this.getClass());
   GraphDB.serializeFiledsOfPojoToGraphDocument(propertyList, this, edge);
   if (outVertex != null) outVertex.save();
   if (inVertex != null) inVertex.save();
   edge.save();
   GraphDB.serializeFiledsOfGraphDocumentToPojo(propertyList, edge, this);
 }
  @Test
  public void updateTest() {
    String preupdateString = "preupdate";
    String user0 = "user0";
    String user1 = "user1";
    String user2 = "user2";

    // Manually insert three documents
    for (String key : Arrays.asList(user0, user1, user2)) {
      ODocument doc = new ODocument(CLASS);
      for (int i = 0; i < NUM_FIELDS; i++) {
        doc.field(FIELD_PREFIX + i, preupdateString);
      }
      doc.save();
      orientDBDictionary.put(key, doc);
    }

    HashMap<String, ByteIterator> updateMap = new HashMap<>();
    for (int i = 0; i < NUM_FIELDS; i++) {
      updateMap.put(
          FIELD_PREFIX + i,
          new StringByteIterator(buildDeterministicValue(user1, FIELD_PREFIX + i)));
    }

    orientDBClient.update(CLASS, user1, updateMap);

    // Ensure that user0 record was not changed
    ODocument result = orientDBDictionary.get(user0);
    for (int i = 0; i < NUM_FIELDS; i++) {
      assertEquals(
          "Assert first row fields contain preupdateString",
          result.field(FIELD_PREFIX + i),
          preupdateString);
    }

    // Check that all the columns have expected values for user1 record
    result = orientDBDictionary.get(user1);
    for (int i = 0; i < NUM_FIELDS; i++) {
      assertEquals(
          "Assert updated row fields are correct",
          result.field(FIELD_PREFIX + i),
          updateMap.get(FIELD_PREFIX + i).toString());
    }

    // Ensure that user2 record was not changed
    result = orientDBDictionary.get(user2);
    for (int i = 0; i < NUM_FIELDS; i++) {
      assertEquals(
          "Assert third row fields contain preupdateString",
          result.field(FIELD_PREFIX + i),
          preupdateString);
    }
  }
Esempio n. 24
0
 public static void logout(String pushToken) throws SqlInjectionException {
   ODocument user = getCurrentUser();
   ODocument systemProps = user.field(UserDao.ATTRIBUTES_SYSTEM);
   ArrayList<ODocument> loginInfos = systemProps.field(UserDao.USER_LOGIN_INFO);
   for (ODocument loginInfo : loginInfos) {
     if (loginInfo.field(UserDao.USER_PUSH_TOKEN) != null
         && loginInfo.field(UserDao.USER_PUSH_TOKEN).equals(pushToken)) {
       loginInfos.remove(loginInfo);
       break;
     }
   }
   systemProps.save();
 }
  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();
      }
    }
  }
Esempio n. 26
0
 public static void removeSocialLoginTokens(ODocument user, String socialNetwork)
     throws ODatabaseException {
   DbHelper.requestTransaction();
   try {
     ODocument systemProps = user.field(UserDao.ATTRIBUTES_SYSTEM);
     Map<String, ODocument> ssoTokens = systemProps.field(UserDao.SOCIAL_LOGIN_INFO);
     if (ssoTokens == null) {
       throw new ODatabaseException(socialNetwork + " is not linked with this account");
     } else {
       ssoTokens.remove(socialNetwork);
       systemProps.field(UserDao.SOCIAL_LOGIN_INFO, ssoTokens);
       user.field(UserDao.ATTRIBUTES_SYSTEM, systemProps);
       systemProps.save();
       user.save();
       if (Logger.isDebugEnabled()) Logger.debug("saved tokens for user ");
       DbHelper.commitTransaction();
     }
   } catch (Exception e) {
     e.printStackTrace();
     DbHelper.rollbackTransaction();
     throw new ODatabaseException("unable to add tokens");
   }
 }
Esempio n. 27
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);
   }
 }
Esempio n. 28
0
  public static ODocument updateProfile(
      String username,
      String role,
      JsonNode nonAppUserAttributes,
      JsonNode privateAttributes,
      JsonNode friendsAttributes,
      JsonNode appUsersAttributes)
      throws Exception {
    try {
      ORole newORole = RoleDao.getRole(role);
      if (newORole == null) throw new InvalidParameterException(role + " is not a role");
      if (!RoleService.isAssignable(newORole))
        throw new RoleIsNotAssignableException("Role " + role + " is not assignable");
      ORID newRole = newORole.getDocument().getIdentity();
      UserDao udao = UserDao.getInstance();
      ODocument profile = udao.getByUserName(username);
      if (profile == null) throw new InvalidParameterException(username + " is not a user");
      profile =
          updateProfile(
              profile,
              nonAppUserAttributes,
              privateAttributes,
              friendsAttributes,
              appUsersAttributes);

      Set<OIdentifiable> roles =
          (Set<OIdentifiable>) ((ODocument) profile.field("user")).field("roles");
      // extracts the role skipping the friends ones
      String oldRole = null;
      for (OIdentifiable r : roles) {
        oldRole = ((String) ((ODocument) r.getRecord()).field("name"));
        if (!oldRole.startsWith(RoleDao.FRIENDS_OF_ROLE)) {
          break;
        }
      }
      ORole oldORole = RoleDao.getRole(oldRole);
      // TODO: update role
      OUser ouser = DbHelper.getConnection().getMetadata().getSecurity().getUser(username);
      ouser.getRoles().remove(oldORole);
      ouser.addRole(newORole);
      ouser.save();
      profile.save();
      profile.reload();

      return profile;
    } catch (Exception e) {
      throw e;
    }
  } // updateProfile with role
Esempio n. 29
0
  public void testIndexMapSQL() {
    final ODocument docOne = new ODocument();
    docOne.save();

    final ODocument docTwo = new ODocument();
    docTwo.save();

    Map<String, ORID> map = new HashMap<String, ORID>();

    map.put("key1", docOne.getIdentity());
    map.put("key2", docTwo.getIdentity());

    final ODocument document = new ODocument("LinkMapIndexTestClass");
    document.field("linkMap", map);
    document.save();

    final List<ODocument> resultByKey =
        database.query(
            new OSQLSynchQuery<ODocument>(
                "select * from LinkMapIndexTestClass where linkMap containskey ?"),
            "key1");
    Assert.assertNotNull(resultByKey);
    Assert.assertEquals(resultByKey.size(), 1);

    Assert.assertEquals(map, document.field("linkMap"));

    final List<ODocument> resultByValue =
        database.query(
            new OSQLSynchQuery<ODocument>(
                "select * from LinkMapIndexTestClass where linkMap  containsvalue ?"),
            docOne.getIdentity());
    Assert.assertNotNull(resultByValue);
    Assert.assertEquals(resultByValue.size(), 1);

    Assert.assertEquals(map, document.field("linkMap"));
  }
Esempio n. 30
0
  public static void addSocialLoginTokens(ODocument user, UserInfo userInfo)
      throws ODatabaseException {
    DbHelper.requestTransaction();
    try {
      ODocument systemProps = user.field(UserDao.ATTRIBUTES_SYSTEM);
      Map<String, ODocument> ssoTokens = systemProps.field(UserDao.SOCIAL_LOGIN_INFO);
      if (ssoTokens == null) {
        ssoTokens = new HashMap<String, ODocument>();
      }

      String jsonRep = userInfo.toJson();
      ssoTokens.put(userInfo.getFrom(), (ODocument) new ODocument().fromJSON(jsonRep));
      systemProps.field(UserDao.SOCIAL_LOGIN_INFO, ssoTokens);
      user.field(UserDao.ATTRIBUTES_SYSTEM, systemProps);
      systemProps.save();
      user.save();
      if (Logger.isDebugEnabled()) Logger.debug("saved tokens for user ");
      DbHelper.commitTransaction();

    } catch (Exception e) {
      DbHelper.rollbackTransaction();
      throw new ODatabaseException("unable to add tokens");
    }
  }