1. /*
  2. * Copyright 2002-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 org.apache.tools.ant.BuildException;
  19. import org.apache.tools.ant.ProjectComponent;
  20. import org.apache.tools.ant.types.Reference;
  21. /**
  22. * Condition that tests whether a given reference has been defined.
  23. *
  24. * <p>Optionally tests whether it is of a given type/class.</p>
  25. *
  26. * @since Ant 1.6
  27. * @version $Revision: 1.5.2.4 $
  28. */
  29. public class IsReference extends ProjectComponent implements Condition {
  30. private Reference ref;
  31. private String type;
  32. /**
  33. * Set the refid attribute.
  34. *
  35. * @param r a Reference value
  36. */
  37. public void setRefid(Reference r) {
  38. ref = r;
  39. }
  40. /**
  41. * Set the type attribute. This is optional attribute.
  42. *
  43. * @param type an ant component type name
  44. */
  45. public void setType(String type) {
  46. this.type = type;
  47. }
  48. /**
  49. * @return true if the reference exists and if type is set, if
  50. * the reference is the same type
  51. * @exception BuildException if an error occurs
  52. */
  53. public boolean eval() throws BuildException {
  54. if (ref == null) {
  55. throw new BuildException("No reference specified for isreference "
  56. + "condition");
  57. }
  58. Object o = getProject().getReference(ref.getRefId());
  59. if (o == null) {
  60. return false;
  61. } else if (type == null) {
  62. return true;
  63. } else {
  64. Class typeClass =
  65. (Class) getProject().getDataTypeDefinitions().get(type);
  66. if (typeClass == null) {
  67. typeClass =
  68. (Class) getProject().getTaskDefinitions().get(type);
  69. }
  70. if (typeClass == null) {
  71. // don't know the type, should throw exception instead?
  72. return false;
  73. }
  74. return typeClass.isAssignableFrom(o.getClass());
  75. }
  76. }
  77. }