91b74042242d9c70c1bd1a14fe81d9bd4798be10
[dcaegen2/collectors/datafile.git] /
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2019 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. 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 distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * ============LICENSE_END========================================================================
15  */
16
17 package org.onap.dcaegen2.collectors.datafile.service;
18
19 import java.nio.file.Path;
20 import java.time.Instant;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.Map;
24
25 /**
26  * A cache of all files that already has been published. Key is the local file path and the value is a time stamp, when
27  * the key was last used.
28  */
29 public class PublishedFileCache {
30     private final Map<Path, Instant> publishedFiles = new HashMap<Path, Instant>();
31
32     /**
33      * Adds a file to the cache.
34      *
35      * @param path the name of the file to add.
36      * @return <code>null</code> if the file is not already in the cache.
37      */
38     public synchronized Instant put(Path path) {
39         return publishedFiles.put(path, Instant.now());
40     }
41
42     /**
43      * Removes a file from the cache.
44      *
45      * @param localFileName name of the file to remove.
46      */
47     public synchronized void remove(Path localFileName) {
48         publishedFiles.remove(localFileName);
49     }
50
51     /**
52      * Removes files 24 hours older than the given instant.
53      *
54      * @param now the instant will determine which files that will be purged.
55      */
56     public synchronized void purge(Instant now) {
57         for (Iterator<Map.Entry<Path, Instant>> it = publishedFiles.entrySet().iterator(); it.hasNext();) {
58             Map.Entry<Path, Instant> pair = it.next();
59             if (isCachedPublishedFileOutdated(now, pair.getValue())) {
60                 it.remove();
61             }
62         }
63     }
64
65     public synchronized int size() {
66         return publishedFiles.size();
67     }
68
69     private static boolean isCachedPublishedFileOutdated(Instant now, Instant then) {
70         final int timeToKeepInfoInSeconds = 60 * 60 * 24;
71         return now.getEpochSecond() - then.getEpochSecond() > timeToKeepInfoInSeconds;
72     }
73 }