<p>I have a question on the best way of exposing an asynchronous remote interface.</p>

<p>The conditions are as follows:</p>

<ul>
<li>The protocol is asynchronous</li>
<li>A third party can modify the data at any time</li>
<li>The command round-trip can be significant</li>
<li>The model should be well suited for UI interaction</li>
<li>The protocol supports queries over certain objects, and so must the model</li>
</ul>

<p>As a means of improving my lacking skills in this area (and brush up my Java in general), I have started a <a href="http://Telharmonium.devjavu.com/" rel="nofollow noreferrer">project</a> to create an Eclipse-based front-end for <a href="http://xmms2.xmms.se" rel="nofollow noreferrer">xmms2</a> (described below).</p>

<p>So, the question is; how should I expose the remote interface as a neat data model (In this case, track management and event handling)?</p>

<p>I welcome anything from generic discussions to pattern name-dropping or concrete examples and patches :)</p>

<hr>

<p>My primary goal here is learning about this class of problems in general. If my project can gain from it, fine, but I present it strictly to have something to start a discussion around.</p>

<p>I've implemented a protocol abstraction which I call <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-client" rel="nofollow noreferrer">'client'</a> (for legacy reasons) which allows me to access most exposed features using method calls which I am happy with even if it's far from perfect.</p>

<p>The features provided by the xmms2 daemon are things like track searching, meta-data retrieval and manipulation, change playback state, load playlists and so on and so forth.</p>

<p>I'm in the middle of updating to the latest stable release of xmms2, and I figured I might as well fix some of the glaring weaknesses of my current implementation.</p>

<p>My plan is to build a better abstraction on top of the protocol interface, one that allows a more natural interaction with the daemon. The current <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-model" rel="nofollow noreferrer">'model'</a> implementation is hard to use and is frankly quite ugly (not to mention the UI-code which is truly horrible atm).</p>

<p>Today I have the <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-model/src/se/fnord/xmms2/model/Tracks.java" rel="nofollow noreferrer">Tracks</a> interface which I can use to get instances of <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-model/src/se/fnord/xmms2/model/Track.java" rel="nofollow noreferrer">Track</a> classes based on their id. Searching is performed through the <a href="http://telharmonium.devjavu.com/browser/trunk/xmms2-model/src/se/fnord/xmms2/model/Collections.java" rel="nofollow noreferrer">Collections</a> interface (unfortunate namespace clash) which I'd rather move to Tracks, I think.</p>

<p>Any data can be modified by a third party at any time, and this should be properly reflected in the model and change-notifications distributed</p>

<p>These interfaces are exposed when connecting, by returning an object hierarchy that looks like this:</p>

<ul>
<li>Connection

<ul>
<li>Playback getPlayback()

<ul>
<li>Play, pause, jump, current track etc</li>
<li>Expose playback state changes</li>
</ul></li>
<li>Tracks getTracks()

<ul>
<li>Track getTrack(id) etc</li>
<li>Expose track updates</li>
</ul></li>
<li>Collections getCollection()

<ul>
<li>Load and manipulate playlists or named collections</li>
<li>Query media library</li>
<li>Expose collection updates</li>
</ul></li>
</ul></li>
</ul>

