*** empty log message ***
[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(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 usage = getAttributeValue(attributes, USAGE_ATTR);
140         String Tokenval = getAttributeValue(attributes, TOKENVAL_ATTR);
141
142         StringBuffer buffer= new StringBuffer();
143         NodeList children= node.getChildNodes();
144         for (int j= 0; j != children.getLength(); j++) {
145           String value= children.item(j).getNodeValue();
146           if (value != null)
147             buffer.append(value);
148         }
149         String description = buffer.toString().trim();
150         
151         if (Keyword == null && Type == null && Function == null && Constant == null) {
152           //ignore as it is not a valid phpsyntax tag
153         } else {
154           if (Keyword != null) {
155             syntaxdata.addElement(new PHPKeyword(Keyword, usage, Tokenval));
156           } else if (Type != null) {
157             syntaxdata.addElement(new PHPType(Type, usage));
158           } else if (Function != null) {
159             syntaxdata.addElement(new PHPFunction(Function, usage, description));
160           } else if (Constant != null) {
161             syntaxdata.addElement(new PHPConstant(Constant, usage));
162           }
163         }
164       }
165     } catch (ParserConfigurationException e) {
166       throwReadException(e);
167     } catch (IOException e) {
168       throwReadException(e);
169     } catch (SAXException e) {
170       throwReadException(e);
171     }
172   }
173
174   public static Vector getsyntaxdata() {
175     return (Vector) syntaxdata.clone();
176   }
177
178   public static void replaceUserDefFile() {
179     /*Replace the user-defined syntax file if it exists*/
180     String buffer = new String(store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE));
181     if (!buffer.equals("") || buffer == null) {
182       readFromFile(buffer);
183     }
184   }
185
186   public static Vector getUserDefinitions() {
187     return (Vector) userdefsyntaxdata.clone();
188   }
189
190   private static File getSyntaxFile() {
191     IPath path = PHPeclipsePlugin.getDefault().getStateLocation();
192     path = path.append(PHPSYNTAX_FILE);
193     return path.toFile();
194   }
195
196   private static String getAttributeValue(NamedNodeMap attributes, String name) {
197     Node node = attributes.getNamedItem(name);
198     return node == null ? null : node.getNodeValue();
199   }
200
201   public static void saveToFile(File file) throws CoreException {
202     OutputStream stream = null;
203     try {
204       stream = new FileOutputStream(file);
205       saveToStream(stream);
206     } catch (IOException e) {
207       throwWriteException(e);
208     } finally {
209       try {
210         if (stream != null)
211           stream.close();
212       } catch (IOException e) {
213       }
214     }
215   }
216
217   public static void saveToStream(OutputStream stream) throws CoreException {
218     try {
219       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
220       DocumentBuilder builder = factory.newDocumentBuilder();
221       Document document = builder.newDocument();
222       Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ //$NON-NLS-1$
223       document.appendChild(root);
224       for (int i = 0; i != syntaxdata.size(); i++) {
225         Object bufferobj = (Object) syntaxdata.get(i);
226         Attr name = null;
227         Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ //$NON-NLS-1$
228         root.appendChild(node);
229         NamedNodeMap attributes = node.getAttributes();
230         if (bufferobj instanceof PHPType)
231           name = document.createAttribute(TYPE_ATTR);
232         if (bufferobj instanceof PHPKeyword)
233           name = document.createAttribute(KEYWORD_ATTR);
234         if (bufferobj instanceof PHPFunction)
235           name = document.createAttribute(FN_ATTR);
236         if (bufferobj instanceof PHPConstant)
237           name = document.createAttribute(CONSTANT_ATTR);
238         name.setValue(((PHPElement) bufferobj).getName());
239         attributes.setNamedItem(name);
240         Attr description = document.createAttribute(USAGE_ATTR);
241         description.setValue(((PHPElement) bufferobj).getUsage());
242         attributes.setNamedItem(description);
243         if (bufferobj instanceof PHPKeyword) {
244           Attr tokenval = document.createAttribute(TOKENVAL_ATTR);
245           tokenval.setValue((new Integer(((PHPKeyword) bufferobj).gettokenval())).toString());
246           attributes.setNamedItem(tokenval);
247         }
248         if (bufferobj instanceof PHPFunction) {
249     //      Attr usage = document.createAttribute(USAGE_ATTR);
250           Text usage = document.createTextNode(((PHPFunction) bufferobj).getDescription());
251           node.appendChild(usage);
252 //          usage.setValue(((PHPFunction) bufferobj).getUsage());
253 //          attributes.setNamedItem(usage);
254         }
255       }
256       OutputFormat format = new OutputFormat();
257       format.setPreserveSpace(true);
258       try {
259         Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format);
260         serializer.asDOMSerializer().serialize(document);
261       } catch (UnsupportedEncodingException e) {
262       } catch (IOException e) {
263       } //$NON-NLS-1$
264       //                        Serializer serializer = SerializerFactory.getSerializer().makeSerializer(stream, format); //$NON-NLS-1$
265     } catch (ParserConfigurationException e) {
266       throwWriteException(e);
267       //        } catch (IOException e) {
268       //            throwWriteException(e);
269     }
270   }
271
272   private static void throwReadException(Throwable t) throws CoreException {
273     PHPeclipsePlugin.log(t);
274     //          IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
275     //                  TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
276     //          throw new JavaUIException(status);
277   }
278
279   private static void throwWriteException(Throwable t) throws CoreException {
280     PHPeclipsePlugin.log(t);
281     //          IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
282     //                  TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
283     //          throw new JavaUIException(status);
284   }
285
286 }