Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consume REST Service in XPage

Can anyone point me to a article, tutorial, or walk-through of getting started with consuming REST services in XPages? I have seen a few that use the Domino Data Service or a Domino REST service, but I would like to see one consuming external REST services such as PayPal's.

Please don't direct me to Social Business Toolkit, I have looked at it and even downloaded it but don't feel I should have to install J2EE and Eclipse to see a demo of 12 lines of JavaScript.

like image 912
John Avatar asked Dec 19 '22 19:12

John


1 Answers

I know this is a bit after the fact, but for mere consumption of a RESTful endpoint for use in XPages, I blogged recently about doing so on the server-side. My implementation makes use of a Java Class used to generate the output via URLConnection and, ultimately, a StringBuffer to read in the contents, then parse it into a JsonObject for return. I did two folow ups on the topic and you can find them accordingly:

Series page / TOC

  1. REST consumption, server-side with Java
  2. REST consumption with authentication
  3. Generating Custom JSON data from Java

My examples make use of the Google GSON library, but as pointed out by Paul T. Calhoun, there is the com.ibm.commons.util.io.json package which has come with Domino for a while and probably the better option for Domino devs (no external dependencies and no potential java.policy edit).

The basic structure of the method is:

/* 
 * @param String of the url
 * @return JsonObject containing the data from the REST response.
 * @throws IOException
 * @throws MalformedURLException
 * @throws ParseException 
 */
public static JsonObject GetMyRestData( String myUrlStr ) throws IOException, MalformedURLException {
    JsonObject myRestData = new JsonObject();
    try{

        URL myUrl = new URL(myUrlStr);
        URLConnection urlCon = myUrl.openConnection();
        urlCon.setConnectTimeout(5000);
        InputStream is = urlCon.getInputStream();
        InputStreamReader isR = new InputStreamReader(is);
        BufferedReader reader = new BufferedReader(isR);
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while( (line = reader.readLine()) != null ){
            buffer.append(line);
        }
        reader.close();
        JsonParser parser = new JsonParser();
        myRestData = (JsonObject) parser.parse(buffer.toString());

        return myRestData;

    }catch( MalformedURLException e ){
        e.printStackTrace();
        myRestData.addProperty("error", e.toString());
        return myRestData;
    }catch( IOException e ){
        e.printStackTrace();
        myRestData.addProperty("error", e.toString());
        return myRestData;
    }
}
like image 147
Eric McCormick Avatar answered Jan 04 '23 09:01

Eric McCormick