eclipse tricks

Download Eclipse Tricks

If you can't read please download the document

Upload: kaniska-mandal

Post on 20-May-2015

2.350 views

Category:

Documents


0 download

TRANSCRIPT

  • 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. 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. 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. 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. 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 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. 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. 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. 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. 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("