Java Code Examples for com.orientechnologies.orient.core.metadata.schema.OClass

The following are top voted examples for showing how to use com.orientechnologies.orient.core.metadata.schema.OClass. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Ferma-OrientDB   File: IndexTest.java   Source Code and License 6 votes vote down vote up
/**
 * Setup some indices. This is highly orientdb specific and may not be easy so setup using blueprint API.
 */
private void setupTypesAndIndices() {
	try (Tx tx = graph.tx()) {
		OrientGraph g = ((OrientGraph) ((DelegatingFramedOrientGraph) tx.getGraph()).getBaseGraph());
		ODatabaseDocument rawDb = g.getRawDatabase();
		OClass e = rawDb.createEdgeClass("HAS_MEMBER");
		e.createProperty("in", OType.LINK);
		e.createProperty("out", OType.LINK);
		e.createIndex("e.has_member", OClass.INDEX_TYPE.UNIQUE_HASH_INDEX, "out", "in");

		OClass v = rawDb.createVertexClass(Group.class.getSimpleName());
		v.createProperty("name", OType.STRING);

		v = rawDb.createVertexClass(Person.class.getSimpleName());
		v.createProperty("name", OType.STRING);
		v.createIndex(Person.class.getSimpleName() + ".name", OClass.INDEX_TYPE.UNIQUE_HASH_INDEX, "name");
		tx.success();
	}

}
 
Example 2
Project: light   File: RepositorySource.java   Source Code and License 6 votes vote down vote up
private void initTableClass()
{
    OObjectDatabaseTx objectDatabaseTx = getObjectDatabaseTx();

    OClass oClass = objectDatabaseTx.getMetadata().getSchema().getClass(Transaction.class);

    if (oClass != null && !oClass.areIndexed("tid"))
    {
        oClass.createIndex("TransactionIdUnique", OClass.INDEX_TYPE.UNIQUE, "tid");
    }

    oClass = objectDatabaseTx.getMetadata().getSchema().getClass(ProfileData.class);

    if (oClass != null && !oClass.areIndexed("tid", "sequence"))
    {
        oClass.createIndex("TransactionIdSequenceUnique", OClass.INDEX_TYPE.UNIQUE, "tid", "sequence");
    }

    objectDatabaseTx.close();
}
 
Example 3
Project: light   File: OrientJdbcTest.java   Source Code and License 6 votes vote down vote up
private void createSchemaDB(ODatabaseDocumentTx db)
{
    OSchema schema = db.getMetadata().getSchema();

    // item
    OClass item = schema.createClass("Item");

    item.createProperty("stringKey", OType.STRING).createIndex(OClass.INDEX_TYPE.UNIQUE);
    item.createProperty("intKey", OType.INTEGER).createIndex(OClass.INDEX_TYPE.UNIQUE);
    item.createProperty("date", OType.DATE).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    item.createProperty("time", OType.DATETIME).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    item.createProperty("text", OType.STRING);
    item.createProperty("length", OType.LONG).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    item.createProperty("published", OType.BOOLEAN).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    item.createProperty("title", OType.STRING).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    item.createProperty("author", OType.STRING).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    item.createProperty("tags", OType.EMBEDDEDLIST);

}
 
Example 4
Project: guice-persist-orient-examples   File: ManualSchemeInitializer.java   Source Code and License 6 votes vote down vote up
@Override
public void initialize() {
    // method is called under unit of work (with NOTX transaction mode,
    // because orient "DDL" must be executed in this mode).

    final ODatabaseDocumentTx db = context.getConnection();
    final OSchema schema = db.getMetadata().getSchema();

    // creating class only if it isn't already exists
    // this is very naive approach: normally existing class structure must also be
    // verified and updated if necessary
    if (schema.existsClass(CLASS_NAME)) {
        return;
    }

    final OClass sampleClass = schema.createClass(CLASS_NAME);
    sampleClass.createProperty("name", OType.STRING);
    sampleClass.createProperty("amount", OType.INTEGER);
}
 
Example 5
Project: spring-session-orientdb   File: OrientHttpSessionRepository.java   Source Code and License 6 votes vote down vote up
public OrientHttpSessionRepository(final OPartitionedDatabasePool pool,
                                   final int sessionTimeout) {
  this.pool = pool;
  this.sessionTimeout = sessionTimeout;

  try (final OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire())) {
    db.setAutomaticSchemaGeneration(true);
    db.getEntityManager().registerEntityClass(OrientHttpSession.class);
    db.getMetadata().getSchema().synchronizeSchema();

    final OClass sessionClass = db.getMetadata().getSchema().getClass(OrientHttpSession.class);

    createIndex(sessionClass, SESSION_ID_PROPERTY, UNIQUE_HASH_INDEX);
    createIndex(sessionClass, LAST_ACCESSED_TIME_PROPERTY, NOTUNIQUE);
    createIndex(sessionClass, MAX_INACTIVE_INTERVAL_IN_SECONDS_PROPERTY, NOTUNIQUE);
  }
}
 
Example 6
Project: mesh   File: MissingOrientCredentialFixer.java   Source Code and License 6 votes vote down vote up
public static void fix(MeshOptions options) {
	File graphDir = new File(options.getStorageOptions().getDirectory(), "storage");
	if (graphDir.exists()) {
		log.info("Checking database {" + graphDir + "}");
		OrientGraphFactory factory = new OrientGraphFactory("plocal:" + graphDir.getAbsolutePath()).setupPool(5, 100);
		try {
			// Enable the patched security class
			factory.setProperty(ODatabase.OPTIONS.SECURITY.toString(), OSecuritySharedPatched.class);
			ODatabaseDocumentTx tx = factory.getDatabase();
			try {
				OClass userClass = tx.getMetadata().getSchema().getClass("OUser");
				if (userClass == null) {
					log.info("OrientDB user credentials not found. Recreating needed roles and users.");
					tx.getMetadata().getSecurity().create();
					tx.commit();
				} else {
					log.info("OrientDB user credentials found. Skipping fix.");
				}
			} finally {
				tx.close();
			}
		} finally {
			factory.close();
		}
	}
}
 
Example 7
Project: gcplot   File: AbstractOrientDbRepository.java   Source Code and License 6 votes vote down vote up
protected <T> void register(OObjectDatabaseTx db, OSchema schema, Class<T> aClass) {
    if (schema.getClass(aClass.getSimpleName()) == null) {
        db.getEntityManager().registerEntityClasses(aClass, true);
        OClass cls = db.getMetadata().getSchema().getClass(aClass);
        String indexName = aClass.getName() + ".unq";
        Table t = aClass.getAnnotation(Table.class);
        if (t != null) {
            Set<String> fields = new HashSet<>();
            for (UniqueConstraint uc : t.uniqueConstraints()) {
                fields.addAll(Lists.newArrayList(uc.columnNames()));
            }
            if (fields.size() > 0) {
                LOG.info("Registering unique constraint for fields: " + fields);
                for (String field : fields)
                    cls.createIndex(indexName + "." + field, OClass.INDEX_TYPE.UNIQUE_HASH_INDEX, field);
            }
        }
    } else {
        db.getEntityManager().registerEntityClasses(aClass, true);
    }
}
 
