com.orientechnologies.orient.core.id.ORID Java Examples

The following examples show how to use com.orientechnologies.orient.core.id.ORID. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
@Ignore //TODO: Uncomment when OrientDB issue will be fixed: https://github.com/orientechnologies/orientdb/issues/8067
@Test
public void testLinkToOUser() {
	ODatabaseDocument db = wicket.getTester().getDatabase();
	OSchema schema = db.getMetadata().getSchema();
	final OClass classA = schema.createClass("TestLinkToOUser");
	classA.createProperty("name", OType.STRING);
	classA.createProperty("user", OType.LINK).setLinkedClass(schema.getClass("OUser"));
	ORID userRid = new ORecordId("#5:0");
	ODocument doc = new ODocument(classA);
	wicket.getTester().signIn("writer", "writer");
	db = wicket.getTester().getDatabase();
	db.begin();
	ODocument userDoc = userRid.getRecord();
	userDoc.field("roles");
	doc.field("Admin");
	doc.field("user", userDoc);
	doc.save();
	db.commit();
}
 
Example #2
Source File: DisableIfDocumentNotSavedBehavior.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
@Override
public void onConfigure(Component component) {
	super.onConfigure(component);
	Object object = component.getDefaultModelObject();
	if(object!=null && object instanceof OIdentifiable) {
		ORID rid = ((OIdentifiable)object).getIdentity();
		if(rid.isPersistent()) {
			component.setEnabled(true);
		} else {
			// Is record scheduled for creation?
			OTransaction transaction = OrientDbWebSession.get().getDatabase().getTransaction();
			ORecordOperation operation = transaction.getRecordEntry(rid);
			component.setEnabled(operation!=null && operation.type==ORecordOperation.CREATED);
		}
	}
}
 
Example #3
Source File: ConvertToODocumentFunction.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
@Override
public ODocument apply(F input) {
	if(input==null)
	{
		return null;
	}
	else if(input instanceof ODocument)
	{
		return (ODocument)input;
	}
	else if(input instanceof ORID)
	{
		return ((ORID)input).getRecord();
	}
	else if(input instanceof CharSequence)
	{
		return new ORecordId(input.toString()).getRecord();
	}
	else
	{
		throw new WicketRuntimeException("Object '"+input+"' of type '"+input.getClass()+"' can't be converted to ODocument");
	}
}
 
Example #4
Source File: DynamicPropertyValueModel.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected T load() {
	ODocument doc = docModel.getObject();
	OProperty prop = propertyModel!=null?propertyModel.getObject():null;
	if(doc==null) return null;
	if(prop==null) return (T) doc;
	if(valueType==null) {
		return (T) doc.field(prop.getName());
	} else
	{
		Object ret = doc.field(prop.getName(), valueType);
		if(ORecord.class.isAssignableFrom(valueType) && ret instanceof ORID) {
			ret = ((ORID)ret).getRecord();
		}
		return (T) ret;
	}
}
 
Example #5
Source File: PurgeUnusedSnapshotsFacetImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private ODocument newComponentDoc(final TestData testData) {
  ORID id = new ORecordId(1, clusterPosition++);
  ODocument componentDoc = new ODocument(id);
  componentDoc.field(P_NAME, testData.artifactId);
  componentDoc.field(P_BUCKET, bucketEntityAdapter.recordIdentity(bucket));
  componentDoc.field(P_FORMAT, "maven2");

  Map<String, Object> mavenAttributes = new HashMap<>();
  mavenAttributes.put(P_GROUP_ID, testData.groupId);
  mavenAttributes.put(P_ARTIFACT_ID, testData.artifactId);
  mavenAttributes.put(P_BASE_VERSION, testData.baseVersion);

  Map<String, Object> map = new HashMap<>();
  map.put("maven2", mavenAttributes);
  componentDoc.field(P_ATTRIBUTES, map);

  return componentDoc;
}
 
