a lot of fixes
[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 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 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(
81                                         PHPSyntaxRdr.class.getResourceAsStream(PHPSYNTAX_FILE));
82                                 saveToFile(syntaxFile);
83                         }
84                         /*Read the user-defined syntax file if it exists*/
85                         //String buffer = new String(store.getString(PHPeclipsePlugin.PHP_USERDEF_XMLFILE));
86                         if (store == null)
87                                 store = PHPeclipsePlugin.getDefault().getPreferenceStore();
88                         String buffer =
89                                 new String(
90                                         store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE));
91                         if (!(buffer.equals("") || buffer == null)) {
92                                 readFromFile(buffer);
93                         }
94                 } catch (CoreException ce) {
95                         ce.printStackTrace();
96                 }
97         }
98
99         public static void readFromFile(String filename) {
100                 try {
101                         readFromFile(new File(filename));
102                 } catch (CoreException e) {
103                 }
104         }
105
106         public static void readFromFile(File file) throws CoreException {
107                 InputStream stream = null;
108
109                 if (file.exists()) {
110                         try {
111                                 stream = new FileInputStream(file);
112                                 readFromStream(stream);
113                         } catch (IOException e) {
114                                 throwReadException(e);
115                         } finally {
116                                 try {
117                                         if (stream != null) {
118                                                 stream.close();
119                                         }
120                                 } catch (IOException e) {
121                                 }
122                         }
123                 }
124         }
125         public static void readFromStream(InputStream stream)
126                 throws CoreException {
127                 try {
128                         DocumentBuilderFactory factory =
129                                 DocumentBuilderFactory.newInstance();
130                         DocumentBuilder parser = factory.newDocumentBuilder();
131                         Document document = parser.parse(new InputSource(stream));
132                         //Read in the Standard PHPSyntax "stuff"
133                         NodeList elements = document.getElementsByTagName(PHPSYNTAX_TAG);
134
135                         int count = elements.getLength();
136                         for (int i = 0; i != count; i++) {
137                                 Node node = elements.item(i);
138                                 NamedNodeMap attributes = node.getAttributes();
139
140                                 if (attributes == null)
141                                         continue;
142
143                                 String Keyword = getAttributeValue(attributes, KEYWORD_ATTR);
144                                 String Type = getAttributeValue(attributes, TYPE_ATTR);
145                                 String Function = getAttributeValue(attributes, FN_ATTR);
146                                 String Constant = getAttributeValue(attributes, CONSTANT_ATTR);
147                                 String usage = getAttributeValue(attributes, USAGE_ATTR);
148                                 String Tokenval = getAttributeValue(attributes, TOKENVAL_ATTR);
149
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();
154                                         if (value != null)
155                                                 buffer.append(value);
156                                 }
157                                 String description = buffer.toString().trim();
158
159                                 if (Keyword == null
160                                         && Type == null
161                                         && Function == null
162                                         && Constant == null) {
163                                         //ignore as it is not a valid phpsyntax tag
164                                 } else {
165                                         if (Keyword != null) {
166                                                 syntaxdata.addElement(
167                                                         new PHPKeyword(Keyword, usage, Tokenval));
168                                         } else if (Type != null) {
169                                                 syntaxdata.addElement(new PHPType(Type, usage));
170                                         } else if (Function != null) {
171                                                 syntaxdata.addElement(
172                                                         new PHPFunction(Function, usage, description));
173                                         } else if (Constant != null) {
174                                                 syntaxdata.addElement(new PHPConstant(Constant, usage));
175                                         }
176                                 }
177                         }
178                 } catch (ParserConfigurationException e) {
179                         throwReadException(e);
180                 } catch (IOException e) {
181                         throwReadException(e);
182                 } catch (SAXException e) {
183                         throwReadException(e);
184                 }
185         }
186
187         public static Vector getsyntaxdata() {
188                 return (Vector) syntaxdata.clone();
189         }
190
191         public static void replaceUserDefFile() {
192                 /*Replace the user-defined syntax file if it exists*/
193                 String buffer =
194                         new String(
195                                 store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE));
196                 if (!buffer.equals("") || buffer == null) {
197                         readFromFile(buffer);
198                 }
199         }
200
201         public static Vector getUserDefinitions() {
202                 return (Vector) userdefsyntaxdata.clone();
203         }
204
205         private static File getSyntaxFile() {
206                 IPath path = PHPeclipsePlugin.getDefault().getStateLocation();
207                 path = path.append(PHPSYNTAX_FILE);
208                 return path.toFile();
209         }
210
211         private static String getAttributeValue(
212                 NamedNodeMap attributes,
213                 String name) {
214                 Node node = attributes.getNamedItem(name);
215                 return node == null ? null : node.getNodeValue();
216         }
217
218         public static void saveToFile(File file) throws CoreException {
219                 OutputStream stream = null;
220                 try {
221                         stream = new FileOutputStream(file);
222                         saveToStream(stream);
223                 } catch (IOException e) {
224                         throwWriteException(e);
225                 } finally {
226                         try {
227                                 if (stream != null)
228                                         stream.close();
229                         } catch (IOException e) {
230                         }
231                 }
232         }
233
234         public static void saveToStream(OutputStream stream) throws CoreException {
235                 try {
236                         DocumentBuilderFactory factory =
237                                 DocumentBuilderFactory.newInstance();
238                         DocumentBuilder builder = factory.newDocumentBuilder();
239                         Document document = builder.newDocument();
240                         Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ //$NON-NLS-1$
241                         document.appendChild(root);
242                         for (int i = 0; i != syntaxdata.size(); i++) {
243                                 Object bufferobj = (Object) syntaxdata.get(i);
244                                 Attr name = null;
245                                 Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ //$NON-NLS-1$
246                                 root.appendChild(node);
247                                 NamedNodeMap attributes = node.getAttributes();
248                                 if (bufferobj instanceof PHPType)
249                                         name = document.createAttribute(TYPE_ATTR);
250                                 if (bufferobj instanceof PHPKeyword)
251                                         name = document.createAttribute(KEYWORD_ATTR);
252                                 if (bufferobj instanceof PHPFunction)
253                                         name = document.createAttribute(FN_ATTR);
254                                 if (bufferobj instanceof PHPConstant)
255                                         name = document.createAttribute(CONSTANT_ATTR);
256                                 name.setValue(((PHPElement) bufferobj).getName());
257                                 attributes.setNamedItem(name);
258                                 Attr description = document.createAttribute(USAGE_ATTR);
259                                 description.setValue(((PHPElement) bufferobj).getUsage());
260                                 attributes.setNamedItem(description);
261                                 if (bufferobj instanceof PHPKeyword) {
262                                         Attr tokenval = document.createAttribute(TOKENVAL_ATTR);
263                                         tokenval.setValue(
264                                                 (new Integer(((PHPKeyword) bufferobj).gettokenval()))
265                                                         .toString());
266                                         attributes.setNamedItem(tokenval);
267                                 }
268                                 if (bufferobj instanceof PHPFunction) {
269                                         //      Attr usage = document.createAttribute(USAGE_ATTR);
270                                         Text usage =
271                                                 document.createTextNode(
272                                                         ((PHPFunction) bufferobj).getDescription());
273                                         node.appendChild(usage);
274                                         //          usage.setValue(((PHPFunction) bufferobj).getUsage());
275                                         //          attributes.setNamedItem(usage);
276                                 }
277                         }
278                         OutputFormat format = new OutputFormat();
279                         format.setPreserveSpace(true);
280                         try {
281                                 Serializer serializer =
282                                         SerializerFactory.getSerializerFactory(
283                                                 "xml").makeSerializer(
284                                                 stream,
285                                                 format);
286                                 serializer.asDOMSerializer().serialize(document);
287                         } catch (UnsupportedEncodingException e) {
288                         } catch (IOException e) {
289                         } //$NON-NLS-1$
290                         //                      Serializer serializer = SerializerFactory.getSerializer().makeSerializer(stream, format); //$NON-NLS-1$
291                 } catch (ParserConfigurationException e) {
292                         throwWriteException(e);
293                         //        } catch (IOException e) {
294                         //            throwWriteException(e);
295                 }
296         }
297
298         private static void throwReadException(Throwable t) throws CoreException {
299                 PHPeclipsePlugin.log(t);
300                 //              IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
301                 //                      ObfuscatorMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
302                 //              throw new JavaUIException(status);
303         }
304
305         private static void throwWriteException(Throwable t) throws CoreException {
306                 PHPeclipsePlugin.log(t);
307                 //              IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
308                 //                      ObfuscatorMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
309                 //              throw new JavaUIException(status);
310         }
311
312 }