@Test
  public void queryProjectionOk() {
    database.open("admin", "admin");

    List<ODocument> result =
        database
            .command(
                new OSQLSynchQuery<ODocument>(
                    " select nick, followings, followers from Profile where nick is defined and followings is defined and followers is defined"))
            .execute();

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

    for (ODocument d : result) {
      String[] colNames = d.fieldNames();
      Assert.assertEquals(colNames.length, 3);
      Assert.assertEquals(colNames[0], "nick");
      Assert.assertEquals(colNames[1], "followings");
      Assert.assertEquals(colNames[2], "followers");

      Assert.assertNull(d.getClassName());
      Assert.assertEquals(d.getRecordType(), ODocument.RECORD_TYPE);
    }

    database.close();
  }
Esempio n. 2
0
 static String prepareResponseToJson(List<ODocument> listOfDoc) {
   response().setContentType("application/json");
   try {
     for (ODocument doc : listOfDoc) {
       doc.detach();
       if (doc.field("user") instanceof ODocument) {
         OMVRBTreeRIDSet roles = ((ODocument) doc.field("user")).field("roles");
         if (roles.size() > 1) {
           Iterator<OIdentifiable> it = roles.iterator();
           while (it.hasNext()) {
             if (((ODocument) it.next().getRecord())
                 .field("name")
                 .toString()
                 .startsWith(FriendShipService.FRIEND_ROLE_NAME)) {
               it.remove();
             }
           }
         }
       }
     }
     return JSONFormats.prepareResponseToJson(listOfDoc, JSONFormats.Formats.USER);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
  /**
   * helper to load nodes relation to document
   *
   * @param document relationLink document/link
   * @param direction "in" or "out"
   * @return INode instance or null
   */
  private @Nullable INode getRelatedEntity(ODocument document, String direction) {
    Object nodeO = document.field(direction, ORecordId.class);
    if (nodeO == null) {
      logger.error(
          "Could not create related entity while converting relation with direction " + direction);
      return null;
    }
    if (nodeO instanceof ORecordId) nodeO = repositoryFactory.getDb().load((ORecordId) nodeO);
    if (nodeO == null) {
      logger.error("Invalid record in direction " + direction + ": " + document.toString());
      return null;
    }

    // convert
    ODocument nodeDoc = (ODocument) nodeO;

    // slim node: just set title and id
    INode node = new Node();
    node.setTitle(nodeDoc.field("title"));
    node.setId(nodeDoc.getIdentity().toString());

    return node;

    /*
    old -not performant
    String id;
    if (relationO instanceof OIdentifiable) id = ((ORecordId)relationO).getIdentity().toString();
    else {
    	logger.error("Invalid class type: " + relationO.getClass().getName());
    	return null;
    }

    return nodeRepository.find(id);*/
  }
  @Override
  public void loadDataModel(ODatabaseDocumentTx db) {
    if (piutang != null) {
      if (paging != null) {
        int tmp = paging.getCurentHalaman() - 1 * paging.getJumlahPerHalaman();
        if (tmp < 0) {
          tmp = 0;
        }

        model =
            dao.getAllByColumn(
                db, PiutangdDao.piutang, piutang.getIdentity(), tmp, paging.getJumlahPerHalaman());

        //				pelanggans=new ArrayList<ODocument>();
        //				for (ODocument oDocument : model) {
        //					ODocument tmp2=oDocument.field(PenjualanDao.pelanggan);
        //					tmp2.field(PelangganDao.name);
        //					pelanggans.add(tmp2);
        //				}

      } else {
        model =
            (List<ODocument>)
                getDao().getAllByColumn(db, PiutangdDao.piutang, piutang.getIdentity());
      }
    } else {
      model = new ArrayList<ODocument>();
    }
  }
Esempio n. 5
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);
  }
  @Test
  public void queryGroupByNoNulls() {
    database.command(new OCommandSQL("create class GroupByTest extends V")).execute();
    try {
      database.command(new OCommandSQL("insert into GroupByTest set location = 'Rome'")).execute();
      database
          .command(new OCommandSQL("insert into GroupByTest set location = 'Austin'"))
          .execute();
      database
          .command(new OCommandSQL("insert into GroupByTest set location = 'Austin'"))
          .execute();

      final List<ODocument> result =
          database
              .command(
                  new OSQLSynchQuery<ODocument>(
                      "select location, count(*) from GroupByTest group by location"))
              .execute();

      Assert.assertEquals(result.size(), 2);

      for (ODocument d : result) {
        Assert.assertNotNull(d.field("location"), "Found null in resultset with groupby");
      }

    } finally {
      database.command(new OCommandSQL("delete vertex GroupByTest")).execute();
      database.command(new OCommandSQL("drop class GroupByTest UNSAFE")).execute();
    }
  }
