ATG REST Java Coding Tutorial - PDF by yyr12615

VIEWS: 0 PAGES: 9

									ATG REST Java Coding Tutorial

(This tutorial is derived from the "Quick Start" section of the ATG REST documentation.)



Start your ATG server with the REST module. If you rely on other modules, those can
remain in your startup list.



Once the server is running with the REST module, your platform is now able to accept and
process REST requests. There are some things that you need to be aware of before you
start coding. First, the security components in REST, by default, require you to be logged
into make calls. Also, by default, no users have access to any components and therefore
even if logged in will not be able to successfully make any REST requests. For development
purposes we can set a default acl in the security configuration file. This will allow all the
specified users to have access to all nucleus components. Note that this functionality is
provided for convenience and should not be used on a live server unless that is the specified
intent. To set a default acl in the security configuration layer, create a file in your localconfig
directory at atg/rest/security named restSecurityConfiguration.xml. Add the following to
the file. Note that "#username#" should be replaced with a valid profile user login on your
system.




Example 1. Setting default-acl for REST Security




    <rest-security>     <default-acl value="Profile$login
$#username#:read,write,execute"/>      </rest-security>
The above entry is telling the REST security layer that the default security settings are
to allow the specified user to read and write all nucleus component properties and to
allow execution on any nucleus method. Note that for requests made to a repository, the
repository security layer will determine accessibility.



We are now ready to create our first application that uses REST to communicate with the
server. As mentioned above, you will need to be logged in to make calls. Below is a small




Generated by Jive SBS on 2010-05-01-04:00
                                                                                                  1
ATG REST Java Coding Tutorial


application which uses the ATG REST Java client library. The client libraries can be found in
REST/client-lib.



The code below is a simple commandline application which only logs into the server and
logs out. Later we will add additional code to access data.




Example 2. Sample REST Application using Java Client Library




     import atg.rest.client.RestClientException;    import
