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

The following are top voted examples for showing how to use com.orientechnologies.orient.core.metadata.schema.OType. 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: odbogm   File: Auditor.java   Source Code and License 6 votes vote down vote up
public Auditor(Transaction t, String user) {
    this.transaction = t;
    this.auditUser = user;
    
    // verificar que la clase de auditorías exista
    if (this.transaction.getDBClass(this.ODBAUDITLOGVERTEXCLASS) == null) {
        OrientVertexType olog = this.transaction.getGraphdb().createVertexType(this.ODBAUDITLOGVERTEXCLASS);
        olog.createProperty("rid", OType.STRING);
        olog.createProperty("timestamp", OType.DATETIME);
        olog.createProperty("user", OType.STRING);
        olog.createProperty("action", OType.STRING);
        olog.createProperty("label", OType.STRING);
        olog.createProperty("log", OType.STRING);
        this.transaction.commit();
    }
    
}
 
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: light   File: OrientJdbcTest.java   Source Code and License 6 votes vote down vote up
private ODocument createItem(int id, ODocument doc)
{
    String itemKey = Integer.valueOf(id).toString();

    doc.setClassName("Item");
    doc.field("stringKey", itemKey);
    doc.field("intKey", id);
    String contents = "OrientDB is a deeply scalable Document-Graph DBMS with the flexibility of the Document databases and the power to manage links of the Graph databases. " + "It can work in schema-less mode, schema-full or a mix of both. Supports advanced features such as ACID Transactions, Fast Indexes, Native and SQL queries." + " It imports and exports documents in JSON." + " Graphs of hundreads of linked documents can be retrieved all in memory in few milliseconds without executing costly JOIN such as the Relational DBMSs do. " + "OrientDB uses a new indexing algorithm called MVRB-Tree, derived from the Red-Black Tree and from the B+Tree with benefits of both: fast insertion and ultra fast lookup. " + "The transactional engine can run in distributed systems supporting up to 9.223.372.036 Billions of records for the maximum capacity of 19.807.040.628.566.084 Terabytes of data distributed on multiple disks in multiple nodes. " + "OrientDB is FREE for any use. Open Source License Apache 2.0. ";
    doc.field("text", contents);
    doc.field("title", "orientDB");
    doc.field("length", contents.length());
    doc.field("published", (id % 2 > 0));
    doc.field("author", "anAuthor" + id);
    // doc.field("tags", asList("java", "orient", "nosql"), OType.EMBEDDEDLIST);
    Calendar instance = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    instance.add(Calendar.HOUR_OF_DAY, -id);
    Date time = instance.getTime();
    doc.field("date", time, OType.DATE);
    doc.field("time", time, OType.DATETIME);

    return doc;
}
 
Example 5
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 6
Project: mesh   File: OrientDBDatabase.java   Source Code and License 6 votes vote down vote up
/**
 * Convert the vendor agnostic type to an orientdb specific type.
 * 
 * @param fieldType
 * @return
 */
private OType convertType(FieldType fieldType) {
	switch (fieldType) {
	case STRING:
		return OType.STRING;
	case INTEGER:
		return OType.INTEGER;
	case BOOLEAN:
		return OType.BOOLEAN;
	case STRING_SET:
		return OType.EMBEDDEDSET;
	case STRING_LIST:
		return OType.EMBEDDEDLIST;
	default:
		throw new RuntimeException("Unsupported type {" + fieldType + "}");
	}
}
 
