@Test
  public void queryGroupByAndOrderBy() {
    List<ODocument> result =
        database
            .command(
                new OSQLSynchQuery<ODocument>(
                    "select location from Account group by location order by location"))
            .execute();

    Assert.assertTrue(result.size() > 1);
    String last = null;
    for (ODocument d : result) {
      if (last != null) Assert.assertTrue(last.compareTo((String) d.field("location")) < 0);
      last = d.field("location");
    }

    result =
        database
            .command(
                new OSQLSynchQuery<ODocument>(
                    "select location from Account group by location order by location desc"))
            .execute();

    Assert.assertTrue(result.size() > 1);
    last = null;
    for (ODocument d : result) {
      if (last != null) Assert.assertTrue(last.compareTo((String) d.field("location")) > 0);
      last = d.field("location");
    }
  }
  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();
    }
  }
  @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());
  }
  public void updateMultipleFields() {
    database.open("admin", "admin");

    List<OClusterPosition> positions = getValidPositions(3);

    OIdentifiable result =
        database
            .command(
                new OCommandSQL(
                    "  INSERT INTO Account SET id= 3232,name= 'my name',map= {\"key\":\"value\"},dir= '',user= #3:"
                        + positions.get(0)))
            .execute();
    Assert.assertNotNull(result);

    ODocument record = result.getRecord();

    Assert.assertEquals(record.field("id"), 3232);
    Assert.assertEquals(record.field("name"), "my name");
    Map<String, String> map = record.field("map");
    Assert.assertTrue(map.get("key").equals("value"));
    Assert.assertEquals(record.field("dir"), "");
    Assert.assertEquals(record.field("user", OType.LINK), new ORecordId(3, positions.get(0)));

    database.close();
  }
Exemple #5
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) + "");
    }
  }
Exemple #6
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();
  }
  @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;
  }
  // 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());
    }
  }
Exemple #9
0
 public void send(String message, String username)
     throws PushNotInitializedException, UserNotFoundException, SqlInjectionException,
         InvalidRequestException, IOException, UnknownHostException {
   if (Logger.isDebugEnabled())
     Logger.debug("Try to send a message (" + message + ") to " + username);
   UserDao udao = UserDao.getInstance();
   ODocument user = udao.getByUserName(username);
   if (user == null) {
     if (Logger.isDebugEnabled()) Logger.debug("User " + username + " does not exist");
     throw new UserNotFoundException("User " + username + " does not exist");
   }
   ODocument userSystemProperties = user.field(UserDao.ATTRIBUTES_SYSTEM);
   if (Logger.isDebugEnabled()) Logger.debug("userSystemProperties: " + userSystemProperties);
   List<ODocument> loginInfos = userSystemProperties.field(UserDao.USER_LOGIN_INFO);
   if (Logger.isDebugEnabled()) Logger.debug("Sending to " + loginInfos.size() + " devices");
   for (ODocument loginInfo : loginInfos) {
     String pushToken = loginInfo.field(UserDao.USER_PUSH_TOKEN);
     String vendor = loginInfo.field(UserDao.USER_DEVICE_OS);
     if (Logger.isDebugEnabled()) Logger.debug("push token: " + pushToken);
     if (Logger.isDebugEnabled()) Logger.debug("vendor: " + vendor);
     if (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(pushToken)) {
       VendorOS vos = VendorOS.getVendorOs(vendor);
       if (Logger.isDebugEnabled()) Logger.debug("vos: " + vos);
       if (vos != null) {
         IPushServer pushServer = Factory.getIstance(vos);
         pushServer.setConfiguration(getPushParameters());
         pushServer.send(message, pushToken);
       } // vos!=null
     } // (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(deviceId)
   } // for (ODocument loginInfo : loginInfos)
 } // send
  @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();
  }
