View Javadoc

1   package org.rundeck.api.parser;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   import org.apache.http.HttpResponse;
6   import org.dom4j.Document;
7   import org.dom4j.DocumentException;
8   import org.dom4j.Node;
9   import org.dom4j.io.SAXReader;
10  import org.rundeck.api.RundeckApiException;
11  
12  /**
13   * Helper for parsing RunDeck responses
14   * 
15   * @author Vincent Behar
16   */
17  public class ParserHelper {
18  
19      /**
20       * Load an XML {@link Document} from the given RunDeck {@link HttpResponse}.
21       * 
22       * @param httpResponse from an API call to RunDeck
23       * @return an XML {@link Document}
24       * @throws RundeckApiException if we failed to read the response, or if the response is an error
25       * @see #loadDocument(InputStream)
26       */
27      public static Document loadDocument(HttpResponse httpResponse) throws RundeckApiException {
28          InputStream inputStream = null;
29  
30          try {
31              inputStream = httpResponse.getEntity().getContent();
32          } catch (IllegalStateException e) {
33              throw new RundeckApiException("Failed to read RunDeck reponse", e);
34          } catch (IOException e) {
35              throw new RundeckApiException("Failed to read RunDeck reponse", e);
36          }
37  
38          return loadDocument(inputStream);
39      }
40  
41      /**
42       * Load an XML {@link Document} from the given {@link InputStream}
43       * 
44       * @param inputStream from an API call to RunDeck
45       * @return an XML {@link Document}
46       * @throws RundeckApiException if we failed to read the response, or if the response is an error
47       * @see #loadDocument(HttpResponse)
48       */
49      public static Document loadDocument(InputStream inputStream) throws RundeckApiException {
50          SAXReader reader = new SAXReader();
51          reader.setEncoding("UTF-8");
52  
53          Document document;
54          try {
55              document = reader.read(inputStream);
56          } catch (DocumentException e) {
57              throw new RundeckApiException("Failed to read RunDeck reponse", e);
58          }
59          document.setXMLEncoding("UTF-8");
60  
61          Node result = document.selectSingleNode("result");
62          if (result != null) {
63              Boolean failure = Boolean.valueOf(result.valueOf("@error"));
64              if (failure) {
65                  throw new RundeckApiException(result.valueOf("error/message"));
66              }
67          }
68  
69          return document;
70      }
71  
72  }