alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2002 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.struts;

import java.util.ResourceBundle;

import org.openide.actions.*;
import org.openide.cookies.*;
import org.openide.filesystems.*;
import org.openide.loaders.*;
import org.openide.nodes.*;
import org.openide.TopManager;
import org.openide.util.HelpCtx;
import org.openide.util.RequestProcessor;
import org.openide.util.NbBundle;
import org.netbeans.modules.xml.catalog.settings.CatalogSettings;
import org.openide.text.Annotation;
import org.openide.text.Line;
import org.openide.util.NbBundle;
import org.openide.windows.InputOutput;
import org.openide.windows.OutputWriter;

// JDOM
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
// XML
import org.xml.sax.SAXParseException;
// Struts Console
import org.apache.struts.console.jdom.JDOMUtil;
import org.netbeans.modules.struts.nodes.ElementChildren;

/** Represents a StrutsConfig object in the Repository.
 *
 * @author  mk115033
 */
public class StrutsConfigDataObject extends MultiDataObject implements ChangableDocument{
    private static StrutsCatalog strutsCatalog;    
    private Document jdomDocument,nodeStructure;
    private StrutsEditorSupport editorSupport;
    private StrutsConfigOpenSupport openSupport;
    private RequestProcessor.Task parsingDocumentTask;
    private boolean documentValid=true;
    private boolean panelChanged=false;
    private Annotation errorAnnotation;
    private InputOutput inOut;
    private ResourceBundle nodeStructureBundle;
    private JDOMException jdomException;
    
    public StrutsConfigDataObject(FileObject pf, StrutsConfigDataLoader loader) throws DataObjectExistsException {
        super(pf, loader);
        init();
    }
    
    private void init() {
        CookieSet cookies = getCookieSet();        
        // Add whatever capabilities you need, e.g.:

        cookies.add(getOpenSupport());
        cookies.add(getEditorSupport());
        /*
        cookies.add (new ExecSupport (getPrimaryEntry ()));
        // See Editor Support template in Editor API:
        cookies.add (new CompilerSupport.Compile (getPrimaryEntry ()));
        cookies.add (new CompilerSupport.Build (getPrimaryEntry ()));
        cookies.add (new CompilerSupport.Clean (getPrimaryEntry ()));
        cookies.add (new OpenCookie () {
                public void open () {
                    // do something...but usually you want to use OpenSupport instead
                }
            });
        */
        
        if (strutsCatalog==null) {
            strutsCatalog = new StrutsCatalog();
            CatalogSettings.getDefault().addCatalog(strutsCatalog);
        }
    }
    
    
    public HelpCtx getHelpCtx() {
        return HelpCtx.DEFAULT_HELP;
        // If you add context help, change to:
        // return new HelpCtx (StrutsConfigDataObject.class);
    }
    
    protected Node createNodeDelegate() {
        return new StrutsConfigDataNode(this,getNodeStructure(),createJdomDocument());
    }
    
    ResourceBundle getNodeStructureBundle() {
        return nodeStructureBundle;
    }
    /* If you made an Editor Support you will want to add these methods: */
     
    final void addSaveCookie (SaveCookie save) {
        getCookieSet ().add (save);
    }
     
    final void removeSaveCookie (SaveCookie save) {
        getCookieSet ().remove (save);
    }
     

    public void setJdomDocument(Document jdomDocument)
    {
            this.jdomDocument = jdomDocument;
    }


    public Document getJdomDocument()
    {
            return (jdomDocument);
    }
    
    public Document createJdomDocument()
    {
        if (jdomDocument==null) {
            try {
                jdomDocument = JDOMUtil.loadDocument(getPrimaryFile().getInputStream(), true);
            } catch (Exception e) {
                if (e instanceof JDOMException) {
                    jdomException = (JDOMException)e;
                    setDocumentValid(false);
                }
            }
        }
        return (jdomDocument);
    }
    
