001/*
002 * Copyright c 2018 Rusi Popov, MDA Tools.net All rights reserved.
003 *
004 * This program and the accompanying materials are made available under the terms of the
005 * Eclipse Public License v2.0 which accompanies this distribution, and is available at
006 * http://www.eclipse.org/legal/epl-v20.html
007 */
008package net.mdatools.modelant.core.operation.model.topology;
009
010import java.util.Collection;
011import java.util.HashMap;
012import java.util.Map;
013
014import javax.jmi.reflect.RefBaseObject;
015import javax.jmi.reflect.RefObject;
016
017import net.mdatools.modelant.core.api.Function;
018
019/**
020 * Cache the results of the wrapped operation based on the reflective type of the argument
021 */
022public class CacheClassResults implements Function<RefObject, Collection<String>> {
023
024  /**
025   * wrapped operation to cache results of
026   */
027  private final Function<RefObject, Collection<String>> wrapped;
028
029  /**
030   * cache of results
031   */
032  private final Map<RefBaseObject, Collection<String>> cache = new HashMap<>();
033
034  /**
035   * @param wrapped not null operation to wrap and whose results to cache
036   */
037  public CacheClassResults(Function<RefObject, Collection<String>> wrapped) {
038    this.wrapped = wrapped;
039  }
040
041  public Collection<String> execute(RefObject arg0) throws RuntimeException, IllegalArgumentException {
042    Collection<String> result;
043
044    result = cache.get( arg0.refClass() );
045    if ( result == null  ) {
046      result = wrapped.execute( arg0 );
047
048      cache.put( arg0.refClass(), result );
049    }
050    return result;
051  }
052}