Esempio n. 7
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");
  }
  @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);
    }
  }
Esempio n. 9
0
  public void getEntries(final Collection<?> keys, IndexEntriesResultListener resultListener) {
    checkForRebuild();

    final List<Object> sortedKeys = new ArrayList<Object>(keys);
    Collections.sort(sortedKeys, ODefaultComparator.INSTANCE);

    acquireSharedLock();
    try {
      for (Object key : sortedKeys) {
        key = getCollatingValue(key);

        final OIdentifiable val = indexEngine.get(key);
        if (val != null) {
          final ODocument document = new ODocument();
          document.field("key", key);
          document.field("rid", val.getIdentity());
          document.unsetDirty();

          if (!resultListener.addResult(document)) return;
        }
      }
    } finally {
      releaseSharedLock();
    }
  }
  @Override
  public RESULT onTrigger(TYPE iType, ORecord iRecord) {
    // TODO Auto-generated method stub
    if (iRecord instanceof ODocument) {

      switch (iType) {
        case BEFORE_CREATE:
          {
            String instant = Instant.now().toString();

            ((ODocument) iRecord).field("createdAt", instant);
            ((ODocument) iRecord).field("updatedAt", instant);

            return RESULT.RECORD_CHANGED;
          }

        case BEFORE_UPDATE:
          {
            String instant = Instant.now().toString();

            ((ODocument) iRecord).field("updatedAt", instant);

            return RESULT.RECORD_CHANGED;
          }

        default:
          break;
      }
    }
    return RESULT.RECORD_NOT_CHANGED;
  }
Esempio n. 11
0
  /**
   * * Creates an entry into the ODocument-Collection and create a new Class named "collectionName"
   *
   * @param collectionName
   * @return
   * @throws Throwable
   */
  public ODocument create(String collectionName) throws Throwable {
    Logger.trace("Method Start");
    try {
      if (existsCollection(collectionName))
        throw new InvalidCollectionException("Collection " + collectionName + " already exists");
    } catch (SqlInjectionException e) {
      throw new InvalidCollectionException(e);
    }
    ODocument doc = super.create();
    doc.field("name", collectionName);
    save(doc);

    // create new class
    OClass documentClass = db.getMetadata().getSchema().getClass(CLASS_NODE_NAME);
    db.getMetadata().getSchema().createClass(collectionName, documentClass);

    // grants to the new class
    ORole registeredRole = RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString());
    ORole anonymousRole = RoleDao.getRole(DefaultRoles.ANONYMOUS_USER.toString());
    registeredRole.addRule(
        ODatabaseSecurityResources.CLASS + "." + collectionName, ORole.PERMISSION_ALL);
    registeredRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + collectionName, ORole.PERMISSION_ALL);
    anonymousRole.addRule(
        ODatabaseSecurityResources.CLASS + "." + collectionName, ORole.PERMISSION_READ);
    anonymousRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + collectionName, ORole.PERMISSION_READ);
    PermissionsHelper.grantRead(doc, registeredRole);
    PermissionsHelper.grantRead(doc, anonymousRole);
    Logger.trace("Method End");
    return doc;
  } // getNewModelInstance(String collectionName)
Esempio n. 12
0
 public static void resetUserPasswordFinalStep(String username, String newPassword)
     throws SqlInjectionException, ResetPasswordException {
   ODocument user = UserDao.getInstance().getByUserName(username);
   ODocument ouser = ((ODocument) user.field("user"));
   ouser.field("password", newPassword).save();
   ResetPwdDao.getInstance().setResetPasswordDone(username);
 }
  public void testSelectMap() {
    List<ODocument> result =
        database.query(
            new OSQLSynchQuery<ODocument>(
                "select list( 1, 4, 5.00, 'john', map( 'kAA', 'vAA' ) ) as myresult"));

    Assert.assertEquals(result.size(), 1);

    ODocument document = result.get(0);
    List myresult = document.field("myresult");
    Assert.assertNotNull(myresult);

    Assert.assertTrue(myresult.remove(Integer.valueOf(1)));
    Assert.assertTrue(myresult.remove(Integer.valueOf(4)));
    Assert.assertTrue(myresult.remove(Float.valueOf(5)));
    Assert.assertTrue(myresult.remove("john"));

    Assert.assertEquals(myresult.size(), 1);

    Assert.assertTrue(myresult.get(0) instanceof Map, "The object is: " + myresult.getClass());
    Map map = (Map) myresult.get(0);

    String value = (String) map.get("kAA");
    Assert.assertEquals(value, "vAA");

    Assert.assertEquals(map.size(), 1);
  }
  private static boolean supportNullValues(OIndex<?> index) {
    final ODocument metadata = index.getMetadata();
    if (metadata == null) return false;

    final Boolean ignoreNullValues = metadata.field("ignoreNullValues");
    return Boolean.FALSE.equals(ignoreNullValues);
  }
