source: trunk/src/groovy/dbnp/rest/common/CommunicationManager.groovy @ 631

Last change on this file since 631 was 631, checked in by jahn, 10 years ago

Cleaned up CommunicationManager? and put it in uniform use and package
structure with the dbnp.rest used in the Simple Assay Module.

File size: 2.0 KB
Line 
1package dbnp.rest.common
2
3import grails.converters.JSON
4import java.net.URLEncoder
5import org.codehaus.groovy.grails.web.json.*
6
7
8
9
10/**  CommunicationManager
11 *
12 *   @author Jahn
13 *
14 *   This class implements a Rest client for fetching data from Rest resources provided by
15 *   GSCF and SAM. This class provides general means needed for fetching the JSON data.
16 *   Do not use this class directly to fetch data. Instead use your module's RestWrapper.
17 *   For instance, use dbnp.rest.sam.GSCFtoSAMRestWrapper to define a new method for accessing
18 *   GSCF's Rest service in SAM; your new method shoud then use this class.
19 */
20
21
22class CommunicationManager {
23
24    def static Encoding = "UTF-8" 
25
26    /**
27     * Get the results of provided by a rest Rest resource.
28     *
29     * @params String resource The name of the resource, e.g. importer/pages
30     * @params Map params      A Map of parmater names and values., e.g. ['externalAssayID':12]
31     * @return String url   
32     */
33    public static Object getRestResource( RestServerURL, resource, params ) {
34                def url = getRestURL( RestServerURL, resource, params )
35                return  JSON.parse( url.newReader() )
36    }
37
38
39    /**
40     * Convenience method for constructing URLs for SAM that need parameters.
41     * Note that parameters are first convereted to strings by calling their toString() method
42     * and then Encoded to protect special characters.
43     *
44     * @params String resource The name of the resource, e.g. importer/pages
45     * @params Map params      A Map of parmater names and values., e.g. ['externalAssayID':12]
46     * @return String url   
47     */
48    public static URL getRestURL( RestServerURL, resource, params ) {
49        def url = RestServerURL + '/' + resource
50                def first = true
51                params.each { name, value ->
52                        if(first) {
53                                first = false
54                                url += '/nil?' + name + "=" + URLEncoder.encode( value.toString(), Encoding )
55                        }
56                        else { 
57                                url += '&' + name + "=" + URLEncoder.encode( value.toString(), Encoding  )
58                        }
59                }
60                return new URL( url )
61    }
62
63}
Note: See TracBrowser for help on using the repository browser.