Statistics
| Revision:

ccc / projets / CMC2ELAN / src / ApplyXsl2.groovy @ 2

History | View | Annotate | Download (8.6 kB)

1
// Copyright © 2010-2013 ENS de Lyon.
2
// Copyright © 2007-2010 ENS de Lyon, CNRS, INRP, University of
3
// Lyon 2, University of Franche-Comté, University of Nice
4
// Sophia Antipolis, University of Paris 3.
5
// 
6
// The TXM platform is free software: you can redistribute it
7
// and/or modify it under the terms of the GNU General Public
8
// License as published by the Free Software Foundation,
9
// either version 2 of the License, or (at your option) any
10
// later version.
11
// 
12
// The TXM platform is distributed in the hope that it will be
13
// useful, but WITHOUT ANY WARRANTY; without even the implied
14
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15
// PURPOSE. See the GNU General Public License for more
16
// details.
17
// 
18
// You should have received a copy of the GNU General
19
// Public License along with the TXM platform. If not, see
20
// http://www.gnu.org/licenses.
21

    
22
//
23
// This file is part of the TXM platform.
24
//
25
// The TXM platform is free software: you can redistribute it and/or modif y
26
// it under the terms of the GNU General Public License as published by
27
// the Free Software Foundation, either version 3 of the License, or
28
// (at your option) any later version.
29
//
30
// The TXM platform is distributed in the hope that it will be useful,
31
// but WITHOUT ANY WARRANTY; without even the implied warranty of
32
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33
// GNU General Public License for more details.
34
//
35
// You should have received a copy of the GNU General Public License
36
// along with the TXM platform.  If not, see <http://www.gnu.org/licenses/>.
37
// 
38
// 
39
// 
40
// $LastChangedDate: 2011-11-03 17:59:23 +0100 (jeu., 03 nov. 2011) $
41
// $LastChangedRevision: 2051 $
42
// $LastChangedBy: mdecorde $ 
43
//
44

    
45

    
46
/**
47
 * @author mdecorde
48
 */
49

    
50
import java.io.File;
51
import java.io.FileNotFoundException;
52
import java.io.FileOutputStream;
53
import java.util.HashMap;
54

    
55
import javax.xml.transform.Transformer;
56
import javax.xml.transform.TransformerConfigurationException;
57
import javax.xml.transform.TransformerException;
58
import javax.xml.transform.stream.StreamResult;
59
import javax.xml.transform.stream.StreamSource;
60

    
61
import net.sf.saxon.TransformerFactoryImpl;
62

    
63

    
64
// TODO: Auto-generated Javadoc
65
/**
66
 * apply a xsl file to a file : use process(File infile, File outfile, String[]
67
 * args) to apply the xslt file loaded by the constructor args =
68
 * ["name1","value1","name2",value2, ...]
69
 * 
70
 * @author mdecorde
71
 */