Example 8
Project: nexus-public   File: LegacyKeyStoreUpgradeService.java   Source Code and License 6 votes vote down vote up
public void upgradeSchema() throws Exception {
  log.debug("Updgrading schema for trust store");
  try (ODatabaseDocumentTx db = databaseInstance.get().connect()) {
    OSchema schema = db.getMetadata().getSchema();
    OClass type = schema.getClass(DB_CLASS);
    if (type == null) {
      type = schema.createClass(DB_CLASS);
      type.createProperty(P_NAME, OType.STRING).setMandatory(true).setNotNull(true);
      type.createProperty(P_BYTES, OType.BINARY).setMandatory(true).setNotNull(true);
      type.createIndex(I_NAME, INDEX_TYPE.UNIQUE, P_NAME);
      log.debug("Created schema type {}: properties={}, indexes={}", type, type.properties(), type.getIndexes());
    }
    else {
      // NOTE: Upgrade steps run on each node but within a cluster, another node might already have upgraded the db
      log.debug("Skipped creating existing schema type {}: properties={}, indexes={}", type, type.properties(),
          type.getIndexes());
    }
  }
}
 
Example 9
Project: nexus-public   File: LegacyKeyStoreUpgradeServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testUpgradeSchema_TypeDoesNotYetExist() throws Exception {
  service.upgradeSchema();
  try (ODatabaseDocumentTx db = database.getInstance().connect()) {
    OSchema schema = db.getMetadata().getSchema();
    OClass type = schema.getClass("key_store");
    assertThat(type, is(notNullValue()));
    OProperty prop = type.getProperty("name");
    assertThat(prop, is(notNullValue()));
    assertThat(prop.isMandatory(), is(true));
    assertThat(prop.isNotNull(), is(true));
    assertThat(prop.getType(), is(OType.STRING));
    prop = type.getProperty("bytes");
    assertThat(prop, is(notNullValue()));
    assertThat(prop.isMandatory(), is(true));
    assertThat(prop.isNotNull(), is(true));
    assertThat(prop.getType(), is(OType.BINARY));
    assertThat(type.getInvolvedIndexes("name"), hasSize(1));
    assertThat(type.getInvolvedIndexes("name").iterator().next().getType(), is("UNIQUE"));
  }
}
 
Example 10
Project: nexus-public   File: AuditDataEntityAdapter.java   Source Code and License 6 votes vote down vote up
@Override
protected void defineType(final OClass type) {
  type.createProperty(P_DOMAIN, OType.STRING)
      .setNotNull(true);
  type.createProperty(P_TYPE, OType.STRING)
      .setNotNull(true);
  type.createProperty(P_CONTEXT, OType.STRING)
      .setNotNull(true);
  type.createProperty(P_TIMESTAMP, OType.LONG)
      .setNotNull(true);
  type.createProperty(P_NODE_ID, OType.STRING)
      .setNotNull(true);
  type.createProperty(P_INITIATOR, OType.STRING)
      .setNotNull(true);
  type.createProperty(P_ATTRIBUTES, OType.EMBEDDEDMAP);
}
 
Example 11
Project: nexus-public   File: RecordIdObfuscatorSupport.java   Source Code and License 6 votes vote down vote up
/**
 * @see #doEncode(OClass, ORID)
 */
