1 /*
2 * Copyright 2011 Vincent Behar
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.rundeck.api.parser;
17
18 import java.io.InputStream;
19 import org.dom4j.Document;
20 import org.dom4j.DocumentException;
21 import org.dom4j.Node;
22 import org.dom4j.io.SAXReader;
23 import org.rundeck.api.RundeckApiException;
24
25 /**
26 * Helper for parsing Rundeck responses
27 *
28 * @author Vincent Behar
29 */
30 public class ParserHelper {
31
32 /**
33 * Load an XML {@link Document} from the given {@link InputStream}
34 *
35 * @param inputStream from an API call to Rundeck
36 * @return an XML {@link Document}
37 * @throws RundeckApiException if we failed to read the response, or if the response is an error
38 */
39 public static Document loadDocument(InputStream inputStream) throws RundeckApiException {
40 SAXReader reader = new SAXReader();
41 reader.setEncoding("UTF-8");
42
43 Document document;
44 try {
45 document = reader.read(inputStream);
46 } catch (DocumentException e) {
47 throw new RundeckApiException("Failed to read Rundeck response", e);
48 }
49 document.setXMLEncoding("UTF-8");
50
51 Node result = document.selectSingleNode("result");
52 if (result != null) {
53 Boolean failure = Boolean.valueOf(result.valueOf("@error"));
54 if (failure) {
55 throw new RundeckApiException(result.valueOf("error/message"));
56 }
57 }
58
59 return document;
60 }
61
62 }