REST - allow GET resource/ to output different versions - api

For simplicity, say I have a resource users. The HTTP call GET users/ returns a list of links to concrete users:
<users>
<link rel='user' href='/users/user/1/'/>
<link rel='user' href='/users/user/2/'/>
<link rel='user' href='/users/user/3/'/>
....
</users>
The result representation is described in a specific media type:
application/vnd.company.Users+xml
In our frontends, we want to display a table with all users. This means we need to be able to fetch user information to display, such as the name, gender, friends, ... I would like to avoid that we need a separate request for each user (GET /users/user/x/) to retrieve this information. In addition, some frontends will only display the name, while other frontends will display the name and his/her friends. And so on.
In essence, we are still returning users, but with extentions depending on what the frontend needs.
Which option would you choose? Why?
(1) Make GET users/ customizable via parameters such that the customizations are listed. Depending on the customizations , different media types might be returned, since the syntax of one version/combination might be very different than one of another version/combination:
GET users/ -> application/vnd.company.Users+xml
GET users/?fields=name,gender -> application/vnd.company.Users+xml
GET users/?fields=name,gender,friends -> application/vnd.company.UsersWithFriends+xml
(2) Different resources are created to distinguish different between media types. Parameters are still used for basic customizations covered by the media type. This gives:
GET users?fields=name -> application/vnd.company.Users+xml
GET users?fields=name,gender -> application/vnd.company.Users+xml
GET users_with_friends?fields=gender -> application/vnd.company.UsersWithFriends+xml
(3) The same as (1), but instead of parameters, the desired media type is set by the client in the Accept header. Customizable fields covered by the media type are still set via parameters:
GET users/?fields=name ACCEPT application/vnd.company.Users+xml
GET users/?fields=name,gender ACCEPT application/vnd.company.Users+xml
GET users/?fields=name,gender ACCEPT application/vnd.company.UsersWithFriends+xml
(4) Something else?
To answer my own question, I think that:
Solution (1) is very very wrong. The media type must not be dependant on parameters.
Solution (2) and (3) are more or less equal and up to preferences. I prefer (3) since this would not introduce an explosion of resources to be introduced. In addition, in essence we are still returning users. The only difference is the amount of information, reflected by different media types, that is returned. So one might argue that there is no real need to introduce new resources as done in (2).
Do you agree? What do you think?

(3) is surely the best using strict Media Type, but would require specific HTTP Request client and won't be accessible through basic URL open library or browser.
Why not using solution 1 with another extra parameter : names "expect" or "as".
ie:
users/?fields=name,gender&expect=application/vnd.company.Users+xml
users/?fields=name,gender&expect=application/vnd.company.UsersWithFriends+xml
This would be the same as ACCEPT solution but won't need very custom client library to forge the request.
However you'll have to parse the parameter to provide correct output (the (3) would also have this requirement for parsing the ACCEPT)

Personally, I'm not a fan of using query string parameters to allow clients to pick the data elements they wish to include in a representation. I find it makes it hard to optimize the server and it pollutes the cache with many overlapping variants. Also, you really shouldn't try and use conneg to select between representations that contain different sets of data. Conneg is really just for selecting the serialization format.
With the Hal media type you can approach this problem a bit differently. Consider a service with a root representation that looks like:
<resource rel="self"
href="http://example.org/userservice"
xmlns:us="http://example.org/userservice/rels">
<link rel="us:users" name="users" href="http://example.org/users">
<link rel="us:userswithfriends" href="http://example.org/userswithfriends">
</resource>
When you use hal, instead of using the media type documentation to describe your application domain, you can use link relations. In this case, the us:users link points to a document that contains a list of users. I know the namespace stuff looks a bit wierd, but it is not really being used as an XML namespace, just as way of making a Compact URI (CURIE). When you invent your own rel values, they need to be specified in the form of a URI to try and ensure uniqueness.
The list of users would look something like:
<resource rel="self"
href="http://example.org/users"
xmlns:us="http://example.org/userservice/rels">
<resource rel="us:user" name="1" href="/user/1">
<name>Bob</name>
<age>45</age>
<resource>
<resource rel="us:user" name="2" href="/user/2">
<name>Fred</name>
<age>Bill</age>
<resource>
</resource>
and 'us:userswithfriends' points to a different resource that contains the list of users with each user containing a list of friends.
<resource rel="self"
href="http://example.org/users"
xmlns:us="http://example.org/userservice/rels">
<resource rel="us:user" name="1" href="/user/1">
<name>Bob</name>
<resource rel="us:friend" name="1" href="/user/10">
<name>Sheila</name>
<resource>
<resource rel="us:friend" name="2" href="/user/74">
<name>Robert</name>
<resource>
<resource>
<resource rel="user" name="2" href="/user/2">
<name>Fred</name>
<resource rel="us:friend" name="1" href="/user/14">
<name>Bill</name>
<resource>
<resource rel="us:friend" name="2" href="/user/33">
<name>Margaret</name>
<resource>
<resource>
</resource>
With hal it is the documentation of your rels (us:users, us:friend) that decribes what data elements are allowed to exist in the resource element. You are free to embed all of the data of the resource, or more likely just a subset of the data. If the client wants to access a completely representation of the embedded resource then it can follow the provided link.

