Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 33ce3a4a4dc8e4a2d7225c6ab09e8b7ae9998907 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*******************************************************************************
 * Copyright (c) 2000, 2003 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
/**********************************************************************
This file is made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
**********************************************************************/

//
// Copyright:
// GEBIT Gesellschaft fuer EDV-Beratung
// und Informatik-Technologien mbH, 
// Berlin, Duesseldorf, Frankfurt (Germany) 2002
// All rights reserved.
//
package org.eclipse.ui.externaltools.internal.ant.editor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.text.MessageFormat;
import java.util.Stack;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.util.FileUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.ui.externaltools.internal.model.ExternalToolsPlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;


/**
 * The <code>DefaultHandler</code> for the parsing of the currently edited file.
 * 
 * @version 19.09.2002
 * @author Alf Schiefelbein
 */
public class PlantySaxDefaultHandler extends DefaultHandler {

    /**
     * The locator that tells us the location of the currently parsed element 
     * in the parsed document.
     */
    protected Locator locator;


    /**
     * Stack of still open elements.
     * <P>
     * On top of the stack is the innermost element.
     */
    protected Stack stillOpenElements = new Stack();


    /**
     * The parent element that we search for.
     * <P>
     * This variable will be set during the parsing process, when we first
     * passed the cursor location.
     */
    protected Element parentElement;


    /**
     * Flag that determines wether we are finished with parsing.
     * <P>
     * This is usually the case when the parent element was found and closed.
     */
    protected boolean parsingFinished;


    /**
     * Document that is used to create the elements.
     */
    protected Document document;


    /**
     * The startingRow where the cursor is located in the document.
     * <P>
     * The first startingRow is refered to with an index of '0'.
     */
    protected int rowOfCursorPosition = -1;
    
    
    /**
     * The startingColumn where the cursor is located in the document.
     * <P>
     * The first startingColumn is refered to with an index of '0'.
     */
    protected int columnOfCursorPosition = -1;
    
    /**
     * The name of the document root element or null if none seen.
     */
	public String rootElementName;
	
	/**
	 * Used as a helper for resolving external relative entries.
	 */
	private File mainFileContainer;


