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

Monday, April 13, 2015

Eclipse Spy plugins

To make spy plugins available for your run-time eclipse, add below 2 plugins in dependencies.
1. org.eclipse.pde.runtime
2. org.eclipse.pde.ui

Showing notification or popup dialog in Eclispe

Will use PopupDialog Class from eclipse Jface framework.

I am taking about something like this.











Example:

import org.eclipse.jface.dialogs.PopupDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class PopupDialogExample {

public static void main(String[] args) {
open();
}
static void open(){
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("PopupDialog");
shell.setLayout(new GridLayout());
shell.setSize(400, 300);
Button button = new Button(shell,SWT.PUSH);
button.setText("Click here!");
button.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
int shellStyle = PopupDialog.INFOPOPUPRESIZE_SHELLSTYLE;
boolean takeFocusOnOpen = true;
boolean persistSize = true;
boolean persistLocation = true;
boolean showDialogMenu = true;
boolean showPersistActions = true;
String titleText = "Updates Available"
String infoText = "Eclipse updates are available!";
PopupDialog  dialog = new PopupDialog(shell, shellStyle, takeFocusOnOpen, persistSize, persistLocation, showDialogMenu, showPersistActions, titleText, infoText){

@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
Label text = new Label(composite,SWT.SINGLE);
text.setText("There is a update for your plugin, please install them before proceed!");
return composite;
}
};
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
shell.layout();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
}


}

Thursday, April 9, 2015

Eclipse Jobs framework best practice: Handling the long running background jobs while Eclipse shutdown

How to handle background jobs which are running silently for a long time during the Eclipse shutdown ?

Solution would be to cancel all the jobs before before plugin stops,so that jobs won't complain about the other resources availablity. If we don't do this, some times we can get some null pointer issues in the log.

In Plugin Activator class, just invoke Job.getJobManager().cancel(jobName);


import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.osgi.framework.BundleContext;

public abstract class AbstractJob extends Job
{

private String jobFamilyName;

public AbstractJob(String name, String jobFamilyName)
{
super(name);
this.jobFamilyName = jobFamilyName;
}

@Override
public boolean belongsTo(Object family)
{
return this.jobFamilyName.equals(family);
}
}

Your Actual Job Implementation:

Job coreJob = new AbstractJob("Collecting assets", "ASSETS_FAMILY")
{

@Override
protected IStatus run(IProgressMonitor monitor)
{
//TODO: some long work job

return Status.OK_STATUS;
}
};

coreJob.schedule();


In Activate Class:

public void stop(BundleContext context) throws Exception {
plugin = null;
Job.getJobManager().cancel("ASSETS_FAMILY");
super.stop(context);
}

This will cancel all the jobs who's family name is ASSETS_FAMILY.


Wednesday, April 8, 2015

Adding resource filter for project in eclipse

try
{
project.createFilter(IResourceFilterDescription.EXCLUDE_ALL | IResourceFilterDescription.FOLDERS,
new FileInfoMatcherDescription("org.eclipse.core.resources.regexFilterMatcher", //$NON-NLS-N$
"node_modules"), IResource.BACKGROUND_REFRESH, new NullProgressMonitor());
}
catch (CoreException e)
{

}


This piece code will hide the "node_modules" folder from project.

Tuesday, March 24, 2015

Registering a listener for changes in network connections and proxy from eclipse preferences

import org.eclipse.core.net.proxy.IProxyChangeEvent;
import org.eclipse.core.net.proxy.IProxyChangeListener;
import org.eclipse.core.net.proxy.IProxyService;
import org.osgi.util.tracker.ServiceTracker;

public class ProxyHelper
{

public void registerListener()
{
ServiceTracker tracker = new ServiceTracker(MyPlugin.getDefault().getBundle().getBundleContext(),
IProxyService.class.getName(), null);
tracker.open();
IProxyService proxyService = (IProxyService) tracker.getService();
proxyService.addProxyChangeListener(new IProxyChangeListener()
{

@Override
public void proxyInfoChanged(IProxyChangeEvent event)
{
// TODO: your action for proxy changed
}
});
}

}

Thursday, November 27, 2014

Eclispe Mac - Changing text file encoding

By default, mac eclipse is configured with US-ASCII text encoding, but this does not work out if your file is having some special characters.

When you try to save a file which is having some special characters, you will face the below problem.












By changing default text encoding from US-ASCII to UTF-8 will resolve the problem.