Example #6
Source File: ContentExpressionFunctionTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() {
  when(variableResolverAdapterManager.get(FORMAT)).thenReturn(assetVariableResolver);
  when(assetVariableResolver.fromDocument(assetDocument)).thenReturn(variableSource);

  when(bucketDocument.getRecord()).thenReturn(bucketDocument);
  when(bucketDocument.field("repository_name", String.class)).thenReturn(REPOSITORY_NAME);
  when(bucketDocument.getIdentity()).thenReturn(mock(ORID.class));

  when(assetDocument.getClassName()).thenReturn("asset");
  when(assetDocument.getRecord()).thenReturn(assetDocument);
  when(assetDocument.field("bucket", OIdentifiable.class)).thenReturn(bucketDocument);
  when(assetDocument.field("name", String.class)).thenReturn(PATH);
  when(assetDocument.field("format", String.class)).thenReturn(FORMAT);

  when(commandRequest.execute(any(Map.class))).thenReturn(Collections.singletonList(assetDocument));
  when(database.command(any(OCommandRequest.class))).thenReturn(commandRequest);

  when(selectorManager.newSelectorConfiguration()).thenAnswer(invocation -> new OrientSelectorConfiguration());

  underTest = new ContentExpressionFunction(variableResolverAdapterManager, selectorManager, contentAuthHelper);
}
 
Example #7
Source File: AssetEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public EntityEvent newEvent(final ODocument document, final EventKind eventKind) {
  EntityMetadata metadata = new AttachedEntityMetadata(this, document);

  String repositoryName = ((ODocument) document.field(P_BUCKET)).field(P_REPOSITORY_NAME);

  ORID rid = document.field(P_COMPONENT, ORID.class);
  EntityId componentId = rid != null ? new AttachedEntityId(componentEntityAdapter, rid) : null;

  switch (eventKind) {
    case CREATE:
      return new AssetCreatedEvent(metadata, repositoryName, componentId);
    case UPDATE:
      return new AssetUpdatedEvent(metadata, repositoryName, componentId);
    case DELETE:
      return new AssetDeletedEvent(metadata, repositoryName, componentId);
    default:
      return null;
  }
}
 
Example #8
Source File: RecordIdObfuscatorSupport.java    From nexus-public with Eclipse Public License 1.0 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 #9
Source File: LuceneInsertDeleteTest.java    From orientdb-lucene with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertUpdateWithIndex() throws Exception {

  databaseDocumentTx.getMetadata().reload();
  OSchema schema = databaseDocumentTx.getMetadata().getSchema();

  ODocument doc = new ODocument("City");
  doc.field("name", "Rome");
  databaseDocumentTx.save(doc);

  OIndex idx = schema.getClass("City").getClassIndex("City.name");
  Collection<?> coll = (Collection<?>) idx.get("Rome");
  Assert.assertEquals(coll.size(), 1);
  Assert.assertEquals(idx.getSize(), 1);
  doc = databaseDocumentTx.load((ORID) coll.iterator().next());

  databaseDocumentTx.delete(doc);

  coll = (Collection<?>) idx.get("Rome");
  Assert.assertEquals(coll.size(), 0);
  Assert.assertEquals(idx.getSize(), 0);

}
 
Example #10
Source File: RecordIdObfuscatorSupport.java    From nexus-public with Eclipse Public License 1.0 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 #11
Source File: IndexSyncService.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void syncIndex(final Map<ORID, EntityAdapter> changes) {
  IndexBatchRequest batch = new IndexBatchRequest();
  try (ODatabaseDocumentTx db = componentDatabase.get().acquire()) {
    changes.forEach((rid, adapter) -> {
      ODocument document = db.load(rid);
      if (document != null) {
        EntityId componentId = findComponentId(document);
        if (componentId != null) {
          batch.update(findRepositoryName(document), componentId);
        }
      }
      else if (adapter instanceof ComponentEntityAdapter) {
        batch.delete(null, componentId(rid));
      }
    });
  }
  indexRequestProcessor.process(batch);
}
 
