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

The following examples show how to use com.orientechnologies.orient.core.id.ORecordId. 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: FormKey.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
public static FormKey parse(String formKey) {
	FormKey ret = new FormKey();
	if(formKey!=null) {
		Matcher m = FORM_KEY_PATTERN.matcher(formKey);
		if(m.matches()){
			ret.schemaClassName = m.group(2);
			String val = m.group(3);
			if(ORecordId.isA(val)) {
				ret.rid = new ORecordId(val);
			} else {
				ret.variableName = val;
			}
		}
	}
	return ret;
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: ODocumentsPage.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
protected IModel<List<ODocument>> resolveByPageParameters(PageParameters params) {
    String docs = params.get("docs").toOptionalString();
    IModel<List<ODocument>> result = new ListModel<>();

    if (!Strings.isNullOrEmpty(docs)) {
        List<ODocument> docsList = new LinkedList<>();
        result.setObject(docsList);
        if (docs.contains(",")) {
            String [] rids = docs.split(",");
            for (String rid : rids) {
                docsList.add(new ORecordId(rid).getRecord());
            }
        } else {
            docsList.add(new ORecordId(docs).getRecord());
        }
    }
    return result;
}
 
Example #9
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 #10
Source File: ODocumentPage.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected IModel<ODocument> resolveByPageParameters(PageParameters parameters) {
	String rid = parameters.get("rid").toOptionalString();
	if (rid != null) {
		try {
			return new ODocumentModel(new ORecordId(rid));
		} catch (IllegalArgumentException e) {
			//NOP Support of case with wrong rid
		}
	}
	String className = parameters.get("class").toOptionalString();
	return new ODocumentModel(!Strings.isEmpty(className) ? new ODocument(className) : null);
}
 
Example #11
Source File: AbstractODocumentPage.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected IModel<ODocument> resolveByPageParameters(PageParameters parameters) {
	String rid = parameters.get("rid").toOptionalString();
	if(rid!=null)
	{
		try
		{
			return new ODocumentModel(new ORecordId(rid));
		} catch (IllegalArgumentException e)
		{
			//NOP Support of case with wrong rid
		}
	}
	return new ODocumentModel((ODocument)null);
}
 
Example #12
Source File: FormKey.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
public ODocument calculateODocument(ProcessEngine processEngine, String taskId) {
	if(rid!=null) return (ODocument)rid.getRecord();
	if(variableName!=null) {
		Object recording = processEngine.getTaskService().getVariable(taskId, variableName);
		if(recording!=null) {
			return new ORecordId(recording.toString()).getRecord();
		}
	}
	if(schemaClassName!=null) {
		return new ODocument(schemaClassName);
	}
	return null;
}
 
Example #13
Source File: TestModels.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testODocumentPropertyLocator()
{
	ORecordId recordId = new ORecordId("#5:0");
	assertModelObjectEquals("admin", new PropertyModel<>(new ODocumentModel(recordId), "name"));
	assertModelObjectEquals("OUser", new PropertyModel<>(new ODocumentModel(recordId), "@schemaClass.name"));
}
 
Example #14
Source File: ODocumentTextChoiceProvider.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<ODocument> toChoices(final Collection<String> ids) {
    List<ODocument> documents = new ArrayList<ODocument>();
    for (String id : ids) {
        ORecordId rid = new ORecordId(id);
        ODocument ret = rid.getRecord();
        documents.add(ret);
    }
    return documents;
}
 
Example #15
Source File: ODocumentChoiceRenderer.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public ODocument getObject(String id,
		IModel<? extends List<? extends ODocument>> choicesModel) {
	if(ORecordId.isA(id)) {
		ORecordId rid = new ORecordId(id);
		ODocument ret =  rid.getRecord();
		List<? extends ODocument> choices = choicesModel.getObject();
		return choices!=null && choices.contains(ret)?ret:null;
	}
	return null;
}
 
Example #16
Source File: OLuceneMapEntryIterator.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public Map.Entry<K, V> next() {
  try {
    Document doc = reader.document(currentIdx);
    String val = "";
    if (definition.getFields().size() > 0) {
      for (String field : definition.getFields()) {
        val += doc.get(field);
      }
    } else {
      val = doc.get(OLuceneIndexManagerAbstract.KEY);
    }
    final String finalVal = val;
    final ORecordId id = new ORecordId(doc.get(OLuceneIndexManagerAbstract.RID));
    currentIdx++;
    return new Map.Entry<K, V>() {
      @Override
      public K getKey() {
        return (K) finalVal;
      }

      @Override
      public V getValue() {
        return (V) id;
      }

      @Override
      public V setValue(V value) {
        return null;
      }
    };
  } catch (IOException e) {
    OLogManager.instance().error(this, "Error on iterating Lucene result", e);
  }
  return null;
}
 
Example #17
Source File: ODocumentChoiceProvider.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<ODocument> toChoices(Collection<String> ids) {
    ArrayList<ODocument> documents = new ArrayList<ODocument>();
    for (String id : ids) {
        ORecordId rid = new ORecordId(id);
        ODocument ret = rid.getRecord();
        documents.add(ret);
    }
    return documents;
}
 
Example #18
Source File: RidUtils.java    From guice-persist-orient with MIT License 5 votes vote down vote up
private static String checkRid(final Object strVal) {
    final String val = (String) strVal;
    if (!ORecordId.isA(val)) {
        throw new PersistException(String.format("String '%s' is not rid", val));
    }
    return val;
}
 
Example #19
Source File: MainUtilsTest.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testDocumentConverter() throws Exception
{
	ORID orid = new ORecordId("#5:0"); //Admin ORID
	ODocument adminDocument = orid.getRecord();
	ODocumentConverter converter = new ODocumentConverter();
	assertEquals(adminDocument, converter.convertToObject("#5:0", Locale.getDefault()));
	assertEquals(orid, converter.convertToOIdentifiable("#5:0", Locale.getDefault()));
	assertEquals("#5:0", converter.convertToString(adminDocument, Locale.getDefault()));
}
 
Example #20
Source File: MainUtilsTest.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testDocumentWrapper() throws Exception
{
	ORID orid = new ORecordId("#5:0"); //Admin ORID
	ODocument adminDocument = orid.getRecord();
	OUser admin = wicket.getTester().getMetadata().getSecurity().getUser("admin");
	DocumentWrapperTransformer<OUser> transformer = new DocumentWrapperTransformer<OUser>(OUser.class);
	assertEquals(admin, transformer.apply(adminDocument));
}
 
Example #21
Source File: MainUtilsTest.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testConverters() throws Exception
{
	OSchema schema = wicket.getTester().getSchema();
	testConverter(OClassClassNameConverter.INSTANCE, schema.getClass("OUser"), "OUser");
	testConverter(OPropertyFullNameConverter.INSTANCE, schema.getClass("Ouser").getProperty("name"), "OUser.name");
	testConverter(OIndexNameConverter.INSTANCE, schema.getClass("Ouser").getClassIndex("OUser.name"), "OUser.name");
	ORID orid = new ORecordId("#5:0"); //Admin ORID
	ODocument document = orid.getRecord();
	testConverter(ODocumentORIDConverter.INSTANCE, document, orid);
}
 
Example #22
Source File: PurgeUnusedSnapshotsFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Deletes the unused snapshot components and their associated metadata.
 */
@TransactionalDeleteBlob
protected void deleteUnusedSnapshotComponents(LocalDate olderThan) {
  StorageTx tx = UnitOfWork.currentTx();

  // entire component count is used just for reporting progress
  Repository repo = getRepository();
  long totalComponents = tx.countComponents(builder().build(), singletonList(repo));
  log.info("Found {} total components in repository {} to evaluate for unused snapshots", totalComponents,
      repo.getName());

  ORID bucketId = id(tx.findBucket(getRepository()));
  String unusedWhereTemplate = getUnusedWhere(bucketId);

  long skipCount = 0;
  lastComponent = new ORecordId(-1, -1);
  while (skipCount < totalComponents && !isCanceled()) {
    log.info(PROGRESS,
        format("Processing components [%.2f%%] complete", ((double) skipCount / totalComponents) * 100));

    for (Component component : findNextPageOfUnusedSnapshots(tx, olderThan, bucketId, unusedWhereTemplate)) {
      if (isCanceled()) {
        return;
      }

      deleteComponent(component);
    }

    // commit each loop as well
    tx.commit();
    tx.begin();

    skipCount += findUnusedLimit;
  }
}
 
Example #23
Source File: EchoUrlResource.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected CharSequence getData(Attributes attributes) {
	PageParameters params = attributes.getParameters();
       String ridStr = "#"+params.get("rid").toOptionalString();
       ORID orid = ORecordId.isA(ridStr) ? new ORecordId(ridStr) : null;
       String field = params.get("field").toString();
       boolean full = params.get("full").toBoolean();
       return OContentShareResource.urlFor(orid.getRecord(), field, "text/plain", full);
}
 
Example #24
Source File: OPropertyValueValidator.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
protected void validateEmbedded(final IValidatable<T> validatable,
		final OProperty p, final Object fieldValue) {
	if (fieldValue instanceof ORecordId) {
		validatable.error(newValidationError("embeddedRecord"));
		return;
	} else if (fieldValue instanceof OIdentifiable) {
		if (((OIdentifiable) fieldValue).getIdentity().isValid()) {
			validatable.error(newValidationError("embeddedRecord"));
			return;
		}

		final OClass embeddedClass = p.getLinkedClass();
		if (embeddedClass != null) {
			final ORecord rec = ((OIdentifiable) fieldValue).getRecord();
			if (!(rec instanceof ODocument)) {
				validatable.error(newValidationError("embeddedNotDoc"));
				return;
			}

			final ODocument doc = (ODocument) rec;
			if (doc.getSchemaClass() == null
					|| !(doc.getSchemaClass().isSubClassOf(embeddedClass))) {
				validatable.error(newValidationError("embeddedWrongType", "expectedType", embeddedClass.getName()));
				return;
			}
		}

	} else {
		validatable.error(newValidationError("embeddedNotDoc"));
		return;
	}
}
 
Example #25
Source File: PurgeUnusedSnapshotsFacetImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void 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);
  when(bucket.getEntityMetadata()).thenReturn(entityMetadata);
}
 
Example #26
Source File: ConflictHook.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a record containing the original in-conflict changes.
 */
private ODocument getChangeRecord(final ORecordId rid, final byte[] content) {
  // check the 'record-save' cache as it's likely already there
  ODocument record = (ODocument) ORecordSaveThreadLocal.getLast();
  if (record == null || !rid.equals(record.getIdentity())) {
    record = new ODocument(rid).fromStream(content);
  }
  return record;
}
 
Example #27
Source File: EncryptedRecordIdObfuscator.java    From nexus-public with Eclipse Public License 1.0 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 #28
Source File: RecordIdObfuscatorPerfSupport.java    From nexus-public with Eclipse Public License 1.0 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 #29
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 #30
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"));
}