2 * Copyright © 2019 IBM.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.ccsdk.cds.controllerblueprints.core.scripts
19 import com.google.common.cache.CacheBuilder
20 import com.google.common.cache.CacheLoader
21 import com.google.common.cache.LoadingCache
22 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
23 import org.onap.ccsdk.cds.controllerblueprints.core.logger
24 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
25 import java.net.URLClassLoader
27 object BluePrintCompileCache {
29 val log = logger(BluePrintCompileCache::class)
31 private val classLoaderCache: LoadingCache<String, URLClassLoader> = CacheBuilder.newBuilder()
33 .build(BluePrintClassLoader)
35 fun classLoader(key: String): URLClassLoader {
36 return classLoaderCache.get(key)
39 fun cleanClassLoader(key: String) {
40 if (hasClassLoader(key)) {
41 // Make sure to close all classloader loaded resources before we let go of it.
42 // This fixes a Delete failure message on filesystem that keeps locks on opened jars;
43 // like Windows and NFS.
44 classLoaderCache.get(key).close()
45 classLoaderCache.invalidate(key)
46 log.info("Cleaned compiled cache($key)")
48 log.warn("No compiled cache($key) present to clean.")
52 fun hasClassLoader(key: String): Boolean {
53 return classLoaderCache.asMap().containsKey(key)
57 object BluePrintClassLoader : CacheLoader<String, URLClassLoader>() {
59 val log = logger(BluePrintClassLoader::class)
61 override fun load(key: String) = try {
62 log.info("loading compiled cache($key)")
63 BluePrintFileUtils.getURLClassLoaderFromDirectory(key)
64 } catch (e: Exception) {
65 throw BluePrintException("failed to load cache($key) with Exception($e)")