Working with Views

 

Author: Eike Stepper

This chapter covers view management, resource handling, querying, transactions, and related options in CDO client applications. Views are central to accessing and interacting with model data in a CDO repository. Understanding how to use views effectively is key to building responsive and scalable applications.

Table of Contents

1 Understanding Views and Their Types
2 Opening and Closing Views
3 Thread Safety
3.1 Using Critical Sections
3.2 Using a Delegable Lock
4 Understanding the CDO File System
4.1 The Root Resource
4.2 Resource Folders
4.3 Model Resources
4.4 Binary Resources
4.5 Text Resources
5 Resource Sets and Their Usage
6 Navigating Models
7 Waiting For Updates
8 Querying Resources
9 Querying Model Objects
10 Querying Cross References
11 Custom Queries
12 Units
13 View Events
13.1 View Invalidation Events
13.2 View Lock Events
13.3 View Permission Events
13.4 View Target Events
13.5 Adapter Notification Completion Events
13.6 Durability Events
13.7 Provider Events
14 View Options
14.1 Load Notification Enabled
14.2 Detachment Notification Enabled
14.3 Invalidation Notification Enabled
14.4 Invalidation Policy
14.5 Change Subscription Policies
14.6 Cache Reference Type
14.7 Strong Reference Policy
14.8 Stale Reference Policy
14.9 Revision Prefetching Policy
14.10 Feature Analyzer
14.11 Clear Adapter Policy
14.12 Lock Notification Enabled
15 View Properties

1  Understanding Views and Their Types

A view binds one client-side CDOView and its objects to a session, a resource set, and a branch point. Use a read-only view for navigation, queries, or a stable historical target; use a CDOTransaction when the operation must stage local edits and commit them. A normal head view can receive remote invalidations as repository commits arrive, so it is not a frozen snapshot. Audit or historical views read an explicit branch/time point and are read-only. Objects are view-scoped: reopen by persistent ID in another view instead of carrying model objects across view lifetimes.

OpenReadOnlyView.java      
CDOView view = session.openView();

try
{
  System.out.println("Opened view with ID: " + view.getViewID());
}
finally
{
  view.close();
}

shows a short-lived read; the transaction example

ModifyAndCommit.java      
CDOTransaction transaction = session.openTransaction();

try
{
  CDOObject object = transaction.getObject(objectID);
  if (!object.eClass().getEAllStructuralFeatures().contains(feature))
  {
    throw new IllegalArgumentException("Feature does not belong to the object's EClass");
  }

  object.eSet(feature, value);
  transaction.commit();
}
catch (CommitException | RuntimeException ex)
{
  transaction.rollback();
  throw ex;
}
finally
{
  transaction.close();
}

shows an editable view and its commit boundary.

2  Opening and Closing Views

Open views from a session with CDOSession.openView() for the current branch head, or choose an explicit branch point through the session's view-opener overloads. Open a transaction when the operation must modify data; a historical view is read-only. The session tracks its open views, their resource sets, caches, listeners, and remote view state, so close each view in a finally block or try-with-resources pattern when the work ends. Closing a view releases those resources and ends the validity of its model-object context. It does not close the session, which may create later views. Avoid sharing a single long-lived view across unrelated operations just to avoid reopening it; view lifetime should match the consistency and object-identity scope the application needs.

OpenReadOnlyView.java      
CDOView view = session.openView();

try
{
  System.out.println("Opened view with ID: " + view.getViewID());
}
finally
{
  view.close();
}

and

ModifyAndCommit.java      
CDOTransaction transaction = session.openTransaction();

try
{
  CDOObject object = transaction.getObject(objectID);
  if (!object.eClass().getEAllStructuralFeatures().contains(feature))
  {
    throw new IllegalArgumentException("Feature does not belong to the object's EClass");
  }

  object.eSet(feature, value);
  transaction.commit();
}
catch (CommitException | RuntimeException ex)
{
  transaction.rollback();
  throw ex;
}
finally
{
  transaction.close();
}

shows the transaction cleanup pattern.

3  Thread Safety

Views in CDO are inherently thread-safe, but this guarantee applies only to individual method calls. When performing multiple operations that need to be atomic or consistent, developers must use a CriticalSection to synchronize access to the view. A CDO view provides its critical section via the CDOView.sync().

Each individual access to a view or one of its objects is synchronized with the view's internal work. This does not make a sequence of separate calls atomic: an invalidation may occur between calls. Use CDOView.sync() around the smallest multi-call operation that must observe one coherent state. Keep that critical section short; do not wait for network work, block on another thread, or call arbitrary application callbacks while holding it.

3.1  Using Critical Sections

To ensure thread-safe access to a CDO view when performing multiple operations, use the view's critical section object. It is returned by the CDOView.sync() method. The critical section provides methods to execute code blocks safely, such as CriticalSection.run(Runnable) and CriticalSection.call(Callable).

Here is an example of using a critical section with a callable to access multiple objects in a view atomically:

CriticalSectionWithCallable.java      
CriticalSection sync = view.sync();

