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