Difference between revisions of "REST API:BaseClient"

From AgileApps Support Wiki
imported>Aeric
m (Text replace - 'Setup > ' to 'Settings > ')
 
imported>Aeric
 
(12 intermediate revisions by the same user not shown)
Line 1: Line 1:
The [{{DOCHOST}}/samples/demo/rest/BaseClient.java BaseClient] demo program logs into the platform, echoes the sessionId, and logs out. It's a superclass for other programs that will utilize other REST resources before logging out. (In BaseClient.java, the <tt>main()</tt> method is a test that lets you know the login succeeded.) This page summarizes the methods it contains.
The [{{DOCHOST}}/samples/demo/rest/BaseClient.java BaseClient] demo program logs into the platform, echoes the sessionId, and logs out. It's a superclass for other programs that will utilize other REST resources before logging out. (In BaseClient.java, the <tt>main()</tt> method is a test that lets you know the login succeeded.) This page summarizes the methods it contains.


{{Tip|The [{{DOCHOST}}/samples/zips/REST_samples.zip REST_samples.zip] file contains BaseClient, the utility class it uses, and extensions to it that demonstrate REST operations.}}
{{Note|
* The [{{DOCHOST}}/samples/zips/REST_samples.zip REST_samples.zip] file contains BaseClient, the utility class it uses, and extensions to it that demonstrate REST operations.
* The [{{DOCHOST}}/samples/zips/REST_samples.zip REST_samples.zip] is a sample program that runs external to the AgileApps Server. You may run into JAR conflicts, if you manually copy these JAR files into the AgileApps Server. The AgileApps Server may not start up, if a newer version of this JAR file is used with the AgileApps Server.
}}
__TOC__
__TOC__
==Setting Up the Development Enviroment==
==Setting Up the Development Enviroment==
Line 35: Line 38:
FOR LATER USE:  
FOR LATER USE:  
For use in applications that run in the platform, the JARs need to be enabled by the service provider admin:
For use in applications that run in the platform, the JARs need to be enabled by the service provider admin:
* Go to: '''Settings > Service Provider Settings > Service_Provider_Settings > Develop_Configuration'''
* From {{Service Provider URL}}
* Section: '''Libraries supported in Java Code'''
* Go to: '''Settings > Service Provider Settings'''
* Go to the '''Develop Configuration''' section
* Under '''Libraries supported in Java Code'''
* Add a comma-separated list of JAR file names:
* Add a comma-separated list of JAR file names:
:<syntaxhighlight lang="java" enclose="div">
:<syntaxhighlight lang="java" enclose="div">
Line 58: Line 63:
:;logout(): Logs out of the platform. ''Learn more:'' [[REST API:logout Resource]]
:;logout(): Logs out of the platform. ''Learn more:'' [[REST API:logout Resource]]


:;main(): Calls the login method, echoes the session ID, and logs out. It's worth showing in it's entirety, because it's small.
:;main(): Calls the login method, and logs out. In between those operations is where you'll utilize other resources:
 
::<syntaxhighlight lang="java" enclose="div">
::<syntaxhighlight lang="java" enclose="div">
   public static void main(String args[])
   public static void main(String args[])
Line 65: Line 69:
     BaseClient client = new BaseClient();
     BaseClient client = new BaseClient();
     String sessionId = client.login();
     String sessionId = client.login();
     System.out.println("SessionId is: " + sessionId); 
     // Do something here
     client.logout();
     client.logout();
   }
   }
</syntaxhighlight>
</syntaxhighlight>


