~ubuntu-branches/ubuntu/utopic/xslthl/utopic

« back to all changes in this revision

Viewing changes to src/net/sf/xslthl/Config.java

  • Committer: Package Import Robot
  • Author(s): Mathieu Malaterre
  • Date: 2013-05-16 08:59:07 UTC
  • mfrom: (4.1.2 sid)
  • Revision ID: package-import@ubuntu.com-20130516085907-ujk9f81x8w344ch1
Tags: 2.1.0-2
Upload to sid

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 * xslthl - XSLT Syntax Highlighting
3
 
 * https://sourceforge.net/projects/xslthl/
4
 
 * Copyright (C) 2005-2008 Michal Molhanec, Jirka Kosek, Michiel Hendriks
5
 
 * 
6
 
 * This software is provided 'as-is', without any express or implied
7
 
 * warranty.  In no event will the authors be held liable for any damages
8
 
 * arising from the use of this software.
9
 
 * 
10
 
 * Permission is granted to anyone to use this software for any purpose,
11
 
 * including commercial applications, and to alter it and redistribute it
12
 
 * freely, subject to the following restrictions:
13
 
 * 
14
 
 * 1. The origin of this software must not be misrepresented; you must not
15
 
 *    claim that you wrote the original software. If you use this software
16
 
 *    in a product, an acknowledgment in the product documentation would be
17
 
 *    appreciated but is not required.
18
 
 * 2. Altered source versions must be plainly marked as such, and must not be
19
 
 *    misrepresented as being the original software.
20
 
 * 3. This notice may not be removed or altered from any source distribution.
21
 
 * 
22
 
 * Michal Molhanec <mol1111 at users.sourceforge.net>
23
 
 * Jirka Kosek <kosek at users.sourceforge.net>
24
 
 * Michiel Hendriks <elmuerte at users.sourceforge.net>
25
 
 */
26
 
package net.sf.xslthl;
27
 
 
28
 
import java.io.File;
29
 
import java.net.URI;
30
 
import java.net.URISyntaxException;
31
 
import java.net.URL;
32
 
import java.util.HashMap;
33
 
import java.util.Map;
34
 
 
35
 
import javax.xml.parsers.DocumentBuilder;
36
 
import javax.xml.parsers.DocumentBuilderFactory;
37
 
 
38
 
import net.sf.xslthl.highlighters.AnnotationHighlighter;
39
 
import net.sf.xslthl.highlighters.HeredocHighlighter;
40
 
import net.sf.xslthl.highlighters.HexaDecimalHighlighter;
41
 
import net.sf.xslthl.highlighters.KeywordsHighlighter;
42
 
import net.sf.xslthl.highlighters.MultilineCommentHighlighter;
43
 
import net.sf.xslthl.highlighters.NestedMultilineCommentHighlighter;
44
 
import net.sf.xslthl.highlighters.NumberHighlighter;
45
 
import net.sf.xslthl.highlighters.OnelineCommentHighlighter;
46
 
import net.sf.xslthl.highlighters.RegexHighlighterEx;
47
 
import net.sf.xslthl.highlighters.StringHighlighter;
48
 
import net.sf.xslthl.highlighters.WordHighlighter;
49
 
import net.sf.xslthl.highlighters.XMLHighlighter;
50
 
 
51
 
import org.w3c.dom.Document;
52
 
import org.w3c.dom.Element;
53
 
import org.w3c.dom.NodeList;
54
 
 
55
 
/**
56
 
 * Contains the Xslthl configuration
57
 
 */
58
 
public class Config {
59
 
 
60
 
    /**
61
 
     * System property that defines the path to the configuration file
62
 
     */
63
 
    public static final String CONFIG_PROPERTY = "xslthl.config";
64
 
 
65
 
    /**
66
 
     * If set to true be verbose during loading of the configuration
67
 
     */
68
 
    public static final String VERBOSE_LOADING_PROPERTY = "xslthl.config.verbose";
69
 
 
70
 
    /**
71
 
     * Property set to disable external configuration loading
72
 
     */
73
 
    public static final String NO_EXTERNAL_PROPERTY = "xslthl.noexternal";
74
 
 
75
 
    /**
76
 
     * Instances per config file
77
 
     */
78
 
    private static final Map<String, Config> instances = new HashMap<String, Config>();
79
 
 
80
 
    /**
81
 
     * Registered highlighter classes
82
 
     */
83
 
    public static final Map<String, Class<? extends Highlighter>> highlighterClasses = new HashMap<String, Class<? extends Highlighter>>();
84
 
 
85
 
    static {
86
 
        highlighterClasses.put("multiline-comment",
87
 
                MultilineCommentHighlighter.class);
88
 
        highlighterClasses.put("nested-multiline-comment",
89
 
                NestedMultilineCommentHighlighter.class);
90
 
        highlighterClasses.put("oneline-comment",
91
 
                OnelineCommentHighlighter.class);
92
 
        highlighterClasses.put("string", StringHighlighter.class);
93
 
        highlighterClasses.put("heredoc", HeredocHighlighter.class);
94
 
        highlighterClasses.put("keywords", KeywordsHighlighter.class);
95
 
        highlighterClasses.put("annotation", AnnotationHighlighter.class);
96
 
        highlighterClasses.put("regex", RegexHighlighterEx.class);
97
 
        highlighterClasses.put("word", WordHighlighter.class);
98
 
        highlighterClasses.put("number", NumberHighlighter.class);
99
 
        highlighterClasses.put("hexnumber", HexaDecimalHighlighter.class);
100
 
        highlighterClasses.put("xml", XMLHighlighter.class);
101
 
    }
102
 
 
103
 
