1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * 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 package org.apache.commons.jxpath; 19 20 import java.util.HashMap; 21 22 /** 23 * A basic implementation of the Variables interface that uses a HashMap. 24 */ 25 public class BasicVariables implements Variables { 26 27 private static final long serialVersionUID = 2708263960832062725L; 28 29 /** 30 * Contains the values of declared variables 31 */ 32 private final HashMap vars = new HashMap(); 33 34 /** 35 * Constructs a new instance. 36 */ 37 public BasicVariables() { 38 // empty 39 } 40 41 /** 42 * Defines a new variable with the specified value or modifies the value of an existing variable. 43 * 44 * @param varName is a variable name without the "$" sign 45 * @param value is the new value for the variable, which can be null 46 */ 47 @Override 48 public void declareVariable(final String varName, final Object value) { 49 vars.put(varName, value); 50 } 51 52 /** 53 * Returns the value of the variable if it is defined, otherwise, throws IllegalArgumentException 54 * 55 * @param varName is a variable name without the "$" sign 56 * @return the value of the variable 57 */ 58 @Override 59 public Object getVariable(final String varName) { 60 // Note that a variable may be defined with a null value 61 if (vars.containsKey(varName)) { 62 return vars.get(varName); 63 } 64 throw new IllegalArgumentException("No such variable: '" + varName + "'"); 65 } 66 67 /** 68 * Returns true if the variable has been defined, even if the value of the variable is null. 69 * 70 * @param varName is a variable name without the "$" sign 71 * @return true if the variable is declared 72 */ 73 @Override 74 public boolean isDeclaredVariable(final String varName) { 75 return vars.containsKey(varName); 76 } 77 78 @Override 79 public String toString() { 80 return vars.toString(); 81 } 82 83 /** 84 * Removes an existing variable. May throw UnsupportedOperationException. 85 * 86 * @param varName is a variable name without the "$" sign 87 */ 88 @Override 89 public void undeclareVariable(final String varName) { 90 vars.remove(varName); 91 } 92 }