    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.jexl3;
    019
    020import java.util.HashMap;
    021import java.util.Map;
    022
    023/**
    024 * Wraps a map in a context.
    025 * <p>Each entry in the map is considered a variable name, value pair.</p>
    026 */
    027public class MapContext implements JexlContext {
    028
    029    /**
    030     * The wrapped variable map.
    031     */
    032    private final Map<String, Object> map;
    033
    034    /**
    035     * Creates a MapContext on an automatically allocated underlying HashMap.
    036     */
    037    public MapContext() {
    038        this(null);
    039    }
    040
    041    /**
    042     * Creates a MapContext wrapping an existing user provided map.
    043     *
    044     * @param vars the variable map
    045     */
    046    public MapContext(final Map<String, Object> vars) {
    047        map = vars == null ? new HashMap<>() : vars;
    048    }
    049
    050    @Override
    051    public boolean has(final String name) {
    052        return map.containsKey(name);
    053    }
    054
    055    @Override
    056    public Object get(final String name) {
    057        return map.get(name);
    058    }
    059
    060    @Override
    061    public void set(final String name, final Object value) {
    062        map.put(name, value);
    063    }
    064
    065    /**
    066     * Clears all variables.
    067     */
    068    public void clear() {
    069        map.clear();
    070    }
    071}