Example #12
Source File: ConfigDatabaseUpgrade_1_2.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@VisibleForTesting
void updateAssetBlobStoreRefs(final Map<String, String> renamedBlobStores) {
  try (ODatabaseDocumentTx db = componentDatabaseInstance.get().connect()) {
    renamedBlobStores.forEach((originalName, newName) -> {
      log.debug("Searching for BlobStoreRefs, original name: {}, new name: {} ", originalName, newName);

      OSQLSynchQuery query = new OSQLSynchQuery<>("select from asset where blob_ref like ? and @rid > ? limit 100");
      String nameTestValue = originalName + "@%";

      List<ODocument> results = db.query(query, nameTestValue, new ORecordId());

      while (!results.isEmpty()) {
        log.debug("Updating set of {} Refs", results.size());
        ORID last = results.get(results.size() - 1).getIdentity();

        results.forEach(doc -> updateDocWithNewName(originalName, newName, doc));

        results = db.query(query, nameTestValue, last);
      }
    });
  }
}
 
Example #13
Source File: ComponentDatabaseUpgrade_1_10.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void fixComponentBatch(final ODatabaseDocumentTx db, final OIdentifiable bucket) {
  log.debug("Processing batch of {} yum component records...", BATCH_SIZE);

  OSQLSynchQuery<Object> query = new OSQLSynchQuery<>(SELECT_COMPONENT_BATCH_SQL);

  List<ODocument> components = db.query(query, bucket, new ORecordId());

  while (!components.isEmpty()) {
    ORID last = components.get(components.size() - 1).getIdentity();

    for (ODocument component : components) {
      fixComponent(db, component, bucket);
    }

    components = db.query(query, bucket, last);
  }
}
 
Example #14
Source File: RecordIdObfuscatorTestSupport.java    From nexus-public with Eclipse Public License 1.0 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 #15
Source File: OrientDbDocumentTrial.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void recordIdEncoding() throws Exception {
  try (ODatabaseDocumentTx db = createDatabase()) {
    ODocument doc = createPerson(db);
    assertThat(doc, notNullValue());
    log("New Document: {}", doc);

    ORID rid = doc.getIdentity();
    log("RID: {}", rid);

    String encoded = Hex.encode(rid.toStream());
    log("Hex Encoded: {}", encoded);

    ORID decoded = new ORecordId().fromStream(Hex.decode(encoded));
    log("Decoded RID: {}", decoded);

    assertThat(decoded, is(rid));

    doc = db.getRecord(decoded);
    log("Fetched Document: {}", doc);
  }
}
 
Example #16
Source File: BrowseNodeEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Associates a {@link OrientBrowseNode} with the given {@link Component}.
 */
public void createComponentNode(final ODatabaseDocumentTx db,
                                final String repositoryName,
                                final String format,
                                final List<? extends BrowsePath> paths,
                                final Component component)
{
  //create any parent folder nodes for this component if not already existing
  maybeCreateParentNodes(db, repositoryName, format, paths.subList(0, paths.size() - 1));

  //now create the component node
  OrientBrowseNode node = newNode(repositoryName, format, paths);
  ODocument document = findNodeRecord(db, node);
  if (document == null) {
    // complete the new entity before persisting
    node.setComponentId(EntityHelper.id(component));
    addEntity(db, node);
  }
  else {
    ORID oldComponentId = document.field(P_COMPONENT_ID, ORID.class);
    ORID newComponentId = componentEntityAdapter.recordIdentity(component);
    if (oldComponentId == null) {
      // shortcut: merge new information directly into existing record
      document.field(P_COMPONENT_ID, newComponentId);
      document.save();
    }
    else if (!oldComponentId.equals(newComponentId)) {
      // retry in case this is due to an out-of-order delete event
      throw new BrowseNodeCollisionException("Node already has a component");
    }
  }
}
 
Example #17
Source File: BrowseNodeEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Associates a {@link OrientBrowseNode} with the given {@link Asset}.
 */
