Showing posts with label eclipse. Show all posts
Showing posts with label eclipse. Show all posts

May 5, 2008

Adding util methods to the generated EMF classes

We had EMF generated model classes and a Util class with lot of helper methods. Both were exposed to clients as an API. Most of the methods in the Util classes were like:

//API - Util class
Book getBook(Writer writer, String title);

//Customer code
Util.getBook(daveSteinberg, "Eclipse Modeling Framew
ork");

These methods would have been more appropriate in the Writer class itself rather than in a Util class, and it will be more natural to code like:

daveSteinberg.getBook("Eclipse Modeling Framework");

This tip is about how to add such methods in the generated code.

The first way is simple. Just edit the generated java code and add these methods. EMF is smart enough to identify this method and keeps it safe during regeneration of code. But if you were like me, who consider the generated Java files are as good as class files and don't want them checked into the repository, you can follow the second way.

In the eCore Editor for your model, right click the EClass and add a new child EOperation.


Go to the Properties view and specify the name, this will be the name of your method. The EType represents the return type of the method.


If your method has any parameters, then add EParameter children to the EOperation & specify their types and names.



To add the code, add an EAnnotation to the EOperation.


In the properties view, set the Source to "http://www.eclipse.org/emf/2002/GenModel".


Add a details entry to the EAnnotation.



In the properties view set the key to 'body' and value to the code that you want to be generated.



Reload your .genmodel from .ecore and generate the code:

Apr 1, 2008

Content type Specific File icons

Eclipse 3.4 M6 is out. It has lots of wonderful features like p2 and the installer. But one small change that is going to save a lot of developers time is the content type specific file icons. Earlier if I had to contribute an icon for a specific file, I've to write my own label decorator. Now Eclipse comes with a label decorator that does the same.

All you have to do is to define the content type and associate an editor with that content type. If you were wondering writing an editor is not a trivial task, don't worry, you can reuse the existing ones.

Assume that in my app, I have some files with extension 'config'. They are nothing but normal properties files. I would like to invoke the Properties editor on this extension and give a different icon. Here is how I create a new content type for the extension associated the Properties editor for that.

<extension point="org.eclipse.core.contenttype.contentTypes">
<content-type base-type="org.eclipse.core.runtime.properties"
file-extensions="config"

id="in.cypal.eclipse.myConfig"
name="My Config File"

priority="normal">

</content-type>

</extension
>
<extension point="org.eclipse.ui.editors">
<editor
class="org.eclipse.jdt.internal.ui.propertiesfileeditor.PropertiesFileEditor"
default="false"

extensions="config"

icon="icons/sample.gif"

id="in.cypal.eclipse.editors.myConfigEditor"

name="My Config Editor">
<contentTypeBinding contentTypeId="in.cypal.eclipse.myConfig">
</contentTypeBinding>
</editor>
</extension>





Content types are not just based on file names/extensions. If you have an xml file, you can use the XMLContentDescriber to find the content type based on the root element; create an editor extension; specify the Text Editor/XML Editor class; associate the content id and add the icon to the editor. You are done. All of this without writing a single line of code!

Mar 15, 2008

How does EMF finds the right parser?

ResourceSet resourceSet = new ResourceSetImpl();
Resource resource = resourceSet.createResource(someUri);


The API can't get any simpler. But the implementation details behind this is not simple. Resources are generally loaded by Resource.Factory. Your ECore model would have generated an appropriate Factory. You can find it in the util package with the name {your model name}ResourceFactoryImpl. Lets take a journey from the ResourceSet to this Factory.

ResourceSetImpl class delegates the job of finding the right Factory to the Resource.Factory.Registry. The default implementation of the registry (ResourceFactoryRegistryImpl) tries to find the factory by:

* lookup in the protocol map for the uri
* lookup in the extension map for the uri
* lookup in the content type map for the uri
* lookup in the extension map for the default extension (*)
* lookup in the content type map for the default content type (*)


If the above lookups did not find a factory then the delegatedGetFactory() method is called.

All three maps (protocol, extension & content type) are by default empty in the ResourceFactoryRegistryImpl. Either you can subclass and initialize in your constructor or call the resourceFactory.get{map type}ToFactoryMap().put({key}, {value}) to add your entries.

Since we have not added any entries in the registry, the delegatedGetFactory() method is called. The ResourceSetImpl overrides that method (thru an anonymous subclass of ResourceFactoryRegistryImpl) and calls again the getFactory() method with the maps from Resource.Factory.Registry.INSTANCE. BTW, all three maps in that instance are filled with the details from the extension points:

org.eclipse.emf.ecore.protocol_parser
org.eclipse.emf.ecore.extension_parser
org.eclipse.emf.ecore.content_parser

You should be using these extensions to register the right parser (the generated
ResourceFactoryImpl) for your resource.

Phew! If you think its done, you should look into the EMF code. All the above said stuff are optimized to the core. The ResourceSetImpl creates the ResourceFactoryRegistryImpl instance only when the getResourceFactoryRegistry() is called for the first time; all the above lookups are performed only when the map is not empty; and so on. EMF takes all the pain and finally we end up with:

ResourceSet resourceSet = new ResourceSetImpl();
Resource resource = resourceSet.createResource(someUri);


See, you got to love EMF. Or in general, Eclipse for making our life easier :-)