    /**
104
 
     * Prefix to use on created XML elements
105
 
     */
106
 
    protected String prefix = "http://xslthl.sf.net";
107
 
 
108
 
    /**
109
 
     * The namespace uri
110
 
     */
111
 
    protected String uri = "xslthl";
112
 
 
113
 
    /**
114
 
     * Registered highlighters
115
 
     */
116
 
    protected Map<String, MainHighlighter> highlighters = new HashMap<String, MainHighlighter>();
117
 
 
118
 
    protected boolean verbose;
119
 
 
120
 
    /**
121
 
     * Get the default config
122
 
     * 
123
 
     * @return
124
 
     */
125
 
    public static Config getInstance() {
126
 
        return getInstance(null);
127
 
    }
128
 
 
129
 
    /**
130
 
     * Get the config from a given file
131
 
     * 
132
 
     * @param filename
133
 
     * @return
134
 
     */
135
 
    public static Config getInstance(String filename) {
136
 
        String key = (filename == null) ? "" : filename;
137
 
        if (!instances.containsKey(key)) {
138
 
            Config conf = new Config(filename);
139
 
            instances.put(key, conf);
140
 
        }
141
 
        return instances.get(key);
142
 
    }
143
 
 
144
 
    /**
145
 
     * @return the prefix
146
 
     */
147
 
    public String getPrefix() {
148
 
        return prefix;
149
 
    }
150
 
 
151
 
    /**
152
 
     * @return the uri
153
 
     */
154
 
    public String getUri() {
155
 
        return uri;
156
 
    }
157
 
 
158
 
    /**
159
 
     * Get the highlighter for a given language id
160
 
     * 
161
 
     * @param id
162
 
     * @return
163
 
     */
164
 
    public MainHighlighter getMainHighlighter(String id) {
165
 
        if (id != null && id.length() > 0 && !highlighters.containsKey(id)) {
166
 
            if (!Boolean.getBoolean(NO_EXTERNAL_PROPERTY)) {
167
 
                // might be a URI
168
 
                String uri = null;
169
 
                try {
170
 
                    URI location = new URI(id);
171
 
                    if (location.getScheme() != null) {
172
 
                        uri = location.toString();
173
 
                    }
174
 
                } catch (URISyntaxException e) {
175
 
                }
176
 
                if (uri == null) {
177
 
                    File floc = new File(id);
178
 
                    if (floc.getAbsoluteFile().exists()) {
179
 
                        uri = floc.getAbsoluteFile().toURI().toString();
180
 
                    } else if (verbose) {
181
 
                        System.out
182
 
                                .println(String
183
 
                                        .format(
184
 
                                                "%s is not an known language id, valid URI, or existing file name",
185
 
                                                id));
186
 
                    }
187
 
                }
188
 
                if (uri != null) {
189
 
                    try {
190
 
                        MainHighlighter hl = loadHl(uri);
191
 
                        highlighters.put(id, hl);
192
 
                        return hl;
193
 
                    } catch (Exception e) {
194
 
                        System.err.println(String.format(
195
 
                                "Unable to load highlighter from %s: %s", id, e
196
 
                                        .getMessage()));
197
 
                    }
198
 
                }
199
 
            }
200
 
        }
201
 
        return highlighters.get(id);
202
 
    }
203
 
 
204
 
    /**
205
 
     * Load a highlighter
206
 
     * 
207
 
     * @param filename
208
 
     * @return
209
 
     * @throws Exception
210
 
     */
211
 
    protected MainHighlighter loadHl(String filename) throws Exception {
212
 
        MainHighlighter main = new MainHighlighter();
213
 
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
214
 
        DocumentBuilder builder = dbf.newDocumentBuilder();
215
 
        Document doc = builder.parse(filename);
216
 
        createHighlighters(main, doc.getDocumentElement().getElementsByTagName(
217
 
                "highlighter"));
218
 
        // backwards compatibility
219
 
        createHighlighters(main, doc.getDocumentElement().getElementsByTagName(
220
 
                "wholehighlighter"));
221
 
        return main;
222
 
    }
223
 
 
224
 
    /**
225
 
     * Creates the defined highlighters
226
 
     * 
227
 
     * @param main
228
 
     * @param list
229
 
     */
230
 