Example 7
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 8
Project: nexus-public   File: AssetDownloadCountEntityAdapter.java   Source Code and License 6 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_ASSET_NAME, OType.STRING).setMandatory(true).setNotNull(true);
  type.createProperty(P_NODE_ID, OType.STRING).setMandatory(true).setNotNull(true);
  type.createProperty(P_COUNT, OType.LONG).setMandatory(true).setNotNull(true);
  type.createProperty(P_DATE_TYPE, OType.STRING).setMandatory(true).setNotNull(true);
  type.createProperty(P_DATE, OType.DATETIME).setMandatory(true).setNotNull(true);

  type.createIndex(I_REPO_NAME_ASSET_NAME_DATE_TYPE_DATE, INDEX_TYPE.NOTUNIQUE, P_REPOSITORY_NAME, P_ASSET_NAME,
      P_DATE_TYPE, P_DATE);
  type.createIndex(I_NODE_ID_REPO_NAME_ASSET_NAME_DATE_TYPE_DATE, INDEX_TYPE.NOTUNIQUE, P_NODE_ID, P_REPOSITORY_NAME,
      P_ASSET_NAME, P_DATE_TYPE, P_DATE);
  type.createIndex(I_NODE_ID_DATE_TYPE_DATE, INDEX_TYPE.NOTUNIQUE, P_NODE_ID, P_DATE_TYPE, P_DATE);
  type.createIndex(I_REPO_NAME_DATE_TYPE_DATE, INDEX_TYPE.NOTUNIQUE, P_REPOSITORY_NAME, P_DATE_TYPE);
}
 
Example 9
Project: nexus-public   File: AssetDownloadCountEntityAdapter.java   Source Code and License 6 votes vote down vote up
public long getCount(final ODatabaseDocumentTx db, final String repositoryName, final String assetName) {
  checkNotNull(db);
  checkNotNull(repositoryName);
  checkNotNull(assetName);

  Map<String, Object> parameters = buildQueryParameters(repositoryName, assetName, DateType.DAY, null, null);
  Iterable<ODocument> docs = db.command(new OCommandSQL(TOTAL_COUNT_QUERY)).execute(parameters);

  ODocument result = Iterables.getFirst(docs, null);

  if (result != null) {
    return result.field("sum", OType.LONG);
  }

  return 0;
}
 
Example 10
Project: nexus-public   File: AssetDownloadCountEntityAdapter.java   Source Code and License 6 votes vote down vote up
public long getCount(final ODatabaseDocumentTx db,
                     final String repositoryName,
                     final String assetName,
                     final DateType dateType)
{
  checkNotNull(db);
  checkNotNull(repositoryName);
  checkNotNull(assetName);
  checkNotNull(dateType);

  Map<String, Object> parameters = buildQueryParameters(repositoryName, assetName, dateType, null, null);
  String query = String.format(
      "select sum(%s) from %s where %s = :repositoryName and %s = :assetName and %s = :dateType",
      P_COUNT, DB_CLASS, P_REPOSITORY_NAME, P_ASSET_NAME, P_DATE_TYPE);
  Iterable<ODocument> docs = db.command(new OCommandSQL(query)).execute(parameters);

  ODocument result = Iterables.getFirst(docs, null);

  if (result != null) {
    return result.field("sum", OType.LONG);
  }

  return 0;
}
 
Example 11
Project: nexus-public   File: AssetDownloadCountEntityAdapter.java   Source Code and License 6 votes vote down vote up
public long getCount(final ODatabaseDocumentTx db,
                     final String repositoryName,
                     final DateType dateType,
                     final DateTime date)
{
  checkNotNull(db);
  checkNotNull(repositoryName);
  checkNotNull(dateType);
  checkNotNull(date);

  Map<String, Object> parameters = buildQueryParameters(repositoryName, "", dateType, date, null);
  Iterable<ODocument> docs = db.command(new OCommandSQL(DATED_COUNT_ALL_OF_REPO_QUERY)).execute(parameters);

  ODocument result = Iterables.getFirst(docs, null);

  if (result != null) {
    return result.field("sum", OType.LONG);
  }

  return 0;
}
 
Example 12
Project: nexus-public   File: AssetDownloadCountEntityAdapter.java   Source Code and License 6 votes vote down vote up
public long getCount(final ODatabaseDocumentTx db,
                     final String repositoryName,
                     final String assetName,
                     final DateType dateType,
                     final DateTime date)
{
  checkNotNull(db);
  checkNotNull(repositoryName);
  checkNotNull(assetName);
  checkNotNull(dateType);
  checkNotNull(date);

  Map<String, Object> parameters = buildQueryParameters(repositoryName, assetName, dateType, date, null);
  Iterable<ODocument> docs = db.command(new OCommandSQL(DATED_COUNT_QUERY)).execute(parameters);

  ODocument result = Iterables.getFirst(docs, null);

  if (result != null) {
    return result.field("sum", OType.LONG);
  }

  return 0;
}
 
