source: other-projects/the-macronizer/trunk/src/java/monogram/plugin/PluginDOCX.java@ 35725

Last change on this file since 35725 was 35719, checked in by cstephen, 2 years ago

Add support for JSON response to direct input queries. Cleanup other components.

File size: 2.4 KB
Line 
1/*
2 * To change this template, choose Tools | Templates
3 * and open the template in the editor.
4 */
5
6package monogram.plugin;
7
8import java.io.File;
9import java.io.IOException;
10import java.util.UUID;
11import org.fuin.utils4j.Utils4J;
12import monogram.restorer.XMLRestorer;
13import util.FileUtil;
14
15/**
16 *
17 * @author OEM
18 */
19public class PluginDOCX implements Plugin {
20
21 private File tmpdir;
22
23 public PluginDOCX(File tmpdir) {
24 this.tmpdir = tmpdir;
25 }
26
27 public File run(PluginConfiguration configuration) throws Exception {
28 //Create a directory to store the unzipped file.
29 File unzipDir = createTmpDirectoryInTmp();
30 //Unzip the file in the directory.
31 Utils4J.unzip(configuration.getFile(), unzipDir);
32
33 //Restore the document.xml file.
34 File documentIn = new File(unzipDir, "word" + File.separator + "document.xml");
35 File documentOut = new File(unzipDir, "word" + File.separator + "mi-tmp-document.xml");
36 XMLRestorer restorer = new XMLRestorer();
37
38 restorer.restore
39 (
40 documentIn,
41 "utf-8",
42 documentOut,
43 configuration.getPreserveExistingMacrons(),
44 configuration.getMarkupChangedWords()
45 );
46
47 //Delete the old document.xml and rename the restored document.
48 documentIn.delete();
49 documentOut.renameTo(new File(unzipDir.getCanonicalPath() + File.separator + "word" + File.separator + "document.xml"));
50
51 //Create a file to store the zipped file.
52 File zipFile = File.createTempFile("mi-tmp-", configuration.getFileType(), tmpdir);
53 //Zip the file.
54 Utils4J.zipDir(unzipDir, null, zipFile);
55 //Delete zip directory.
56 if (unzipDir.getName().startsWith("mi-tmp-")) {
57 FileUtil.deleteFile(unzipDir);
58 }
59 return zipFile;
60 }
61
62 private File createTmpDirectoryInTmp() throws IOException {
63 final int maxAttempts = 10;
64 int attempt = 0;
65 do {
66 String random = UUID.randomUUID().toString();
67 File dir = new File(tmpdir + File.separator + "mi-tmp-" + random);
68 if (! dir.exists() && dir.mkdir()) {
69 System.out.println("PluginDOCX::createTmpDirectoryInTmp(): " + dir.getCanonicalPath());
70 return dir;
71 }
72 } while (++attempt < maxAttempts);
73 throw new IOException("Cound not create temp directory.");
74 }
75}
Note: See TracBrowser for help on using the repository browser.