MyResult result = sync.call(() -> {
  // Access the view and its objects safely here.
  CDOObject object1 = view.getObject(id1);
  CDOObject object2 = view.getObject(id2);
  CDOObject object3 = view.getObject(id3);

  // Return a result object.
  return new MyResult();
});

The CriticalSection interface provides the following methods:

A view's critical section uses a real reentrant lock; the current default is a non-fair reentrant lock. A lock supplied with CDOUtil.setNextViewLock(Lock) or the session's delegable-lock option is used when configured. Synchronizing directly on the view object is unsupported. By default, CDO detects this when a view lock is next entered and throws UnsupportedOperationException, directing the caller to CDOView.sync(). Set -Dorg.eclipse.emf.cdo.view.DISABLE_INTRINSIC_MONITOR_CHECK=true to disable that safety check.

Deprecated monitor and lock methods fail fast by default. Set -Dorg.eclipse.emf.cdo.view.ENABLE_LEGACY_LOCKING_API=true to re-enable their best-effort behavior. The compatibility monitor returned by getViewMonitor() coordinates only callers that synchronize on that returned object; it does not coordinate by itself with CDO's internal view lock. The deprecated lock methods use the real view lock when enabled.

Here's an example of setting a custom lock for the next view to be opened:

CustomLockForNextView.java      
Lock customLock = new ReentrantLock();
CDOUtil.setNextViewLock(customLock);
CDOView view = null;
try
{
  view = session.openView();
  CriticalSection sync = view.sync();

  if (!(sync instanceof LockedCriticalSection) || ((LockedCriticalSection)sync).getLock() != customLock)
  {
    throw new IllegalStateException("The configured lock was not installed");
  }
}
finally
{
  if (view != null)
  {
    view.close();
  }

  CDOUtil.setNextViewLock(null);
}

A DelegableReentrantLock is useful when a framework synchronously hands work to another thread that must access the same view, such as an SWT UI callback. It solves that specific lock-ownership handoff; it is not a reason to hold the critical section across arbitrary blocking work. Register the relevant delegate detector and enable the session option or install the lock before opening the view.

3.2  Using a Delegable Lock

As an alternative to the default locking strategy of a view's critical section, you can use a DelegableReentrantLock, which allows to delegate the lock ownership to a different thread. This is useful in scenarios where you need to hold the lock while waiting for an asynchronous operation to complete in a different thread.

A typical example is the Display.syncExec() method in SWT/JFace UI applications. With the default locking strategy this can lead to deadlocks:

  1. Thread A (not the UI thread) holds the view lock and calls Display.syncExec() to execute some code in the UI thread.
  2. The Runnable passed to syncExec() is scheduled for execution in the UI thread. Thread A waits for the Runnable to complete.
  3. The UI thread executes the Runnable, which tries to access the view or an object of the view. This requires the view lock, which is already held by thread A.
  4. Deadlock: Thread A waits for the Runnable to complete and the UI thread waits for the view lock to be released.

Here is an example that illustrates this scenario:

DeadlockExample.java      
CDOObject object = view.getObject(id);
object.eAdapters().add(new AdapterImpl()
{
  @Override
  public void notifyChanged(Notification msg)
  {
    // This code is executed in a non-UI thread and holds the view lock.

    // The following call to Display.syncExec() will execute the Runnable in the UI thread
    // and make the current thread wait for it to complete. During that time the view lock
    // is still held by the current thread.
    Display.getDefault().syncExec(() -> {
      // This code is executed in the UI thread.
      // It tries to access the view while the view lock is held by the non-UI thread.
      // The result is a deadlock.
      CDOResource resource = view.getResource("/my/resource");
    });
  }
});

Note that, in this scenario, Thread A is holding the view lock while waiting for the Runnable to complete. This is kind of an anti-pattern, because it blocks other threads from accessing the view for an indeterminate amount of time. In addition, it is not necessary to hold the view lock while waiting for the Runnable to complete, because Thread A can not access the view in that time.

A DelegableReentrantLock can be used to avoid the deadlock. It uses so called lock delegation to temporarily transfer the ownership of the lock to a different thread. In the scenario described above, Thread A can delegate the lock ownership to the UI thread while waiting for the Runnable to complete. When the Runnable completes, the lock ownership is transferred back to Thread A. This way, the UI thread can access the view while executing the Runnable and no deadlock occurs.

DelegableReentrantLock uses DelegateDetectors to determine whether the current thread is allowed to delegate the lock ownership to a different thread. A DelegateDetector can be registered with the lock by calling DelegableReentrantLock.addDelegateDetector(DelegateDetector). The org.eclipse.net4j.util.ui plugin provides a DisplayDelegateDetector for the SWT/JFace UI thread that detects calls to Display.syncExec().