public void createAssetNode(final ODatabaseDocumentTx db,
                            final String repositoryName,
                            final String format,
                            final List<? extends BrowsePath> paths,
                            final Asset asset)
{
  //create any parent folder nodes for this asset if not already existing
  maybeCreateParentNodes(db, repositoryName, format, paths.subList(0, paths.size() - 1));

  //now create the asset node
  OrientBrowseNode node = newNode(repositoryName, format, paths);
  ODocument document = findNodeRecord(db, node);
  if (document == null) {
    // complete the new entity before persisting
    node.setAssetId(EntityHelper.id(asset));
    addEntity(db, node);
  }
  else {
    ORID oldAssetId = document.field(P_ASSET_ID, ORID.class);
    ORID newAssetId = assetEntityAdapter.recordIdentity(asset);
    if (oldAssetId == null) {
      // shortcut: merge new information directly into existing record
      document.field(P_ASSET_ID, newAssetId);
      String path = document.field(P_PATH, OType.STRING);

      //if this node is now an asset, we don't want a trailing slash
      if (!asset.name().endsWith("/") && path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
        document.field(P_PATH, path);
      }
      document.save();
    }
    else if (!oldAssetId.equals(newAssetId)) {
      // retry in case this is due to an out-of-order delete event
      throw new BrowseNodeCollisionException("Node already has an asset");
    }
  }
}
 
Example #18
Source File: PurgeUnusedFacetImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Bucket mockBucket() {
  EntityAdapter owner = mock(EntityAdapter.class);
  ODocument document = mock(ODocument.class);
  ORID orID = new ORecordId(1, 1);
  when(document.getIdentity()).thenReturn(orID);
  EntityMetadata entityMetadata = new AttachedEntityMetadata(owner, document);

  Bucket bucket = mock(Bucket.class);
  when(bucket.getEntityMetadata()).thenReturn(entityMetadata);
  return bucket;
}
 
Example #19
Source File: AssetEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Custom affinity based on name, so recreated assets will have the same affinity.
 * Attempts to give asset events the same affinity as events from their component.
 */
@Override
public String eventAffinity(final ODocument document) {
  ORID bucketId = document.field(P_BUCKET, ORID.class);
  // this either returns a pre-fetched document or an ORID needing fetching
  OIdentifiable component = document.field(P_COMPONENT, OIdentifiable.class);
  ODocument node = null;
  if (component != null) {
    node = component.getRecord(); // fetch document (no-op if it's already there)
  }
  if (node == null) {
    node = document; // no component (or it's AWOL) so fall back to asset node
  }
  return bucketId + "@" + node.field(P_NAME, OType.STRING);
}
 
Example #20
Source File: MetadataNodeEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void readFields(final ODocument document, final T entity) {
  ORID bucketId = document.field(P_BUCKET, ORID.class);
  String format = document.field(P_FORMAT, OType.STRING);
  Date lastUpdated = document.field(P_LAST_UPDATED, OType.DATETIME);
  Map<String, Object> attributes = document.field(P_ATTRIBUTES, OType.EMBEDDEDMAP);

  entity.bucketId(new AttachedEntityId(bucketEntityAdapter, bucketId));
  entity.format(format);
  entity.lastUpdated(new DateTime(lastUpdated));
  entity.attributes(new NestedAttributesMap(P_ATTRIBUTES, detachable(attributes)));
  entity.newEntity(document.getIdentity().isNew());
}
 
Example #21
Source File: PageDelegate.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
public PageDelegate(WebPage page, ORID pageOrid, ORID docOrid) {
	this.page = page;
	this.pageDocumentModel = new ODocumentModel(pageOrid);
	ODocument doc = (ODocument)(docOrid!=null?docOrid.getRecord():pageDocumentModel.getObject().field(PagesModule.OPROPERTY_DOCUMENT));
	if(doc!=null) page.setDefaultModel(new ODocumentModel(doc));
	String script = pageDocumentModel.getObject().field(PagesModule.OPROPERTY_SCRIPT);
	if(!Strings.isEmpty(script)) {
		OScriptManager scriptManager = Orient.instance().getScriptManager();
		ODatabaseDocument db = OrienteerWebSession.get().getDatabase();
		final OPartitionedObjectPool.PoolEntry<ScriptEngine> entry = 
				scriptManager.acquireDatabaseEngine(db.getName(), "javascript");
		final ScriptEngine scriptEngine = entry.object;
		Bindings binding = null;
	    try {
			binding = scriptManager.bind(scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE), 
											(ODatabaseDocumentTx) db, null, null);
			binding.put("page", page);
			binding.put("pageDoc", pageDocumentModel.getObject());
			binding.put("doc", doc);
			try {
				scriptEngine.eval(script);
			} catch (ScriptException e) {
				scriptManager.throwErrorMessage(e, script);
			}
		} finally {
			if (scriptManager != null && binding != null) {
				scriptManager.unbind(binding, null, null);
				scriptManager.releaseDatabaseEngine("javascript", db.getName(), entry);
			}
		}
	}
}
 
