metabup.annotations.wizards.NewAnnotationWizard.java Source code

Java tutorial

Introduction

Here is the source code for metabup.annotations.wizards.NewAnnotationWizard.java

Source

/*******************************************************************************
 * Copyright (c) 2015 IBM Corporation and others.
 * 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:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package metabup.annotations.wizards;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;

import metabup.annotations.Activator;
import metabup.annotations.general.AnnotationHandler;
import metabup.annotations.preferences.AnnotationsPluginPreferenceConstants;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;
import org.osgi.framework.Bundle;

/**
 * This is a sample new wizard. Its role is to create a new file 
 * resource in the provided container. If the container resource
 * (a folder or a project) is selected in the workspace 
 * when the wizard is opened, it will accept it as the target
 * container. The wizard creates one file with the extension
 * "java". If a sample multi-page editor (also available
 * as a template) is registered for the same extension, it will
 * be able to open it.
 */

public class NewAnnotationWizard extends Wizard implements INewWizard {
    private NewAnnotationWizardPage page;
    private ISelection selection;

    /**
     * Constructor for NewAnnotationWizard.
     */
    public NewAnnotationWizard() {
        super();
        setNeedsProgressMonitor(true);
    }

    /**
     * Adding the page to the wizard.
     */

    public void addPages() {
        page = new NewAnnotationWizardPage(selection);
        addPage(page);
    }

    /**
     * This method is called when 'Finish' button is pressed in
     * the wizard. We will create an operation and run it
     * using wizard as execution context.
     */
    public boolean performFinish() {
        final String projectName = page.getProjectName();
        final String fileName = page.getFileName();
        final String annotationName = page.getAnnotationName();
        final String description = page.getDescription();

        IRunnableWithProgress op = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException {
                try {
                    doFinish(projectName, fileName, annotationName, description, monitor);
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                } finally {
                    monitor.done();
                }
            }
        };

        try {
            getContainer().run(true, false, op);
        } catch (InterruptedException e) {
            return false;
        } catch (InvocationTargetException e) {
            Throwable realException = e.getTargetException();
            MessageDialog.openError(getShell(), "Error", realException.getMessage());
            return false;
        }
        return true;
    }

    /**
     * The worker method. It will find the container, create the
     * file if missing or just replace its contents, and open
     * the editor on the newly created file.
     */

    private void doFinish(String projectName, String fileName, String annotationName, String description,
            IProgressMonitor monitor) throws CoreException {
        // create a sample file
        monitor.beginTask("Creating " + fileName, 2);
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IResource resource = root.findMember(new Path(projectName));
        if (!resource.exists() || !(resource instanceof IProject))
            throwCoreException("Project \"" + projectName + "\" does not exist.");

        monitor.worked(1);

        IProject project = (IProject) resource;

        /*
         * Turn project into a Java project, if not yet
         */

        IProjectDescription projectDescription = project.getDescription();
        String javaNature[] = { JavaCore.NATURE_ID };
        String projectNatures[] = projectDescription.getNatureIds();

        boolean isJavaEnabled = false;

        for (int i = 0; i < projectNatures.length; i++) {
            if (projectNatures[i].equals(javaNature[0])) {
                isJavaEnabled = true;
                i = projectNatures.length;
            }
        }

        IJavaProject javaProject = JavaCore.create(project);

        if (!isJavaEnabled) {
            IProjectDescription pDescription = project.getDescription();
            pDescription.setNatureIds(new String[] { JavaCore.NATURE_ID });
            project.setDescription(pDescription, monitor);

            IFolder binFolder = project.getFolder("bin");
            if (!binFolder.exists())
                binFolder.create(false, true, monitor);
            javaProject.setOutputLocation(binFolder.getFullPath(), monitor);

        }

        monitor.worked(1);

        //Import Activator library

        Bundle plugin = Activator.getDefault().getBundle();

        IPath relativePagePath = new Path(AnnotationsPluginPreferenceConstants.P_ANNOTATIONS_LIB_FILES);
        URL fileInPlugin = FileLocator.find(plugin, relativePagePath, null);

        if (fileInPlugin != null) {
            // the file exists         
            URL fileUrl;
            try {
                fileUrl = FileLocator.toFileURL(fileInPlugin);

                File file = new File(fileUrl.getPath());

                IClasspathEntry libEntry[] = { JavaCore.newLibraryEntry(new Path(file.getAbsolutePath()), null, // no source
                        null, // no source
                        false) }; // not exported

                monitor.worked(1);

                //set the build path      
                IClasspathEntry[] buildPath = { JavaCore.newSourceEntry(project.getFullPath().append("src")),
                        JavaRuntime.getDefaultJREContainerEntry(), libEntry[0] };

                javaProject.setRawClasspath(buildPath, project.getFullPath().append("bin"), null);

                IFolder srcFolder = project.getFolder("src");
                if (!srcFolder.exists())
                    srcFolder.create(true, true, monitor);
                project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

                monitor.worked(1);

                //Add folder to Java element
                IPackageFragmentRoot folder = javaProject.getPackageFragmentRoot(srcFolder);
                //create package fragment
                IPackageFragment fragment = folder.createPackageFragment(
                        AnnotationsPluginPreferenceConstants.P_ANNOTATIONS_PACKAGE, true, monitor);
                StringBuffer buffer = new StringBuffer();
                ICompilationUnit cu = fragment.createCompilationUnit(fileName,
                        AnnotationHandler.generateInstanceCode(buffer, annotationName, description).toString(),
                        false, monitor);
                project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

                monitor.worked(1);

                project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Activator.log(IStatus.ERROR, "Activator library couldn't be added to the java build path.");
            }
        } else {
            Activator.log(IStatus.ERROR, "Activator library couldn't be added to the java build path.");
        }

        /*final IFile file = container.getFile(new Path(fileName));
        try {
           InputStream stream = openContentStream();
           if (file.exists()) {
        file.setContents(stream, true, true, monitor);
           } else {
        file.create(stream, true, monitor);
           }
           stream.close();
        } catch (IOException e) {
        }*/

        /*monitor.setTaskName("Opening file for editing...");
        getShell().getDisplay().asyncExec(new Runnable() {
           public void run() {
        IWorkbenchPage page =
           PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        try {
           IDE.openEditor(page, file, true);
        } catch (PartInitException e) {
        }
           }
        });*/

        monitor.worked(1);
    }

    /**
     * We will initialize file contents with a sample text.
     */

    /*private InputStream openContentStream() {
       String contents =
     "package " + 
     "import metabup.annotations.interfaces.IAnnotation;";
       return new ByteArrayInputStream(contents.getBytes());
    }*/

    private void throwCoreException(String message) throws CoreException {
        IStatus status = new Status(IStatus.ERROR, "metabup.annotations", IStatus.OK, message, null);
        throw new CoreException(status);
    }

    /**
     * We will accept the selection in the workbench to see if
     * we can initialize from it.
     * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
     */
    public void init(IWorkbench workbench, IStructuredSelection selection) {
        this.selection = selection;
    }
}