There are two ways to use a DelegableReentrantLock with a CDO view:

  1. Set the lock as the next view lock by calling CDOUtil.setNextViewLock(Lock) before opening the view. This way, the view will use the lock for its critical section. Here's an example:

    IndividualViewLock.java      
    CDOUtil.setNextViewLock(new DelegableReentrantLock());

    CDOView view = session.openView();
    CriticalSection sync = view.sync();

    // Acquire the view lock.
    sync.run(() -> {
      // This code is executed in a non-UI thread and holds the view lock.

      // The following call to Display.syncExec() will execute the Runnable in the UI thread
      Display.getDefault().syncExec(() -> {
        // This code is executed in the UI thread.
        // It can access the view because the lock ownership has been delegated to the UI thread.
        CDOResource resource = view.getResource("/my/resource");
        System.out.println("Resource: " + resource.getURI());
      });
    });

  2. Set delegableViewLockEnabled to true on the session. This way, all views opened from the session will use a DelegableReentrantLock for their critical section. The lock is created automatically and configured with all DelegateDetectors that are registered. Example:

    SetDelegableViewLockEnabled.java      
    session.options().setDelegableViewLockEnabled(true);

    CDOView view = session.openView();
    CriticalSection sync = view.sync();

    // Acquire the view lock.
    sync.run(() -> {
      // This code is executed in a non-UI thread and holds the view lock.

      // The following call to Display.syncExec() will execute the Runnable in the UI thread
      Display.getDefault().syncExec(() -> {
        // This code is executed in the UI thread.
        // It can access the view because the lock ownership has been delegated to the UI thread.
        CDOResource resource = view.getResource("/my/resource");
        System.out.println("Resource: " + resource.getURI());
      });
    });

4  Understanding the CDO File System

The CDO repository exposes a virtual file system for organizing model resources. This section describes the structure and usage of the file system, including root resources, folders, and different resource types.

4.1  The Root Resource

The root resource is the entry point to the CDO file system. It contains all top-level folders and resources, providing a hierarchical view of the repository's contents.

Each CDO view or transaction can provide the root resource. Here is an example of how to access and list the contents of the root resource:

GetRootResource.java      
// Each CDO view or transaction can provide the root resource.
CDOResource rootResource = view.getRootResource();

for (EObject content : rootResource.getContents())
{
  if (content instanceof CDOResourceFolder)
  {
    CDOResourceFolder folder = (CDOResourceFolder)content;
    System.out.println("Folder: " + folder.getName());
  }
  else if (content instanceof CDOResource)
  {
    CDOResource resource = (CDOResource)content;
    System.out.println("Model Resource: " + resource.getName());
  }
  else if (content instanceof CDOBinaryResource)
  {
    CDOBinaryResource binary = (CDOBinaryResource)content;
    System.out.println("Binary File: " + binary.getName());
  }
  else if (content instanceof CDOTextResource)
  {
    CDOTextResource text = (CDOTextResource)content;
    System.out.println("Text File: " + text.getName());
  }
}

When you don't have a view or transaction available, you can ask a session for the root resource's ID as follows:

GetRootResourceID.java      
CDOID rootResourceID = session.getRepositoryInfo().getRootResourceID();
CDOBranch mainBranch = session.getBranchManager().getMainBranch();

CDORevision rootResourceRevision = session.getRevisionManager().request().getRevision(rootResourceID, mainBranch.getHead());
System.out.println("Root Resource Revision: " + rootResourceRevision);

The root resource of a repository is created automatically when the repository is initialized for the first time. It can not be deleted, but its contents can be modified like any other resource.

4.2  Resource Folders

The CDO resource hierarchy is a repository-side virtual file system. A CDOResourceFolder is a persistent model object that contains resource nodes; those nodes may be folders, model resources, binary resources, or text resources. Use folders when resource paths need meaningful grouping and use the node APIs to enumerate children without loading every model's contents. Folder creation is a transaction change and becomes visible to other views only after commit.

For creating resource folders you need a CDOTransaction. Here is an example that illustrates how to create folders and subfolders:

CreateFolder.java      
// Create a new folder at the specified path directly in the transaction.
CDOResourceFolder folder = transaction.createResourceFolder("/my/new/folder");
System.out.println("Created folder: " + folder.getPath()); // Outputs: /my/new/folder

CDOResourceFolder parent = folder.getFolder();
System.out.println("Parent folder: " + parent.getPath()); // Outputs: /my/new

CDOResourceFolder parent2 = parent.getFolder();
System.out.println("Parent parent folder: " + parent2.getPath()); // Outputs: /my

// Create a subfolder within the newly created folder.
CDOResourceFolder subfolder = folder.addResourceFolder("subfolder");
System.out.println("Created subfolder: " + subfolder.getPath()); // Outputs: /my/new/folder/subfolder

// None of the above changes are visible in other views/transactions.
// They become visible only after committing the transaction.
transaction.commit();

Listing subnodes (folders and resources) within a folder does not require a transaction and can be done as follows:

ListSubNodes.java      
// List all nodes (folders and resources) within the folder.
for (CDOResourceNode node : folder.getNodes())
{
  System.out.println("Node: " + node.getName());
}

// Access a specific subnode by name.
CDOResourceNode subnode = folder.getNode("subfolder"); // May return null.
if (subnode instanceof CDOResourceFolder)
{
  CDOResourceFolder subfolder = (CDOResourceFolder)subnode;
  System.out.println("Subfolder path: " + subfolder.getPath());
}