This can be changed from the eclipse preferences-> General -> Workspace.


Changing the Eclipse Java thread time out value


Did you ever face below kind of issue while starting your eclipse product ? 

!ENTRY org.eclipse.osgi 2 0 2014-11-28 11:17:57.835
!MESSAGE While loading class "com.kk.tool.model.KContainer", thread "Thread[main,6,main]" timed out waiting (5015ms) for thread "Thread[Thread-3,5,main]" to finish starting bundle "com.kk.tool_6.0.190.DEV_v201411271801 [664]". To avoid deadlock, thread "Thread[main,6,main]" is proceeding but "com.kk.tool.model.KContainer" may not be fully initialized.
!STACK 0
org.osgi.framework.BundleException: State change in progress for bundle "reference:file:dropins/com.kk.tool_6.0.190.DEV_v201411271801.jar" by thread "Thread-3


There are two majors reasons for this.
1. Real dead lock would have occurred
2. Your product might have lot of bundles and each one of them might have dependencies on other plugins startup. Because of this, eclipse startup will be delayed.

If it is (1), we need to identify the root cause for a dead lock and fix it.

In general, OSGI controlling java threads time out by 5000 ms by default. We can control this time out by osgi parameter which need to be configured in the config.ini file.

equinox.statechange.timeout=8000

You can find config.ini file in the configuration folder of eclipse directory.
<eclipse>/configuration/config.ini

Caution: Don't jump strait to the timeout solution with out really looking at the dead lock possibility, 99% of time problem might be there with our code only!!!!

Resources:



Wednesday, November 26, 2014

StackLayout to switch between Composites

For example, If your dialog is having 2 radio buttons and based on the radio button selection you wanted to change the composite area. So rather than disposing the composite every time and recreating based on the selection of a radio button, we can manage this through stacklayout.

As per eclipse doc,This Layout stacks all the controls one on top of the other and resizes all controls to have the same size and location. The control specified in topControl is visible and all other controls are not visible. Users must set the topControl value to flip between the visible items and then call layout() on the composite which has the StackLayout.


public static void main(String[] args) {
                Display display = new Display();
                Shell shell = new Shell(display);
                shell.setLayout(new GridLayout());
        
                final Composite parent = new Composite(shell, SWT.NONE);
                parent.setLayoutData(new GridData(GridData.FILL_BOTH));
                final StackLayout layout = new StackLayout();
                parent.setLayout(layout);
                final Button[] bArray = new Button[10];
                for (int i = 0; i < 10; i++) {
                        bArray[i] = new Button(parent, SWT.PUSH);
                        bArray[i].setText("Button "+i);
                }
                layout.topControl = bArray[0];
        
                Button b = new Button(shell, SWT.PUSH);
                b.setText("Show Next Button");
                final int[] index = new int[1];
                b.addListener(SWT.Selection, new Listener(){
                        public void handleEvent(Event e) {
                                index[0] = (index[0] + 1) % 10;
                                layout.topControl = bArray[index[0]];
                                parent.layout();
                        }
                });
        
                shell.open();
                while (shell != null && !shell.isDisposed()) {
                        if (!display.readAndDispatch())
                                display.sleep(); 
                }       
        }


http://git.eclipse.org/c/platform/eclipse.platform.swt.git/tree/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet249.java


This is something new learning for me!!

Wednesday, October 29, 2014

Linking external project to eclipse workspace without really moving the project content

If you wanted to access the external eclipse project resources without really adding them into eclipse workspace, below piece code will help to do that.


 privagte void linkProject(String projectPath) throws CoreException {

IProjectDescription description = ResourcesPlugin.getWorkspace().loadProjectDescription( new Path(projectPath + File.separator +".project"));

IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(description.getName()); 
project.create(description, IProject.FORCE, null);
 if (!project.isOpen()) {
   project.open(null);
   }

 }

Saturday, October 18, 2014

Closing eclipse empty editor area

I have a use case, where I need to the close the eclipse empty editor area, so that editor area can be used by something else.

This can be achieved by implementing IPartListerner2 interface which is provided org.eclipse.ui.*


import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.editors.text.TextEditor;

public class AbstractMyEditor extends TextEditor implements IPartListener2 {

@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
site.getPage().addPartListener(this);
super.init(site, input);
}
@Override
public void partActivated(IWorkbenchPartReference partRef) {
}

