Java tutorial
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.extra; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; public class DockerMetadataCache { private static final Logger LOG = LoggerFactory.getLogger(DockerMetadataCache.class); private final LoadingCache<String, Map> cache; private final String basePath; private final String filename; public DockerMetadataCache(String base, String file) { this.basePath = base; this.filename = file; CacheLoader<String, Map> loader = new CacheLoader<String, Map>() { private final ObjectMapper mapper = new ObjectMapper(); @Override public Map load(String key) throws Exception { FileSystem fs = FileSystems.getDefault(); Path path = fs.getPath(basePath, key, filename); final String contents = new String(Files.readAllBytes(path), Charset.forName("UTF-8")); return mapper.readValue(contents, HashMap.class); } }; cache = CacheBuilder.newBuilder().expireAfterAccess(10, TimeUnit.MINUTES).maximumSize(1000).build(loader); } public Object get(String key) { try { return cache.get(key); } catch (ExecutionException e) { LOG.error("Failed to get cached object for key: '{}'", key); return null; } } }