Note that resource folders are model objects and therefore support EMF features such as adapters, notifications, and so on.

4.3  Model Resources

A CDOResource is an EMF resource backed by a CDO view. Its root objects and resource metadata participate in the view's model and notification behavior; creating a resource or changing its contents requires a CDOTransaction. Loading it in a read-only view gives access to repository state through that view's ResourceSet. Adding a resource to an ordinary EMF ResourceSet does not persist it in CDO; use the CDO transaction's resource-creation APIs and commit the transaction to publish the change.

For creating model resources you need a CDOTransaction. Here is an example that illustrates how to create model resources:

CreateResource.java      
// Create a new folder at the specified path directly in the transaction.
CDOResource resource = transaction.createResource("/my/new/resource");
System.out.println("Created resource: " + resource.getPath()); // Outputs: /my/new/resource

// Your method to create the root object.
EObject rootObject = createContentTree();

// Add the root object to the resource's contents.
resource.getContents().add(rootObject);

// CDO resources support multiple root objects.
resource.getContents().add(EcoreUtil.copy(rootObject));

// None of the above changes are visible in other views/transactions.
// They become visible only after committing the transaction.
transaction.commit();

Listing root objects and contained objects within a model resource does not require a transaction and can be done as follows:

GetContents.java      
// List root objects in the resource.
for (EObject rootObject : resource.getContents())
{
  System.out.println("Root object: " + rootObject);
}

// Iterate over all contained objects in the resource. Normal EMF model object operation.
TreeIterator<EObject> allContents = resource.eAllContents();
allContents.forEachRemaining(eObject -> System.out.println("Contained object: " + eObject));

Note that model resources are model objects and therefore support EMF features such as adapters, notifications, and so on.

4.4  Binary Resources

Binary resources allow storage of non-model data, such as images or files, within the CDO repository. They are based on CDO's special data type CDOBlob, which supports efficient handling of large binary objects. Large object support is described in detail in the chapter Large Objects.

For creating binary resources you need a CDOTransaction. Here is an example that illustrates how to create binary resources:

CreateBinaryFile.java      
// Create a new binary file at the specified path directly in the transaction.
CDOBinaryResource binary = transaction.createBinaryResource("/my/new/file");
System.out.println("Created binary file: " + binary.getPath()); // Outputs: /my/new/file

CDOBlob blob = transaction.getSession().newBlob(new byte[] { 0, 1, 2, 3, 4, 5 });
binary.setContents(blob);

// None of the above changes are visible in other views/transactions.
// They become visible only after committing the transaction.
transaction.commit();

Getting the binary contents of a binary resource does not require a transaction and can be done as follows:

GetContents.java      
// Get the binary contents.
CDOBlob blob = binary.getContents();

// Print some information about the binary contents.
System.out.println("Binary contents ID: " + blob.getID());
System.out.println("Binary contents size: " + blob.getSize());

// For demonstration purposes, copy the binary contents to System.out.
blob.copyTo(System.out);

try (InputStream stream = blob.getContents())
{
  // Or do something else with the InputStream...
}

Note that binary resources are model objects and therefore support EMF features such as adapters, notifications, and so on.

4.5  Text Resources

Text resources store textual data, such as configuration files or documentation, in the repository. They are based on CDO's special data type CDOClob, which supports efficient handling of large text objects. Large object support is described in detail in the chapter Large Objects.

For creating text resources you need a CDOTransaction. Here is an example that illustrates how to create text resources:

CreateTextFile.java      
// Create a new text file at the specified path directly in the transaction.
CDOTextResource text = transaction.createTextResource("/my/new/text");
System.out.println("Created text file: " + text.getPath()); // Outputs: /my/new/file

CDOClob clob = transaction.getSession().newClob("Hello, CDO Text Resource!");
text.setContents(clob);

// None of the above changes are visible in other views/transactions.
// They become visible only after committing the transaction.
transaction.commit();

Getting the text contents of a text resource does not require a transaction and can be done as follows:

GetContents.java      
// Get the text contents.
CDOClob clob = text.getContents();

// Print some information about the binary contents.
System.out.println("Text contents ID: " + clob.getID());
System.out.println("Text contents size: " + clob.getSize());

// For demonstration purposes, copy the binary contents to System.out.
clob.copyTo(new OutputStreamWriter(System.out));

try (Reader reader = clob.getContents())
{
  // Or do something else with the Reader...
}

Note that text resources are model objects and therefore support EMF features such as adapters, notifications, and so on.

5  Resource Sets and Their Usage

A CDOView is the CDO access context; its ResourceSet is the EMF loading context used to resolve CDO resource URIs and keep the resulting objects associated with that view. A session can create a ResourceSet for a view or the caller can supply one through a CDOSession.openView(ResourceSet) overload. In either case, use that set with its view for the view's lifetime. CDO objects are view-scoped; moving a resource to another set does not transfer its identity or make its objects usable in another view. Reopen objects there by CDOObject.cdoID().