atg.rest.client.RestComponentHelper;       import atg.rest.client.RestResult;    import
atg.rest.client.RestSession;


     import java.io.IOException;


     public class RestClientSample {       private String mUsername = null;       private
String mPassword = null;      private String mHost = "localhost";     private int mPort =
80;      private RestSession mSession = null;


      public RestClientSample() {}


       protected void parseArguments(String[] pArgs) throws Exception {         for (int i = 0;
i < pArgs.length; i++) {       String arg = pArgs[i];


         if (arg.equals("-user"))      mUsername = pArgs[i+1];             else if
(arg.equals("-password"))          mPassword = pArgs[i+1];          else if (arg.equals("-
host"))           mHost = pArgs[i+1];     else if (arg.equals("-port"))            mPort =
Integer.parseInt(pArgs[i+1]);       }


      if (isBlank(mUsername))           throw new Exception("Must supply
username");         if (isBlank(mPassword))        throw new Exception("Must supply
password");       }



Generated by Jive SBS on 2010-05-01-04:00
                                                                                                  2
ATG REST Java Coding Tutorial


        protected boolean isBlank(String pStr) {          return (pStr == null || pStr.length() == 0
|| pStr.trim().length() == 0);    }


      protected void println(String s) {        System.out.println(s);         }


      protected void println(Throwable t) {           t.printStackTrace(System.out);         }


      protected void execute() throws RestClientException { mSession
= RestSession.createSession(mHost, mPort, mUsername, mPassword);
mSession.setUseHttpsForLogin(false);


        try {         mSession.login();            println("Login Successful");


        }      catch (Throwable t) {          println(t);    }         finally {             try
{         mSession.logout();           println("Logout Successful");           }              catch
(RestClientException e) {         println(e);           }    }       }


     /**     * @param args        */     public static void main(String[] args) {
RestClientSample sample = new RestClientSample();


       try {        sample.parseArguments(args);                 sample.execute();          }
 catch (Throwable t) {       sample.println(t);            }       }    }


In order to compile the above code, you will need to include the atg-rest-N.N.jar, org.json.jar,
dom4j-N.N.N.jar, and log4j-N.N.N.jar files. (Note the 'N' is for a specific version number of
that library.) All these libraries can be found in the REST/lib directory.



In the above code, the most interesting portion is the execute method. It begins by first
creating a RestSession object. It does this by calling the static RestSession.createSession()
method. The parameters to createSession are the hostname, port, username, and
password. By default all login calls are issued with https. If you do not want this functionality,
just set the useHttpsForLogin flag to false on the session object, just as we did above. The
next section of code is where we login. Simply call login() on the RestSession object. If the
login attempt fails, then a RestClientException is thrown. The last section of code in the



Generated by Jive SBS on 2010-05-01-04:00
                                                                                                   3
ATG REST Java Coding Tutorial


finally block is where we logout. Simply call logout and the session will be concluded. To
make it a bit more interesting we will access a nucleus component property.



To make the example a bit more interesting we will retrieve data from the server. Take a
look at the next code sample and the explanation that follows. We have only included the
execute() method.




Example 3. Using the RestComponentHelper to access data from the server




    protected void execute() throws RestClientException {           RestResult result = null;


   mSession = RestSession.createSession(mHost, mPort, mUsername, mPassword);
mSession.setUseHttpsForLogin(false);


     try {      mSession.login();           println("Login Successful");


        result = RestComponentHelper.getComponent("/atg/dynamo/Configuration",
null, mSession);           String responseData = result.readInputStream();       if
(responseData != null) {              JSONObject json = new JSONObject(responseData);
  println(json.toString());         }    }      catch (Throwable t) {  println(t);  }
finally {       if (result != null)        result.close();


      try {     mSession.logout();       println("Logout Successful");              }       catch
(RestClientException e) {    println(e);      }     }   }

In the code above what we have done is made a request for all the properties of a nucleus
component. We do this by using the RestComponentHelper class. (Similar to this class is
the RestRepositoryHelper class which is used to assist with repository requests.) This class
has several static convenience methods which assist in creating the requests and issuing
them to the server. The getComponent() method takes the path to a nucleus component, a
map of optional parameters, and the RestSession object and returns a RestResult object.
The RestResult object can be used to access the data from the response. Above we call
readInputStream() to return a String of the response data. In this case we will assume that



Generated by Jive SBS on 2010-05-01-04:00
                                                                                                    4
ATG REST Java Coding Tutorial


the server is using the default output format which is JSON (Javascript object notation). The
string in the responseData variable will contain the JSON output. We then construct a JSON
object and output it. Note that we could have just output responseData, but here we are
illustrating how one might use the output. Similarly, if the output was XML, one could create
an XML document object using the dom4j library. Finally, you will notice in the finally block
there is a call to close the result. Doing this will release the underlying connection resources.
If this part is omitted, the next call to the server using the same RestSession object will close
the result.



In the next example we will show how to set a property value on a nucleus component.




Example 4. Using the RestComponentHelper to set data on the server




    protected void execute() throws RestClientException {            RestResult result = null;


   mSession = RestSession.createSession(mHost, mPort, mUsername, mPassword);
mSession.setUseHttpsForLogin(false);


     try {      mSession.login();           println("Login Successful");


       result = RestComponentHelper.setPropertyValue("/atg/dynamo/
Configuration", "httpPort", 8080, null, mSession);           String responseData =
result.readInputStream();         if (responseData != null) {            JSONObject json =
new JSONObject(responseData);                println(json.toString());          } }     catch
(Throwable t) {       println(t);      }    finally {       if (result != null)     result.close();


      try {     mSession.logout();       println("Logout Successful");               }       catch
(RestClientException e) {    println(e);      }     }   }



You will see that we are using the RestComponentHelper.setPropertyValue() method. This
method takes 5 parameters. The nucleus component path, the property name to set the
value on, the value to set, a parameter map, and the RestSession object. The client library


Generated by Jive SBS on 2010-05-01-04:00
                                                                                                      5
ATG REST Java Coding Tutorial


will convert the third parameter (the value) appropriately. The result object will contain either
XML or JSON with a true or false value indicating whether or not the value was set.



In the next example, we show a repository call.




Example 5. Using the RestRepositoryHelper to execute a query and retrieve the results




    protected void execute() throws RestClientException {             RestResult result = null;


   mSession = RestSession.createSession(mHost, mPort, mUsername, mPassword);
mSession.setUseHttpsForLogin(false);


     try {       mSession.login();           println("Login Successful");


       result = RestRepositoryHelper.executeRQLQuery("/atg/commerce/catalog/
ProductCatalog", "product", "price < 1.0", null, mSession);  String responseData =
result.readInputStream();       result.close();


       JSONObject json = new JSONObject(responseData);                JSONArray products
= json.getJSONArray("product");           for (int i = 0; i < products.length(); i++) {
result = mSession.createHttpRequest(products.getString(i), null, RestConstants.GET);
 responseData = result.readInputStream();


         JSONObject product = new JSONObject(responseData);
println(product.getString("displayName"));


        result.close();         }      }      catch (Throwable t) {         println(t);       }   finally
{      if (result != null)          result.close();


      try {     mSession.logout();       println("Logout Successful");                    }       catch
(RestClientException e) {    println(e);      }     }   }


Generated by Jive SBS on 2010-05-01-04:00
                                                                                                            6
ATG REST Java Coding Tutorial




In this example, the third parameter of the RestRepositoryHelper.executeRQLQuery()
method is the RQL query string. The result of this call will return an array of repository item
REST urls. By iterating through the URLs and requesting each one, we can access the
contents. In the for loop above you will see that we are making a direct REST request by
calling the createHttpRequest() method on the RestSession object. The first parameter is
the URL and that can be accessed via the first entry in the products JSONArray object.
The createHttpRequest() call will return an object with all the product's properties. We can
then construct a new JSONObject or xml Document object in order to access the data. As
you can see, we are accessing the displayName property. Because we are accessing only
that property, we could modify the createHttpRequest() call to only return the displayName
property. This will save on having to transfer the unused data from the server.




Example 6. Returning only the displayName property




   result = mSession.createHttpRequest(products.getString(i) + "/displayName", null,
RestConstants.GET);



You may have noticed that we are making an excessive number of calls to the server in
Example 5 to access each item. We could make a single call to get all the items. This
would be done by using the RestConstants.DEPTH parameter. The DEPTH parameter
tells the server that we want the requested resource and all its children which are only
one level deep to be returned. To do this, we would supply the DEPTH parameter in the
RestRepositoryHelper.executeRQLQuery() method, as follows.




Example 7. Using the RestConstants.DEPTH parameter




    Map<String,Object> params = new HashMap<String,Object>();
params.put(RestConstants.DEPTH, 1);       result =
RestRepositoryHelper.executeRQLQuery("/atg/commerce/catalog/ProductCatalog",
"product", "price < 1.0", params, mSession);




Generated by Jive SBS on 2010-05-01-04:00
                                                                                                  7
ATG REST Java Coding Tutorial




The result of the query in Example 7 will be an array of objects, rather than an array of URL
strings. In Example 8 below, we show how this simplifies the code.




Example 8. Processing the results of a call which uses the RestConstants.DEPTH parameter




   protected void execute() throws RestClientException { mSession =
RestSession.createSession(mHost, mPort, mUsername, mPassword);
mSession.setUseHttpsForLogin(false);


     RestResult result = null;


     try {      mSession.login();           println("Login Successful");


       result = RestRepositoryHelper.executeRQLQuery("/atg/commerce/catalog/
ProductCatalog", "product", "price < 1.0", null, mSession);  String responseData =
result.readInputStream();       result.close();


        JSONObject json = new JSONObject(responseData);                     JSONArray
products = json.getJSONArray("product");           for (int i = 0; i < products.length();
i++) {        JSONObject product = products.getJSONObject(i);
println(product.getString("displayName"));         }      }      catch (Throwable t) {
  println(t);   }     finally {       try {       mSession.logout();           println("Logout
Successful");       }         catch (RestClientException e) {           Throwable cause
= e.getCause();          if (cause != null && !(cause instanceof IOException))
println(e);      }     }     }



What is happening above is that a single request is being made to return the properties
for all the items that result from the query. We are making a single call to the server and
it is returning a larger amount of data compared to the approach used in example 5. If we
wanted to only return the displayName property for all the items, then we would need to
configure the filtering and aliasing functionality. This we leave as an exercise and I direct you
to the Filtering and Aliasing section in the REST documentation.


Generated by Jive SBS on 2010-05-01-04:00
                                                                                                 8
ATG REST Java Coding Tutorial




Generated by Jive SBS on 2010-05-01-04:00
                                            9

								
To top