Related:

EMF Packing changes in 2.4
Using EMF with XML Catalog
Converting EMF Resource to Platform Resource (IFile)

Wizard as a Dialog

In an RCP application, I had these requirements for a Dialog box:

  • OK button should not be enabled until all the mandatory fields are filled
  • Hints for probably incorrect data (The email id grprakash+eclipse@gmail.com "looks" like a wrong one) These should not stop the user from pressing OK
  • Progress bar should be shown for long running operations (clicking OK, "check for user id availability", etc)

I was thinking on how to handle all these in a Dialog and something flashed in my mind - JFace Wizards. All the above requirements can be easily done if I use a Wizard. The Finish button is disabled when we call setPageComplete(false), we can show warnings and still allow the user to finish and by calling setNeedsProgressMonitor() & getContainer().run() we can show the progress bar in the UI as well. But there are two small issues to be handled when we use the wizard.

  • The first one is to get rid of the Back and Next buttons. We are lucky here because JFace will not show those buttons if there is only one page in the wizard
  • The "Finish" looks odd and should be renamed to "OK" or "Submit. This can be done by subclassing the WizardDialog:
WizardDialog dialog = new WizardDialog(shell, wizard) {

@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
Button finishButton = getButton(IDialogConstants.FINISH_ID);
finishButton.setText(IDialogConstants.OK_LABEL);
}
};


Now with the util method, I can enable/disable the "OK" button, reflecting the status of the UI items.

Related:
Util method for Wizard Pages
JFace Wizard Guidelines

Feb 15, 2008

Using EMF with XML Catalog

When you try to load an XML document using EMF, you might have noticed that the XML Catalog is not respected and might throw parse exceptions. First I thought I had made a mistake in extending org.eclipse.wst.xml.core.catalogContributions and was debugging that. Only after a while I realized that the XML Catalog is contributed by WTP and EMF is not depending on that. So there is no way for EMF to know the existence of such catalog. I found a quick solution using some internal classes. I'm not sure whether its the best, but it works (at least for my requirement)

The idea is when EMF fails to resolve when loading an XML we should get the WTP Catalog and try to resolve with that:


loadOptions.put(XMLResource.OPTION_USE_PARSER_POOL, new XMLParserPoolImpl() {

@Override
public synchronized XMLDefaultHandler getDefaultHandler(XMLResource resource, XMLLoad xmlLoad, XMLHelper helper, Map options) {
return
new SAXXMLHandler(resource, helper, options)
{
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
InputSource result;
try {
result = super.resolveEntity(publicId, systemId);
}catch(SAXException e) {
try {
ICatalog catalog = XMLCorePlugin.getDefault().getDefaultXMLCatalog();
String resolvePublic = catalog.resolvePublic(publicId, systemId).substring(5);
InputStream inputStream = getURIConverter().createInputStream(URI.createFileURI(resolvePublic));
result = new InputSource(inputStream);
result.setPublicId(publicId);
result.setSystemId(systemId);
return result;
} catch (Exception exception) {
throw new SAXException(exception);
}
}
return result;
}
};

}

});

There are many cases where this code will fail (like if you had added the catalog entry by uri/systemId) and there might be a much better way of doing that without using any internal classes. Till I find that, I'm going to live with this hack.

Feb 14, 2008