Exemple #11
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);*/
  }
  @Test(dependsOnMethods = "updateCollectionsRemoveWithWhereOperator")
  public void updateMapsWithPutOperatorAndWhere() {

    ODocument doc =
        database
            .command(
                new OCommandSQL(
                    "insert into cluster:default (equaledges, name, properties) values ('no', 'updateMapsWithPutOperatorAndWhere', {} )"))
            .execute();

    Integer records =
        database
            .command(
                new OCommandSQL(
                    "update "
                        + doc.getIdentity()
                        + " put properties = 'one', 'two' where name = 'updateMapsWithPutOperatorAndWhere'"))
            .execute();

    Assert.assertEquals(records.intValue(), 1);

    ODocument loadedDoc = database.load(doc.getIdentity(), "*:-1", true);

    Assert.assertTrue(loadedDoc.field("properties") instanceof Map);

    @SuppressWarnings("unchecked")
    Map<Object, Object> entries = loadedDoc.field("properties");
    Assert.assertEquals(entries.size(), 1);

    Assert.assertNull(entries.get("round"));
    Assert.assertNull(entries.get("blaaa"));

    Assert.assertEquals(entries.get("one"), "two");
  }
  @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 testInsertUpdateTransactionWithIndex() throws Exception {

    databaseDocumentTx.close();
    databaseDocumentTx.open("admin", "admin");
    OSchema schema = databaseDocumentTx.getMetadata().getSchema();
    schema.reload();
    databaseDocumentTx.begin();
    ODocument doc = new ODocument("City");
    doc.field("name", "");
    ODocument doc1 = new ODocument("City");
    doc1.field("name", "");
    doc = databaseDocumentTx.save(doc);
    doc1 = databaseDocumentTx.save(doc1);
    databaseDocumentTx.commit();
    databaseDocumentTx.begin();
    doc = databaseDocumentTx.load(doc);
    doc1 = databaseDocumentTx.load(doc1);
    doc.field("name", "Rome");
    doc1.field("name", "Rome");
    databaseDocumentTx.save(doc);
    databaseDocumentTx.save(doc1);
    databaseDocumentTx.commit();
    OIndex idx = schema.getClass("City").getClassIndex("City.name");
    Collection<?> coll = (Collection<?>) idx.get("Rome");
    Assert.assertEquals(coll.size(), 2);
    Assert.assertEquals(idx.getSize(), 2);
  }
Exemple #16
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"));
    }
  }
Exemple #17
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));
    }
  }