Related

Hey Cortana, how to handle multiple VCD languages in code?

In my app, I want to give the user the opportunity to switch a light on and off with voice commands (via Cortana for example). I understand the VCD concept and really like but I don't know how to handle the different languages in my code.
Given I have two languages (English and German):
<CommandSet xml:lang="en" Name="LightSwitch_en">
<CommandPrefix>Switch the light</CommandPrefix>
<Example>Switch the light on.</Example>
<Command Name="switchLight">
<Example>on</Example>
<ListenFor>{status}</ListenFor>
<Feedback>Light will be switched {status}.</Feedback>
<Navigate />
</Command>
<PhraseList Label="status">
<Item>on</Item>
<Item>off</Item>
</PhraseList>
</CommandSet>
<CommandSet xml:lang="de" Name="LightSwitch_de">
<CommandPrefix>Schalte das licht</CommandPrefix>
<Example>Schalte das Licht ein.</Example>
<Command Name="switchLight">
<Example>ein</Example>
<ListenFor>{status}</ListenFor>
<Feedback>Licht wird {status}geschaltet.</Feedback>
<Navigate />
</Command>
<PhraseList Label="status">
<Item>ein</Item>
<Item>aus</Item>
</PhraseList>
</CommandSet>
When my app launches by a voice command, I can easily extract the spoken words and can access the status parameter. But because it's a string I will get a different result depending on which language the user has spoken.
So if the user speaks English, the string is "on", but if he speaks German, the string would be "ein". So how do I know, which string I need to listen for inside my app? I am targeting something like this:
if (arg.Equals("on"))
Light.On();
else if (arg.Equals("off"))
Light.Off();
But this only works in English of cause, not in German. I resent checking for all different strings in all languages, that can't be the right way. Unfortuantely it is also not possible to give the <Item> tags an additional attribute due to they are just strings.
I could do something like if (arg.Equals("on") || arg.Equals("ein")) Light.On(); but as you can see this is really ugly and I have to adjust it every time I change something and well, imagine I had about 15 languages to check...
Do you know a smarter solution?
As Cortana will use the same localization as the built in app localization method can you not put all your strings in resource files and then compare the returned string with the localized resource?
In case you just need to solve that particular case you can do the following, instead a list just define two commands per language:
<Command Name="oncommand" >
<Example>switch on</Example>
<ListenFor>switch on</ListenFor>
<Feedback>Light will be switched on.</Feedback>
<Navigate />
</Command>
<Command Name="offcommand">
<Example>switch off</Example>
<ListenFor>switch off</ListenFor>
<Feedback>Light will be switched off.</Feedback>
<Navigate />
</Command>
and then detect in code what command was called:
if (args.Kind == ActivationKind.VoiceCommand)
{
var commandArgs = args as VoiceCommandActivatedEventArgs;
var speechRecognitionResult = commandArgs.Result;
string voiceCommandName = speechRecognitionResult.RulePath.First();
string textSpoken = speechRecognitionResult.Text;
return voiceCommandName;
}
where voiceCommandName is 'oncommand' or 'offcommand'.

Is the default CQ5 Search Configuration incorrect?

