Java Code Examples for com.orientechnologies.orient.core.record.impl.ODocument#getIdentity()

The following examples show how to use com.orientechnologies.orient.core.record.impl.ODocument#getIdentity() . 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: 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 2
Source File: OrientConfigurationEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void readFields(final ODocument document, final OrientConfiguration 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);

  ODocument routingRule = document.field(P_ROUTING_RULE_ID, OType.LINK);
  EntityId routingRuleId =
      routingRule == null ? null : new AttachedEntityId(routingRuleEntityAdapter, routingRule.getIdentity());
  entity.setRoutingRuleId(routingRuleId);

  entity.setRecipeName(recipeName);
  entity.setRepositoryName(repositoryName);
  entity.setOnline(online);
  entity.setAttributes(decrypt(attributes));
}
 
Example 3
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 6 votes vote down vote up
@Override
public RESULT onRecordBeforeDelete(final ODocument iDocument) {
  final ORecordVersion version = iDocument.getRecordVersion(); // Cache the transaction-provided value
  if (iDocument.fields() == 0) {
    // FORCE LOADING OF CLASS+FIELDS TO USE IT AFTER ON onRecordAfterDelete METHOD
    iDocument.reload();
    if (version.getCounter() > -1 && iDocument.getRecordVersion().compareTo(version) != 0) // check for record version errors
      if (OFastConcurrentModificationException.enabled())
        throw OFastConcurrentModificationException.instance();
      else
        throw new OConcurrentModificationException(iDocument.getIdentity(), iDocument.getRecordVersion(), version,
            ORecordOperation.DELETED);
  }

  return RESULT.RECORD_NOT_CHANGED;
}
 
Example 4
Source File: PurgeUnusedSnapshotsFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds the next page of snapshot components that were last accessed before the specified date. The date when a
 * component was last downloaded is the last time an asset of that snapshot was downloaded.
 *
 * Uses an iterative approach in order to handle large repositories with many hundreds of thousands or millions of
 * assets. Note the current implementation is a bit hacky due to an Orient bug which prevents us from using a GROUP
 * BY with LIMIT. Furthermore, because of the required use of the Orient 'script sql' approach, we must loop through
 * the entire component set. Forward looking to Orient 3, it fixes the GROUP BY approach and this can be much
 * simplified. See NEXUS-13130 for further details.
 */
private List<Component> findNextPageOfUnusedSnapshots(final StorageTx tx,
                                                      final LocalDate olderThan,
                                                      final ORID bucketId,
                                                      final String unusedWhereTemplate)
{
  String query = format(UNUSED_QUERY, bucketId, lastComponent, findUnusedLimit, unusedWhereTemplate, olderThan,
      findUnusedLimit - 1);

  List<ODocument> result = tx.getDb().command(new OCommandScript("sql", query)).execute();

  if (isEmpty(result)) {
    return emptyList();
  }

  // get the last component to use in the WHERE for the next page
  ODocument lastDoc = Iterables.getLast(result).field(P_COMPONENT);
  lastComponent = lastDoc.getIdentity();

  Date olderThanDate = java.sql.Date.valueOf(olderThan);

  // filters in this stream are to check the last record as all others are filtered out in the 3rd part of the command query
  return result.stream() // remove entries that don't match on last download date
      .filter(entries -> {
        Date lastDownloaded = entries.field("lastdownloaded");
        return lastDownloaded.compareTo(olderThanDate) < 0;
      })
      .map(doc -> componentEntityAdapter.readEntity(doc.field(P_COMPONENT)))
      // remove entries that are not snapshots
      .filter(
          component -> {
            String baseVersion = (String) component.attributes().child(Maven2Format.NAME).get(P_BASE_VERSION);
            return baseVersion != null && baseVersion.endsWith("SNAPSHOT");
          })
      .collect(Collectors.toList());
}
 
Example 5
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 6
Source File: DeleteEdgeCommand.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void performMultiAction(AjaxRequestTarget target, List<ODocument> objects) {
       OrientGraph tx = orientGraphProvider.get();
       for (ODocument doc : objects) {
           ORID id = doc.getIdentity();
           OrientEdge edge = tx.getEdge(id);
           tx.removeEdge(edge);
       }
       tx.commit();tx.begin();
       sendActionPerformed();
}
 