Example #22
Source File: AssetEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 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 #23
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactions() throws Exception {
	ODatabaseDocument db = wicket.getTester().getDatabase();
	try {
		assertFalse(db.getTransaction().isActive());
		OSchema schema = db.getMetadata().getSchema();
		OClass classA = schema.createClass("TransA");
		classA.createProperty("name", OType.STRING);
		ODocument doc = new ODocument(classA);
		doc.field("name", "test1");
		doc.save();
		ORID orid = doc.getIdentity();
		db.begin();
		assertTrue(db.getTransaction().isActive());
		doc = orid.getRecord();
		assertEquals("test1", doc.field("name"));
		doc.field("name", "test2");
		doc = orid.getRecord();
		assertEquals("test2", doc.field("name"));
		//There is NO SAVE!
		db.commit();
		db.getLocalCache().clear();
		/* COMMENT START */
		//db.close();
		//db = wicket.getTester().getDatabase();
		/* COMMENT STOP */
		doc = orid.getRecord();
		assertEquals("test1", doc.field("name"));
		
	} finally {
		db.commit();
	}
}
 
Example #24
Source File: LuceneInsertUpdateTest.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Test
public void testInsertUpdateWithIndex() throws Exception {

  OSchema schema = databaseDocumentTx.getMetadata().getSchema();

  ODocument doc = new ODocument("City");
  doc.field("name", "Rome");

  databaseDocumentTx.save(doc);
  OIndex idx = schema.getClass("City").getClassIndex("City.name");
  Collection<?> coll = (Collection<?>) idx.get("Rome");
  Assert.assertEquals(coll.size(), 1);

  doc = databaseDocumentTx.load((ORID) coll.iterator().next());
  Assert.assertEquals(doc.field("name"), "Rome");

  doc.field("name", "London");
  databaseDocumentTx.save(doc);

  coll = (Collection<?>) idx.get("Rome");
  Assert.assertEquals(coll.size(), 0);
  coll = (Collection<?>) idx.get("London");
  Assert.assertEquals(coll.size(), 1);

  doc = databaseDocumentTx.load((ORID) coll.iterator().next());
  Assert.assertEquals(doc.field("name"), "London");

  doc.field("name", "Berlin");
  databaseDocumentTx.save(doc);

  coll = (Collection<?>) idx.get("Rome");
  Assert.assertEquals(coll.size(), 0);
  coll = (Collection<?>) idx.get("London");
  Assert.assertEquals(coll.size(), 0);
  coll = (Collection<?>) idx.get("Berlin");
  Assert.assertEquals(coll.size(), 1);

}
 
Example #25
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testLoosingLinkedClass() throws Exception
{
	ODatabaseDocument db = wicket.getTester().getDatabase();
	OSchema schema = wicket.getTester().getSchema();
	OClass mainClass = schema.createClass("LMainClass");
	OClass embeddedClass = schema.createClass("LEmbeddedClass");
	mainClass.createProperty("name", OType.STRING);
	mainClass.createProperty("embedded", OType.EMBEDDED).setLinkedClass(embeddedClass);
	embeddedClass.createProperty("name", OType.STRING);
	
	db.begin();
	ODocument main = new ODocument(mainClass);
	main.field("name", "main");
	ODocument embedded = new ODocument(embeddedClass);
	//embedded.field("name", "embedded");
	main.field("embedded", embedded);
	//NO Save here!
	db.commit();
	db.close();
	
	main.fromStream(main.toStream());
	
	db = wicket.getTester().getDatabase();
	db.begin();
	assertEmbeddedIsCorrect(main);
	main.save();
	ORID recordId = main.getIdentity();
	db.commit();
	db.close();
	
	db = wicket.getTester().getDatabase();
	db.begin();
	main = recordId.getRecord();
	assertEmbeddedIsCorrect(main);
	db.commit();
}
 
