*** empty log message ***
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpdt / internal / corext / template / TemplateSet.java
1 /*
2  * (c) Copyright IBM Corp. 2000, 2001.
3  * All Rights Reserved.
4  */
5 package net.sourceforge.phpdt.internal.corext.template;
6
7 import java.io.File;
8 import java.io.FileInputStream;
9 import java.io.FileOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.OutputStream;
13 import java.util.ArrayList;
14 import java.util.Arrays;
15 import java.util.Comparator;
16 import java.util.Iterator;
17 import java.util.List;
18
19 import javax.xml.parsers.DocumentBuilder;
20 import javax.xml.parsers.DocumentBuilderFactory;
21 import javax.xml.parsers.ParserConfigurationException;
22
23 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
24
25 import org.apache.xml.serialize.OutputFormat;
26 import org.apache.xml.serialize.Serializer;
27 import org.apache.xml.serialize.SerializerFactory;
28 import org.eclipse.core.runtime.CoreException;
29 import org.w3c.dom.Attr;
30 import org.w3c.dom.Document;
31 import org.w3c.dom.NamedNodeMap;
32 import org.w3c.dom.Node;
33 import org.w3c.dom.NodeList;
34 import org.w3c.dom.Text;
35 import org.xml.sax.InputSource;
36 import org.xml.sax.SAXException;
37
38 /**
39  * <code>TemplateSet</code> manages a collection of templates and makes them
40  * persistent.
41  */
42 public class TemplateSet {
43         
44         private static class TemplateComparator implements Comparator {
45                 public int compare(Object arg0, Object arg1) {
46                         if (arg0 == arg1)
47                                 return 0;
48                         
49                         if (arg0 == null)
50                                 return -1;
51                                 
52                         Template template0= (Template) arg0;
53                         Template template1= (Template) arg1;
54                         
55                         return template0.getName().compareTo(template1.getName());
56                 }
57         }
58
59         private static final String TEMPLATE_TAG= "template"; //$NON-NLS-1$
60         private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
61         private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
62         private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$
63         private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$
64
65         private List fTemplates= new ArrayList();
66         private Comparator fTemplateComparator= new TemplateComparator();
67         private Template[] fSortedTemplates= new Template[0];
68         
69         /**
70          * Convenience method for reading templates from a file.
71          * 
72          * @see #addFromStream(InputStream)
73          */
74         public void addFromFile(File file) throws CoreException {
75                 InputStream stream= null;
76
77                 try {
78                         stream= new FileInputStream(file);
79                         addFromStream(stream);
80
81                 } catch (IOException e) {
82                         throwReadException(e);
83
84                 } finally {
85                         try {
86                                 if (stream != null)
87                                         stream.close();
88                         } catch (IOException e) {}
89                 }               
90         }
91
92         /**
93          * Reads templates from a XML stream and adds them to the template set.
94          */     
95         public void addFromStream(InputStream stream) throws CoreException {
96                 try {
97                         DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
98                         DocumentBuilder parser= factory.newDocumentBuilder();           
99                         Document document= parser.parse(new InputSource(stream));
100                         NodeList elements= document.getElementsByTagName(TEMPLATE_TAG);
101                         
102                         int count= elements.getLength();
103                         for (int i= 0; i != count; i++) {
104                                 Node node= elements.item(i);                                    
105                                 NamedNodeMap attributes= node.getAttributes();
106
107                                 if (attributes == null)
108                                         continue;
109
110                                 String name= getAttributeValue(attributes, NAME_ATTRIBUTE);
111                                 String description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE);
112                                 String context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE);
113                                 Node enabledNode= attributes.getNamedItem(ENABLED_ATTRIBUTE);
114
115                                 if (name == null || description == null || context == null)
116                                         throw new SAXException(TemplateMessages.getString("TemplateSet.error.missing.attribute")); //$NON-NLS-1$
117
118                                 boolean enabled= (enabledNode == null) || (enabledNode.getNodeValue().equals("true")); //$NON-NLS-1$
119
120                                 StringBuffer buffer= new StringBuffer();
121                                 NodeList children= node.getChildNodes();
122                                 for (int j= 0; j != children.getLength(); j++) {
123                                         String value= children.item(j).getNodeValue();
124                                         if (value != null)
125                                                 buffer.append(value);
126                                 }
127                                 String pattern= buffer.toString().trim();
128
129                                 Template template= new Template(name, description, context, pattern);   
130                                 template.setEnabled(enabled);
131                                 add(template);
132                         }
133         
134                         sort();
135
136                 } catch (ParserConfigurationException e) {
137                         throwReadException(e);
138                 } catch (IOException e) {
139                         throwReadException(e);
140                 } catch (SAXException e) {
141                         throwReadException(e);
142                 }
143         }
144         
145         private String getAttributeValue(NamedNodeMap attributes, String name) {
146                 Node node= attributes.getNamedItem(name);
147
148                 return node == null
149                         ? null
150                         : node.getNodeValue();
151         }
152
153         /**
154          * Convenience method for saving to a file.
155          * 
156          * @see #saveToStream(OutputStream)
157          */
158         public void saveToFile(File file) throws CoreException {
159                 OutputStream stream= null;
160
161                 try {
162                         stream= new FileOutputStream(file);
163                         saveToStream(stream);
164
165                 } catch (IOException e) {
166                         throwWriteException(e);
167
168                 } finally {
169                         try {
170                                 if (stream != null)
171                                         stream.close();
172                         } catch (IOException e) {}
173                 }
174         }
175                 
176         /**
177          * Saves the template set as XML.
178          */
179         public void saveToStream(OutputStream stream) throws CoreException {
180                 try {
181                         DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
182                         DocumentBuilder builder= factory.newDocumentBuilder();          
183                         Document document= builder.newDocument();
184
185                         Node root= document.createElement("templates"); // $NON-NLS-1$ //$NON-NLS-1$
186                         document.appendChild(root);
187                         
188                         for (int i= 0; i != fTemplates.size(); i++) {
189                                 Template template= (Template) fTemplates.get(i);
190                                 
191                                 Node node= document.createElement("template"); // $NON-NLS-1$ //$NON-NLS-1$
192                                 root.appendChild(node);
193                                 
194                                 NamedNodeMap attributes= node.getAttributes();
195                                 
196                                 Attr name= document.createAttribute(NAME_ATTRIBUTE);
197                                 name.setValue(template.getName());
198                                 attributes.setNamedItem(name);
199         
200                                 Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
201                                 description.setValue(template.getDescription());
202                                 attributes.setNamedItem(description);
203         
204                                 Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
205                                 context.setValue(template.getContextTypeName());
206                                 attributes.setNamedItem(context);                       
207
208                                 Attr enabled= document.createAttribute(ENABLED_ATTRIBUTE);
209                                 enabled.setValue(template.isEnabled() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
210                                 attributes.setNamedItem(enabled);
211                                 
212                                 Text pattern= document.createTextNode(template.getPattern());
213                                 node.appendChild(pattern);                      
214                         }               
215                         
216                         OutputFormat format = new OutputFormat();
217                         format.setPreserveSpace(true);
218                         Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format); //$NON-NLS-1$
219                         serializer.asDOMSerializer().serialize(document);
220
221                 } catch (ParserConfigurationException e) {
222                         throwWriteException(e);
223                 } catch (IOException e) {
224                         throwWriteException(e);
225                 }               
226         }
227
228         private static void throwReadException(Throwable t) throws CoreException {
229     PHPeclipsePlugin.log(t);
230 //              IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
231 //                      TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
232 //              throw new JavaUIException(status);
233         }
234         
235         private static void throwWriteException(Throwable t) throws CoreException {
236     PHPeclipsePlugin.log(t);
237 //              IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
238 //                      TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
239 //              throw new JavaUIException(status);
240         }
241
242         /**
243          * Adds a template to the set.
244          */
245         public void add(Template template) {
246                 if (exists(template))
247                         return; // ignore duplicate
248                 
249                 fTemplates.add(template);
250                 sort();
251         }
252
253         private boolean exists(Template template) {
254                 for (Iterator iterator = fTemplates.iterator(); iterator.hasNext();) {
255                         Template anotherTemplate = (Template) iterator.next();
256
257                         if (template.equals(anotherTemplate))
258                                 return true;
259                 }
260                 
261                 return false;
262         }
263         
264         /**
265          * Removes a template to the set.
266          */     
267         public void remove(Template template) {
268                 fTemplates.remove(template);
269                 sort();
270         }
271
272         /**
273          * Empties the set.
274          */             
275         public void clear() {
276                 fTemplates.clear();
277                 sort();
278         }
279         
280         /**
281          * Returns all templates.
282          */
283         public Template[] getTemplates() {
284                 return (Template[]) fTemplates.toArray(new Template[fTemplates.size()]);
285         }
286         
287         /**
288          * Returns all templates with a given name.
289          */
290         public Template[] getTemplates(String name) {
291                 ArrayList res= new ArrayList();
292                 for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) {
293                         Template curr= (Template) iterator.next();
294                         if (curr.getName().equals(name)) {
295                                 res.add(curr);
296                         }
297                 }
298                 return (Template[]) res.toArray(new Template[res.size()]);
299         }       
300         
301         private void sort() {
302                 fSortedTemplates= (Template[]) fTemplates.toArray(new Template[fTemplates.size()]);
303                 Arrays.sort(fSortedTemplates, fTemplateComparator);
304         }
305         
306 }
307