Eclipse Forum India 2008

This year's Eclipse Forum India is happening in Bangalore on 8-11 April. Its now open for registrations. There is a "very early bird" price, which closes Feb 15th (Yes, its tomorrow) In case you miss it, the "normal" early bird prices are open till March 14th.

I had mixed experience after attending last year's EFI. The workshop was definitely nice and few other sessions as well. But the rest of the sessions were simply not that great and not useful. I decided not to attend this year (Esp, I with just 3 sessions on Eclipse). May be I'll wait for the feedback of this year and decide for EFI 2009 :-)

Related:
Eclipse Forum India 2007 - First Impressions ...
Eclipse Forum India - Day 2
Eclipse Forum India - Day 3

Feb 12, 2008

Eclipse Search

It was during 2007 Eclipse Awards I guess. When I Googled for Eclipse Awards, I ended up with more results on horse racing than our Eclipse Awards. (Its much better now, that the result I wanted is at least in the first page) I thought how good, if we can filter out only "our" eclipse related results. Soon after that I created a custom search engine, which does that filtering. After that, I always search with that. Recently Google introduced Labels and Refinements to the Custom Search Engine. I tried adding few labels and it works nicely. For example, if I want to search for Cheat Sheet, I get a whole lot of results. All of them are relevant.



I can filter them with the labels, so I can see what blogs are available, the source code, the documentation or even the images that are related to Cheat Sheets.



I've added many of the sites and blogs (Thanks to Planet Eclipse, I can find them in one place) to this search engine, in case your favorite site/blog doesn't appear in the results, I might have missed it out. Let me know, I'll add them.

You can try out the Eclipse Search and find yourself the usefulness of it

Feb 11, 2008

Eclipse Icons - follow up post

Follow up 1:
Ben had a nice script for fetching all the icons from the cvs. I'm adding it here:

#!/bin/sh

CVSROOT=:pserver:anonymous@dev.eclipse.org:/cvsroot/eclipse
export CVSROOT

mkdir -p eclipse
cd eclipse
cvs -q co org.eclipse.debug.ui/icons
cvs -q co org.eclipse.pde.ui/icons
cvs -q co org.eclipse.jdt.ui/icons
cvs -q co org.eclipse.vcm.ui/icons
cvs -q co org.eclipse.team.ui/icons
cvs -q co org.eclipse.ant.ui/icons
cvs -q co org.eclipse.help.ui/icons
cvs -q co org.eclipse.ui/icons
cvs -q co org.eclipse.ui.views/icons
cvs -q co org.eclipse.ui.console/icons
cd ..
rm -f ~/public_html/eclipse-icons.zip
find eclipse -name "*.gif" -print | zip ~/public_html/eclipse-icons.zip -@

Follow up 2:
I remember Ben having a HTML page which lists all the icons. But due to bandwidth issues, he moved it to a zipped set of icons. Now that is also gone from the page. I've a back up of those icons. So if you want the complete set of icons, instead of the most commonly used ones, download them here.

Follow up 3:
Phillipus left a comment in the post saying how to access the icons from other plugins without bundling them in your plugin:

AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.ui", "$nl$/icons/full/etool16/import_wiz.gif");

This is cool but raises an interesting question. What happens during an Eclipse upgrade? Will they be retained in the same name? Or rather a straight question: Are these icons part of API? I didn't know the answer. So posting the question here. Those who know please throw some light on this.

Related:

Eclipse Icons - original post
Searching for Eclipse - source, blogs, images ...
Accessing CVS of Eclipse.org

Feb 8, 2008

Eclipse icons

Explaining an action or describing an object with fewer words is tough. Showing them as 16x16 icons is even more tougher. Eclipse has a wonderful collection of icons. The best part of it - the whole set is consistent in sizing, coloring and styling. (I personally feel that icons like the filter , jar library , plugins are brilliantly done). You can reuse them in many places in your own plugins/RCP Application as well. AFAIK, these icons are under Eclipse Public License and so you should not be falling into any legal trap for using these (don't take my word, I'm not a lawyer :-).

Many common images (undo, redo, file, folder, cut, copy) are available thru the org.eclipse.ui.ISharedImages interface. You can get them with IWorkbench:

Image folderImg = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);

For other common items (refresh, filter, collapse all, expand all), finding the images inside the plugins jars will be a tough task. So here are some images that you can reuse in your plugins:

Add, Delete :
Collapse All/Expand All:
Navigation:
Window operations:
Run & Debug:
Import & Export:
Date & Time:
Editor Operations:
Vertical & Horizontal:
Flat & Hierarchical:
Misc: Eclipse , Config & , Console , Font Help , Lock , Stop , Properties , Search & , Tip/Quick Fix , Sort , Task & , Sync & , Pulldown Menu, Binary , Bookmark , Category

Let me know if I've missed any commonly used icon. I'll add it to this list. The complete set of above icons can be downloaded from here.

Related:
Eclipse Icons - follow up post
Searching for Eclipse - source, blogs, images ...
Accessing CVS of Eclipse.org

All WTP early adopters, please stand up

If you are an early adopter of WTP like me, probably you would have gone thru the pain of downloading & installing all the prerequisites of WTP, that too for every milestone build. Of course, EPP has downloads for the milestone builds, but those are not enough. If you compare the versions, JEE version doesn't have source, which I quite often refer for how-tos or as sample implementations of an extension point) and the RCP version doesn't have JST. Recently I found that there is a bug already opened for providing all-in-one version for milestone builds, but its not been done because the PMC is not sure of how many people need it. If you are one of the guys who are in need of such build, do vote here.

Rest of us can download the EPP's Milestone builds here.



Feb 6, 2008

Feature based configuration of an RCP application

For a RCP application, I started with plugins based product configuration. When I reached a point where I need to provide software updates thru an update site, I needed a feature based product configuration. I thought should be as simple as selecting the features check box and adding the feature. But I spent around two whole days googling and debugging to bring it up and running. I think everyone would have gone thru the phase. I thought I'll write a blog entry on the issues, but I was lazy to draft such a long post. Yesterday Jan Kohnert sent a nice mail on his experience to the news group. Instead of copy-pasting the whole thing here, I present the information with little modifications. Thanks Jan.

  • Open your product file and select features in the Overview tab:


  • In the Configuration tab, click "New Feature...", and create the new feature:

  • In the newly created feature, go to the included features tab and add "org.eclipse.rcp" feature:
  • Go to the plugins tab and add your product's plugins
  • RCP feature has most of the plugins that you would require. However if you use anything other plugins (core.resources, ui.forms, etc), you need to add those plugins to the feature:
At this point you should be successfully running your RCP application. If you are not interesting in providing support for Software Updates for your app, you should be fine with this.

Ideally, even for software updates, this should work fine. However, if you try to create an update site and try running software update, you will be hitting the java.lang.SecurityException: "Invalid signature file digest for Manifest main attributes". To get rid of that, remove the RCP feature from the included features list of your feature and add the plugins in RCP feature to your feature. Thanks to PDE team, copy-pasting works in the plugins tab of Feature Editor :-)



While going thru the update stuff, I realized that the update will not function as expected if we launch it from the IDE (Not sure of why). So I have to export the product and run from the disk, which means I can't debug and step thru the code :-( To know what happens during the update, I start the application with -debug options and add these lines in the .options file:

org.eclipse.update.core/debug=true
org.eclipse.update.core/debug/warning=true
org.eclipse.update.core/debug/parsing=true
org.eclipse.update.core/debug/install=true
org.eclipse.update.core/debug/configuration=true
org.eclipse.update.core/debug/type=true
org.eclipse.update.core/debug/web=true
org.eclipse.update.core/debug/installhandler=true
org.eclipse.update.core/debug/reconciler=true


Click here for more info on the .options

Nov 30, 2007

Eclipse Demo Camp, Bangalore


Eclipse Demo Camp is coming to Bangalore on 10th Dec. Looking at other Demo Camps, Bangalore might be the one with highest number of registration (around 50) - and its still growing. In case you wish to attend, do register here.

Yup, I'm working on a presentation on GEF. Meet you all there.

Nov 5, 2007

JFace Wizard Guidelines

During Eclipse Plugin Developement training, I always end JFace Wizards session with these guidelines:

  1. Wizards should be aimed for minimal user interaction
  2. Wizard pages can be filled with meaningful defaults
  3. When a Wizard is shown it should not contain any errors. They should appear only after a user interaction
  4. Present Errors/Warnings in the tab order of the fields
  5. When a task is split into steps, a wizard page can model a step and shouldn't be doing more things
  6. Don't create pages that needs scrolling. In general if a wizard's height is greater than its width, probably it needs a review
  7. Total number of Wizard pages should be ~ 5