@Override
public String encode(final OClass type, final ORID rid) {
  checkNotNull(type);
  checkNotNull(rid);

  log.trace("Encoding: {}->{}", type, rid);
  try {
    return doEncode(type, rid);
  }
  catch (Exception e) {
    log.error("Failed to encode: {}->{}", type, rid);
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
Example 12
Project: nexus-public   File: RecordIdObfuscatorSupport.java   Source Code and License 6 votes vote down vote up
/**
 * @see #doDecode(OClass, String)
 */
@Override
public ORID decode(final OClass type, final String encoded) {
  checkNotNull(type);
  checkNotNull(encoded);

  log.trace("Decoding: {}->{}", type, encoded);
  ORID rid;
  try {
    rid = doDecode(type, encoded);
  }
  catch (Exception e) {
    log.error("Failed to decode: {}->{}", type, encoded);
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }

  // ensure rid points to the right type
  checkArgument(Ints.contains(type.getClusterIds(), rid.getClusterId()),
      "Invalid RID '%s' for class: %s", rid, type);

  return rid;
}
 
Example 13
Project: nexus-public   File: RecordIdObfuscatorTestSupport.java   Source Code and License 6 votes vote down vote up
@Test
public void verifyIdTypeMismatchFails() {
  ORID rid = new ORecordId("#9:1");
  OClass type = mock(OClass.class);
  when(type.getClusterIds()).thenReturn(new int[] { 1 });
  String encoded = underTest.encode(type, rid);

  // this should fail since the cluster-id of the RID is not a member of the given type
  try {
    underTest.decode(type, encoded);
    fail();
  }
  catch (IllegalArgumentException e) {
    // expected
  }
}
 
Example 14
Project: mondo-hawk   File: OrientNode.java   Source Code and License 6 votes vote down vote up
protected static void setupDocumentClass(OClass oClass) {
	// Oversize leaves some extra space in the record, to reduce the
	// frequency in which we need to defragment. Orient sets the oversize
	// of class V at 2 by default, so we do the same.
	oClass.setOverSize(2);

	// TODO: should use constants from .graph, or there should be a way for
	// graph to tell the DB certain things so it can optimize for them.
	switch (oClass.getName()) {
	case "V_eclass":
		oClass.setOverSize(4);
		oClass.createProperty(PREFIX_INCOMING + "ofType", OType.LINKBAG);
		oClass.createProperty(PREFIX_INCOMING + "ofKind", OType.LINKBAG);
		break;
	case "V_eobject":
		oClass.createProperty(PREFIX_OUTGOING + "file", OType.LINKBAG);
		oClass.createProperty(PREFIX_OUTGOING + "ofType", OType.LINKLIST);
		oClass.createProperty(PREFIX_OUTGOING + "ofKind", OType.LINKLIST);
		break;
	case "V_file":
		oClass.createProperty(PREFIX_INCOMING + "file", OType.LINKBAG);
		break;
	}

	System.out.println("set up properties for " + oClass.getName() + ": "+ oClass.declaredProperties());
}
 
Example 15
Project: nexus-public   File: ComponentDatabaseUpgrade_1_2_Test.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() {
  try (ODatabaseDocumentTx db = componentDatabase.getInstance().connect()) {
    OSchema schema = db.getMetadata().getSchema();

    OClass bucketType = schema.createClass(BUCKET_CLASS);

    OClass componentType = schema.createClass(COMPONENT_CLASS);

    componentType.createProperty(P_GROUP, OType.STRING);
    componentType.createProperty(P_NAME, OType.STRING)
        .setMandatory(true)
        .setNotNull(true);
    componentType.createProperty(P_VERSION, OType.STRING);
    componentType.createProperty(P_BUCKET, OType.LINK, bucketType).setMandatory(true).setNotNull(true);
  }

  underTest = new ComponentDatabaseUpgrade_1_2(componentDatabase.getInstanceProvider());
}
 
Example 16
Project: nexus-public   File: JobDetailEntityAdapter.java   Source Code and License 6 votes vote down vote up
@Override
protected void defineType(final OClass type) {
  super.defineType(type);

  type.createProperty(P_NAME, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_GROUP, OType.STRING)
      .setMandatory(true)
      .setNotNull(false); // nullable
  type.createProperty(P_JOB_TYPE, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);

  type.createIndex(I_NAME_GROUP, INDEX_TYPE.UNIQUE, P_NAME, P_GROUP);
}
 
Example 17
Project: runrightfast-vertx   File: EventLogRepository.java   Source Code and License 6 votes vote down vote up
public static void initDatabase(@NonNull final ODatabase db) {
    final JsonLog info = JsonLog.newInfoLog(Logger.getLogger(EventLogRepository.class.getName()), EventLogRepository.class.getName());
    try {
        OClass timestampedClass = db.getMetadata().getSchema().getClass(Timestamped.class.getSimpleName());
        if (timestampedClass == null) {
            timestampedClass = db.getMetadata().getSchema().createAbstractClass(Timestamped.class.getSimpleName());
            timestampedClass.createProperty(Timestamped.Field.created_on.name(), OType.DATETIME);
            timestampedClass.createProperty(Timestamped.Field.updated_on.name(), OType.DATETIME);
            info.log("startUp", () -> Json.createObjectBuilder().add("class", Timestamped.class.getSimpleName()).add("created", true).build());
        } else {
            info.log("startUp", () -> Json.createObjectBuilder().add("class", Timestamped.class.getSimpleName()).build());
        }

        OClass logRecordClass = db.getMetadata().getSchema().getClass(EventLogRecord.class.getSimpleName());
        if (logRecordClass == null) {
            logRecordClass = db.getMetadata().getSchema().createClass(EventLogRecord.class.getSimpleName()).setSuperClasses(ImmutableList.of(timestampedClass));
            logRecordClass.createProperty(EventLogRecord.Field.event.name(), OType.STRING);
            info.log("startUp", () -> Json.createObjectBuilder().add("class", EventLogRecord.class.getSimpleName()).add("created", true).build());
        } else {
            info.log("startUp", () -> Json.createObjectBuilder().add("class", EventLogRecord.class.getSimpleName()).build());
        }

    } finally {
        db.close();
    }
}
 
Example 18
Project: runrightfast-vertx   File: EmbeddedOrientDBServiceWithSSLTest.java   Source Code and License 6 votes vote down vote up
private static void initDatabase() {
    final OServerAdmin admin = service.getServerAdmin();
    try {
        OrientDBUtils.createDatabase(admin, CLASS_NAME);
    } finally {
        admin.close();
    }

    final Optional<ODatabaseDocumentTxSupplier> dbSupplier = service.getODatabaseDocumentTxSupplier(CLASS_NAME);
    assertThat(dbSupplier.isPresent(), is(true));

    try (final ODatabase db = dbSupplier.get().get()) {
        final OClass timestampedClass = db.getMetadata().getSchema().createAbstractClass(Timestamped.class.getSimpleName());
        timestampedClass.createProperty(Timestamped.Field.created_on.name(), OType.DATETIME);
        timestampedClass.createProperty(Timestamped.Field.updated_on.name(), OType.DATETIME);

        final OClass logRecordClass = db.getMetadata().getSchema().createClass(EventLogRecord.class.getSimpleName()).setSuperClasses(ImmutableList.of(timestampedClass));
        logRecordClass.createProperty(EventLogRecord.Field.event.name(), OType.STRING);
    }
}
 
Example 19
Project: runrightfast-vertx   File: EmbeddedOrientDBServiceWithSSLWithClientAuthTest.java   Source Code and License 6 votes vote down vote up
private static void initDatabase() {
    final OServerAdmin admin = service.getServerAdmin();
    try {
        OrientDBUtils.createDatabase(admin, CLASS_NAME);
    } finally {
        admin.close();
    }

    final Optional<ODatabaseDocumentTxSupplier> dbSupplier = service.getODatabaseDocumentTxSupplier(CLASS_NAME);
    assertThat(dbSupplier.isPresent(), is(true));

    try (final ODatabase db = dbSupplier.get().get()) {
        final OClass timestampedClass = db.getMetadata().getSchema().createAbstractClass(Timestamped.class.getSimpleName());
        timestampedClass.createProperty(Timestamped.Field.created_on.name(), OType.DATETIME);
        timestampedClass.createProperty(Timestamped.Field.updated_on.name(), OType.DATETIME);

        final OClass logRecordClass = db.getMetadata().getSchema().createClass(EventLogRecord.class.getSimpleName()).setSuperClasses(ImmutableList.of(timestampedClass));
        logRecordClass.createProperty(EventLogRecord.Field.event.name(), OType.STRING);
    }
}
 
Example 20
Project: runrightfast-vertx   File: EmbeddedOrientDBServiceTest.java   Source Code and License 6 votes vote down vote up
private static void initDatabase() {
    final OServerAdmin admin = service.getServerAdmin();
    try {
        OrientDBUtils.createDatabase(admin, CLASS_NAME);
    } finally {
        admin.close();
    }

    final Optional<ODatabaseDocumentTxSupplier> dbSupplier = service.getODatabaseDocumentTxSupplier(CLASS_NAME);
    assertThat(dbSupplier.isPresent(), is(true));

    try (final ODatabase db = dbSupplier.get().get()) {
        final OClass timestampedClass = db.getMetadata().getSchema().createAbstractClass(Timestamped.class.getSimpleName());
        timestampedClass.createProperty(Timestamped.Field.created_on.name(), OType.DATETIME);
        timestampedClass.createProperty(Timestamped.Field.updated_on.name(), OType.DATETIME);

        final OClass logRecordClass = db.getMetadata().getSchema().createClass(EventLogRecord.class.getSimpleName()).setSuperClasses(ImmutableList.of(timestampedClass));
        logRecordClass.createProperty(EventLogRecord.Field.event.name(), OType.STRING);
    }
}
 
Example 21
Project: runrightfast-vertx   File: OrientDBHazelcastPluginTest.java   Source Code and License 6 votes vote down vote up
private static void initDatabase() {
    final OServerAdmin admin = service.getServerAdmin();
    try {
        OrientDBUtils.createDatabase(admin, CLASS_NAME);
    } finally {
        admin.close();
    }
    try (final ODatabase db = service.getODatabaseDocumentTxSupplier(CLASS_NAME).get().get()) {
        final OClass timestampedClass = db.getMetadata().getSchema().createAbstractClass(Timestamped.class.getSimpleName());
        timestampedClass.createProperty(Timestamped.Field.created_on.name(), OType.DATETIME);
        timestampedClass.createProperty(Timestamped.Field.updated_on.name(), OType.DATETIME);

        final OClass logRecordClass = db.getMetadata().getSchema().createClass(EventLogRecord.class.getSimpleName()).setSuperClasses(ImmutableList.of(timestampedClass));
        logRecordClass.createProperty(EventLogRecord.Field.event.name(), OType.STRING);
    }
}
 
Example 22
Project: orientdb-gremlin   File: OrientGraphFactory.java   Source Code and License 6 votes vote down vote up
protected void initGraph(OrientGraph g) {
    final ODatabaseDocumentTx db = g.getRawDatabase();
    boolean txActive = db.getTransaction().isActive();

    if (txActive)
        // COMMIT TX BEFORE ANY SCHEMA CHANGES
        db.commit();

    OSchema schema = db.getMetadata().getSchema();
    if (!schema.existsClass(OClass.VERTEX_CLASS_NAME))
        schema.createClass(OClass.VERTEX_CLASS_NAME).setOverSize(2);
    if (!schema.existsClass(OClass.EDGE_CLASS_NAME))
        schema.createClass(OClass.EDGE_CLASS_NAME);

    if (txActive) {
        // REOPEN IT AGAIN
        db.begin();
    }
}
 
Example 23
Project: orientdb-spatial   File: OLuceneSpatialIndexFactory.java   Source Code and License 6 votes vote down vote up
@Override
public OIndexInternal<?> createIndex(String name, ODatabaseDocumentInternal database, String indexType, String algorithm,
                                     String valueContainerAlgorithm, ODocument metadata, int version)
    throws OConfigurationException {

  OAbstractPaginatedStorage storage = (OAbstractPaginatedStorage) database.getStorage()
                                                                          .getUnderlying();

  OBinarySerializer<?> objectSerializer = storage.getComponentsFactory().binarySerializerFactory
      .getObjectSerializer(OLuceneMockSpatialSerializer.INSTANCE.getId());

  if (objectSerializer == null) {
    storage.getComponentsFactory().binarySerializerFactory
        .registerSerializer(OLuceneMockSpatialSerializer.INSTANCE, OType.EMBEDDED);
  }

  if (metadata == null)
    metadata = new ODocument().field("analyzer", StandardAnalyzer.class.getName());

  if (OClass.INDEX_TYPE.SPATIAL.toString()
                               .equals(indexType)) {

    return new OLuceneSpatialIndex(name, indexType, LUCENE_ALGORITHM, version, storage, valueContainerAlgorithm, metadata);
  }
  throw new OConfigurationException("Unsupported type : " + algorithm);
}
 
Example 24
Project: jbake-rtl-jalaali   File: ContentStore.java   Source Code and License 5 votes vote down vote up
private void createDocType(final OSchema schema, final String doctype) {
    logger.debug("Create document class '{}'", doctype );

    OClass page = schema.createClass(doctype);
    page.createProperty(String.valueOf(DocumentAttributes.SHA1), OType.STRING).setNotNull(true);
    page.createIndex(doctype + "sha1Index", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.SHA1.toString());
    page.createProperty(String.valueOf(DocumentAttributes.SOURCE_URI), OType.STRING).setNotNull(true);
    page.createIndex(doctype + "sourceUriIndex", OClass.INDEX_TYPE.UNIQUE, DocumentAttributes.SOURCE_URI.toString());
    page.createProperty(String.valueOf(DocumentAttributes.CACHED), OType.BOOLEAN).setNotNull(true);
    page.createIndex(doctype + "cachedIndex", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.CACHED.toString());
    page.createProperty(String.valueOf(DocumentAttributes.RENDERED), OType.BOOLEAN).setNotNull(true);
    page.createIndex(doctype + "renderedIndex", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.RENDERED.toString());
    page.createProperty(String.valueOf(DocumentAttributes.STATUS), OType.STRING).setNotNull(true);
    page.createIndex(doctype + "statusIndex", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.STATUS.toString());
}
 
Example 25
Project: jbake-rtl-jalaali   File: ContentStore.java   Source Code and License 5 votes vote down vote up
private void createSignatureType(OSchema schema) {
    OClass signatures = schema.createClass("Signatures");
    signatures.createProperty(String.valueOf(DocumentAttributes.KEY), OType.STRING).setNotNull(true);
    signatures.createIndex("keyIdx", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.KEY.toString());
    signatures.createProperty(String.valueOf(DocumentAttributes.SHA1), OType.STRING).setNotNull(true);
    signatures.createIndex("sha1Idx", OClass.INDEX_TYPE.UNIQUE, DocumentAttributes.SHA1.toString());
}
 
Example 26
Project: light   File: RepositorySource.java   Source Code and License 5 votes vote down vote up
public OClass findClass(String className)
{
    //        ODatabaseDocumentTx documentTx = objectDatabaseTx.getDatabase();
    OSchema schema = getObjectDatabaseTx().getMetadata().getSchema();

    return schema.getClass(className);
}
 
Example 27
Project: light   File: RepositoryFactory.java   Source Code and License 5 votes vote down vote up
private static void initTableClass()
{
    ODatabaseDocumentTx documentTx = factory.getDatabase();
    OSchema schema = documentTx.getMetadata().getSchema();
    OClass oClass = schema.getClass("Classes");

    if (oClass == null)
    {
        oClass = schema.createClass("Classes");
        oClass.createProperty("name", OType.STRING);
        oClass.createProperty("byteCode", OType.BINARY);

        oClass.createIndex("ClassNameUnique", OClass.INDEX_TYPE.UNIQUE, "name");
    }
}
 
Example 28
Project: vertx-orientdb   File: TestVerticle.java   Source Code and License 5 votes vote down vote up
private void createDocumentDatabase(final Handler<AsyncResult<Void>> handler) {
  selectConnectionInfo(co -> {
    if (co.failed()) {
      handler.handle(Future.failedFuture(co.cause()));
    }
    else {
      ConnectionOptions connectionOptions = co.result();
      manager.createDocumentInstance(
          connectionOptions,
          adb -> {
            log.info("Schema update");
            OSchema schema = adb.getMetadata().getSchema();
            if (!schema.existsClass("test")) {
              OClass oclass = schema.createClass("test");
              oclass.createProperty("name", OType.STRING);
              oclass.createProperty("value", OType.STRING);
            }
            log.info("Schema done");
          },
          v -> {
            if (v.failed()) {
              log.info("Test subject DB creation failed", v.cause());
              handler.handle(Future.failedFuture(v.cause()));
            }
            else {
              log.info("Test subject DB creation done");
              deployVerticles(connectionOptions, handler);
            }
          }
      );
    }
  });
}
 
Example 29
Project: it-keeps   File: vCommon.java   Source Code and License 5 votes vote down vote up
protected static List<String> getAllSuperClassesNames(OrientVertex ov) {
	List<String> list = new ArrayList<>();

	for (OClass oc : ov.getType().getAllSuperClasses()) {
		list.add(oc.getName());
	}

	return list;
}
 
Example 30
Project: guice-persist-orient-examples   File: SampleService.java   Source Code and License 5 votes vote down vote up
public List<String> getEdgeClasses() {
    // return registered tables for edges (extending base E type)
    return Lists.transform(
            Lists.newArrayList(context.getConnection().getEdgeBaseType().getAllBaseClasses()),
            new Function<OClass, String>() {
                @Override
                public String apply(OClass input) {
                    return input.getName() + " (cluster " + input.getDefaultClusterId() + ")";
                }
            });
}
 
Example 31
Project: mesh   File: OrientDBDatabase.java   Source Code and License 5 votes vote down vote up
@Override
public void addCustomEdgeIndex(String label, String indexPostfix, String... fields) {
	OrientGraphNoTx noTx = factory.getNoTx();
	try {
		OrientEdgeType e = noTx.getEdgeType(label);
		if (e == null) {
			throw new RuntimeException("Could not find edge type {" + label + "}. Create edge type before creating indices.");
		}

		for (String key : fields) {
			if (e.getProperty(key) == null) {
				OType type = OType.STRING;
				if (key.equals("out") || key.equals("in")) {
					type = OType.LINK;
				}
				e.createProperty(key, type);
			}
		}
		String name = "e." + label + "_" + indexPostfix;
		name = name.toLowerCase();
		if (fields.length != 0 && e.getClassIndex(name) == null) {
			e.createIndex(name, OClass.INDEX_TYPE.NOTUNIQUE_HASH_INDEX, fields);
		}

	} finally {
		noTx.shutdown();
	}
}
 
Example 32
Project: mesh   File: OrientDBDatabase.java   Source Code and License 5 votes vote down vote up
@Override
public void addVertexIndex(String indexName, Class<?> clazzOfVertices, boolean unique, String fieldKey, FieldType fieldType) {
	if (log.isDebugEnabled()) {
		log.debug("Adding vertex index  for class {" + clazzOfVertices.getName() + "}");
	}
	OrientGraphNoTx noTx = factory.getNoTx();
	try {
		String name = clazzOfVertices.getSimpleName();
		OrientVertexType v = noTx.getVertexType(name);
		if (v == null) {
			throw new RuntimeException("Vertex type {" + name + "} is unknown. Can't create index {" + indexName + "}");
		}

		if (v.getProperty(fieldKey) == null) {
			OType type = convertType(fieldType);
			OType subType = convertToSubType(fieldType);
			if (subType != null) {
				v.createProperty(fieldKey, type, subType);
			} else {
				v.createProperty(fieldKey, type);
			}
		}

		if (v.getClassIndex(indexName) == null) {
			v.createIndex(indexName, unique ? OClass.INDEX_TYPE.UNIQUE_HASH_INDEX.toString() : OClass.INDEX_TYPE.NOTUNIQUE_HASH_INDEX.toString(),
					null, new ODocument().fields("ignoreNullValues", true), new String[] { fieldKey });
		}
	} finally {
		noTx.shutdown();
	}

}
 
Example 33
Project: mesh   File: EdgeIndexPerformanceTest.java   Source Code and License 5 votes vote down vote up
private static void setupTypesAndIndices(OrientGraphFactory factory2) {
	OrientGraph g = factory.getTx();
	try {
		// g.setUseClassForEdgeLabel(true);
		g.setUseLightweightEdges(false);
		g.setUseVertexFieldsForEdgeLabels(false);
	} finally {
		g.shutdown();
	}

	try {
		g = factory.getTx();

		OrientEdgeType e = g.createEdgeType("HAS_ITEM");
		e.createProperty("in", OType.LINK);
		e.createProperty("out", OType.LINK);
		e.createIndex("e.has_item", OClass.INDEX_TYPE.UNIQUE_HASH_INDEX, "out", "in");

		OrientVertexType v = g.createVertexType("root", "V");
		v.createProperty("name", OType.STRING);

		v = g.createVertexType("item", "V");
		v.createProperty("name", OType.STRING);
		v.createIndex("item", OClass.INDEX_TYPE.FULLTEXT_HASH_INDEX, "name");

	} finally {
		g.shutdown();
	}

}
 
Example 34
Project: gcplot   File: FiltersOrientDbRepository.java   Source Code and License 5 votes vote down vote up
@Override
protected void init(OObjectDatabaseTx db, OSchema schema) {
    if (schema.getClass("Filter") == null) {
        OClass filterClass = schema.createClass("Filter");
        filterClass.createProperty("type", OType.STRING);
        filterClass.createProperty("value", OType.STRING);
        filterClass.createIndex("filter.type.indices", OClass.INDEX_TYPE.FULLTEXT_HASH_INDEX, "type");
        filterClass.createIndex("filter.value.indices", OClass.INDEX_TYPE.FULLTEXT_HASH_INDEX, "value");
    }
}
 
Example 35
Project: gcplot   File: OrientDbConfigurationManager.java   Source Code and License 5 votes vote down vote up
@Override
public void init() {
    try (ODatabaseDocumentTx db = docDb()) {
        OSchema schema = db.getMetadata().getSchema();
        if (!schema.existsClass(GCP_CONFIG)) {
            OClass newClass = schema.createClass(GCP_CONFIG);
            newClass.createProperty("hg", OType.STRING);
            newClass.createProperty("map", OType.EMBEDDEDMAP);
            newClass.createIndex("hg.unq", OClass.INDEX_TYPE.UNIQUE, "hg");
            db.commit(true);
            db.command(new OCommandSQL("INSERT INTO " + GCP_CONFIG +
                    " SET hg=\"" + hostGroup + "\", map={}")).execute();
        }
        fetchFromDb(db);
        executor.scheduleAtFixedRate(() -> {
            LOG.info("Trying to reload configuration from main DB.");
            putLock.writeLock().lock();
            try {
                if (!isClosed) {
                    try (ODatabaseDocumentTx _db = docDb()) {
                        fetchFromDb(_db);
                    }
                }
            } finally {
                putLock.writeLock().unlock();
            }
        }, readLong(ConfigProperty.POLL_INTERVAL), readLong(ConfigProperty.POLL_INTERVAL), TimeUnit.MILLISECONDS);
    }
}
 
Example 36
Project: nexus-public   File: ScriptEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void defineType(final OClass type) {
  type.createProperty(P_NAME, OType.STRING).setNotNull(true);
  type.createProperty(P_TYPE, OType.STRING).setNotNull(true);
  type.createProperty(P_CONTENT, OType.STRING).setNotNull(true);

  //ensure name is unique as it serves as the ID for a script
  type.createIndex(I_NAME, INDEX_TYPE.UNIQUE, P_NAME);
}
 
Example 37
Project: orientdb-spatial   File: LuceneSpatialPolygonTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public void init() {
  initDB();

  databaseDocumentTx.set(ODatabase.ATTRIBUTES.CUSTOM, "strictSql=false");
  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  OClass v = schema.getClass("V");
  OClass oClass = schema.createClass("Place");
  oClass.setSuperClass(v);
  oClass.createProperty("location", OType.EMBEDDED, schema.getClass("OPolygon"));
  oClass.createProperty("name", OType.STRING);

  databaseDocumentTx.command(new OCommandSQL("CREATE INDEX Place.location ON Place(location) SPATIAL ENGINE LUCENE")).execute();

}
 
Example 38
Project: nexus-public   File: EntityHook.java   Source Code and License 5 votes vote down vote up
private boolean recordEvent(final ODocument document, final EventKind eventKind) {
  final OClass schemaType = document.getSchemaClass();
  if (schemaType != null) {
    final EntityAdapter adapter = recordingAdapters.get(schemaType);
    if (adapter != null) {
      final ODatabaseInternal db = ODatabaseRecordThreadLocal.INSTANCE.get();
      if (db != null) {
        // workaround OrientDB 2.1 issue where in-TX dictionary updates are not replicated
        if (db.getStorage().isDistributed() && adapter instanceof SingletonEntityAdapter) {
          ((SingletonEntityAdapter) adapter).singleton.replicate(document, eventKind);
        }
        Map<ODocument, EventKind> events = dbEvents.get(db);
        if (events == null) {
          events = new LinkedHashMap<>();
          dbEvents.put(db, events);
        }
        // replace mapping after merge so key always points to the latest document instance
        // (avoids a risk that the original key became disconnected/detached at this point)
        EventKind updatedEventKind = updateEventKind(events.remove(document), eventKind);
        if (updatedEventKind != null) {
          events.put(document, updatedEventKind);
        }
        return true;
      }
    }
  }
  return false;
}
 
Example 39
Project: nexus-public   File: EntityAdapter.java   Source Code and License 5 votes vote down vote up
public void register(final ODatabaseDocumentTx db, @Nullable final Runnable initializer) {
  checkNotNull(db);

  OSchema schema = db.getMetadata().getSchema();
  OClass type = schema.getClass(typeName);
  if (type == null) {
    int clusters = getMinimumClusters();
    type = clusters > 0 ? schema.createClass(typeName, clusters) : schema.createClass(typeName);
    defineType(db, type);

    log.debug("Created schema type '{}': properties={}, indexes={}",
        type,
        type.properties(),
        type.getIndexes()
    );

    if (initializer != null) {
      log.debug("Running initializer: {}", initializer);
      initializer.run();
    }
  }

  this.dbName = db.getName();
  this.schemaType = type;

  if (sendEvents() && entityHook != null) {
    entityHook.enableEvents(this);
  }
}
 
Example 40
Project: orientdb-spatial   File: LuceneSpatialMultiPolygonTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public void init() {
  initDB();

  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  OClass v = schema.getClass("V");
  OClass oClass = schema.createClass("Place");
  oClass.setSuperClass(v);
  oClass.createProperty("location", OType.EMBEDDED, schema.getClass("OMultiPolygon"));
  oClass.createProperty("name", OType.STRING);

  databaseDocumentTx.command(new OCommandSQL("CREATE INDEX Place.location ON Place(location) SPATIAL ENGINE LUCENE")).execute();

}
 
Example 41
Project: nexus-public   File: EncryptedRecordIdObfuscator.java   Source Code and License 5 votes vote down vote up
@Override
protected String doEncode(final OClass type, final ORID rid) throws Exception {
  Cipher cipher = crypto.createCipher(TRANSFORMATION);
  // rid is 10 byte long, need to be in multiples of 8 for cipher
  byte[] plain = ByteBuffer.allocate(16).put(rid.toStream()).array();
  cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
  byte[] encrypted = cipher.doFinal(plain);
  return Hex.encode(encrypted);
}
 
Example 42
Project: nexus-public   File: EncryptedRecordIdObfuscator.java   Source Code and License 5 votes vote down vote up
@Override
protected ORID doDecode(final OClass type, final String encoded) throws Exception {
  Cipher cipher = crypto.createCipher(TRANSFORMATION);
  byte[] encrypted = Hex.decode(encoded);
  cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
  byte[] plain = cipher.doFinal(encrypted);
  return new ORecordId().fromStream(plain);
}
 
Example 43
Project: nexus-public   File: DatabaseUpgradeSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Runs a {@link BiConsumer} of {@link ODatabaseDocumentTx} and {@link OClass}
 * if the specified {@code className} exists.
 */
protected static void withDatabaseAndClass(final Provider<DatabaseInstance> databaseInstance, final String className,
                                           final BiConsumer<ODatabaseDocumentTx, OClass> consumer)
{
  withDatabase(databaseInstance, db -> {
    if (db.getMetadata().getSchema().existsClass(className)) {
      consumer.accept(db, db.getMetadata().getSchema().getClass(className));
    }
  });
}
 
Example 44
Project: orientdb-spatial   File: LuceneSpatialLineStringTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public void init() {
  initDB();

  databaseDocumentTx.set(ODatabase.ATTRIBUTES.CUSTOM, "strictSql=false");
  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  OClass v = schema.getClass("V");
  OClass oClass = schema.createClass("Place");
  oClass.setSuperClass(v);
  oClass.createProperty("location", OType.EMBEDDED, schema.getClass("OLineString"));
  oClass.createProperty("name", OType.STRING);

  databaseDocumentTx.command(new OCommandSQL("CREATE INDEX Place.location ON Place(location) SPATIAL ENGINE LUCENE")).execute();

}
 
Example 45
Project: nexus-public   File: RecordIdObfuscatorPerfSupport.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  this.underTest = createTestSubject();

  this.rid = new ORecordId("#9:1");

  this.type = mock(OClass.class);
  when(type.getClusterIds()).thenReturn(new int[] { rid.getClusterId() });

  // prime jvm byte code optimization (maybe, we hope)
  for (int i=0; i<1000; i++) {
    encodeAndDecode();
  }
}
 
Example 46
Project: orientdb-spatial   File: LuceneSpatialMultiLineStringTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
@Override
public void init() {
  super.init();
  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  OClass v = schema.getClass("V");
  OClass oClass = schema.createClass("Place");
  oClass.setSuperClass(v);
  oClass.createProperty("location", OType.EMBEDDED, schema.getClass("OMultiLineString"));
  oClass.createProperty("name", OType.STRING);

  databaseDocumentTx.command(new OCommandSQL("CREATE INDEX Place.location ON Place(location) SPATIAL ENGINE LUCENE")).execute();
}
 
Example 47
Project: nexus-public   File: BlobStoreConfigurationEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void defineType(final OClass type) {
  type.createProperty(P_NAME, OType.STRING)
      .setCollate(new OCaseInsensitiveCollate())
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_TYPE, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_ATTRIBUTES, OType.EMBEDDEDMAP)
      .setMandatory(true)
      .setNotNull(true);
  type.createIndex(I_NAME, INDEX_TYPE.UNIQUE, P_NAME);
}
 