@Override
public void partBroughtToTop(IWorkbenchPartReference partRef) {
}

@Override
public void partClosed(IWorkbenchPartReference partRef) {
IWorkbenchPage page = partRef.getPage();
if (page.isEditorAreaVisible()) {
IEditorReference[] editores = page.getEditorReferences();
if (editores.length <= 0) {
page.setEditorAreaVisible(false);
}
}
}

@Override
public void partDeactivated(IWorkbenchPartReference partRef) {
}

@Override
public void partOpened(IWorkbenchPartReference partRef) {
}

@Override
public void partHidden(IWorkbenchPartReference partRef) {
}

@Override
public void partVisible(IWorkbenchPartReference partRef) {
}

@Override
public void partInputChanged(IWorkbenchPartReference partRef) { }
}

Tuesday, October 14, 2014

Eclipse view id's

For my reference.

Eclipse view id's for progress view and error log view.

org.eclipse.ui.views.ProgressView
org.eclipse.pde.runtime.LogView
org.eclipse.ui.console.ConsoleView

org.eclipse.ui.views.ResourceNavigator  => IPageLayout.ID_RES_NAV
org.eclipse.ui.navigator.ProjectExplorer  => IPageLayout.ID_PROJECT_EXPLORER

Monday, October 13, 2014

How do I know with which version of Java eclipse got launched ?

Eclipse would have launched with some JRE support, to understand and know which version of java is used and from where it picked up. Follow these steps.

Go to Help->About Eclipse -> Installation Details -> Configuration

Look for below parameters:
java.version=1.7.0_55
java.home=C:\Program Files\Java\jre7
eclipse.vm=C:\Program Files\Java\jre7\bin\javaw.exe

Tuesday, October 7, 2014

Where can I find eclipse preferences stored files ?

Eclipse stores all the preferences in the preference configuration files. This you can find in the below eclipse workspace location.

<eclipseworkspace>\.metadata\.plugins\org.eclipse.core.runtime\.settings\

Say for example, jre configuration will be stored in the "org.eclipse.jdt.launching.prefs" file.

Wednesday, September 17, 2014

How to get active perspective in Eclipse

Active workbench page will have getPerspective() this will return the IPerspectiveDescriptor