Example #26
Source File: RecordIdObfuscatorTestSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void encodeAndDecode() {
  ORID rid = new ORecordId("#9:1");
  OClass type = mock(OClass.class);
  when(type.getClusterIds()).thenReturn(new int[] { rid.getClusterId() });
  log("RID: {}", rid);
  String encoded = underTest.encode(type, rid);
  log("Encoded: {}", encoded);
  ORID decoded = underTest.decode(type, encoded);
  log("Decoded: {}", decoded);
  assertThat(decoded.toString(), is("#9:1"));
}
 
Example #27
Source File: OrientDbDocumentTrial.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void loadNonExistingDocument() throws Exception {
  try (ODatabaseDocumentTx db = createDatabase()) {
    ORID rid = new ORecordId("#1:2"); // NOTE: #1:1 will return a record, #1:2 will return null
    log("RID: {}", rid);

    ORecordMetadata md = db.getRecordMetadata(rid);
    log("Metadata: {}", md);
    assertThat(md, nullValue());

    ORecordInternal record = db.load(rid);
    log("Record: {}", record);
    assertThat(record, nullValue());
  }
}
 
Example #28
Source File: OrientDbDocumentTrial.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void documentExistance() throws Exception {
  try (ODatabaseDocumentTx db = createDatabase()) {
    ODocument doc = createPerson(db);
    log("Document: {}", doc);

    ORID rid = doc.getIdentity();
    log("RID: {}", rid);

    ORecordMetadata md = db.getRecordMetadata(rid);
    log("Metadata: {}", md);
    assertThat(md, notNullValue());
  }
}
 
Example #29
Source File: OrientRebuildBrowseNodeServiceTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void executeProcessesAllAssetsInPages() throws RebuildBrowseNodeFailedException {
  ORID bucketId = AttachedEntityHelper.id(bucket);

  Asset asset1 = createMockAsset("#1:1");
  Asset asset2 = createMockAsset("#1:2");
  Asset asset3 = createMockAsset("#2:1");

  List<Entry<Object, EntityId>> page1 = asList(
      createIndexEntry(bucketId, EntityHelper.id(asset1)),
      createIndexEntry(bucketId, EntityHelper.id(asset2)));
  List<Entry<Object, EntityId>> page2 = asList(
      createIndexEntry(bucketId, EntityHelper.id(asset3)));
  List<Entry<Object, EntityId>> page3 = emptyList();

  when(assetStore.countAssets(any())).thenReturn(3L);
  when(assetStore.getNextPage(any(), eq(REBUILD_PAGE_SIZE))).thenReturn(page1, page2, page3);
  when(assetStore.getById(EntityHelper.id(asset1))).thenReturn(asset1);
  when(assetStore.getById(EntityHelper.id(asset2))).thenReturn(asset2);
  when(assetStore.getById(EntityHelper.id(asset3))).thenReturn(asset3);

  underTest.rebuild(repository, () -> false);

  verify(assetStore, times(3)).getNextPage(any(), eq(REBUILD_PAGE_SIZE));

  verify(browseNodeManager).createFromAssets(eq(repository), eq(asList(asset1, asset2)));
  verify(browseNodeManager).createFromAssets(eq(repository), eq(asList(asset3)));
}
 
Example #30
Source File: IndexSyncService.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nullable
private EntityId findComponentId(final ODocument document) {
  if (document.containsField(P_COMPONENT)) {
    // get the owning component from the asset, might be null if asset is standalone
    return componentId(document.field(P_COMPONENT, ORID.class));
  }
  else {
    // not an asset, must be a component itself
    return componentId(document.getIdentity());
  }
}