1 /*
2 * Copyright (C) 2012 Alberto Irurueta Carro (alberto@irurueta.com)
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16 package com.irurueta.geometry.io;
17
18 import java.io.Closeable;
19 import java.io.File;
20 import java.io.IOException;
21 import java.nio.BufferUnderflowException;
22 import java.nio.channels.FileChannel;
23
24 /**
25 * Abstract class defining the interface for file loaders.
26 * Specific implementations must be done for each file format to be supported.
27 */
28 public abstract class Loader implements Closeable {
29
30 /**
31 * Default limit of bytes to keep mapped in memory.
32 */
33 public static final long DEFAULT_FILE_SIZE_LIMIT_TO_KEEP_IN_MEMORY = 50000000;
34
35 /**
36 * Instance in charge of reading data from file.
37 */
38 protected AbstractFileReaderAndWriter reader;
39
40 /**
41 * Boolean indicating that this instance is locked because decoding is being
42 * done.
43 */
44 protected boolean locked;
45
46 /**
47 * Listener in charge of notifying when the decoding starts, ends or
48 * progress events.
49 */
50 protected LoaderListener listener;
51
52 /**
53 * File to be read.
54 */
55 protected File file;
56
57 /**
58 * Limit of bytes to keep mapped in memory. If provided file exceeds this
59 * value, then it is not mapped into memory.
60 */
61 private long fileSizeLimitToKeepInMemory;
62
63 /**
64 * Default Constructor.
65 */
66 protected Loader() {
67 fileSizeLimitToKeepInMemory = DEFAULT_FILE_SIZE_LIMIT_TO_KEEP_IN_MEMORY;
68 reader = null;
69 locked = false;
70 listener = null;
71 }
72
73 /**
74 * Constructor.
75 *
76 * @param f file to be read.
77 * @throws IOException raised if provided file does not exist or an I/O
78 * exception occurs.
79 */
80 protected Loader(final File f) throws IOException {
81 fileSizeLimitToKeepInMemory = DEFAULT_FILE_SIZE_LIMIT_TO_KEEP_IN_MEMORY;
82 file = f;
83 if (f.length() < fileSizeLimitToKeepInMemory) {
84 reader = new MappedFileReaderAndWriter(f, FileChannel.MapMode.READ_ONLY);
85 } else {
86 reader = new FileReaderAndWriter(f, FileChannel.MapMode.READ_ONLY);
87 }
88 locked = false;
89 listener = null;
90 }
91
92 /**
93 * Constructor.
94 *
95 * @param listener listener to notify start, end and progress events.
96 */
97 protected Loader(final LoaderListener listener) {
98 fileSizeLimitToKeepInMemory = DEFAULT_FILE_SIZE_LIMIT_TO_KEEP_IN_MEMORY;
99 reader = null;
100 locked = false;
101 this.listener = listener;
102 }
103
104 /**
105 * Constructor.
106 *
107 * @param f file to be read.
108 * @param listener listener to notify start, end and progress events.
109 * @throws IOException raised if provided file does not exist or an I/O
110 * exception occurs.
111 */
112 protected Loader(final File f, final LoaderListener listener) throws IOException {
113 fileSizeLimitToKeepInMemory = DEFAULT_FILE_SIZE_LIMIT_TO_KEEP_IN_MEMORY;
114 file = f;
115 if (f.length() < fileSizeLimitToKeepInMemory) {
116 reader = new MappedFileReaderAndWriter(f, FileChannel.MapMode.READ_ONLY);
117 } else {
118 reader = new FileReaderAndWriter(f, FileChannel.MapMode.READ_ONLY);
119 }
120 locked = false;
121 this.listener = listener;
122 }
123
124 /**
125 * Get maximum size (in bytes) to determine whether a file is completely
126 * cached in memory (if lower than maximum size), or if it is just streamed
127 * (if greater than maximum size).
128 *
129 * @return Maximum size to determine whether file is cached in memory or not.
130 */
131 public long getFileSizeLimitToKeepInMemory() {
132 return fileSizeLimitToKeepInMemory;
133 }
134
135 /**
136 * Sets maximum size (in bytes) to determine whether a file is completely
137 * cached in memory (if lower than maximum size), or if it is just streamed
138 * (if greater than maximum size).
139 *
140 * @param fileSizeLimitToKeepInMemory maximum size to determine whether file
141 * is cached in memory or not.
142 * @throws LockedException if loader is locked because it is currently
143 * processing a file.
144 */
145 public void setFileSizeLimitToKeepInMemory(final long fileSizeLimitToKeepInMemory) throws LockedException {
146 if (isLocked()) {
147 throw new LockedException();
148 }
149
150 this.fileSizeLimitToKeepInMemory = fileSizeLimitToKeepInMemory;
151 }
152
153 /**
154 * Indicates whether a file to be loaded has already been set.
155 *
156 * @return True if file has already been provided, false otherwise.
157 */
158 public boolean hasFile() {
159 return reader != null;
160 }
161
162 /**
163 * Sets file to be loaded.
164 *
165 * @param f file to be loaded.
166 * @throws LockedException raised if this instance is loaded because a file
167 * is already being loaded.
168 * @throws IOException raised if provided file does not exist or if an I/O
169 * exception occurs.
170 */
171 @SuppressWarnings("DuplicatedCode")
172 public void setFile(final File f) throws LockedException, IOException {
173 if (isLocked()) {
174 throw new LockedException();
175 }
176 file = f;
177
178 if (reader != null) {
179 // close previous file
180 reader.close();
181 }
182
183 if (f.length() < fileSizeLimitToKeepInMemory) {
184 reader = new MappedFileReaderAndWriter(f, FileChannel.MapMode.READ_ONLY);
185 } else {
186 reader = new FileReaderAndWriter(f, FileChannel.MapMode.READ_ONLY);
187 }
188 }
189
190 /**
191 * Closes file provided to this loader.
192 *
193 * @throws IOException if an I/O error occurs.
194 */
195 @Override
196 public void close() throws IOException {
197 if (reader != null) {
198 reader.close();
199 reader = null;
200 }
201 }
202
203 /**
204 * Determines whether this instance is locked.
205 * A loader remains locked while decoding of a file is being done.
206 * This instance will remain locked once the loading process starts until
207 * it finishes either successfully or not.
208 * While this instance remains locked no parameters can be changed,
209 * otherwise a LockedException will be raised.
210 *
211 * @return True if instance is locked, false otherwise.
212 */
213 public synchronized boolean isLocked() {
214 return locked;
215 }
216
217 /**
218 * Sets the lock value of this instance so that no parameters cannot be
219 * changed until this instance is unlocked.
220 *
221 * @param locked value that determines whether this instance is locked or
222 * not.
223 */
224 protected synchronized void setLocked(final boolean locked) {
225 this.locked = locked;
226 }
227
228 /**
229 * Runs a step of the loading process (started while this loader is
230 * locked) and releases the lock if the step fails, so that this loader
231 * can be reused after a corrupted or unreadable file.
232 * A premature end of data ({@link BufferUnderflowException}) is reported
233 * as a {@link LoaderException}, since it means that file is corrupted.
234 *
235 * @param operation loading step to be executed.
236 * @param <T> type of result returned by the loading step.
237 * @return result of the loading step.
238 * @throws IOException if an I/O error occurs.
239 * @throws LoaderException if file is corrupted or cannot be interpreted.
240 */
241 protected <T> T loadReleasingLockOnFailure(
242 final LoadOperation<T> operation)
243 throws IOException, LoaderException {
244 try {
245 return operation.run();
246 } catch (final BufferUnderflowException e) {
247 setLocked(false);
248 throw new LoaderException(e);
249 } catch (final IOException | LoaderException | RuntimeException e) {
250 setLocked(false);
251 throw e;
252 }
253 }
254
255 /**
256 * Reads a chunk of data while iterating a file and releases the lock of
257 * this loader if reading fails, so that this loader can be reused after a
258 * corrupted or unreadable file.
259 * A premature end of data ({@link BufferUnderflowException}) is reported
260 * as a {@link LoaderException}, since it means that file is corrupted.
261 *
262 * @param operation reading step to be executed.
263 * @return read chunk of data.
264 * @throws IOException if an I/O error occurs.
265 * @throws LoaderException if file is corrupted or cannot be
266 * interpreted.
267 * @throws NotAvailableException if no more data is available.
268 */
269 protected DataChunk readReleasingLockOnFailure(
270 final ReadOperation operation)
271 throws IOException, LoaderException, NotAvailableException {
272 try {
273 return operation.run();
274 } catch (final BufferUnderflowException e) {
275 setLocked(false);
276 throw new LoaderException(e);
277 } catch (final IOException | LoaderException
278 | NotAvailableException | RuntimeException e) {
279 setLocked(false);
280 throw e;
281 }
282 }
283
284 /**
285 * Step of the loading process executed while this loader is locked.
286 *
287 * @param <T> type of result returned by the loading step.
288 */
289 @FunctionalInterface
290 protected interface LoadOperation<T> {
291
292 /**
293 * Executes loading step.
294 *
295 * @return result of the loading step.
296 * @throws IOException if an I/O error occurs.
297 * @throws LoaderException if file is corrupted or cannot be
298 * interpreted.
299 */
300 T run() throws IOException, LoaderException;
301 }
302
303 /**
304 * Reads a chunk of data while iterating a file.
305 */
306 @FunctionalInterface
307 protected interface ReadOperation {
308
309 /**
310 * Reads a chunk of data.
311 *
312 * @return read chunk of data.
313 * @throws IOException if an I/O error occurs.
314 * @throws LoaderException if file is corrupted or cannot be
315 * interpreted.
316 * @throws NotAvailableException if no more data is available.
317 */
318 DataChunk run()
319 throws IOException, LoaderException, NotAvailableException;
320 }
321
322 /**
323 * Returns listener of this instance.
324 * A listener notifies of start, end and progress change events.
325 *
326 * @return listener of this instance.
327 */
328 public LoaderListener getListener() {
329 return listener;
330 }
331
332 /**
333 * Sets listener of this instance.
334 * A listener notifies of start, end and progress change events.
335 *
336 * @param listener listener of this instance.
337 * @throws LockedException Raised if this instance is already locked.
338 */
339 public void setListener(final LoaderListener listener) throws LockedException {
340 if (isLocked()) {
341 throw new LockedException();
342 }
343 this.listener = listener;
344 }
345
346 /**
347 * Determines whether enough parameters have been set so that the loading
348 * process can start.
349 *
350 * @return True if this instance is ready to start loading a file, false
351 * otherwise.
352 */
353 public abstract boolean isReady();
354
355 /**
356 * Returns mesh format this instance is capable of loading.
357 *
358 * @return Mesh format.
359 */
360 public abstract MeshFormat getMeshFormat();
361
362 /**
363 * Determines if provided file is a valid file that can be read by this
364 * loader.
365 *
366 * @return true if file is valid, false otherwise.
367 * @throws LockedException raised if this instance is already locked.
368 * @throws IOException if an I/O error occurs.
369 */
370 public abstract boolean isValidFile() throws LockedException, IOException;
371
372 /**
373 * Starts the loading process of provided file.
374 * This method returns a LoaderIterator to start the iterative process to
375 * load a file in small chunks of data.
376 *
377 * @return a loader iterator to read the file in a step-by-step process.
378 * @throws LockedException raised if this instance is already locked.
379 * @throws NotReadyException raised if this instance is not yet ready.
380 * @throws IOException if an I/O error occurs.
381 * @throws LoaderException if file is corrupted or cannot be interpreted.
382 */
383 public abstract LoaderIterator load() throws LockedException, NotReadyException, IOException, LoaderException;
384 }