source: josm/trunk/src/org/openstreetmap/josm/io/CacheCustomContent.java@ 11795

Last change on this file since 11795 was 11510, checked in by Don-vip, 7 years ago

sonar - fb-contrib:ACEM_ABSTRACT_CLASS_EMPTY_METHODS

  • Property svn:eol-style set to native
File size: 6.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import java.io.BufferedInputStream;
5import java.io.BufferedOutputStream;
6import java.io.File;
7import java.io.FileInputStream;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.nio.charset.StandardCharsets;
11import java.util.concurrent.TimeUnit;
12
13import org.openstreetmap.josm.Main;
14
15/**
16 * Use this class if you want to cache and store a single file that gets updated regularly.
17 * Unless you flush() it will be kept in memory. If you want to cache a lot of data and/or files, use CacheFiles.
18 * @author xeen
19 * @param <T> a {@link Throwable} that may be thrown during {@link #updateData()},
20 * use {@link RuntimeException} if no exception must be handled.
21 * @since 1450
22 */
23public abstract class CacheCustomContent<T extends Throwable> {
24
25 /** Update interval meaning an update is always needed */
26 public static final int INTERVAL_ALWAYS = -1;
27 /** Update interval meaning an update is needed each hour */
28 public static final int INTERVAL_HOURLY = (int) TimeUnit.HOURS.toSeconds(1);
29 /** Update interval meaning an update is needed each day */
30 public static final int INTERVAL_DAILY = (int) TimeUnit.DAYS.toSeconds(1);
31 /** Update interval meaning an update is needed each week */
32 public static final int INTERVAL_WEEKLY = (int) TimeUnit.DAYS.toSeconds(7);
33 /** Update interval meaning an update is needed each month */
34 public static final int INTERVAL_MONTHLY = (int) TimeUnit.DAYS.toSeconds(28);
35 /** Update interval meaning an update is never needed */
36 public static final int INTERVAL_NEVER = Integer.MAX_VALUE;
37
38 /**
39 * Where the data will be stored
40 */
41 private byte[] data;
42
43 /**
44 * The ident that identifies the stored file. Includes file-ending.
45 */
46 private final String ident;
47
48 /**
49 * The (file-)path where the data will be stored
50 */
51 private final File path;
52
53 /**
54 * How often to update the cached version
55 */
56 private final int updateInterval;
57
58 /**
59 * This function will be executed when an update is required. It has to be implemented by the
60 * inheriting class and should use a worker if it has a long wall time as the function is
61 * executed in the current thread.
62 * @return the data to cache
63 * @throws T a {@link Throwable}
64 */
65 protected abstract byte[] updateData() throws T;
66
67 /**
68 * Initializes the class. Note that all read data will be stored in memory until it is flushed
69 * by flushData().
70 * @param ident ident that identifies the stored file. Includes file-ending.
71 * @param updateInterval update interval in seconds. -1 means always
72 */
73 public CacheCustomContent(String ident, int updateInterval) {
74 this.ident = ident;
75 this.updateInterval = updateInterval;
76 this.path = new File(Main.pref.getCacheDirectory(), ident);
77 }
78
79 /**
80 * This function serves as a comfort hook to perform additional checks if the cache is valid
81 * @return True if the cached copy is still valid
82 */
83 protected boolean isCacheValid() {
84 return true;
85 }
86
87 private boolean needsUpdate() {
88 if (isOffline()) {
89 return false;
90 }
91 return Main.pref.getInteger("cache." + ident, 0) + updateInterval < TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
92 || !isCacheValid();
93 }
94
95 private boolean isOffline() {
96 try {
97 checkOfflineAccess();
98 return false;
99 } catch (OfflineAccessException e) {
100 Main.trace(e);
101 return true;
102 }
103 }
104
105 /**
106 * Ensures underlying resource is not accessed in offline mode.
107 * @throws OfflineAccessException if resource is accessed in offline mode
108 */
109 protected abstract void checkOfflineAccess();
110
111 /**
112 * Updates data if required
113 * @return Returns the data
114 * @throws T if an error occurs
115 */
116 public byte[] updateIfRequired() throws T {
117 if (needsUpdate())
118 return updateForce();
119 return getData();
120 }
121
122 /**
123 * Updates data if required
124 * @return Returns the data as string
125 * @throws T if an error occurs
126 */
127 public String updateIfRequiredString() throws T {
128 if (needsUpdate())
129 return updateForceString();
130 return getDataString();
131 }
132
133 /**
134 * Executes an update regardless of updateInterval
135 * @return Returns the data
136 * @throws T if an error occurs
137 */
138 public byte[] updateForce() throws T {
139 this.data = updateData();
140 saveToDisk();
141 Main.pref.putInteger("cache." + ident, (int) (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())));
142 return data;
143 }
144
145 /**
146 * Executes an update regardless of updateInterval
147 * @return Returns the data as String
148 * @throws T if an error occurs
149 */
150 public String updateForceString() throws T {
151 updateForce();
152 return new String(data, StandardCharsets.UTF_8);
153 }
154
155 /**
156 * Returns the data without performing any updates
157 * @return the data
158 * @throws T if an error occurs
159 */
160 public byte[] getData() throws T {
161 if (data == null) {
162 loadFromDisk();
163 }
164 return data;
165 }
166
167 /**
168 * Returns the data without performing any updates
169 * @return the data as String
170 * @throws T if an error occurs
171 */
172 public String getDataString() throws T {
173 byte[] array = getData();
174 if (array == null) {
175 return null;
176 }
177 return new String(array, StandardCharsets.UTF_8);
178 }
179
180 /**
181 * Tries to load the data using the given ident from disk. If this fails, data will be updated, unless run in offline mode
182 * @throws T a {@link Throwable}
183 */
184 private void loadFromDisk() throws T {
185 try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(path))) {
186 this.data = new byte[input.available()];
187 if (input.read(this.data) < this.data.length) {
188 Main.error("Failed to read expected contents from "+path);
189 }
190 } catch (IOException e) {
191 Main.trace(e);
192 if (!isOffline()) {
193 this.data = updateForce();
194 }
195 }
196 }
197
198 /**
199 * Stores the data to disk
200 */
201 private void saveToDisk() {
202 try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(path))) {
203 output.write(this.data);
204 output.flush();
205 } catch (IOException e) {
206 Main.error(e);
207 }
208 }
209
210 /**
211 * Flushes the data from memory. Class automatically reloads it from disk or updateData() if required
212 */
213 public void flushData() {
214 data = null;
215 }
216}
Note: See TracBrowser for help on using the repository browser.