1 /*******************************************************************************
2 * Copyright (c) 2000, 2004 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.internal.corext.template.php;
14 import java.io.FileInputStream;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.OutputStream;
19 import java.util.ArrayList;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.MissingResourceException;
23 import java.util.ResourceBundle;
25 import javax.xml.parsers.DocumentBuilder;
26 import javax.xml.parsers.DocumentBuilderFactory;
27 import javax.xml.parsers.ParserConfigurationException;
28 import javax.xml.transform.OutputKeys;
29 import javax.xml.transform.Transformer;
30 import javax.xml.transform.TransformerException;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.dom.DOMSource;
33 import javax.xml.transform.stream.StreamResult;
35 import org.w3c.dom.Attr;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.NamedNodeMap;
38 import org.w3c.dom.Node;
39 import org.w3c.dom.NodeList;
40 import org.w3c.dom.Text;
42 import org.xml.sax.InputSource;
43 import org.xml.sax.SAXException;
45 import org.eclipse.core.runtime.CoreException;
46 import org.eclipse.core.runtime.IStatus;
47 import org.eclipse.core.runtime.Status;
49 import org.eclipse.jface.text.templates.TemplateContextType;
50 import org.eclipse.jface.text.templates.ContextTypeRegistry;
51 import org.eclipse.jface.text.templates.Template;
52 import org.eclipse.jface.text.templates.TemplateException;
55 * <code>TemplateSet</code> manages a collection of templates and makes them
58 * @deprecated use TemplateStore instead
61 public class TemplateSet {
63 private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
64 private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
65 private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$
67 private List fTemplates= new ArrayList();
68 private String fTemplateTag;
70 private static final int TEMPLATE_PARSE_EXCEPTION= 10002;
71 private static final int TEMPLATE_IO_EXCEPTION= 10005;
72 private ContextTypeRegistry fRegistry;
74 public TemplateSet(String templateTag, ContextTypeRegistry registry) {
75 fTemplateTag= templateTag;
80 * Convenience method for reading templates from a file.
83 * @param allowDuplicates
85 * @see #addFromStream(InputStream, boolean, boolean, ResourceBundle)
86 * @throws CoreException
88 public void addFromFile(File file, boolean allowDuplicates, ResourceBundle bundle) throws CoreException {
89 InputStream stream= null;
92 stream= new FileInputStream(file);
93 addFromStream(stream, allowDuplicates, false, bundle);
95 } catch (IOException e) {
96 throwReadException(e);
102 } catch (IOException e) {}
106 public String getTemplateTag() {
112 * Reads templates from a XML stream and adds them to the templates
115 * @param allowDuplicates
117 * @param doTranslations
118 * @see #addFromStream(InputStream, boolean, boolean, ResourceBundle)
119 * @throws CoreException
121 public void addFromStream(InputStream stream, boolean allowDuplicates, boolean doTranslations, ResourceBundle bundle) throws CoreException {
123 DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
124 DocumentBuilder parser= factory.newDocumentBuilder();
125 Document document= parser.parse(new InputSource(stream));
127 NodeList elements= document.getElementsByTagName(getTemplateTag());
129 int count= elements.getLength();
130 for (int i= 0; i != count; i++) {
131 Node node= elements.item(i);
132 NamedNodeMap attributes= node.getAttributes();
134 if (attributes == null)
137 String name= getAttributeValue(attributes, NAME_ATTRIBUTE);
138 String description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE);
139 if (name == null || description == null)
142 if (doTranslations) {
143 description= translateString(description, bundle);
145 String context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE);
147 if (name == null || description == null || context == null)
148 throw new SAXException(JavaTemplateMessages.getString("TemplateSet.error.missing.attribute")); //$NON-NLS-1$
150 StringBuffer buffer= new StringBuffer();
151 NodeList children= node.getChildNodes();
152 for (int j= 0; j != children.getLength(); j++) {
153 String value= children.item(j).getNodeValue();
155 buffer.append(value);
157 String pattern= buffer.toString().trim();
158 if (doTranslations) {
159 pattern= translateString(pattern, bundle);
162 Template template= new Template(name, description, context, pattern);
164 String message= validateTemplate(template);
165 if (message == null) {
166 if (!allowDuplicates) {
167 Template[] templates= getTemplates(name);
168 for (int k= 0; k < templates.length; k++) {
169 remove(templates[k]);
174 throwReadException(null);
177 } catch (ParserConfigurationException e) {
178 throwReadException(e);
179 } catch (IOException e) {
180 throwReadException(e);
181 } catch (SAXException e) {
182 throwReadException(e);
186 private String translateString(String str, ResourceBundle bundle) {
187 int idx= str.indexOf('%');
191 StringBuffer buf= new StringBuffer();
194 buf.append(str.substring(k, idx));
195 for (k= idx + 1; k < str.length() && !Character.isWhitespace(str.charAt(k)); k++) {
198 String key= str.substring(idx + 1, k);
199 buf.append(getBundleString(key, bundle));
200 idx= str.indexOf('%', k);
202 buf.append(str.substring(k));
203 return buf.toString();
206 private String getBundleString(String key, ResourceBundle bundle) {
207 if (bundle != null) {
209 return bundle.getString(key);
210 } catch (MissingResourceException e) {
211 return '!' + key + '!';
214 return JavaTemplateMessages.getString(key); // default messages
217 protected String validateTemplate(Template template) {
218 TemplateContextType type= fRegistry.getContextType(template.getContextTypeId());
220 return "Unknown context type: " + template.getContextTypeId(); //$NON-NLS-1$
223 type.validate(template.getPattern());
225 } catch (TemplateException e) {
226 return e.getMessage();
230 private String getAttributeValue(NamedNodeMap attributes, String name) {
231 Node node= attributes.getNamedItem(name);
235 : node.getNodeValue();
239 * Convenience method for saving to a file.
241 * @see #saveToStream(OutputStream)
243 public void saveToFile(File file) throws CoreException {
244 OutputStream stream= null;
247 stream= new FileOutputStream(file);
248 saveToStream(stream);
250 } catch (IOException e) {
251 throwWriteException(e);
257 } catch (IOException e) {}
262 * Saves the template set as XML.
264 public void saveToStream(OutputStream stream) throws CoreException {
266 DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
267 DocumentBuilder builder= factory.newDocumentBuilder();
268 Document document= builder.newDocument();
270 Node root= document.createElement("templates"); //$NON-NLS-1$
271 document.appendChild(root);
273 for (int i= 0; i != fTemplates.size(); i++) {
274 Template template= (Template) fTemplates.get(i);
276 Node node= document.createElement(getTemplateTag());
277 root.appendChild(node);
279 NamedNodeMap attributes= node.getAttributes();
281 Attr name= document.createAttribute(NAME_ATTRIBUTE);
282 name.setValue(template.getName());
283 attributes.setNamedItem(name);
285 Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
286 description.setValue(template.getDescription());
287 attributes.setNamedItem(description);
289 Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
290 context.setValue(template.getContextTypeId());
291 attributes.setNamedItem(context);
293 Text pattern= document.createTextNode(template.getPattern());
294 node.appendChild(pattern);
298 Transformer transformer=TransformerFactory.newInstance().newTransformer();
299 transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
300 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
301 DOMSource source = new DOMSource(document);
302 StreamResult result = new StreamResult(stream);
304 transformer.transform(source, result);
306 } catch (ParserConfigurationException e) {
307 throwWriteException(e);
308 } catch (TransformerException e) {
309 throwWriteException(e);
313 private static void throwReadException(Throwable t) throws CoreException {
315 if (t instanceof SAXException)
316 code= TEMPLATE_PARSE_EXCEPTION;
318 code= TEMPLATE_IO_EXCEPTION;
319 // IStatus status= JavaUIStatus.createError(code, TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
320 // throw new JavaUIException(status);
321 throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.jface.text", code, JavaTemplateMessages.getString("TemplateSet.error.read"), t)); //$NON-NLS-1$ //$NON-NLS-2$
324 private static void throwWriteException(Throwable t) throws CoreException {
325 // IStatus status= JavaUIStatus.createError(IJavaStatusConstants.TEMPLATE_IO_EXCEPTION,
326 // TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
327 // throw new JavaUIException(status);
328 throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.jface.text", TEMPLATE_IO_EXCEPTION, JavaTemplateMessages.getString("TemplateSet.error.write"), t)); //$NON-NLS-1$ //$NON-NLS-2$
332 * Adds a template to the set.
334 public void add(Template template) {
335 if (exists(template))
336 return; // ignore duplicate
338 fTemplates.add(template);
341 private boolean exists(Template template) {
342 for (Iterator iterator = fTemplates.iterator(); iterator.hasNext();) {
343 Template anotherTemplate = (Template) iterator.next();
345 if (template.equals(anotherTemplate))
353 * Removes a template to the set.
355 public void remove(Template template) {
356 fTemplates.remove(template);
362 public void clear() {
367 * Returns all templates.
369 public Template[] getTemplates() {
370 return (Template[]) fTemplates.toArray(new Template[fTemplates.size()]);
374 * Returns all templates with a given name.
376 public Template[] getTemplates(String name) {
377 ArrayList res= new ArrayList();
378 for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) {
379 Template curr= (Template) iterator.next();
380 if (curr.getName().equals(name)) {
384 return (Template[]) res.toArray(new Template[res.size()]);
388 * Returns the first templates with the given name.
390 public Template getFirstTemplate(String name) {
391 for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) {
392 Template curr= (Template) iterator.next();
393 if (curr.getName().equals(name)) {