Example 13
Project: nexus-public   File: ApiKeyEntityAdapter.java   Source Code and License 6 votes vote down vote up
@Override
protected void defineType(final OClass type) {
  type.createProperty(P_APIKEY, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_DOMAIN, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_PRIMARY_PRINCIPAL, OType.STRING)
      .setMandatory(true)
      .setNotNull(true);
  type.createProperty(P_PRINCIPALS, OType.BINARY)
      .setMandatory(true)
      .setNotNull(true);
  type.createIndex(I_APIKEY, INDEX_TYPE.UNIQUE, P_DOMAIN, P_APIKEY);
  type.createIndex(I_PRIMARY_PRINCIPAL, INDEX_TYPE.UNIQUE, P_DOMAIN, P_PRIMARY_PRINCIPAL);
}
 
Example 14
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 15
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 16
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 17
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 18
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 19
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 20
Project: runrightfast-vertx   File: EventLogRepository.java   Source Code and License 6 votes vote down vote up
public void initDatabase() {
    try (final ODatabase db = dbSupplier.get()) {
        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());
        }
    }
}
 
Example 21
Project: orientdb-gremlin   File: OrientGraphIndexTest.java   Source Code and License 6 votes vote down vote up
@Test
public void indexCollation() {
    OrientGraph graph = newGraph();

    String label = "VC1";
    String key = "name";
    String value = "bob";

    Configuration config = new BaseConfiguration();
    config.setProperty("type", "UNIQUE");
    config.setProperty("keytype", OType.STRING);
    config.setProperty("collate", "ci");
    graph.createVertexIndex(key, label, config);

    graph.addVertex(label, label, key, value);
    // TODO: test with a "has" traversal, if/when that supports a case insensitive match predicate
    //        OrientIndexQuery indexRef = new OrientIndexQuery(true, Optional.of(label), key, value.toUpperCase());
    //        Iterator<OrientVertex> result = graph.getIndexedVertices(indexRef).iterator();
    //        Assert.assertEquals(result.hasNext(), true);
}
 