Example 48
Project: nexus-public   File: ConfigurationEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void defineType(final OClass type) {
  type.createProperty(P_REPOSITORY_NAME, OType.STRING)
      .setCollate(new OCaseInsensitiveCollate())
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_RECIPE_NAME, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_ONLINE, OType.BOOLEAN)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_ATTRIBUTES, OType.EMBEDDEDMAP);
  type.createIndex(I_REPOSITORY_NAME, INDEX_TYPE.UNIQUE, P_REPOSITORY_NAME);
}
 
Example 49
Project: nexus-public   File: BucketEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void defineType(final OClass type) {
  type.createProperty(P_REPOSITORY_NAME, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_ATTRIBUTES, OType.EMBEDDEDMAP)
      .setNotNull(true);

  type.createIndex(I_REPOSITORY_NAME, INDEX_TYPE.UNIQUE, P_REPOSITORY_NAME);
}
 
Example 50
Project: nexus-public   File: AssetEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void defineType(final ODatabaseDocumentTx db, final OClass type) {
  super.defineType(type);
  type.createProperty(P_COMPONENT, OType.LINK, componentEntityAdapter.getSchemaType());
  type.createProperty(P_NAME, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_SIZE, OType.LONG);
  type.createProperty(P_CONTENT_TYPE, OType.STRING);
  type.createProperty(P_BLOB_REF, OType.STRING);
  type.createProperty(P_LAST_DOWNLOADED, OType.DATETIME);
  type.createProperty(P_BLOB_CREATED, OType.DATETIME);
  type.createProperty(P_BLOB_UPDATED, OType.DATETIME);
  type.createProperty(P_CREATED_BY, OType.STRING);
  type.createProperty(P_CREATED_BY_IP, OType.STRING);

  ODocument metadata = db.newInstance()
      .field("ignoreNullValues", false)
      .field("mergeKeys", false);
  type.createIndex(I_BUCKET_COMPONENT_NAME, INDEX_TYPE.UNIQUE.name(), null, metadata,
      new String[]{P_BUCKET, P_COMPONENT, P_NAME}
  );
  type.createIndex(I_BUCKET_NAME, INDEX_TYPE.NOTUNIQUE, P_BUCKET, P_NAME);
  type.createIndex(I_COMPONENT, INDEX_TYPE.NOTUNIQUE, P_COMPONENT);

  new OIndexBuilder(type, I_NAME_CASEINSENSITIVE, INDEX_TYPE.NOTUNIQUE)
      .property(P_NAME, OType.STRING)
      .caseInsensitive()
      .build(db);
}
 
