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