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-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.java.ui.wizard;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.NoSuchElementException;

import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeListener;

import org.openide.ErrorManager;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataFolder;
import org.openide.loaders.TemplateWizard;
import org.openide.util.Utilities;
import org.openide.util.NbBundle;

import org.openide.src.Type;

import org.netbeans.modules.java.JavaDataLoader;
import org.netbeans.api.java.classpath.ClassPath;

public class JavaWizardIterator implements TemplateWizard.Iterator {
    private static final long serialVersionUID = -1987345873459L;

    /** Array of panels that form the Wizard.
     */
    private transient WizardDescriptor.Panel[] panels;

    /**
     * Names for panels used in the Wizard.
     */
    private static String[] panelNames;
    
    /** Singleton instance of JavaWizardIterator, should it be ever needed.
     */
    private static JavaWizardIterator instance;
    
    /** Index of the current panel. Panels are numbered from 0 to PANEL_COUNT - 1.
     */
    private transient int panelIndex = 0;
    
    /**
     * Holds a reference to the instance of TemplateWizard we are communicating with.
     */
    private transient TemplateWizard wizardInstance;

    public JavaWizardIterator() {
    }
    
    /** Returns JavaWizardIterator singleton instance. This method is used
     * for constructing the instance from filesystem.attributes.
     */
    public static synchronized JavaWizardIterator singleton() {
        if (instance == null) {
            instance = new JavaWizardIterator();
        }
        return instance;
    }
    // ========================= TemplateWizard.Iterator ============================

    /** Instantiates the template using informations provided by
     * the wizard.
     *
     * @param wiz the wizard
     * @return set of data objects that has been created (should contain
     *  at least one
     * @exception IOException if the instantiation fails
    */
    public java.util.Set instantiate(TemplateWizard wiz) throws IOException, IllegalArgumentException {
        DataObject obj = instantiateTemplate(wiz.getTemplate(), wiz.getTargetFolder(), wiz.getTargetName());

        // run default action (hopefully should be here)
        final org.openide.nodes.Node node = obj.getNodeDelegate ();
        final org.openide.util.actions.SystemAction sa = node.getDefaultAction ();
        if (sa != null) {
            SwingUtilities.invokeLater(new Runnable () {
                public void run () {
                    sa.actionPerformed (new ActionEvent (node, ActionEvent.ACTION_PERFORMED, "")); // NOI18N
                }
            });
        }
        return java.util.Collections.singleton(obj);
    }
    
    public WizardDescriptor.Panel current() {
        return panels[panelIndex];
    }
    
    public String name() {
        return ""; // NOI18N
    }
    
    public boolean hasNext() {
        return false;
    }
    
    public boolean hasPrevious() {
        return false;
    }
    
    public void nextPanel() {
        throw new NoSuchElementException();
    }
    
    public void previousPanel() {
        throw new NoSuchElementException();
    }
    
    /** Add a listener to changes of the current panel.
     * The listener is notified when the possibility to move forward/backward changes.
     * @param l the listener to add
    */
    public void addChangeListener(ChangeListener l) {
    }
    
    /** Remove a listener to changes of the current panel.
     * @param l the listener to remove
    */
    public void removeChangeListener(ChangeListener l) {
    }

    public void initialize(TemplateWizard wizard) {
        this.wizardInstance = wizard;
        
	if (panels == null) {
            
            Component panel = wizard.targetChooser().getComponent();
            panelNames = new String[]{panel.getName()};
            if (panel instanceof javax.swing.JComponent) {
                ((javax.swing.JComponent)panel).putClientProperty(
                    "WizardPanel_contentData", panelNames); // NOI18N
            }
            panels = new WizardDescriptor.Panel[] {
                wizardInstance.targetChooser()
            };
	}
    }
    
    public void uninitialize(TemplateWizard wiz) {
	    panels = null;
        wizardInstance = null;
    }

    // ========================= IMPLEMENTATION ============================
    
    private Object readResolve() {
        return singleton();
    }
    
    /** Instantiates the template. Currently it just delegates to the template DataObject's
     * createFromTemplate method.
     */
    private DataObject instantiateTemplate(DataObject tpl, DataFolder target, String name) throws IOException {
        if (name == null) {
            name = getDefaultName(tpl, target);
        }
        
        checkValidPackageName(target);
        checkTargetName(target, name);
        return tpl.createFromTemplate(target, name);
    }
    
    private boolean isValidPackageName(String s) {
        // valid package is an empty one, or well-formed java identifier :-)
        if ("".equals(s)) // NOI18N
            return true;
        try {
            Type t = Type.parse(s);
            return true;
        } catch (IllegalArgumentException ex) {
            return false;
        }
    }
    
    private void checkValidPackageName(DataFolder targetFolder) 
        throws IllegalStateException {
        FileObject folder = targetFolder.getPrimaryFile();
        ClassPath cp = ClassPath.getClassPath(folder,ClassPath.SOURCE);
        String msg = null;
        if (cp != null) {
            String fullTarget = cp.getResourceName(folder, '.',false);
            if (isValidPackageName (fullTarget)) {
                return;
            }
            else {
                msg = MessageFormat.format(getString("FMTERR_IllegalFolderName"), // NOI18N
                    new Object[] {
                    folder.getPath(),
                    fullTarget});
            }
        }
        else {
            msg = getString ("ERR_NotInSourcePath");
        }
        // checking for java-compatible name - both the folder name and the target name
        // must be acceptable.
        throw (IllegalStateException)ErrorManager.getDefault().annotate(
            new IllegalStateException(msg),
            ErrorManager.USER, null, msg,
            null, null);
    }
    
    /** 
     * @param folder target folder for java file
     * @param desiredName name to check
     * @return true if the desiredName is OK
     */ 
    private boolean checkTargetName(DataFolder folder, String desiredName) {
        if (!Utilities.isJavaIdentifier(desiredName)) {
            String msg = MessageFormat.format(getString("FMTERR_IllegalTargetName"), // NOI18N
            new Object[] {
                desiredName
            });
            notifyError(msg);
            return false;
        }
        
        FileObject f = folder.getPrimaryFile();
        // check whether the name already exists:
        if (f.getFileObject(desiredName, JavaDataLoader.JAVA_EXTENSION) != null) {
            String msg = MessageFormat.format(getString("FMTERR_TargetExists"), // NOI18N
            new Object[] {
                desiredName
            });
            notifyError(msg);
            return false;
        }
        return true;
    }
    
    private void notifyError(String msg) {
        this.wizardInstance.putProperty("WizardPanel_errorMessage", msg); //NOI18N
        IllegalStateException ex = new IllegalStateException(msg);
        ErrorManager.getDefault().annotate(ex, ErrorManager.USER, null, msg, null, null);
        throw ex;
    }
    
    private String getDefaultName(DataObject template, DataFolder targetFolder) {
        String desiredName = org.openide.filesystems.FileUtil.findFreeFileName(targetFolder.getPrimaryFile(),
            template.getName(), JavaDataLoader.JAVA_EXTENSION);
        return desiredName;
    }

    static String getString(String key) {
        return NbBundle.getMessage(JavaWizardIterator.class, key);
    }
    
    static char getMnemonic(String key) {
	    return getString(key).charAt(0);
    }
}
... 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.