~ubuntu-branches/ubuntu/utopic/freemind/utopic

« back to all changes in this revision

Viewing changes to freemind/accessories/plugins/ExportWithXSLT.java

  • Committer: Bazaar Package Importer
  • Author(s): Benjamin Drung
  • Date: 2010-01-03 14:19:19 UTC
  • mfrom: (2.1.1 sid)
  • Revision ID: james.westby@ubuntu.com-20100103141919-m5az7dkicy21hqop
Tags: 0.9.0~rc6+dfsg-1ubuntu1
* Merge from Debian unstable (LP: #182927), remaining changes:
  - debian/copyright: add license/copyright for
    freemind/freemind/main/ExampleFileFilter.java

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*FreeMind - A Program for creating and viewing Mindmaps
 
2
*Copyright (C) 2000-2006 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitri Polivaev and others.
 
3
*
 
4
*See COPYING for Details
 
5
*
 
6
*This program is free software; you can redistribute it and/or
 
7
*modify it under the terms of the GNU General Public License
 
8
*as published by the Free Software Foundation; either version 2
 
9
*of the License, or (at your option) any later version.
 
10
*
 
11
*This program is distributed in the hope that it will be useful,
 
12
*but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
*GNU General Public License for more details.
 
15
*
 
16
*You should have received a copy of the GNU General Public License
 
17
*along with this program; if not, write to the Free Software
 
18
*Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
19
*/
 
20
/*
 
21
 * Created on 08.04.2004
 
22
 *
 
23
 * To change the template for this generated file go to
 
24
 * Window>Preferences>Java>Code Generation>Code and Comments
 
25
 */
 
26
package accessories.plugins;
 
27
 
 
28
import java.awt.image.BufferedImage;
 
29
import java.io.BufferedWriter;
 
30
import java.io.File;
 
31
import java.io.FileOutputStream;
 
32
import java.io.FilenameFilter;
 
33
import java.io.IOException;
 
34
import java.io.InputStream;
 
35
import java.io.OutputStreamWriter;
 
36
import java.io.StringReader;
 
37
import java.io.StringWriter;
 
38
import java.net.MalformedURLException;
 
39
import java.net.URL;
 
40
import java.util.StringTokenizer;
 
41
import java.util.Vector;
 
42
 
 
43
import javax.imageio.ImageIO;
 
44
import javax.swing.JOptionPane;
 
45
import javax.xml.transform.Result;
 
46
import javax.xml.transform.Source;
 
47
import javax.xml.transform.Transformer;
 
48
import javax.xml.transform.TransformerFactory;
 
49
import javax.xml.transform.stream.StreamResult;
 
50
import javax.xml.transform.stream.StreamSource;
 
51
 
 
52
import accessories.plugins.util.html.ClickableImageCreator;
 
53
import accessories.plugins.util.xslt.ExportDialog;
 
54
import freemind.extensions.ExportHook;
 
55
import freemind.main.Resources;
 
56
import freemind.main.Tools;
 
57
import freemind.modes.MindIcon;
 
58
import freemind.modes.MindMap;
 
59
import freemind.modes.MindMapNode;
 
60
import freemind.modes.ModeController;
 
61
/**
 
62
 * @author foltin
 
63
 *
 
64
 * Exports the map using an XSLT script. The parameterization is described
 
65
 * in the corresponding Export... .xml-file.
 
66
 */
 
67
public class ExportWithXSLT extends ExportHook {
 
68
        private static final String NAME_EXTENSION_PROPERTY = "name_extension";
 
69
    /**
 
70
         * For test purposes. True=no error
 
71
         */
 
72
        private boolean mTransformResultWithoutError = false;
 
73
        
 
74
    protected File chooseFile() {
 
75
        
 
76
        String nameExtension = null;
 
77
        if (getProperties().containsKey(NAME_EXTENSION_PROPERTY)) {
 
78
            nameExtension = getResourceString(NAME_EXTENSION_PROPERTY);
 
79
        }        
 
80
        return chooseFile(getResourceString("file_type"), getTranslatableResourceString("file_description"), nameExtension);
 
81
    }
 
82
 
 
83
    /**
 
84
         * 
 
85
         */
 
86
        public ExportWithXSLT() {
 
87
                super();
 
88
        }
 
89
 
 
90
        /* (non-Javadoc)
 
91
         * @see freemind.extensions.MindMapHook#startupMapHook()
 
92
         */
 
93
        public void startupMapHook() {
 
94
                super.startupMapHook();
 
95
                ModeController mc = getController();
 
96
                MindMap model = getController().getMap();
 
97
                 if (Tools.safeEquals(getResourceString("file_type"), "user")) {
 
98
                         if(model == null) 
 
99
                                 return; // there may be no map open
 
100
                         if((model.getFile() == null) || model.isReadOnly()) {
 
101
                                if(mc.save()) {
 
102
                                        export(model.getFile());
 
103
                                        return;
 
104
                                }
 
105
                                else
 
106
                                        return;
 
107
                         }
 
108
                         else
 
109
                                 export(model.getFile());
 
110
                 } else {
 
111
                         File saveFile = chooseFile();
 
112
                         if(saveFile==null) {
 
113
                                 // no file.
 
114
                                 return;
 
115
                         }
 
116
                     transform(saveFile);
 
117
                 }
 
118
        }
 
119
        /**
 
120
         * @param saveFile 
 
121
     * 
 
122
     */
 
123
    public void transform(File saveFile) {
 
124
        try {
 
125
                        mTransformResultWithoutError=true;
 
126
            // get AREA:
 
127
            // create HTML image?
 
128
            boolean create_image = Tools.safeEquals(getResourceString("create_html_linked_image"), "true");
 
129
            String areaCode = getAreaCode(create_image);
 
130
            // XSLT Transformation
 
131
            String xsltFileName = getResourceString("xslt_file");
 
132
            boolean success = transformMapWithXslt(xsltFileName, saveFile, areaCode);
 
133
            if (!success) {
 
134
                                JOptionPane.showMessageDialog(null,
 
135
                                                getResourceString("error_applying_template"),
 
136
                                                "Freemind", JOptionPane.ERROR_MESSAGE);
 
137
                                return;
 
138
                        }
 
139
            // create directory?
 
140
            if(success && Tools.safeEquals(getResourceString("create_dir"), "true")) {
 
141
                String directoryName = saveFile.getAbsolutePath()+"_files";
 
142
                success = createDirectory(directoryName);
 
143
                
 
144
                // copy files from the resources to the file system:
 
145
                if(success) {
 
146
                    String files = getResourceString("files_to_copy");
 
147
                    String filePrefix = getResourceString("file_prefix");
 
148
                    copyFilesFromResourcesToDirectory(directoryName, files, filePrefix);
 
149
                }
 
150
                // copy icons?
 
151
                if(success && Tools.safeEquals(getResourceString("copy_icons"),"true")) {
 
152
                    success = copyIcons(directoryName);
 
153
                }
 
154
                if(success && Tools.safeEquals(getResourceString("copy_map"),"true")) {
 
155
                    success = copyMap(directoryName);
 
156
                }
 
157
                if(success && create_image) {
 
158
                    createImageFromMap(directoryName);
 
159
                }
 
160
            }
 
161
            if(!success){
 
162
                JOptionPane.showMessageDialog(null, getResourceString("error_creating_directory"), "Freemind", JOptionPane.ERROR_MESSAGE);
 
163
                return;
 
164
            }
 
165
            if(Tools.safeEquals(getResourceString("load_file"), "true")) {
 
166
                getController().getFrame().openDocument(Tools.fileToUrl(saveFile));
 
167
            }
 
168
        } catch (Exception e) {
 
169
            freemind.main.Resources.getInstance().logException(e);
 
170
            mTransformResultWithoutError = false;
 
171
        }
 
172
    }
 
173
 
 
174
    private boolean copyMap(String pDirectoryName) throws IOException
 
175
    {
 
176
        boolean success = true;
 
177
//      Generating output Stream            
 
178
        BufferedWriter fileout = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(pDirectoryName+File.separator + "map.mm") ) );
 
179
        getController().getMap().getFilteredXml(fileout);
 
180
        return success;
 
181
    }
 