Esempio n. 15
0
  public static void query() {
    System.out.println("Querying docs...");

    // List<ODocument> result = database.query(new ONativeSynchQuery<ODocument,
    // OQueryContextNativeSchema<ODocument>>(database,
    // "Account", new OQueryContextNativeSchema<ODocument>()) {
    // @Override
    // public boolean filter(OQueryContextNativeSchema<ODocument> iRecord) {
    // return iRecord.field("id").eq(1000l).field("name").go();
    // }
    // });

    long start = System.currentTimeMillis();

    List<ODocument> result =
        database.query(new OSQLSynchQuery<ODocument>("SELECT FROM Account WHERE id = " + 100999));

    System.out.println("Elapsed: " + (System.currentTimeMillis() - start));

    System.out.println("Query done");

    for (ODocument o : result) {
      System.out.println("id=" + o.field("id") + "\tname=" + o.field("name"));
    }
  }
Esempio n. 16
0
  public void setContentComponent(ODocument o) {
    if (o != null && modelIsTrue(o)) {
      UsrDao d = App.getUsrDao();
      code.setText(d.getCode(o));

      username.setText(d.getUsername(o));
      //				grp.setText(model.field(Usr.)+"");
      nama.setText(d.getNama(o));
      alamat.setText(d.getAlamat(o));

      kota.setText(d.getKota(o));
      noIdentitas.setText(d.getNoIdentitas(o));
      jenisIdentitas.setText(d.getJenisIdentitas(o));
      kotaLahir.setText(d.getKotaLahir(o));
      tglLahir.setText(d.tglLahirToString(o));
      jenisKelamin.setText(d.jenisKelaminToString(o));
      noTelp.setText(d.getNoTelp(o));
      noHp1.setText(d.getNoHp1(o));
      noHp2.setText(d.getNoHp2(o));
      pinBb.setText(d.getPinBb(o));
      tglMasuk.setText(d.tglMasukToString(o));
      gaji.setText(d.gajiToString(o));
      //				jenisPekerjaan.setText(model.field(Usr.JENIS_PEKERJAAN)+"");
      pendidikanTerakhir.setText(d.getPendidikanTerakhir(o));
      status.setText(d.statusToString(o));

    } else if (o != null && o.field("@class").equals(Grp.TABLE)) {
      grp.setText(o.field(Grp.NAME) + "");
    } else if (o != null && o.field("@class").equals(JenisPekerjaan.TABLE)) {
      jenisPekerjaan.setText(o.field(JenisPekerjaan.NAMA) + "");
    }
  }
 private String getAnalyzer(final OIndex classIndex) {
   // analyzer is stored only in metadata and there is no way to get default analyzer.. just assume
   // it
   final ODocument metadata = classIndex.getMetadata();
   final String analyzer = metadata != null ? metadata.<String>field(ANALYZER) : null;
   return Objects.firstNonNull(analyzer, StandardAnalyzer.class.getName());
 }
  @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();
    }
  }
 public String getTableName(int column) throws SQLException {
   ODocument currentRecord = this.resultSet.unwrap(ODocument.class);
   if (currentRecord == null) return null;
   else
     // TODO TEST getStreamableName
     return currentRecord.getSchemaClass().getName();
 }
Esempio n. 20
0
  @Test
  public void queryDate() {
    List<ODocument> result =
        database
            .command(new OSQLSynchQuery<ODocument>("select count(*) as tot from Account"))
            .execute();
    Assert.assertEquals(result.size(), 1);
    int tot = ((Number) result.get(0).field("tot")).intValue();

    int updated =
        ((Number)
                database.command(new OCommandSQL("update Account set created = date()")).execute())
            .intValue();
    Assert.assertEquals(updated, tot);

    String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

    result =
        database
            .command(
                new OSQLSynchQuery<ODocument>(
                    "select from Account where created <= date('"
                        + dateFormat.format(new Date())
                        + "', '"
                        + pattern
                        + "')"))
            .execute();

    Assert.assertEquals(result.size(), tot);
    for (ODocument d : result) {
      Assert.assertNotNull(d.field("created"));
    }
  }
  public int getColumnCount() throws SQLException {
    ODocument currentRecord = this.resultSet.unwrap(ODocument.class);

    if (currentRecord == null) return 0;

    return currentRecord.fields();
  }
