73051392c6224fe87b59de04493796020ceca068
[ccsdk/cds.git] /
1 /*
2  *  Copyright © 2019 IBM.
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  */
16
17 package org.onap.ccsdk.cds.controllerblueprints.core.scripts
18
19 import com.google.common.cache.CacheBuilder
20 import com.google.common.cache.CacheLoader
21 import com.google.common.cache.LoadingCache
22 import com.google.common.util.concurrent.ListenableFuture
23 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
24 import org.onap.ccsdk.cds.controllerblueprints.core.logger
25 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
26 import java.net.URL
27 import java.net.URLClassLoader
28
29
30 object BluePrintCompileCache {
31     val log = logger(BluePrintCompileCache::class)
32
33     private val classLoaderCache: LoadingCache<String, URLClassLoader> = CacheBuilder.newBuilder()
34             .maximumSize(10)
35             .build(BluePrintClassLoader)
36
37     fun classLoader(key: String): URLClassLoader {
38         return classLoaderCache.get(key)
39     }
40
41     fun cleanClassLoader(key: String) {
42         classLoaderCache.invalidate(key)
43         log.info("Cleaned script cache($key)")
44     }
45
46     fun hasClassLoader(key: String): Boolean {
47         return classLoaderCache.asMap().containsKey(key)
48     }
49 }
50
51 object BluePrintClassLoader : CacheLoader<String, URLClassLoader>() {
52
53     val log = logger(BluePrintClassLoader::class)
54
55     override fun reload(key: String, oldValue: URLClassLoader): ListenableFuture<URLClassLoader> {
56         return reload(key, oldValue)
57     }
58
59     override fun load(key: String): URLClassLoader {
60         log.info("loading cache key($key)")
61         val keyPath = normalizedFile(key)
62         if (!keyPath.exists()) {
63             throw BluePrintException("failed to load cache($key), missing files.")
64         }
65         val urls = arrayListOf<URL>()
66         keyPath.walkTopDown()
67                 .filter { it.name.endsWith("cba-kts.jar") }
68                 .forEach {
69                     log.debug("Adding (${it.absolutePath}) to cache key($key)")
70                     urls.add(it.toURI().toURL())
71                 }
72         return URLClassLoader(urls.toTypedArray(), this.javaClass.classLoader)
73     }
74 }