001: package dalma.ant;
002:
003: import org.apache.tools.ant.BuildException;
004: import org.apache.tools.ant.Project;
005: import org.apache.tools.ant.Task;
006:
007: import java.io.File;
008: import java.io.FileInputStream;
009: import java.io.IOException;
010: import java.io.InputStream;
011: import java.io.PrintStream;
012: import java.net.HttpURLConnection;
013: import java.net.URL;
014:
015: /**
016: * Deploys a dar file to the webui.
017: *
018: * @author Kohsuke Kawaguchi
019: */
020: public class Deployer extends Task {
021: private String name;
022: private URL dalmaUrl;
023: private File darFile;
024:
025: public void setName(String name) {
026: this .name = name;
027: }
028:
029: public void setURL(URL url) {
030: this .dalmaUrl = url;
031: }
032:
033: public void setFile(File darFile) {
034: this .darFile = darFile;
035: }
036:
037: private static final String BOUNDARY = "---aXej3hgOjxE";
038: private static final String NEWLINE = "\r\n";
039:
040: public void execute() throws BuildException {
041: try {
042: if (name == null)
043: throw new BuildException(
044: "No application name is specified");
045: if (dalmaUrl == null)
046: throw new BuildException("URL is not specified");
047:
048: log("Deploying to " + dalmaUrl, Project.MSG_INFO);
049:
050: HttpURLConnection con = (HttpURLConnection) new URL(
051: dalmaUrl, "createApp").openConnection();
052: con.setDoOutput(true);
053: con.setRequestMethod("POST");
054: con.setRequestProperty("Content-Type",
055: "multipart/form-data; boundary=" + BOUNDARY);
056: con.connect();
057: PrintStream out = new PrintStream(con.getOutputStream());
058: out.print("--" + BOUNDARY);
059: out.print(NEWLINE);
060: out.print("Content-Disposition: form-data; name=\"name\"");
061: out.print(NEWLINE);
062: out.print(NEWLINE);
063: out.print(name);
064: out.print(NEWLINE);
065: out.print("--" + BOUNDARY);
066: out.print(NEWLINE);
067: out
068: .print("Content-Disposition: form-data; name=\"file\"; filename=\"some.dar\"");
069: out.print(NEWLINE);
070: out.print("Content-Type: application/octet-stream");
071: out.print(NEWLINE);
072: out.print("Content-Length: " + darFile.length());
073: out.print(NEWLINE);
074: out.print(NEWLINE);
075:
076: InputStream in = new FileInputStream(darFile);
077: copyStream(in, out);
078: out.print(NEWLINE);
079:
080: out.print("--" + BOUNDARY + "--");
081: out.print(NEWLINE);
082: out.close();
083:
084: if (con.getResponseCode() >= 300) {
085: String msg = "Failed to deploy: "
086: + con.getResponseMessage();
087: log(msg, Project.MSG_ERR);
088: in = con.getErrorStream();
089: copyStream(in, System.out);
090: throw new BuildException(msg);
091: }
092: } catch (IOException e) {
093: throw new BuildException(e);
094: }
095: }
096:
097: private void copyStream(InputStream in, PrintStream out)
098: throws IOException {
099: byte[] buf = new byte[8192];
100: int len;
101: while ((len = in.read(buf)) >= 0) {
102: out.write(buf, 0, len);
103: }
104: in.close();
105: }
106: }
|