    private void updateTextDocument(Document document) {     
        EditorCookie editorCookie = (EditorCookie) getCookie(EditorCookie.class);
        try
        {
                javax.swing.text.StyledDocument doc = editorCookie.openDocument();
                XMLOutputter outputter = new XMLOutputter();
                doc.remove(0,doc.getLength());
                doc.insertString(0,outputter.outputString(document),null);
                jdomDocument=document;
                setDocumentValid(true);
                ((ElementChildren)getNodeDelegate().getChildren()).updateChildren(jdomDocument.getRootElement());
        }
        catch (Exception e)
        {
                e.printStackTrace(System.out);
        }
        panelChanged=false;            
    }
    
    private void updateEditorPanel() {
        EditorCookie editorCookie = (EditorCookie) getCookie(EditorCookie.class);
        try
        {
                javax.swing.text.StyledDocument doc = editorCookie.openDocument();
                java.io.InputStream is = new java.io.StringBufferInputStream(doc.getText(0,doc.getLength()));
                Document newDoc = JDOMUtil.loadDocument(is, true);
                if (newDoc!=null) {
                    jdomDocument=newDoc;
                    getOpenSupport().update(jdomDocument);
                    setDocumentValid(true);
                    ((ElementChildren)getNodeDelegate().getChildren()).updateChildren(jdomDocument.getRootElement());
                }

        }
        catch (Exception e)
        {
            if (e instanceof org.jdom.JDOMException) {
                jdomException = (JDOMException)e;
                setDocumentValid(false);
            }
        }
    }
        
    public synchronized void replaceDocument(final Document doc) {
        if (parsingDocumentTask==null || parsingDocumentTask.isFinished() || 
            parsingDocumentTask.cancel()) {
            parsingDocumentTask = RequestProcessor.postRequest(new Runnable(){
                public void run(){
                    updateTextDocument(doc);
                }
            },100);                 
        } else {
            parsingDocumentTask = RequestProcessor.postRequest(new Runnable(){
                public void run(){
                    updateTextDocument(doc);
                }
            },2000);             
        }
    }
    
    public void fireDocumentChange() {
        panelChanged=false;
        replaceDocument(jdomDocument);
    }
    
    public synchronized void updatePanel() {
        //System.out.println("XMLJ2eeEditorSupport:restartTimer "+this.hashCode());
        //dataObject.setDocumentDirty(true);
        if (parsingDocumentTask==null || parsingDocumentTask.isFinished() || 
            parsingDocumentTask.cancel()) {
            parsingDocumentTask = RequestProcessor.postRequest(new Runnable(){
                public void run(){
                    updateEditorPanel();
                }
            },100);                 
        } else {
            parsingDocumentTask = RequestProcessor.postRequest(new Runnable(){
                public void run(){
                    updateEditorPanel();
                }
            },2000);             
        }
    }  

    synchronized StrutsConfigOpenSupport getOpenSupport() {
        if (openSupport==null) {
            openSupport = new StrutsConfigOpenSupport(this);
        }
        return openSupport;
    }
    
    synchronized StrutsEditorSupport getEditorSupport() {
        if (editorSupport==null) {
            editorSupport = new StrutsEditorSupport(this);
        }
        return editorSupport;
    }
    
    synchronized void discardDocumentChanges() {
        try {
            jdomDocument = JDOMUtil.loadDocument(getPrimaryFile().getInputStream(), true);
            updateTextDocument(jdomDocument);
        }
        catch (Exception e) {
                // set the line number that the error occured on
                // so that we can display a button to go right
                // to the error in the source file
                int lineNumber = 0;
                if (e instanceof JDOMException) {
                        setDocumentValid(false);
                        jdomException = (JDOMException)e;
                }
                /*
                errorPanel.setLineNumber(lineNumber);

                // show error panel if unable to load document
                // which occurs when the underlying XML file
                // is invalid
                errorPanel.setMessage(e.getMessage());
                cardLayout.show(cardPanel, CARD_ERROR);
                */
        }
    }  
    
    
    public boolean isDocumentValid(){
        return documentValid;
    }
    public void setDocumentValid(boolean valid){
        if (documentValid!=valid) {
            DataNode node = (DataNode)getNodeDelegate();
            if (valid) {
                jdomException=null;
                if (inOut!=null) {
                    inOut.closeInputOutput();
                    this.errorAnnotation.detach();
                }
                node.setIconBase ("/org/netbeans/modules/struts/resources/StrutsConfigIcon");
            } else {
                node.setIconBase ("/org/netbeans/modules/struts/resources/xmlError");
            }
        }
        this.documentValid=valid;
    }
    
