1. /*
  2. * Copyright 1999-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. package org.apache.commons.jxpath;
  17. import java.util.HashMap;
  18. /**
  19. * A basic implementation of the Variables interface that uses a HashMap.
  20. *
  21. * @author Dmitri Plotnikov
  22. * @version $Revision: 1.7 $ $Date: 2004/02/29 14:17:42 $
  23. */
  24. public class BasicVariables implements Variables {
  25. /**
  26. * Contains the values of declared variables
  27. */
  28. private HashMap vars = new HashMap();
  29. /**
  30. * Returns true if the variable has been defined, even if the
  31. * value of the variable is null.
  32. *
  33. * @param varName is a variable name without the "$" sign
  34. *
  35. * @return true if the variable is declared
  36. */
  37. public boolean isDeclaredVariable(String varName) {
  38. return vars.containsKey(varName);
  39. }
  40. /**
  41. * Returns the value of the variable if it is defined,
  42. * otherwise, throws IllegalArgumentException
  43. *
  44. * @param varName is a variable name without the "$" sign
  45. *
  46. * @return the value of the variable
  47. */
  48. public Object getVariable(String varName) {
  49. // Note that a variable may be defined with a null value
  50. if (vars.containsKey(varName)) {
  51. return vars.get(varName);
  52. }
  53. throw new IllegalArgumentException(
  54. "No such variable: '" + varName + "'");
  55. }
  56. /**
  57. * Defines a new variable with the specified value or modifies
  58. * the value of an existing variable.
  59. *
  60. * @param varName is a variable name without the "$" sign
  61. * @param value is the new value for the variable, which can be null
  62. */
  63. public void declareVariable(String varName, Object value) {
  64. vars.put(varName, value);
  65. }
  66. /**
  67. * Removes an existing variable. May throw UnsupportedOperationException.
  68. *
  69. * @param varName is a variable name without the "$" sign
  70. */
  71. public void undeclareVariable(String varName) {
  72. vars.remove(varName);
  73. }
  74. public String toString() {
  75. return vars.toString();
  76. }
  77. }