Saturday Jul 06, 2013

View Code Templates While Coding

Sometimes handy to know the code templates NetBeans IDE makes available while you're coding. Click the image below to see the full effect, i.e., the full list of code templates next to the Java editor:

Here's the code:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.util.List;
import javax.swing.JButton;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.OutlineView;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.BeanNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.lookup.Lookups;
import org.openide.windows.IOProvider;
import org.openide.windows.InputOutput;
import org.openide.windows.OutputWriter;
import org.openide.windows.TopComponent;
import org.openide.xml.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

@TopComponent.Description(
        preferredID = "CodeTemplatesViewer",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(
        mode = "properties",
        openAtStartup = true)
@ActionID(
        category = "Window",
        id = "org.netbeans.printtemplates.CodeTemplatesViewer")
@ActionReference(
        path = "Menu/Window")
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_CodeTemplatesAction",
        preferredID = "CodeTemplatesViewer")
@NbBundle.Messages({
    "CTL_CodeTemplatesAction=Show Code Templates",
    "CTL_CodeTemplatesViewer=Available Code Templates",
})
public class CodeTemplatesViewer extends TopComponent implements ExplorerManager.Provider, ActionListener {

    private ExplorerManager em = new ExplorerManager();

    public CodeTemplatesViewer() {
        setName(Bundle.CTL_CodeTemplatesViewer());
        setLayout(new BorderLayout());
        OutlineView outlineView = new OutlineView("Abbreviation");
        outlineView.getOutline().setRootVisible(false);
        outlineView.setPropertyColumns("content", "Content");
        add(outlineView, BorderLayout.CENTER);
        JButton printButton = new JButton("Print");
        printButton.addActionListener(this);
        add(printButton, BorderLayout.NORTH);
        em.setRootContext(new AbstractNode(Children.create(new LanguageChildFactory(), false)));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        InputOutput io = IOProvider.getDefault().getIO("Code Templates", true);
        io.select();
        OutputWriter out = io.getOut();
        for (Node node : em.getRootContext().getChildren().getNodes()) {
            out.println("");
            out.println("");
            out.println("MIME TYPE: " + node.getDisplayName());
            out.println("");
            for (Node templateNode : node.getChildren().getNodes()) {
                CodeTemplate ct = templateNode.getLookup().lookup(CodeTemplate.class);
                String abbreviation = ct.getAbbreviation();
                String content = ct.getContent();
                out.println(abbreviation+" = "+content);
            }
            out.println("-------------------------------------------");
            out.println("");
            out.println("");
        }
    }

    private class LanguageFolder {
        private String name;
        private String folder;
        public LanguageFolder(String name, String folder) {
            this.name = name;
            this.folder = folder;
        }
        public String getFolder() {
            return folder;
        }
        public void setFolder(String folder) {
            this.folder = folder;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

    private class LanguageChildFactory extends ChildFactory<LanguageFolder> {
        @Override
        protected boolean createKeys(List<LanguageFolder> list) {
            FileObject[] textFolder = FileUtil.getConfigFile("Editors/text").getChildren();
            for (FileObject fileObject : textFolder) {
                FileObject codeTemplatesFolder = fileObject.getFileObject("CodeTemplates/Defaults");
                if (codeTemplatesFolder != null) {
                    list.add(new LanguageFolder(fileObject.getName(), codeTemplatesFolder.getPath()));
                }
            }
            return true;
        }
        @Override
        protected Node createNodeForKey(LanguageFolder key) {
            AbstractNode an = new AbstractNode(Children.create(new CodeTemplateChildFactory(key), false));
            an.setDisplayName(key.getName());
            an.setShortDescription(key.getFolder());
            return an;
        }
    }

    private class CodeTemplateChildFactory extends ChildFactory<CodeTemplate> {
        private final LanguageFolder key;
        private CodeTemplateChildFactory(LanguageFolder key) {
            this.key = key;
        }
        @Override
        protected boolean createKeys(List<CodeTemplate> list) {
            FileObject[] codeTemplateFiles = FileUtil.getConfigFile(key.getFolder()).getChildren();
            for (FileObject fileObject : codeTemplateFiles) {
                try {
                    Document doc = XMLUtil.parse(new InputSource(fileObject.getInputStream()), true, true, null, null);
                    NodeList cts = doc.getElementsByTagName("codetemplate");
                    for (int i = 0; i < cts.getLength(); i++) {
                        org.w3c.dom.Node node = cts.item(i);
                        String value = node.getAttributes().item(0).getNodeValue();
                        StringBuilder sb = new StringBuilder();
                        NodeList childNodes = node.getChildNodes();
                        for (int j = 0; j < childNodes.getLength(); j++) {
                            org.w3c.dom.Node item = childNodes.item(j);
                            sb.append(item.getTextContent());
                        }
                        list.add(new CodeTemplate(value, sb.toString().trim()));
                    }
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                } catch (SAXException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
            return true;
        }
        @Override
        protected Node createNodeForKey(CodeTemplate key) {
            TemplateNode node = null;
            try {
                node = new TemplateNode(key);
            } catch (IntrospectionException ex) {
                Exceptions.printStackTrace(ex);
            }
            return node;
        }
    }

    private class TemplateNode extends BeanNode {
        public TemplateNode(CodeTemplate key) throws IntrospectionException {
            super(key, Children.LEAF, Lookups.singleton(key));
            setDisplayName(key.getAbbreviation());
            setShortDescription(key.getContent());
        }
    }

    public class CodeTemplate {
        public String abbreviation;
        public String content;
        public CodeTemplate(String abbreviation, String content) {
            this.abbreviation = abbreviation;
            this.content = content;
        }
        public String getAbbreviation() {
            return abbreviation;
        }
        public String getContent() {
            return content;
        }
        public void setAbbreviation(String abbreviation) {
            this.abbreviation = abbreviation;
        }
        public void setContent(String content) {
            this.content = content;
        }
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return em;
    }

}

About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« July 2013 »
SunMonTueWedThuFriSat
 
5
10
14
21
27
28
29
30
31
   
       
Today