    public void setPanelChanged(boolean changed){
        panelChanged=changed;
    }
    
    public boolean isPanelChanged(){
        return panelChanged;
    }

    public static StrutsCatalog getStrutsCatalog() {
        return strutsCatalog;
    }

    public synchronized Document getNodeStructure() {
        if (nodeStructure==null) {
            FileSystem fs= TopManager.getDefault().getRepository().getDefaultFileSystem();
            FileObject fo = fs.find("Web.Struts","node-structure","xml");
            if (fo!=null)
            try {
                nodeStructureBundle = NbBundle.getBundle((String)fo.getAttribute("SystemFileSystem.localizingBundle"));
                nodeStructure = JDOMUtil.loadDocument(fo.getInputStream(), false);
            }
            catch (Exception e) {
                System.out.println("Node Structure parsing error : "+e);
            }
        }
        return nodeStructure;
    }
    
    public void displayErrorMessage() {
        if (jdomException!=null) {
            if (((JDOMException) jdomException).getCause() instanceof SAXParseException)
            {
                int lineNumber = ((SAXParseException) ((JDOMException) jdomException).getCause()).getLineNumber();
                displayErrorMessage(lineNumber,jdomException);
            }
            else {
                displayErrorMessage(-1,jdomException);
            }
        }
    }
    
    public JDOMException getJdomException() {
        return jdomException;
    }
    
    public void setJdomException(JDOMException ex) {
        jdomException=ex;
    }
    
    private void displayErrorMessage(int lineNumber, JDOMException exception) {
            if (errorAnnotation==null)
                 errorAnnotation = new Annotation() {
                 public String getAnnotationType() {
                   return "org-netbeans-modules-struts-annotation";  // NOI18N
                 }
                 public String getShortDescription() {
                   return NbBundle.getMessage(StrutsConfigDataObject.class, "DESC_StrutsAnnotation");
                 }
            };
            LineCookie cookie = (LineCookie)getCookie(LineCookie.class);
            // getting Line object
            Line xLine = cookie.getLineSet ().getOriginal (lineNumber-1);            
            errorAnnotation.attach(xLine);
            if (inOut==null)
                inOut=TopManager.getDefault().getIO(NbBundle.getMessage(StrutsConfigDataObject.class, "TXT_parser"));
            OutputWriter outputWriter = inOut.getOut();
            try {
                IOCtl outList= new IOCtl(xLine);
                outputWriter.reset();
                outputWriter.println(exception.getMessage(),outList);
                //inOut.setFocusTaken (true);
                inOut.select();
            } catch (java.io.IOException ex){System.out.println("ex="+ex);}
    }
    
    private final class IOCtl implements org.openide.windows.OutputListener {
        /** line we check */
        Line xline;

        public IOCtl (Line xline) {
            this.xline=xline;
        }

        public void outputLineSelected (org.openide.windows.OutputEvent ev) {
            EditorCookie editorCookie = (EditorCookie) StrutsConfigDataObject.this.getCookie(EditorCookie.class);
            try {
                editorCookie.openDocument();
            } catch (java.io.IOException ex){}
            errorAnnotation.attach(xline);
            xline.show(Line.SHOW_TRY_SHOW);
        }

        public void outputLineAction (org.openide.windows.OutputEvent ev) {
            errorAnnotation.attach(xline);
            xline.show(Line.SHOW_TRY_SHOW);
        }
        
        public void outputLineCleared (org.openide.windows.OutputEvent ev) {
            errorAnnotation.detach();
        }
    }    
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.