i need to optimize the CQ5 lucene indexing configuration for my application.
I want to provide a custom search configuration but i struggle to really understand the default configuration.
Source: https://helpx.adobe.com/experience-manager/kb/SearchIndexingConfig.html)
First question:
Are the "include"-tags used in the default configuration correct?
For example:
The default configuration uses the tag "include" to include the Property "jcr:content/jcr:lastModified" for the nt:file-Aggregate
<aggregate primaryType="nt:file">
<include>jcr:content</include>
<include>jcr:content/jcr:lastModified</include>
</aggregate>
Compare this to the Jackrabbit wiki which uses the "include-property" for the exact same case. Source: http://wiki.apache.org/jackrabbit/IndexingConfiguration
<aggregate primaryType="nt:file">
<include>jcr:content</include>
<include-property>jcr:content/jcr:lastModified</include-property>
</aggregate>
I only can assume it doesn't matter but i can't find any source to confirm this.
Second question: for the nodeType "cq:PageContent" all properties of four levels are aggregated.
<aggregate primaryType="cq:PageContent">
<include>*</include>
<include>*/*</include>
<include>*/*/*</include>
<include>*/*/*/*</include>
</aggregate>
I assume that because of the aggregation all properties are indexed which are contained within these 4 levels.
Or do i must consider the index rules for the nodeType nt:base which basicly only includes properties which are matching the pattern ".:.".
<index-rule nodeType="nt:base">
<property nodeScopeIndex="false">analyticsProvider</property>
<property nodeScopeIndex="false">analyticsSnippet</property>
...
<property isRegexp="true">.*:.*</property>
</index-rule>
Best regards
The default configuration is ideed incorrect as confirmed by the Adobe CQ5 Support.
For the aggegate to work correctly properties must be included by the "include-property"-Tag
So the default search configuration (or atleast the documentation) is not correct https://helpx.adobe.com/experience-manager/kb/SearchIndexingConfig.html)

How to get more info within only one geosearch call via Wikipedia API?

I am using an API call similar to http://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gscoord=41.426140|26.099319.
I returns something like this
<?xml version="1.0"?>
<api>
<query>
<geosearch>
<gs pageid="27460829" ns="0" title="Kostilkovo" lat="41.416666666667" lon="26.05" dist="4245.1" primary="" />
<gs pageid="27460781" ns="0" title="Belopolyane" lat="41.45" lon="26.15" dist="4988.7" primary="" />
<gs pageid="27460862" ns="0" title="Siv Kladenets" lat="41.416666666667" lon="26.166666666667" dist="5713.5" primary="" />
<gs pageid="13811116" ns="0" title="Svirachi" lat="41.483333333333" lon="26.116666666667" dist="6521.9" primary="" />
<gs pageid="27460810" ns="0" title="Gorno Lukovo" lat="41.366666666667" lon="26.1" dist="6613.4" primary="" />
<gs pageid="27460799" ns="0" title="Dolno Lukovo" lat="41.366666666667" lon="26.083333333333" dist="6746.2" primary="" />
<gs pageid="27460827" ns="0" title="Kondovo" lat="41.433333333333" lon="26.016666666667" dist="6937" primary="" />
<gs pageid="27460848" ns="0" title="Plevun" lat="41.45" lon="26.016666666667" dist="7383.1" primary="" />
<gs pageid="24179704" ns="0" title="Villa Armira" lat="41.499069444444" lon="26.106263888889" dist="8130" primary="" />
<gs pageid="27460871" ns="0" title="Zhelezari" lat="41.413333333333" lon="25.998333333333" dist="8540.1" primary="" />
</geosearch>
</query>
</api>
But while I am actually trying to get some pictures of those pages, subsequent calls are needed, like
to get some page images
http://en.wikipedia.org/w/api.php?action=query&prop=images&pageids=13843906
then, to get image info
http://en.wikipedia.org/w/api.php?action=query&titles=File:Alexandru_Ioan_Cuza_Dealul_Patriarhiei.jpg&prop=imageinfo&iiprop=url
Well, even if this gets me what I ultimately need, it is not efficient at all.
I would like to know if there are some parameters for this calls, or maybe completely other call(s) that would bring all this info in maximum 2 steps/calls. It would be great, though, if it would be only one.
Wow, I had no idea that such a feature exists nowadays! But to answer your question, since it's a list query, you can probably use it as a generator.
Let's try it:
Original geosearch query: http://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gscoord=41.426140|26.099319
Generator query to get images on matching pages: http://en.wikipedia.org/w/api.php?action=query&prop=images&imlimit=max&generator=geosearch&ggsradius=10000&ggscoord=41.426140|26.099319
The prop=images query can also be used as a generator, so you can also do this:
Get URLs for all images on a list of pages: http://en.wikipedia.org/w/api.php?action=query&prop=imageinfo&iiprop=url&generator=images&gimlimit=max&pageids=13811116|24179704|27460781|27460799|27460810|27460827|27460829|27460848|27460862|27460871
Alas, AFAIK you can't nest generators, so you can't do both steps in one query. You can either:
get the list of images in one query, and then use another query to get the URLs, or
start with the basic geosearch query to get the page IDs, and then get the images and their URLs in another query.
Alas, it turns out that both of these options fail to give you some information that you may want. If you use list=geosearch as a generator, you don't get the coordinate information that you may need if you e.g. wish to display the results on a map. On the other hand, using prop=images as a generator makes you miss out on something even more important: the knowledge of which images are used on which pages!
Thus, unfortunately, it seems that, if your goal is to place images on a map, you'll probably have to do it with three separate queries. At least you can still query multiple pages / images in one request, so you shouldn't need more than three (until you hit the query limits and need to use continuations, that is).
(Also, doing it in three steps lets you apply some filtering to the images before the third step. For example, most of the pages returned by your example query only have the same three images — Flag of Bulgaria.svg, Ivaylovgrad Reservoir.jpg and Oblast Khaskovo.png — all of which are used via templates, and none of which really look like good choices to represent the specific location.)
Ps. If you're just interested in finding images near a particular location, even if they're not used on any specific Wikipedia article, you might want to try using geosearch directly on Wikimedia Commons. It doesn't seem to return any results for your Bulgarian example coordinates, but it works just fine in a more crowded location.
Here is an alternative to build on the previous answer. If you start with this query as a partial answer:
https://en.wikipedia.org/w/api.php?action=query&prop=images&imlimit=max&generator=geosearch&ggsradius=10000&ggscoord=41.426140|26.099319
Then you can build on this to get the information in a single query. The pageimages property can work with the generator. You cannot nest generators but you can chain properties. A query can use pageimages to get the page's main image url for each of the geosearch results. It looks like this:
https://en.wikipedia.org/w/api.php?action=query&prop=images|pageimages&pilimit=max&piprop=thumbnail&iwurl=&imlimit=max&generator=geosearch&ggsradius=10000&ggscoord=41.426140|26.099319
This query returns the image "File" names (images property) and a single URL for the main image (pageimages property). The main image of the page is all I need. You might be able to extrapolate the "file" urls by matching the changes from the file to the url that is output with the query but I cannot recommend such a hack.
The images property has a setting that is supposed to return urls for interwiki links, iwurl. I see the "file" as an interwiki link. This parameter is not working and images does not return a url. Playing on the sandbox might lead you to a better answer.
Intuitively it seems like you should be able to chain the images and imageinfo properties together. Doing so does not give the expected results.
If a single url for the main image of the page is not enough I can encourage you to play in the API sandbox to try and get what you need with some combination of properties. I am using the geosearch generator and get the page image, text description, and lat/long coordinates so that I can get the address. Good luck!

how to add working sets to eclipse common navigator?

I would love to add support for Working Sets for my Eclipse plugin that used the Common Navigator framework.
In Eclipse bugzilla there is mention that this is supported
None of the online manuals for the Common Navigator explain how to do it
I do not know where to start even since there is no extension point for it, and the Working Set implementation classes are all "internal". I have a very basic navigator setup showing default project resources and some additional IFileSystem stuff implementing ITreeContentProvider.
You can get the working set manager using:
IWorkingSetManager manager = PlatformUI.getWorkbench().getWorkingSetManager();
and from that get the visible working sets with:
IWorkingSet [] workingSets = manager.getWorkingSets();
the members of a working set can be accessed with:
IAdaptable [] elements = workingSet.getElements();
so you could use the working sets list as the input for the tree viewer and adjust your tree content provider to deal with this.
In retrospect the following is a better solution. Instead of implementing ITreeContentProvider and traversing the working sets ourselves, we can reuse existing standard providers for the same content, which might work better.
You can use them like so:
<extension
point="org.eclipse.ui.navigator.viewer">
<viewerContentBinding
viewerId="rascal.navigator">
<includes>
<contentExtension pattern="org.eclipse.ui.navigator.resourceContent" />
<contentExtension pattern="org.eclipse.ui.navigator.resources.filters.*"/>
<contentExtension pattern="org.eclipse.ui.navigator.resources.linkHelper"/>
<contentExtension pattern="org.eclipse.ui.navigator.resources.workingSets"/>
</includes>
</viewerContentBinding>
In particular the org.eclipse.ui.navigator.resources.workingSets is what adds working sets capabilities to your navigator.
Adding your own content then becomes an issue of adding another content provider which ignores workingsets and projects and other kinds of resources which are already taken care of, e.g. like so:
<extension
point="org.eclipse.ui.navigator.navigatorContent">
<navigatorContent
activeByDefault="true"
contentProvider="org.rascalmpl.eclipse.navigator.NavigatorContentProvider"
id="org.rascalmpl.navigator.searchPathContent"
labelProvider="org.rascalmpl.eclipse.navigator.NavigatorContentLabelProvider"
name="Rascal search path"
priority="normal">
<triggerPoints>
<or>
<instanceof value="org.eclipse.core.resources.IResource"/>
</or>
</triggerPoints>
<possibleChildren>
<or>
<instanceof value="java.lang.Object"/>
</or>
</possibleChildren>
<actionProvider
class="org.rascalmpl.eclipse.navigator.NavigatorActionProvider"
id="org.rascalmpl.navigator.actions">
</actionProvider>
<commonSorter
class="org.rascalmpl.eclipse.navigator.Sorter">
</commonSorter>
</navigatorContent>
<commonWizard
type="new"
wizardId="rascal_eclipse.wizards.NewRascalFile">
<enablement></enablement>
</commonWizard>
<commonWizard
type="new"
wizardId="rascal_eclipse.projectwizard">
<enablement></enablement>
</commonWizard>
</extension>
and in the NavigatorContentProvider class we implement getElements and getChildren but only for our own additional content.

list=alllinks confusion

I'm doing a research project for the summer and I've got to use get some data from Wikipedia, store it and then do some analysis on it. I'm using the Wikipedia API to gather the data and I've got that down pretty well.
What my questions is in regards to the links-alllinks option in the API doc here
After reading the description, both there and in the API itself (it's down and bit and I can't link directly to the section), I think I understand what it's supposed to return. However when I ran a query it gave me back something I didn't expect.
Here's the query I ran:
http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=google&rvprop=ids|timestamp|user|comment|content&rvlimit=1&list=alllinks&alunique&allimit=40&format=xml
Which in essence says: Get the last revision of the Google page, include the id, timestamp, user, comment and content of each revision, and return it in XML format.
The allinks (I thought) should give me back a list of wikipedia pages which point to the google page (In this case the first 40 unique ones).
I'm not sure what the policy is on swears, but this is the result I got back exactly:
<?xml version="1.0"?>
<api>
<query><normalized>
<n from="google" to="Google" />
</normalized>
<pages>
<page pageid="1092923" ns="0" title="Google">
<revisions>
<rev revid="366826294" parentid="366673948" user="Citation bot" timestamp="2010-06-08T17:18:31Z" comment="Citations: [161]Tweaked: url. [[User:Mono|Mono]]" xml:space="preserve">
<!-- The page content, I've replaced this cos its not of interest -->
</rev>
</revisions>
</page>
</pages>
<alllinks>
<!-- offensive content removed -->
</alllinks>
</query>
<query-continue>
<revisions rvstartid="366673948" />
<alllinks alfrom="!2009" />
</query-continue>
</api>
The <alllinks> part, its just a load of random gobbledy-gook and offensive comments. No nearly what I thought I'd get. I've done a fair bit of searching but I can't seem to find a direct answer to my question.
What should the list=alllinks option return?
Why am I getting this crap in there?
You don't want a list; a list is something that iterates over all pages. In your case you simply "enumerate all links that point to a given namespace".
You want a property associated with the Google page, so you need prop=links instead of the alllinks crap.
So your query becomes:
http://en.wikipedia.org/w/api.php?action=query&prop=revisions|links&titles=google&rvprop=ids|timestamp|user|comment|content&rvlimit=1&format=xml