:In practice, the <tt>main()</tt> method for a subclass will tend to look something like this:
:The actual main method in the login method illustrates the basic pattern by retrieving the current user's information:
::<syntaxhighlight lang="java" enclose="div">
::<syntaxhighlight lang="java" enclose="div">
   public static void main(String args[])
   public static void main(String args[])
   {
   {
     SubclassClient client = new SubclassClient();
     BaseClient client = new BaseClient();
     String sessionId = client.login();
     String cookieString = client.login();                    
     System.out.println("SessionId is: " + sessionId);
     System.out.println("Session cookie:\n  " + cookieString);  
     try {    
     try {
       // Utilize a resource
       // Access a resource
      String resourceUrl = baseUrl + "/user/info";  // Current user info
       Resource resource = getResource(downloadPackageUrl);
       Resource resource = client.getResource(resourceUrl);  
       resource.header("Cookie", "JSESSIONID=" + sessionId);
       resource.header("Cookie", cookieString);
       
      resource.accept("application/xml");             // or application/json
       // Make calls on the resource
      ClientResponse response = resource.get();        // Fetch data
        ...
       // ClientResponse response = resource.post(xml); // Add data
      // ClientResponse response = resource.put(xml);  // Update data
 
      // Inspect the response
      String responseXml = response.getEntity(String.class);
      echoResponse(responseXml);       
     }     
     }     
     catch (ClientWebException webException)
     catch (ClientWebException webException)

Latest revision as of 08:07, 3 December 2021

The BaseClient demo program logs into the platform, echoes the sessionId, and logs out. It's a superclass for other programs that will utilize other REST resources before logging out. (In BaseClient.java, the main() method is a test that lets you know the login succeeded.) This page summarizes the methods it contains.

Notepad.png

Note:

  • The REST_samples.zip file contains BaseClient, the utility class it uses, and extensions to it that demonstrate REST operations.
  • The REST_samples.zip is a sample program that runs external to the AgileApps Server. You may run into JAR conflicts, if you manually copy these JAR files into the AgileApps Server. The AgileApps Server may not start up, if a newer version of this JAR file is used with the AgileApps Server.

Setting Up the Development Enviroment

The sample programs use the following JARs:

JAR / Version Contains... Used by ...
Apache Wink Client
wink-1.0-incubating.jar
RestClient BaseClient
PackageDownloadClient
PackageSubscribeClient
Apache Commons HTTP Client
commons-httpclient-3.1.jar
HttpClient BulkUploadClient
StaticResourceUploadClient
Xerces XML Parser
xerces.jar
XML pretty-print classes
DocumentBuilder
BaseUtil
BulkUploadClient
JAX-RS (Java API for RESTful Web Services)
jsr311-api-1.0.jar
Media type constants BulkUploadClient
PackageDownloadClient
PackageSubscribeClient
StaticResourceUploadClient
MultivaluedMap PackageDownloadClient
Notes
  • The jar files can be found in the REST samples zipfile.
  • The Wink REST client makes for simpler coding of standard REST requests. But so far, at least, it does not appear to work for client-side multipart requests. So programs that need to do that use the Apache HTTP client.
  • The BulkUploadClient is an exception, in that it does not extend BaseClient. Instead, it does minimal error handling, while duplicating some of the code. The result is less well-factored and perhaps somewhat less robust, but possibly more easily read and understood.

Configuring the BaseClient

Edit the BaseClient code to change the values for the following variables:
baseUrl
The URL that takes you to the platform REST APIs, without a final slash.
For example: http://yourPlatform.com/networking/rest
username
Your username, or the name of the user you'll be logging in as.
password
The password you need to log in.

Notepad.png

Note: The plan is to read those values from a file, one fine day.

Primary Methods

login()
Logs into the platform. Returns a String containing the session ID. Learn more: REST API:login Resource
logout()
Logs out of the platform. Learn more: REST API:logout Resource
main()
Calls the login method, and logs out. In between those operations is where you'll utilize other resources:
  public static void main(String args[])
  {
    BaseClient client = new BaseClient();
    String sessionId = client.login();
    // Do something here 
    client.logout();
  }
The actual main method in the login method illustrates the basic pattern by retrieving the current user's information:
  public static void main(String args[])
  {
    BaseClient client = new BaseClient();
    String cookieString = client.login();                      
    System.out.println("Session cookie:\n  " + cookieString); 
    try {     
       // Utilize a resource
       String resourceUrl = baseUrl + "/user/info";  // Current user info
       Resource resource = client.getResource(resourceUrl); 
       resource.header("Cookie", cookieString);
       resource.accept("application/xml");              // or application/json
       ClientResponse response = resource.get();        // Fetch data
       // ClientResponse response = resource.post(xml); // Add data
       // ClientResponse response = resource.put(xml);  // Update data

       // Inspect the response
       String responseXml = response.getEntity(String.class);
       echoResponse(responseXml);        
    }    
    catch (ClientWebException webException)
    {
        echoResponse(webException);
    }
    catch (Exception e)
    {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    finally
    {
        client.logout();
    }
  }

Utility Methods

These methods are generally used by subclasses. Many of them delegate the actual work to methods in the BaseUtil class.
getValue(String xpath_expr, String xml)
Delegates to the BaseUtil xpath_result method to get a value from an XML string. Generally used to get the /platform/message/status from a response.
getResource(String uri)
Returns the Resource object for a URI or URL, using the RestClient object created by logging in.
echoResponse(InputStream xml_in)
Delegates to the BaseUtil prettyPrint method to display response XML in nicely-formatted form.
echoResponse(String xml)
Version that pretty prints an XML string.
echoResponse(ClientWebException e)
Version that pretty prints the response contained in an Apache ClientWebException object. (Fixes a problem in the HTML returned by Apache Tomcat. Does not fix other errors.)
echoStatus(int status, String xml)
Displays the Http status code that accompanies a response, as well as the platform message code and associated description contained in the response.
statusMessage(int status)
Used by the echoStatus method to provide the useful interpretations of Http status codes. Returns a descriptive string for a status code that is somewhat customized for the platform.