182
 
 
183
    /**
 
184
     */
 
185
    private boolean copyIcons(String directoryName)
 
186
    {
 
187
        boolean success;
 
188
        String iconDirectoryName = directoryName + File.separatorChar + "icons";
 
189
        
 
190
        success = createDirectory(iconDirectoryName);
 
191
        if(success) {
 
192
            copyIconsToDirectory(iconDirectoryName);
 
193
        }
 
194
        return success;
 
195
    }
 
196
 
 
197
    /**
 
198
     */
 
199
    private void createImageFromMap(String directoryName)
 
200
    {
 
201
                // in the test case, we don't have a viewer and skip the image.
 
202
                if(getController().getView() == null)
 
203
                        return;
 
204
        // create image:
 
205
        BufferedImage image = createBufferedImage();
 
206
        try {
 
207
                FileOutputStream out = new FileOutputStream(directoryName+File.separator+"image.png");
 
208
                ImageIO.write(image, "png", out);
 
209
                out.close();
 
210
        } catch (IOException e1) {
 
211
        freemind.main.Resources.getInstance().logException(     e1);
 
212
        }
 
213
    }
 
214
 
 
215
    /**
 
216
     */
 
217
    private void copyIconsToDirectory(String directoryName2)
 
218
    {
 
219
        Vector iconNames = MindIcon.getAllIconNames();
 
220
        for ( int i = 0 ; i < iconNames.size(); ++i ) {
 
221
            String iconName = ((String) iconNames.get(i));
 
222
            MindIcon myIcon     = MindIcon.factory(iconName);
 
223
            copyFromResource(MindIcon.getIconsPath(), myIcon.getIconBaseFileName(), directoryName2); 
 
224
        }
 
225
        File iconDir = new File (Resources.getInstance().getFreemindDirectory(),"icons");
 
226
        if (iconDir.exists()){
 
227
            String[] userIconArray = iconDir.list(new FilenameFilter(){
 
228
                public boolean accept(File dir, String name) {
 
229
                    return name.matches(".*\\.png");
 
230
                }                
 
231
            });
 
232
            for ( int i = 0 ; i < userIconArray.length; ++i ) {
 
233
                String iconName = userIconArray[i];
 
234
                if(iconName.length() == 4){
 
235
                    continue;
 
236
                }
 
237
                copyFromFile(iconDir.getAbsolutePath(), iconName, directoryName2);
 
238
            }
 
239
        }
 
240
 
 
241
    }
 
