1 package net.mograsim.plugin.nature;
3 import java.util.Iterator;
5 import org.eclipse.core.commands.AbstractHandler;
6 import org.eclipse.core.commands.ExecutionEvent;
7 import org.eclipse.core.commands.ExecutionException;
8 import org.eclipse.core.resources.IProject;
9 import org.eclipse.core.resources.IProjectDescription;
10 import org.eclipse.core.runtime.CoreException;
11 import org.eclipse.core.runtime.IAdaptable;
12 import org.eclipse.jface.viewers.ISelection;
13 import org.eclipse.jface.viewers.IStructuredSelection;
14 import org.eclipse.ui.handlers.HandlerUtil;
16 public class AddRemoveMograsimNatureHandler extends AbstractHandler
19 public Object execute(ExecutionEvent event) throws ExecutionException
21 ISelection selection = HandlerUtil.getCurrentSelection(event);
23 if (selection instanceof IStructuredSelection)
25 for (Iterator<?> it = ((IStructuredSelection) selection).iterator(); it.hasNext();)
27 Object element = it.next();
28 IProject project = null;
29 if (element instanceof IProject)
31 project = (IProject) element;
32 } else if (element instanceof IAdaptable)
34 project = ((IAdaptable) element).getAdapter(IProject.class);
40 toggleNature(project);
42 catch (CoreException e)
45 throw new ExecutionException("Failed to toggle nature", e);
55 * Toggles sample nature on a project
57 * @param project to have sample nature added or removed
59 private void toggleNature(IProject project) throws CoreException
61 IProjectDescription description = project.getDescription();
62 String[] natures = description.getNatureIds();
64 for (int i = 0; i < natures.length; ++i)
66 if (MograsimNature.NATURE_ID.equals(natures[i]))
69 String[] newNatures = new String[natures.length - 1];
70 System.arraycopy(natures, 0, newNatures, 0, i);
71 System.arraycopy(natures, i + 1, newNatures, i, natures.length - i - 1);
72 description.setNatureIds(newNatures);
73 project.setDescription(description, null);
79 String[] newNatures = new String[natures.length + 1];
80 System.arraycopy(natures, 0, newNatures, 0, natures.length);
81 newNatures[natures.length] = MograsimNature.NATURE_ID;
82 description.setNatureIds(newNatures);
83 project.setDescription(description, null);