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

Last change on this file since 8855 was 8840, checked in by Don-vip, 9 years ago

sonar - squid:S3052 - Fields should not be initialized to default values

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