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 */
017package org.apache.juneau.internal;
018
019import static org.apache.juneau.commons.utils.Utils.*;
020
021import java.util.*;
022
023import org.apache.juneau.*;
024import org.apache.juneau.collections.*;
025
026/**
027 * Represents a wrapped {@link Map} where entries in the map can be removed without affecting the underlying map.
028 *
029 *
030 * @param <T> The class type of the wrapped bean.
031 * @serial exclude
032 */
033@SuppressWarnings("rawtypes")
034public class DelegateMap<T extends Map> extends JsonMap implements Delegate<T> {
035   private static final long serialVersionUID = 1L;
036
037   private transient ClassMeta<T> classMeta;
038
039   /**
040    * Constructor.
041    *
042    * @param m The metadata object that created this delegate object.
043    * @param session The current bean session.
044    */
045   @SuppressWarnings("unchecked")
046   public DelegateMap(T m, BeanSession session) {
047      this.classMeta = session.getClassMetaForObject(m);
048      m.forEach((k, v) -> put(s(k), v));
049   }
050
051   /**
052    * Remove all but the specified keys from this map.
053    *
054    * <p>
055    * This does not affect the underlying map.
056    *
057    * @param keys The remaining keys in the map (in the specified order).
058    * @return This object.
059    */
060   public DelegateMap<T> filterKeys(List<String> keys) {
061      var m = new JsonMap();
062      keys.forEach(k -> {
063         if (containsKey(k))
064            m.put(k, get(k));
065      });
066      this.clear();
067      this.putAll(m);
068      return this;
069   }
070
071   @Override /* Overridden from Delegate */
072   public ClassMeta<T> getClassMeta() { return classMeta; }
073}