/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package monogram.plugin; import java.io.File; import java.io.IOException; import java.util.UUID; import org.fuin.utils4j.Utils4J; import monogram.restorer.XMLRestorer; import util.FileUtil; /** * * @author OEM */ public class PluginDOCX implements Plugin { private File tmpdir; public PluginDOCX(File tmpdir) { this.tmpdir = tmpdir; } public File run(PluginConfiguration configuration) throws Exception { //Create a directory to store the unzipped file. File unzipDir = createTmpDirectoryInTmp(); //Unzip the file in the directory. Utils4J.unzip(configuration.getFile(), unzipDir); //Restore the document.xml file. File documentIn = new File(unzipDir, "word" + File.separator + "document.xml"); File documentOut = new File(unzipDir, "word" + File.separator + "mi-tmp-document.xml"); XMLRestorer restorer = new XMLRestorer(); restorer.restore ( documentIn, "utf-8", documentOut, configuration.getPreserveExistingMacrons(), configuration.getMarkupChangedWords() ); //Delete the old document.xml and rename the restored document. documentIn.delete(); documentOut.renameTo(new File(unzipDir.getCanonicalPath() + File.separator + "word" + File.separator + "document.xml")); //Create a file to store the zipped file. File zipFile = File.createTempFile("mi-tmp-", configuration.getFileType(), tmpdir); //Zip the file. Utils4J.zipDir(unzipDir, null, zipFile); //Delete zip directory. if (unzipDir.getName().startsWith("mi-tmp-")) { FileUtil.deleteFile(unzipDir); } return zipFile; } private File createTmpDirectoryInTmp() throws IOException { final int maxAttempts = 10; int attempt = 0; do { String random = UUID.randomUUID().toString(); File dir = new File(tmpdir + File.separator + "mi-tmp-" + random); if (! dir.exists() && dir.mkdir()) { System.out.println("PluginDOCX::createTmpDirectoryInTmp(): " + dir.getCanonicalPath()); return dir; } } while (++attempt < maxAttempts); throw new IOException("Cound not create temp directory."); } }