Example 51
Project: nexus-public   File: BrowseNodeEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void defineType(final OClass type) {
  type.createProperty(P_REPOSITORY_NAME, OType.STRING).setMandatory(true).setNotNull(true);
  type.createProperty(P_PARENT_PATH, OType.STRING).setMandatory(true).setNotNull(true);
  type.createProperty(P_NAME, OType.STRING).setMandatory(true).setNotNull(true);
  type.createProperty(P_COMPONENT_ID, OType.LINK, componentEntityAdapter.getSchemaType());
  type.createProperty(P_ASSET_ID, OType.LINK, assetEntityAdapter.getSchemaType());
  type.createProperty(P_ASSET_NAME_LOWERCASE, OType.STRING);
}
 
Example 52
Project: nexus-public   File: BrowseNodeEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void defineType(final ODatabaseDocumentTx db, final OClass type) {
  defineType(type);

  // primary index that guarantees path uniqueness for nodes in a given repository
  type.createIndex(I_REPOSITORY_NAME_PARENT_PATH_NAME, INDEX_TYPE.UNIQUE, P_REPOSITORY_NAME, P_PARENT_PATH, P_NAME);

  // save space and ignore nulls because we'll never query on a null component/asset id
  ODocument ignoreNullValues = db.newInstance().field("ignoreNullValues", true);
  type.createIndex(I_COMPONENT_ID, INDEX_TYPE.NOTUNIQUE.name(), null, ignoreNullValues, new String[] { P_COMPONENT_ID });
  type.createIndex(I_ASSET_ID, INDEX_TYPE.UNIQUE.name(), null, ignoreNullValues, new String[] { P_ASSET_ID });
}
 
