KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > corext > template > java > TemplateSet


1 /*******************************************************************************
2  * Copyright (c) 2000, 2005 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.jdt.internal.corext.template.java;
12
13 import java.io.File JavaDoc;
14 import java.io.FileInputStream JavaDoc;
15 import java.io.FileOutputStream JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.io.InputStream JavaDoc;
18 import java.io.OutputStream JavaDoc;
19 import java.util.ArrayList JavaDoc;
20 import java.util.Iterator JavaDoc;
21 import java.util.List JavaDoc;
22
23 import javax.xml.parsers.DocumentBuilder JavaDoc;
24 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
25 import javax.xml.parsers.ParserConfigurationException JavaDoc;
26 import javax.xml.transform.OutputKeys JavaDoc;
27 import javax.xml.transform.Transformer JavaDoc;
28 import javax.xml.transform.TransformerException JavaDoc;
29 import javax.xml.transform.TransformerFactory JavaDoc;
30 import javax.xml.transform.dom.DOMSource JavaDoc;
31 import javax.xml.transform.stream.StreamResult JavaDoc;
32
33 import org.eclipse.core.runtime.CoreException;
34 import org.eclipse.core.runtime.IStatus;
35 import org.eclipse.core.runtime.Status;
36
37 import org.eclipse.jface.text.templates.ContextTypeRegistry;
38 import org.eclipse.jface.text.templates.Template;
39 import org.eclipse.jface.text.templates.TemplateContextType;
40 import org.eclipse.jface.text.templates.TemplateException;
41
42 import org.w3c.dom.Attr JavaDoc;
43 import org.w3c.dom.Document JavaDoc;
44 import org.w3c.dom.NamedNodeMap JavaDoc;
45 import org.w3c.dom.Node JavaDoc;
46 import org.w3c.dom.NodeList JavaDoc;
47 import org.w3c.dom.Text JavaDoc;
48 import org.xml.sax.InputSource JavaDoc;
49 import org.xml.sax.SAXException JavaDoc;
50
51 /**
52  * <code>TemplateSet</code> manages a collection of templates and makes them
53  * persistent.
54  *
55  * @deprecated use TemplateStore instead
56  * @since 3.0
57  */

