Saturday, August 23, 2008

Eclipse Test Oriented Templates

Eclipse templates decrease some of the drudgery of re-typing common patterns. While there are quite a few posts that describe the process for importing, exporting and writing custom templates, I have not encountered too many custom templates geared specifically to the test-oriented community (aside from the standard Test and test Java type member templates). With the recent addition of the Templates View in Ganymede, the abilty to paste snippets from the clipboard to this view, and a new feature that allows the automatic addition of Java imports, I will keep the idea of factoring common code patterns to templates in the back of my mind during my day-to-day coding. Because I am a test-oriented developer, I have found the following particularly useful:

JUnit templates:


setup (Context Java type members) Used to create a JUnit4 setUp method

${:import(org.junit.Before)}
@Before
public void setUp() {
}


setup_before_class (Context Java type members) Used to create a static JUnit4 Class setUp method

${:import(org.junit.BeforeClass)}
@BeforeClass
public static void setUpBeforeClass() {
}


teardown (Context Java type members) Used to create a JUnit4 tearDown method

${:import(org.junit.After)}
@After
public void tearDown() {
}


teardown_after_class (Context Java type members) Used to create a static JUnit4 Class tearDowan method

${:import(org.junit.AfterClass)}
@AfterClass
public static void tearDownAfterClass() {
}


Test_expected_exception (Context Java type members) Used to create a JUnit4 test method that expects an Exception to be thrown

@${testType:newType(org.junit.Test)}(expected = ${cursor})
public void ${testname}() throws Exception {
${staticImport:importStatic('org.junit.Assert.*')}
}


Test_timeout (Context Java type members) Used to create a JUnit4 test method with a time limit

@${testType:newType(org.junit.Test)}(timeout = ${cursor})
public void ${testname}() throws Exception {
${staticImport:importStatic('org.junit.Assert.*')}
}


JMock templates:



run_with_jmock (Context Java) Used to annotate a Test Class that it should be run with the JMock runner

${:import(org.junit.runner.RunWith,org.jmock.integration.junit4.JMock)}
@RunWith(JMock.class)


mockery_for_classes (Context Java type members) Used to create a new JMock mockery for Classes

${:import(org.jmock.Mockery,org.jmock.lib.legacy.ClassImposteriser)}
private final Mockery mockery = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};


mockery_for_interfaces (Context Java type members) Used to create a new JMock mockery for Interfaces

${:import(org.jmock.Mockery)}
private final Mockery mockery = new Mockery();


checking (Context Java statements) Used to setup JMock expectations

${:import(org.jmock.Expectations)}

mockery.checking(new Expectations() {
{
}
});


General templates:


sysdebug (Context Java statements) Slightly more robust than sysout, labels the value printed to standard out.

System.out.println("${word_selection}=["+${word_selection}${}+"].");${cursor}


templates.xml


You can also copy the following text to a templates.xml file and import it through Eclipse Window -> Preferences -> Java -> Editor -> Templates