242
 
 
243
    /**
 
244
     */
 
245
    private void copyFilesFromResourcesToDirectory(String directoryName, String files, String filePrefix)
 
246
    {
 
247
        StringTokenizer tokenizer = new StringTokenizer(files, ",");
 
248
        while(tokenizer.hasMoreTokens()) {
 
249
            String next = tokenizer.nextToken();
 
250
            copyFromResource(filePrefix, next, directoryName); 
 
251
        }
 
252
    }
 
253
 
 
254
    /**
 
255
     */
 
256
    private boolean createDirectory(String directoryName)
 
257
    {
 
258
        File dir = new File(directoryName);
 
259
        // create directory, if not exists:
 
260
        if (!dir.exists()) {
 
261
            return dir.mkdir();
 
262
        }
 
263
        return true;
 
264
    }
 
265
 
 
266
    /**
 
267
     * @throws IOException
 
268
     */
 
269
    private boolean transformMapWithXslt(String xsltFileName, File saveFile, String areaCode) throws IOException
 
270
    {
 
271
        StringWriter writer = getMapXml();
 
272
        StringReader reader = new StringReader(writer.getBuffer().toString());
 
273
        // search for xslt file:
 
274
        URL xsltUrl = getResource(xsltFileName);
 
275
        if(xsltUrl == null) {
 
276
            logger.severe("Can't find " + xsltFileName + " as resource.");
 
277
            throw new IllegalArgumentException("Can't find " + xsltFileName + " as resource.");
 
278
        }
 
279
        InputStream xsltFile = xsltUrl.openStream();
 
280
        return transform(new StreamSource(reader), xsltFile, saveFile, areaCode);
 
281
    }
 
282
 
 
283
    /**
 
284
     * @throws IOException
 
285
     */
 
286
    private StringWriter getMapXml() throws IOException
 
287
    {
 
288
        // get output:
 
289
        StringWriter writer = new StringWriter();
 
290
        // get XML
 
291
        getController().getMap().getFilteredXml(writer);
 
292
        return writer;
 
293
    }
 
294
 
 
295
    /**
 
296
     * @param create_image
 
297
     */
 
298
    private String getAreaCode(boolean create_image)
 
299
    {
 
300
        String areaCode="";
 
301
        if(create_image) {
 
302
            MindMapNode root = getController().getMap().getRootNode();
 
303
            ClickableImageCreator creator = new ClickableImageCreator(root, getController(), 
 
304
                    getResourceString("link_replacement_regexp"));
 
305
            areaCode = creator.generateHtml();
 
306
        }
 
307
        return areaCode;
 
308
    }
 
309
 
 
310
    private void export(File file) {
 
311
        ExportDialog exp = new ExportDialog(file, getController());
 
312
        exp.setVisible(true);
 
313
        }
 
314
 
 
315
    public boolean transform(Source xmlSource, InputStream xsltStream, File resultFile, String areaCode)
 
316
    {
 
317
        //System.out.println("set xsl");
 
318
       Source xsltSource =  new StreamSource(xsltStream);
 
319
        //System.out.println("set result");
 
320
       Result result = new StreamResult(resultFile);
 
321
    
 
322
       // create an instance of TransformerFactory
 
323
       try{
 
324
           //System.out.println("make transform instance");
 
325
       TransformerFactory transFact = TransformerFactory.newInstance(  );
 
326
    
 
327
       Transformer trans = transFact.newTransformer(xsltSource);
 
328
       // set parameter:
 
329
       // relative directory <filename>_files
 
330
       trans.setParameter("destination_dir", resultFile.getName()+"_files/");
 
331
       trans.setParameter("area_code", areaCode);
 
332
       trans.setParameter("folding_type", getController().getFrame().getProperty("html_export_folding"));
 
333
       trans.transform(xmlSource, result);
 
334
       }
 
335
       catch(Exception e){
 
336
       //System.err.println("error applying the xslt file "+e);
 
337
       freemind.main.Resources.getInstance().logException(e);
 
338
       return false;
 
339
       };
 
340
      return true;
 
341
      }
 
342
 
 
343
        public boolean isTransformResultWithoutError() {
 
344
                return mTransformResultWithoutError;
 
345
        }
 
346
      
 
347
        
 
348
        
 
349
}