mt.com.southedge.jclockwork.plugin.wizard.MainObjectMapWizardPage.java Source code

Java tutorial

Introduction

Here is the source code for mt.com.southedge.jclockwork.plugin.wizard.MainObjectMapWizardPage.java

Source

/**
 * 
 */
package mt.com.southedge.jclockwork.plugin.wizard;

/* ******************************************************************************
 * Copyright (c) 2011 SouthEdge Software and Consultancy.  
 * 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:
 *     Carl Frendo - initial design and implementation
 * ******************************************************************************/

/*
 * 15-03-2011 - Added addDelimiter method.
 * 23-03-2011 - Added check for non-bean classes
 */
import java.lang.reflect.Method;

import mt.com.southedge.jclockwork.commons.log.util.StatusInfo;
import mt.com.southedge.jclockwork.plugin.classloader.JClockWorkClassLoader;
import mt.com.southedge.jclockwork.plugin.messages.ClockWorkWizardMessages;
import mt.com.southedge.jclockwork.plugin.utils.IgnoreMethodUtil;
import mt.com.southedge.jclockwork.plugin.wizard.controls.CreateControlLabel;
import mt.com.southedge.jclockwork.plugin.wizard.controls.CreateControlObject;
import mt.com.southedge.jclockwork.plugin.wizard.controls.CreateSelectionButtonGroup;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.wizards.NewTypeWizardPage;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

/**
 * 
 * @author cfrendo
 * 
 */
public class MainObjectMapWizardPage extends NewTypeWizardPage {

    private static final int FOUR = 4;
    private static final String PAGE_NAME = "MainObjectMapWizardPage"; //$NON-NLS-1$

    private static final String SETTINGS_CREATEMAIN = "create_main"; //$NON-NLS-1$
    private static final String SETTINGS_CREATECONSTR = "create_constructor"; //$NON-NLS-1$
    private static final String SETTINGS_CREATEUNIMPLEMENTED = "create_unimplemented"; //$NON-NLS-1$

    private IStatus statusSourceBean;
    private IStatus statusTargetBean;

    private CreateSelectionButtonGroup createSelectionButtonGroup;
    private CreateControlObject sourceControlObject;
    private CreateControlObject targetControlObject;

    private StatusInfo statInfo;

    private IJavaElement jelem;

    private TypeFieldListenerAdapter adapter = new TypeFieldListenerAdapter();

    /**
     * Simple constructor.
     */
    public MainObjectMapWizardPage() {
        super(true, PAGE_NAME);

        setTitle(ClockWorkWizardMessages.ClockWorkWizard_Title);
        setDescription(ClockWorkWizardMessages.ClockWorkWizard_Description);

        String[] buttonNames3 = new String[] { ClockWorkWizardMessages.ClockWorkWizard_Create_Main_Method,
                ClockWorkWizardMessages.ClockWorkWizard_Create_Super_Constructor,
                ClockWorkWizardMessages.ClockWorkWizard_Create_Inherited_Methods };

        createSelectionButtonGroup = new CreateSelectionButtonGroup(SWT.CHECK, buttonNames3, 1,
                ClockWorkWizardMessages.ClockWorkWizard_Create_Method_Stubs);

    }

    /**
     * Method that creates all the controls in the wizard form.
     * 
     * @param parent the composite
     */
    public void createControl(Composite parent) {
        initializeDialogUnits(parent);

        Composite composite = new Composite(parent, SWT.NONE);
        composite.setFont(parent.getFont());

        int nColumns = FOUR;

        GridLayout layout = new GridLayout();
        layout.numColumns = nColumns;
        composite.setLayout(layout);

        createContainerControls(composite, nColumns);
        createPackageControls(composite, nColumns);

        createSeparator(composite, nColumns);

        createTypeNameControls(composite, nColumns);
        createModifierControls(composite, nColumns);

        createSuperClassControls(composite, nColumns);
        createSuperInterfacesControls(composite, nColumns);

        createMethodStubSelectionControls(composite, nColumns);

        createSeparator(composite, nColumns);

        sourceControlObject = createBeanControls(composite, nColumns,
                new CreateControlObject(ClockWorkWizardMessages.ClockWorkWizard_Source_Label,
                        ClockWorkWizardMessages.ClockWorkWizard_Browse_Button));

        targetControlObject = createBeanControls(composite, nColumns,
                new CreateControlObject(ClockWorkWizardMessages.ClockWorkWizard_Target_Label,
                        ClockWorkWizardMessages.ClockWorkWizard_Browse_Button));

        setControl(composite);

        Dialog.applyDialogFont(composite);
    }

    /**
     * 
     * @param composite the compsite
     * @param nColumns the number of columns
     * @param controlObject the controlObject
     * @return
     */
    public CreateControlObject createBeanControls(Composite composite, int nColumns,
            CreateControlObject controlObject) {

        controlObject.createBeanControls(composite, nColumns);
        controlObject.getTextbox().addModifyListener(adapter);
        return controlObject;

    }

