001: /*
002: * SalomeTMF is a Test Management Framework
003: * Copyright (C) 2005 France Telecom R&D
004: *
005: * This library is free software; you can redistribute it and/or
006: * modify it under the terms of the GNU Lesser General Public
007: * License as published by the Free Software Foundation; either
008: * version 2 of the License, or (at your option) any later version.
009: *
010: * This library is distributed in the hope that it will be useful,
011: * but WITHOUT ANY WARRANTY; without even the implied warranty of
012: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
013: * Lesser General Public License for more details.
014: *
015: * You should have received a copy of the GNU Lesser General Public
016: * License along with this library; if not, write to the Free Software
017: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
018: *
019: * @author Aurore PENAULT, Marche Mikael
020: *
021: * Contact: mikael.marche@orange-ft.com
022: */
023:
024: package salomeTMF_plug.docXML.export;
025:
026: import java.io.BufferedWriter;
027: import java.io.File;
028: import java.io.FileInputStream;
029: import java.io.FileNotFoundException;
030: import java.io.FileOutputStream;
031: import java.io.FileWriter;
032: import java.io.IOException;
033: import java.io.Writer;
034: import java.net.URL;
035: import java.util.ArrayList;
036: import java.util.Iterator;
037: import java.util.List;
038: import java.util.Vector;
039:
040: import javax.xml.transform.OutputKeys;
041: import javax.xml.transform.Result;
042: import javax.xml.transform.Source;
043: import javax.xml.transform.Transformer;
044: import javax.xml.transform.TransformerException;
045: import javax.xml.transform.TransformerFactory;
046: import javax.xml.transform.stream.StreamResult;
047: import javax.xml.transform.stream.StreamSource;
048:
049: import net.sf.saxon.OutputURIResolver;
050:
051: import org.dom4j.Document;
052: import org.dom4j.DocumentException;
053: import org.dom4j.DocumentHelper;
054: import org.dom4j.Element;
055: import org.dom4j.io.OutputFormat;
056: import org.dom4j.io.SAXReader;
057: import org.dom4j.io.XMLWriter;
058: import org.objectweb.salome_tmf.api.Api;
059: import org.objectweb.salome_tmf.api.Util;
060: import org.objectweb.salome_tmf.ihm.tools.Tools;
061: import org.objectweb.salome_tmf.plugins.core.XMLPrinterPlugin;
062:
063: import salomeTMF_plug.docXML.languages.Language;
064:
065: public class XSLGenerator {
066:
067: private Vector listXMLPlugins;
068:
069: private boolean dynamicMode = false;
070:
071: private String translatePath;
072:
073: public XSLGenerator(Vector listXMLPlugins, boolean dynamicMode,
074: String translatePath) {
075: this .listXMLPlugins = listXMLPlugins;
076: this .dynamicMode = dynamicMode;
077: this .translatePath = translatePath;
078: }
079:
080: /**
081: * Méthode pour effectuer une transformation xslt
082: * @param multiFrame true if the generated document is in HTML multi frame mode
083: * @param srcXml document xml source pour la transformation
084: * @param srcXslt document xslt pour la transformation
085: * @param outHtml fichier dans lequel doit être mis lengthrésultat de la transformation
086: * @param jpegImg si true, insertion des fichiers jpeg dans le document html
087: * @param gifImg si true, insertion des fichiers gif dans le document html
088: * @param pngImg si true, insertion des fichiers png dans le document html
089: * @param chosenChaptersList
090: * @param urlTranslate
091: */
092: public void transform(boolean multiFrame, boolean htmlFormat,
093: String srcXml, String url_txt, String srcXslt,
094: String outHtml, boolean jpegImg, boolean gifImg,
095: boolean pngImg, String destDir, ArrayList chosenChaptersList)
096: throws Exception {
097: File newMainXslt = resolveImport(url_txt, srcXslt, multiFrame,
098: htmlFormat);
099: importTranslate(translatePath);
100:
101: //to use the Saxon XSLT processor
102: System.setProperty("javax.xml.transform.TransformerFactory",
103: "net.sf.saxon.TransformerFactoryImpl");
104: StreamSource styleSource = new StreamSource(newMainXslt.toURL()
105: .openStream());
106: TransformerFactory factory = TransformerFactory.newInstance();
107: String outputDir = outHtml.substring(0, outHtml
108: .lastIndexOf(File.separator) + 1);
109: factory.setAttribute(
110: net.sf.saxon.FeatureKeys.OUTPUT_URI_RESOLVER,
111: new UserOutputResolver(outputDir));
112: Transformer x = null;
113: Util.log("[XmlGenerator:transform] create TransformerFactory");
114: x = factory.newTransformer(styleSource);
115:
116: Util.log("[XmlGenerator:transform] set parameter");
117:
118: if (jpegImg) {
119: Util.log("\t jpeg = true");
120: x.setParameter("jpeg", "1");
121: }
122: if (gifImg) {
123: Util.log("\t gif = true");
124: x.setParameter("gif", "1");
125: }
126: if (pngImg) {
127: Util.log("\t png = true");
128: x.setParameter("png", "1");
129: }
130: if (!htmlFormat) {
131: String urlBase = new File(outputDir).toURI().toString();
132: Util.log("\t urlBase = " + urlBase);
133: x.setParameter("urlBase", urlBase);
134: }
135: Iterator it = chosenChaptersList.iterator();
136: while (it.hasNext()) {
137: String chapterName = (String) it.next();
138: if (chapterName.equals(Language.getInstance().getText(
139: "Projet"))) {
140: Util.log("\t project = true");
141: x.setParameter("project", "1");
142: } else if (chapterName.equals(Language.getInstance()
143: .getText("Environnements"))) {
144: Util.log("\t environments = true");
145: x.setParameter("environments", "1");
146: } else if (chapterName.equals(Language.getInstance()
147: .getText("Dossier_de_tests"))) {
148: Util.log("\t testplan = true");
149: x.setParameter("testplan", "1");
150: } else if (chapterName.equals(Language.getInstance()
151: .getText("Campagnes_du_projet"))) {
152: Util.log("\t campaigns = true");
153: x.setParameter("campaigns", "1");
154: } else if (chapterName.equals(Language.getInstance()
155: .getText("Rapport_d_exécution"))) {
156: Util.log("\t executionreport = true");
157: x.setParameter("executionreport", "1");
158: }
159: int size = listXMLPlugins.size();
160: for (int i = 0; i < size; i++) {
161: XMLPrinterPlugin pXMLPrinterPlugin = (XMLPrinterPlugin) listXMLPlugins
162: .elementAt(i);
163: String paramName = pXMLPrinterPlugin
164: .getParameterName(chapterName);
165: if (paramName != null) {
166: Util.log("\t " + paramName + " = true");
167: x.setParameter(paramName, "1");
168: }
169: }
170: }
171: Util.log("\t local = " + Api.getUsedLocale());
172: x.setParameter("local", Api.getUsedLocale());
173: String urlTranslate = new File(translatePath).toURL()
174: .toString();
175: x.setParameter("translate", urlTranslate);
176:
177: /* Utilise pour que les xsl trouve translate.xml */
178: System.setProperty("user.dir", System.getProperties()
179: .getProperty("java.io.tmpdir"));
180:
181: if (multiFrame) {
182: String frame1Param = outHtml.substring(outHtml
183: .lastIndexOf(File.separator) + 1, outHtml
184: .lastIndexOf("."))
185: + "_sommaire.html";
186: String frame2Param = outHtml.substring(outHtml
187: .lastIndexOf(File.separator) + 1, outHtml
188: .lastIndexOf("."))
189: + "_princ.html";
190: Util.log("\t frame1 = " + frame1Param);
191: Util.log("\t frame2 = " + frame2Param);
192: x.setParameter("frame1", frame1Param);
193: x.setParameter("frame2", frame2Param);
194: }
195: FileOutputStream fileOut = null;
196: try {
197: x.setOutputProperty(OutputKeys.INDENT, "yes");
198: Util.log("[XmlGenerator:transform] get source file : "
199: + srcXml);
200: Source source = new StreamSource(new File(srcXml));
201: Result target = null;
202: Util
203: .log("[XmlGenerator:transform] set target : "
204: + outHtml);
205: fileOut = new FileOutputStream(outHtml);
206:
207: target = new javax.xml.transform.stream.StreamResult(
208: fileOut);
209: Util.log("[XmlGenerator:transform] do transformation ");
210: x.transform(source, target);
211: fileOut.close();
212: } catch (Exception e) {
213: if (fileOut != null) {
214: fileOut.close();
215: }
216: throw e;
217: }
218: }
219:
220: /**
221: * Import translations from plugins
222: * @param urlTranslate
223: * @throws Exception
224: */
225: private void importTranslate(String urlTranslate) throws Exception {
226: File mainTranslateFile = new File(urlTranslate);
227: int size = listXMLPlugins.size();
228: for (int i = 0; i < size; i++) {
229: XMLPrinterPlugin pXMLPrinterPlugin = (XMLPrinterPlugin) listXMLPlugins
230: .elementAt(i);
231: File translateFileToImport = pXMLPrinterPlugin
232: .getTranslationFile();
233: if (translateFileToImport != null) {
234: importTranslation(mainTranslateFile,
235: translateFileToImport);
236: }
237: }
238: }
239:
240: /**
241: * Import translation file from plugins in the main translation file
242: * @param mainTranslationFile the main translation file
243: * @param translationFileToImport translation file from plugin to import
244: * @throws Exception
245: */
246: private void importTranslation(File mainTranslationFile,
247: File translationFileToImport) throws Exception {
248: SAXReader reader = new SAXReader();
249: Document mainDoc = reader.read(mainTranslationFile);
250: Document importDoc = reader.read(translationFileToImport);
251: List importTemplateList = importDoc.selectNodes("//headings");
252: Iterator itImport = importTemplateList.iterator();
253: while (itImport.hasNext()) {
254: Element headingsImportElem = (Element) itImport.next();
255: String language = headingsImportElem.attributeValue("lang");
256: Element mainHeadingsElem = (Element) mainDoc
257: .selectSingleNode("//headings[@xml:lang='"
258: + language + "']");
259: List children = headingsImportElem.elements();
260: Iterator elemIt = children.iterator();
261: while (elemIt.hasNext()) {
262: Element elemToAdd = ((Element) elemIt.next())
263: .createCopy();
264: String category = elemToAdd.attributeValue("category");
265: if (mainDoc.getRootElement().selectSingleNode(
266: "//headings[@xml:lang='" + language
267: + "']/heading[@category='" + category
268: + "']") == null) {
269: mainHeadingsElem.add(elemToAdd);
270: }
271: }
272: }
273: OutputFormat format = OutputFormat.createPrettyPrint();
274: XMLWriter writer = new XMLWriter(new FileOutputStream(
275: mainTranslationFile), format);
276: writer.write(mainDoc);
277: }
278:
279: /**
280: * Modify the XSLT file to include XSL files from plugins
281: * @param url_txt
282: * @param srcXslt
283: * @param multiFrame
284: */
285: private File resolveImport(String url_txt, String srcXslt,
286: boolean multiFrame, boolean htmlFormat) throws Exception {
287: int size = listXMLPlugins.size();
288: File temporaryFile = File.createTempFile("oldMain", ".xsl");
289: String temporaryFilePath = temporaryFile.getAbsolutePath();
290: try {
291: URL xsltURL = new URL(url_txt + srcXslt);
292: Tools.writeFile(xsltURL.openStream(), temporaryFilePath);
293: } catch (Exception e) {
294: Tools.writeFile(XSLGenerator.class
295: .getResourceAsStream("/salome/" + srcXslt),
296: temporaryFilePath);
297: }
298: if (size == 0) {
299: return temporaryFile;
300: }
301: File newMainXslt = null;
302: for (int i = 0; i < size; i++) {
303: XMLPrinterPlugin pXMLPrinterPlugin = (XMLPrinterPlugin) listXMLPlugins
304: .elementAt(i);
305: File xsltFileToImport = pXMLPrinterPlugin.getXSLToImport(
306: dynamicMode, multiFrame, htmlFormat);
307: if (xsltFileToImport != null) {
308: newMainXslt = importXSLT(temporaryFile,
309: xsltFileToImport);
310: }
311: copy(newMainXslt, temporaryFile);
312: }
313: return newMainXslt;
314: }
315:
316: public void copy(File source, File destination) throws Exception {
317: FileInputStream sourceFile = null;
318: FileOutputStream destinationFile = null;
319: destination.createNewFile();
320: sourceFile = new java.io.FileInputStream(source);
321: destinationFile = new java.io.FileOutputStream(destination);
322: byte buffer[] = new byte[512 * 1024];
323: int nbLecture;
324: while ((nbLecture = sourceFile.read(buffer)) != -1) {
325: destinationFile.write(buffer, 0, nbLecture);
326: }
327: sourceFile.close();
328: destinationFile.close();
329: }
330:
331: /**
332: * Import an XSLT file from a plugin in the main XSLT file
333: * @param mainXsltFile the main XSLT file
334: * @param xsltFileToImport the XSLT file to import
335: * @throws DocumentException
336: */
337: private File importXSLT(File mainXsltFile, File xsltFileToImport)
338: throws Exception {
339: SAXReader reader = new SAXReader();
340: Document mainDoc = reader.read(mainXsltFile);
341: Document importDoc = reader.read(xsltFileToImport);
342: Element mainRootElem = mainDoc.getRootElement();
343: List importParamList = importDoc
344: .selectNodes("/xsl:stylesheet/xsl:param");
345: Iterator it = importParamList.iterator();
346: while (it.hasNext()) {
347: Element elemToAdd = ((Element) it.next()).createCopy();
348: mainRootElem.add(elemToAdd);
349: }
350: List importVariableList = importDoc
351: .selectNodes("/xsl:stylesheet/xsl:variable");
352: it = importVariableList.iterator();
353: while (it.hasNext()) {
354: Element elemToAdd = ((Element) it.next()).createCopy();
355: mainRootElem.add(elemToAdd);
356: }
357: List importTemplateList = importDoc
358: .selectNodes("//xsl:template");
359: it = importTemplateList.iterator();
360: while (it.hasNext()) {
361: Element importTemplateElem = (Element) it.next();
362: String importTemplateName = importTemplateElem
363: .attributeValue("name");
364: if (importTemplateName != null) {
365: Element mainElem = (Element) mainDoc
366: .selectSingleNode("//xsl:template[@name='"
367: + importTemplateName + "']");
368: if (mainElem != null) {
369: //add children of importTemplateElem to mainElem
370: List children = importTemplateElem.elements();
371: Iterator elemIt = children.iterator();
372: while (elemIt.hasNext()) {
373: Element elemToAdd = ((Element) elemIt.next())
374: .createCopy();
375: if (!elemToAdd.getName().equals("param"))
376: mainElem.add(elemToAdd);
377: }
378: } else {
379: Element elemToAdd = importTemplateElem.createCopy();
380: mainRootElem.add(elemToAdd);
381: }
382: } else {
383: //add at the end of the main stylesheet
384: Element elemToAdd = importTemplateElem.createCopy();
385: mainRootElem.add(elemToAdd);
386: }
387: }
388: List importFunctionList = importDoc
389: .selectNodes("/xsl:stylesheet/xsl:function");
390: it = importFunctionList.iterator();
391: while (it.hasNext()) {
392: Element elemToAdd = ((Element) it.next()).createCopy();
393: mainRootElem.add(elemToAdd);
394: }
395: //write the main document in a temporary file
396: File temp = File.createTempFile("main", ".xsl");
397:
398: // Delete temp file when program exits.
399: temp.deleteOnExit();
400:
401: OutputFormat format = OutputFormat.createPrettyPrint();
402: XMLWriter writer = new XMLWriter(new FileOutputStream(temp),
403: format);
404: writer.write(mainDoc);
405:
406: return temp;
407: }
408:
409: /**
410: * Méthode qui permet d'ajouter soit une page de garde soit une en-tête soit un pied de page
411: * @param pathHtml document Html auquel il faut ajouter la mise en page
412: * @param pathAdd document Html contenant la mise en page
413: * @param tete true->en-tête ou page de garde, false->pied de page
414: */
415: public void addTitlePage(String pathHtml, String pathAdd,
416: boolean tete) throws Exception {
417: SAXReader reader = new SAXReader(false);
418: reader.setIncludeExternalDTDDeclarations(false);
419: reader.setIncludeInternalDTDDeclarations(false);
420: Document doc = reader.read(new FileInputStream(new File(
421: pathHtml)));
422: SAXReader reader2 = new SAXReader(false);
423: reader.setIncludeExternalDTDDeclarations(false);
424: reader.setIncludeInternalDTDDeclarations(false);
425: Document add = reader2.read(new FileInputStream(new File(
426: pathAdd)));
427:
428: Document document = DocumentHelper.createDocument();
429: Element root = document.addElement("html");
430: Element head = ((Element) doc.selectSingleNode("//head"))
431: .createCopy();
432: root.add(head);
433: Element body = root.addElement("body");
434: if (tete) {
435: ArrayList listElement = (ArrayList) add
436: .selectNodes("//body/child::*");
437: if (!listElement.isEmpty()) {
438: Iterator it = listElement.iterator();
439: while (it.hasNext()) {
440: Element elem = ((Element) it.next()).createCopy();
441: body.add(elem);
442: }
443: }
444: ArrayList bodyElems = (ArrayList) doc
445: .selectNodes("//body/child::*");
446: if (!bodyElems.isEmpty()) {
447: Iterator it = bodyElems.iterator();
448: while (it.hasNext()) {
449: Element elem = ((Element) it.next()).createCopy();
450: body.add(elem);
451: }
452: }
453: } else {
454: ArrayList bodyElems = (ArrayList) doc
455: .selectNodes("//body/child::*");
456: if (!bodyElems.isEmpty()) {
457: Iterator it = bodyElems.iterator();
458: while (it.hasNext()) {
459: Element elem = ((Element) it.next()).createCopy();
460: body.add(elem);
461: }
462: }
463: body.addElement("hr");
464: ArrayList listElement = (ArrayList) add
465: .selectNodes("//body/child::*");
466: if (!listElement.isEmpty()) {
467: Iterator it = listElement.iterator();
468: while (it.hasNext()) {
469: Element elem = ((Element) it.next()).createCopy();
470: body.add(elem);
471: }
472: }
473: }
474: OutputFormat format = OutputFormat.createPrettyPrint();
475: format.setEncoding("iso-8859-1");
476: XMLWriter writer;
477: Writer outputWriter = new BufferedWriter(new FileWriter(
478: new File(pathHtml)));
479: writer = new XMLWriter(outputWriter, format);
480: writer.write(document);
481: writer.close();
482: }
483:
484: /**
485: * Méthode qui ajoute la mise en forme
486: * si boolean tete = true : ajoute un en-tête
487: * sinon ajoute un pied de page
488: * @param pathHtml page html auquel on ajoute une mise en page
489: * @param addElement élément à ajouter
490: * @param tete détermine en-tête ou pied de page
491: */
492: public void addTitlePage(String pathHtml, Element addElement,
493: boolean tete) throws Exception {
494: SAXReader reader = new SAXReader(false);
495: reader.setIncludeExternalDTDDeclarations(false);
496: reader.setIncludeInternalDTDDeclarations(false);
497: Document doc = reader.read(new FileInputStream(new File(
498: pathHtml)));
499:
500: Document document = DocumentHelper.createDocument();
501: Element elemCopy = addElement.createCopy();
502: Element root = document.addElement("html");
503: Element head = ((Element) doc.selectSingleNode("//head"))
504: .createCopy();
505: root.add(head);
506: Element body = root.addElement("body");
507: if (tete) {
508: body.add(elemCopy);
509: ArrayList bodyElems = (ArrayList) doc
510: .selectNodes("//body/child::*");
511: if (!bodyElems.isEmpty()) {
512: Iterator it = bodyElems.iterator();
513: while (it.hasNext()) {
514: Element elem = ((Element) it.next()).createCopy();
515: body.add(elem);
516: }
517: }
518: } else {
519: ArrayList bodyElems = (ArrayList) doc
520: .selectNodes("//body/child::*");
521: if (!bodyElems.isEmpty()) {
522: Iterator it = bodyElems.iterator();
523: while (it.hasNext()) {
524: Element elem = ((Element) it.next()).createCopy();
525: body.add(elem);
526: }
527: }
528: body.addElement("hr");
529: body.add(elemCopy);
530: }
531: OutputFormat format = OutputFormat.createPrettyPrint();
532: format.setEncoding("iso-8859-1");
533: XMLWriter writer;
534: Writer outputWriter = new BufferedWriter(new FileWriter(
535: new File(pathHtml)));
536: writer = new XMLWriter(outputWriter, format);
537: writer.write(document);
538: writer.close();
539: }
540:
541: public static class UserOutputResolver implements OutputURIResolver {
542:
543: FileOutputStream fileOut;
544: String outputDir;
545:
546: public UserOutputResolver(String outputDir) {
547: this .outputDir = outputDir;
548: }
549:
550: public void close(Result arg0) throws TransformerException {
551: try {
552: if (fileOut != null)
553: fileOut.close();
554: } catch (IOException e) {
555: //TODO
556: }
557: }
558:
559: public Result resolve(String href, String base)
560: throws TransformerException {
561: try {
562: File out = new File(outputDir + href);
563: fileOut = new FileOutputStream(out);
564: } catch (FileNotFoundException e) {
565: //TODO
566: }
567: StreamResult res = new StreamResult(fileOut);
568: return res;
569: }
570:
571: }
572: }
|