Once when I finished explaining them, one smart guy said: "Have you ever looked at the New Java Project Wizard?". True. The first page of that wizard doesn't comply with the Guideline #6. These points are not official standards, mere guidelines by me, but still I think they are good. So what is the problem with the New Java Project Wizard and how can it be better?

The options in the first page falls into three categories:
  1. Resource: Project name, location & working sets
  2. Compiler: Source folders
  3. Runtime: JRE & Execution env.

Ideally the first page should just give the resource related options and the others can be pushed to second page/elsewhere. Since the second page allows the user to configure the JRE, source & binary folder, I guess we are not loosing any functionality if we get rid of those options. If the first page is cleaned up to have only resource related options, this is how it would look like:




in contrast to the current:


Oct 13, 2007

Wow shortcut!

Now that I've been accused as the evil friend, who will provide suggestions for your itching, let me try to do some damage control. How about letting you know about a cool shortcut? No, not the Ctrl+3, the whole world knows and loves that. This is about copying a Java file from other editor.

There are many times you would be using a TextPad or your favourite trivial editor because you double clicked a Java file from your local disk. How do you import that file into your Eclipse workspace?

Either you can locate the file in your disk, drag and drop to the Package Explorer view or simply Ctrl+A in TextPad, select the package in the Package Explorer view and do a Ctrl+V, you are done! A Java file is created for you in that package with right name and also your package statement in the file is correctly updated.

This is very helpful when you are viewing a web page with code (either some public CVS thru web or some nice tips on the web) you can do a copy and paste them in your Package Explorer view.

Cool isn't it?

Despite the usefulness, I haven't seen this in any documentation, does anyone knows a place with complete list of wonderful features like this?

Oct 11, 2007

Removing Widgets from a composite

One of the frequent questions from Swing-to-SWT developers is: What is the equivalent of the Container.remove method in SWT?

AFAIK, there is none. The Composite doesn't have any method to remove its children. But then we have a workaround. We can dispose the child widget!

Let me give a simple code to explain. The problem statement is simple: Have a Combo box for different UI elements and fill a composite based on the selection. Hope the code is clear and doesn't require any clarifications.

composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));

Label label = new Label(composite, SWT.None);
label.setText("Select Control:");

combo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN);
combo.add("Text Box");
combo.add("Combo");
combo.add("Radio Button");

combo.addSelectionListener(new SelectionAdapter() {

@Override
public void widgetSelected(SelectionEvent e) {

if (control != null)
control.dispose();


switch (combo.getSelectionIndex()) {
case 0:
control = new Text(composite, SWT.BORDER);
break;
case 1:
control = new Combo(composite, SWT.DROP_DOWN);
break;
case 2:
control = new Button(composite, SWT.RADIO);
break;
}

GridData data = new GridData(SWT.FILL, SWT.NONE, false, false);
data.horizontalSpan = 2;
control.setLayoutData(data);

composite.layout(true);
}
});

Here is the result:





Sep 7, 2007

Debug your app

I don't have to explain the power of debugging and tracing thru the code. But it can happen only if you are executing your code locally. How can we debug a program which is executing in your customer's desktop? Logging is the solution. Although its not as powerful as debugging, it really helps in finding the bugs.

Eclipse provides a nice -debug command line option to switch on the logging mode. Shouldn't this option be -logging to avoid confusions? Don't ask me. I don't know :-P

The API Platform.inDebugMode() returns whether Eclipse is started with -debug or not. So in our code:

if(Platform.inDebugMode()){
System.out.println("My plugin is doing something");
}

When a customer has a bug, all he has to do is to start Eclipse with -debug option and send you the output. Simple? But the problem is your customer would have installed umpteen number of plugins and the log would literally be unreadable. How to enable logging for a specific plugin alone?

The .options file comes to rescue. This is a normal properties file, where you can specify the options including which plugins should be in debug mode and which are not. You can google for sample files.

Plugins are expected to look for this before printing the statement. So the above code should be:

if(Platform.inDebugMode() && Boolean.getBoolean(Platform.getDebugOption(Activator.PLUGIN_ID+"/debug"))){
System.out.println("My plugin is doing something");
}