<?xml version="1.0" encoding="UTF-8"?><templates><template autoinsert="true" context="java-statements" deleted="false" description="Setup JMock expectations" enabled="true" name="checking">${:import(org.jmock.Expectations)}&#13;
mockery.checking(new Expectations() {&#13;
{&#13;
}&#13;
});</template><template autoinsert="true" context="java-members" deleted="false" description="Create a new JMock Mockery" enabled="true" name="mockery_for_classes">${:import(org.jmock.Mockery,org.jmock.lib.legacy.ClassImposteriser)}&#13;
private final Mockery mockery = new Mockery() {&#13;
{&#13;
setImposteriser(ClassImposteriser.INSTANCE);&#13;
}&#13;
};</template><template autoinsert="true" context="java-members" deleted="false" description="Create a new JMock Mockery" enabled="true" name="mockery_for_interfaces">${:import(org.jmock.Mockery)}&#13;
private final Mockery mockery = new Mockery();</template><template autoinsert="true" context="java" deleted="false" description="Creates a @RunWith(JMock.class) declaration" enabled="true" name="run_with_jmock">${:import(org.junit.runner.RunWith,org.jmock.integration.junit4.JMock)}&#13;
@RunWith(JMock.class)</template><template autoinsert="true" context="java-members" deleted="false" description="setup a JUnit test case" enabled="true" name="setup">${:import(org.junit.Before)}&#13;
@Before&#13;
public void setUp() {&#13;
}</template><template autoinsert="true" context="java-members" deleted="false" description="Create a static setup method" enabled="true" name="setup_before_class">${:import(org.junit.BeforeClass)}&#13;
@BeforeClass&#13;
public static void setUpBeforeClass() {&#13;
}</template><template autoinsert="true" context="java-statements" deleted="false" description="print to standard out with a descriptive variable name" enabled="true" name="sysdebug">System.out.println("${word_selection}=["+${word_selection}${}+"].");${cursor}</template><template autoinsert="true" context="java-members" deleted="false" description="tear down a JUnit test case" enabled="true" name="teardown">${:import(org.junit.After)}&#13;
@After&#13;
public void tearDown() {&#13;
}</template><template autoinsert="true" context="java-members" deleted="false" description="Create a static teardown method" enabled="true" name="teardown_after_class">${:import(org.junit.AfterClass)}&#13;
@AfterClass&#13;
public static void tearDownAfterClass() {&#13;
}</template><template autoinsert="false" context="java-members" deleted="false" description="Test method (JUnit 4) for an expected exception" enabled="true" name="Test_expected_exception">@${testType:newType(org.junit.Test)}(expected = ${cursor})
public void ${testname}() throws Exception {
${staticImport:importStatic('org.junit.Assert.*')}
}</template><template autoinsert="false" context="java-members" deleted="false" description="Test method (JUnit 4) that sets a timeout" enabled="true" name="Test_timeout">@${testType:newType(org.junit.Test)}(timeout = ${cursor})
public void ${testname}() throws Exception {
${staticImport:importStatic('org.junit.Assert.*')}
}</template></templates>

Wednesday, July 30, 2008

Run Weblogic Ant Tasks Without setDomainEnv

Suppose we need to run one of the Weblogic ant tasks for deployment of an application, such as wldeploy, or for webservice support, such as clientgen, jwsc or wsdlc (or any task that requires the environment to be set previously by executing the setDomainEnv script). Suppose we need to execute such an ant task in one command without having set the domain environment previously with this script, say from inside Eclipse. The problem turned out to be more frustrating than I would have preferred, especially since calling the .cmd and then calling ant from another .bat file was problematic. The solution is straightforward, and we can walk through it using the wldeploy example.

The first step is to setup some properties describing your environment, i.e., the location of the weblogic installation, the weblogic domain installation and the weblogic classpath. Assuming we are using weblogic 10 with a domain called aDomain, those properties will look something like this:

<?xml version="1.0"?>
<project ....>
    ....
    <property name="my.home" location="C:/bea" />
    <property name="my.domain" location="${my.home}/user_projects/domains/aDomain" />
    <path id="weblogic.classpath">
        <fileset dir="${my.home}/wlserver_10.0/server/lib">
            <include name="*.jar" />
        </fileset>
    </path>
    ....
</project>



Next, we define the wldeploy task:

<project ....>
    ....
    <taskdef name="wldeploy" 
        classname="weblogic.ant.taskdefs.management.WLDeploy">
        <classpath refid="weblogic.classpath" />
    </taskdef>
    ....
</project>



Now we can create a macro for running any weblogic ant task that requires the environment be set through the setDomainEnv script:

<project ....>
    ....
    <macrodef name="run-domain-task">
        <attribute name="task.name" />
        <sequential>
            <property name="runner" location="${my.domain}/bin/run_domain_task.cmd" />
            <copy file="${my.domain}/bin/setDomainEnv.cmd" tofile="${runner}" overwrite="true" />
            <concat append="true" destfile="${runner}">
                  ant -f "${ant.file}" @{task.name}</concat>
            <exec executable="${runner}" />
        </sequential>
    </macrodef>
    ....
</project>



This macro takes as input a target, such as deploy-to-domain below. It copies the setDomainEnv.cmd to a runner script and appends a command to call the input target from ant. In this way, the domain environment will be set properly before the weblogic-specific task runs.

We can now create a target to be called from the runner deployed in the macro:

<project ....>
    ....
    <target name="deploy-to-domain">
      <wldeploy action="deploy" .... />
    </target>
    ....
</project>



Finally, we add a public target that we call directly or that our Continuous Integration system can run when it has finished building our enterprise application.

<project ....>
    ....
    <target name="deploy">
        <run-domain-task task.name="deploy-to-domain" />
    </target>
    ....
</project>



Ideally, I would prefer to set the environment directly through Ant instead of through the script. As a quick solution, and because setDomainEnv is generated based on a particular installation of a domain, the solution works well in the general case. If anyone is aware of a generic, fully Ant-based solution to this problem, I would certainly like to hear about it.
I would also recommend moving away from Ant and towards Maven2 when at all possible. These instructions should be a good starting point for migrating toward a Maven2 build and deployment solution for Weblogic.

Tuesday, July 29, 2008

ODA Ecore Getting Started Guide -- Part Kettő

Note: this post is a continuation of The ODA-Ecore Getting Started Guide and assumes that you are familiar with its contents and the examples presented therein.

Creating a Master-Details Report


Suppose we want to report on all the Writers and their Books in a model.  Each Writer's name should appear in the Master part of the report.  Each of the Writer's Books should appear as a Detail and should display the Title, Number of Pages and the Category for the Book.

There are at least two solutions with the current implementation of the enablement plug-in.

EReference Resolution

The ODA-Ecore enablement plug-in supports EReference resolution. For any EObject that contains a reference to another EObject, it is possible to display the value of a particular EAttribute of that EReference (or an EAttribute of an EReference to an EReference, etc.). It is also possible to display the value of the full EReference itself (which is just a toString() of the EObject that is referenced).  A user selects EAttributes of EReferences when creating a new Data Set in the Data Set Columns Wizard Page.  Collections of References are returned as a <cr>-delimited String of the selected EAttributes for an EReference. The more deeply nested the EAttribute or EReference, the more dificult interpretation of the results becomes, which is why this method is prefered only in simple cases.



In this selection, we have chosen to output the publicationDate of any books written by a particular Writer, along with the address of any borrowers of the books written by the Writer.

Using EReferences is a simple solution, but it is limited in the general case. For such a simple use case, it will satisfy our needs, however.
From the Query Wizard Page, select Writer as the Invariant.
As your Boolean Query, use "self.oclIsKindOf(Writer)".
From the Columns Wizard Page, select

  • Writer::name
  • Writer::books::title
  • Writer::books::pages
  • Writer::books::category

In the BIRT report, we will insert a new table with 1 columns and 2 details. The first details row will be the Master part, the second will be the Details part.
In column 1 of the first detail row, we will drag Writer::name from the Data Set.
In the second detail row, we will insert a new table with 2 columns and 1 detail. The first column is for spacing, the second will contain the EAttribute values (for the Details part).
In the detail row of the second column of the nested table, we will insert another table with 3 columns and 1 detail row.
Finally, into these 3 columns, we will drag Writer::books::title, Writer::books::pages and Writer::books::category from the Data Set.
We could remove the header information and re-space the columns to get the layout of the information that we want.


The Layout of the Report using EReference Resolution for Master-Details display.




We have achieved our goal using three nested tables and a single query that resolves EReferences. 

Joining ResultSets

Parameterizing the BooleanOCLQuery and and using multiple joined data sets are solutions for more complex situations.

each ? in the query is replaced with the input parameters in order (the first ? is replaced with the first parameter, the second ? is replaced with the second parameter, etc.). Named parameters are not yet supported.

For the example stated above (a Master-Details table of each Writer's name as the Master with information about all the Writer's Books as the Detail.)
1. Create a DataSource and point it to the Extlibrary file.
2. Create a DataSet called "Writers Data Set" with these features:

  • Invariant -- Writer
  • Query -- self.oclIsKindOf(Writer)
  • Selected Column -- Writer::name

3. Create a DataSet called "Books Data Set" with these features:

  • Invariant -- Book
  • Query -- self.oclIsKindOf(Book) and self.oclAsType(Book).author.name = '?'
  • Selected Columns -- Book::title, Book::pages, Book::category, Book::author::name (just to prove out what we are doing)
  • Parameters -- input param1 with default value 'James Fenimore Cooper' (make sure you use quotes or you will get a Javascript error).