58 public class TemplateSet {
59
60     private static final String JavaDoc NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
61
private static final String JavaDoc DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
62
private static final String JavaDoc CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$
63

64     private List JavaDoc fTemplates= new ArrayList JavaDoc();
65     private String JavaDoc fTemplateTag;
66     
67     private static final int TEMPLATE_PARSE_EXCEPTION= 10002;
68     private static final int TEMPLATE_IO_EXCEPTION= 10005;
69     private ContextTypeRegistry fRegistry;
70     
71     public TemplateSet(String JavaDoc templateTag, ContextTypeRegistry registry) {
72         fTemplateTag= templateTag;
73         fRegistry= registry;
74     }
75     
76     /**
77      * Convenience method for reading templates from a file.
78      *
79      * @param file
80      * @param allowDuplicates
81      * @see #addFromStream(InputStream, boolean)
82      * @throws CoreException
83      */

84     public void addFromFile(File JavaDoc file, boolean allowDuplicates) throws CoreException {
85         InputStream JavaDoc stream= null;
86
87         try {
88             stream= new FileInputStream JavaDoc(file);
89             addFromStream(stream, allowDuplicates);
90
91         } catch (IOException JavaDoc e) {
92             throwReadException(e);
93
94         } finally {
95             try {
96                 if (stream != null)
97                     stream.close();
98             } catch (IOException JavaDoc e) {
99                 // just exit
100
}
101         }
102     }
103     
104     public String JavaDoc getTemplateTag() {
105         return fTemplateTag;
106     }
107     
108
109     /**
110      * Reads templates from a XML stream and adds them to the templates
111      *
112      * @param stream
113      * @param allowDuplicates
114      * @throws CoreException
115      */

116     public void addFromStream(InputStream JavaDoc stream, boolean allowDuplicates) throws CoreException {
117         try {
118             DocumentBuilderFactory JavaDoc factory= DocumentBuilderFactory.newInstance();
119             DocumentBuilder JavaDoc parser= factory.newDocumentBuilder();
120             Document JavaDoc document= parser.parse(new InputSource JavaDoc(stream));
121             
122             NodeList JavaDoc elements= document.getElementsByTagName(getTemplateTag());
123             
124             int count= elements.getLength();
125             for (int i= 0; i != count; i++) {
126                 Node JavaDoc node= elements.item(i);
127                 NamedNodeMap JavaDoc attributes= node.getAttributes();
128
129                 if (attributes == null)
130                     continue;
131
132                 String JavaDoc name= getAttributeValue(attributes, NAME_ATTRIBUTE);
133                 String JavaDoc description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE);
134                 if (name == null || description == null)
135                     continue;
136                 
137                 String JavaDoc context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE);
138
139                 if (name == null || description == null || context == null)
140                     throw new SAXException JavaDoc(JavaTemplateMessages.TemplateSet_error_missing_attribute);
141
142                 StringBuffer JavaDoc buffer= new StringBuffer JavaDoc();
143                 NodeList JavaDoc children= node.getChildNodes();
144                 for (int j= 0; j != children.getLength(); j++) {
145                     String JavaDoc value= children.item(j).getNodeValue();
146                     if (value != null)
147                         buffer.append(value);
148                 }
149                 String JavaDoc pattern= buffer.toString().trim();
150
151                 Template template= new Template(name, description, context, pattern);
152                 
153                 String JavaDoc message= validateTemplate(template);
154                 if (message == null) {
155                     if (!allowDuplicates) {
156                         Template[] templates= getTemplates(name);
157                         for (int k= 0; k < templates.length; k++) {
158                             remove(templates[k]);
159                         }
160                     }
161                     add(template);
162                 } else {
163                     throwReadException(null);
164                 }
165             }
166         } catch (ParserConfigurationException JavaDoc e) {
167             throwReadException(e);
168         } catch (IOException JavaDoc e) {
169             throwReadException(e);
170         } catch (SAXException JavaDoc e) {
171             throwReadException(e);
172         }
173     }
174     
175     protected String JavaDoc validateTemplate(Template template) {
176         TemplateContextType type= fRegistry.getContextType(template.getContextTypeId());
177         if (type == null) {
178             return "Unknown context type: " + template.getContextTypeId(); //$NON-NLS-1$
179
}
180         try {
181             type.validate(template.getPattern());
182             return null;
183         } catch (TemplateException e) {
184             return e.getMessage();
185         }
186     }
187     
188     private String JavaDoc getAttributeValue(NamedNodeMap JavaDoc attributes, String JavaDoc name) {
189         Node JavaDoc node= attributes.getNamedItem(name);
190
191         return node == null
192             ? null
193             : node.getNodeValue();
194     }
195
196     /**
197      * Convenience method for saving to a file.
198      *
199      * @param file the file
200      * @throws CoreException in case the save operation fails
201      * @see #saveToStream(OutputStream)
202      */

203     public void saveToFile(File JavaDoc file) throws CoreException {
204         OutputStream JavaDoc stream= null;
205
206         try {
207             stream= new FileOutputStream JavaDoc(file);
208             saveToStream(stream);
209
210         } catch (IOException JavaDoc e) {
211             throwWriteException(e);
212
213         } finally {
214             try {
215                 if (stream != null)
216                     stream.close();
217             } catch (IOException JavaDoc e) {
218                 // just exit
219
}
220         }
221     }
222         
223     /**
224      * Saves the template set as XML.
225      *
226      * @param stream the stream
227      * @throws CoreException in case the save operation fails
228      */

