001/** 002 * Copyright (C) 2006-2024 Talend Inc. - www.talend.com 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.talend.sdk.component.runtime.manager.interceptor; 017 018import static java.util.stream.Collectors.joining; 019 020import java.lang.reflect.Method; 021import java.util.concurrent.ConcurrentHashMap; 022import java.util.concurrent.ConcurrentMap; 023import java.util.function.BiFunction; 024import java.util.stream.Stream; 025 026import org.talend.sdk.component.api.service.cache.Cached; 027import org.talend.sdk.component.api.service.cache.LocalCache; 028import org.talend.sdk.component.api.service.interceptor.InterceptorHandler; 029 030public class CacheHandler implements InterceptorHandler { 031 032 private final BiFunction<Method, Object[], Object> invoker; 033 034 private final LocalCache cache; 035 036 private final ConcurrentMap<Method, Long> timeouts = new ConcurrentHashMap<>(); 037 038 public CacheHandler(final BiFunction<Method, Object[], Object> invoker, final LocalCache cache) { 039 this.invoker = invoker; 040 this.cache = cache; 041 } 042 043 @Override 044 public Object invoke(final Method method, final Object[] args) { 045 final String key = toKey(method, args); 046 final long timeout = timeouts.computeIfAbsent(method, m -> findAnnotation(m, Cached.class).get().timeout()); 047 return cache.computeIfAbsent(Object.class, key, timeout, () -> invoker.apply(method, args)); 048 } 049 050 // assumes toString() and hashCode() of params are representative 051 private String toKey(final Method method, final Object[] args) { 052 return method.getDeclaringClass().getName() + "#" + method.getName() + "(" 053 + (args == null ? "" 054 : Stream 055 .of(args) 056 .map(s -> String.valueOf(s) + "/" + (s == null ? 0 : s.hashCode())) 057 .collect(joining(","))) 058 + ")"; 059 } 060}