    /**
     * 
     * @param selection the init selection
     */
    public void init(IStructuredSelection selection) {
        jelem = getInitialJavaElement(selection);
        initContainerPage(jelem);
        initTypePage(jelem);
        doStatusUpdate();

        boolean createMain = false;
        boolean createConstructors = false;
        boolean createUnimplemented = true;
        IDialogSettings dialogSettings = getDialogSettings();
        if (dialogSettings != null) {
            IDialogSettings section = dialogSettings.getSection(PAGE_NAME);
            if (section != null) {
                createMain = section.getBoolean(SETTINGS_CREATEMAIN);
                createConstructors = section.getBoolean(SETTINGS_CREATECONSTR);
                createUnimplemented = section.getBoolean(SETTINGS_CREATEUNIMPLEMENTED);
            }
        }

        setMethodStubSelection(createMain, createConstructors, createUnimplemented, true);

    }

    private void createMethodStubSelectionControls(Composite composite, int nColumns) {

        Control labelControl = createSelectionButtonGroup.getLabelControl(composite);

        setHorizontalSpan(labelControl, nColumns);

        CreateControlLabel.createEmptySpace(composite);

        Control buttonGroup = createSelectionButtonGroup.getSelectionButtonsGroup(composite);

        setHorizontalSpan(buttonGroup, nColumns - 1);

    }

    private void setHorizontalSpan(Control control, int nColumns) {
        Object ld = control.getLayoutData();
        if (ld instanceof GridData) {
            ((GridData) ld).horizontalSpan = nColumns;
        } else if (nColumns != 1) {
            GridData gd = new GridData();
            gd.horizontalSpan = nColumns;
            control.setLayoutData(gd);
        }
    }

    private class TypeFieldListenerAdapter implements ModifyListener {

        /**
         * @param e the event
         */
        public void modifyText(ModifyEvent e) {
            handleFieldChanged("CONTAINER");
        }

    }

    /**
     * 
     * @param createMain set enabled the main method control check box
     * @param createConstructors set enabled the super constructor check box
     * @param createInherited set enabled the create inherited methods check box
     * @param canBeModified
     */
    public void setMethodStubSelection(boolean createMain, boolean createConstructors, boolean createInherited,
            boolean canBeModified) {
        createSelectionButtonGroup.setSelection(0, createMain);
        createSelectionButtonGroup.setSelection(1, createConstructors);
        createSelectionButtonGroup.setSelection(2, createInherited);

    }

    /**
     * Updates the IStatuses of specified controls.
     */
    public void doStatusUpdate() {
        IStatus[] status = new IStatus[] { fContainerStatus,
                isEnclosingTypeSelected() ? fEnclosingTypeStatus : fPackageStatus, fTypeNameStatus, fModifierStatus,
                fSuperClassStatus, fSuperInterfacesStatus, statusSourceBean, statusTargetBean };
        updateStatus(status);
    }

    /**
     * Method that is called each time a control specified from the doStatusUpdate is modified.
     */
    protected void handleFieldChanged(String fieldName) {
        super.handleFieldChanged(fieldName);
        statusSourceBean = statusSourceChanged();
        statusTargetBean = statusTargetChanged();

        doStatusUpdate();
    }

    private IStatus statusSourceChanged() {
        statInfo = new StatusInfo();
        IPackageFragmentRoot root = getPackageFragmentRoot();

        if (sourceControlObject != null) {
            sourceControlObject.getButton().setEnabled(root != null);
        }

        if (root == null) {
            statInfo.setError("");
            return statInfo;
        }

        if (sourceControlObject != null) {
            String textValue = sourceControlObject.getTextbox().getText();

            if (textValue.length() == 0) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Source_Empty);
                return statInfo;
            }

