Difference between revisions of "Teams Winter 2011/team2/lab3"

From CDOT Wiki
Jump to: navigation, search
 
(17 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
=Tutorial=
 
=Tutorial=
In this tutorial, we are creating an RCP application to inform the user of current weather temperatures in major cities of Canada. We will use our previous lab 2 classes and alter them according to our specification for this lab. For reference material, we are using  [http://www.vogella.de/articles/EclipseRCP/article.html#architecture_overview Eclipse RCP] and [http://www.vogella.de/articles/EclipseJFaceTable/article.html#jfaceviewers Eclipse JFace Table] tutorial.
+
In this tutorial, we are creating an RCP application to inform the user of current weather temperatures in major cities of North America. We will use our previous lab 2 classes and alter them according to our specification for this lab. For reference material, we are using  [http://www.vogella.de/articles/EclipseRCP/article.html#architecture_overview Eclipse RCP] and [http://www.vogella.de/articles/EclipseJFaceTable/article.html#jfaceviewers Eclipse JFace Table] tutorial.
 
==Prerequisites==
 
==Prerequisites==
 
*Download [http://www.eclipse.org/downloads/packages/eclipse-rcp-and-rap-developers/heliossr2 Eclipse RCP & RAP Developer]
 
*Download [http://www.eclipse.org/downloads/packages/eclipse-rcp-and-rap-developers/heliossr2 Eclipse RCP & RAP Developer]
 
+
*Install RCP plug-in
 
=Create a RCP Application=
 
=Create a RCP Application=
 
==Run a RCP Application==
 
==Run a RCP Application==
Line 9: Line 9:
 
*Select/Enter your preferred workspace in the text box provided and click okay
 
*Select/Enter your preferred workspace in the text box provided and click okay
 
[[File:RcpwT2.png]]
 
[[File:RcpwT2.png]]
*After Eclipse has completed loaded, create a plug-in project by clicking on "File" on the menu bar then scroll to New->Project->Other. A wizard should pop-up in which you should progress to click on the "Plugin-in Development" tree, select "Plug-in Project", and click next.
+
*After Eclipse has completed loaded, create a plug-in project by clicking on "File" on the menu bar then scroll to New->Project->Other. A wizard should pop-up in which you should progress to click on the "Plug-in Development" tree, select "Plug-in Project", and click next.
 
[[File:WizwT2.png]]
 
[[File:WizwT2.png]]
 
*Enter the following information that is seen in the image below
 
*Enter the following information that is seen in the image below
Line 48: Line 48:
 
[[File:Runconf2T2.png]]
 
[[File:Runconf2T2.png]]
 
==Creating a Package and Classes==
 
==Creating a Package and Classes==
*We are now going to create a package called "weathermodel". To do this, right-click the src folder, move the cursor to "New", then click packages. Enter "weathermodel" in the "Name" textbox and click Finish.
+
*We are now going to create a package called "ecl.team2.lab3.weathermodel". To do this, right-click the src folder, move the cursor to "New", then click packages. Enter "ecl.team2.lab3.weathermodel" in the "Name" textbox and click Finish.
 
[[File:PckgT2.png]][[File:Pckg2T2.png]]
 
[[File:PckgT2.png]][[File:Pckg2T2.png]]
 +
*Now we are going to create classes within this package. To create a class, right-click our newly created package, highlight "New", and scroll down and click "Class". Create a class for "Weather" and "SimpleWeatherSystem".
 +
[[File:Classl3T2.png]]
 +
*Copy and paste the following to their respective file.
 +
'''Weather.java'''
 +
<source lang=java>
 +
package ecl.team2.lab3.weathermodel;
 +
 +
import java.beans.PropertyChangeListener;
 +
import java.beans.PropertyChangeSupport;
 +
import java.util.Random;
 +
 +
public class Weather {
 +
    private String city;
 +
    private float tempInCelcius;
 +
    private float rainInMM;
 +
    private float snowInMM;
 +
    private float windspeedInKM;
 +
    private char windDirection;
 +
 
 +
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
 +
 
 +
    public Weather()
 +
    {
 +
    }
 +
 
 +
    public Weather(String cit)
 +
    {
 +
        city=cit;
 +
     
 +
        Random randomGenerator = new Random();
 +
        tempInCelcius = randomGenerator.nextFloat()+35;
 +
        rainInMM = randomGenerator.nextFloat()+10;
 +
        snowInMM = randomGenerator.nextFloat()+10;
 +
        windspeedInKM = randomGenerator.nextFloat()+50;
 +
     
 +
        int r = randomGenerator.nextInt(4);
 +
        switch(r){
 +
        case 0:
 +
            windDirection = 'E';
 +
            break;
 +
        case 1:
 +
            windDirection = 'W';
 +
            break;
 +
        case 2:
 +
            windDirection = 'N';
 +
            break;
 +
        case 3:
 +
            windDirection = 'S';
 +
            break;
 +
        }
 +
    }
 +
 
 +
    public Weather(String pcity, float ptemp, float prain, float psnow, float pwspeed, char pwdirection){
 +
        this.setCity(pcity);
 +
        this.setTempInCelcius(ptemp);
 +
        this.setRainInMM(prain);
 +
        this.setSnowInMM(psnow);
 +
        this.setWindspeedInKM(pwspeed);
 +
        this.setWindDirection(pwdirection);
 +
    }
 +
 
 +
    public void setWindDirection(char windDirection) {
 +
        propertyChangeSupport.firePropertyChange("",
 +
                this.windDirection, this.windDirection = windDirection);
 +
    }
 +
 +
    public char getWindDirection() {
 +
        return windDirection;
 +
    }
 +
 +
    public void setWindspeedInKM(float windspeedInKM) {
 +
        propertyChangeSupport.firePropertyChange("", this.windspeedInKM,
 +
        this.windspeedInKM = windspeedInKM);
 +
    }
 +
 +
    public float getWindspeedInKM() {
 +
        return windspeedInKM;
 +
    }
 +
 +
    public void setSnowInMM(float snowInMM) {
 +
        propertyChangeSupport.firePropertyChange("",
 +
        this.snowInMM, this.snowInMM = snowInMM);
 +
    }
 +
 +
    public float getSnowInMM() {
 +
        return snowInMM;
 +
    }
 +
 +
    public void setRainInMM(float rainInMM) {
 +
        propertyChangeSupport.firePropertyChange("", this.rainInMM,
 +
        this.rainInMM = rainInMM);
 +
    }
 +
 +
    public float getRainInMM() {
 +
        return rainInMM;
 +
    }
 +
 +
    public void setTempInCelcius(float tempInCelcius) {
 +
        propertyChangeSupport.firePropertyChange("", this.tempInCelcius,
 +
        this.tempInCelcius = tempInCelcius);
 +
    }
 +
 +
    public float getTempInCelcius() {
 +
        return tempInCelcius;
 +
    }
 +
 +
    public void setCity(String city) {
 +
        propertyChangeSupport.firePropertyChange("", this.city,
 +
        this.city = city);
 +
    }
 +
 +
    public String getCity() {
 +
        return city;
 +
    }
 +
 
 +
    public void addPropertyChangeListener(String name, PropertyChangeListener listener)
 +
    {
 +
        propertyChangeSupport.addPropertyChangeListener(name,listener);
 +
    }
 +
 
 +
    public void removePropertyChangeListener(PropertyChangeListener listener)
 +
    {
 +
        propertyChangeSupport.addPropertyChangeListener(listener);
 +
    }
 +
 
 +
    public String toString()
 +
    {
 +
        return city + " " + tempInCelcius + " " + rainInMM + " " + snowInMM + " "
 +
        + windspeedInKM + " " + windDirection;
 +
    }
 +
}
 +
</source>
 +
'''SimpleWeatherSystem.java'''
 +
<source lang=java>
 +
package ecl.team2.lab3.weathermodel;
 +
 +
import java.util.ArrayList;
 +
import java.util.Random;
 +
 +
public enum SimpleWeatherSystem {
 +
    INSTANCE;
 +
 
 +
    ArrayList<Weather> weathers = new ArrayList<Weather>();
 +
    private SimpleWeatherSystem(){
 +
        ArrayList<String> cities = new ArrayList<String>();
 +
        cities.add("Toronto");
 +
        cities.add("New York");
 +
        cities.add("Calgary");
 +
        cities.add("Ottawa");
 +
        cities.add("Vancouver");
 +
        cities.add("Regina");
 +
        cities.add("Winnipeg");
 +
        cities.add("St. John");
 +
        cities.add("Fredericton");
 +
        cities.add("Halifax");
 +
        cities.add("Quebec City");
 +
        cities.add("Whitehorse");
 +
        cities.add("Yellowknife");
 +
        for(String c:cities){
 +
            Random randomGenerator = new Random();
 +
            float temp = randomGenerator.nextFloat()+35;
 +
            float rain = randomGenerator.nextFloat()+10;
 +
            float snow = randomGenerator.nextFloat()+10;
 +
            float windspeed = randomGenerator.nextFloat()+50;
 +
            char winddirection = '.';
 +
            int r = randomGenerator.nextInt(4);
 +
            switch(r){
 +
            case 0:
 +
                winddirection = 'E';
 +
                break;
 +
            case 1:
 +
                winddirection = 'W';
 +
                break;
 +
            case 2:
 +
                winddirection = 'N';
 +
                break;
 +
            case 3:
 +
                winddirection = 'S';
 +
                break;
 +
                 
 +
            }
 +
         
 +
            Weather w =  new Weather(c, temp, rain, snow, windspeed, winddirection);
 +
            this.weathers.add(w);
 +
            System.out.println(w.toString());
 +
        } 
 +
    }
 +
 
 +
    public Weather getWeather(String city) throws Exception {
 +
        // TODO Auto-generated method stub
 +
        Weather found = null;
 +
        for(Weather w:this.weathers){
 +
            city = city.toLowerCase();
 +
            String wcity =w.getCity().toLowerCase();
 +
            if(city.equals(wcity)){
 +
                found = w;
 +
                return found;
 +
            }
 +
        }
 +
        return found;
 +
    }
 +
 
 +
    public void addCity(String nCity)
 +
    {
 +
        Random randomGenerator = new Random();
 +
        float temp = randomGenerator.nextFloat()+35;
 +
        float rain = randomGenerator.nextFloat()+10;
 +
        float snow = randomGenerator.nextFloat()+10;
 +
        float windspeed = randomGenerator.nextFloat()+50;
 +
        char winddirection = '.';
 +
        int r = randomGenerator.nextInt(4);
 +
        switch(r){
 +
        case 0:
 +
            winddirection = 'E';
 +
            break;
 +
        case 1:
 +
            winddirection = 'W';
 +
            break;
 +
        case 2:
 +
            winddirection = 'N';
 +
            break;
 +
        case 3:
 +
            winddirection = 'S';
 +
            break;
 +
        }
 +
     
 +
        Weather w =  new Weather(nCity, temp, rain, snow, windspeed, winddirection);
 +
        this.weathers.add(w);
 +
        System.out.println(w.toString());
 +
    }
 +
 
 +
    public void removeCity(String oCity)
 +
    {
 +
        this.weathers.remove(oCity);
 +
    }
 +
 
 +
    public ArrayList<Weather> getAllWeather()
 +
    {
 +
        return weathers;
 +
    }
 +
}
 +
</source>
 +
*You will notice that we used a public "enum" type instead of a class. This would make the object in our program a global point for the whole application to access. It's a singleton (static class).
 +
*These classes will be used later on into the tutorial.
 +
 +
==Creating and Using Commands/Views==
 +
===Commands===
 +
*Commands are in the most laymen terms, actions. What we mean by action is that we are insisting through some physical representation, whether it be a button or plain-typed text, we are calling an event. That event can be to exit the program or even perform a feature within the application.
 +
*Let's create our first menu for the menu bar that will contain a command to exit the application.
 +
*First open the file plugin.xml, click on the tab "Extensions", and then click on the "Add" button.
 +
[[File:PluginT2.png]]
 +
*Now search for "org.eclipse.ui.menus", click it to ensure it's selected, then finish it by clicking on the finish button.
 +
[[File:ExtT2.png]]
 +
*You should notice the plug-in was added to your extension.
 +
*From your current display, right-click the recently added extension->New->menuContribution. After the item has been added, change the "locationUri" to "menu:org.eclipse.ui.main.menu" (this informs the application to attach it the main ui window that Eclipse makes. Afterwords, right-click that item and perform the following actions New->menu.
 +
*Fill in the necessary based on the picture below
 +
[[File:MenuT2.png]]
 +
*Before we progress any further with menu, we must create a "Command". We'll first develop the "exit" command. Perform the exact same series of steps done earlier to add a new extension, except this time search for "org.eclipse.ui.commands". Add an item, "Commands", and add the following information based on the picture below.
 +
[[File:ExtT2.png]]
 +
*As you may recall, I made mention that commands are akin to basically doing an action, which is based on an occurrence of an event. Well, just like an event, you must develop a class that extends a type of handler to inform the application of what actions to take place. That is why you must now create package called "ecl.team2.lab3.commands" and a java file named "ExitHandler".
 +
*Copy and paste this code into the ExitHandler
 +
<source lang=java>
 +
package ecl.team2.lab3.commands;
 +
 +
import org.eclipse.core.commands.AbstractHandler;
 +
import org.eclipse.core.commands.ExecutionEvent;
 +
import org.eclipse.core.commands.ExecutionException;
 +
import org.eclipse.ui.handlers.HandlerUtil;
 +
 +
public class ExitHandler extends AbstractHandler {
 +
 +
    @Override
 +
    public Object execute(ExecutionEvent event) throws ExecutionException {
 +
        HandlerUtil.getActiveWorkbenchWindow(event).close();
 +
        return null;
 +
    }
 +
 +
}
 +
</source>
 +
*Return back to File menu and add a command file to it.
 +
*Enter what is shown in the picture below.
 +
[[File:Ext3T2.png]]
 +
*Save the MANIFEST file and run the application as we've done previously (Overview tab)
 +
*You should see this window pop-up
 +
[[File:FWindowpop3T2.png]]
 +
*Now click on "File" within the menu bar and click "Exit", this will close the program based on the small application we created for that command.
 +
'''Pre-emptive work for later on'''
 +
*Given that you now have context of how to create a command, we will now progress to creating commands that will be used later within our application. Please create the following commands along with the required items:
 +
 +
'''AddCityHandler'''
 +
For Commmand
 +
<pre>
 +
id: ecl.team2.lab3.rcpExample.AddCity
 +
name: Add City
 +
defaultHandler: ecl.team2.lab3.commands.AddCityHandler
 +
</pre>
 +
 +
For Menu Command
 +
<pre>
 +
commandId: ecl.team2.lab3.rcpExample.AddCity
 +
label: Add City
 +
tooltip: Adds a city to list
 +
</pre>
 +
 +
For AddCityHandler.java
 +
<source lang=java>
 +
package ecl.team2.lab3.commands;
 +
 +
import org.eclipse.core.commands.AbstractHandler;
 +
import org.eclipse.core.commands.ExecutionEvent;
 +
import org.eclipse.core.commands.ExecutionException;
 +
import org.eclipse.core.commands.IHandler;
 +
import org.eclipse.ui.IWorkbenchWindow;
 +
import org.eclipse.ui.IWorkbenchPage;
 +
import org.eclipse.ui.PartInitException;
 +
import org.eclipse.ui.handlers.HandlerUtil;
 +
 +
//This will allow us to edit the content using the editor window
 +
import ecl.team2.lab3.editor.WeatherEditor;
 +
import ecl.team2.lab3.editor.WeatherInput;
 +
 +
public class AddCityHandler extends AbstractHandler implements IHandler {
 +
 +
    @Override
 +
    public Object execute(ExecutionEvent event) throws ExecutionException {
 +
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
 +
        IWorkbenchPage page = window.getActivePage();
 +
     
 +
        WeatherInput input = new WeatherInput("-1");
 +
        try
 +
        {
 +
            page.openEditor(input, WeatherEditor.ID);
 +
        }
 +
        catch (PartInitException e)
 +
        {
 +
            System.out.println(e.getMessage());
 +
        }
 +
     
 +
        return null;
 +
    }
 +
 +
}
 +
</source>
 +
<br/>
 +
<br/>
 +
 +
'''RemoveCityHandler'''
 +
For Commmand
 +
<pre>
 +
id: ecl.team2.lab3.rcpExample.RemoveCity
 +
name: Add City
 +
defaultHandler: ecl.team2.lab3.commands.RemoveCityHandler
 +
</pre>
 +
 +
For Menu Command
 +
<pre>
 +
commandId: ecl.team2.lab3.rcpExample.RemoveCity
 +
label: Remove City
 +
tooltip: Removes a city or multiple cities based on selection
 +
</pre>
 +
 +
For RemoveCityHandler.java
 +
<source lang=java>
 +
package ecl.team2.lab3.commands;
 +
 +
import java.util.ArrayList;
 +
import java.util.Iterator;
 +
 +
import org.eclipse.core.commands.AbstractHandler;
 +
import org.eclipse.core.commands.ExecutionEvent;
 +
import org.eclipse.core.commands.ExecutionException;
 +
import org.eclipse.core.commands.IHandler;
 +
import org.eclipse.jface.viewers.ISelection;
 +
import org.eclipse.jface.viewers.IStructuredSelection;
 +
import org.eclipse.ui.IWorkbenchPage;
 +
import org.eclipse.ui.IWorkbenchWindow;
 +
import org.eclipse.ui.handlers.HandlerUtil;
 +
 +
import ecl.team2.lab3.rcpexample.WeatherView;
 +
import ecl.team2.lab3.weathermodel.*;
 +
 +
public class RemoveCityHandler extends AbstractHandler implements IHandler {
 +
 +
    @Override
 +
    public Object execute(ExecutionEvent event) throws ExecutionException {
 +
     
 +
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
 +
        IWorkbenchPage page = window.getActivePage();
 +
        WeatherView view = (WeatherView) page.findView(WeatherView.ID);
 +
        ISelection select = view.getSite().getSelectionProvider().getSelection();
 +
     
 +
        if(select!=null && select instanceof IStructuredSelection)
 +
        {
 +
            IStructuredSelection sel = (IStructuredSelection)select;
 +
         
 +
         
 +
            for(Iterator<Weather> iter = sel.iterator(); iter.hasNext();)
 +
            {
 +
                Weather temp = iter.next();
 +
                SimpleWeatherSystem.INSTANCE.removeCity(temp.getCity());
 +
            }
 +
            view.getViewer().refresh();
 +
        }
 +
        return null;
 +
    }
 +
 +
}
 +
</source>
 +
<br/>
 +
===Views===
 +
Since most of the back-end coding has been completed through the "Commands" section, this portion will be brief.
 +
*In order to view and edit our content, we must create a view. Creating a view is very similar to creating a command, except you must add the extension "org.eclipse.ui.views" in our MANIFEST file.
 +
*You should have something that looks akin to this
 +
[[File:UiviewsT2.png]]
 +
*Now that we've included the extension, we should create a new view so we may view and edit our content. We do this by right-clicking our recent addition, scroll to "New", and then click on "view".
 +
*Enter the following information below and once that's completed click on "class*". Clicking on "class*" will allow us to create classes on the fly using the "New Java Class" wizard. Most of the mandatory components for creating a view java class has already been added, so all we have to do is click "Finish"
 +
[[File:Ext4T2.png]]
 +
*Replace code inside "WeatherView.java" with:
 +
<source lang=java>
 +
package ecl.team2.lab3.rcpexample;
 +
 +
import org.eclipse.swt.SWT;
 +
import org.eclipse.swt.widgets.Composite;
 +
import org.eclipse.swt.widgets.Text;
 +
import org.eclipse.ui.part.ViewPart;
 +
 +
public class WeatherView extends ViewPart
 +
{
 +
    public static final String ID = "ecl.team2.lab3.rcpexample.WeatherView";
 +
 
 +
    @Override
 +
    public void createPartControl(Composite parent)
 +
    {
 +
        this.setPartName("Weather");
 +
        Text text = new Text(parent, SWT.BORDER);
 +
        text.setText("Weather content will be displayed here");
 +
    }
 +
 +
    @Override
 +
    public void setFocus()
 +
    {
 +
        // TODO Auto-generated method stub
 +
    }
 +
}
 +
</source>
 +
<br/>
 +
*We must now add our recently created view to the perspective, we do this by again engaging with the extensions in the MANIFEST file. We must include the "org.eclipse.ui.perspectiveExtensions" extension. After it is added, we will add a "view" to the last branch dubbed "*(perspectiveExtensions).
 +
*Mimic the contents in the picture below
 +
[[File:Ext5T2.png]]
 +
*Launch the application, should get something akin to this
 +
[[File:AppT2.png]]
 +
<br/>
 +
==Define and Use Editor==

Latest revision as of 00:43, 23 March 2011

Tutorial

In this tutorial, we are creating an RCP application to inform the user of current weather temperatures in major cities of North America. We will use our previous lab 2 classes and alter them according to our specification for this lab. For reference material, we are using Eclipse RCP and Eclipse JFace Table tutorial.

Prerequisites

Create a RCP Application

Run a RCP Application

  • Run Eclipse
  • Select/Enter your preferred workspace in the text box provided and click okay

RcpwT2.png

  • After Eclipse has completed loaded, create a plug-in project by clicking on "File" on the menu bar then scroll to New->Project->Other. A wizard should pop-up in which you should progress to click on the "Plug-in Development" tree, select "Plug-in Project", and click next.

WizwT2.png

  • Enter the following information that is seen in the image below

Wiz2wT2.png Wiz3wT2.png Wiz4wT2.png

  • Since we decided to use a template to create our first project, there are already a few predefined classes that we will alter to suit our requirements for this lab.
  • What you should see in your Eclipse environment is something that looks very similar to the picture below

EclipseStartT2.png

  • In the "MANIFEST" file, click on "Launch an Eclipse Application", this will run the "Hello RCP" template program that has not been edited yet. Running this application as is will result in a window to pop-up.

ManiRun1T2.pngFWindowpopT2.png

  • Lets open "ApplicationWorkbenchWindowAdvisor.java" file so we can alter the window of our application.
  • Replace the following method with the one below
public void preWindowOpen() {
     //Retrieves the main window
     IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
     //Sets the size of the window
     configurer.setInitialSize(new Point(600, 500));
     
     //Header bar becomes available
     configurer.setShowCoolBar(true);
   
     //Footer bar becomes available
     configurer.setShowStatusLine(true);
       
     //Title of the window
     configurer.setTitle("My First RCP Application"); //$NON-NLS-1$
}
  • Redo the same step previously to run the application and your window should be larger and have both header and footer bars.

FWindowpop2T2.png

Configure Your Run

  • To ensure your application has all the resources, files, etc. required to run, we need to modify the "Run Configuration" for our application.
  • Right-click the "MANIFEST" file, scroll down to "Run As", and then highlight and click "Run Configurations..."

RunconfT2.png

  • The "Run Configurations" window is now present. From here, click on the Plug-in tab and check the box "Validate plug-ins automatically prior to launching" and click Apply. This will essentially provide you with all the plug-ins needed for your program to work during runtime.

Runconf2T2.png

Creating a Package and Classes

  • We are now going to create a package called "ecl.team2.lab3.weathermodel". To do this, right-click the src folder, move the cursor to "New", then click packages. Enter "ecl.team2.lab3.weathermodel" in the "Name" textbox and click Finish.

PckgT2.pngPckg2T2.png

  • Now we are going to create classes within this package. To create a class, right-click our newly created package, highlight "New", and scroll down and click "Class". Create a class for "Weather" and "SimpleWeatherSystem".

Classl3T2.png

  • Copy and paste the following to their respective file.

Weather.java

package ecl.team2.lab3.weathermodel;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Random;

public class Weather {
    private String city;
    private float tempInCelcius;
    private float rainInMM;
    private float snowInMM;
    private float windspeedInKM;
    private char windDirection;
   
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
   
    public Weather()
    {
    }
   
    public Weather(String cit)
    {
        city=cit;
       
        Random randomGenerator = new Random();
        tempInCelcius = randomGenerator.nextFloat()+35;
        rainInMM = randomGenerator.nextFloat()+10;
        snowInMM = randomGenerator.nextFloat()+10;
        windspeedInKM = randomGenerator.nextFloat()+50;
       
        int r = randomGenerator.nextInt(4);
        switch(r){
        case 0:
            windDirection = 'E';
            break;
        case 1:
            windDirection = 'W';
            break;
        case 2:
            windDirection = 'N';
            break;
        case 3:
            windDirection = 'S';
            break;
        }
    }
   
    public Weather(String pcity, float ptemp, float prain, float psnow, float pwspeed, char pwdirection){
        this.setCity(pcity);
        this.setTempInCelcius(ptemp);
        this.setRainInMM(prain);
        this.setSnowInMM(psnow);
        this.setWindspeedInKM(pwspeed);
        this.setWindDirection(pwdirection);
    }
   
    public void setWindDirection(char windDirection) {
        propertyChangeSupport.firePropertyChange("",
                this.windDirection, this.windDirection = windDirection);
    }

    public char getWindDirection() {
        return windDirection;
    }

    public void setWindspeedInKM(float windspeedInKM) {
        propertyChangeSupport.firePropertyChange("", this.windspeedInKM,
        this.windspeedInKM = windspeedInKM);
    }

    public float getWindspeedInKM() {
        return windspeedInKM;
    }

    public void setSnowInMM(float snowInMM) {
        propertyChangeSupport.firePropertyChange("",
        this.snowInMM, this.snowInMM = snowInMM);
    }

    public float getSnowInMM() {
        return snowInMM;
    }

    public void setRainInMM(float rainInMM) {
        propertyChangeSupport.firePropertyChange("", this.rainInMM,
        this.rainInMM = rainInMM);
    }

    public float getRainInMM() {
        return rainInMM;
    }

    public void setTempInCelcius(float tempInCelcius) {
        propertyChangeSupport.firePropertyChange("", this.tempInCelcius,
        this.tempInCelcius = tempInCelcius);
    }

    public float getTempInCelcius() {
        return tempInCelcius;
    }

    public void setCity(String city) {
        propertyChangeSupport.firePropertyChange("", this.city,
        this.city = city);
    }

    public String getCity() {
        return city;
    }
   
    public void addPropertyChangeListener(String name, PropertyChangeListener listener)
    {
        propertyChangeSupport.addPropertyChangeListener(name,listener);
    }
   
    public void removePropertyChangeListener(PropertyChangeListener listener)
    {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }
   
    public String toString()
    {
        return city + " " + tempInCelcius + " " + rainInMM + " " + snowInMM + " "
        + windspeedInKM + " " + windDirection;
    }
}

SimpleWeatherSystem.java

package ecl.team2.lab3.weathermodel;

import java.util.ArrayList;
import java.util.Random;

public enum SimpleWeatherSystem {
    INSTANCE;
   
    ArrayList<Weather> weathers = new ArrayList<Weather>();
    private SimpleWeatherSystem(){
        ArrayList<String> cities = new ArrayList<String>();
        cities.add("Toronto");
        cities.add("New York");
        cities.add("Calgary");
        cities.add("Ottawa");
        cities.add("Vancouver");
        cities.add("Regina");
        cities.add("Winnipeg");
        cities.add("St. John");
        cities.add("Fredericton");
        cities.add("Halifax");
        cities.add("Quebec City");
        cities.add("Whitehorse");
        cities.add("Yellowknife");
        for(String c:cities){
            Random randomGenerator = new Random();
            float temp = randomGenerator.nextFloat()+35;
            float rain = randomGenerator.nextFloat()+10;
            float snow = randomGenerator.nextFloat()+10;
            float windspeed = randomGenerator.nextFloat()+50;
            char winddirection = '.';
            int r = randomGenerator.nextInt(4);
            switch(r){
            case 0:
                winddirection = 'E';
                break;
            case 1:
                winddirection = 'W';
                break;
            case 2:
                winddirection = 'N';
                break;
            case 3:
                winddirection = 'S';
                break;
                   
            }
           
            Weather w =  new Weather(c, temp, rain, snow, windspeed, winddirection);
            this.weathers.add(w);
            System.out.println(w.toString());
        }   
    }
   
    public Weather getWeather(String city) throws Exception {
        // TODO Auto-generated method stub
        Weather found = null;
        for(Weather w:this.weathers){
            city = city.toLowerCase();
            String wcity =w.getCity().toLowerCase();
            if(city.equals(wcity)){
                found = w;
                return found;
            }
        }
        return found;
    }
   
    public void addCity(String nCity)
    {
        Random randomGenerator = new Random();
        float temp = randomGenerator.nextFloat()+35;
        float rain = randomGenerator.nextFloat()+10;
        float snow = randomGenerator.nextFloat()+10;
        float windspeed = randomGenerator.nextFloat()+50;
        char winddirection = '.';
        int r = randomGenerator.nextInt(4);
        switch(r){
        case 0:
            winddirection = 'E';
            break;
        case 1:
            winddirection = 'W';
            break;
        case 2:
            winddirection = 'N';
            break;
        case 3:
            winddirection = 'S';
            break;
        }
       
        Weather w =  new Weather(nCity, temp, rain, snow, windspeed, winddirection);
        this.weathers.add(w);
        System.out.println(w.toString());
    }
   
    public void removeCity(String oCity)
    {
        this.weathers.remove(oCity);
    }
   
    public ArrayList<Weather> getAllWeather()
    {
        return weathers;
    }
}
  • You will notice that we used a public "enum" type instead of a class. This would make the object in our program a global point for the whole application to access. It's a singleton (static class).
  • These classes will be used later on into the tutorial.

Creating and Using Commands/Views

Commands

  • Commands are in the most laymen terms, actions. What we mean by action is that we are insisting through some physical representation, whether it be a button or plain-typed text, we are calling an event. That event can be to exit the program or even perform a feature within the application.
  • Let's create our first menu for the menu bar that will contain a command to exit the application.
  • First open the file plugin.xml, click on the tab "Extensions", and then click on the "Add" button.

PluginT2.png

  • Now search for "org.eclipse.ui.menus", click it to ensure it's selected, then finish it by clicking on the finish button.

ExtT2.png

  • You should notice the plug-in was added to your extension.
  • From your current display, right-click the recently added extension->New->menuContribution. After the item has been added, change the "locationUri" to "menu:org.eclipse.ui.main.menu" (this informs the application to attach it the main ui window that Eclipse makes. Afterwords, right-click that item and perform the following actions New->menu.
  • Fill in the necessary based on the picture below

MenuT2.png

  • Before we progress any further with menu, we must create a "Command". We'll first develop the "exit" command. Perform the exact same series of steps done earlier to add a new extension, except this time search for "org.eclipse.ui.commands". Add an item, "Commands", and add the following information based on the picture below.

ExtT2.png

  • As you may recall, I made mention that commands are akin to basically doing an action, which is based on an occurrence of an event. Well, just like an event, you must develop a class that extends a type of handler to inform the application of what actions to take place. That is why you must now create package called "ecl.team2.lab3.commands" and a java file named "ExitHandler".
  • Copy and paste this code into the ExitHandler
package ecl.team2.lab3.commands;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;

public class ExitHandler extends AbstractHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        HandlerUtil.getActiveWorkbenchWindow(event).close();
        return null;
    }

}
  • Return back to File menu and add a command file to it.
  • Enter what is shown in the picture below.

Ext3T2.png

  • Save the MANIFEST file and run the application as we've done previously (Overview tab)
  • You should see this window pop-up

FWindowpop3T2.png

  • Now click on "File" within the menu bar and click "Exit", this will close the program based on the small application we created for that command.

Pre-emptive work for later on

  • Given that you now have context of how to create a command, we will now progress to creating commands that will be used later within our application. Please create the following commands along with the required items:

AddCityHandler For Commmand

id: ecl.team2.lab3.rcpExample.AddCity
name: Add City
defaultHandler: ecl.team2.lab3.commands.AddCityHandler

For Menu Command

commandId: ecl.team2.lab3.rcpExample.AddCity
label: Add City
tooltip: Adds a city to list

For AddCityHandler.java

package ecl.team2.lab3.commands;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

//This will allow us to edit the content using the editor window
import ecl.team2.lab3.editor.WeatherEditor;
import ecl.team2.lab3.editor.WeatherInput;

public class AddCityHandler extends AbstractHandler implements IHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
        IWorkbenchPage page = window.getActivePage();
       
        WeatherInput input = new WeatherInput("-1");
        try
        {
            page.openEditor(input, WeatherEditor.ID);
        }
        catch (PartInitException e)
        {
            System.out.println(e.getMessage());
        }
       
        return null;
    }

}



RemoveCityHandler For Commmand

id: ecl.team2.lab3.rcpExample.RemoveCity
name: Add City
defaultHandler: ecl.team2.lab3.commands.RemoveCityHandler

For Menu Command

commandId: ecl.team2.lab3.rcpExample.RemoveCity
label: Remove City
tooltip: Removes a city or multiple cities based on selection

For RemoveCityHandler.java

package ecl.team2.lab3.commands;

import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import ecl.team2.lab3.rcpexample.WeatherView;
import ecl.team2.lab3.weathermodel.*;

public class RemoveCityHandler extends AbstractHandler implements IHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
       
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
        IWorkbenchPage page = window.getActivePage();
        WeatherView view = (WeatherView) page.findView(WeatherView.ID);
        ISelection select = view.getSite().getSelectionProvider().getSelection();
       
        if(select!=null && select instanceof IStructuredSelection)
        {
            IStructuredSelection sel = (IStructuredSelection)select;
           
           
            for(Iterator<Weather> iter = sel.iterator(); iter.hasNext();)
            {
                Weather temp = iter.next();
                SimpleWeatherSystem.INSTANCE.removeCity(temp.getCity());
            }
            view.getViewer().refresh();
        }
        return null;
    }

}


Views

Since most of the back-end coding has been completed through the "Commands" section, this portion will be brief.

  • In order to view and edit our content, we must create a view. Creating a view is very similar to creating a command, except you must add the extension "org.eclipse.ui.views" in our MANIFEST file.
  • You should have something that looks akin to this

UiviewsT2.png

  • Now that we've included the extension, we should create a new view so we may view and edit our content. We do this by right-clicking our recent addition, scroll to "New", and then click on "view".
  • Enter the following information below and once that's completed click on "class*". Clicking on "class*" will allow us to create classes on the fly using the "New Java Class" wizard. Most of the mandatory components for creating a view java class has already been added, so all we have to do is click "Finish"

Ext4T2.png

  • Replace code inside "WeatherView.java" with:
package ecl.team2.lab3.rcpexample;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

public class WeatherView extends ViewPart
{
    public static final String ID = "ecl.team2.lab3.rcpexample.WeatherView";
   
    @Override
    public void createPartControl(Composite parent)
    {
        this.setPartName("Weather");
        Text text = new Text(parent, SWT.BORDER);
        text.setText("Weather content will be displayed here");
    }

    @Override
    public void setFocus()
    {
        // TODO Auto-generated method stub
    }
}


  • We must now add our recently created view to the perspective, we do this by again engaging with the extensions in the MANIFEST file. We must include the "org.eclipse.ui.perspectiveExtensions" extension. After it is added, we will add a "view" to the last branch dubbed "*(perspectiveExtensions).
  • Mimic the contents in the picture below

Ext5T2.png

  • Launch the application, should get something akin to this

AppT2.png

Define and Use Editor