Exemple #18
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);
 }
  private void createNetworkCache() throws NdexException {

    String networkIdStr = this.getTask().getResource();

    try (NetworkDAO dao = new NetworkDAO(NdexDatabase.getInstance().getAConnection())) {
      Long taskCommitId = (Long) getTask().getAttribute(TaskAttribute.readOnlyCommitId);

      String fullpath =
          Configuration.getInstance().getNdexNetworkCachePath() + taskCommitId + ".gz";

      ODocument d = dao.getNetworkDocByUUIDString(networkIdStr);
      d.reload();
      Long actId = d.field(NdexClasses.Network_P_readOnlyCommitId);

      if (!actId.equals(taskCommitId)) {
        // stop task
        getTask()
            .setMessage(
                "Network cache not created. readOnlyCommitId="
                    + actId
                    + " in db, but in task we have commitId="
                    + taskCommitId);
        return;
      }

      // create cache.

      Network n = dao.getNetworkById(UUID.fromString(networkIdStr));

      try (GZIPOutputStream w = new GZIPOutputStream(new FileOutputStream(fullpath), 16384)) {
        //  String s = mapper.writeValueAsString( original);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(w, n);
      } catch (FileNotFoundException e) {
        throw new NdexException("Can't create network cache file in server: " + fullpath);
      } catch (IOException e) {
        throw new NdexException(
            "IO Error when writing cache file: " + fullpath + ". Cause: " + e.getMessage());
      }

      // check again.
      d.reload();
      actId = d.field(NdexClasses.Network_P_readOnlyCommitId);
      if (!actId.equals(taskCommitId)) {
        // stop task
        getTask()
            .setMessage(
                "Network cache not created. Second check found network readOnlyCommitId is"
                    + actId
                    + ", task has commitId "
                    + taskCommitId);
        return;
      }

      d.field(NdexClasses.Network_P_cacheId, taskCommitId).save();
      logger.info("Cache " + actId + " created.");
      dao.commit();
    }
  }
  public void testUpdateEdgeContent() {
    final OSchema schema = database.getMetadata().getSchema();
    OClass vertex = schema.getClass("V");
    OClass edge = schema.getClass("E");

    schema.createClass("UpdateEdgeContentV", vertex);
    schema.createClass("UpdateEdgeContentE", edge);

    final ORID vOneId =
        ((ODocument)
                database.command(new OCommandSQL("create vertex UpdateEdgeContentV")).execute())
            .getIdentity();
    final ORID vTwoId =
        ((ODocument)
                database.command(new OCommandSQL("create vertex UpdateEdgeContentV")).execute())
            .getIdentity();

    database
        .command(new OCommandSQL("create edge UpdateEdgeContentE from " + vOneId + " to " + vTwoId))
        .execute();
    database
        .command(new OCommandSQL("create edge UpdateEdgeContentE from " + vOneId + " to " + vTwoId))
        .execute();
    database
        .command(new OCommandSQL("create edge UpdateEdgeContentE from " + vOneId + " to " + vTwoId))
        .execute();

    List<ODocument> result =
        database.query(
            new OSQLSynchQuery<ODocument>("select outV(), inV() from UpdateEdgeContentE"));

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

    for (ODocument doc : result) {
      Assert.assertEquals(doc.field("outV"), vOneId);
      Assert.assertEquals(doc.field("inV"), vTwoId);
    }

    database
        .command(new OCommandSQL("update UpdateEdgeContentE content {value : 'val'}"))
        .execute();

    result =
        database.query(
            new OSQLSynchQuery<ODocument>("select outV(), inV() from UpdateEdgeContentE"));

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

    for (ODocument doc : result) {
      Assert.assertEquals(doc.field("outV"), vOneId);
      Assert.assertEquals(doc.field("inV"), vTwoId);
    }

    result = database.query(new OSQLSynchQuery<ODocument>("select from UpdateEdgeContentE"));
    Assert.assertEquals(result.size(), 3);
    for (ODocument doc : result) {
      Assert.assertEquals(doc.field("value"), "val");
    }
  }
 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;
 }
 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"));
 }
 public <T extends OUT, U extends IN> void setVertexes(final T outVertex, final U inVertex) {
   if (outVertex == null || inVertex == null)
     throw new IllegalArgumentException("outVertex and inVertex must not be null");
   this.outVertex = outVertex;
   this.inVertex = inVertex;
   final ODocument doc = getDocument();
   doc.field(OGraphDatabase.EDGE_FIELD_OUT, this.outVertex.getDocument());
   doc.field(OGraphDatabase.EDGE_FIELD_IN, this.inVertex.getDocument());
 }
  public void testUpdateVertexContent() {
    final OSchema schema = database.getMetadata().getSchema();
    OClass vertex = schema.getClass("V");
    schema.createClass("UpdateVertexContent", vertex);

    final ORID vOneId =
        ((ODocument)
                database.command(new OCommandSQL("create vertex UpdateVertexContent")).execute())
            .getIdentity();
    final ORID vTwoId =
        ((ODocument)
                database.command(new OCommandSQL("create vertex UpdateVertexContent")).execute())
            .getIdentity();

    database.command(new OCommandSQL("create edge from " + vOneId + " to " + vTwoId)).execute();
    database.command(new OCommandSQL("create edge from " + vOneId + " to " + vTwoId)).execute();
    database.command(new OCommandSQL("create edge from " + vOneId + " to " + vTwoId)).execute();

    List<ODocument> result =
        database.query(
            new OSQLSynchQuery<ODocument>(
                "select sum(outE().size(), inE().size()) from UpdateVertexContent"));

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

    for (ODocument doc : result) {
      Assert.assertEquals(doc.field("sum"), 3);
    }

    database
        .command(
            new OCommandSQL(
                "update UpdateVertexContent content {value : 'val'} where @rid = " + vOneId))
        .execute();
    database
        .command(
            new OCommandSQL(
                "update UpdateVertexContent content {value : 'val'} where @rid =  " + vTwoId))
        .execute();

    result =
        database.query(
            new OSQLSynchQuery<ODocument>(
                "select sum(outE().size(), inE().size()) from UpdateVertexContent"));

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

    for (ODocument doc : result) {
      Assert.assertEquals(doc.field("sum"), 3);
    }

    result = database.query(new OSQLSynchQuery<ODocument>("select from UpdateVertexContent"));
    Assert.assertEquals(result.size(), 2);
    for (ODocument doc : result) {
      Assert.assertEquals(doc.field("value"), "val");
    }
  }
  public int getColumnType(int column) throws SQLException {
    ODocument currentRecord = this.resultSet.unwrap(ODocument.class);
    String fieldName = currentRecord.fieldNames()[column - 1];
    // The OClass is not available so attempting to retrieve the OType from
    // the schema class
    // results in a NullPointerException
    // OClass oclass = currentRecord.getSchemaClass();
    OType otype = currentRecord.fieldType(fieldName);

    if (otype == null) {
      Object value = currentRecord.field(fieldName);
      if (value == null) return Types.NULL;
      // Check if the type is a binary record or a collection of binary
      // records
      else if (value instanceof ORecordBytes) return Types.BINARY;
      else if (value instanceof ORecordLazyList) {
        ORecordLazyList list = (ORecordLazyList) value;
        // check if all the list items are instances of ORecordBytes
        ListIterator<OIdentifiable> iterator = list.listIterator();
        OIdentifiable listElement;
        boolean stop = false;
        while (iterator.hasNext() && !stop) {
          listElement = iterator.next();
          if (!(listElement instanceof ORecordBytes)) stop = true;
        }
        if (!stop) return Types.BLOB;
      }
      return this.getSQLTypeFromJavaClass(value);
    } else if (otype == OType.EMBEDDED || otype == OType.LINK) {
      Object value = currentRecord.field(fieldName);
      if (value == null) return Types.NULL;
      // 1. Check if the type is another record or a collection of records
      if (value instanceof ORecordBytes) return Types.BINARY;
      else
        // the default type
        return oTypesSqlTypes.get(otype);
    } else if (otype == OType.EMBEDDEDLIST || otype == OType.LINKLIST) {
      Object value = currentRecord.field(fieldName);
      if (value == null) return Types.NULL;
      if (value instanceof ORecordLazyList) {
        ORecordLazyList list = (ORecordLazyList) value;
        // check if all the list items are instances of ORecordBytes
        ListIterator<OIdentifiable> iterator = list.listIterator();
        OIdentifiable listElement;
        boolean stop = false;
        while (iterator.hasNext() && !stop) {
          listElement = iterator.next();
          if (!(listElement instanceof ORecordBytes)) stop = true;
        }
        if (stop) return oTypesSqlTypes.get(otype);
        else return Types.BLOB;
      } else return Types.JAVA_OBJECT;
    } else return oTypesSqlTypes.get(otype);
  }
  @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);
    }
  }
  @Test
  public void queryMinInline() {
    List<ODocument> result =
        database.command(new OSQLSynchQuery<ODocument>("select min(1,2,7,0,-2,3)")).execute();

    Assert.assertTrue(result.size() == 1);
    for (ODocument d : result) {
      Assert.assertNotNull(d.field("min"));

      Assert.assertEquals(((Number) d.field("min")).intValue(), -2);
    }
  }
