Config editor through XML file
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / PHPSyntaxRdr.java
1 package net.sourceforge.phpeclipse.phpeditor;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9 import java.io.UnsupportedEncodingException;
10 import java.util.Vector;
11
12 import javax.xml.parsers.DocumentBuilder;
13 import javax.xml.parsers.DocumentBuilderFactory;
14 import javax.xml.parsers.ParserConfigurationException;
15
16 import org.apache.xml.serialize.OutputFormat;
17 import org.apache.xml.serialize.Serializer;
18 import org.apache.xml.serialize.SerializerFactory;
19 import org.eclipse.core.runtime.CoreException;
20 import org.eclipse.core.runtime.IPath;
21 import org.eclipse.jface.preference.IPreferenceStore;
22 import org.w3c.dom.Attr;
23 import org.w3c.dom.Document;
24 import org.w3c.dom.NamedNodeMap;
25 import org.w3c.dom.Node;
26 import org.w3c.dom.NodeList;
27 import org.xml.sax.InputSource;
28 import org.xml.sax.SAXException;
29
30 import net.sourceforge.phpeclipse.IPreferenceConstants;
31 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
32 import net.sourceforge.phpeclipse.phpeditor.php.PHPConstant;
33 import net.sourceforge.phpeclipse.phpeditor.php.PHPElement;
34 import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction;
35 import net.sourceforge.phpeclipse.phpeditor.php.PHPKeyword;
36 import net.sourceforge.phpeclipse.phpeditor.php.PHPType;
37
38 /**
39  * <code>PHPSyntaxRdr</code> reads PHP specifics from an XML file (eg. keywords) 
40  */
41
42 public class PHPSyntaxRdr {
43   private static final String PHPDEFAULT_FILE = "default-phpsyntax.xml"; //$NON-NLS-1$
44   private static final String PHPSYNTAX_FILE = "phpsyntax.xml"; //$NON-NLS-1$
45   private static final String USERSYNTAX_FILE = "usersyntax.xml"; //$NON-NLS-1$
46   private static final String USERDEFAULT_FILE = "default-usersyntax.xml"; //$NON-NLS-1$
47   private static final String PHPSYNTAX_TAG = "phpsyntax";
48   private static final String KEYWORD_ATTR = "keyword";
49   private static final String TYPE_ATTR = "type";
50   private static final String CONSTANT_ATTR = "constant";
51   private static final String FN_ATTR = "function";
52   private static final String DESCRIPTION = "description";
53   private static final String USAGE_ATTR = "usage";
54   private static final String TOKENVAL_ATTR = "tokenval";
55   private static IPreferenceStore store;
56   private static boolean hasXMLFileBeenRead = true;
57
58   //The following variable is used to hold the syntax from
59   //the suers custom file - if that file should be changed,
60   //then all entries in this variable should be removed from
61   //the word list, reread from the file and then reinserted.
62   private static Vector userdefsyntaxdata;
63
64   private static Vector syntaxdata;
65
66   public PHPSyntaxRdr() {
67     syntaxdata = new Vector();
68     store = PHPeclipsePlugin.getDefault().getPreferenceStore();
69   }
70
71   public static void readInSyntax() {
72     try {
73       hasXMLFileBeenRead = true;
74       /*Attempt to read the syntax file from the metadata
75        * if this does not work, create metadata from default*/
76       File syntaxFile = getSyntaxFile();
77       if (syntaxFile.exists()) {
78         readFromFile(syntaxFile);
79       } else {
80         readFromStream(PHPSyntaxRdr.class.getResourceAsStream(PHPSYNTAX_FILE));
81         saveToFile(syntaxFile);
82       }
83       /*Read the user-defined syntax file if it exists*/
84       //String buffer = new String(store.getString(PHPeclipsePlugin.PHP_USERDEF_XMLFILE));
85       if (store == null)
86         store = PHPeclipsePlugin.getDefault().getPreferenceStore();
87       String buffer = new String(store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE));
88       if (!buffer.equals("") || buffer != null) {
89         readFromFile(buffer);
90       }
91     } catch (CoreException ce) {
92       ce.printStackTrace();
93     }
94   }
95
96   public static void readFromFile(String filename) {
97     try {
98       readFromFile(new File(filename));
99     } catch (CoreException e) {
100     }
101   }
102
103   public static void readFromFile(File file) throws CoreException {
104     InputStream stream = null;
105     try {
106       stream = new FileInputStream(file);
107       readFromStream(stream);
108     } catch (IOException e) {
109       throwReadException(e);
110     } finally {
111       try {
112         if (stream != null) {
113           stream.close();
114         }
115       } catch (IOException e) {
116       }
117     }
118   }
119   public static void readFromStream(InputStream stream) throws CoreException {
120     try {
121       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
122       DocumentBuilder parser = factory.newDocumentBuilder();
123       Document document = parser.parse(new InputSource(stream));
124       //Read in the Standard PHPSyntax "stuff"
125       NodeList elements = document.getElementsByTagName(PHPSYNTAX_TAG);
126
127       int count = elements.getLength();
128       for (int i = 0; i != count; i++) {
129         Node node = elements.item(i);
130         NamedNodeMap attributes = node.getAttributes();
131
132         if (attributes == null)
133           continue;
134
135         String Keyword = getAttributeValue(attributes, KEYWORD_ATTR);
136         String Type = getAttributeValue(attributes, TYPE_ATTR);
137         String Function = getAttributeValue(attributes, FN_ATTR);
138         String Constant = getAttributeValue(attributes, CONSTANT_ATTR);
139         String Description = getAttributeValue(attributes, DESCRIPTION);
140         String Usage = getAttributeValue(attributes, USAGE_ATTR);
141         String Tokenval = getAttributeValue(attributes, TOKENVAL_ATTR);
142
143         if (Keyword == null && Type == null && Function == null && Constant == null) {
144           //ignore as it is not a valid phpsyntax tag
145         } else {
146           if (Keyword != null) {
147             syntaxdata.addElement(new PHPKeyword(Keyword, Description, Tokenval));
148           } else if (Type != null) {
149             syntaxdata.addElement(new PHPType(Type, Description));
150           } else if (Function != null) {
151             syntaxdata.addElement(new PHPFunction(Function, Description, Usage));
152           } else if (Constant != null) {
153             syntaxdata.addElement(new PHPConstant(Constant, Description));
154           }
155         }
156       }
157     } catch (ParserConfigurationException e) {
158       throwReadException(e);
159     } catch (IOException e) {
160       throwReadException(e);
161     } catch (SAXException e) {
162       throwReadException(e);
163     }
164   }
165
166   public static Vector getsyntaxdata() {
167     return (Vector) syntaxdata.clone();
168   }
169
170   public static void replaceUserDefFile() {
171     /*Replace the user-defined syntax file if it exists*/
172     String buffer = new String(store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE));
173     if (!buffer.equals("") || buffer == null) {
174       readFromFile(buffer);
175     }
176   }
177
178   public static Vector getUserDefinitions() {
179     return (Vector) userdefsyntaxdata.clone();
180   }
181
182   private static File getSyntaxFile() {
183     IPath path = PHPeclipsePlugin.getDefault().getStateLocation();
184     path = path.append(PHPSYNTAX_FILE);
185     return path.toFile();
186   }
187
188   private static String getAttributeValue(NamedNodeMap attributes, String name) {
189     Node node = attributes.getNamedItem(name);
190     return node == null ? null : node.getNodeValue();
191   }
192
193   public static void saveToFile(File file) throws CoreException {
194     OutputStream stream = null;
195     try {
196       stream = new FileOutputStream(file);
197       saveToStream(stream);
198     } catch (IOException e) {
199       throwWriteException(e);
200     } finally {
201       try {
202         if (stream != null)
203           stream.close();
204       } catch (IOException e) {
205       }
206     }
207   }
208
209   public static void saveToStream(OutputStream stream) throws CoreException {
210     try {
211       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
212       DocumentBuilder builder = factory.newDocumentBuilder();
213       Document document = builder.newDocument();
214       Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ //$NON-NLS-1$
215       document.appendChild(root);
216       for (int i = 0; i != syntaxdata.size(); i++) {
217         Object bufferobj = (Object) syntaxdata.get(i);
218         Attr name = null;
219         Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ //$NON-NLS-1$
220         root.appendChild(node);
221         NamedNodeMap attributes = node.getAttributes();
222         if (bufferobj instanceof PHPType)
223           name = document.createAttribute(TYPE_ATTR);
224         if (bufferobj instanceof PHPKeyword)
225           name = document.createAttribute(KEYWORD_ATTR);
226         if (bufferobj instanceof PHPFunction)
227           name = document.createAttribute(FN_ATTR);
228         if (bufferobj instanceof PHPConstant)
229           name = document.createAttribute(CONSTANT_ATTR);
230         name.setValue(((PHPElement) bufferobj).getName());
231         attributes.setNamedItem(name);
232         Attr description = document.createAttribute(DESCRIPTION);
233         description.setValue(((PHPElement) bufferobj).getDescription());
234         attributes.setNamedItem(description);
235         if (bufferobj instanceof PHPKeyword) {
236           Attr tokenval = document.createAttribute(TOKENVAL_ATTR);
237           tokenval.setValue((new Integer(((PHPKeyword) bufferobj).gettokenval())).toString());
238           attributes.setNamedItem(tokenval);
239         }
240         if (bufferobj instanceof PHPFunction) {
241           Attr usage = document.createAttribute(USAGE_ATTR);
242           usage.setValue(((PHPFunction) bufferobj).getUsage());
243           attributes.setNamedItem(usage);
244         }
245       }
246       OutputFormat format = new OutputFormat();
247       format.setPreserveSpace(true);
248       try {
249         Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format);
250         serializer.asDOMSerializer().serialize(document);
251       } catch (UnsupportedEncodingException e) {
252       } catch (IOException e) {
253       } //$NON-NLS-1$
254       //                        Serializer serializer = SerializerFactory.getSerializer().makeSerializer(stream, format); //$NON-NLS-1$
255     } catch (ParserConfigurationException e) {
256       throwWriteException(e);
257       //        } catch (IOException e) {
258       //            throwWriteException(e);
259     }
260   }
261
262   private static void throwReadException(Throwable t) throws CoreException {
263     PHPeclipsePlugin.log(t);
264     //          IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
265     //                  TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
266     //          throw new JavaUIException(status);
267   }
268
269   private static void throwWriteException(Throwable t) throws CoreException {
270     PHPeclipsePlugin.log(t);
271     //          IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
272     //                  TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
273     //          throw new JavaUIException(status);
274   }
275
276 }