Showing posts with label JDT. Show all posts
Showing posts with label JDT. Show all posts

Monday, October 1, 2012

How to open a Java file in read-only mode?

In one of my eclipse plugin based application I wanted to open Java files in read only mode. One option was to use org.eclipse.jface.text.source.SourceViewer , where I could have used JavaSourceViewerConfiguration
for providing Java highlighting and all. But there were two problems:
  1. Source viewer won't inherit the Java editor settings (and if you have modified eclipse Java editor theme), which means your background and foreground in the SourceViewer gets completely messed up.
  2. Secondly you would lose all the markup and bookmarking facilities available with editors
So, I decided to extend the existing Java editor. The steps are extremely simple,
  1. Create an editor extension
  2. Extend the extension class with org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor
  3. Override some of the methods
  4. Open your file with this editor

Code

Editor Code

import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;

@SuppressWarnings("restriction")
public class ReadonlyEd extends CompilationUnitEditor 
{
 public static final String ID = "read.only";
 public ReadonlyEd() {
 }
 @Override
 public boolean isEditable() {
     return false;
 }
 @Override
 public boolean isEditorInputModifiable() {
     return false;
 }
 @Override
 public boolean isEditorInputReadOnly() {
     return true;
 }
 @Override
 public boolean isDirty() {
     return false;
 }
}

Code for Invoking the Editor

IFile file = ...; // Get the Java file instance
IWorkbenchPage page = ...; // Get the workbench page
  
FileEditorInput input = new FileEditorInput(file);
try {
 IDE.openEditor(window.getActivePage(), input, ReadonlyEd.ID);
} catch (PartInitException e) {
 e.printStackTrace();
}

Wednesday, April 18, 2012

Programmatically create eclipse Java project

Following is a brief code snippet for creating an eclipse Java project using core JDT API.

private IJavaProject createProject() throws Exception
{
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    String projName = getProjectName();

    if(projName == null || projName.trim().length() == 0)
        return null;

    //create eclipse project
    IProject project = root.getProject(projName);
    if(project.exists())
        project.delete(true, null);

    project.create(null);
    project.open(null);

    //set the java project nature
    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] { JavaCore.NATURE_ID});
    project.setDescription(description, null);

    //create java project
    IJavaProject javaProject = JavaCore.create(project);

    //add bin/ouput folder
    IFolder binFolder = project.getFolder("bin");
    binFolder.create(false, true, null);
    javaProject.setOutputLocation(binFolder.getFullPath(), null);

    //add libs to project class path
    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
    LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);
    for (LibraryLocation element : locations) {
        entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
    }
    
    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);

    //create source folder
    IFolder sourceFolder = project.getFolder("src");
    sourceFolder.create(false, true, null);

    IPackageFragmentRoot srcRoot = project.getPackageFragmentRoot(sourceFolder);
    IClasspathEntry[] oldEntries = project.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(srcRoot.getPath());
    project.setRawClasspath(newEntries, null);

    return javaProject;
}

private String getProjectName()
{
    String init_value = "project_" + System.currentTimeMillis();
    InputDialog dialog = new InputDialog(getShell(), "Java Project", "Provide project name ..", init_value, new IInputValidator() {
        public String isValid(String newText)
        {
            char[] array = newText.toCharArray();
            for (int i = 0; i < array.length; i++)
            {
                if(!Character.isJavaIdentifierPart(array[i]))
                    return "Cannot contain special characters !!";
            }

            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            IProject[] projs = root.getProjects();
            for (int i = 0; i < projs.length; i++) {
                if(projs[i].getName().equalsIgnoreCase(newText))
                    return "Project already exist !!";
            }

            /*
                Not checking for special Win32 names like con etc.
            */
            return null;
        }
    });

    if(dialog.open() == Dialog.CANCEL)
        return null;

    return dialog.getValue();
}