            if (checkForBeans()) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Source_Target_Match);
                return statInfo;
            }

            try {
                JClockWorkClassLoader loader = JClockWorkClassLoader.getInstance();
                loader.createClassLoader(getJavaProject()).loadClass(sourceControlObject.getTextbox().getText());
            } catch (ClassNotFoundException i) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Source_TSIXE);
                return statInfo;
            } catch (CoreException e) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Source_TSIXE);
                return statInfo;
            }

            try {
                Method[] methods = Class.forName(sourceControlObject.getTextbox().getText()).getDeclaredMethods();

                boolean foundGetter = false;
                for (Method method : methods) {
                    if ((method.getName().startsWith("get") || method.getName().startsWith("is"))
                            && !IgnoreMethodUtil.containsNameExceptions(method.getName())) {
                        foundGetter = true;
                    }
                }

                if (!foundGetter) {
                    statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Source_NoGetterInClass);
                    return statInfo;
                }
            } catch (SecurityException e) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Source_InvalidClass);
                return statInfo;
            } catch (ClassNotFoundException e) {
                // should not happen. Loaded class
            }
        }
        return statInfo;
    }

    private boolean checkForBeans() {
        return sourceControlObject.getTextbox().getText().equals(targetControlObject.getTextbox().getText());
    }

    private IStatus statusTargetChanged() {
        statInfo = new StatusInfo();
        IPackageFragmentRoot root = getPackageFragmentRoot();

        if (targetControlObject != null) {
            targetControlObject.getButton().setEnabled(root != null);
        }

        if (root == null) {
            statInfo.setError("");
            return statInfo;
        }

        if (targetControlObject != null) {
            String textValue = targetControlObject.getTextbox().getText();

            if (textValue.length() == 0) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Target_Empty);
                return statInfo;
            }
            if (checkForBeans()) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Source_Target_Match);
                return statInfo;
            }

            try {
                JClockWorkClassLoader loader = JClockWorkClassLoader.getInstance();
                loader.createClassLoader(getJavaProject()).loadClass(targetControlObject.getTextbox().getText());
            } catch (ClassNotFoundException i) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Target_TSIXE);
                return statInfo;
            } catch (CoreException e) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Target_TSIXE);
            }

            try {
                Method[] methods = Class.forName(targetControlObject.getTextbox().getText()).getDeclaredMethods();

                boolean foundGetter = false;
                for (Method method : methods) {
                    if ((method.getName().startsWith("get") || method.getName().startsWith("is"))
                            && !IgnoreMethodUtil.containsNameExceptions(method.getName())) {
                        foundGetter = true;
                    }
                }

                if (!foundGetter) {
                    statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Target_NoGetterInClass);
                    return statInfo;
                }
            } catch (SecurityException e) {
                statInfo.setError(ClockWorkWizardMessages.ClockWorkWizard_Target_InvalidClass);
                return statInfo;
            } catch (ClassNotFoundException e) {
                // should not happen. Loaded class
            }
        }
        return statInfo;
    }

    /**
     * @param visible sets visible enabled controls visible or not visible
     */
    public void setVisible(boolean visible) {
        super.setVisible(visible);
        if (visible) {
            setFocus();
        } else {
            IDialogSettings dialogSettings = getDialogSettings();
            if (dialogSettings != null) {
                IDialogSettings section = dialogSettings.getSection(PAGE_NAME);
                if (section == null) {
                    section = dialogSettings.addNewSection(PAGE_NAME);
                }
                section.put(SETTINGS_CREATEMAIN, createSelectionButtonGroup.isSelected(0));
                section.put(SETTINGS_CREATECONSTR, createSelectionButtonGroup.isSelected(1));
                section.put(SETTINGS_CREATEUNIMPLEMENTED, createSelectionButtonGroup.isSelected(2));
            }
        }
    }

    /**
     * method designed to be called on finish.
     * 
     * @param type the file type to be created
     * @param imports the imports to be added
     * @param monitor handles the process
     */
    protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor)
            throws CoreException {

        boolean doMain = createSelectionButtonGroup.isSelected(0);
        boolean doConstr = createSelectionButtonGroup.isSelected(1);
        boolean doInherited = createSelectionButtonGroup.isSelected(2);

        createInheritedMethods(type, doConstr, doInherited, imports, new SubProgressMonitor(monitor, 1));

        if (doMain) {
            StringBuffer buf = new StringBuffer();
            final String lineDelim = "\n"; //$NON-NLS-1$
            String comment = CodeGeneration.getMethodComment(type.getCompilationUnit(),
                    type.getTypeQualifiedName('.'), "main", new String[] { "args" }, new String[0], //$NON-NLS-1$//$NON-NLS-2$
                    Signature.createTypeSignature("void", true), null, lineDelim); //$NON-NLS-1$
            if (comment != null) {
                buf.append(comment);
                buf.append(lineDelim);
            }
            buf.append("public static void main("); //$NON-NLS-1$ 
            buf.append(imports.addImport("java.lang.String")); //$NON-NLS-1$
            buf.append("[] args) {"); //$NON-NLS-1$
            buf.append(lineDelim);
            final String content = CodeGeneration.getMethodBodyContent(type.getCompilationUnit(),
                    type.getTypeQualifiedName('.'), "main", false, "", lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
            if (content != null && content.length() != 0)
                buf.append(content);
            buf.append(lineDelim);
            buf.append("}"); //$NON-NLS-1$
            type.createMethod(buf.toString(), null, false, null);
        }

        if (monitor != null) {
            monitor.done();
        }
    }

    /**
     * @return the sourceControlObject
     */
    public CreateControlObject getSourceControlObject() {
        return sourceControlObject;
    }

    /**
     * @return the targetControlObject
     */
    public CreateControlObject getTargetControlObject() {
        return targetControlObject;
    }

    /**
     * @return the jelem
     */
    public IJavaElement getJelem() {
        return jelem;
    }
}