code cleanup and formatting
[meviz.git] / src / main / java / eu / svjatoslav / meviz / htmlindexer / metadata / fileTypes / AbstractFile.java
1 package eu.svjatoslav.meviz.htmlindexer.metadata.fileTypes;
2
3 import eu.svjatoslav.commons.file.FilePathParser;
4
5 import java.io.File;
6 import java.io.IOException;
7 import java.io.Serializable;
8
9 public abstract class AbstractFile implements Serializable {
10
11     private static final long serialVersionUID = -2547388204667088033L;
12
13     /**
14      * File name relative to the immediate parent directory.
15      */
16     public final String fileName;
17
18     /**
19      * File length in bytes.
20      */
21     private long fileLength = -1;
22
23     private transient boolean metaInfoVerified;
24
25     public AbstractFile(final File parentDirectory, final String fileName)
26             throws Exception {
27         this.fileName = fileName;
28         ensureFileMetainfoIsUpToDate(parentDirectory);
29     }
30
31     /**
32      * @return <code>true</code> if file metadata was updated.
33      */
34     public boolean ensureFileMetainfoIsUpToDate(final File parentDirectory)
35             throws Exception {
36         if (!isMetainfoUpToDate(parentDirectory)) {
37             fileLength = getFile(parentDirectory).length();
38             updateFileMetainfo(parentDirectory);
39             metaInfoVerified = true;
40             return true;
41         }
42         return false;
43     }
44
45     public boolean fileExists(final File parentDirectory) {
46         return getFile(parentDirectory).exists();
47     }
48
49     public File getFile(final File parentDirectory) {
50         return new File(parentDirectory.getAbsolutePath(), fileName);
51     }
52
53     public String getFileExtension() {
54         return FilePathParser.getFileExtension(fileName);
55     }
56
57     public long getFileLength() {
58         return fileLength;
59     }
60
61     private boolean isMetainfoUpToDate(final java.io.File parentDirectory)
62             throws IOException {
63
64         if (metaInfoVerified)
65             return true;
66
67         final File file = getFile(parentDirectory);
68
69         // first check that file exists at all
70         if (!file.exists()) {
71             System.out.println(file);
72             throw new RuntimeException("Picture file by name \"" + fileName
73                     + "\" does not exist in the parent directory \""
74                     + parentDirectory.getAbsolutePath() + "\"");
75         }
76
77         // check that file length is the same as before
78         if (file.length() != fileLength)
79             return false;
80
81         metaInfoVerified = true;
82         return true;
83     }
84
85     public boolean isMetaInfoVerified() {
86         return metaInfoVerified;
87     }
88
89     protected abstract void updateFileMetainfo(final File parentDirectory)
90             throws Exception;
91
92 }