229     public void saveToStream(OutputStream JavaDoc stream) throws CoreException {
230         try {
231             DocumentBuilderFactory JavaDoc factory= DocumentBuilderFactory.newInstance();
232             DocumentBuilder JavaDoc builder= factory.newDocumentBuilder();
233             Document JavaDoc document= builder.newDocument();
234
235             Node JavaDoc root= document.createElement("templates"); //$NON-NLS-1$
236
document.appendChild(root);
237             
238             for (int i= 0; i != fTemplates.size(); i++) {
239                 Template template= (Template) fTemplates.get(i);
240                 
241                 Node JavaDoc node= document.createElement(getTemplateTag());
242                 root.appendChild(node);
243                 
244                 NamedNodeMap JavaDoc attributes= node.getAttributes();
245                 
246                 Attr JavaDoc name= document.createAttribute(NAME_ATTRIBUTE);
247                 name.setValue(template.getName());
248                 attributes.setNamedItem(name);
249     
250                 Attr JavaDoc description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
251                 description.setValue(template.getDescription());
252                 attributes.setNamedItem(description);
253     
254                 Attr JavaDoc context= document.createAttribute(CONTEXT_ATTRIBUTE);
255                 context.setValue(template.getContextTypeId());
256                 attributes.setNamedItem(context);
257
258                 Text JavaDoc pattern= document.createTextNode(template.getPattern());
259                 node.appendChild(pattern);
260             }
261             
262             
263             Transformer JavaDoc transformer=TransformerFactory.newInstance().newTransformer();
264             transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
265
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
266
DOMSource JavaDoc source = new DOMSource JavaDoc(document);
267             StreamResult JavaDoc result = new StreamResult JavaDoc(stream);
268
269             transformer.transform(source, result);
270
271         } catch (ParserConfigurationException JavaDoc e) {
272             throwWriteException(e);
273         } catch (TransformerException JavaDoc e) {
274             throwWriteException(e);
275         }
276     }
277
278     private static void throwReadException(Throwable JavaDoc t) throws CoreException {
279         int code;
280         if (t instanceof SAXException JavaDoc)
281             code= TEMPLATE_PARSE_EXCEPTION;
282         else
283             code= TEMPLATE_IO_EXCEPTION;
284 // IStatus status= JavaUIStatus.createError(code, TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
285
// throw new JavaUIException(status);
286
throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.jface.text", code, JavaTemplateMessages.TemplateSet_error_read, t)); //$NON-NLS-1$
287
}
288     
289     private static void throwWriteException(Throwable JavaDoc t) throws CoreException {
290 // IStatus status= JavaUIStatus.createError(IJavaStatusConstants.TEMPLATE_IO_EXCEPTION,
291
// TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
292
// throw new JavaUIException(status);
293
throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.jface.text", TEMPLATE_IO_EXCEPTION, JavaTemplateMessages.TemplateSet_error_write, t)); //$NON-NLS-1$
294
}
295
296     /**
297      * Adds a template to the set.
298      *
299      * @param template the template to add to the set
300      */

301     public void add(Template template) {
302         if (exists(template))
303             return; // ignore duplicate
304

305         fTemplates.add(template);
306     }
307
308     private boolean exists(Template template) {
309         for (Iterator JavaDoc iterator = fTemplates.iterator(); iterator.hasNext();) {
310             Template anotherTemplate = (Template) iterator.next();
311
312             if (template.equals(anotherTemplate))
313                 return true;
314         }
315         
316         return false;
317     }
318     
319     /**
320      * Removes a template to the set.
321      *
322      * @param template the template to remove from the set
323      */

324     public void remove(Template template) {
325         fTemplates.remove(template);
326     }
327
328     /**
329      * Empties the set.
330      */

331     public void clear() {
332         fTemplates.clear();
333     }
334     
335     /**
336      * Returns all templates.
337      *
338      * @return all templates
339      */

340     public Template[] getTemplates() {
341         return (Template[]) fTemplates.toArray(new Template[fTemplates.size()]);
342     }
343     
344     /**
345      * Returns all templates with a given name.
346      *
347      * @param name the template name
348      * @return the templates with the given name
349      */

350     public Template[] getTemplates(String JavaDoc name) {
351         ArrayList JavaDoc res= new ArrayList JavaDoc();
352         for (Iterator JavaDoc iterator= fTemplates.iterator(); iterator.hasNext();) {
353             Template curr= (Template) iterator.next();
354             if (curr.getName().equals(name)) {
355                 res.add(curr);
356             }
357         }
358         return (Template[]) res.toArray(new Template[res.size()]);
359     }
360     
361     /**
362      * Returns the first templates with the given name.
363      *
364      * @param name the template name
365      * @return the first template with the given name
366      */

367     public Template getFirstTemplate(String JavaDoc name) {
368         for (Iterator JavaDoc iterator= fTemplates.iterator(); iterator.hasNext();) {
369             Template curr= (Template) iterator.next();
370             if (curr.getName().equals(name)) {
371                 return curr;
372             }
373         }
374         return null;
375     }
376     
377 }
378
379
Popular Tags