at.spardat.xma.guidesign.presentation.NewComponentWizard.java Source code

Java tutorial

Introduction

Here is the source code for at.spardat.xma.guidesign.presentation.NewComponentWizard.java

Source

/*******************************************************************************
 * Copyright (c) 2003, 2007 s IT Solutions AT Spardat GmbH .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     s IT Solutions AT Spardat GmbH - initial API and implementation
 *******************************************************************************/

/**
 * <copyright>
 * </copyright>
 *
 * %W%
 * @version %I% %H%
 */
package at.spardat.xma.guidesign.presentation;

import java.util.Collections;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.ISetSelectionTarget;

import at.spardat.xma.gui.projectw.cmp.BuildToolEnumeration;
import at.spardat.xma.gui.projectw.cmp.ComponentManipulation;
import at.spardat.xma.guidesign.GuidesignFactory;
import at.spardat.xma.guidesign.GuidesignPackage;
import at.spardat.xma.guidesign.XMAComponent;
import at.spardat.xma.guidesign.plugin.GUIDesignerPlugin;
import at.spardat.xma.guidesign.preferences.PreferenceConstants;

//import at.spardat.xma.;

/**
 * This is a simple wizard for creating a new model file.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public class NewComponentWizard extends Wizard implements INewWizard {
    /**
     * This caches an instance of the model package.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected GuidesignPackage guidesignPackage = GuidesignPackage.eINSTANCE;

    /**
     * This caches an instance of the model factory.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected GuidesignFactory guidesignFactory = guidesignPackage.getGuidesignFactory();

    /**
     * This is the file creation page.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected NewComponentCreationPage componentCreationPage;

    protected WizardPage badSelectionPage;
    /**
     * Remember the selection during initialization for populating the default container.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected IStructuredSelection selection;

    /**
     * Remember the workbench during initialization.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected IWorkbench workbench;

    /**
     * Remember the selected resource for creating entries in the appl descriptor and build file
     */
    protected IResource selectedResource;

    /**
     * This just records the information.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    public void init(IWorkbench workbench, IStructuredSelection selection) {
        this.workbench = workbench;
        this.selection = selection;
        setWindowTitle(GUIDesignerPlugin.INSTANCE.getString("_UI_Wizard_label"));
        setDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE
                .getImageDescriptor(GUIDesignerPlugin.INSTANCE.getImage("full/wizban/NewGuidesign")));
    }

    /**
     * Create a new model. <!-- begin-user-doc --> <!-- end-user-doc -->
     * 
     * @generated
     */
    EObject createInitialModel() {
        return createInitialModel(componentCreationPage.getNamPackage(), componentCreationPage.getNamClass());
    }

    /**
     * Create a new model. <!-- begin-user-doc --> <!-- end-user-doc -->
     * 
     * @generated
     */
    public static EObject createInitialModel(String namPackage, String namClass) {
        XMAComponent component = GuidesignFactory.eINSTANCE.createXMAComponent();
        component.setNamPackage(namPackage);
        component.setNamClass(namClass);
        //build the help uri
        StringBuffer uri = new StringBuffer(32);
        uri.append("help/");
        uri.append(component.getNamPackageAsPath());
        uri.append("/");
        uri.append(namClass);
        uri.append(".html");
        component.setUriHelp(uri.toString());

        return component;
    }

    /**
     * Do the work after everything is specified.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    public boolean performFinish() {
        try {
            // Remember the file.
            //
            final IFile modelFile = getModelFile();

            // Do the work within an operation.
            //
            WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
                protected void execute(IProgressMonitor progressMonitor) {
                    try {
                        // Create a resource set
                        //
                        ResourceSet resourceSet = new ResourceSetImpl();

                        // Get the URI of the model file.
                        //
                        URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString());

                        // Create a resource for this file.
                        //
                        Resource resource = resourceSet.createResource(fileURI);

                        // Add the initial model object to the contents.
                        //
                        EObject rootObject = createInitialModel();
                        if (rootObject != null) {
                            resource.getContents().add(rootObject);
                        }

                        // Save the contents of the resource to the file system.
                        //
                        resource.save(Collections.EMPTY_MAP);
                    } catch (Exception exception) {
                        GUIDesignerPlugin.INSTANCE.log(exception);
                    } finally {
                        progressMonitor.done();
                    }
                }
            };

            getContainer().run(false, false, operation);

            //augment the application descriptor and the build file with the new component info
            try {
                createApplicationDescriptor(selectedResource.getProject(), componentCreationPage.getNamPackage(),
                        componentCreationPage.getNamClass(), selectedResource.getName());
            } catch (Throwable ex) {
                String message = ex.getMessage() + "\n"
                        + GUIDesignerPlugin.INSTANCE.getString("_UI_WARN_AppDescrCreation_Failed_label");
                MessageDialog.openError(workbench.getActiveWorkbenchWindow().getShell(),
                        GUIDesignerPlugin.INSTANCE.getString("_UI_WARN_AppDescrCreation_Failed_text"), message);
                GUIDesignerPlugin.INSTANCE.log(ex);
            }

            // Select the new file resource in the current view.
            //
            IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
            IWorkbenchPage page = workbenchWindow.getActivePage();
            final IWorkbenchPart activePart = page.getActivePart();
            if (activePart instanceof ISetSelectionTarget) {
                final ISelection targetSelection = new StructuredSelection(modelFile);
                getShell().getDisplay().asyncExec(new Runnable() {
                    public void run() {
                        ((ISetSelectionTarget) activePart).selectReveal(targetSelection);
                    }
                });
            }

            // Open an editor on the new file.
            //
            try {
                // TODO Prio 1: an 3.0 API anpassen
                IDE.openEditor(page, modelFile);
            } catch (PartInitException exception) {
                MessageDialog.openError(workbenchWindow.getShell(),
                        GUIDesignerPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage());
                return false;
            }

            return true;
        } catch (Exception exception) {
            GUIDesignerPlugin.INSTANCE.log(exception);
            return false;
        }
    }

    public static void createApplicationDescriptor(IProject project, String namPackage, String namClass,
            String ResourceName) {

        ComponentManipulation compManipulation = new ComponentManipulation(project);

        if (BuildToolEnumeration.ANT.equals(GUIDesignerPlugin.getPlugin().getBuildTool(project))) {
            compManipulation.createComponent(namClass, namPackage);
        } else {

            compManipulation.createComponent(namClass, namPackage,
                    GUIDesignerPlugin.getPlugin().getApplicationDescriptorFolder(project, ResourceName + "/"),
                    GUIDesignerPlugin.getPlugin().getBuildTool(project));
        }
    }

    /**
     * recursivly creates the folder and all missing parent-folders
     * @param folder
     * @throws CoreException if the eclipse Resources are a mess.
     */
    public static void mkdirs(IFolder folder) throws CoreException {
        IResource parent = folder.getParent();
        if (!parent.exists()) {
            if (parent instanceof IFolder) {
                mkdirs((IFolder) parent);
            } else {
                throw new CoreException(new Status(Status.ERROR, "guidesign", 13,
                        "cannot create " + parent.getFullPath().toString(), null));
            }
        }
        folder.create(true, true, null);
    }

    public static IFile getComponentFile(IProject curProject, String namComponent, String namPackage,
            String filenameExtension) throws CoreException {
        String modelFilename = namComponent + "." + filenameExtension;
        //create the path
        String path = GUIDesignerPlugin.getPlugin().getJavaSourceFolder(curProject) + namPackage.replace('.', '/');
        IFolder folder = curProject.getFolder(path);
        if (!folder.exists()) {
            mkdirs(folder);
        }
        return ResourcesPlugin.getWorkspace().getRoot().getFile(folder.getFullPath().append(modelFilename));
    }

    /**
     * This is the page where the component attributes are defined.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    public class NewComponentCreationPage extends WizardPage implements Listener {
        /*
         * Remember the curently selected project
         */
        private IProject curProject;

        /**
         * Remember the input field for the package
         */
        private Text texPackage;

        /**
         * Remember the input field for the class and xma filename
         */
        private Text texClass;

        /**
         * Pass in the selection.
         * <!-- begin-user-doc -->
         * <!-- end-user-doc -->
         * @generated
         */
        public NewComponentCreationPage(String pageId) {
            super(pageId);

        }

        /**
         * <!-- begin-user-doc -->
         * <!-- end-user-doc -->
         * @generated
         */
        public void createControl(Composite parent) {
            Composite composite = new Composite(parent, SWT.NONE);
            {
                GridLayout layout = new GridLayout();
                layout.numColumns = 1;
                layout.verticalSpacing = 12;
                composite.setLayout(layout);

                GridData data = new GridData();
                data.verticalAlignment = GridData.FILL;
                data.grabExcessVerticalSpace = true;
                data.horizontalAlignment = GridData.FILL;
                composite.setLayoutData(data);
            }

            Label pmtPackage = new Label(composite, SWT.LEFT);
            {
                pmtPackage.setText(GUIDesignerPlugin.INSTANCE.getString("_UI_Wizard_Package_label"));
                GridData data = new GridData();
                data.horizontalAlignment = GridData.FILL;
                pmtPackage.setLayoutData(data);
            }

            texPackage = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            {
                texPackage.setText(getDefaultPackage());
                GridData data = new GridData();
                data.horizontalAlignment = GridData.FILL;
                data.grabExcessHorizontalSpace = true;
                // data.horizontalSpan = 2;
                texPackage.setLayoutData(data);
                texPackage.addListener(SWT.Modify, this);
            }

            Label pmtClass = new Label(composite, SWT.LEFT);
            {
                pmtClass.setText(GUIDesignerPlugin.INSTANCE.getString("_UI_Wizard_Class_label"));
                GridData data = new GridData();
                data.horizontalAlignment = GridData.FILL;
                pmtClass.setLayoutData(data);
            }

            texClass = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            {
                texClass.setText(GUIDesignerPlugin.INSTANCE.getString("_UI_GuidesignEditorFilenameDefaultBase"));
                GridData data = new GridData();
                data.horizontalAlignment = GridData.FILL;
                data.grabExcessHorizontalSpace = true;
                // data.horizontalSpan = 2;
                texClass.setLayoutData(data);
                texClass.addListener(SWT.Modify, this);
            }
            setControl(composite);
        }

        /**
         * The framework calls this to see if the file is correct.
         * <!-- begin-user-doc -->
         * <!-- end-user-doc -->
         * @modifed
         */
        public boolean isPageComplete() {
            if (isPackageValid() && isClassValid()) {
                return true;
            } else {
                return false;
            }
        }

        /**
         *
         * @return true if the texPackage input field has a valid content
         */
        private boolean isPackageValid() {
            if (getNamPackage() == null) {
                //no input in the package input field
                setErrorMessage("Packagename may not be empty!");
                return false;
            }
            if (!getNamPackage().toLowerCase().equals(getNamPackage())) {
                //Uppercase letters in package contained
                setErrorMessage("Package name may not contain upper case letters!");
                return false;
            }
            if (getNamPackage().endsWith(".")) {
                //package is not completed
                setErrorMessage("Package may not end with a dot!");
                return false;
            }
            if (XmaResourceInPackageExists()) {
                //package is not completed
                setErrorMessage("A component resource file already exists in this package!");
                return false;
            }
            setErrorMessage(null);
            return true;
        }

        /**
         *
         * @return true if the package already exists
         */
        private boolean XmaResourceInPackageExists() {
            try {
                String path = GUIDesignerPlugin.getPlugin().getJavaSourceFolder(curProject)
                        + getNamPackage().replace('.', '/');
                IFolder folder = curProject.getFolder(path);
                if (folder.exists()) {
                    IResource[] resources = folder.members();
                    for (int i = 0; i < resources.length; i++) {
                        if (resources[i].getFileExtension() != null
                                && resources[i].getFileExtension().equals("xma")) {
                            return true;
                        }
                    }
                }
                return false;
            } catch (CoreException ex) {
                ex.printStackTrace();
                return true;
            }
        }

        /**
         *
         * @return true if the texClass input field has a valid content
         * @modified
         */
        private boolean isClassValid() {
            if (getNamClass() == null) {
                setErrorMessage("Classname may not be empty!");
                return false;
            }
            setErrorMessage(null);
            return true;
        }

        /**
         * Store the dialog field settings upon completion.
         * @modified
         */
        public boolean performFinish() {
            return true;
        }

        /**
         *
         * @return the packagename from the input field
         * @modified
         */
        public String getNamPackage() {
            if (texPackage.getText().equals("")) {
                return null;
            } else {
                return texPackage.getText();
            }
        }

        /**
         *
         * @return the classname from the input field
         * @modified
         */
        public String getNamClass() {
            if (texClass.getText().equals("")) {
                return null;
            } else {
                return texClass.getText();

            }
        }

        /**
         *
         * @return the default for the package input field
         */
        private String getDefaultPackage() {
            StringBuffer result = new StringBuffer("at.spardat.");
            if (curProject != null) {
                String projname = curProject.getFullPath().segment(0);
                result.append(projname.toLowerCase());
                result.append(".");
            }
            return result.toString();
        }

        /**
         * set the current project field
         * @param project
         */
        public void setProject(IProject project) {
            curProject = project;
        }

        public IFile getComponentFile() {
            try {
                String filenameExtension = GUIDesignerPlugin.INSTANCE
                        .getString("_UI_GuidesignEditorFilenameExtension");
                return NewComponentWizard.getComponentFile(curProject, getNamClass(), getNamPackage(),
                        filenameExtension);
            } catch (Exception ex) {
                GUIDesignerPlugin.INSTANCE.log(ex);
                return null;
            }
        }

        /* (non-Javadoc)
         * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
         */
        public void handleEvent(Event event) {
            setPageComplete(isPageComplete());
        }

    }

    /**
     * This is the page where the component attributes are defined.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    public class ErrorPage extends WizardPage implements Listener {
        /**
         * Pass in the selection.
         * @modified
         */
        public ErrorPage(String pageId) {
            super(pageId);

        }

        /**
         * Pass in the selection.
         * @modified
         */
        public void createControl(Composite parent) {
            Composite composite = new Composite(parent, SWT.NONE);
            {
                GridLayout layout = new GridLayout();
                layout.numColumns = 1;
                layout.verticalSpacing = 12;
                composite.setLayout(layout);

                GridData data = new GridData();
                data.verticalAlignment = GridData.FILL;
                data.grabExcessVerticalSpace = true;
                data.horizontalAlignment = GridData.FILL;
                composite.setLayoutData(data);
            }
            setControl(composite);
        }

        /**
         *
         * @modified
         */
        public boolean performFinish() {
            return false;
        }

        /* (non-Javadoc)
         * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
         */
        public void handleEvent(Event event) {
            setPageComplete(isPageComplete());
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.wizard.IWizardPage#isPageComplete()
         */
        public boolean isPageComplete() {
            setErrorMessage(GUIDesignerPlugin.INSTANCE.getString("_ERR_NoResource_selection"));
            setPreviousPage(null);
            return false;
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.dialogs.DialogPage#setErrorMessage(java.lang.String)
         */
        public void setErrorMessage(String newMessage) {
            super.setErrorMessage(newMessage);
        }

    }

    /**
     * The framework calls this to create the contents of the wizard.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @modified
     */
    public void addPages() {
        // Try and get the resource selection to determine a current directory for the file dialog.
        selectedResource = getSelectedResource(selection);
        if (selectedResource != null) {
            componentCreationPage = new NewComponentCreationPage("Component Creation");
            componentCreationPage.setTitle(GUIDesignerPlugin.INSTANCE.getString("_UI_GuidesignModelWizard_label"));
            componentCreationPage
                    .setDescription(GUIDesignerPlugin.INSTANCE.getString("_UI_Wizard_initial_object_description"));
            componentCreationPage.setProject(selectedResource.getProject());
            addPage(componentCreationPage);
        } else {
            badSelectionPage = new ErrorPage("Error");
            badSelectionPage.setTitle(GUIDesignerPlugin.INSTANCE.getString("_UI_GuidesignModelWizard_label"));
            badSelectionPage.setDescription(GUIDesignerPlugin.INSTANCE.getString("_ERR_NoResource_selection"));
            addPage(badSelectionPage);
        }
    }

    public static IResource getSelectedResource(IStructuredSelection selection) {
        // Try and get the resource selection to determine a current directory for the file dialog.
        IResource selectedResource = null;
        if (selection != null && !selection.isEmpty()) {
            // Get the resource...
            //
            Object selectedElement = selection.iterator().next();
            if (selectedElement instanceof IResource) {
                // Get the resource parent, if its a file.
                //
                selectedResource = (IResource) selectedElement;
                if (selectedResource.getType() == IResource.FILE) {
                    selectedResource = selectedResource.getParent();
                }
            }
        }
        return selectedResource;
    }

    /**
     * Get the file from the page.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    public IFile getModelFile() {
        return componentCreationPage.getComponentFile();
    }
}