Example 7
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
private static ODocument checkForLoading(final ODocument iRecord) {
  if (iRecord.getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) {
    try {
      return (ODocument) iRecord.load();
    } catch (final ORecordNotFoundException e) {
      throw new OIndexException("Error during loading of record with id : " + iRecord.getIdentity());
    }
  }
  return iRecord;
}
 
Example 8
Source File: ODocumentModel.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
  public void detach()
  {
if(isAttached())
{
	ODocument doc = getObject();
	if(doc!=null)
	{
		if(autoSave) doc.save();
        this.orid = doc.getIdentity();
        if(orid!=null && orid.isValid())
        {
        	savedDocument=null;
        }
        else
        {
        	orid=null;
        	savedDocument = doc;
        	//Should be there to avoid double documents and rolling back to prev doc
        	//Related issue https://github.com/orientechnologies/orientdb/issues/7646
        	//TODO: remove when that will be fixed in OrientDB
        	ORecordInternal.setDirtyManager(savedDocument, null);
        }
	}
	else
	{
		orid=null;
		savedDocument=null;
	}
}
super.detach();
  }
 
Example 9
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 10
Source File: UnlinkVertexCommand.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void performMultiAction(AjaxRequestTarget target, List<ODocument> objects) {
	super.performMultiAction(target, objects);
       OrientGraph tx = orientGraphProvider.get();
       for (ODocument doc : objects) {
           ORID id = doc.getIdentity();
           OrientVertex vertex = tx.getVertex(id);

           removeEdges(tx, vertex);
       }
       tx.commit();tx.begin();
       sendActionPerformed();
}
 
Example 11
Source File: ReferencesConsistencyHook.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private void removeLink(ODocument doc, OProperty property, ODocument value)
{
	if(doc==null || property ==null || value == null || isUnderTheLock(doc)) return;
	String field = property.getName();
	if(doc.getSchemaClass().isSubClassOf(property.getOwnerClass()))
	{
		Object wrappedValue = value.getIdentity().isPersistent()?value.getIdentity():value;
		if(property.getType().isMultiValue())
		{
			Collection<Object> objects = doc.field(field);
			if(objects!=null && objects.remove(wrappedValue))
			{
				doc.field(field, objects);
				//It's safe for multivalue docs
				saveOutOfHook(doc);
			}
		}
		else
		{
			if(value.getIdentity().equals(doc.field(field, ORID.class)))
			{
				doc.field(field, (Object) null);
				doc.save();
			}
		}
	}
}
 
Example 12
Source File: ReferencesConsistencyHook.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void addLink(ODocument doc, OProperty property, ODocument value)
{
	if(doc==null || property ==null || value == null || isUnderTheLock(doc)) return;
	String field = property.getName();
	if(doc.getSchemaClass().isSubClassOf(property.getOwnerClass()))
	{
		Object wrappedValue = value.getIdentity().isPersistent()?value.getIdentity():value;
		Object oldValue = doc.field(field);
		if(property.getType().isMultiValue())
		{
			Collection<Object> objects = (Collection<Object>) oldValue;
			if(objects==null)
			{
				objects = new ArrayList<Object>(1);
				objects.add(wrappedValue);
				doc.field(field, objects);
				//It's safe of fields with multivalue
				saveOutOfHook(doc);
			}
			else if(!objects.contains(wrappedValue)) 
			{
				objects.add(wrappedValue);
				//It's safe of fields with multivalue
				saveOutOfHook(doc);
			}
		}
		else
		{
			if (oldValue==null || !oldValue.equals(wrappedValue)){
				doc.field(field, wrappedValue);
				doc.save();
			}
		}
	}
}
 
Example 13
Source File: PagesMountedMapper.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
public PagesMountedMapper(ODocument page) {
	super(page.field(PagesModule.OPROPERTY_PATH), getPageClass(page), new OPageParametersEncoder(page.getIdentity()));
	pageIdentity = page.getIdentity();
}
 
