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

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
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;
25
26 import hudson.util.DualOutputStream;
27 import hudson.util.EncodingStream;
28 import com.thoughtworks.xstream.core.util.Base64Encoder;
29 import hudson.util.IOUtils;
30
31 import java.io.File;
32 import java.io.FileInputStream;
33 import java.io.FileOutputStream;
34 import java.io.IOException;
35 import java.io.OutputStreamWriter;
36 import java.io.Writer;
37 import java.net.HttpRetryException;
38 import java.net.HttpURLConnection;
39 import java.net.URL;
40 import java.net.URLEncoder;
41 import java.util.ArrayList;
42 import java.util.List;
43 import java.nio.charset.Charset;
44
45 /**
46 * Entry point to Hudson from command line.
47 *
48 * <p>
49 * This tool runs another process and sends its result to Hudson.
50 *
51 * @author Kohsuke Kawaguchi
52 */
53 public class Main {
54 public static void main(String[] args) {
55 try {
56 System.exit(run(args));
57 } catch (Exception e) {
58 e.printStackTrace();
59 System.exit(-1);
60 }
61 }
62
63 public static int run(String[] args) throws Exception {
64 String home = getHudsonHome();
65 if (home==null) {
66 System.err.println("JENKINS_HOME is not set.");
67 return -1;
68 }
69 if (args.length < 2) {
70 System.err.println("Usage: <job-name> <command> <args..>");
71 return -1;
72 }
73
74 return remotePost(args);
75 }
76
77 private static String getHudsonHome() {
78 String home = EnvVars.masterEnvVars.get("JENKINS_HOME");
79 if (home!=null) return home;
80 return EnvVars.masterEnvVars.get("HUDSON_HOME");
81 }
82
83 /**
84 * Run command and place the result to a remote Hudson installation
85 */
86 public static int remotePost(String[] args) throws Exception {
87 String projectName = args[0];
88
89 String home = getHudsonHome();
90 if(!home.endsWith("/")) home = home + '/'; // make sure it ends with '/'
91
92 // check for authentication info
93 String auth = new URL(home).getUserInfo();
94 if(auth != null) auth = "Basic " + new Base64Encoder().encode(auth.getBytes("UTF-8"));
95
96 {// check if the home is set correctly
97 HttpURLConnection con = open(new URL(home));
98 if (auth != null) con.setRequestProperty("Authorization", auth);
99 con.connect();
100 if(con.getResponseCode()!=200
101 || con.getHeaderField("X-Hudson")==null) {
102 System.err.println(home+" is not Hudson ("+con.getResponseMessage()+")");
103 return -1;
104 }
105 }
106
107 String projectNameEnc = URLEncoder.encode(projectName,"UTF-8").replaceAll("\\+","%20");
108
109 {// check if the job name is correct
110 HttpURLConnection con = open(new URL(home+"job/"+projectNameEnc+"/acceptBuildResult"));
111 if (auth != null) con.setRequestProperty("Authorization", auth);
112 con.connect();
113 if(con.getResponseCode()!=200) {
114 System.err.println(projectName+" is not a valid job name on "+home+" ("+con.getResponseMessage()+")");
115 return -1;
116 }
117 }
118
119 // get a crumb to pass the csrf check
120 String crumbField = null, crumbValue = null;
121 try {
122 HttpURLConnection con = open(new URL(home +
123 "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
124 if (auth != null) con.setRequestProperty("Authorization", auth);
125 String line = IOUtils.readFirstLine(con.getInputStream(),"UTF-8");
126 String[] components = line.split(":");
127 if (components.length == 2) {
128 crumbField = components[0];
129 crumbValue = components[1];
130 }
131 } catch (IOException e) {
132 // presumably this Hudson doesn't use CSRF protection
133 }
134
135 // write the output to a temporary file first.
136 File tmpFile = File.createTempFile("hudson","log");
137 try {
138 FileOutputStream os = new FileOutputStream(tmpFile);
139
140 Writer w = new OutputStreamWriter(os,"UTF-8");
141 w.write("<?xml version='1.0' encoding='UTF-8'?>");
142 w.write("<run><log encoding='hexBinary' content-encoding='"+Charset.defaultCharset().name()+"'>");
143 w.flush();
144
145 // run the command
146 long start = System.currentTimeMillis();
147
148 List<String> cmd = new ArrayList<String>();
149 for( int i=1; i<args.length; i++ )
150 cmd.add(args[i]);
151 Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]),(String[])null,System.in,
152 new DualOutputStream(System.out,new EncodingStream(os)));
153
154 int ret = proc.join();
155
156 w.write("</log><result>"+ret+"</result><duration>"+(System.currentTimeMillis()-start)+"</duration></run>");
157 w.close();
158
159 String location = home+"job/"+projectNameEnc+"/postBuildResult";
160 while(true) {
161 try {
162 // start a remote connection
163 HttpURLConnection con = open(new URL(location));
164 if (auth != null) con.setRequestProperty("Authorization", auth);
165 if (crumbField != null && crumbValue != null) {
166 con.setRequestProperty(crumbField, crumbValue);
167 }
168 con.setDoOutput(true);
169 // this tells HttpURLConnection not to buffer the whole thing
170 con.setFixedLengthStreamingMode((int)tmpFile.length());
171 con.connect();
172 // send the data
173 FileInputStream in = new FileInputStream(tmpFile);
174 Util.copyStream(in,con.getOutputStream());
175 in.close();
176
177 if(con.getResponseCode()!=200) {
178 Util.copyStream(con.getErrorStream(),System.err);
179 }
180
181 return ret;
182 } catch (HttpRetryException e) {
183 if(e.getLocation()!=null) {
184 // retry with the new location
185 location = e.getLocation();
186 continue;
187 }
188 // otherwise failed for reasons beyond us.
189 throw e;
190 }
191 }
192 } finally {
193 tmpFile.delete();
194 }
195 }
196
197 /**
198 * Connects to the given HTTP URL and configure time out, to avoid infinite hang.
199 */
200 private static HttpURLConnection open(URL url) throws IOException {
201 HttpURLConnection c = (HttpURLConnection)url.openConnection();
202 c.setReadTimeout(TIMEOUT);
203 c.setConnectTimeout(TIMEOUT);
204 return c;
205 }
206
207 /**
208 * Set to true if we are running unit tests.
209 */
210 public static boolean isUnitTest = false;
211
212 /**
213 * Set to true if we are running inside "mvn hpi:run" or "mvn hudson-dev:run"
214 */
215 public static boolean isDevelopmentMode = Boolean.getBoolean(Main.class.getName()+".development");
216
217 /**
218 * Time out for socket connection to Hudson.
219 */
220 public static final int TIMEOUT = Integer.getInteger(Main.class.getName()+".timeout",15000);
221 }
222