Use getResource(path) when the repository path is already known. Use CDOView.createResourceURI(String) with ResourceSet.getResource(URI, boolean) when integrating with code that follows normal EMF URI loading. Proxy resolution then uses the resource set's URI handling and resolves CDO targets in the owning view. Ordinary EMF resources may coexist in a ResourceSet when their resource factories and URI handlers are registered; those resources retain their own persistence semantics and are not made persistent by being placed beside a CDO resource. See Integrating with EMF and Other Frameworks for broader EMF integration.

The examples show direct path lookup and EMF URI loading from the same view ResourceSet:

LoadResources.java      
CDOResource byPath = view.getResource("/library/books");
ResourceSet resourceSet = view.getResourceSet();

URI uri = view.createResourceURI("/library/authors");
Resource byURI = resourceSet.getResource(uri, true);
System.out.println(byPath.getContents().size() + ": " + byURI.getURI());

6  Navigating Models

Use ordinary EMF navigation for a known, bounded part of the graph: EObject.eContainer(), EObject.eContents(), EObject.eGet(EStructuralFeature), and generated getters all preserve normal EMF semantics. Containment navigation visits already-related objects, while non-containment references can be represented by proxies. Resolving a proxy may fetch a target from the repository, so a broad traversal can produce many remote loads and a large view cache. Keep navigation in one view; do not compare object identity across views.

For a known persistent identifier use CDOView.getObject(CDOID); for several identifiers, CDOView.getObjects(java.util.Collection) retrieves missing objects in one round trip. For repository-wide selection by EClass use CDOView.queryInstances(org.eclipse.emf.ecore.EClass). Prefer traversal for a bounded local graph, bulk lookup for a known ID set, and a query when the repository should select candidates. The example receives two persistent identifiers: rootID for the traversal root and relatedID for the independent bulk lookup. It demonstrates graph walking and batched ID lookup:

NavigateAndLoad.java      
CDOObject root = view.getObject(rootID);
TreeIterator<EObject> contents = root.eAllContents();

while (contents.hasNext())
{
  EObject child = contents.next();

  for (EReference reference : child.eClass().getEAllReferences())
  {
    child.eGet(reference);
  }
}

CDOObject related = view.getObjects(Collections.singleton(relatedID)).get(relatedID);
System.out.println(related);

7  Waiting For Updates

CDOView implements org.eclipse.emf.cdo.util.CDOUpdatable. Its org.eclipse.emf.cdo.util.CDOUpdatable.getLastUpdateTime() reports the timestamp of the last processed update; this may be inaccurate when passive updates are disabled. org.eclipse.emf.cdo.util.CDOUpdatable.waitForUpdate(long, long) blocks until the view has processed at least the requested commit timestamp or its timeout expires, returning true only when the timestamp is reached. Pass org.eclipse.emf.cdo.util.CDOUpdatable.NO_TIMEOUT to wait indefinitely.

Waiting does not enable passive updates. That is session-wide configuration and must be enabled on CDOSession.Options; it affects views from that session. Head views then process remote commits according to their invalidation policy. A historical view remains at its selected branch point. For event-driven UI work, observe view invalidation events instead of polling. Never wait while holding CDOView.sync(): update processing may need the view's synchronization lock. Also avoid blocking a UI thread or a callback needed by the update dispatcher.

This example waits for an expected commit timestamp with a bounded timeout. In a two-session application, obtain the timestamp from the committing session's commit result or commit-info event and pass it to the observing view:

WaitForRemoteCommit.java      
boolean received = view.waitForUpdate(commitTime, 10_000);
if (received)
{
  System.out.println("View reached commit time " + view.getLastUpdateTime());
}
else
{
  System.out.println("Timed out; last processed update was " + view.getLastUpdateTime());
}

8  Querying Resources

CDOView.queryResources(CDOResourceFolder, String, boolean) searches child resource nodes in one folder; pass null for the folder to search at the repository root. With exactMatch == true, the name must match exactly; otherwise the name is a prefix. The synchronous method returns a java.util.List. Its asynchronous counterpart CDOView.queryResourcesAsync(CDOResourceFolder, String, boolean) streams through a org.eclipse.net4j.util.collection.CloseableIterator, which must be closed even when iteration stops early. A resource query does not recursively search every descendant folder. Use it to select nodes before loading model contents, rather than walking a large folder tree and opening every resource.

This example contrasts exact matching with prefix matching and closes the asynchronous iterator:

FindResources.java      
List<CDOResourceNode> exact = view.queryResources(folder, "books", true);
System.out.println("Exact matches: " + exact.size());

CloseableIterator<CDOResourceNode> matches = view.queryResourcesAsync(folder, "book", false);

try
{
  while (matches.hasNext())
  {
    System.out.println(matches.next().getPath());
  }
}
finally
{
  matches.close();
}

9  Querying Model Objects

CDOView.queryInstances(org.eclipse.emf.ecore.EClass) selects instances of an org.eclipse.emf.ecore.EClass; use CDOView.queryInstancesAsync(org.eclipse.emf.ecore.EClass, boolean) when results should be consumed incrementally. The exact flag controls whether only that EClass is matched or compatible subtypes are included. Returned EObjects belong to the querying view and must not outlive or be passed to another view as if their identity were shared. Asynchronous iterators are closeable and should be used in try-with-resources.