Example 22
Project: orientdb-spatial   File: OLuceneLegacySpatialIndexEngine.java   Source Code and License 6 votes vote down vote up
public Object searchIntersect(OCompositeKey key, double distance, OCommandContext context) throws IOException {

    double lat = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(0), Double.class)).doubleValue();
    double lng = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(1), Double.class)).doubleValue();
    SpatialOperation operation = SpatialOperation.Intersects;

    Point p = ctx.makePoint(lng, lat);
    SpatialArgs args = new SpatialArgs(operation, ctx.makeCircle(lng, lat,
        DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
    Filter filter = strategy.makeFilter(args);
    IndexSearcher searcher = searcher();
    ValueSource valueSource = strategy.makeDistanceValueSource(p);
    Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(searcher);

    return new LuceneResultSet(this,
        new SpatialQueryContext(context, searcher, new MatchAllDocsQuery(), filter, distSort).setSpatialArgs(args));
  }
 
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: orientdb-spatial   File: ORectangleLegacyBuilder.java   Source Code and License 6 votes vote down vote up
@Override
public Rectangle makeShape(OCompositeKey key, SpatialContext ctx) {

  Point[] points = new Point[2];
  int i = 0;

  for (Object o : key.getKeys()) {
    List<Number> numbers = (List<Number>) o;
    double lat = ((Double) OType.convert(numbers.get(0), Double.class)).doubleValue();
    double lng = ((Double) OType.convert(numbers.get(1), Double.class)).doubleValue();
    points[i] = ctx.makePoint(lng, lat);
    i++;
  }

  Point lowerLeft = points[0];
  Point topRight = points[1];
  if (lowerLeft.getX() > topRight.getX()) {
    double x = lowerLeft.getX();
    lowerLeft = ctx.makePoint(topRight.getX(), lowerLeft.getY());
    topRight = ctx.makePoint(x, topRight.getY());
  }
  return ctx.makeRectangle(lowerLeft, topRight);
}
 
Example 25
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 26
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 27
Project: orientdb-oda-birt   File: ResultSetMetaData.java   Source Code and License 5 votes vote down vote up
public int getColumnType( int index ) throws OdaException
{
	//return Types.JAVA_OBJECT;//Any OrientDB field may be NULL
	///*
	String fieldName = getColumnName(index);
	OType fieldType = rowDoc.fieldType(fieldName);
	if (fieldType!=null){
		return typesSqlTypes.get(fieldType);
	}else{
		return Types.VARCHAR;
		//throw new OdaException("Unknown OType of field "+fieldName+" with index "+index);
	}
	//*/
}
 
Example 28
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 29
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 30
Project: it-keeps   File: vBaseStandard.java   Source Code and License 5 votes vote down vote up
@DatabaseProperty(
		name = jBaseStandard.OTHER_NAME, 
		type = OType.EMBEDDEDLIST
		)
protected final List<String> getOtherName() {
	return this.getListString(jBaseStandard.OTHER_NAME);
}
 
Example 31
Project: it-keeps   File: vBase.java   Source Code and License 5 votes vote down vote up
@DatabaseProperty(name = jBase.CREATION_DATE, isReadOnly = true, type = OType.DATETIME)
public final DateTime getCreationDate() {

    Date value = this.getProperty(jBase.CREATION_DATE);

    if (value == null) {
        return null;
    }

    return new DateTime(value);
}
 
Example 32
Project: guice-persist-orient-examples   File: ManualSchemeInitializer.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize() {

    final OrientBaseGraph db = context.getConnection();

    /**
     * Avoid creating scheme if table already exist.
     * Look method implementation: internally it use document api the same way as it was used in
     * document sample.
     */
    if (db.getVertexType(CLASS_NAME) != null) {
        return;
    }

    /**
     * In database scheme the only difference with other apis would be that
     * Sample class would extend "V" in scheme (which marks type as Vertex type).
     */
    final OrientVertexType vtype = db.createVertexType(CLASS_NAME);
    vtype.createProperty("name", OType.STRING);
    vtype.createProperty("amount", OType.INTEGER);

    // registration of graph type is not mandatory (orient will create it on-the-fly)
    // but with warning

    // also note that edge name is case-insensitive and so used as "belongsTo" everywhere in code
    db.createEdgeType("BelongsTo");
}
 
Example 33
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 34
Project: mesh   File: OrientDBDatabase.java   Source Code and License 5 votes vote down vote up
@Override
public void addEdgeType(String label, Class<?> superClazzOfEdge, String... stringPropertyKeys) {
	if (log.isDebugEnabled()) {
		log.debug("Adding edge type for label {" + label + "}");
	}
	OrientGraphNoTx noTx = factory.getNoTx();
	try {
		OrientEdgeType e = noTx.getEdgeType(label);
		if (e == null) {
			String superClazz = "E";
			if (superClazzOfEdge != null) {
				superClazz = superClazzOfEdge.getSimpleName();
			}
			e = noTx.createEdgeType(label, superClazz);
		} else {
			// Update the existing edge type and set the super class
			if (superClazzOfEdge != null) {
				OrientEdgeType superType = noTx.getEdgeType(superClazzOfEdge.getSimpleName());
				if (superType == null) {
					throw new RuntimeException("The supertype for edges with label {" + label + "} can't be set since the supertype {"
							+ superClazzOfEdge.getSimpleName() + "} was not yet added to orientdb.");
				}
				e.setSuperClass(superType);
			}
		}

		for (String key : stringPropertyKeys) {
			if (e.getProperty(key) == null) {
				e.createProperty(key, OType.STRING);
			}
		}
	} finally {
		noTx.shutdown();
	}
}
 
Example 35
Project: mesh   File: OrientDBDatabase.java   Source Code and License 5 votes vote down vote up
/**
 * Convert the vendor agnostic type to an orientdb specific sub type (eg. string for string lists)
 * 
 * @param fieldType
 * @return
 */
private OType convertToSubType(FieldType fieldType) {
	switch (fieldType) {
	case STRING_SET:
		return OType.STRING;
	case STRING_LIST:
		return OType.STRING;
	default:
		return null;
	}
}
 
Example 36
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 37
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 38
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 39
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 40
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 41
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 42
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);
}
 