Example 53
Project: orientdb-spatial   File: LuceneSpatialPointTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public void init() {
  initDB();

  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  OClass v = schema.getClass("V");
  OClass oClass = schema.createClass("City");
  oClass.setSuperClass(v);
  oClass.createProperty("location", OType.EMBEDDED, schema.getClass("OPoint"));
  oClass.createProperty("name", OType.STRING);

  OClass place = schema.createClass("Place");
  place.setSuperClass(v);
  place.createProperty("latitude", OType.DOUBLE);
  place.createProperty("longitude", OType.DOUBLE);
  place.createProperty("name", OType.STRING);

  databaseDocumentTx.command(new OCommandSQL("CREATE INDEX City.location ON City(location) SPATIAL ENGINE LUCENE")).execute();

  databaseDocumentTx.command(new OCommandSQL("CREATE INDEX Place.l_lon ON Place(latitude,longitude) SPATIAL ENGINE LUCENE"))
      .execute();

  ODocument rome = newCity("Rome", 12.5, 41.9);
  ODocument london = newCity("London", -0.1275, 51.507222);

  ODocument rome1 = new ODocument("Place");
  rome1.field("name", "Rome");
  rome1.field("latitude", 41.9);
  rome1.field("longitude", 12.5);
  databaseDocumentTx.save(rome1);
  databaseDocumentTx.save(rome);
  databaseDocumentTx.save(london);

  databaseDocumentTx.command(new OCommandSQL("insert into City set name = 'Test' , location = ST_GeomFromText('" + PWKT + "')"))
      .execute();
}
 