72

    
73
public class ApplyXsl2 {
74

    
75
        //        /** The proc. */
76
        //        private Processor proc;
77
        //        
78
        //        /** The comp. */
79
        //        private XsltCompiler comp;
80
        //        
81
        //        /** The exp. */
82
        //        private XsltExecutable exp;
83
        //
84
        //        /** The source. */
85
        //        private XdmNode source;
86
        //        
87
        //        /** The out. */
88
        //        private Serializer out;
89
        //        
90
        //        /** The trans. */
91
        //        private XsltTransformer trans;
92

    
93
        net.sf.saxon.TransformerFactoryImpl tFactory;
94
        Transformer transformer;
95
        private HashMap<String, String> params = new HashMap<String, String>();
96
        private File xsltfile;
97

    
98
        /**
99
         * initialize with the xslt file.
100
         *
101
         * @param xsltfile the xsltfile
102
         * @throws TransformerConfigurationException 
103
         */
104
        public ApplyXsl2(String xsltfile) throws TransformerConfigurationException {
105

    
106
                System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
107

    
108
                this.xsltfile = new File(xsltfile);
109
                tFactory = new TransformerFactoryImpl();
110
                transformer = tFactory.newTransformer(new StreamSource(this.xsltfile));
111

    
112
                //println("new tFactory: "+tFactory);
113
                //println("new transformer: "+transformer);
114
        }
115

    
116
        /**
117
         * initialize with the xslt file.
118
         *
119
         * @param xsltfile the xsltfile
120
         */
121
        public ApplyXsl2(File xsltfile) {
122
                this.xsltfile = xsltfile;
123

    
124
                System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
125

    
126
                tFactory = new net.sf.saxon.TransformerFactoryImpl();
127
                println("new tFactory: "+tFactory);
128
                println("ApplyXsl2 from file: "+xsltfile);
129
                reload();
130
                println("new transformer: "+transformer);
131
        }
132

    
133
        /**
134
         * Set in and out file.
135
         *
136
         * @param xmlinfile the xmlinfile
137
         * @param xmloutfile the xmloutfile
138
         * @return true, if successful
139
         */
140
        private boolean SetInOutSource(File xmlinfile, File xmloutfile) {
141
                //                if (proc == null || exp == null || comp == null)
142
                //                        return false;
143
                //
144
                //                source = proc.newDocumentBuilder().build(
145
                //                                new StreamSource(new File(xmlinfile)));
146
                //                out = new Serializer();
147
                //                out.setOutputFile(new File(xmloutfile));
148
                //
149
                //                trans = exp.load();
150
                //                transformer.set.setInitialContextNode(source);
151
                //                transformer.setDestination(out);
152
                return true;
153
        }
154

    
155
        /**
156
         * Set a xslt param.
157
         *
158
         * @param name the name
159
         * @param value the value
160
         * @return true, if successful
161
         */
162
        public boolean SetParam(String name, Object value) {
163
                if (transformer != null) {
164
                        transformer.setParameter(name, value);
165
                        params.put(name, value.toString());
166
                        return true;
167
                } else
168
                        return false;
169
        }
170

    
171
        public boolean resetParams() {
172
                if (transformer != null) {
173
                        transformer.reset();
174
                        params.clear();
175
                } else
176
                        return false;
177
                return true;
178
        }
179

    
180
        /**
181
         * Force java to clean memory after processing a xslt. If not we might catch
182
         * a JavaHeapspace Exception
183
         * 
184
         */
185
        private void cleanMemory() {
186
                reload();
187
                for (String name : params.keySet()) { // reload parameters
188
                        transformer.setParameter(name, params.get(name));
189
                }
190
        }
191

    
192
        private boolean reload() {
193
                try {
194
                        transformer = null;
195
                        transformer = tFactory.newTransformer(new StreamSource(xsltfile));
196
                } catch (TransformerConfigurationException e) {
197
                        e.printStackTrace();
198
                        println("Error while reloading transformer: "+e);
199
                        return false;
200
                }
201
                return true;
202
        }
203

    
204
        /**
205
         * Process files with xslt args.
206
         *
207
         * @param xmlinfile file to be processed
208
         * @param xmloutfile output file
209
         * @param args xslt args ["arg1","arg1value","arg2","arg2value"...]
210
         * @return true, if successful
211
         * @throws TransformerException 
212
         * @throws FileNotFoundException 
213
         */
214

    
215
        public boolean process(String xmlinfile, String xmloutfile, String[] args) throws Exception {
216
                File infile = new File(xmlinfile);
217
                File outfile = new File(xmloutfile);
218
                if (!this.SetInOutSource(infile, outfile))
219
                        return false;
220
                //System.out.println(xmlinfile+" Params: "+Arrays.toString(args));
221
                for (int i = 0; i < args.length; i = i + 2) {
222
                        if (!this.SetParam(args[i], args[i + 1]))
223
                                return false;
224
                }
225

    
226
                transformer.transform(new StreamSource(xmlinfile), new StreamResult(new FileOutputStream(xmloutfile)));
227
                cleanMemory(); // save memory
228
                // System.out.println("Done");
229
                return true;
230
        }
231

    
232
        /**
233
         * Process files without xslt args.
234
         *
235
         * @param xmlinfile the xmlinfile
236
         * @param xmloutfile the xmloutfile
237
         * @return true, if successful
238
         * @throws TransformerException 
239
         * @throws FileNotFoundException 
240
         */
241
        public boolean process(File xmlinfile, File xmloutfile) throws FileNotFoundException, TransformerException {
242
                if (!this.SetInOutSource(xmlinfile, xmloutfile))
243
                        return false;
244
                if (transformer == null) return false;
245
                transformer.transform(new StreamSource(xmlinfile), new StreamResult(new FileOutputStream(xmloutfile)));
246
                cleanMemory();
247
                return true;
248
        }
249

    
250
        public static boolean processImportSources(File xslFile, File srcdir, File outdir) throws FileNotFoundException, TransformerException
251
        {
252
                HashMap<String, String> params = new HashMap<String, String>();
253
                return processImportSources(xslFile, srcdir, outdir, params);
254
        }
255
        
256
        public static boolean processImportSources(File xslFile, File srcdir, File outdir, HashMap<String, String> params) throws FileNotFoundException, TransformerException
257
        {
258
                outdir.mkdir();
259
                if (xslFile.exists()) {
260
                        ApplyXsl2 builder = new ApplyXsl2(xslFile);
261
                        for(String name : params.keySet())
262
                                builder.SetParam(name, params.get(name));
263
                        System.out.println("-- Apply xsl "+xslFile+" with parameters: "+params);
264
                        File[] files = srcdir.listFiles();
265
                        if (files != null)
266
                        for (File f : files) {
267
                                if (f.isHidden() || f.isDirectory())
268
                                        continue;
269
                                if (f.getName().endsWith(".properties"))
270
                                        continue;
271
                                if (f.getName().equals("import.xml"))
272
                                        continue;
273
                                if (f.getName().endsWith(".csv"))
274
                                        continue;
275
                                if (f.getName().endsWith(".dtd"))
276
                                        continue;
277
                                if (f.getName().endsWith(".xsl"))
278
                                        continue;
279
                                
280
                                System.out.print(".");
281
                                File outfile = new File(outdir, f.getName());
282
                                if (!builder.process(f, outfile)) {
283
                                        System.out.println("Failed with file "+ f);
284
                                        outfile.delete();
285
                                }
286
                        }
287
                        System.out.println("");
288
                        return true;
289
                } else {
290
                        System.out.println("XSL file does not exists: "+ xslFile);
291
                }
292
                return false;
293
        }
294
}