1. How to find the topmost element of a treepath
in a TreeViewer ?
IStructuredSelection sel = (IStructuredSelection) tree
.getSelection();
List topMostElementList= new ArrayList();
TreePath[] path = ((TreeSelection) sel).getPaths();
if (path != null && path.length > 0) {
for (int i = path[0].getSegmentCount(); i > 0; i--) {
// traverses and makes sure it's a Binding, then remove
if (path[0].getSegment(i - 1) instanceof RootElement) {
topMostElementList.add((EObject) path[0].getSegment(i - 1));
}
}
return topMostElementList;
Eclipse : Tips - How to use PageBook for
caching and dynamically displaying ui-
controls ?
Lets consider the following scenario : If user selects a data type in a combo, then dynamically we need
to display the control corresponding to the data-type.
dynamicallyShowDataTypeControl(PageBook dataTypePageBook, int dataType) {
Control currentPage = (Control) dataTypePageBook.getData(dataType);
if(currentPage == null){
currentPage = createValueControl(dataTypePageBook, dataType);
dataTypePageBook.setData(dataType, currentPage);
}
dataTypePageBook.showPage(currentPage);
}
*************************
createValueControl(PageBook dataTypePageBook, int dataType) {
switch (dataType) {
case BOOLEAN:
valueControl = new Button(dataTypePageBook, SWT.CHECK);
break;
case INTEGER:
valueControl = new Spinner(dataTypePageBook, SWT.ARROW_DOWN | SWT.BORDER);
2. break;
case STRING:
valueControl = new Text(dataTypePageBook, SWT.NONE);
break;
case PASSWORD:
valueControl = new Text(dataTypePageBook, SWT.PASSWORD);
break;
}
return valueControl;
}
Eclipse : Tips - Common Utility API in Eclipse
Eclipse API users very often reinvent some common utilities which are already provided by some
Eclipse core plugins.
org.eclipse.gmf.runtime.common.ui.util.FileUtil provides methods like createFile(..) and deleteFile(.)..
org.eclipse.gmf.runtime.common.core.util.FileCopyUtil help copyFile(..) and copyFolder(..)
copyFolder(String sourceFolder, String targetFolder) performs a deep copy of all internal folders.
While creating any swt control with Grid data we can reuse org.eclipse.debug.internal.ui.SWTFactory
Unfortunately same SWTFactory exists also in org.eclipse.pde.internal.ui
Instead of duplicating or internalizing or privatizing in a specific tool - such utility
classes FileUtil, FileCopyUtil and SWTFactory etc. should be part of a common core public API.
Similarly org.eclipse.jface.layout.GridDataFactory provides a convienient shorthand for creating and
initializing GridData.
Example : Typical grid data for a button
// GridDataFactory version
Point preferredSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, false);
* Point hint = Geometry.max(LayoutConstants.getMinButtonSize(), preferredSize);
* GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).hint(hint).applyTo(button);
The same factory can be used many times to create several GridData instances.
In order to create LightWeight Dialog we should extend PopupDialog and for a Multi-selection Search
Dialog we have to extend FilteredMultiSelectionDialog which provides a nice ‘search filter text box’.
3. And there is a well-known - org.eclipse.core.resources.IFile.ResourceUtil – which provides convenience
methods findEditor(IWorkbenchPage page, IFile file) to return the editor in the given page whose input
represents the given file and vice versa i.e. getFile(IEditorInput editorInput) to find file from editorInput.
org.eclipse.gmf.runtime.common.ui.action.util.SelectionUtil – selects and reveals the object in all the
corresponding parts.
It also has got an useful refactoring method startRename(IWorkbenchPart part, Object newElement).
org.eclipse.ui.dialogs.PreferencesUtil provides convenience methodscreatePreferenceDialogOn() to
create a workbench preference dialog and alsocreatePropertyDialogOn().
In the modeling world, in order to copy, remove, replace and resolve semantic model
elements EcoreUtil provides all the necessary methods.
Similarly org.eclipse.gmf.runtime.diagram.core.util.ViewUtil provides methods to resolve, delete, insert
view model elements.
Eclipse : Tips - How to find an existing problem-
marker ?
protected void removeMarkers(EObject target, IValidationContext ctx) {
IFile file = WorkspaceSynchronizer.getFile(target.eResource());
try {
IMarker[] markers = file.findMarkers(MARKER_ID, true, IFile.DEPTH_INFINITE);
for (IMarker marker : markers) {
String markerId = marker.getAttribute(IIssue.ID, "unknown");
if(markerId.equals(ctx.getCurrentConstraintId())){
marker.delete();
}
}
} catch (CoreException e) {
e.printStackTrace();
}
}
********************
protected boolean markerExists(EObject target, IValidationContext ctx){
IFile file = WorkspaceSynchronizer.getFile(target.eResource());
try {
IMarker[] markers = file.findMarkers(MARKER_ID, true, IFile.DEPTH_INFINITE);
for (IMarker marker : markers) {
String markerId = marker.getAttribute(IIssue.ID, "unknown");
4. if(markerId.equals(ctx.getCurrentConstraintId())){
return true;
}
}
} catch (CoreException e) {
e.printStackTrace();
}
return false;
}
Eclipse : Tips - How to create menu-items
dynamically ?
First we should contribute a menu group say dynamicMenuGroup as follows :
locationURI="popup:org.eclipse.ui.popup.any?after=editGroup">
icon="icons/dynamic-menu.png"
id="dynamicMenu"
label="%DynamicMenu.label"
mnemonic="%DynamicMenu.mnemonic"
tooltip="%DynamicMenu.tooltip">
name="dynamicMenuGroup"
visible="false">
************************
Next we need to make a dynamic menu contribution
extension
id=".eclipse.examples.dynamic.popup.menu"
name="Dynamic popup menu"
point="org.eclipse.ui.menus">
locationURI="popup:dynamicMenu?after=dynamicMenuGroup">
class="com.eclipse.examples.ShowDynamicMenu"
id="org.eclipse.ui.showDynamicMenu">
checkEnabled="false">
*****************************************
Finally we should create the following class :
DynamicMenu extends ContributionItem {
private Action[] actions;
private IWorkbenchWindow window;
5. protected boolean dirty = true;
public static final String SHOW_QUICK_FIX_ID = "org.eclipse.ui.showDynamic"; ////$NON-NLS-N$
public DynamicMenu () {
this(SHOW_QUICK_FIX_ID);
}
private final class DynamicAction extends Action {
public DynamicAction() {
}
public void run(){
//........................... DO THE NEEDFUL ....
}
}
********************
public DynamicMenu (String id) {
super(id);
for(){
actions.add(new DynamicAction());
}
}
********************
private IMenuListener menuListener = new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
manager.markDirty();
dirty = true;
}
};
********************
public void fill(Menu menu, int index) {
if (getParent() instanceof MenuManager) {
((MenuManager) getParent()).addMenuListener(menuListener);
}
if (!dirty) {
return;
}
MenuManager manager = new MenuManager();
fillMenu(manager);
IContributionItem items[] = manager.getItems();
if (items.length > 0 ) {
for (int i = 0; i < items.length; i++) {
6. items[i].fill(menu, index++);
}
}
dirty = false;
}
****************************
private void fillMenu(IMenuManager innerMgr) {
// Remove all.
innerMgr.removeAll();
// If no page disable all.
IWorkbenchPage page = window.getActivePage();
if (page == null) {
return;
}
for (int i = 0; i < actions.length; i++) {
innerMgr.add(actions[i]);
}
}
Eclipse : Tips - How to extend WSDL to provide
support for different types of binding
WTP WSDL WIzard by default provides support for the Binding types SOAP 1.1 and HTTP.
Now what if users need to provide support for a new binding type.
For example, there is a new soap model (SOAP 1.2) to provide support for new soap operations as
defined in wsdl11soap12.xsd
Step 1: User needs to create the emf model and generate source inside a fragment project so that this
models's SOAP12OperationImpl can be loaded and called to reconcile the new operation from DOM
to EMF Model.
Step 2: After ceating the new soap model artifacts, user needs to contibute anExtensibilityFactory say
SOAP12ExtensibilityElementFactory.
It is a -WSDL Extensibility Element Factory- which is registered as a factory for creating custom SOAP
extensibility elements. WSDL API will be able to bind SOAP 1.2 Artifacts.
WSDLFactoryImpl creates ExtensibilityElementFactory
extension point="org.eclipse.wst.wsdl.extensibilityElementFactories">
7. Step 3: Also the new soap schema needs to be contributed to wst xml contribution so that the xsd
doms are loaded in the model dynamically emf models are created from them.
extension id="com.wsdl.binding.extn.soap12.schema"
name="SOAP1.2 Schema Contrbution"
point="org.eclipse.wst.xml.core.catalogContributions">
Step 4:
We can create a fragment to add functionalities to its host:org.eclipse.wst.wsdl.ui
At runtime, contributions from fragments are merged into a single manifest and a single namespace of
libraries and resources.
We need to create a fragment project to capture the new model features as extension to wsdl.
Step 5:
First we contrbute the new Binding Model Extension.
extension point="org.eclipse.wst.wsdl.ui.extensionCategories">
Step 6:
We need to contribute a Contentgenerator to org.eclipse.wst.wsdl.contentGenerators for the same
model namespace "http://schemas.xmlsoap.org/wsdl/soap12/"
extension point="org.eclipse.wst.wsdl.contentGenerators">
Step 7:
Next contribution is org.eclipse.wst.wsdl.ui.contentGeneratorUI to create the UI for the new binding say
soap1.2
Either we can refer to existing classes or extend them.
extension point="org.eclipse.wst.wsdl.ui.contentGeneratorUI">
Step 8:
Also need to contribute a nodeCustomization toorg.eclipse.wst.xsd.ui.extensibilityNodeCustomizations.
We can use the same org.eclipse.wst.wsdl.ui.internal.soap.customizations.SOAPNodeEditorProvider
for the new model or we can extend this class.
extension point="org.eclipse.wst.xsd.ui.extensibilityNodeCustomizations">
Eclipse : Tips - find a resource in workspace
using visitor
public class WorkspaceResourceLocator implements IResourceProxyVisitor {
private String location;
private String resourceName;
8. private WorkspaceResourceLocator(String resourceLocation) {
this.location = resourceLocation;
this.resourceName = // find the resource name from the location
}
*************
public static IResource findResource(String absolutePath) throws CoreException {
WorkspaceResourceLocator fileLocator = new WorkspaceResourceLocator(absolutePath);
ResourcesPlugin.getWorkspace().getRoot().accept(fileLocator, IResource.NONE);
return fileLocator.locatedResource;
}
***************
public boolean visit(IResourceProxy proxy) throws CoreException {
// check if the name of the resource matches
if (proxy.getName().equals(resourceName)) {
locatedResource = proxy.requestResource();
// apply your logic to find required resource
return false;
}
return true;
}
}
Eclipse : Tips - Show/hide grid controls
dynamically
private void enableDynamicControl(boolean enable) {
dynamicControl.setVisible(enable);
((GridData) dynamicControl.getLayoutData()).exclude = !enable;
// if parentControl is ScrolledForm then call
parentControl.reflow(true);
// otherwise call parentControl.layout(true);
}
Eclipse : Tips - Create a Structured Selection for
a New Resource Creation Wizard
IStructuredSelection selectionToPass = StructuredSelection.EMPTY;
Class resourceClass = LegacyResourceSupport.getResourceClass();
9. if (resourceClass != null) {
IWorkbenchPart part = workbench.getActiveWorkbenchWindow().getPartService() .getActivePart();
if (part instanceof IEditorPart) {
IEditorInput input = ((IEditorPart) part).getEditorInput();
Object resource = org.eclipse.ui.internal.util.Util.getAdapter(input, resourceClass);
if (resource != null) {
selectionToPass = new StructuredSelection(resource);
}
}
}
Eclipse : Tips - Custom Filter Widget
Sometimes we need to display a filtering text box where user can specify a search criteria (regex) exp.
public class FilterWidget {
protected IFilterListener filterListener;
protected Composite container;
protected Label label;
protected Text text;
public void setFilterListener(IFilterListener filterListener){
this.filterListener= filterListener;
}
*************
public Composite create(Composite parent, FormToolkit toolkit) {
container = toolkit.createComposite(parent);
GridLayout gl = new GridLayout();
gl.marginWidth = 0;
gl.marginHeight = 0;
gl.verticalSpacing = 0;
container.setLayout(gl);
label = toolkit.createLabel(container, "Filter (?=any character, *=any String).");
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
text = toolkit.createText(container, "*");
text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
text.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
10. if(e.keyCode == SWT.ARROW_DOWN) {
// set the focus on the next control
}
}
});
text.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
filterChanged();
}
});
return container;
}
************************
protected void filterChanged() {
String filter = text.getText().trim();
if("".equals(filter)) {
filter = "*";
}
if(filter.endsWith("<")) {
filter = filter.substring(filter.length() - 1);
}else if("".equals(filter) == false && filter.endsWith("*") == false) {
filter = filter + "*";
}
// convert the pattern syntax into something palattable
filter = filter.replaceAll(".", ".");
filter = filter.replaceAll("*", ".*");
filter = filter.replaceAll("?", ".?");
Pattern p = Pattern.compile(filter, Pattern.CASE_INSENSITIVE);
filterListener.filterChanged(p);
}
public void dispose() {
label.dispose();
text.dispose();
container.dispose();
}
}
} public interface IFilterListener {
} public void filterChanged(Pattern pattern);
11. }
}}
Eclipse : Tips - Custom FilteredSelectionDialog
The first most important thing is to override fillContentProvider() in order to add model items to
dialog's content provider as shown in the attached saple code.
Then Base API will call the filter that should be provided by extender by overriiding
createFilter() method.
Finally we need to override restoreDialog to invoke applyFillter because restoreDialog will be called
everytime the dialog is recreated or refreshed.
We should provide a label provider for showing item details in the status bar of dialog.
We can also add a ViewerFilter to the content provider as shown in attached snippet.
public class MyModelSelectionDialog extends FilteredItemsSelectionDialog {
private AbstractContentProvider contentProvider;
private SearchPattern fPatternMatcher;
public MyModelSelectionDialog(Shell shell, IProject project, String title) {
super(shell);
setTitle(title);
MyModelLabelProvider lp = new MyModelLabelProvider();
setListLabelProvider(lp);
setListSelectionLabelDecorator(lp);
setDetailsLabelProvider(new MyModelDetailsLabelProvider());
// setDialogImage();
// setDefaultImage();
}
@Override
protected void restoreDialog(IDialogSettings settings) {
super.restoreDialog(settings);
applyFilter();
}
protected void applyFilter() {
super.applyFilter();
12. }
private Collection getModelList() {
List list = Collections.EMPTY_LIST;
return list;
}
@Override
protected ItemsFilter createFilter() {
return new ItemsFilter() {
@Override
public boolean isConsistentItem(Object item) {
return true;
}
@Override
public boolean matchItem(Object element) {
/*
* if (element instanceof MyModel) { MyModel item = (MyModel)
* element; if (!matches(item.getName())) { return false; } }
*/
return true;
}
@Override
public String getPattern() {
if (fPatternMatcher == null) {
fPatternMatcher = patternMatcher;
}
if ("".equals(patternMatcher.getPattern())) { //$NON-NLS-1$
return "?"; //$NON-NLS-1$
} else {
return super.getPattern();
}
}
};
}
@Override
protected void fillContentProvider(AbstractContentProvider contentProvider,
15. }
@Override
public Image getImage(Object element) {
Image image = null;
return image;
}
public Image decorateImage(Image image, Object element) {
return image;
}
public String decorateText(String text, Object element) {
return text;
}
}
@Override
protected void setResult(List newResult) {
List resultset = new ArrayList(newResult.size());
for (Object object : newResult) {
// add your logic
// resultset.add(object);
}
super.setResult(resultset);
}
@Override
protected Control createExtendedContentArea(Composite parent) {
// TODO Auto-generated method stub
return null;
}
}
How to contribute a wizard under export menu
group of for a file ?
1. Contribute a wizard to 'org.eclipse.ui.exportWizard'
2. then contribute that exportWizard as commonWizard to ' org.eclipse.ui.navigator.navigatorContent' in
16. the 'export' category.
3. specify a property tester to enable the wizard only the required type of file.
How to load a file placed inside a plugin ?
String pluginID = "com.examples.eclipse.test";
String baseSegment = "Samples";
String fileName = "testProject.zip";
org.eclipse.emf.common.util.URI uri = org.eclipse.emf.common.util.URI
.createPlatformPluginURI(pluginID, true);
uri = uri.appendSegments(new String[] { baseSegment, fileName});
uri = CommonPlugin.resolve(uri);
String path = uri.toFileString();
File resolvedFile = new File(path);
How to launch eclipse application from a
webpage ?
We can launch 'Sample Applications' from a Splash Screen.
Reference : http://www.eclipse.org/swt/jws/
Courtesy : http://help.eclipse.org/galileo/index.jsp
Platform Plug-in Developer Guide > Programmer's Guide > Packaging and delivering Eclipse
based products
Deploying eclipse based application with Java Web Start
Applications built on Eclipse can be deployed using Java Web Start.
Java Web Start "is an application-deployment technology that gives you the power to
launch full-featured applications with a single click from your web browser".
The prerequisites to start eclipse from Java Web Start are:
The deployed application must be based on Eclipse 3.1 or later;
All deployed plug-ins must be jar'ed;
All plug-ins must be signed since the application needs full permission from the client.
The following steps describe how to setup a Java Web Start site serving up a feature based
17. RCP application. These steps are for applications based on eclipse 3.3. Instructions on
how to achieve the same for eclipse 3.1 and 3.2 can respectively be found in the 3.1 and
3.2 SDKs.
Step 1, creating a wrapper feature
Create a feature including all the features that are listed in your product definition;
Ensure that the org.eclipse.equinox.launcher plug-in is in the feature or in one of the
included feature;
Step 2, exporting the wrapper feature
Note. Before proceeding with this step make sure to have a key store available. Eclipse
does not provide any facility to create key stores. You can use the keytool application that
comes with the JDK. In addition, ensure that the eclipse you are developing with is running
on a Java SDK instead of a JRE. If this constraint is not satisfied, the jar signing will fail.
Select the wrapper feature and do File > Export > Plug-in Development > Deployable
Features. In the wizard, select the wrapper feature, choose the "directory" option to export
your JNLP application to, and check the option "package features and plug-ins as individual
JAR archives". On the next page of the wizard, fill in the information relative to your key
store in the "Signing JAR Archives" section. Then in the "JNLP section", enter the name of
the server that will serve up your application and the level of JRE required to start your
application. That last value will be used to in the generated JNLP files to fill in the value of .
Click finish.
Once the export is done you should have the following structure on disk
site/ (The root of your jnlp site)
features/
WrapperingFeature_1.0.0.jar
WrapperingFeature_1.0.0.jnlp
com.xyz.abc_1.0.0.jar
com.xyz.abc_1.0.0.jnlp
...
plugins/
org.eclipse.core.runtime_3.1.0.jar
com.foo.baz_1.0.0.jnlp
org.eclipse.equinox.launcher_.jar
...
Step 3, creating the main JNLP file
A Java Web Start application is described by JNLP files. They replace the eclipse.exe and
the config.ini files by some equivalent mechanism. For example, JNLP has its own
mechanism to control splash screen, ways to pass parameters and define what constitutes
the application.
When you did the export, all the simple JNLP files have been created, so you are left with
18. writing the main file that will control the application. Because the majority of the main file is
common to all applications, it is recommended to start from the following self documented
template.
On the site serving up your application, the file must be located at the root. Once you will
be done editing this file, your application will be ready'
Tip: once you have created this file, you can store it in the wrapper feature in a folder such
that on every export you will get the complete structure. This folder needs to be referenced
from the root property of the build.properties (e.g: root=/).
Plug-ins based application
Even though your RCP application does not use features, Java Web Start-ing it is possible.
To do so, it is recommended to create a wrapper feature in order to facilitate the creation of
the main jnlp file and ease the deployment. This wrapper feature will list all the plug-ins of
your application. Once the feature has been updated copy the generated JNLP file and
modify it to become your main JNLP file.
Miscellaneous
Java Web Start on linux
When an eclipse application is started with Web Start on Linux the default windowing
system is motif. If you want to run GTK, you need to set the property osgi.ws to "gtk" in the
main jnlp file. For example you can add:
Known limitations
Eclipse Update and Java Web Start
Those two deployment technologies can work together under the following restrictions:
plug-ins installed by Java Web Start can not be updated by Update and vice-versa.
Features and plug-ins installed by Java Web Start can't be referred in the prerequisites of
features that needs to be installed by Update;
Request to exit the application with a restart code are ignored;
On the Mac, you can only use Web Start with Java 1.5 or later.
19. How to decorate icon and text of Viewer
Elements ?
Create a Decorator class say MyTreeDecorator.
Then set this Decorator as the Label Provider for the Viewer.
-------------------------------------------------------------
public class MyTreeDecorator extends StyledCellLabelProvider {
private MyTreeLabelProvider myTreeLabelProvider;
private static StyleRange styleRange;
private ImageDescriptor overlayImg = null;
private OverlayImageDescriptor overlayIntentImageDescriptor;
private Point fSize;
private ImageDescriptor baseImg = CompositeResourcesUIActivator
.getDefault()
.getImageDescriptor("icons/other/baseImg.png"); //$NON-NLS-1$
private ImageDescriptor overlayWarningImg = ImageDescriptor
.createFromImage(icons/other/warningImage.bmpE);
private ImageDescriptor overlayErrorImg = CompositeResourcesUIActivator
.getDefault().getImageDescriptor("icons/other/errorImage.bmp"); //$NON-NLS-1$
public MyTreeDecorator(
MyTreeLabelProvider myTreeLabelProvider) {
super();
this.myTreeLabelProvider = myTreeLabelProvider;
overlayMyImageDescriptor = new OverlayMyDescriptor(baseImg);
}
/**
* @param ViewerCell
*/
public void update(ViewerCell cell) {
Object selection = cell.getElement();
// based upon the selection get the baseImg
baseImg = myTreeLabelProvider.getImage(selection);
// determine the overlayImg
20. OverlayImageDescriptor overlayImageDescriptor = new OverlayImageDescriptor(
baseImg);
cell.setImage(overlayImageDescriptor.createImage());
// now decorate text
StyleRange styleRange = new StyleRange();
styleRange.start = selection.getName().length();
styleRange.length = myTreeLabelProvider.getText(selection).length()
- selection.getName().length();
styleRange.fontStyle = SWT.BOLD;
styleRange.foreground = foregroundColor;
cell.setStyleRanges(new StyleRange[] { styleRange });
cell.setText(myTreeLabelProvider.getText(selection));
}
}