    protected void createHighlighters(MainHighlighter main, NodeList list) {
231
 
        for (int i = 0; i < list.getLength(); i++) {
232
 
            Element hl = (Element) list.item(i);
233
 
            Params params = new Params(hl);
234
 
            String type = hl.getAttribute("type");
235
 
            try {
236
 
                Class<? extends Highlighter> hlClass = highlighterClasses
237
 
                        .get(type);
238
 
                if (hlClass != null) {
239
 
                    Highlighter hlinstance = hlClass.newInstance();
240
 
                    hlinstance.init(params);
241
 
                    main.add(hlinstance);
242
 
                } else {
243
 
                    System.err.println(String.format("Unknown highlighter: %s",
244
 
                            type));
245
 
                }
246
 
            } catch (HighlighterConfigurationException e) {
247
 
                System.err.println(String.format(
248
 
                        "Invalid configuration for highlighter %s: %s", type, e
249
 
                                .getMessage()));
250
 
            } catch (InstantiationException e) {
251
 
                System.err.println(String.format(
252
 
                        "Error constructing highlighter %s: %s", type, e
253
 
                                .getMessage()));
254
 
            } catch (IllegalAccessException e) {
255
 
                System.err.println(String.format(
256
 
                        "IError constructing highlighter %s: %s", type, e
257
 
                                .getMessage()));
258
 
            }
259
 
        }
260
 
    }
261
 
 
262
 
    protected Config() {
263
 
        this(null);
264
 
    }
265
 
 
266
 
    protected Config(String configFilename) {
267
 
        verbose = Boolean.getBoolean(VERBOSE_LOADING_PROPERTY);
268
 
        if (verbose) {
269
 
            System.out.println("Initializing xslthl " + Version.getVersion());
270
 
        }
271
 
 
272
 
        try {
273
 
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
274
 
            DocumentBuilder builder = dbf.newDocumentBuilder();
275
 
            if (configFilename == null || "".equals(configFilename)) {
276
 
                if (verbose) {
277
 
                    System.out
278
 
                            .println("No config file specified, falling back to default behavior");
279
 
                }
280
 
                if (System.getProperty(CONFIG_PROPERTY) != null) {
281
 
                    configFilename = System.getProperty(CONFIG_PROPERTY);
282
 
                } else {
283
 
                    configFilename = "xslthl-config.xml";
284
 
                }
285
 
            }
286
 
            System.out.println("Loading Xslthl configuration from "
287
 
                    + configFilename + "...");
288
 
            Document doc = builder.parse(configFilename);
289
 
            NodeList hls = doc.getDocumentElement().getElementsByTagName(
290
 
                    "highlighter");
291
 
            Map<String, MainHighlighter> fileMapping = new HashMap<String, MainHighlighter>();
292
 
            for (int i = 0; i < hls.getLength(); i++) {
293
 
                Element hl = (Element) hls.item(i);
294
 
                String id = hl.getAttribute("id");
295
 
 
296
 
                if (highlighters.containsKey(id)) {
297
 
                    System.out
298
 
                            .println(String
299
 
                                    .format(
300
 
                                            "Warning: highlighter with id '%s' already exists!",
301
 
                                            id));
302
 
                }
303
 
 
304
 
                String filename = hl.getAttribute("file");
305
 
                String absFilename = new URL(new URL(configFilename), filename)
306
 
                        .toString();
307
 
                if (fileMapping.containsKey(absFilename)) {
308
 
                    // no need to load the same file twice.
309
 
                    if (verbose) {
310
 
                        System.out.println("Reusing loaded highlighter for "
311
 
                                + id + " from " + absFilename + "...");
312
 
                    }
313
 
                    highlighters.put(id, fileMapping.get(absFilename));
314
 
                    continue;
315
 
                }
316
 
                if (verbose) {
317
 
                    System.out.print("Loading " + id + " highligter from "
318
 
                            + absFilename + "...");
319
 
                }
320
 
                try {
321
 
                    MainHighlighter mhl = loadHl(absFilename);
322
 
                    highlighters.put(id, mhl);
323
 
                    if (verbose) {
324
 
                        System.out.println(" OK");
325
 
                        fileMapping.put(absFilename, mhl);
326
 
                    }
327
 
                } catch (Exception e) {
328
 
                    if (verbose) {
329
 
                        System.out.println(" error: " + e.getMessage());
330
 
                    } else {
331
 
                        System.err.println("Error loading highlighter from "
332
 
                                + absFilename + ": " + e.getMessage());
333
 
                    }
334
 
                }
335
 
            }
336
 
            NodeList prefixNode = doc.getDocumentElement()
337
 
                    .getElementsByTagName("namespace");
338
 
            if (prefixNode.getLength() == 1) {
339
 
                Element e = (Element) prefixNode.item(0);
340
 
                prefix = e.getAttribute("prefix");
341
 
                uri = e.getAttribute("uri");
342
 
            }
343
 
        } catch (Exception e) {
344
 
            System.err
345
 
                    .println("XSLT Highlighter: Cannot read xslthl-config.xml, no custom highlighters will be available.");
346
 
        }
347
 
 
348
 
        if (!highlighters.containsKey("xml")) {
349
 
            // add the built-in XML highlighting if it wasn't overloaded
350
 
            MainHighlighter xml = new MainHighlighter();
351
 
            xml.add(new XMLHighlighter());
352
 
            highlighters.put("xml", xml);
353
 
        }
354
 
    }
355
 
}