Example 54
Project: orientdb-spatial   File: OPointShapeBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public void initClazz(ODatabaseDocumentTx db) {

  OSchemaProxy schema = db.getMetadata().getSchema();
  OClass point = schema.createAbstractClass(getName(),superClass(db));
  OProperty coordinates = point.createProperty(COORDINATES, OType.EMBEDDEDLIST, OType.DOUBLE);
  coordinates.setMin("2");
  coordinates.setMin("2");
}
 
Example 55
Project: nexus-public   File: ComponentDatabaseUpgrade_1_5.java   Source Code and License 5 votes vote down vote up
private void createCaseInsensitiveNameCaseInsensitiveIndex(final ODatabaseDocumentTx db, final OClass type) {
  log.info("Creating case-insensitive index on case-insensitive name field on component");
  OIndexManager indexManager = db.getMetadata().getIndexManager();
  if (indexManager.getIndex(I_CI_NAME_CASE_INSENSITIVE) == null) {
    new OIndexBuilder(type, I_CI_NAME_CASE_INSENSITIVE, INDEX_TYPE.NOTUNIQUE)
        .property(P_CI_NAME, OType.STRING)
        .caseInsensitive()
        .build(db);
  }
}
 
Example 56
Project: nexus-public   File: ComponentDatabaseUpgrade_1_3.java   Source Code and License 5 votes vote down vote up
private void renameAssetLastAccessedField() {
  try (ODatabaseDocumentTx db = componentDatabaseInstance.get().connect()) {
    OClass assetClass = getAssetDbClass(db);
    if (assetClass.existsProperty(P_LAST_ACCESSED)) {
      db.command(new OCommandSQL(ALTER_ASSET_LAST_ACCESSED)).execute();
    }
  }
}
 