    /**
     * Creates an PlantySaxDefaultHandler, with the specified parameters.
     * 
     * @param aRowOfCursorPosition the startingRow where the cursor is located in the
     * document. The first startingRow is refered to with an index of '0'.
     * @param aColumnOfCursorPosition the startingColumn where the cursor is located in
     * the document. The first startingColumn is refered to with an index of '0'.
     */
    public PlantySaxDefaultHandler(File mainFileContainer, int aRowOfCursorPosition, int aColumnOfCursorPosition) throws ParserConfigurationException {
        super();
		if (ExternalToolsPlugin.getDefault() != null && ExternalToolsPlugin.getDefault().isDebugging()) {
			ExternalToolsPlugin.getDefault().log("PlantySaxDefaultHandler(" +aRowOfCursorPosition+ ", "+aColumnOfCursorPosition+ ")", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
        if(aRowOfCursorPosition < 0 || aColumnOfCursorPosition < 0) {
            throw new IllegalArgumentException(MessageFormat.format(AntEditorMessages.getString("PlantySaxDefaultHandler.Invalid_cursor_position"), new String[]{Integer.toString(aRowOfCursorPosition), Integer.toString(aColumnOfCursorPosition)})); //$NON-NLS-1$
        }
        rowOfCursorPosition = aRowOfCursorPosition;
        columnOfCursorPosition = aColumnOfCursorPosition;
        this.mainFileContainer= mainFileContainer;
        initialize();
    }


    /**
     * Initializes the handler.
     */
    protected void initialize() throws ParserConfigurationException {
        DocumentBuilder tempDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        document = tempDocumentBuilder.newDocument();
    }



    /**
     * Checks wether the parent element, that we are searching for can be or
     * has already been determined.
     * <P>
     * This will be done by comparing the current parsing position with the
     * cursor position. If we just passed the cursor position and the parent
     * element has not been set yet, it will be set.
     * 
     * @return <code>true</code> if the parent element is known otherwise
     * <code>false</code>
     */
    protected boolean checkForParentElement() {
        if(parentElement == null) {
            if(locator != null) {

                /*
                 * The locator's numbers are 1-based though, we do everything
                 * 0-based.
                 */

                int tempLineNr = locator.getLineNumber() -1;
                int tempColumnNr = locator.getColumnNumber() -1;
                if(tempLineNr> rowOfCursorPosition ||
                    (tempLineNr == rowOfCursorPosition && tempColumnNr > columnOfCursorPosition)) {
                        parentElement = (Element)stillOpenElements.peek();
                        if (ExternalToolsPlugin.getDefault() != null && ExternalToolsPlugin.getDefault().isDebugging()) {
							ExternalToolsPlugin.getDefault().log("PlantySaxDefaultHandler.checkForParentElement(): Parent element found: " +parentElement, null); //$NON-NLS-1$
                        }
                        return true;
                    }
            }
            return false;
        }
        
        // Parent element has been set already before
        return true;
    }
    


    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#startElement(String, String, String, Attributes)
     */
    public void startElement(
        String aUri,
        String aLocalName,
        String aQualifiedName,
        Attributes anAttributes)
        throws SAXException {
        /*
         * While the crimson parser passes the tag name as local name, apache's
         * xerces parser, passes the tag name as qualilfied name and an empty 
         * string as local name.
         */
        
		 if (ExternalToolsPlugin.getDefault() != null && ExternalToolsPlugin.getDefault().isDebugging()) {
			ExternalToolsPlugin.getDefault().log("PlantySaxDefaultHandler.startElement(" +aUri+ ", " +aLocalName+ ", "+aQualifiedName+ ", "+anAttributes+ ")", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
        }
        if(parsingFinished) {
            return;
        }        

        // Checks wether we know the parent for sure
        checkForParentElement();

        // Create a Dom Element
        String tempTagName = aLocalName.length() > 0 ? aLocalName : aQualifiedName;
        if(tempTagName == null || tempTagName.length() == 0) {
            throw new PlantyException(AntEditorMessages.getString("PlantySaxDefaultHandler.Error_parsing")); //$NON-NLS-1$
        }
        // This code added to determine root element in a rational way bf
        if (rootElementName == null)
        	rootElementName = tempTagName;
        
        Element tempElement = document.createElement(tempTagName);
        
        stillOpenElements.push(tempElement);
        
        super.startElement(aUri, aLocalName, aQualifiedName, anAttributes);
    }


    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#endElement(String, String, String)
     */
    public void endElement(String aUri, String aLocalName, String aQualifiedName)
        throws SAXException {

		if (ExternalToolsPlugin.getDefault() != null && ExternalToolsPlugin.getDefault().isDebugging()) {
			ExternalToolsPlugin.getDefault().log("PlantySaxDefaultHandler.endElement(" +aUri+ ", " +aLocalName+ ", "+aQualifiedName+ ")", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
		}

        if(parsingFinished) {
            return;
        }        
        
        // Checks whether we know the parent for sure
        boolean tempParentKnown = checkForParentElement();
        
        String tempTagName = aLocalName.length() > 0 ? aLocalName : aQualifiedName;

		if(!stillOpenElements.isEmpty()) {        
	        Element tempLastStillOpenElement = (Element)stillOpenElements.peek(); 
	        if(tempLastStillOpenElement != null && tempLastStillOpenElement.getTagName().equals(tempTagName)) {
	            stillOpenElements.pop();
	            
	            if(!stillOpenElements.empty()) {
	                Element tempSecondLastStillOpenElement = (Element)stillOpenElements.peek();
	                tempSecondLastStillOpenElement.appendChild(tempLastStillOpenElement);
	            }
	            if(tempParentKnown && parentElement != null && parentElement.getTagName().equals(tempTagName)) {
	                parsingFinished = true;
	            }
	        }
		}
    }


    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#setDocumentLocator(Locator)
     */
    public void setDocumentLocator(Locator aLocator) {
        locator = aLocator;
        super.setDocumentLocator(aLocator);
    }


    /**
     * Returns the parent element that has been determined during a prior 
     * parsing.
     * <P>
     * It is quite common that parsing stopped before the current cursor 
     * position. That happens when the parser finds an error within the parsed 
     * document before. In that case the parent element might be guessed to be
     * the one that opened last. To tell the handler whether the parent should
     * be guessed, <code>aGuessParentFlag</code> may be specified.
     * 
     * @param aGuessParentFlag wether the parent should be guessed
     * @return the parent element or <code>null</code> if not known.
     */
    public Element getParentElement(boolean aGuessParentFlag) {
        if(parentElement != null) {
            return parentElement;
        }
        if(aGuessParentFlag) {
            if(!stillOpenElements.empty()) {
                return (Element)stillOpenElements.peek();
            }
        }
        return null;
    }


    /* (non-Javadoc)
     * @see org.xml.sax.ErrorHandler#error(SAXParseException)
     */
    public void error(SAXParseException anException) throws SAXException {
        super.error(anException);
    }

    /**
     * We have to handle fatal errors.
     * <P>
     * They come up whenever we parse a not valid file, what we do all the time.
     * Therefore a fatal error is nothing special for us.
     * <P>
     * Actually, we ignore all fatal errors for now.
     * 
     * @see org.xml.sax.ErrorHandler#fatalError(SAXParseException)
     */
    public void fatalError(SAXParseException anException) throws SAXException {
        if(locator != null) {
          //  int tempLineNr = locator.getLineNumber() -1;
          //  int tempColumnNr = locator.getColumnNumber() -1;
          //  super.fatalError(anException);
        }
    }
    
	/**
	 * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
	 */
	public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
		int index= systemId.indexOf(':');
		if (index > 0) {
			//remove file:
			systemId= systemId.substring(index+1, systemId.length());
		}
		File resolvedFile= null;
		IPath filePath= new Path(systemId);
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(filePath);
		if (file == null || !file.exists()) {
			//relative path
			try {
				//this call is ok if mainFileContainer is null
				resolvedFile= FileUtils.newFileUtils().resolveFile(mainFileContainer, systemId);
			} catch (BuildException be) {
				return null;
			}
		} else {
			resolvedFile= file.getLocation().toFile();
		}
		
		if (resolvedFile != null && resolvedFile.exists()) {
			try {
				return new InputSource(new FileReader(resolvedFile));
			} catch (FileNotFoundException e) {
				return null;
			}
		}
			
		return super.resolveEntity(publicId, systemId);
	}
}

Back to the top