IWorkbench workbench = PlatformUI.getWorkbench();
if (workbench != null) {
IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
if (activeWorkbenchWindow != null) {
IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
if (activePage != null) {
IPerspectiveDescriptor perspective = activePage.getPerspective();
if (perspective != null) {
String id = perspective.getId();
//This is your active perspective
}
}
}

visibleWhen on toolbar in Eclipse

I have added visibleWhen directly under toolbar, look like platform is not respecting visibleWhen for toolbar.

This is how I defined the extension:

<extension
       point="org.eclipse.ui.menus">
    <menuContribution
          allPopups="false"
          locationURI="toolbar:org.eclipse.ui.trim.vertical2">
       <toolbar
             id="com.kk.toolbar2"
             label="Charm bar">
          <command
                commandId="com.kk.command.showhelp"
                icon="icons/help.gif"
                label="Help"
                style="push">
           </command>
<visibleWhen
                   checkEnabled="false">
                <test
                      forcePluginActivation="true"
                      property="com.kk.isKKPerspective"
                      value="true">
                </test>
        </visibleWhen>
            </toolbar>
    </menuContribution>
 </extension>


visibleWhen has no effect on toolbar
https://bugs.eclipse.org/bugs/show_bug.cgi?id=201589


Workaround for this problem is, adding visibleWhen for each command. 
By adding visibleWhen on each command, toolbar is automatically getting disappeared if there are no visible elements

In my case, I want to add add a righside trim toolbar with some tool items. But I wanted to show this only in my perspective 'KKPerspective'.

<extension
       point="org.eclipse.ui.menus">
    <menuContribution
          allPopups="false"
          locationURI="toolbar:org.eclipse.ui.trim.vertical2">
       <toolbar
             id="com.kk.toolbar2"
             label="Charm bar">
          <command
                commandId="com.kk.command.showhelp"
                icon="icons/help.gif"
                label="Help"
                style="push">
             <visibleWhen
                   checkEnabled="false">
                <test
                      forcePluginActivation="true"
                      property="com.kk.isKKPerspective"
                      value="true">
                </test>
             </visibleWhen>
          </command>
            </toolbar>
    </menuContribution>
 </extension>

   <extension
         point="org.eclipse.core.expressions.propertyTesters">
      <propertyTester
            class="com.kk.KKPerspectiveTester"
            id="com.kk.propertyTester2"
            namespace="com.kk.propertyTester2"
            properties="isKKPerspective"
            type="java.lang.Object">
      </propertyTester>
   </extension>

Tuesday, September 16, 2014

Conventions for naming git branches for your development

Some practices which I follow for naming git branches.

If you are working on sprint/agile development, you might have planned certain activities for each sprint.

let's say, every sprint development is for 1 month,so for every sprint we can maintain different branches as mentioned below.

Example: In Development mode
Sprint 1  =>  Branch name: dev-1.0.1

here, dev-<Major version>.<Minor version>.<Sprint version>

While handing over your work to QA team, we can promote this branch to QA branch.

Example: In QA mode
dev-1.0.1 will become qa-1.0.1

If you are providing builds one top of dev branches.
Example: For sprint 1 on dev branch
com.kk.product_dev-1.0.1.0.jar

Here, <pluginname>_<<branch name>.<build number>>.jar

on QA builds generation,
com.kk.product_qa-1.0.1.0.jar

If many people are working on sprint on various features, then we can create a different branch for each feature(ex: dev-1.0.1_explorer), once the feature is stabilized then we can merge this with the main sprint branch i.e dev-1.0.1


Monday, September 15, 2014

Eclipse Plugin name and package name conventions

I will follow below conventions for naming any new plug-in which I am contributing.

Plug-in names should follow the standard Eclipse Naming conventions. That means that,
(i)   The project name on disk(Plug-in name) is the same as the plug-in id and
(ii)  Plug-in packages should start with plug-in name.
(iii) Don’t mix generated code plug-in and implementation plugins

com.kk.studio.<component name>
com.kk.studio.<major component name>.<minor component name>

 Examples:
com.kk.studio.sky   => Implemented code plug-in
com.kk.studio.sky.model    => EMF model based generated code plug-in

Package Names:
com.kk.studio.sky  => Plug-in name/Plug-in id

com.kk.studio.sky
com.kk.studio.sky.explorer
com.kk.studio.sky.explorer.model
com.kk.studio.sky.explorer.view
com.kk.studio.sky.explorer.view.actions
com.kk.studio.sky.explorer.view.dialogs
com.kk.studio.sky.explorer.view.dialogs.data
com.kk.studio.sky.explorer.view.providers
com.kk.studio.sky.i18n
com.kk.studio.sky.util


Eclipse Resources:
http://wiki.eclipse.org/Development_Resources/HOWTO/Project_Naming_Policy
http://wiki.eclipse.org/index.php/Naming_Conventions#Eclipse_Workspace_Projects

How to add right trimbar/side bar in eclipse

This can be achieved through "org.eclipse.ui.menus" extension point with the locationURI as "toolbar:org.eclipse.ui.trim.vertical2"

<extension
       point="org.eclipse.ui.menus">
    <menuContribution
          allPopups="false"
          locationURI="toolbar:org.eclipse.ui.trim.vertical2">
       <toolbar
             id="myrightsidetrimbar"
             label="Eclispe rightside trimbar">
          <command
                commandId="com.kk.command.showHelp"
                icon="icons/help.gif"
                label="Help"
                style="push">
          </command>
            </toolbar>
    </menuContribution>
 </extension>


toolbar:org.eclipse.ui.trim.vertical2 -> will be for used for Right trimbar

We can find all these uri identifiers in MenuUtil.java in eclipse org.eclispe.ui.workbench plugin

 /** Top Left Trim Area */
public final static String TRIM_COMMAND1 = "toolbar:org.eclipse.ui.trim.command1"; //$NON-NLS-1$
/** Top Right Trim Area */
public final static String TRIM_COMMAND2 = "toolbar:org.eclipse.ui.trim.command2"; //$NON-NLS-1$
/** Left Vertical Trim Area */
public final static String TRIM_VERTICAL1 = "toolbar:org.eclipse.ui.trim.vertical1"; //$NON-NLS-1$
/** Right Vertical Trim Area */
public final static String TRIM_VERTICAL2 = "toolbar:org.eclipse.ui.trim.vertical2"; //$NON-NLS-1$
/** Bottom (Status) Trim Area */
public final static String TRIM_STATUS = "toolbar:org.eclipse.ui.trim.status"; //$NON-NLS-1$