Exemple #28
0
  @Test
  public void insertOperator() {
    database.open("admin", "admin");

    int addressId = database.getMetadata().getSchema().getClass("Address").getDefaultClusterId();

    List<OClusterPosition> positions = getValidPositions(addressId);

    ODocument doc =
        (ODocument)
            database
                .command(
                    new OCommandSQL(
                        "insert into Profile (name, surname, salary, location, dummy) values ('Luca','Smith', 109.9, #"
                            + addressId
                            + ":"
                            + positions.get(3)
                            + ", 'hooray')"))
                .execute();

    Assert.assertTrue(doc != null);
    Assert.assertEquals(doc.field("name"), "Luca");
    Assert.assertEquals(doc.field("surname"), "Smith");
    Assert.assertEquals(((Number) doc.field("salary")).floatValue(), 109.9f);
    Assert.assertEquals(
        doc.field("location", OType.LINK), new ORecordId(addressId, positions.get(3)));
    Assert.assertEquals(doc.field("dummy"), "hooray");

    doc =
        (ODocument)
            database
                .command(
                    new OCommandSQL(
                        "insert into Profile SET name = 'Luca', surname = 'Smith', salary = 109.9, location = #"
                            + addressId
                            + ":"
                            + positions.get(3)
                            + ", dummy =  'hooray'"))
                .execute();

    database.delete(doc);

    Assert.assertTrue(doc != null);
    Assert.assertEquals(doc.field("name"), "Luca");
    Assert.assertEquals(doc.field("surname"), "Smith");
    Assert.assertEquals(((Number) doc.field("salary")).floatValue(), 109.9f);
    Assert.assertEquals(
        doc.field("location", OType.LINK), new ORecordId(addressId, positions.get(3)));
    Assert.assertEquals(doc.field("dummy"), "hooray");

    database.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 queryCount() {
    List<ODocument> result =
        database
            .command(new OSQLSynchQuery<ODocument>("select count(*) as total from Account"))
            .execute();

    Assert.assertTrue(result.size() == 1);
    for (ODocument d : result) {
      Assert.assertNotNull(d.field("total"));
      Assert.assertTrue(((Number) d.field("total")).longValue() > 0);
    }
  }