File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\model\Api.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson.model;
25
26 import hudson.util.IOException2;
27 import jenkins.model.Jenkins;
28 import org.dom4j.CharacterData;
29 import org.dom4j.Document;
30 import org.dom4j.DocumentException;
31 import org.dom4j.DocumentFactory;
32 import org.dom4j.Element;
33 import org.dom4j.io.SAXReader;
34 import org.dom4j.io.XMLWriter;
35 import org.kohsuke.stapler.QueryParameter;
36 import org.kohsuke.stapler.StaplerRequest;
37 import org.kohsuke.stapler.StaplerResponse;
38 import org.kohsuke.stapler.export.*;
39 import org.kohsuke.stapler.export.TreePruner.ByDepth;
40
41 import javax.servlet.ServletException;
42 import javax.servlet.http.HttpServletResponse;
43 import javax.xml.transform.stream.StreamResult;
44 import java.io.IOException;
45 import java.io.OutputStream;
46 import java.io.StringReader;
47 import java.io.StringWriter;
48 import java.net.HttpURLConnection;
49 import java.util.List;
50 import java.util.logging.Level;
51 import java.util.logging.Logger;
52
53 /**
54 * Used to expose remote access API for ".../api/"
55 *
56 * <p>
57 * If the parent object has a <tt>_api.jelly</tt> view, it will be included
58 * in the api index page.
59 *
60 * @author Kohsuke Kawaguchi
61 * @see Exported
62 */
63 public class Api extends AbstractModelObject {
64 /**
65 * Model object to be exposed as XML/JSON/etc.
66 */
67 public final Object bean;
68
69 public Api(Object bean) {
70 this.bean = bean;
71 }
72
73 public String getDisplayName() {
74 return "API";
75 }
76
77 public String getSearchUrl() {
78 return "api";
79 }
80
81 /**
82 * Exposes the bean as XML.
83 */
84 public void doXml(StaplerRequest req, StaplerResponse rsp,
85 @QueryParameter String xpath,
86 @QueryParameter String wrapper,
87 @QueryParameter String tree,
88 @QueryParameter int depth) throws IOException, ServletException {
89 setHeaders(rsp);
90
91 String[] excludes = req.getParameterValues("exclude");
92
93 if(xpath==null && excludes==null) {
94 // serve the whole thing
95 rsp.serveExposedBean(req,bean,Flavor.XML);
96 return;
97 }
98
99 StringWriter sw = new StringWriter();
100
101 // first write to String
102 Model p = MODEL_BUILDER.get(bean.getClass());
103 TreePruner pruner = (tree!=null) ? new NamedPathPruner(tree) : new ByDepth(1 - depth);
104 p.writeTo(bean,pruner,Flavor.XML.createDataWriter(bean,sw));
105
106 // apply XPath
107 Object result;
108 try {
109 Document dom = new SAXReader().read(new StringReader(sw.toString()));
110
111 // apply exclusions
112 if (excludes!=null) {
113 for (String exclude : excludes) {
114 List<org.dom4j.Node> list = (List<org.dom4j.Node>)dom.selectNodes(exclude);
115 for (org.dom4j.Node n : list) {
116 Element parent = n.getParent();
117 if(parent!=null)
118 parent.remove(n);
119 }
120 }
121 }
122
123 if(xpath==null) {
124 result = dom;
125 } else {
126 List list = dom.selectNodes(xpath);
127 if (wrapper!=null) {
128 Element root = DocumentFactory.getInstance().createElement(wrapper);
129 for (Object o : list) {
130 if (o instanceof String) {
131 root.addText(o.toString());
132 } else {
133 root.add(((org.dom4j.Node)o).detach());
134 }
135 }
136 result = root;
137 } else if (list.isEmpty()) {
138 rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
139 rsp.getWriter().print(Messages.Api_NoXPathMatch(xpath));
140 return;
141 } else if (list.size() > 1) {
142 rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
143 rsp.getWriter().print(Messages.Api_MultipleMatch(xpath,list.size()));
144 return;
145 } else {
146 result = list.get(0);
147 }
148 }
149
150 } catch (DocumentException e) {
151 LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:"+sw, e);
152 throw new IOException2("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.",e);
153 }
154
155 OutputStream o = rsp.getCompressedOutputStream(req);
156 try {
157 if (result instanceof CharacterData || result instanceof String || result instanceof Number || result instanceof Boolean) {
158 if (INSECURE) {
159 rsp.setContentType("text/plain;charset=UTF-8");
160 String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString();
161 o.write(text.getBytes("UTF-8"));
162 } else {
163 rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; can use -Dhudson.model.Api.INSECURE=true if you run without security");
164 }
165 return;
166 }
167
168 // otherwise XML
169 rsp.setContentType("application/xml;charset=UTF-8");
170 new XMLWriter(o).write(result);
171 } finally {
172 o.close();
173 }
174 }
175
176 /**
177 * Generate schema.
178 */
179 public void doSchema(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
180 setHeaders(rsp);
181 rsp.setContentType("application/xml");
182 StreamResult r = new StreamResult(rsp.getOutputStream());
183 new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r);
184 r.getOutputStream().close();
185 }
186
187 /**
188 * Exposes the bean as JSON.
189 */
190 public void doJson(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
191 if (INSECURE || req.getParameter("jsonp") == null) {
192 setHeaders(rsp);
193 rsp.serveExposedBean(req,bean, Flavor.JSON);
194 } else {
195 rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "jsonp forbidden; can use -Dhudson.model.Api.INSECURE=true if you run without security");
196 }
197 }
198
199 /**
200 * Exposes the bean as Python literal.
201 */
202 public void doPython(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
203 setHeaders(rsp);
204 rsp.serveExposedBean(req,bean, Flavor.PYTHON);
205 }
206
207 private void setHeaders(StaplerResponse rsp) {
208 rsp.setHeader("X-Jenkins", Jenkins.VERSION);
209 rsp.setHeader("X-Jenkins-Session", Jenkins.SESSION_HASH);
210 }
211
212 private static final Logger LOGGER = Logger.getLogger(Api.class.getName());
213 private static final ModelBuilder MODEL_BUILDER = new ModelBuilder();
214 private static final boolean INSECURE = "true".equals(System.getProperty("hudson.model.Api.INSECURE"));
215
216 }
217