KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > ddloaders > common > xmlutils > XMLJ2eeDataObject


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.ddloaders.common.xmlutils;
21
22 import org.openide.cookies.*;
23 import org.openide.nodes.CookieSet;
24 import org.openide.filesystems.FileObject;
25 import org.openide.loaders.MultiFileLoader;
26 import org.openide.loaders.XMLDataObject;
27 import org.openide.ErrorManager;
28 import org.openide.text.Line;
29 import org.openide.windows.*;
30 import org.openide.util.NbBundle;
31
32 import java.io.*;
33 import org.xml.sax.*;
34 import org.openide.xml.*;
35 import org.netbeans.api.xml.cookies.CheckXMLCookie;
36 import org.netbeans.spi.xml.cookies.*;
37
38 /** Represents a XMLJ2eeDataObject in the Repository.
39  *
40  * @author mkuchtiak
41  */

42 public abstract class XMLJ2eeDataObject extends XMLDataObject implements CookieSet.Factory {
43
44     protected boolean nodeDirty = false;
45     private boolean documentDirty = true;
46     private boolean savingDocument;
47     private InputStream inputStream;
48     private InputOutput inOut;
49     protected XMLJ2eeEditorSupport editor;
50     private boolean documentValid=true;
51     private SAXParseError error;
52     private org.openide.text.Annotation errorAnnotation;
53
54     private static final long serialVersionUID = -515751072013886985L;
55     
56     /** Property name for property documentValid */
57     public static final String JavaDoc PROP_DOC_VALID = "documentValid"; // NOI18N
58

59     public XMLJ2eeDataObject(FileObject pf, MultiFileLoader loader)
60         throws org.openide.loaders.DataObjectExistsException {
61         super(pf,loader);
62         
63         getCookieSet().add(XMLJ2eeEditorSupport.class, this);
64         getCookieSet().add(EditCookie.class, this);
65         getCookieSet().add(EditorCookie.class, this);
66         getCookieSet().add(LineCookie.class, this);
67         getCookieSet().add(PrintCookie.class, this);
68         getCookieSet().add(CloseCookie.class, this);
69         // added CheckXMLCookie
70
InputSource in = DataObjectAdapters.inputSource(this);
71         CheckXMLCookie checkCookie = new CheckXMLSupport(in);
72         getCookieSet().add(checkCookie);
73     }
74     // Issuezilla 23493 - this is the way how to disable the OpenCoookie from this data object
75
protected EditorCookie createEditorCookie () {
76         return null;
77     }
78     /** Update the node from document. This method is called after document is changed.
79     * @param is Input source for the document
80     * @return number of the line with error (document is invalid), 0 (xml document is valid)
81     */

82     protected abstract SAXParseError updateNode(org.xml.sax.InputSource JavaDoc is) throws java.io.IOException JavaDoc;
83     /** gets the Icon Base for node delegate when parser accepts the xml document as valid
84     * @return Icon Base for node delegate
85     */

86     protected abstract String JavaDoc getIconBaseForValidDocument();
87     
88     /** gets the Icon Base for node delegate when parser finds error(s) in xml document
89     * @return Icon Base for node delegate
90     */

91     protected abstract String JavaDoc getIconBaseForInvalidDocument();
92     
93     /** Implements <code>CookieSet.Factory</code> interface. */
94     public org.openide.nodes.Node.Cookie createCookie(Class JavaDoc clazz) {
95         if(clazz.isAssignableFrom(XMLJ2eeEditorSupport.class))
96             return getEditorSupport();
97         else
98             return null;
99     }
100     
101     /** Gets editor support for this data object. */
102     protected synchronized XMLJ2eeEditorSupport getEditorSupport() {
103         if(editor == null) {
104             editor = new XMLJ2eeEditorSupport(this);
105         }
106         return editor;
107     }
108     /** gets the String for status line when parser finds error(s) in xml document
109     * @param error info about an error
110     * @return String for status line
111     */

112     public String JavaDoc getOutputStringForInvalidDocument(SAXParseError error){
113         //return error.getErrorText()+" ["+error.getErrorLine()+","+error.getErrorColumn()+"]";
114
String JavaDoc mes = NbBundle.getMessage (XMLJ2eeDataObject.class, "TXT_errorMessage",
115                                 new Object JavaDoc [] { error.getErrorText(),
116                                                 new Integer JavaDoc(error.getErrorLine()),
117                                                 new Integer JavaDoc(error.getErrorColumn()) });
118         return mes;
119     }
120     /** Getter for property nodeDirty.
121     * @return Value of property nodeDirty.
122     */

123     public boolean isNodeDirty(){
124         return nodeDirty;
125     }
126
127     /** setter for property documentDirty. Method updateDocument() usually setsDocumentDirty to false
128     */

129     public void setDocumentDirty(boolean dirty){
130         documentDirty=dirty;
131     }
132     
133     /** Getter for property documentDirty.
134     * @return Value of property documentDirty.
135     */

136     public boolean isDocumentDirty(){
137         return documentDirty;
138     }
139     
140     /** Setter for property nodeDirty.
141      * @param dirty New value of property nodeDirty.
142      */

143     public void setNodeDirty(boolean dirty){
144         nodeDirty=dirty;
145     }
146     
147     /** This method repairs Node Delegate (usually after changing document by property editor)
148     */

149     protected void repairNode(){
150         // PENDING: set the icon in Node
151
// ((DataNode)getNodeDelegate()).setIconBase (getIconBaseForValidDocument());
152
if (inOut!=null) {
153             inOut.closeInputOutput();
154             errorAnnotation.detach();
155         }
156     }
157     
158     /** This method parses XML document and calls abstract updateNode method which
159     * updates corresponding Node.
160     */

161     public void parsingDocument(){
162         //System.out.println("background parsing "); // NOI18N
163
//Thread.dumpStack();
164
SAXParseError err=null;
165         try {
166             err=updateNode(prepareInputSource());
167         }
168         catch (Exception JavaDoc e) {
169             ErrorManager.getDefault ().notify (ErrorManager.INFORMATIONAL, e);
170             setDocumentValid(false);
171             return;
172         }
173         finally {
174             closeInputSource();
175             documentDirty=false;
176         }
177         if (err==null){
178             setDocumentValid(true);
179         }else {
180             setDocumentValid(false);
181         }
182     }
183
184     /** This method is used for obtaining the current source of xml document.
185     * First try if document is in the memory. If not, provide the input from
186     * underlayed file object.
187     * @return The input source from memory or from file
188     * @exception IOException if some problem occurs
189     */

190     protected org.xml.sax.InputSource JavaDoc prepareInputSource() throws java.io.IOException JavaDoc {
191         if ((editor != null) && (editor.isDocumentLoaded())) {
192             // loading from the memory (Document)
193
final javax.swing.text.Document JavaDoc doc = editor.getDocument();
194             final String JavaDoc[] str = new String JavaDoc[1];
195             // safely take the text from the document
196
Runnable JavaDoc run = new Runnable JavaDoc() {
197                 public void run() {
198                     try {
199                         str[0] = doc.getText(0, doc.getLength());
200                     }
201                     catch (javax.swing.text.BadLocationException JavaDoc e) {
202                         // impossible
203
}
204                 }
205             };
206             
207             doc.render(run);
208             // TODO: this StringReader should be also closed.
209
StringReader reader = new StringReader(str[0]);
210             return new org.xml.sax.InputSource JavaDoc(reader);
211         }
212         else {
213             // loading from the file
214
inputStream = new BufferedInputStream(getPrimaryFile().getInputStream());
215             return new org.xml.sax.InputSource JavaDoc(inputStream);
216         }
217     }
218     
219     /** This method has to be called everytime after prepareInputSource calling.
220      * It is used for closing the stream, because it is not possible to access the
221      * underlayed stream hidden in InputSource.
222      * It is save to call this method without opening.
223      */

224     protected void closeInputSource() {
225         InputStream is = inputStream;
226         if (is != null) {
227             try {
228                 is.close();
229             }
230             catch (IOException e) {
231                 // nothing to do, if exception occurs during saving.
232
}
233             if (is == inputStream) {
234                 inputStream = null;
235             }
236         }
237     }
238     public boolean isDocumentValid(){
239         return documentValid;
240     }
241     public void setDocumentValid (boolean valid){
242         if (documentValid!=valid) {
243             if (valid)
244                 repairNode();
245             documentValid=valid;
246             firePropertyChange (PROP_DOC_VALID, !documentValid ? Boolean.TRUE : Boolean.FALSE, documentValid ? Boolean.TRUE : Boolean.FALSE);
247         }
248     }
249     public void addSaveCookie(SaveCookie cookie){
250         getCookieSet().add(cookie);
251     }
252     public void removeSaveCookie(){
253         org.openide.nodes.Node.Cookie cookie = getCookie(SaveCookie.class);
254         if (cookie!=null) getCookieSet().remove(cookie);
255     }
256     
257     public void setSavingDocument(boolean saving){
258         savingDocument=saving;
259     }
260     public boolean isSavingDocument(){
261         return savingDocument;
262     }
263     public void displayErrorMessage() {
264             if (error==null) return;
265             if (errorAnnotation==null)
266                  errorAnnotation = new org.openide.text.Annotation() {
267                  public String JavaDoc getAnnotationType() {
268                    return "xml-j2ee-annotation"; // NOI18N
269
}
270                  String JavaDoc desc = NbBundle.getMessage(XMLJ2eeDataObject.class, "HINT_XMLErrorDescription");
271                  public String JavaDoc getShortDescription() {
272                    return desc;
273                  }
274             };
275             if (inOut==null)
276                 inOut=org.openide.windows.IOProvider.getDefault().getIO(NbBundle.getMessage(XMLJ2eeDataObject.class, "TXT_parser"), false);
277             inOut.setFocusTaken (false);
278             OutputWriter outputWriter = inOut.getOut();
279             int line = Math.max(0,error.getErrorLine());
280 // int column = Math.max(0,error.getErrorColumn());
281

282             LineCookie cookie = (LineCookie)getCookie(LineCookie.class);
283             // getting Line object
284
Line xline = cookie.getLineSet ().getCurrent(line==0?0:line-1);
285             // attaching Annotation
286
errorAnnotation.attach(xline);
287             
288             try {
289                 outputWriter.reset();
290                 // defining of new OutputListener
291
IOCtl outList= new IOCtl(xline);
292                 outputWriter.println(this.getOutputStringForInvalidDocument(error),outList);
293             }catch(IOException e){}
294     }
295     
296     public void setValid(boolean valid) throws java.beans.PropertyVetoException JavaDoc {
297         if (!valid && inOut!=null) inOut.closeInputOutput();
298         super.setValid(valid);
299     }
300
301     final class IOCtl implements OutputListener {
302         /** line we check */
303         Line xline;
304
305         public IOCtl (Line xline) {
306             this.xline=xline;
307         }
308
309         public void outputLineSelected (OutputEvent ev) {
310             errorAnnotation.attach(xline);
311             xline.show(Line.SHOW_TRY_SHOW);
312         }
313
314         public void outputLineAction (OutputEvent ev) {
315             errorAnnotation.attach(xline);
316             xline.show(Line.SHOW_TRY_SHOW);
317         }
318         
319         public void outputLineCleared (OutputEvent ev) {
320             errorAnnotation.detach();
321         }
322     }
323      
324     public static class J2eeErrorHandler implements ErrorHandler {
325         
326         private XMLJ2eeDataObject xmlJ2eeDataObject;
327         
328         public J2eeErrorHandler(XMLJ2eeDataObject obj) {
329              xmlJ2eeDataObject=obj;
330         }
331         
332         public void error(SAXParseException exception) throws SAXException {
333             xmlJ2eeDataObject.createSAXParseError(exception);
334             throw exception;
335         }
336
337         public void fatalError(SAXParseException exception) throws SAXException {
338             xmlJ2eeDataObject.createSAXParseError(exception);
339             throw exception;
340         }
341
342         public void warning(SAXParseException exception) throws SAXException {
343             xmlJ2eeDataObject.createSAXParseError(exception);
344             throw exception;
345         }
346     }
347     
348     private void createSAXParseError(SAXParseException error){
349         this.error = new SAXParseError(error);
350     }
351     
352 }
353
354
Popular Tags