Example 14
Source File: SaveODocumentCommand.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
public static RequiredOrientResource[] getRequiredResources(ODocument doc) {
	ORID orid = doc.getIdentity();
	OrientPermission permission = orid.isNew()?OrientPermission.CREATE:OrientPermission.UPDATE;
	return OSecurityHelper.requireOClass(doc.getSchemaClass(), permission);
}
 
Example 15
Source File: CalculablePropertiesHook.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
@Override
public void onRecordAfterRead(ODocument iDocument) {
	super.onRecordAfterRead(iDocument);
	OClass oClass = iDocument.getSchemaClass();
	if(oClass!=null)
	{
		List<String> calcProperties = getCalcProperties(iDocument);
		
		if(calcProperties!=null && calcProperties.size()>0)
		{
			for (String calcProperty :calcProperties) {
				//Force calculation. Required for work around issue in OrientDB
				//if(iDocument.field(calcProperty)!=null) continue;
				final OProperty property = oClass.getProperty(calcProperty);
				String script = CustomAttribute.CALC_SCRIPT.getValue(property);
				if(!Strings.isEmpty(script))
				{
					try {
						List<ODocument> calculated;
						if(FULL_QUERY_PATTERN.matcher(script).find())
						{
							calculated = iDocument.getDatabase().query(new OSQLSynchQuery<Object>(script), iDocument);
						}
						else
						{
							script = "select "+script+" as value from "+iDocument.getIdentity();
							calculated = iDocument.getDatabase().query(new OSQLSynchQuery<Object>(script));
						}
						if(calculated!=null && calculated.size()>0)
						{
							OType type = property.getType();
							Object value;
							if(type.isMultiValue())
							{
								final OType linkedType = property.getLinkedType();
								value = linkedType==null
										?calculated
										:Lists.transform(calculated, new Function<ODocument, Object>() {
											
											@Override
											public Object apply(ODocument input) {
												return OType.convert(input.field("value"), linkedType.getDefaultJavaType());
											}
										});
							}
							else
							{
								value = calculated.get(0).field("value");
							}
							value = OType.convert(value, type.getDefaultJavaType());
							Object oldValue = iDocument.field(calcProperty); 
							if (oldValue!=value && (oldValue==null || !oldValue.equals(value))){
								iDocument.field(calcProperty, value);
							}
						}
					} catch (OCommandSQLParsingException e) { //TODO: Refactor because one exception prevent calculation for others
						LOG.warn("Can't parse SQL for calculable property", e);
						iDocument.field(calcProperty, e.getLocalizedMessage());
					}
				}
			}
			
		}
	}
}
 
Example 16
Source File: ODocumentModel.java    From wicket-orientdb with Apache License 2.0 4 votes vote down vote up
/**
 * Get {@link ORID} of a stored {@link ODocument}
 * @return identifactor {@link ORID}
 */
public ORID getIdentity() {
	if(orid!=null) return orid;
	ODocument doc = getObject();
	return doc!=null?doc.getIdentity():null;
}
 
Example 17
Source File: ODocumentORIDConverter.java    From wicket-orientdb with Apache License 2.0 4 votes vote down vote up
@Override
protected ORID doForward(ODocument a) {
	return a.getIdentity();
}
 
Example 18
Source File: PageDelegate.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
public OPageResourceStream(ODocument page, String wrapTag) {
	super("text/html");
	content = (String) page.field(PagesModule.OPROPERTY_CONTENT);
	if(!Strings.isEmpty(wrapTag)) content = "<"+wrapTag+">"+content+"</"+wrapTag+">";
	location="OPage"+page.getIdentity()+"?v"+page.getVersion();
}
 
Example 19
Source File: SearchFacetImpl.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Converts a component's Orient record id to its {@link EntityId}.
 */
@Nullable
private EntityId componentId(@Nullable final ODocument doc) {
  return doc != null ? new AttachedEntityId(componentEntityAdapter, doc.getIdentity()) : null;
}
 
Example 20
Source File: AttachedEntityMetadata.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
public AttachedEntityMetadata(final EntityAdapter owner, final ODocument document) {
  this.owner = checkNotNull(owner);
  this.document = checkNotNull(document);
  this.id = new AttachedEntityId(owner, document.getIdentity());
  this.version = new AttachedEntityVersion(owner, document.getVersion());
}