[{'answer_id': 37093, 'author': 'Staale', 'author_id': 3355, 'author_profile': 'https://Stackoverflow.com/users/3355', 'pm_score': 3, 'selected': True, 'text': '<p>For the asynchronous bit, I would suggest checking into <code>java.util.concurrent</code>, and especially the <code>Future&lt;T&gt;</code> interface. The future interface is used to represent objects which are not ready yet, but are being created in a separate thread. You say that objects can be modified at any time by a third party, but I would still suggest you use immutable return objects here, and instead have a separate thread/event log you can subscribe to to get noticed when objects expire. I have little programming with UIs, but I believe using Futures for asynchronous calls would let you have a responsive GUI, rather than one that was waiting for a server reply.</p>\n\n<p>For the queries I would suggest using method chaining to build the query object, and each object returned by method chaining should be <code>Iterable</code>. Similar to how Djangos model is. Say you have <code>QuerySet</code> which implements <code>Iterable&lt;Song&gt;</code>. You can then call <code>allSongs()</code> which would return a result iterating over all Songs. Or <code>allSongs().artist("Beatles")</code>, and you would have an iterable over all Betles songs. Or even <code>allSongs().artist("Beatles").years(1965,1967)</code> and so on. </p>\n\n<p>Hope this helps as a starting place.</p>\n'}, {'answer_id': 37123, 'author': 'Henrik Gustafsson', 'author_id': 2010, 'author_profile': 'https://Stackoverflow.com/users/2010', 'pm_score': 0, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/37041/exposing-a-remote-interface-or-object-model#37093">Staale</a>: Thanks a bunch!</p>\n\n<p>Using Future for the async operations is interesting. The only drawback being that it is doesn\'t provide callbacks. But then again, I tried that approach, and look where that got me :)</p>\n\n<p>I\'m currently solving a similar problem using a worker thread and a blocking queue for dispatching the incoming command replies, but that approach doesn\'t translate very well.</p>\n\n<p>The remote objects can be modified, but since I do use threads, I try to keep the objects immutable. My current hypothesis is that I will send notification events on track updates on the form</p>\n\n<pre><code>somehandlername(int changes, Track old_track, Track new_track)\n</code></pre>\n\n<p>or similar, but then I might end up with several versions of the same track.</p>\n\n<p>I\'ll definitely look into Djangos method chaining. I\'ve been looking at some similar constructs but haven\'t been able to come up with a good variant. Returning something iterable is interesting, but the query could take some time to complete, and I wouldn\'t want to actually execute the query before it\'s completely constructed.</p>\n\n<p>Perhaps something like</p>\n\n<pre><code>Tracks.allSongs().artist("Beatles").years(1965,1967).execute()\n</code></pre>\n\n<p>returning a Future might work...</p>\n'}, {'answer_id': 37175, 'author': 'Staale', 'author_id': 3355, 'author_profile': 'https://Stackoverflow.com/users/3355', 'pm_score': 0, 'selected': False, 'text': '<p>Iterable only has the method Iterator get() or somesuch. So no need to build any query or execute any code until you actually start iterating. It does make the execute in your example redundant. However, the thread will be locked until the first result is available, so you might consider using an Executor to run the code for the query in a separate thread.</p>\n'}, {'answer_id': 37226, 'author': 'Henrik Gustafsson', 'author_id': 2010, 'author_profile': 'https://Stackoverflow.com/users/2010', 'pm_score': 0, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/37041/exposing-a-remote-interface-or-object-model#37175">Staale</a></p>\n\n<p>It is certainly possibly, but as you note, that would make it blocking (at home for something like 10 seconds due to sleeping disks), meaning I can\'t use it to update the UI directly.</p>\n\n<p>I could use the iterator to create a copy of the result in a separate thread and then send that to the UI, but while the iterator solution by itself is rather elegant, it won\'t fit in very well. In the end, something implementing <a href="http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/viewers/IStructuredContentProvider.html" rel="nofollow noreferrer">IStructuredContentProvider</a> needs to return an array of all the objects in order to display it in a <a href="http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/viewers/TableViewer.html" rel="nofollow noreferrer">TableViewer</a>, so if I can get away with getting something like that out of a callback... :)</p>\n\n<p>I\'ll give it some more thought. I might just be able to work out something. It does give the code a nice look.</p>\n'}, {'answer_id': 37933, 'author': 'Henrik Gustafsson', 'author_id': 2010, 'author_profile': 'https://Stackoverflow.com/users/2010', 'pm_score': 0, 'selected': False, 'text': '<p>My conclusions so far;</p>\n\n<p>I am torn on whether to use getters for the Track objects or just expose the members since the object is immutable.</p>\n\n<pre><code>class Track {\n    public final String album;\n    public final String artist;\n    public final String title;\n    public final String genre;\n    public final String comment;\n\n    public final String cover_id;\n\n    public final long duration;\n    public final long bitrate;\n    public final long samplerate;\n    public final long id;\n    public final Date date;\n\n    /* Some more stuff here */\n}\n</code></pre>\n\n<p>Anybody who wants to know when something happened to a track in the library would implement this...</p>\n\n<pre><code>interface TrackUpdateListener {\n    void trackUpdate(Track oldTrack, Track newTrack);\n}\n</code></pre>\n\n<p>This is how querys are built. Chain calls to your hearts content. the jury is still out on the get() though. There are some details missing, such as how I should handle wildcards and more advanced queries with disjunctions. I might just need some completion callback functionality, perhaps similar to the <a href="http://www.cse.wustl.edu/~schmidt/PDF/ACT.pdf" rel="nofollow noreferrer">Asynchronous Completion Token</a>, but we\'ll see about that. Perhaps that will happen in an additional layer.</p>\n\n<pre><code>interface TrackQuery extends Iterable&lt;Track&gt; {\n    TrackQuery years(int from, int to);\n    TrackQuery artist(String name);\n    TrackQuery album(String name);\n    TrackQuery id(long id);\n    TrackQuery ids(long id[]);\n\n    Future&lt;Track[]&gt; get();\n}\n</code></pre>\n\n<p>Some examples:</p>\n\n<pre><code>tracks.allTracks();\ntracks.allTracks().artist("Front 242").album("Tyranny (For You)");\n</code></pre>\n\n<p>The tracks interface is mostly just the glue between the connection and the individual tracks. It will be the one implementing or managing meta-data caching, if any (as today, but I think I\'ll just remove it during the refactoring and see if I actually need it). Also, this provides medialib track updates as it would just be too much work to implement it by track.</p>\n\n<pre><code>interface Tracks {\n    TrackQuery allTracks();\n\n    void addUpdateListener(TrackUpdateListener listener);\n    void removeUpdateListener(TrackUpdateListener listener);\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/37041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2010/']