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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package Torello.JavaDoc.SyntaxHiLite;

import Torello.Java.FileNode;
import Torello.Java.StrPrint;
import Torello.Java.FileRW;
import Torello.Java.StorageWriter;

import Torello.Java.Function.QuadFunction;

// Needed for a JavaDoc Comment
import Torello.Java.FileTransfer;

import Torello.JavaDoc.LinkJavaSource;

import java.util.TreeSet;

import java.io.File;

/**
 * A caching-system class that allows this tool to efficiently bypass calls to the server when
 * an exact-copy of the hilited source-code already exists inside the cache.
 */
public abstract class AbstractHashCodeHLC<NUMBER extends Number> implements HiLiteCache
{
    static final short NUM_DIRS = 5000;

    static
    {
        if ((NUM_DIRS < 1000) || (NUM_DIRS > 9999))
            throw new InternalError("Wrong Number of NUM_DIRS");
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Instance Fields
    // ********************************************************************************************
    // ********************************************************************************************


    /** This is nothing more than a "reified" Generic Type Parameter.  No more, no less. */
    public final Class<NUMBER> NUMBER_CLASS;

    /** This is, as the name clearly says, the Cache's Storae-Directory */
    public final String cacheSaveDirectory;


    // This is the list of Hash-Codes for all Code/HTML pairs stored in the cache.  This is the
    // exact data-structure that is referred to as the "Master Hash File"
    // 
    // This has also been recently converted to "Package-Private", instead of "Private"
    // See Above Note for Details.

    final TreeSet<NUMBER> hashCodes;


    // ********************************************************************************************
    // ********************************************************************************************
    // Constructor
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * This will load the hashCodes table to memory from the file-system directory identified
     * by {@code String}-Parameter {@code 'cacheSaveDirectory'}.  An exception shall be thrown
     * if this file is not found.
     *
     * @param cacheSaveDirectory This constructor presumes that this cache has been used and
     * visited before.  This directory name should point to your local-cache of the
     * {@code HiLite.ME} Server Code hilite past-operations.
     *
     * @throws CacheError This error will throw if the cache has not been instantiated, or
     * is corrupted.  If the specified directory does not exist, then this {@code Error} shall
     * also throw.  The chain-cause {@code Throwable} should be visible, and is included as the 
     * {@code Throwable.getCause()}.
     */
    @LinkJavaSource(handle="TreeSetMethods", name="checkCSD")
    @LinkJavaSource(handle="TreeSetMethods", name="checkTS")
    public AbstractHashCodeHLC(
            final String        cacheSaveDirectory,
            final Class<NUMBER> NUMBER_CLASS
        )
    {
        this.cacheSaveDirectory = TreeSetMethods.checkCSD(cacheSaveDirectory);
        this.hashCodes          = TreeSetMethods.checkTS(this.cacheSaveDirectory, NUMBER_CLASS);
        this.NUMBER_CLASS       = NUMBER_CLASS;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Static Builder Method
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * This will initialize a cache-file in the file-system directory identified by parameter
     * {@code String cacheSaveDirectory}.  If the directory specified does not exist, a
     * {@code CacheError} is thrown.  Any old cache files will be removed.  To attempt to
     * preserve old cache-files, call method {@code initializeOrRepair(String, StorageWriter)}
     * 
     * <BR /><BR /><B><I>OrClear:</I></B> If the directory structure provided to this
     * initialize method is not empty, the <SPAN STYLE="color: red;"><B><I>its entire contents
     * shall be erased by a call to </I></B></SPAN> (Below)
     * 
     * <DIV CLASS=LOC>{@code 
     * FileTransfer.deleteFilesRecursive
     *     (FileNode.createRoot(cacheSaveDirectory).loadTree(), sw);
     * }</DIV>
     * 
     * @param cacheSaveDirectory This constructor presumes that this cache has been used and
     * visited before.  This directory name should point to your local-cache of 
     * {@code HiLite.ME} Server Code hilite past-operations.
     * 
     * @param sw This receives log-writes from the call to
     * {@link FileTransfer#deleteFilesRecursive} which clears the files currently in the cache.
     * This parameter may be null, and if it is, output-text will be shunted.
     * 
     * @throws CacheError This exception will be throw if there are errors deleting any
     * old-cache files currently in the directory; or if there is any error creating the new
     * master hash-cache file.  The chain-cause {@code Throwable} should be visible, and is 
     * included as the {@code Throwable.getCause()}.
     */
    @LinkJavaSource(handle="TreeSetMethods", name="initializeOrClear")
    public static String initializeOrClear(String cacheSaveDirectory, StorageWriter sw)
    { return TreeSetMethods.initializeOrClear(cacheSaveDirectory, sw); }


    // ********************************************************************************************
    // ********************************************************************************************
    // Implemented Interface Methods
    // ********************************************************************************************
    // ********************************************************************************************


    public long totalSize()
    {
        return FileNode
            .createRoot(this.cacheSaveDirectory)
            .loadTree()
            .getDirTotalContentsSize();
    }

    public int totalNumber()
    {
        return FileNode
            .createRoot(this.cacheSaveDirectory)
            .loadTree()
            .count();
    }

    @LinkJavaSource(handle="TreeSetMethods", name="persistMasterHashToDisk")
    public void persistMasterHashToDisk() throws CacheError
    { TreeSetMethods.persistMasterHashToDisk(this.hashCodes, this.cacheSaveDirectory); }


    // ********************************************************************************************
    // ********************************************************************************************
    // Implemented Interface Methods: Check In and Out
    // ********************************************************************************************
    // ********************************************************************************************


    @LinkJavaSource(handle="CheckInOut", name="get")
    public String get(
            final String    sourceCodeAsString,
            final String    codeTypeParam,
            final boolean   includeLineNumbers,
            final byte      styleNum
        )
    {
        return CheckInOut.get(
            sourceCodeAsString,
            this.computeCacheKey
                (codeTypeParam, includeLineNumbers, styleNum, sourceCodeAsString),
            this
        );
    }

    @LinkJavaSource(handle="CheckInOut", name="checkIn")
    public void checkIn(
            final String    sourceCodeAsString,
            final String    hilitedCodeAsString, 
            final String    codeTypeParam,
            final boolean   includeLineNumbers,
            final byte      styleNum
        )
    {
        CheckInOut.checkIn(
            sourceCodeAsString,
            hilitedCodeAsString,
            this.computeCacheKey
                (codeTypeParam, includeLineNumbers, styleNum, sourceCodeAsString),
            this 
        );
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Abstract Methods
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Compute a Hash-Code
     * @param codeTypeParam         <EMBED CLASS='external-html' DATA-FILE-ID=HLC_PARAM_CODE_TP>
     * @param includeLineNumbers    <EMBED CLASS='external-html' DATA-FILE-ID=HLC_PARAM_INC_LINEN>
     * @param styleNum              <EMBED CLASS='external-html' DATA-FILE-ID=HLC_PARAM_STYLE_N>
     * @param sourceCodeAsString    <EMBED CLASS='external-html' DATA-FILE-ID=HLC_PARAM_SRC_ASSTR>
     * @return A key which may be used for saving a file to disk.
     */
    public abstract NUMBER computeCacheKey(
            final String    codeTypeParam,
            final boolean   includeLineNumbers,
            final byte      styleNum,
            final String    sourceCodeAsString
        );

    abstract String getSubDirName(NUMBER hashCode);


    // ********************************************************************************************
    // ********************************************************************************************
    // I forgot ...
    // ********************************************************************************************
    // ********************************************************************************************


    public static void main(String[] argv)
    {
        if (argv.length != 1)
        {
            System.out.println(
                "argv.length != 1\n" +
                "argv[0] must contain the Cache-Directory Name.\n"
            );

            System.exit(1);
        }

        java.io.File f = new java.io.File(argv[0]);

        if ((! f.exists()) || (! f.isDirectory()))
        {
            System.out.println(
                "argv[0] must contain the Cache-Directory Name.\n" +
                "Unfortunately: ((! f.exists()) || (! f.isDirectory()))\n"
            );

            System.exit(1);
        }

        initializeOrClear(argv[0], new StorageWriter());
    }
}