Example 43
Project: nexus-public   File: AuditDataEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void readFields(final ODocument document, final AuditData entity) throws Exception {
  entity.setDomain(document.field(P_DOMAIN, OType.STRING));
  entity.setType(document.field(P_TYPE, OType.STRING));
  entity.setContext(document.field(P_CONTEXT, OType.STRING));
  entity.setTimestamp(document.field(P_TIMESTAMP, OType.DATETIME));
  entity.setNodeId(document.field(P_NODE_ID, OType.STRING));
  entity.setInitiator(document.field(P_INITIATOR, OType.STRING));

  Map<String, String> attributes = document.field(P_ATTRIBUTES, OType.EMBEDDEDMAP);
  if (attributes != null) {
    entity.setAttributes(detachable(attributes));
  }
}
 
Example 44
Project: nexus-public   File: BlobStoreConfigurationEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void readFields(final ODocument document, final BlobStoreConfiguration entity) {
  String name = document.field(P_NAME, OType.STRING);
  String type = document.field(P_TYPE, OType.STRING);
  Map<String, Map<String, Object>> attributes = document.field(P_ATTRIBUTES, OType.EMBEDDEDMAP);

  entity.setName(name);
  entity.setType(type);
  entity.setAttributes(detachable(attributes));
}
 
Example 45
Project: orientdb-spatial   File: LuceneTransactionGeoQueryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPointTransactionRollBack() {

  ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:txPoint");

  try {
    db.create();

    OSchema schema = db.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);

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

    OIndex idx = db.getMetadata().getIndexManager().getIndex("City.location");
    ODocument rome = newCity("Rome", 12.5, 41.9);
    ODocument london = newCity("London", -0.1275, 51.507222);

    db.begin();

    db.command(new OCommandSQL("insert into City set name = 'Test' , location = ST_GeomFromText('" + PWKT + "')")).execute();
    db.save(rome);
    db.save(london);
    String query = "select * from City where location && 'LINESTRING(-160.06393432617188 21.996535232496047,-160.1099395751953 21.94304553343818,-160.169677734375 21.89399562866819,-160.21087646484375 21.844928843026818,-160.21018981933594 21.787556698550834)' ";
    List<ODocument> docs = db.query(new OSQLSynchQuery<ODocument>(query));
    Assert.assertEquals(1, docs.size());
    Assert.assertEquals(3, idx.getSize());
    db.rollback();

    query = "select * from City where location && 'LINESTRING(-160.06393432617188 21.996535232496047,-160.1099395751953 21.94304553343818,-160.169677734375 21.89399562866819,-160.21087646484375 21.844928843026818,-160.21018981933594 21.787556698550834)' ";
    docs = db.query(new OSQLSynchQuery<ODocument>(query));
    Assert.assertEquals(0, docs.size());
    Assert.assertEquals(0, idx.getSize());
  } finally {
    db.drop();
  }
}
 
Example 46
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 47
Project: nexus-public   File: ConfigurationEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void readFields(final ODocument document, final Configuration entity) {
  String recipeName = document.field(P_RECIPE_NAME, OType.STRING);
  String repositoryName = document.field(P_REPOSITORY_NAME, OType.STRING);
  Boolean online = document.field(P_ONLINE, OType.BOOLEAN);
  Map<String, Map<String, Object>> attributes = document.field(P_ATTRIBUTES, OType.EMBEDDEDMAP);

  entity.setRecipeName(recipeName);
  entity.setRepositoryName(repositoryName);
  entity.setOnline(online);
  entity.setAttributes(decrypt(attributes));
}
 
