blob: 973e65fa847766d48e68b7bb8c71e04027fa1738 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
package cgeo.geocaching.files;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.utils.CancellableHandler;
import org.apache.commons.io.IOUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Date;
import java.util.concurrent.CancellationException;
public abstract class FileParser {
/**
* Parses caches from input stream.
*
* @param stream
* @param progressHandler
* for reporting parsing progress (in bytes read from input stream)
* @return collection of caches
* @throws IOException
* if the input stream can't be read
* @throws ParserException
* if the input stream contains data not matching the file format of the parser
*/
public abstract Collection<Geocache> parse(@NonNull final InputStream stream, @Nullable final CancellableHandler progressHandler) throws IOException, ParserException;
/**
* Convenience method for parsing a file.
*
* @param file
* @param progressHandler
* @return
* @throws IOException
* @throws ParserException
*/
public Collection<Geocache> parse(final File file, final CancellableHandler progressHandler) throws IOException, ParserException {
BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file));
try {
return parse(stream, progressHandler);
} finally {
IOUtils.closeQuietly(stream);
}
}
protected static StringBuilder readStream(@NonNull final InputStream is, @Nullable final CancellableHandler progressHandler) throws IOException {
final StringBuilder buffer = new StringBuilder();
ProgressInputStream progressInputStream = new ProgressInputStream(is);
final BufferedReader input = new BufferedReader(new InputStreamReader(progressInputStream, "UTF-8"));
try {
String line;
while ((line = input.readLine()) != null) {
buffer.append(line);
showProgressMessage(progressHandler, progressInputStream.getProgress());
}
return buffer;
} finally {
IOUtils.closeQuietly(input);
}
}
protected static void showProgressMessage(@Nullable final CancellableHandler handler, final int bytesRead) {
if (handler != null) {
if (handler.isCancelled()) {
throw new CancellationException();
}
handler.sendMessage(handler.obtainMessage(0, bytesRead, 0));
}
}
protected static void fixCache(Geocache cache) {
if (cache.getInventory() != null) {
cache.setInventoryItems(cache.getInventory().size());
} else {
cache.setInventoryItems(0);
}
final long time = new Date().getTime();
cache.setUpdated(time);
cache.setDetailedUpdate(time);
}
}
|