XNHttpClientGroovy

/

  • Groovy class : httpClientGroovy 
  • This class is used to interact with the XWiki network REST service
    */

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.NameValuePair;

class httpClientClass{
   def xwiki;
   def xcontext;
   def services;
   HttpClient httpClient;
   JAXBContext jaxbContext;
   Unmarshaller unmarshaller;
   private def rsHost;
   private def rsPort;
   private def rsProtocol;
   private def username;
   private def password;
   String defaultDataType = "application/json";

   / Initialize the class /
   void init(xwiki, xcontext, services) {
      this.xwiki = xwiki;
      this.xcontext = xcontext;
      this.services = services;
      Configure http client
      def configDoc = xwiki.getDocumentAsAuthor("XWikiComCode.XNFormConfiguration");
      def configObj = configDoc.getObject("XWikiComCode.XNFormConfigurationClass");
      if(configObj){
         this.rsHost = configObj.getValue("rsHost");
         this.rsPort = configObj.getValue("rsPort");
         if (!this.rsPort) {
            this.rsPort = AuthScope.ANY_PORT;
         }
         this.rsProtocol = configObj.getValue("rsProtocol");
         if (!this.rsProtocol) {
            this.rsProtocol = "https";
         }
         this.username = configObj.getValue("username");
         this.password = configObj.getValue("password");         
      }
      this.httpClient = getClient();
      this.jaxbContext = JAXBContext.newInstance("org.xwiki.rest.model.jaxb");
      this.unmarshaller = this.jaxbContext.createUnmarshaller();
   }

   /

  • Create and initialize the http client.
       *
  • @return an HttpClient object
       */
       HttpClient getClient() {
          HttpClient httpClient = new HttpClient();
          httpClient.getParams().setAuthenticationPreemptive(true);
          httpClient.getState().setCredentials(
             new AuthScope(this.rsHost, this.rsPort, AuthScope.ANY_REALM),
             new UsernamePasswordCredentials(this.username, this.password)
          );
          return httpClient;
       }

   /

  • HTTP GET method
       *
  • @params Query/Form parameters
  • dataType returned data type
  • @return String
       */
       def get (String rsURL, Map<String, Object> params = null, dataType = defaultDataType) {
          GetMethod getMethod = new GetMethod(rsURL);
          getMethod.addRequestHeader("Accept", dataType);
          if (params != null && params.size() > 0) {
             NameValuePair[] parameters = new NameValuePair[params.size()];
             def i = 0;
             params.each { key, val ->
                parameters[i] = new NameValuePair(key, (val instanceof String[])? val[0]: val);            i++;
             };
             getMethod.setQueryString(parameters);
          }
          getMethod.setDoAuthentication( true );
          try {
             int status = httpClient.executeMethod(getMethod);
             return ["retCode": status, "response": getMethod.getResponseBodyAsString()];
          } catch (Exception e) {
             return ["retCode": -1, "error": e.getMessage()];
          } finally {
             release any connection resources used by the method
             getMethod.releaseConnection();
          }
       }

   /

  • HTTP PUT method
       *
  • @params Query/Form parameters
  • dataType returned data type
  • @return String
       */
       def put (String rsURL, Map<String, Object> params = null, dataType = defaultDataType) {
          PutMethod putMethod = new PutMethod(rsURL);
          putMethod.addRequestHeader("Accept", dataType);
          if (params != null && params.size() > 0) {
             NameValuePair[] parameters = new NameValuePair[params.size()];
             def i = 0;
             params.each { key, val ->
                parameters[i] = new NameValuePair(key, (val instanceof String[])? val[0]: val);
                i++;
             };
             putMethod.setQueryString(parameters);
          }
          putMethod.setDoAuthentication( true );
          try {
             int status = httpClient.executeMethod(putMethod);
             return ["retCode": status, "response": putMethod.getResponseBodyAsString()];
          } catch (Exception e) {
             return ["retCode": -1, "error": e.getMessage()];
          } finally {
             release any connection resources used by the method
             putMethod.releaseConnection();
          }
       }

   /

  • HTTP POST method
       *
  • @params Query/Form parameters
  • dataType returned data type
  • @return String
       */
       def post (String rsURL, Map<String, Object> params = null, dataType = defaultDataType) {
          PostMethod postMethod = new PostMethod(rsURL);
          postMethod.addRequestHeader("Accept", dataType);
          if (params != null && params.size() > 0) {
             NameValuePair[] parameters = new NameValuePair[params.size()];
             def i = 0;
             params.each { key, val ->
                parameters[i] = new NameValuePair(key, (val instanceof String[])? val[0]: val);
                i++;
             };
             postMethod.setQueryString(parameters);
          }
          postMethod.setDoAuthentication( true );
          try {
             int status = httpClient.executeMethod(postMethod);
             return ["retCode": status, "response": postMethod.getResponseBodyAsString()];
          } catch (Exception e) {
             return ["retCode": -1, "error": e.getMessage()];
          } finally {
             release any connection resources used by the method
             postMethod.releaseConnection();
          }
       }

   /

  • Get the REST service URL
       */
        String getRSUrl(protocol = this.rsProtocol){
           String url = protocol + ":" + this.rsHost;
           if(this.rsPort != AuthScope.ANY_PORT){
              url += ":" + this.rsPort;
           }
           url += "/xwiki/rest";
           return url;
        }
    }