Statistics
| Revision:

root / tmp / org.txm.groovy.core / src / groovy / org / txm / importer / xtz / XTZPager.groovy @ 812

History | View | Annotate | Download (16.4 kB)

1
package org.txm.importer.xtz
2

    
3
import java.io.File;
4
import java.util.ArrayList;
5

    
6
import org.txm.objects.BaseParameters
7
import org.w3c.dom.Element
8
import org.txm.importer.*
9
import org.txm.stat.utils.ConsoleProgressBar
10
import org.txm.utils.BundleUtils;
11
import org.txm.utils.io.FileCopy;
12
import org.txm.utils.i18n.*
13

    
14
import javax.xml.stream.*
15

    
16
class XTZPager extends Pager {
17

    
18
        BaseParameters params;
19

    
20
        Element corpusElem;
21
        String lang;
22
        String page_element;
23
        String wordTag;
24
        int wordsPerPage;
25

    
26
        File cssDirectory, jsDirectory, imagesDirectory;
27

    
28
        public XTZPager(ImportModule module) {
29
                super(module, "default");
30

    
31
                params = module.getParameters()
32

    
33
                corpusElem = params.corpora.get(corpusname);
34
                lang = corpusElem.getAttribute("lang");
35
                wordsPerPage = params.getWordsPerPage("default")
36
                page_element = params.getPageElement("default")
37
                wordTag = module.getParameters().getWordElement().getTextContent()
38

    
39
                cssDirectory = new File(module.getSourceDirectory(), "css")
40
                jsDirectory = new File(module.getSourceDirectory(), "js")
41
                imagesDirectory = new File(module.getSourceDirectory(), "images")
42
        }
43

    
44
        public void process(ArrayList<File> files) {
45
                super.process(files);
46
                
47
                if (files == null) {
48
                        files = inputDirectory.listFiles();
49
                        if (files != null) Collections.sort(files);
50
                }
51
                
52
                if (!doDefaultEditionStep()) return;
53
                if (!doFacsEditionStep()) return;
54
                if (!doPostEditionXSLStep()) return;
55

    
56
                isSuccessFul = true;
57
                println ""
58
        }
59

    
60
        public boolean doDefaultEditionStep() {
61
                
62
                boolean build_edition = module.getParameters().getDoEdition("default")
63
                if (!build_edition) {
64
                        return true;
65
                }
66
                
67
                def second = 0
68

    
69
                println "-- Building 'default' edition of  ${files.size()} texts..."
70

    
71
                def css = ["css/txm.css", "css/${corpusname}.css"] // default CSS inclusion
72

    
73
                // scan existing css files that must be declared in each HTML page
74
                if (cssDirectory.exists()) {
75
                        def cssFiles = cssDirectory.listFiles();
76
                        if (cssFiles != null)
77
                                for (File cssFile : cssFiles) {
78
                                        if (cssFile.isFile() && !cssFile.isHidden() && cssFile.getName().endsWith(".css"))
79
                                                css << "css/"+cssFile.getName();
80
                                }
81
                }
82
                ConsoleProgressBar cpb = new ConsoleProgressBar(files.size())
83
                for (File txmFile : files) {
84
                        cpb.tick()
85
                        String textname = txmFile.getName();
86
                        int i = textname.lastIndexOf(".");
87
                        if (i > 0) textname = textname.substring(0, i);
88

    
89
                        File firstHTMLPageFile = new File(outputDirectory, textname+"_1.html");
90
                        if (firstHTMLPageFile.exists() && firstHTMLPageFile.lastModified() >= txmFile.lastModified()) continue;
91

    
92
                        List<String> NoSpaceBefore = LangFormater.getNoSpaceBefore(lang);
93
                        List<String> NoSpaceAfter = LangFormater.getNoSpaceAfter(lang);
94

    
95
                        Element texts = params.getTextsElement(corpusElem);
96
                        Element text = params.getTextElement(texts, textname);
97
                        if (text == null) { // just in case
98
                                text = params.addText(corpusElem, textname, txmFile)
99
                        }
100
                        def ed = new XTZDefaultPagerStep(this, txmFile, textname, NoSpaceBefore, NoSpaceAfter, css);
101
                        Element edition = params.getEditionElement(text, "default");
102
                        if (edition == null) {
103
                                edition = params.addEdition(text, "default", outputDirectory.getAbsolutePath(), "html");
104
                        } else { // remove existing pages if any
105
                                def children = edition.getChildNodes();
106
                                while (children.getLength() > 0 ) {
107
                                        edition.removeChild(children.item(0))
108
                                }
109
                        }
110

    
111
                        for (i = 0 ; i < ed.getPageFiles().size();) {
112
                                File f = ed.getPageFiles().get(i);
113
                                String wordid = ed.getIdx().get(i);
114
                                params.addPage(edition, ""+(++i), wordid);
115
                        }
116
                }
117
                
118
                // copy default TXM css file in the "facs" edition directory
119
                File csshtmlDirectory = new File(outputDirectory, "css")
120
                csshtmlDirectory.mkdirs()
121
                BundleUtils.copyFiles("org.txm.core", "res", "org/txm/css", "txm.css", csshtmlDirectory);
122
                
123
                // copy CSS files in the "default" edition directory
124
                if (cssDirectory.exists()) {
125
                        FileCopy.copyFiles(cssDirectory, csshtmlDirectory)
126
                }
127
                if (jsDirectory.exists()) {
128
                        File jshtmlDirectory = new File(outputDirectory, "js")
129
                        FileCopy.copyFiles(jsDirectory, jshtmlDirectory)
130
                }
131
                if (imagesDirectory.exists()) {
132
                        File imageshtmlDirectory = new File(outputDirectory, "images")
133
                        FileCopy.copyFiles(imagesDirectory, imageshtmlDirectory)
134
                }
135

    
136
                // save changes
137
                println ""
138
                return true;
139
        }
140

    
141
        public boolean doFacsEditionStep() {
142

    
143
                boolean mustBuildFacsEdition = module.getParameters().getDoFacsEdition();
144
                if (!mustBuildFacsEdition) return true;
145
                
146
                String imageDirectoryPath = module.getParameters().getFacsEditionImageDirectory().trim();
147
                File imageDirectory = new File(imageDirectoryPath);
148
                if (!imageDirectoryPath.startsWith("http") && imageDirectoryPath.length()== 0 && !imageDirectory.exists() && !imageDirectory.isDirectory()) {
149
                        imageDirectory = null;
150
                }
151

    
152
                def second = 0
153

    
154
                println "-- Building 'facs' edition of ${files.size()} texts..."
155
                File newEditionDirectory = new File(htmlDirectory, "facs");
156
                newEditionDirectory.mkdir();
157

    
158
                // declare the "facs" edition
159
                Element editionDefinitionElement = params.getEditionDefinitionElement(corpusElem, "facs");
160
                if (editionDefinitionElement == null) {
161
                        editionDefinitionElement = params.addEditionDefinition(corpusElem, "facs", "groovy", "XTZPager.groovy")
162
                }
163
                Element textsElement = params.getTextsElement(corpusElem)
164

    
165
                ConsoleProgressBar cpb = new ConsoleProgressBar(files.size())
166
                for (File txmFile : files) {
167
                        cpb.tick()
168
                        String txtname = txmFile.getName();
169
                        int i = txtname.lastIndexOf(".");
170
                        if (i > 0) txtname = txtname.substring(0, i);
171

    
172
                        File firstHTMLPageFile = new File(newEditionDirectory, txtname+"_1.html");
173
                        if (firstHTMLPageFile.exists() && firstHTMLPageFile.lastModified() >= txmFile.lastModified()) continue;
174

    
175
                        List<String> NoSpaceBefore = LangFormater.getNoSpaceBefore(lang);
176
                        List<String> NoSpaceAfter = LangFormater.getNoSpaceAfter(lang);
177

    
178
                        // the text should already exists
179
                        Element text = params.getTextElement(textsElement, txtname)
180
                        if (text == null) { // just in case
181
                                text = params.addText(corpusElem, txtname, txmFile)
182
                        }
183
                        Element edition = params.getEditionElement(text, "facs");
184
                        if (edition == null) {
185
                                edition = params.addEdition(text, "facs", newEditionDirectory.getAbsolutePath(), "html");
186
                        } else {
187
                                def children = edition.getChildNodes();
188
                                while (children.getLength() > 0 ) {
189
                                        edition.removeChild(children.item(0))
190
                                }
191
                        }
192

    
193
                        try {
194
                                def ed = new XTZFacsPagerStep(txmFile, newEditionDirectory, imageDirectory, txtname, corpusname, "pb", "facs", wordTag, debug);
195
                                if (!ed.process()) {
196
                                        println "Fail to build edition for text: $txmFile"
197
                                        continue;
198
                                }
199

    
200
                                
201
                                def pages = ed.getPageFiles()
202
                                for (i = 0 ; i < pages.size();) {
203
                                        File f = pages[i][0];
204
                                        String wordid = pages[i][1]
205
                                        //TODO replace '""+(++i)' with something that fetch/findout the page 'name'
206
                                        // TODO or move the Edition and Page corpus declaration in the XTZDefaultPagerStep 
207
                                        params.addPage(edition, ""+(++i), wordid);
208
                                        //println "add facs page: $f $wordid"
209
                                }
210
                        } catch (Exception e) {
211
                                println "Error while processing $txmFile text: "+e
212
                                e.printStackTrace();
213
                                return false;
214
                        }
215
                }
216

    
217
                if (!imageDirectoryPath.startsWith("http") && imageDirectory != null) { // copy files only if local
218
                        File editionImagesDirectory = new File(newEditionDirectory, "res/images/"+corpusname+"/facs");
219
                        editionImagesDirectory.mkdirs();
220
                        FileCopy.copyFiles(imageDirectory, editionImagesDirectory);
221
                }
222
                
223
                // copy SimpleViewer files in the "facs" edition directory
224
                File jshtmlDirectory = new File(newEditionDirectory, "js")
225
                jshtmlDirectory.mkdirs()
226
                BundleUtils.copyFiles("org.txm.core", "res", "org/txm/js", "viewer", jshtmlDirectory);
227
                BundleUtils.copyFiles("org.txm.core", "res", "org/txm/", "images", newEditionDirectory);
228
                
229
                // copy default TXM css file in the "facs" edition directory
230
                File csshtmlDirectory = new File(newEditionDirectory, "css")
231
                csshtmlDirectory.mkdirs()
232
                BundleUtils.copyFiles("org.txm.core", "res", "org/txm/css", "txm.css", csshtmlDirectory);
233
                
234
                // copy CSS/JS/Images sources files in the "facs" edition directory
235
                if (cssDirectory.exists()) {
236
                        FileCopy.copyFiles(cssDirectory, csshtmlDirectory)
237
                }
238
                if (jsDirectory.exists()) {
239
                        FileCopy.copyFiles(jsDirectory, jshtmlDirectory)
240
                }
241
                if (imagesDirectory.exists()) {
242
                        File imageshtmlDirectory = new File(newEditionDirectory, "images")
243
                        FileCopy.copyFiles(imagesDirectory, imageshtmlDirectory)
244
                }
245
                
246
                Element editionsElement = params.getEditionsElement(corpusElem);
247
                editionsElement.setAttribute("default","default,facs");
248

    
249
                println ""
250
                return true;
251
        }
252

    
253
        /**
254
         * read from $bindir/txm and write the result in $bindir/txm
255
         *
256
         */
257
        public boolean doPostEditionXSLStep() {
258

    
259
                File xslDirectory = new File(module.getSourceDirectory(), "xsl/4-edition")
260
                if (xslDirectory.exists()) {
261

    
262
                        // prepare XSL parameters
263
                        def xslParams = module.getParameters().getXsltParams(corpusElem);
264
                        String s = module.getParameters().getWordsPerPage("default");
265
                        if (s != null && s.length() > 0)
266

    
267
                        // shared XSL parameters
268
                        xslParams["number-words-per-page"] = Integer.parseInt(s);
269
                        xslParams["pagination-element"] = module.getParameters().getPageElement("default")
270
                        xslParams["import-xml-path"] = module.getParameters().paramFile.toURI().toString()
271
                        //println "XSL PARAMS: "+xslParams
272

    
273
                        def xslFiles = xslDirectory.listFiles()
274
                        xslFiles.sort()
275
                        def editionsCreated = [:]
276
                        for (File xslFile : xslFiles) {
277
                                if (xslFile.isDirectory() || xslFile.isHidden() || !xslFile.getName().endsWith(".xsl")) continue;
278
                                if (!xslFile.getName().matches("[1-9]-.+")) continue;
279
                                
280
                                String xslName = xslFile.getName().substring(2); // remove the "1-", "2-", etc.
281
                                int idx2 = xslName.indexOf(".")
282
                                if (idx2 > 0) xslName = xslName.substring(0, idx2)
283
                                else {
284
                                        println "$xslFile is not a '.xsl' file"
285
                                        continue;
286
                                }
287
                                int idx3 = xslName.indexOf("-")
288
                                if (idx3 < 0) {
289
                                        println "$xslFile file does not follow the '{Number}-{editionName}-{step}.xsl' name pattern"
290
                                        continue;
291
                                }
292
                                String pagerStep = xslName.substring(idx3 + 1);
293
                                String editionName = xslName.substring(0, idx3);
294

    
295
                                int idx = editionName.indexOf(".")
296
                                if (idx > 0) editionName = editionName.substring(0, idx);
297
                                println "-- Building '$editionName' XSL edition with step '$pagerStep'..."
298

    
299
                                File newEditionDirectory = new File(htmlDirectory, editionName);
300
                                xslParams["output-directory"] = newEditionDirectory.toURI().toString()
301

    
302
                                if (editionsCreated[editionName] == null) { // first XSL, replace an edition
303
                                        editionsCreated[editionName] = xslFile
304
                                        //if (!importModule.isUpdatingCorpus()) {
305
                                        //TODO: optimisation if update is enable,
306
                                        newEditionDirectory.deleteDir(); // delete previous edition if any
307
                                        //}
308
                                        newEditionDirectory.mkdir()
309

    
310
                                        boolean deleteOutputFiles = "pager" == pagerStep;
311
                                        if (ApplyXsl2.processImportSources(xslFile, inputDirectory, newEditionDirectory, xslParams, deleteOutputFiles)) {
312
                                                println ""
313
                                        } else {
314
                                                reason = "Fail to apply edition XSL: $xslFile"
315
                                                return false;
316
                                        }
317

    
318
                                        // copy CSS files in the newEditionDirector edition directory
319
                                        if (cssDirectory.exists()) {
320
                                                File csshtmlDirectory = new File(newEditionDirectory, "css")
321
                                                FileCopy.copyFiles(cssDirectory, csshtmlDirectory)
322
                                        }
323
                                        if (jsDirectory.exists()) {
324
                                                File jshtmlDirectory = new File(newEditionDirectory, "js")
325
                                                FileCopy.copyFiles(jsDirectory, jshtmlDirectory)
326
                                        }
327
                                        if (imagesDirectory.exists()) {
328
                                                File imageshtmlDirectory = new File(newEditionDirectory, "images")
329
                                                FileCopy.copyFiles(imagesDirectory, imageshtmlDirectory)
330
                                        }
331
                                } else { // N+1 XSL working with HTML files
332
                                        def htmlFiles = newEditionDirectory.listFiles()
333
                                        htmlFiles.sort()
334

    
335
                                        if (ApplyXsl2.processImportSources(xslFile, htmlFiles, xslParams)) {
336
                                                if ("pager".equals(pagerStep)) {
337
                                                        // delete the one page HTML files only if the XSL step is "pager"
338
                                                        for (File f : htmlFiles) f.delete();
339
                                                }
340
                                                //        println ""
341
                                        } else {
342
                                                reason = "Fail to apply edition XSL: $xslFile"
343
                                                return false;
344
                                        }
345
                                }
346
                        }
347

    
348
                        // UPDATE import.xml: for each XML-TXM file, we must retrieve the first word ID from the XSL output files
349
                        //println "retrieve word ids from $inputDirectory"
350
                        println "-- Fetching page word IDs..."
351
                        ConsoleProgressBar cpb = new ConsoleProgressBar(editionsCreated.keySet().size())
352
                        for (String editionName : editionsCreated.keySet()) {
353
                                cpb.tick()
354
                                //ensure edition definition is declared
355
                                def editionsElement = params.getEditionsElement(corpusElem)
356
                                def e = params.getEditionDefinitionElement(editionsElement, editionName);
357
                                if (e == null) {
358
                                        params.addEditionDefinition(corpusElem, editionName, "xsl", editionsCreated[editionName].toString());
359
                                }
360

    
361
                                File newEditionDirectory = new File(htmlDirectory, editionName);
362
                                File xslFile = editionsCreated[editionName]
363
                                for (File txmFile : inputDirectory.listFiles()) {
364
                                        if (txmFile.isDirectory()) continue;
365
                                        String textName = txmFile.getName()
366
                                        int idx4 = textName.indexOf(".")
367
                                        if (idx4 > 0) textName = textName.substring(0, idx4);
368

    
369
                                        getFirstWordIDs(textName, editionName, newEditionDirectory, xslFile);
370
                                }
371
                        }
372
                        println ""
373
                }
374
                return true;
375
        }
376

    
377
        private void getFirstWordIDs(String textName, String editionName, File newEditionDirectory, File xslFile) {
378
                //                println "call getFirstWordIDs textName=$textName editionName=$editionName dir=$newEditionDirectory xsl=$xslFile"
379
                Element textsElement = params.getTextsElement(corpusElem)
380
                Element textElement = params.getTextElement(textsElement, textName)
381
                if (textElement == null) { // just in case
382
                        textElement = params.addText(corpusElem, textName, new File(inputDirectory, textName+".xml"))
383
                }
384

    
385
                Element editionElement = params.getEditionElement(textElement, editionName);
386
                if (editionElement == null) { // the edition does not exist, declare it
387
                        editionElement = params.addEdition(textElement, editionName, newEditionDirectory.getAbsolutePath(), "html");
388
                } else { // the edition already exists, remove pages from the existing edition
389
                        def children = editionElement.getChildNodes();
390
                        while (children.getLength() > 0 ) {
391
                                editionElement.removeChild(children.item(0))
392
                        }
393
                }
394
                editionElement.setAttribute("mode", "xsl");
395
                editionElement.setAttribute("script", xslFile.getName());
396

    
397
                LinkedHashMap<File, String> words = new LinkedHashMap<File, String>()
398
                def files = []
399
                newEditionDirectory.eachFile() {it -> if (it.isFile()) files << it}
400

    
401
                files.sort() { f1, f2 ->
402
                        String s1 = f1.getName()
403
                        String s2 = f2.getName()
404
                        int n1 = Integer.parseInt(s1.substring(s1.lastIndexOf("_")+1, s1.lastIndexOf(".")))
405
                        int n2 = Integer.parseInt(s2.substring(s2.lastIndexOf("_")+1, s2.lastIndexOf(".")))
406
                        return n1 - n2;
407
                }
408

    
409
                for (File f : files) {
410
                        String pagename = f.getName();
411
                        if (pagename.startsWith(textName+"_")) { // this is a page
412
                                String firstWordID = getMetaContent(f);
413
                                pagename = pagename.substring((textName+"_").length(), pagename.indexOf(".html")) // !!!!
414
                                params.addPage(editionElement, pagename, firstWordID)
415
                        }
416
                }
417
        }
418

    
419
        public static String getMetaContent(File f) {
420
                def inputData = f.toURI().toURL().openStream();
421
                def factory = XMLInputFactory.newInstance();
422
                factory.setProperty("javax.xml.stream.supportDTD", false); // ignore the DTD declared in doctype
423

    
424
                def parser = factory.createXMLStreamReader(inputData);
425
                String META = "meta"
426
                String BODY = "body"
427
                String NAME = "name"
428
                String DESCRIPTION = "txm:first-word-id"
429
                String CONTENT = "content"
430

    
431
                String content = "";
432
                String desc = "";
433

    
434
                for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
435
                        if (event == XMLStreamConstants.START_ELEMENT) { // start elem
436

    
437
                                if (META.equals(parser.getLocalName())) { // ana elem
438
                                        desc = "";
439
                                        // fetch attribute values
440
                                        for (int i = 0 ; i < parser.getAttributeCount(); i++) { // scan attributes
441
                                                if (NAME.equals(parser.getAttributeLocalName(i))) { // found @name
442
                                                        desc = parser.getAttributeValue(i)
443
                                                } else if (CONTENT.equals(parser.getAttributeLocalName(i))) { // found @content
444
                                                        content = parser.getAttributeValue(i)
445
                                                }
446
                                        }
447
                                        if (DESCRIPTION.equals(desc)) { // stop now
448
                                                break;
449
                                        }
450
                                } else if (BODY.equals(parser.getLocalName())) { // no need to go further, meta@name="description" not found :(
451
                                        content = "";
452
                                        break;
453
                                }
454
                        }
455
                }
456
                parser.close()
457

    
458
                return content;
459
        }
460

    
461
        public static void main(def args) {
462
                println "RESULT: "+getMetaContent(new File("/home/mdecorde/TXM/corpora/QGRAALXTZ/HTML/QGRAALXTZ/default", "qgraal_cm_test201510_page_160_2.html"))
463
        }
464
}