4. Drag the Writers Data Set into the Report and name the Table "Writers List". This is the Master part.
5. Add a column to the right of the Writer::name column.
6. Drag the Books Data Set into the empty column. This is the Details part.
7. Select the Books Data Set Table and add a Data Set Parameter Binding from Writer::name to param1.

8. Select Preview and you should now see a Master-Details report that lists the Writers' names in the first column and, for each Writer, a list of the Books associated to that Writer in a nested table in the right column.



Sorting Results


Suppose we need to sort or filter the results of a query. As only Boolean OCL queries are supported by the enablement plug-in, the driver does not currently support a SORT BY feature in the OCL query itself. Fortunately, BIRT's sorting and filtering mechanism for groups should satisfy many of our needs.
Suppose we want to find all the Writers in the object graph and print their names. In the Wizard to form the DataSet, we would choose "Writer" from the dropdown, our query would be "self.oclIsKindOf(Writer)", and we would choose to report on the column "Writer::name".
For the report, we can drag the Data Set from the Data Explorer to the report.


The unsorted preview of this report.

In the Detail Row, instead of using "[Writer::name]", we will delete the Detail row, right click and select "Insert Group". On the Group Details wizard, we will select the item to group on (here, "Writer::name") and the type of sorting we want to perform (here, "Writer::name" in ascending order).


The configuration of filters and sorters.

The resulting report should consistently contain sorted, unique results.


Duplicates are removed and writers' names appear alphabetically.

Thursday, July 24, 2008

Drop All Tables in a Single Query

Recently, I needed to find a single, simple PL/SQL command to drop all the tables from an Oracle database without explicitly naming each table and without dropping the entire schema. Application development has just started, and I need to easily rename tables and other database objects, so the simplest solution at this early stage is often just to wipe and recreate the entire schema.
One possible solution would be to login as SYS and drop the schema itself, but I need to configure a single login for any database access, i.e., the user whose database objects will be deleted.

I did not find my specific solution online, but I owe thanks to alternative approaches in some other posts.

First, make sure that you connect to Oracle as the correct user, i.e., the one whose tables will be dropped.

This command will drop all the user's tables:
BEGIN 
  FOR i IN (SELECT table_name FROM user_tables) 
    LOOP 
      EXECUTE IMMEDIATE('DROP TABLE ' || user || '.' || i.table_name || ' CASCADE CONSTRAINTS'); 
    END LOOP; 
END;

Similar commands can be used to drop all triggers, sequences, etc.  For example,
BEGIN 
  FOR i IN (SELECT trigger_name FROM user_triggers) 
    LOOP 
      EXECUTE IMMEDIATE('DROP TRIGGER ' || user || '.' || i.trigger_name); 
    END LOOP; 
END;

               and

BEGIN 
  FOR i IN (SELECT sequence_name FROM user_sequences) 
    LOOP 
      EXECUTE IMMEDIATE('DROP SEQUENCE ' || user || '.' || i.sequence_name); 
    END LOOP; 
END;

NB: if you drop all tables before triggers, your triggers will be renamed with special characters and the command might not work; make sure to drop triggers before tables.

Monday, June 30, 2008

Solipse for Eclipse on solaris-gtk-x86

Many thanks to Hugo Garcia for setting up the Solipse project to house our progress in creating a distributable build of Eclipse for solaris-gtk-x86. The scripts that I had previously posted on this blog have now been moved to the downloads area of the project site. We have successfully been able to build fully-functional Eclipse distributions (sans the internal browser and OpenGL support) from 3.3 to 3.4 on OpenSolaris and Nexenta, and our goal is currently to iron out the last details of the SWT browser component, OpenGL support and the p2 SDKProfile and to contribute the binaries back to eclipse to make the build official.
Thanks to everyone who sent suggestions and who found some use for the initial scripts, and please feel welcome on the Solipse community site!

Saturday, June 28, 2008

Edit EMF Tree Nodes Inline

The problem to solve: to edit a specific property inline in a tree editor generated by EMF.

For this example, we will be using a tree editor for UML. For any UML NamedElement, we would like to be able to edit the name directly in the tree editor.