Repository selection is useful when a matching set is spread across resources. Avoid querying an overly broad base type when the result is large; constrain the EClass or use a supported custom query when the predicate needs server-side expression. Transaction queries have transaction-specific behavior for local changes; see CDOTransaction and do not treat them as arbitrary in-memory graph scans. Here is a synchronous and asynchronous pattern, where type is the desired package classifier:

FindInstances.java      
List<EObject> all = view.queryInstances(type);
System.out.println("Instances: " + all.size());

CloseableIterator<EObject> matches = view.queryInstancesAsync(type, true);

try
{
  while (matches.hasNext())
  {
    EObject object = matches.next();
    System.out.println(CDOUtil.getCDOObject(object).cdoID());
  }
}
finally
{
  matches.close();
}

10  Querying Cross References

CDOView.queryXRefs(CDOObject, EReference...) and its set overload ask the repository for incoming references to one or several targets. An empty reference array means all source references; supplying features narrows the search. Each CDOObjectReference describes the referencing source object and the source reference (and, for many-valued features, the list index); it is not an inverse reference value already loaded into the target EObject. This server-assisted lookup is useful when inverse edges have not been loaded. If the local graph is already loaded and bounded, normal EMF traversal may be simpler.

The asynchronous form streams results and requires closure. The example filters by one EReference:

FindIncomingReferences.java      
CloseableIterator<CDOObjectReference> refs = view.queryXRefsAsync(Collections.singleton(target), reference);

try
{
  while (refs.hasNext())
  {
    CDOObjectReference ref = refs.next();
    System.out.println(ref.getSourceObject() + " via " + ref.getSourceReference().getName());
  }
}
finally
{
  refs.close();
}

11  Custom Queries

A org.eclipse.emf.cdo.view.CDOQuery is a request associated with the creating view. Create it with CDOView.createQuery(String, String) or its context overload, set named arguments with org.eclipse.emf.cdo.view.CDOQuery.setParameter(String, Object), and optionally cap transfer with org.eclipse.emf.cdo.view.CDOQuery.setMaxResults(int). Query language identifiers and expressions are interpreted by a matching server IQueryHandler; availability depends on server registration and any required integration bundles. A client-side language constant alone does not install server support.

org.eclipse.emf.cdo.view.CDOQuery.getResult(Class) waits for the complete typed result list; org.eclipse.emf.cdo.view.CDOQuery.getResultAsync(Class) returns a streaming closeable iterator. org.eclipse.emf.cdo.view.CDOQuery.getResultValue(Class) is for a scalar result produced by the handler. Choose the result type expected by that handler. Async iterators must be closed, including on errors or early termination. Invalid parameter names or value types can fail during binding; parsing and execution failures are reported by query execution. For server handler implementation and registration, see Query Handlers.

This example uses the optional OCL integration and therefore requires its server handler to be installed. The supplied context object must have a purchaseOrders reference:

ExecuteOCLQuery.java      
CDOQuery query = view.createQuery("ocl", "self.purchaseOrders->size()", company);
Integer count = query.getResultValue(Integer.class);
System.out.println("Purchase orders: " + count);

12  Units

A org.eclipse.emf.cdo.view.CDOUnit is a managed set of disjunct object subtrees rooted at CDO objects. Unlike a resource, a unit can gather related subtrees without requiring one common containment root. The view's unit manager discovers and opens units, creates them, and manages units opened for the view. Unit APIs expose roots and loaded element counts; they do not change the transaction boundary or make arbitrary objects outside the unit free to access. Unit availability and persistence behavior depend on the repository/store implementation and its capabilities, so do not assume every store supports every operation.

Units belong to their view and must be closed before that view. Closing releases retained elements and subscriptions. Open units can receive change notifications according to their subscription configuration. Retaining a large unit trades fewer later loads for client memory. CDO also manages resource units for resource-backed loading; these are distinct from explicitly created units. Create/open operations have explicit lifetimes; use on-demand opening only when a missing unit should be created. Create through a transaction and supply a root object from that same view. Repository configuration must support units. This example creates and closes one:

CreateAndCloseUnit.java      
CDOUnit unit = transaction.getUnitManager().createUnit(root, true, null);

try
{
  System.out.println("Unit root: " + unit.getRoot());
  System.out.println("Loaded elements: " + unit.getElements());
}
finally
{
  unit.close();
}

To open an existing unit, use org.eclipse.emf.cdo.view.CDOUnitManager.openUnit(EObject, boolean, org.eclipse.core.runtime.IProgressMonitor). The inspection example checks membership using org.eclipse.emf.cdo.view.CDOUnitManager.getOpenUnit(EObject):

InspectUnit.java      
CDOUnit unit = view.getUnitManager().getOpenUnit(root);
if (unit != null)
{
  System.out.println("Unit root: " + unit.getRoot());
  System.out.println("Loaded elements: " + unit.getElements());
  unit.close();
}

13  View Events

