Author: nickboldt
Date: 2011-01-15 14:42:34 -0500 (Sat, 15 Jan 2011)
New Revision: 28268
Modified:
workspace/rstryker/hudson/plugins/org.jboss.tools.hudson.manager.core/src/org/jboss/tools/hudson/manager/core/util/HudsonXMLUtil.java
Log:
add methods for posting config.xml back to server to update a job
Modified:
workspace/rstryker/hudson/plugins/org.jboss.tools.hudson.manager.core/src/org/jboss/tools/hudson/manager/core/util/HudsonXMLUtil.java
===================================================================
---
workspace/rstryker/hudson/plugins/org.jboss.tools.hudson.manager.core/src/org/jboss/tools/hudson/manager/core/util/HudsonXMLUtil.java 2011-01-15
17:27:43 UTC (rev 28267)
+++
workspace/rstryker/hudson/plugins/org.jboss.tools.hudson.manager.core/src/org/jboss/tools/hudson/manager/core/util/HudsonXMLUtil.java 2011-01-15
19:42:34 UTC (rev 28268)
@@ -1,5 +1,254 @@
package org.jboss.tools.hudson.manager.core.util;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.httpclient.Credentials;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.URI;
+import org.apache.commons.httpclient.UsernamePasswordCredentials;
+import org.apache.commons.httpclient.auth.AuthScope;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.dom4j.Document;
+import org.dom4j.DocumentException;
+import org.dom4j.io.SAXReader;
+
public class HudsonXMLUtil {
+ private boolean verbose = false;
+ private String USERNAME = "admin";
+ private String PASSWORD = "chestnuts";
+ private String hudsonURL = "http://localhost:8080/";
+
+ // use like this to submit an updated config.xml to the server:
+ // postXML(configXMLFile, null, hudsonURL + "job/" + jobName +
+ // "/config.xml", true);
+
+ private String[] postXML(String xmlFile, String xmlContents, String jobURL,
+ boolean getErrorMessage) {
+ return postXML(new File(xmlFile), xmlContents, jobURL, getErrorMessage);
+ }
+
+ /**
+ *
+ * @param xmlFile - need either an absolute path to a file
+ * @param xmlContents - or a string containing the XML to write to file (eg., from
Document.asXML())
+ * @param jobURL - URL to which to post the XML
+ * @param getErrorMessage - return a string[] containing result code, or code + message
+ * @return
+ */
+ private String[] postXML(File xmlFile, String xmlContents, String jobURL,
+ boolean getErrorMessage) {
+ int resultCode = -1;
+ String responseBody = "";
+ PostMethod post = new PostMethod(jobURL);
+ HttpClient client = null;
+
+ if (xmlFile == null && xmlContents != null) {
+ File tempDir = null;
+ try {
+ tempDir = createTempDir(getClass().getSimpleName());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ xmlFile = new File(tempDir, "config.xml");
+ try {
+ // TODO: why do we need to write the xml to a file before
+ // pushing it to the server? can't this be streamed out instead?
+ writeToFile(xmlContents, xmlFile);
+ } catch (MojoExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ if (xmlFile != null) {
+ try {
+ post.setRequestEntity(new InputStreamRequestEntity(
+ new FileInputStream(xmlFile), xmlFile.length()));
+ } catch (FileNotFoundException e) {
+ System.err.println("File not found: " + xmlFile);
+ e.printStackTrace();
+ }
+
+ } else {
+ try {
+ throw new MojoExecutionException("Error writing to " + xmlFile);
+ } catch (MojoExecutionException e) {
+ System.err.println("Error writing to " + xmlFile
+ + " in postXML() !");
+ e.printStackTrace();
+ }
+ }
+ // Specify content type and encoding; default to ISO-8859-1
+ post.setRequestHeader("Content-type", "text/xml;
charset=ISO-8859-1");
+
+ if (client == null) {
+ client = getHttpClient(USERNAME, PASSWORD);
+ }
+ try {
+ resultCode = client.executeMethod(post);
+ if (getErrorMessage) {
+
+ responseBody = getResponseBody(post);
+ // resultString = getErrorMessage(post, jobURL);
+ }
+ } catch (HttpException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (DocumentException e) {
+ e.printStackTrace();
+ } finally {
+ post.releaseConnection();
+ }
+
+ if (getErrorMessage) {
+ return new String[] { resultCode + "", responseBody };
+ } else {
+ return new String[] { resultCode + "", "" };
+ }
+ }
+
+ public void writeDomToFile(Document dom, File file)
+ throws MojoExecutionException {
+ writeToFile(dom.asXML(), file);
+ }
+
+ public void writeToFile(String string, File file)
+ throws MojoExecutionException {
+ FileWriter w = null;
+ try {
+ w = new FileWriter(file);
+ w.write(string);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Error updating file " + file, e);
+ } finally {
+ if (w != null) {
+ try {
+ w.close();
+ } catch (IOException e) {
+ // ignore
+ }
+ }
+
+ }
+ }
+
+ public String getResponseBody(HttpMethod method) throws DocumentException,
+ IOException {
+ InputStream is = method.getResponseBodyAsStream();
+ Document dom = null;
+ String out = "";
+ if (is.available() > 0) {
+ dom = new SAXReader().read(is);
+ out = dom.asXML();
+ } else {
+ if (verbose) {
+ // 200: OK
+ // 400: Bad Request (job already exists, cannot createItem)
+ if (method.getStatusCode() != 200
+ && method.getStatusCode() != 400) {
+ System.out.println("["
+ + method.getStatusCode()
+ + "] "
+ + method.getStatusText()
+ + " for "
+ + method.getName()
+ + " to "
+ + method.getPath()
+ + (method.getQueryString() != null ? "?"
+ + method.getQueryString() : ""));
+ }
+ }
+ }
+ return out;
+ }
+
+ public HttpClient getHttpClient(String username, String password) {
+ HttpClient client = new HttpClient();
+ // establish a connection within 5 seconds
+ client.getHttpConnectionManager().getParams()
+ .setConnectionTimeout(5000);
+
+ if (hudsonURL.indexOf("localhost") >= 0) {
+ /* simpler authentication method, may not work w/ secured Hudson */
+ Credentials creds = new UsernamePasswordCredentials(username,
+ password);
+ if (creds != null) {
+ client.getState().setCredentials(AuthScope.ANY, creds);
+ }
+ } else {
+ GetMethod login = new GetMethod(hudsonURL + "loginEntry");
+ try {
+ client.executeMethod(login);
+ } catch (HttpException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ try {
+ checkResult(login.getStatusCode(), login.getURI());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ String location = hudsonURL + "j_security_check";
+ while (true) {
+ PostMethod loginMethod = new PostMethod(location);
+ loginMethod.addParameter("j_username", username);
+ loginMethod.addParameter("j_password", password);
+ loginMethod.addParameter("action", "login");
+ try {
+ client.executeMethod(loginMethod);
+ } catch (HttpException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ if (loginMethod.getStatusCode() / 100 == 3) {
+ // Commons HTTP client refuses to handle redirects for POST
+ // so we have to do it manually.
+ location = loginMethod.getResponseHeader("Location")
+ .getValue();
+ continue;
+ }
+ try {
+ checkResult(loginMethod.getStatusCode(),
+ loginMethod.getURI());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ break;
+ }
+ }
+ return client;
+ }
+
+ private static void checkResult(int i, URI uri) throws IOException {
+ if (i / 100 != 2) {
+ // System.out.println("[WARN] Got result: " + i + " for "+
+ // uri.toString());
+ throw new IOException("Got result: " + i + " for " +
uri.toString());
+ }
+ }
+
+ public File createTempDir(String prefix) throws IOException {
+ File directory = File.createTempFile(prefix, "");
+ if (directory.delete()) {
+ directory.mkdirs();
+ return directory;
+ } else {
+ throw new IOException("Could not create temp directory at: "
+ + directory.getAbsolutePath());
+ }
+ }
+
}
Show replies by date