Instead of repeating this if condition all over your plugin, you declare a field in your Activator and use it in other places:

public boolean inDebugMode = Platform.inDebugMode() &&amp; Boolean.getBoolean(Platform.getDebugOption(Activator.PLUGIN_ID+"/debug"));


and use it other places:

void foo(){
if(Activator.getDefault().inDebugMode()){
// debug mode
}
}

Jun 9, 2007

Help as a Standalone Application

I've been giving training on Eclipse Plugin Development in Bangalore for an year or so. Lot many sessions and lot many questions. Many of the questions are repeated in every session. Till I collect them and post them as a FAQ, I plan to post few in this blog.

The first question here is on help: "We have a set of doc plugins for our product. How to host them on the net like the one at help.eclipse.org?"

Eclipse ships a class called org.eclipse.help.standalone.Infocenter, which is available in org.eclipse.help.base_{version}.jar. It has a main method, so you can run it as a standalone application. You need the following arguments:

-command start
-port 80
-eclipsehome

Assuming the jar is in the classpath, the command would be:

java org.eclipse.help.standalone.Infocenter -command start -port 80 -eclipsehome /Users/prakashgr/eclipse/

May 28, 2007

Eclipse Forum India - First Impressions ...

Finally EFI is here. Here are some of my random thoughts:

  • Totally around 200 people were present for the power workshops today. Around 700 expected for main conference
  • I attended the one by Chris and Wassim (Eclipse Plugin Development). Total strength for this was little less than 100
  • Chris had a excited + curious million $ expression when he was asked to light the lamp. I wish I had a camera to capture that Kodak moment :-)
  • The people who attended were from various backgrounds. Only few haven't created a plugin before
  • The session was just started and the slides were explaining what an extension point is, and there were questions about ant based build, buddy class loading, osgi services, etc...
  • There were exceptions as well:

    Attendee: Does Eclipse use JFace?
    Chris : Yes.
    Attendee: Great!

  • In India, only 19.26% people bring laptops to the conferences. Source: my survey ;-) But this time it was little different. Almost 50% people in the hall had brought their laptops. The workshop had some exercises and those who didn't have laptops, were simply reading the pamphlets for the 253rd time.
  • During coffee breaks, there was a huge crowd around Chris and Wassim. I think the only way to move the crowd out of them was to bring Shilpa Shetty to the stage
  • I didn't attend the other sessions. Few guys were shuffling between all the sessions. They said the other sessions were equally good.
Notes to the organizers:
  • The session started late by 30 mins. Please try to stick to the time
  • If the attendees need to bring laptops, please inform it earlier
  • Please arrange some sort of network or pre-distribute the necessary artifacts. We had to pass on a USB thumb drive for this
  • Whoever decided that the "bag" was a good one, please, please change your mind !!!

Mar 7, 2007

Saving dirty editors

If you want to save all the dirty editors before doing any project level operation (such as build/refactor), you might want to show the user the "Save Resources" dialog with the list of dirty editors. This tip tells you how to do that.

{Update}
The first version of this tip had a roundabout way (read: nasty way) of doing it. Thanks to Boris for pointing the right API which does the trick.

PlatformUI.getWorkbench().saveAllEditors(true)

This returns a boolean value, in case the user presses Cancel button and you want to cancel the operation.

Feb 20, 2007

Opening an Editor programmatically

When you click on a file in the Package Explorer or Navigator, the file will open the associated editor. If you are looking for a way to do the same action through code, this tip is for you.

There are three things you need to open an editor:
(*) The IEditorInput for the resource you want to open
(*) A IWorkbenchPage, in which you want to open the editor
(*) The id of the editor, which you want to open.

For this tip, we assume that you want to open a file. So we can use FileEditorInput.
IEditorInput editorInput = new FileEditorInput(fileToBeOpened);

We will open the editor in the active page of the active window.
IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();

Open the TextEditor in that page.
page.openEditor(editorInput, "org.eclipse.ui.DefaultTextEdtior");

So here goes the entire snippet:

IFile fileToBeOpened = ...;
IEditorInput editorInput = new FileEditorInput(fileToBeOpened);
IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
page.openEditor(editorInput, "org.eclipse.ui.DefaultTextEdtior");