org.eclipse.emf.cdo.view.CDOViewEvent is the common view-scoped event contract; its source is the affected view. Listen on the view's org.eclipse.net4j.util.event.INotifier.addListener(org.eclipse.net4j.util.event.IListener) mechanism and remove the same listener when its owner is disposed. Events may be delivered on CDO-managed threads. Copy the event data needed by the UI and dispatch UI work to the UI thread; do not block update processing or hold a view critical section while calling application code. Session lifecycle events remain session events. EMF notifications go to adapters attached to model objects; option-change events come from view.options(); and org.eclipse.emf.cdo.view.CDOViewEventProducer produces events for its specialized adapters. These channels have different sources and purposes. See Notifications and Event Handling for general guidance.

Registering and removing a listener:

ObserveViewEvents.java      
IListener listener = event -> {
  if (event instanceof CDOViewEvent)
  {
    System.out.println("View event: " + event.getClass().getSimpleName());
  }
};

view.addListener(listener);
view.removeListener(listener);

13.1  View Invalidation Events

org.eclipse.emf.cdo.view.CDOViewInvalidationEvent is emitted after a view processes a remote commit. It exposes the commit timestamp, dirty objects, revision deltas, and detached objects. It reports view update processing; adapters receive their own EMF notifications separately. Keep listeners fast and use the timestamp to correlate with org.eclipse.emf.cdo.view.CDOViewAdaptersNotifiedEvent.

13.2  View Lock Events

org.eclipse.emf.cdo.view.CDOViewLocksChangedEvent reports lock changes visible to the view, including sender and affected objects. Use it to refresh lock decorations; it is distinct from a lock acquisition call result. Delivery follows view event threading rules.

13.3  View Permission Events

org.eclipse.emf.cdo.view.CDOViewPermissionsChangedEvent carries a map of object IDs to old/new permissions when permissions visible to the view change. Applications can refresh enabled actions from this event. Permission state may also depend on server security configuration.

13.4  View Target Events

org.eclipse.emf.cdo.view.CDOViewTargetChangedEvent reports the old and new branch point when a movable view changes target. It is useful for invalidating client presentations tied to a branch point. A fixed historical view does not advance merely because a commit occurs.

13.5  Adapter Notification Completion Events

org.eclipse.emf.cdo.view.CDOViewAdaptersNotifiedEvent indicates that the view has finished notifying EMF adapters for a remote commit; its timestamp correlates with the invalidation event. This is a view event about completed adapter delivery, not an individual Notification and not an adapter notification itself.

13.6  Durability Events

org.eclipse.emf.cdo.view.CDOViewDurabilityChangedEvent reports changes to a view's durable-locking identifier, exposing the old and new IDs. Use it to track durability state; lock operations and lock-change events remain separate APIs.

13.7  Provider Events

org.eclipse.emf.cdo.view.CDOViewProviderChangedEvent reports the old and new provider associated with a view. It is primarily useful to infrastructure managing view-provider selection; ordinary clients rarely need it. Treat it as a view event and keep its callback short.

14  View Options

CDOView.Options controls view-local notification, invalidation, cache, and loading behavior. These settings differ from CDOSession.Options, which configures the session and can affect all its views (for example passive updates). Option changes emit org.eclipse.net4j.util.options.IOptionsEvents from the options object, not org.eclipse.emf.cdo.view.CDOViewEvents from the view. Defaults below refer to the current API implementation; session configuration and repository capabilities can affect observed behavior.

A listener can observe option changes directly:

WatchOptions.java      
IListener listener = event -> System.out.println(event.getClass().getSimpleName());

view.options().addListener(listener);
view.options().setLoadNotificationEnabled(true);
view.options().removeListener(listener);

14.1  Load Notification Enabled

CDOView.Options.isLoadNotificationEnabled() and CDOView.Options.setLoadNotificationEnabled(boolean) control EMF adapter notifications when objects load. The implementation default is false. Enable this when adapters maintain derived or presentation state that must react to loading. It is separate from remote invalidation and subscriptions; changes emit CDOView.LoadNotificationEvent.

14.2  Detachment Notification Enabled

CDOView.Options.isDetachmentNotificationEnabled() and CDOView.Options.setDetachmentNotificationEnabled(boolean) control adapter notification when remote changes detach objects. The default is false. Enable it when clients need to discard references to removed objects. It does not subscribe objects; changes emit CDOView.DetachmentNotificationEvent.

14.3  Invalidation Notification Enabled

CDOView.Options.isInvalidationNotificationEnabled() and CDOView.Options.setInvalidationNotificationEnabled(boolean) control object adapter invalidation notifications. Default is false. This controls EMF notifications, not whether the view processes remote commits or emits its view-level invalidation event. Changes emit CDOView.InvalidationNotificationEvent.

14.4  Invalidation Policy

CDOView.Options.getInvalidationPolicy() and CDOView.Options.setInvalidationPolicy(org.eclipse.emf.cdo.view.CDOInvalidationPolicy) select how a view treats remotely changed objects. The default is org.eclipse.emf.cdo.view.CDOInvalidationPolicy.RELAXED; org.eclipse.emf.cdo.view.CDOInvalidationPolicy.STRICT clears the object's revision on invalidation and reports objects that have become invalid, while RELAXED leaves that handling to later access. This is view-local and requires the session to receive passive updates. Changes emit CDOView.InvalidationPolicyEvent.

