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.io.IOException;
  19. import org.apache.tools.ant.BuildException;
  20. import org.apache.tools.ant.Project;
  21. import org.apache.tools.ant.ProjectComponent;
  22. /**
  23. * Condition to wait for a TCP/IP socket to have a listener. Its attributes are:
  24. * server - the name of the server.
  25. * port - the port number of the socket.
  26. *
  27. * @since Ant 1.5
  28. */
  29. public class Socket extends ProjectComponent implements Condition {
  30. private String server = null;
  31. private int port = 0;
  32. /**
  33. * Set the server attribute
  34. *
  35. * @param server the server name
  36. */
  37. public void setServer(String server) {
  38. this.server = server;
  39. }
  40. /**
  41. * Set the port attribute
  42. *
  43. * @param port the port number of the socket
  44. */
  45. public void setPort(int port) {
  46. this.port = port;
  47. }
  48. /**
  49. * @return true if a socket can be created
  50. * @exception BuildException if the attributes are not set
  51. */
  52. public boolean eval() throws BuildException {
  53. if (server == null) {
  54. throw new BuildException("No server specified in socket "
  55. + "condition");
  56. }
  57. if (port == 0) {
  58. throw new BuildException("No port specified in socket condition");
  59. }
  60. log("Checking for listener at " + server + ":" + port,
  61. Project.MSG_VERBOSE);
  62. java.net.Socket s = null;
  63. try {
  64. s = new java.net.Socket(server, port);
  65. } catch (IOException e) {
  66. return false;
  67. } finally {
  68. if (s != null) {
  69. try {
  70. s.close();
  71. } catch (IOException ioe) {
  72. // Intentionally left blank
  73. }
  74. }
  75. }
  76. return true;
  77. }
  78. }