Eclipse Tricks

2,682 views
2,572 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,682
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
27
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Eclipse Tricks

  1. 1. How to find the topmost element of a treepathin 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 its a Binding, then removeif (path[0].getSegment(i - 1) instanceof RootElement) {topMostElementList.add((EObject) path[0].getSegment(i - 1));}}return topMostElementList;Eclipse : Tips - How to use PageBook forcaching and dynamically displaying ui-controls ?Lets consider the following scenario : If user selects a data type in a combo, then dynamically we needto 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. 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 EclipseEclipse API users very often reinvent some common utilities which are already provided by someEclipse 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.SWTFactoryUnfortunately same SWTFactory exists also in org.eclipse.pde.internal.uiInstead of duplicating or internalizing or privatizing in a specific tool - such utilityclasses 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 andinitializing GridData.Example : Typical grid data for a button// GridDataFactory versionPoint 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 SearchDialog we have to extend FilteredMultiSelectionDialog which provides a nice ‘search filter text box’.
  3. 3. And there is a well-known - org.eclipse.core.resources.IFile.ResourceUtil – which provides conveniencemethods findEditor(IWorkbenchPage page, IFile file) to return the editor in the given page whose inputrepresents 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 thecorresponding parts.It also has got an useful refactoring method startRename(IWorkbenchPart part, Object newElement).org.eclipse.ui.dialogs.PreferencesUtil provides convenience methodscreatePreferenceDialogOn() tocreate a workbench preference dialog and alsocreatePropertyDialogOn().In the modeling world, in order to copy, remove, replace and resolve semantic modelelements EcoreUtil provides all the necessary methods.Similarly org.eclipse.gmf.runtime.diagram.core.util.ViewUtil provides methods to resolve, delete, insertview 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. 4. if(markerId.equals(ctx.getCurrentConstraintId())){return true;}}} catch (CoreException e) {e.printStackTrace();}return false;}Eclipse : Tips - How to create menu-itemsdynamically ?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 contributionextensionid=".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. 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. 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 providesupport for different types of bindingWTP 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 asdefined in wsdl11soap12.xsdStep 1: User needs to create the emf model and generate source inside a fragment project so that thismodelss SOAP12OperationImpl can be loaded and called to reconcile the new operation from DOMto EMF Model.Step 2: After ceating the new soap model artifacts, user needs to contibute anExtensibilityFactory saySOAP12ExtensibilityElementFactory.It is a -WSDL Extensibility Element Factory- which is registered as a factory for creating custom SOAPextensibility elements. WSDL API will be able to bind SOAP 1.2 Artifacts.WSDLFactoryImpl creates ExtensibilityElementFactoryextension point="org.eclipse.wst.wsdl.extensibilityElementFactories">
  7. 7. Step 3: Also the new soap schema needs to be contributed to wst xml contribution so that the xsddoms 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.uiAt runtime, contributions from fragments are merged into a single manifest and a single namespace oflibraries 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 samemodel 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 saysoap1.2Either 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.SOAPNodeEditorProviderfor the new model or we can extend this class.extension point="org.eclipse.wst.xsd.ui.extensibilityNodeCustomizations">Eclipse : Tips - find a resource in workspaceusing visitorpublic class WorkspaceResourceLocator implements IResourceProxyVisitor {private String location;private String resourceName;
  8. 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 matchesif (proxy.getName().equals(resourceName)) {locatedResource = proxy.requestResource();// apply your logic to find required resourcereturn false;}return true;}}Eclipse : Tips - Show/hide grid controlsdynamicallyprivate void enableDynamicControl(boolean enable) {dynamicControl.setVisible(enable);((GridData) dynamicControl.getLayoutData()).exclude = !enable;// if parentControl is ScrolledForm then callparentControl.reflow(true);// otherwise call parentControl.layout(true);}Eclipse : Tips - Create a Structured Selection fora New Resource Creation WizardIStructuredSelection selectionToPass = StructuredSelection.EMPTY;Class resourceClass = LegacyResourceSupport.getResourceClass();
  9. 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 WidgetSometimes 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. 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 palattablefilter = 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. 11. }}}Eclipse : Tips - Custom FilteredSelectionDialogThe first most important thing is to override fillContentProvider() in order to add model items todialogs content provider as shown in the attached saple code.Then Base API will call the filter that should be provided by extender by overriidingcreateFilter() method.Finally we need to override restoreDialog to invoke applyFillter because restoreDialog will be calledeverytime 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();}@Overrideprotected void restoreDialog(IDialogSettings settings) {super.restoreDialog(settings);applyFilter();}protected void applyFilter() {super.applyFilter();
  12. 12. }private Collection getModelList() {List list = Collections.EMPTY_LIST;return list;}@Overrideprotected ItemsFilter createFilter() {return new ItemsFilter() {@Overridepublic boolean isConsistentItem(Object item) {return true;}@Overridepublic boolean matchItem(Object element) {/** if (element instanceof MyModel) { MyModel item = (MyModel)* element; if (!matches(item.getName())) { return false; } }*/return true;}@Overridepublic String getPattern() {if (fPatternMatcher == null) {fPatternMatcher = patternMatcher;}if ("".equals(patternMatcher.getPattern())) { //$NON-NLS-1$return "?"; //$NON-NLS-1$} else {return super.getPattern();}}};}@Overrideprotected void fillContentProvider(AbstractContentProvider contentProvider,
  13. 13. ItemsFilter itemsFilter, IProgressMonitor progressMonitor)throws CoreException {this.contentProvider = contentProvider;populateModelList(itemsFilter);}/****/private void populateModelList(ItemsFilter itemsFilter) {Iterator iterator = getModelList().iterator();while (iterator.hasNext()) {Object item = iterator.next();removeHistoryItem(item);contentProvider.add(item, itemsFilter);}}@Overrideprotected IDialogSettings getDialogSettings() {/** IDialogSettings settings = UIActivator.getDefault()* .getDialogSettings().getSection(this.getClass().getName()); if* (settings == null) { settings = UIActivator.getDefault()* .getDialogSettings().addNewSection( this.getClass().getName()); }* return settings;*/return null;}@Overridepublic String getElementName(Object item) {// apply some logicreturn item.toString();}@Overrideprotected Comparator getItemsComparator() {return new Comparator() {public int compare(Object o1, Object o2) {
  14. 14. Collator.getInstance().compare(o1.toString(), o2.toString());return 0;}};}@Overrideprotected IStatus validateItem(Object item) {return Status.OK_STATUS;}/*** @author kaniska*/private class MyModelLabelProvider extends LabelProvider implementsILabelDecorator {@Overridepublic String getText(Object element) {return element == null ? "- none -" : element.toString();}@Overridepublic Image getImage(Object element) {return null;}public Image decorateImage(Image image, Object element) {return image;}public String decorateText(String text, Object element) {return text;}}private class MyModelDetailsLabelProvider extends LabelProvider implementsILabelDecorator {@Overridepublic String getText(Object element) {return "";
  15. 15. }@Overridepublic 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;}}@Overrideprotected void setResult(List newResult) {List resultset = new ArrayList(newResult.size());for (Object object : newResult) {// add your logic// resultset.add(object);}super.setResult(resultset);}@Overrideprotected Control createExtendedContentArea(Composite parent) {// TODO Auto-generated method stubreturn null;}}How to contribute a wizard under export menugroup of for a file ?1. Contribute a wizard to org.eclipse.ui.exportWizard2. then contribute that exportWizard as commonWizard to org.eclipse.ui.navigator.navigatorContent in
  16. 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 awebpage ?We can launch Sample Applications from a Splash Screen.Reference : http://www.eclipse.org/swt/jws/Courtesy : http://help.eclipse.org/galileo/index.jspPlatform Plug-in Developer Guide > Programmers Guide > Packaging and delivering Eclipsebased 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 jared; 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. 17. RCP application. These steps are for applications based on eclipse 3.3. Instructions onhow to achieve the same for eclipse 3.1 and 3.2 can respectively be found in the 3.1 and3.2 SDKs.Step 1, creating a wrapper featureCreate 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 theincluded feature;Step 2, exporting the wrapper featureNote. Before proceeding with this step make sure to have a key store available. Eclipsedoes not provide any facility to create key stores. You can use the keytool application thatcomes with the JDK. In addition, ensure that the eclipse you are developing with is runningon 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 > DeployableFeatures. In the wizard, select the wrapper feature, choose the "directory" option to exportyour JNLP application to, and check the option "package features and plug-ins as individualJAR archives". On the next page of the wizard, fill in the information relative to your keystore in the "Signing JAR Archives" section. Then in the "JNLP section", enter the name ofthe server that will serve up your application and the level of JRE required to start yourapplication. 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 disksite/ (The root of your jnlp site)features/WrapperingFeature_1.0.0.jarWrapperingFeature_1.0.0.jnlpcom.xyz.abc_1.0.0.jarcom.xyz.abc_1.0.0.jnlp...plugins/org.eclipse.core.runtime_3.1.0.jarcom.foo.baz_1.0.0.jnlporg.eclipse.equinox.launcher_.jar...Step 3, creating the main JNLP fileA Java Web Start application is described by JNLP files. They replace the eclipse.exe andthe config.ini files by some equivalent mechanism. For example, JNLP has its ownmechanism to control splash screen, ways to pass parameters and define what constitutesthe application.When you did the export, all the simple JNLP files have been created, so you are left with
  18. 18. writing the main file that will control the application. Because the majority of the main file iscommon to all applications, it is recommended to start from the following self documentedtemplate.On the site serving up your application, the file must be located at the root. Once you willbe done editing this file, your application will be readyTip: once you have created this file, you can store it in the wrapper feature in a folder suchthat on every export you will get the complete structure. This folder needs to be referencedfrom the root property of the build.properties (e.g: root=/).Plug-ins based applicationEven 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 ofthe main jnlp file and ease the deployment. This wrapper feature will list all the plug-ins ofyour application. Once the feature has been updated copy the generated JNLP file andmodify it to become your main JNLP file.MiscellaneousJava Web Start on linuxWhen an eclipse application is started with Web Start on Linux the default windowingsystem is motif. If you want to run GTK, you need to set the property osgi.ws to "gtk" in themain jnlp file. For example you can add:Known limitationsEclipse Update and Java Web StartThose 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 cant be referred in the prerequisites offeatures 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. 19. How to decorate icon and text of ViewerElements ?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 baseImgbaseImg = myTreeLabelProvider.getImage(selection);// determine the overlayImg
  20. 20. OverlayImageDescriptor overlayImageDescriptor = new OverlayImageDescriptor(baseImg);cell.setImage(overlayImageDescriptor.createImage());// now decorate textStyleRange 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));}}

×