01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18:
19: package org.apache.tools.ant.taskdefs.condition;
20:
21: import java.net.HttpURLConnection;
22: import java.net.MalformedURLException;
23: import java.net.URL;
24: import java.net.URLConnection;
25: import org.apache.tools.ant.BuildException;
26: import org.apache.tools.ant.Project;
27: import org.apache.tools.ant.ProjectComponent;
28:
29: /**
30: * Condition to wait for a HTTP request to succeed. Its attribute(s) are:
31: * url - the URL of the request.
32: * errorsBeginAt - number at which errors begin at; default=400.
33: * @since Ant 1.5
34: */
35: public class Http extends ProjectComponent implements Condition {
36: private static final int ERROR_BEGINS = 400;
37: private String spec = null;
38:
39: /**
40: * Set the url attribute
41: * @param url the url of the request
42: */
43: public void setUrl(String url) {
44: spec = url;
45: }
46:
47: private int errorsBeginAt = ERROR_BEGINS;
48:
49: /**
50: * Set the errorsBeginAt attribute
51: * @param errorsBeginAt number at which errors begin at, default is
52: * 400
53: */
54: public void setErrorsBeginAt(int errorsBeginAt) {
55: this .errorsBeginAt = errorsBeginAt;
56: }
57:
58: /**
59: * @return true if the HTTP request succeeds
60: * @exception BuildException if an error occurs
61: */
62: public boolean eval() throws BuildException {
63: if (spec == null) {
64: throw new BuildException(
65: "No url specified in http condition");
66: }
67: log("Checking for " + spec, Project.MSG_VERBOSE);
68: try {
69: URL url = new URL(spec);
70: try {
71: URLConnection conn = url.openConnection();
72: if (conn instanceof HttpURLConnection) {
73: HttpURLConnection http = (HttpURLConnection) conn;
74: int code = http.getResponseCode();
75: log("Result code for " + spec + " was " + code,
76: Project.MSG_VERBOSE);
77: if (code > 0 && code < errorsBeginAt) {
78: return true;
79: }
80: return false;
81: }
82: } catch (java.io.IOException e) {
83: return false;
84: }
85: } catch (MalformedURLException e) {
86: throw new BuildException("Badly formed URL: " + spec, e);
87: }
88: return true;
89: }
90: }
|