Example 48
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 49
Project: nexus-public   File: BucketEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void readFields(final ODocument document, final Bucket entity) {
  String repositoryName = document.field(P_REPOSITORY_NAME, OType.STRING);
  Map<String, Object> attributes = document.field(P_ATTRIBUTES, OType.EMBEDDEDMAP);

  entity.setRepositoryName(repositoryName);
  entity.attributes(new NestedAttributesMap(P_ATTRIBUTES, attributes));
}
 
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: AssetEntityAdapter.java   Source Code and License 5 votes vote down vote up
@Override
protected void readFields(final ODocument document, final Asset entity) {
  super.readFields(document, entity);

  ORID componentId = document.field(P_COMPONENT, ORID.class);
  String name = document.field(P_NAME, OType.STRING);
  Long size = document.field(P_SIZE, OType.LONG);
  String contentType = document.field(P_CONTENT_TYPE, OType.STRING);
  String blobRef = document.field(P_BLOB_REF, OType.STRING);
  Date lastDownloaded = document.field(P_LAST_DOWNLOADED, OType.DATETIME);
  Date blobCreated = document.field(P_BLOB_CREATED, OType.DATETIME);
  Date blobUpdated = document.field(P_BLOB_UPDATED, OType.DATETIME);
  String createdBy = document.field(P_CREATED_BY, OType.STRING);
  String createdByIp = document.field(P_CREATED_BY_IP, OType.STRING);

  if (componentId != null) {
    entity.componentId(new AttachedEntityId(componentEntityAdapter, componentId));
  }
  entity.name(name);
  entity.size(size);
  entity.contentType(contentType);
  entity.createdBy(createdBy);
  entity.createdByIp(createdByIp);
  if (blobRef != null) {
    entity.blobRef(BlobRef.parse(blobRef));
  }
  if (lastDownloaded != null) {
    entity.lastDownloaded(new DateTime(lastDownloaded));
  }
  if (blobCreated != null) {
    entity.blobCreated(new DateTime(blobCreated));
  }
  if (blobUpdated != null) {
    entity.blobUpdated(new DateTime(blobUpdated));
  }
}
 
Example 52
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 53
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 54
Project: nexus-public   File: ComponentDatabaseUpgrade_1_5.java   Source Code and License 5 votes vote down vote up
private void createCaseInsensitiveNameField(final OClass type) {
  log.info("Creating case-insensitive name field on component");
  if (!type.existsProperty(P_CI_NAME)) {
    type.createProperty(P_CI_NAME, OType.STRING)
        .setCollate(new OCaseInsensitiveCollate())
        .setMandatory(false)
        .setNotNull(false);
  }
}
 
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_7.java   Source Code and License 5 votes vote down vote up
@Override
public void apply() throws Exception {
  withDatabaseAndClass(componentDatabaseInstance, BROWSE_NODE, (db, table) -> {
    db.getMetadata().getSchema().dropClass(BROWSE_NODE);
  });

  withDatabaseAndClass(componentDatabaseInstance, ASSET, (db, table) -> {
    if (!table.existsProperty(AssetEntityAdapter.P_CREATED_BY)) {
      table.createProperty(AssetEntityAdapter.P_CREATED_BY, OType.STRING);
    }
    if (!table.existsProperty(AssetEntityAdapter.P_CREATED_BY_IP)) {
      table.createProperty(AssetEntityAdapter.P_CREATED_BY_IP, OType.STRING);
    }
  });
}
 
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: ComponentDatabaseUpgrade_1_4.java   Source Code and License 5 votes vote down vote up
private void createComponentGroupNameVersionIdx(final ODatabaseDocumentTx db, final OClass type) {
  if (db.getMetadata().getIndexManager().getIndex(I_COMPONENT_GROUP_NAME_VERSION) == null) {
    new OIndexBuilder(type, I_COMPONENT_GROUP_NAME_VERSION, INDEX_TYPE.NOTUNIQUE)
        .property(P_GROUP, OType.STRING)
        .property(P_NAME, OType.STRING)
        .property(P_VERSION, OType.STRING)
        .caseInsensitive()
        .build(db);
  }
}
 
Example 60
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));
}