1. We will generate the UML.genmodel using the UML.ecore file from eclipse cvs

  • host: dev.eclipse.org
  • repository path: /cvsroot/modeling
  • location: org.eclipse.mdt/org.eclipse.uml2/plugins/org.eclipse.uml2.uml/model/UML.ecore

With the UML.genmodel file, emit the UML Model, Edit and Editor code. This custom UML editor is only used for this example. You may very well have a different model editor in mind for customization.


2. We have the UML model code (the domain objects and the factories to create those domain objects), UML edit code (the Item Providers and Item Provider adapter factory for the domain objects) and UML editor in three separate plug-ins. We can call these uml.inline.editing.example (for the model), uml.inline.editing.example.edit (for the item providers) and uml.inline.editing.example.editor (for the editor).

3. We want to make sure that the NamedElementItemProvider implements org.eclipse.emf.edit.provider.IUpdateableItemText because we want to be able to update the name property of NamedElements inline. The two methods we would like to include look like this:

  public void setText(Object o, String s) {
    if (!(o instanceof NamedElement)) {
      return;
    }
    NamedElement namedElement = (NamedElement) o;
    if ("".equals(s) && !namedElement.isSetName()) {
      return;
    }
    IEditorPart activeEditor = PlatformUI.getWorkbench()
      .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
    if (activeEditor instanceof IEditingDomainProvider) {
      EditingDomain editingDomain = ((IEditingDomainProvider) activeEditor)
        .getEditingDomain();
      editingDomain.getCommandStack().execute(
        SetCommand.create(editingDomain, namedElement,
        UmlPackage.eINSTANCE.getNamedElement_Name(), s));
    } else {
      namedElement.setName(s);
    }  
  }
  
  @Override
  public String getUpdateableText(Object o) {
    if (o instanceof NamedElement) {
      NamedElement namedElement = (NamedElement) o;
      if (namedElement.getName() == null) {
        return "";
      }
      return namedElement.getName();
    }
    return super.getUpdateableText(o);
  }

 Keep in mind that the superclass org.eclipse.emf.edit.provider.ItemProviderAdapter already includes a method #getUpdateableText(Object).
 
4. We need to make sure the UMLItemProviderAdapterFactory will adapt NamedElements to this IUpdateableText item provider. For this, we will need to add IUpdateableText.class to the supported types in the constructor.  The generated code is in grey: 

  public UmlItemProviderAdapterFactory() {
    supportedTypes.add(IUpdateableItemText.class);
    supportedTypes.add(IEditingDomainItemProvider.class);
    supportedTypes.add(IStructuredItemContentProvider.class);
    supportedTypes.add(ITreeItemContentProvider.class);
    supportedTypes.add(IItemLabelProvider.class);
    supportedTypes.add(IItemPropertySource.class);
  }

 

What if we want to set the focus of the UMLEditor on the updateable field as soon as the NamedElement is created?

By default, if we were to hit SPACE when a NamedElement node is selected, the cell editor would gain focus.  Suppose we want the cell editor to have focus automatically whenever a new NamedElement is created.

For this we can modify the CommandStackListener in the generated UMLEditor to focus the cell editor in the tree whenever a new child or sibling NamedElement is created in the tree editor. Generated code is in grey:

  commandStack.addCommandStackListener(new CommandStackListener() {
    public void commandStackChanged(final EventObject event) {
      getContainer().getDisplay().asyncExec(new Runnable() {
        public void run() {
          firePropertyChange(IEditorPart.PROP_DIRTY);
   
          // Try to select the affected objects.
          //
          Command mostRecentCommand = ((CommandStack) event
            .getSource()).getMostRecentCommand();
          if (mostRecentCommand != null) {
            setSelectionToViewer(mostRecentCommand
              .getAffectedObjects());

            // set the focus on the editable tree cell
            if (currentViewer instanceof TreeViewer
              && (mostRecentCommand instanceof CreateChildCommand)) {
              Tree tree = ((TreeViewer) currentViewer)
                .getTree();
              TreeItem[] treeItems = tree.getSelection();
              if (treeItems.length == 1) {
                Event enableEditField = new Event();
                enableEditField.button = 1;
                enableEditField.x = treeItems[0].getBounds().x;
                enableEditField.y = treeItems[0].getBounds().y;
                tree.notifyListeners(SWT.Selection, enableEditField);
                tree.notifyListeners(SWT.MouseDown, enableEditField);
                tree.notifyListeners(SWT.MouseUp, enableEditField);
              }
            }
          }
          if (propertySheetPage != null
            && !propertySheetPage.getControl().isDisposed()) {
            propertySheetPage.refresh();
          }
        }
      });
    }
  });