Esempio n. 22
0
  /**
   * Sets values for a property in a certain ODocument
   *
   * @param propertyName the property name
   * @param values the values for the property
   * @param document the document which should contain the data
   */
  protected void setPropertyInternal(ODocument document, QName propertyName, Object... values) {
    String pName = encodeProperty(propertyName);

    if (values == null || values.length == 0) {
      document.removeField(pName);
      return;
    }

    boolean collection = isCollectionProperty(propertyName);

    if (!collection) {
      if (values.length > 1) {
        // TODO log type and property
        log.warn(
            "Attempt to set multiple values on a property that supports only one, using only the first value");
      }

      document.field(pName, convertInstance(values[0]));
    } else {
      List<Object> valueList = new ArrayList<Object>();
      for (Object value : values) {
        valueList.add(convertInstance(value));
      }
      document.field(pName, valueList, getCollectionType(propertyName));
    }
  }
  // Change the component section and save it to disk
  private void setSection(final String section, ODocument sectionDoc) {

    ODocument oldSection = getSection(section);
    try {
      if (configDoc != null) {

        configDoc.field(section, sectionDoc);
        String configFile =
            OSystemVariableResolver.resolveSystemVariables("${ORIENTDB_HOME}/config/security.json");

        // The default "security.json" file can be overridden in the server config file.
        String securityFile = getConfigProperty("server.security.file");
        if (securityFile != null) configFile = securityFile;

        String ssf = OGlobalConfiguration.SERVER_SECURITY_FILE.getValueAsString();
        if (ssf != null) configFile = ssf;

        File f = new File(configFile);
        OIOUtils.writeFile(f, configDoc.toJSON("prettyPrint"));
      }
    } catch (Exception ex) {
      configDoc.field(section, oldSection);
      OLogManager.instance()
          .error(
              this,
              "ODefaultServerSecurity.setSection(%s) Exception: %s",
              section,
              ex.getMessage());
    }
  }
  // Returns a section of the JSON document configuration as an ODocument if section is present.
  private ODocument getSection(final String section) {
    ODocument sectionDoc = null;

    try {
      if (configDoc != null) {
        if (configDoc.containsField(section)) {
          sectionDoc = configDoc.field(section);
        }
      } else {
        OLogManager.instance()
            .error(
                this,
                "ODefaultServerSecurity.getSection(%s) Configuration document is null",
                section);
      }
    } catch (Exception ex) {
      OLogManager.instance()
          .error(
              this,
              "ODefaultServerSecurity.getSection(%s) Exception: %s",
              section,
              ex.getMessage());
    }

    return sectionDoc;
  }
Esempio n. 25
0
 @Override
 public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException {
   final ODocument record = getRecord();
   ((ORecordId) record.getIdentity()).fromString(new String(iStream));
   record.setInternalStatus(STATUS.NOT_LOADED);
   return this;
 }
Esempio n. 26
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();
  }
 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;
 }
 @Test
 public void testBacktick() {
   OSQLSynchQuery sql = new OSQLSynchQuery("SELECT `foo-bar` as r from TestBacktick");
   List<ODocument> results = db.query(sql);
   assertEquals(results.size(), 1);
   ODocument doc = results.get(0);
   assertEquals(doc.field("r"), 10);
 }
Esempio n. 29
0
 private void checkUpdatedDoc(
     ODatabaseDocument database, String expectedName, String expectedCity, String expectedGender) {
   List<ODocument> result = database.query(new OSQLSynchQuery<Object>("select * from person"));
   ODocument oDoc = result.get(0);
   Assert.assertEquals(expectedName, oDoc.field("name"));
   Assert.assertEquals(expectedCity, oDoc.field("city"));
   Assert.assertEquals(expectedGender, oDoc.field("gender"));
 }
Esempio n. 30
0
 @Override
 public ODocument getParent(ODocument doc) {
   if (doc == null || doc.getSchemaClass() == null) return null;
   OClass oClass = doc.getSchemaClass();
   OProperty parent = CustomAttributes.PROP_PARENT.getValue(oClass);
   if (parent != null) return doc.field(parent.getName());
   else return null;
 }