14.5  Change Subscription Policies

CDOView.Options.getChangeSubscriptionPolicies(), CDOView.Options.addChangeSubscriptionPolicy(CDOAdapterPolicy), and CDOView.Options.removeChangeSubscriptionPolicy(CDOAdapterPolicy) select adapted objects registered for remote changes. Initially the policy set is empty. Common policies are CDOAdapterPolicy.NONE, CDOAdapterPolicy.ALL, and CDOAdapterPolicy.CDO; an object needs a matching adapter. Session passive updates must also be enabled. Changes emit CDOView.ChangeSubscriptionPoliciesEvent.

14.6  Cache Reference Type

CDOView.Options.getCacheReferenceType() and CDOView.Options.setCacheReferenceType(org.eclipse.net4j.util.ref.ReferenceType) select strong, soft, or weak references in the view cache. The implementation default is org.eclipse.net4j.util.ref.ReferenceType.SOFT. Strong references retain objects and increase memory; soft and weak references permit collection subject to the strong-reference policy. Passing null restores soft references. The setter reports whether it changed and emits CDOView.CacheReferenceTypeEvent.

14.7  Strong Reference Policy

CDOView.Options.getStrongReferencePolicy() and CDOView.Options.setStrongReferencePolicy(CDOAdapterPolicy) choose which adapted objects remain strongly referenced when the cache reference type is non-strong. Default is CDOAdapterPolicy.ALL; policies can be narrowed to NONE, CDO, or a custom policy. Balance memory use against adapter/object continuity. Changes emit CDOView.StrongReferencePolicyEvent.

14.8  Stale Reference Policy

CDOView.Options.getStaleReferencePolicy() and CDOView.Options.setStaleReferencePolicy(org.eclipse.emf.cdo.view.CDOStaleReferencePolicy) control references to objects absent at the view target. The default is org.eclipse.emf.cdo.view.CDOStaleReferencePolicy.PROXY, which supplies a dynamic proxy; the org.eclipse.emf.cdo.view.CDOStaleReferencePolicy.EXCEPTION policy throws an org.eclipse.emf.cdo.util.ObjectNotFoundException. The older Behaviour methods are deprecated. Changes emit CDOView.StaleReferencePolicyEvent.

14.9  Revision Prefetching Policy

CDOView.Options.getRevisionPrefetchingPolicy() and CDOView.Options.setRevisionPrefetchingPolicy(org.eclipse.emf.cdo.view.CDORevisionPrefetchingPolicy) control fetching revisions in advance to reduce later round trips. The current implementation initializes the policy to NO_REVISION_PREFETCHING; DEFAULT_REVISION_PREFETCHING is a policy constant, not a guarantee of every read's batch size. Profile before tuning because prefetching trades transfer and memory for fewer later requests. Changes emit CDOView.RevisionPrefetchingPolicyEvent.

14.10  Feature Analyzer

CDOView.Options.getFeatureAnalyzer() and CDOView.Options.setFeatureAnalyzer(org.eclipse.emf.cdo.view.CDOFeatureAnalyzer) install analysis of feature access for loading strategies. Default is CDOFeatureAnalyzer.NOOP. It does not change model semantics. Changes emit CDOView.FeatureAnalyzerEvent.

14.11  Clear Adapter Policy

CDOView.Options.getClearAdapterPolicy() and CDOView.Options.setClearAdapterPolicy(CDOAdapterPolicy) select which adapters CDO removes when clearing object adapters. Per-view default is null, so the view set's default policy applies. Changes emit CDOView.ClearAdapterPolicyEvent.

14.12  Lock Notification Enabled

This inherited option is managed by org.eclipse.emf.cdo.common.CDOCommonView.Options.isLockNotificationEnabled() and org.eclipse.emf.cdo.common.CDOCommonView.Options.setLockNotificationEnabled(boolean). Default is false; enabling it requests protocol lock-state updates for this view and requires appropriate server support. The session's org.eclipse.emf.cdo.common.CDOCommonSession.Options.setLockNotificationMode(org.eclipse.emf.cdo.common.CDOCommonSession.Options.LockNotificationMode) also controls notification delivery modes. Changes emit the inherited org.eclipse.emf.cdo.common.CDOCommonView.Options.LockNotificationEvent; this is an option event, not a view event.

15  View Properties

CDOView.properties() exposes the view's org.eclipse.net4j.util.properties.IPropertiesContainer for application metadata. Properties are local to that view's lifetime, are not persisted in the repository, and are distinct from session properties and persistent EStructuralFeatures. Use application-owned keys and remove values when they are no longer needed, especially if they retain large UI or model graphs. Property access and listener behavior follow the properties-container API; do not assume cross-thread safety beyond the guarantees of the concrete container. The example sets, reads, and removes a value:

UseViewProperties.java      
String key = "com.example.selection";
view.properties().put(key, "current-page");

Object selection = view.properties().get(key);
System.out.println(selection);

view.properties().remove(key);