It is just that easy to specify a default property for direct inline editing in a generated EMF editor!



The cell editor is focused.

The name cell editor is focused.


The tree node label is focused.

The label is focused.

Saturday, May 31, 2008

ODA Ecore Driver Backport

This post is a continuation of the description of the ODA Ecore Enablement plug-ins, now available for download from the Eclipse datatools incubator.
Recently, the ODA Ecore plug-ins were backported for JDK 1.4 and Eclipse 3.2 compatibility. This project has been moved into the datatools incubator attic directory. The same functionality is there in both sets of plug-ins, but there is no guarantee of future support for the archived version.
The primary difference between the Europa version and the backport is the backport's use of the now-deprecated org.eclipse.emf.ocl API for running ocl queries that has since been replaced by a new org.eclipse.ocl query parser. The backport does work in Europa, but the newer, EMF 2.3-dependent version of the plug-in allows shorter, context-free ocl query syntax.

Set up the ODA Ecore Driver in Eclipse 3.2


Download Eclipse 3.2 Callisto and unzip it.
Download EMF 2.2 and unzip it into your Callisto directory.
Download the EMF 2.2 examples and unzip them into your Callisto directory if you want to try the example described in the ODA Ecore Getting Started Guide.
Download EMFT Validation 1.0.1 and unzip it into your Callisto directory.
Download EMFT Transaction 1.0.2 and unzip it into your Callisto directory.
Download EMFT OCL 1.0.1 and unzip it into your Callisto directory.
Download EMFT Query 1.0.1 and unzip it into your Callisto directory.

After starting this installation of Eclipse 3.2, install the following plug-ins from the Callisto discovery site:
Database Development -> Datatools Platform Enablement 0.9 and its dependencies
Charting and Reporting -> Eclipse BIRT Report Designer Framework 2.1 and its dependencies (to run the example described in the ODA Ecore Getting Started Guide).

Import The Archived ODA Ecore Driver projects from CVS.
The Host is dev.eclipse.org
The Repository path is /cvsroot/datatools
Browse to org.eclipse.datatools.incubator/attic, select
  • org.eclipse.datatools.enablement.oda.ecore
  • org.eclipse.datatools.enablement.oda.ecore.ui
and check the projects out to your workspace.

Because the plug-ins are JDK 1.4 compatible, if you have a later version of the JDK, you might want to set your Java Compiler Preference to 1.4 Compliance to eliminate any compiler warnings.
Everything should be set-up correctly, and you should now see no compiler errors.

Try the ODA Ecore driver extlibrary Example



We can now launch a new Eclipse runtime and set up an initial BIRT report and .extlibrary file in our workspace as described in the example from the ODA Ecore Getting Started Guide.
Data source creation is the same, so we can follow the instructions without changes.
Data Set creation is slightly different because the query syntax for the backport is more strict. The boolean query in the example, self.oclIsKindOf(Writer), will work for the backport. The differences show up with more complex queries.
Suppose we want to find only references to James Fenimore Cooper. While we can use self.name = 'James Fenimore Cooper' in the latest version of the plug-in, this query will not work in the backport. The query must read self.oclIsKindOf(Writer) and self.oclAsType(Writer).name = 'James Fenimore Cooper'. The newer org.eclipse.ocl query parser can handle the stricter old-style query, but the older org.eclipse.emf.ocl parser cannot properly interpret the shorter context-free query.
Aside from that slight difference in query syntax, the plug-ins currently have the same features. So if you have the restriction that you must continue using Eclipse 3.2 or Java 1.4 and cannot upgrade to Eclipse 3.3 or EMF 2.3, but you need the features exposed by the ODA Ecore driver, you have this backport as an option!