First start with the XMLApiBean class because this is the foundation of your application. Your first methods are utility methods to construct the request URL and submit an Action Request. Construct the URL by taking the server URL, which is stored when the class is instantiated, and adding the action name and action parameters. Your code should look something like this:
protected URL breezeUrl(String action, String queryString
throws Exception {
return new URL(baseUrl + "&action=" + action +
(queryString != null ? ('&' + queryString) : ""));
}
This method will be to perform all Action Requests. The method to submit an Action Request is as simple as the following:
protected Element request(String action, String queryString)
throws Exception {
if (breezesession == null)
login();
URL url= breezeUrl(action, queryString);
URLConnection conn= url.openConnection();
conn.setRequestProperty("Cookie", "BREEZESESSION=" + breezesession);
conn.connect();
InputStream resultStream= conn.getInputStream();
Document doc= new SAXBuilder(false).build(resultStream);
return doc.getRootElement();
}
After making sure the user is logged in to the server, you simply use the breezeUrl method to create a request URL. Send the request to the server and put the response into an XML document which is returned by the method.
Your next method for login is a variation of the request method. Prior to a successful login, you do not have an authenticated session. The XMLApiBean class manages authentication using the breezesession property which stores the BREEZESESSION ID. Once login is successful, the value for BREEZESESSION is saved in this property for future API calls . Your code should look like the following:
protected void login() throws Exception {
if (breezesession != null)
logout();
URL loginUrl= breezeUrl("login","login=" + login +
"&password=" + password);
URLConnection conn= loginUrl.openConnection();
conn.connect();
InputStream resultStream= conn.getInputStream();
Document doc= new SAXBuilder(false).build(resultStream);
String breezesessionString= (String) (conn.getHeaderField("Set-Cookie"));
StringTokenizer st= new StringTokenizer(breezesessionString, "=");
if (st.countTokens() > 1 && st.nextToken().equals("BREEZESESSION")) {
String breezesessionNext= st.nextToken();
int semiIndex= breezesessionNext.indexOf(';');
breezesession= breezesessionNext.substring(0, semiIndex);
if (breezesession == null)
throw new RuntimeException("Could not log in to Breeze.");
}
Notice that the login method is protected in this case. Your request method implicitly handles logging in, which is one last thing to think about when sending a request. One of our design principles is to simplify JSP development, and hiding login handling is one example of that.