Example 57
Project: nexus-public   File: ComponentDatabaseUpgrade_1_4.java   Source Code and License 5 votes vote down vote up
private void createNameCaseInsensitiveIndex(final ODatabaseDocumentTx db, final OClass type) {
  OIndexManager indexManager = db.getMetadata().getIndexManager();
  if (indexManager.getIndex(I_NAME_CASE_INSENSITIVE) == null) {
    new OIndexBuilder(type, I_NAME_CASE_INSENSITIVE, INDEX_TYPE.NOTUNIQUE)
        .property(P_NAME, OType.STRING)
        .caseInsensitive()
        .build(db);
  }
}
 
Example 58
Project: nexus-public   File: ComponentDatabaseUpgrade_1_4.java   Source Code and License 5 votes vote down vote up
private void createAssetNameIdx(final ODatabaseDocumentTx db, final OClass type) {
  if (db.getMetadata().getIndexManager().getIndex(I_ASSET_NAME) == null) {
    new OIndexBuilder(type, I_ASSET_NAME, INDEX_TYPE.NOTUNIQUE)
        .property(P_NAME, OType.STRING)
        .caseInsensitive()
        .build(db);
  }
}
 
Example 59
Project: nexus-public   File: ComponentEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void defineType(final ODatabaseDocumentTx db, final OClass type) {
  super.defineType(type);
  type.createProperty(P_GROUP, OType.STRING);
  type.createProperty(P_NAME, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_VERSION, OType.STRING);
  type.createProperty(P_CI_NAME, OType.STRING)
      .setCollate(new OCaseInsensitiveCollate())
      .setMandatory(true)
      .setNotNull(true);

  ODocument metadata = db.newInstance()
      .field("ignoreNullValues", false)
      .field("mergeKeys", false);
  type.createIndex(I_BUCKET_GROUP_NAME_VERSION, INDEX_TYPE.UNIQUE.name(), null, metadata,
      new String[]{P_BUCKET, P_GROUP, P_NAME, P_VERSION});
  type.createIndex(I_BUCKET_NAME_VERSION, INDEX_TYPE.NOTUNIQUE.name(), null, metadata,
      new String[]{P_BUCKET, P_NAME, P_VERSION});

  new OIndexBuilder(type, I_GROUP_NAME_VERSION_INSENSITIVE, INDEX_TYPE.NOTUNIQUE)
      .property(P_GROUP, OType.STRING)
      .property(P_NAME, OType.STRING)
      .property(P_VERSION, OType.STRING)
      .caseInsensitive()
      .build(db);

  new OIndexBuilder(type, I_CI_NAME_CASE_INSENSITIVE, INDEX_TYPE.NOTUNIQUE)
      .property(P_CI_NAME, OType.STRING)
      .caseInsensitive()
      .build(db);

  componentEntityAdapterExtensions.forEach(d -> d.defineType(db, type));
}
 
Example 60
Project: mondo-hawk   File: AbstractOrientIndex.java   Source Code and License 5 votes vote down vote up
/**
 * Creates the SBTree index paired to this field within this logical index.
 */
protected void createIndex(final Class<?> keyClass) {
	final OIndexManager indexManager = getIndexManager();

	// Indexes have to be created outside transactions
	final String idxName = getSBTreeIndexName(keyClass);
	final boolean txWasOpen = graph.getGraph().getTransaction().isActive();
	if (txWasOpen) {
		graph.getConsole().println("Warning: prematurely committing a transaction so we can create index " + idxName);
		graph.saveDirty();
		graph.getGraph().commit();
	}

	// Index key type
	OType keyType = OType.STRING;
	if (keyClass == Byte.class || keyClass == Short.class || keyClass == Integer.class || keyClass == Long.class) {
		keyType = OType.INTEGER;
	} else if (keyClass == Float.class || keyClass == Double.class) {
		keyType = OType.DOUBLE;
	}

	// Create SBTree NOTUNIQUE index
    final OIndexFactory factory = OIndexes.getFactory(OClass.INDEX_TYPE.NOTUNIQUE.toString(), null);
	
	final OSimpleKeyIndexDefinition indexDef = new OSimpleKeyIndexDefinition(factory.getLastVersion(), OType.STRING, keyType);
	indexManager.createIndex(idxName, OClass.INDEX_TYPE.NOTUNIQUE.toString(), indexDef, null, null, null, null);
}