Model driver development with Eclipse Modeling Framework, Part 1

xiaoxiao2021-03-06  77

Create a UML model and generate a code

Level: Intermediate

Adrian Powell

Advisory I / T Specialist, IBM 2004 May

Eclipse Modeling Framework (EMF) is an open source model drive application development framework. It can create Java code based on the model specified in XML Schema, UML, or the annotated Java to achieve graphical data editing, manipulation, reading, and serialization. EMF is the foundation of many tools in IBM WebSphere Studio and Eclipse projects. This article will help you gradually understand the creation of the model, generate code, using the generated application and custom editor.

What is EMF? Eclipse Modeling Framework (EMF) is an open source framework that achieves the development of model drive architecture (Model-Driven Architecture). If a few people in us have been fortunate to have a UML model, then this framework can help us turn the document into code. As for others, this tool also makes you a chance to confirm to the boss, which spends the time to model the model. In addition to generating an amazing Java code, EMF can also generate an Eclipse plugin, as well as graphical settable editors. When you change the model (this situation will appear), the EMF can keep the code and model synchronize by clicking a button.

The code generated by the EMF is not a solution that only dispenses the trash. This code supports standard creation, acquisition, update, and delete operations, and also supports meticular constraints, complex relationships, and inheritance structures, mask definitions, and a set of properties descriptions. The generated code also provides notifications, reference integrity and customizable XMI persistence. All the work you need to do is to create an object model, just like you have also wanted to do.

EMF is a relatively new thing, but the prospect is broad, and it has strong support for it. It implements a public standard, an object management organization (META-Object Facility, MOF). Now EMF has enhanced the second edition of MOF. Further, EMF is also the basis of EMF: XSD and Hyades, etc., most IBM WebSphere Studio products are also used. The development of EMF second edition has begun, and development builds should be released soon. The second edition development plan includes better XML Schema support, more flexible code generation methods, and mapping mechanisms between the models.

Let the tools spend their own business propaganda has been more than enough. Now let's go directly into the code and see what EMF can do. The following examples are implemented with Eclipse 3.0M7 and EMF 2.0.0, plus the XSD toolbox that matches it. There are now four separate EMF development processes, each applies to different versions of Eclipse, so be sure to select the correct EMF version based on your Eclipse version (see the link in the reference).

We will show you the most important features as an example with a simple web forum. The root of the model is Forum, which includes a set of Member and Topic. Each Topic has a TopicCategory (enumeration type), MEMBER and TOPICs indirectly associated between the POST class, and there is also a direct association between the two, because Member can create Topic.

Creating an EMF model OMONDO with UML and Omondo is a convenient and reliable tool for creating a UML document in Eclipse. It looks like the refredable little brother of Rational Rose, unless you need a particularly powerful function, otherwise you can work very well. However, the tool has not yet supported Eclipse 3, so I use Eclipse 2.1 to create a UML class diagram. At first, we create a new Java project UmlForum, and a new package com.ibm.example.forum. Create a new EMF class diagram, forum.ucd, stored under SRC / COM / IBM / EXAMPLE / Forum. Two files, Forum.ecd and Forum.ecore are created in the catalog. Add a new class to the class diagram, named Forum, and then click Finished. Add an attribute description to the Forum class, type ESTRING (there is a corresponding ECORE class for all simple Java classes), as shown in Figure 1. For properties, you only select Changeable and set to from 0 to 1.

If you have changed your mind, you want to use other features, you can open the Properties view, select the class or properties.

Figure 1. New Forum class and its properties

Repeat the above steps for the following interfaces:

Interface attribute type MEMBERNICKNAMEESTRINGTOPITISTISTRINGPOSTCOMMENTESTERING

To define the association, we can select the associated button, and then click the associated source (Forum) and the target (MEMBER). This will open the associated property setting dialog. Set the name to MEMBERS to ensure only Changeable and Containment are selected, and then the upper limit is set to -1. In the Second Association End tab, uncheck Navigable, then click OK. The same operation is also performed on Forum and Topic, and the attribute name is changed from Members to Topics. Uncheck Navigable, create a directionless association, but we want other properties to remain bidirectional.

Follow the table below to complete the association settings:

Source object name associated with characteristic ranges MemberTopic1st AssociationtopicsCreatedchangeable0 to 12nd Associationcreatorchangeable0 to 1TopicPost1st AssociationpostsContainment, changeable0 to the -12nd Associationtopicchangeable0 1MemberPost1st Associationpostschangeable0 to 1 to -12nd Associationauthorchangeable0

Finally, we want to define an enumeration type to indicate how many different types of Topic. Create a new enumeration type, name is Topiccategory. Add the following contents in Literal:

Announcement, value = 0 guest_book, value = 1 discussion, value = 2

Then, define a new attribute for Topic, called Category, type Topiccategory, Changeable, Range 0-1. If you prefer, you can modify the default values ​​on the property tag, but we will accept the default value of Announcement. Figure 2. Completed UML type model

Once you have completed the UML class diagram shown in Figure 2, the next step is to create an EMF model. To do this, you need to create a new EMF project (File> New> Project ...> Eclipse Modeling Framework> EMF Project), and use com.ibm.example.forum as the name of the project (this is the foundation of the plugin name, So we follow the naming specification of the Eclipse plugin). On the next page, select Load from An Emf Core Model, and then click Next. Load the ECore file from the file system, which will automatically populate the model name of the Generator. On the last page, click the check box next to the package, and then click Finish. This creates an EMF model, and its name is Forum.Genmodel. You can learn from the generated EMF model section, and how to use it.

Creating an EMF Model XML Schema (XSD) with XML Schema is not as strong as UML or Java code with annotated, for example, it cannot express associations with two-way references. However, due to the default serialization method to use your scheme, XSD is the fastest way to customize serialization. If you want to generate a very detailed XML / XMI for the model, then XSD is an inevitable choice.

Listing 1. FORUM.XSD fragment

In Listing 1, you can see how the enumeration is expressed, and you can learn how to define a type with other types of elements and references. In this example, we only use string properties "XSD: String", but other simple Java types are also supported. For more information on XML Schema and Forum.xsd files, see Resources. Once the XSD is completed, the next step is to create an EMF model. Methods are similar to the UML model, first create a new EMF item (File> New> Project ...> Eclipse Modeling Framework> EMF Project), the project name com.ibm.example.forum (this is the foundation of the plugin name, So we follow the naming specification of the Eclipse plugin). Select Load from an XML Schema on the next page, and then click Next. Find the XSD file in the file system and load it, and then the model name in Generator will automatically populate. On the last page, click the check box next to the package, and then click Finish. This creates an EMF model, called Forum.Genmodel. You can learn from the generated EMF model section, and how to use it.

Creating an EMF model with annotated Java code If you define an EMF model through the Java code, we can use Interface to list the properties of each class, as well as the relationship between classes. This is not enough, unable to define all the information we want, so EMF uses a special JavaDoc tag. Each attribute or class, if it is part of the EMF model, you must include a @Model tag in its Javadoc, or a list of additional properties. For example, if you want to construct an object model as shown above, we look like a list 2 as a definition of the Forum.

Listing 2. Forum.java with comments

Package com.ibm.example.forum;

Import java.util.list;

/ **

* @Model

* /

Public interface forum {

/ **

* @Model type = "Topic" containment = "true"

* /

List gettopics ();

/ **

* @Model type = "member" containment = "true"

* /

List getmembers ();

/ **

* @Model

* /

String getdescription ();

}

Listing 2 declares an object called Forum, which has a string type description information and two children, one is a list of Topic, and one is a list of MEMBER. Both children are included within Forum.

For simple properties, such as describing information, @ model tags are sufficient, but for List, you also need to specify the type. The contament property is optional, but if an object is included, it is serialized with its container. In order to simplify the process of serialization, we must ensure that all objects are directly or indirectly included in Forum. Other useful optional properties are as follows:

Opposite (for bidirectional properties). DEFAULT (the default value of the property). Transient (This property cannot be serialized). To get a list of properties, please refer to the EMF User's Guide in the reference.

The only thing that needs to be careful is the type. It is defined as a Class instead of Interface in other model classes! In order to clarify this, Listing 3 shows how the TopiccateGory enumeration type is implemented.

Listing 3. Enumeration Type Topiccategorygory.java

Package com.ibm.example.forum;

/ **

* @Model

* /

Public class topiccategory {

/ **

* @Model Name = "Announcement"

* /

Public static final int Announcement = 0;

/ **

* @Model Name = "Guestbook"

* /

Public static final int guest_book = 1;

/ **

* @Model Name = "Discussion"

* /

Public static final int distribussion = 2;

}

Finally, generate the three interfaces shown below, the model is completed:

Interface Method Model Tag MEMBERLIST GETPOSTS () TYPE = "POST" Opposite = "Author" list gettopicscreated () type = "topic" Opposite = "creat" string getname () Topiclist getPosts () TyPICList getPosts () type = "post" Opposite = "author" Member getCreator () Opposite = "Topicscreated" string gettitle () Topiccategory getcategory () postmember getAuthoropposit = "posts" Topic gettopic () Opposite = "posts" string getcomment ()

When the model definition is complete, the EMF model (File> New> Other> Eclipse Modeling Framework> EMF Models) can be generated. Set the parent directory to Com.ibm.example.forum/src/model ,file name set to Forum.genmodel. On the next page, select Load from Annotated Java, then select the check box next to the package "forum". Then click Finish. This creates an EMF model called Forum.genmodel.

Using the generated EMF model Now there is a generated EMF model forum.genmodel in your workspace. This model contains all the information you enter. Open this model with the default editor (see Figure 3), open the Properties view, then check the properties of each node in the model tree. All attributes previously entered can be customized, but there are also some properties for custom code generation. To verify this, let's try to modify the properties such as "Copyright Text" or "Generate Schema" to see what will happen. Figure 3. Open the generated EMF model in the default editor

If you modify the model description (UML, XSD, with annotation java), you can also use the right-click the model in Package Explorer, then select Reload, so you can reload the model. This achieves synchronization between models generated with EMF and model descriptions. After reloading, you will change the properties you modified in the generated model.

Generate Java code

If you are satisfied with the model description, or if you just want to see what all this mean, then you can generate a code. Right-click on the root node and select one of the generation options: Model, Edit, or Editor Code. Generate Model will create Java implementation code for this EMF model in the current project. It will contain the following:

com.ibm.example.forum - Create the interface and factory of the Java class. Com.ibm.example.forum.Impl - the specific implementation of the interface defined in com.ibm.example.forum. com.ibm.example.forum.util - AdapterFactory.

Generate Editor Code will create a com.ibm.example.forum.edit project. It includes only a package, com.ibm.example.forum.provider, is used to control the way each model object appears in the editor. Generate Editor Code will create a plug-in editor example in the com.ibm.example.forum.Editor project, which contains com.ibm.example.forum.presentation. These classes provide a series of simple JFACE editors that interact with your model.

In order to test the generated plugin, enter Run> Run ...> Run Time Workbench> New. Enter a descriptive name, then in the Plug-INS tab, select Launch With All Workspace and Enabled External Plug-Ins. Under the Common page, click Display In Favorites Menu> Run and Launch in Background. Finally save the settings and run.

A new Eclipse workbench will appear, you can verify that your plugin is available in Help> About Eclipse Platform> Plug-in Details, as shown in Figure 4.

Figure 4. For plugin details

In order to test the generated plugin, you can create a new Simple project, named "forum demo", then enter New> Other ...> Example Emf Model Creation Wizards> Forum Model. Take a name called Sample.forum for the file, then select Forum as Model Object. At this time, a window will open, you can add new model elements to the roots. These include several views: Selection, Parent, List, Tree, Table, and Treetable. All of these views displays the same data and keep synchronization with the Outline view. Although all views displays New Sibling / New Child in the right-click menu option, I found that some views cannot respond correctly when adding a brother node or child node. If you also encounter this, you can use a TableTree view or create a new node in the Outline view. Figure 5 shows the generated plugin editor. Figure 5. Generated plugin editor

Customized code generated code is very good, but this is just the starting point of the real application. In order to meet our needs, we must adjust and customize them. We can change the implementation of the generated model class, or you can extend and customize the editor. Fortunately, I didn't let us down, we can do any customization according to your own ideas, and you will not lose these content when you regenerate the code. All of the work we need to do is to delete the @generated javadoc tag, EMF's JMERGE will guarantee these methods, attributes, or classes not being disturbed.

To focus on what modifications you can do for the code, let us look at a simple example. In the Table view of the generated editor, both fields show the same value. This is not completely useless. To improve, we can modify the second field, let it display the author when selecting a Topic, then add the third field, give the number of posts in the Topic.

The first step is added to the Table view additional fields. This step is implemented in the com.ibm.example.forum.editor project, namely the CreatePages () method in the CreatePages () method. ProM.Presentation.forumEditor. Remove the @Generated tag so that we can save our modifications and locate the location where the table browsing window is located. This code is modified according to the content of the list 4.

Listing 4. Modified CreatePages ()

TableColumn SelfColumn = New TableColumn (Table, Swt.none);

Layout.AddColumndata (New ColumnWeightData (2, 100, true);

SelfColumn.Settext ("Author");

SelfColumn.setResizable (TRUE);

TableColumn Numbercolumn = New TableColumn (Table, SWT.NON);

Layout.AddColumndata (New ColumnWeightData (4, 100, True);

Numbercolumn.Settext ("Number of Posts");

Numbercolumn.setResizable (TRUE);

TableViewer.SetColumnProperties (new string [] {"a", "b", "c"});

This adds an additional field, but now all three fields display the same data. In order to customize data in each field, we need to provide some ITABLETEMLABELPROVIDER implementation. Open com.ibm.example.forum.provider.topicItemProvider, add ITABLETEMLABELPROVIDER in the implementation list. We need to add two methods, getColumnText (Object, int), and getColumnImage (Object, int), as shown in Listing 5. Listing 5. Join TopicItemProvider

Public String getColumnText (Object Obj, int index) {

IF (INDEX == 0) {

Return GetText (OBJ);

}

ELSE IF (index == 1) {

Return ((Topic) Obj) .Getcreator (). getnickname ();

} else if (index == 2) {

Return " ((Topic) Obj) .Getposts (). size ();

}

Return "unknown";

}

Public Object getColumnImnImage (Object obj, int index) {

Return GetImage (OBJ);

}

Finally, we need to register this provider. The implementation method is to edit the constructor of com.ibm.example.forum.provider.ForumItemProvideradApterFactory, add ITABLETEMLABELPROVIDER to the supported type, as shown in Listing 6.

Listing 6. ForumItemProviderFactory constructor

Public forumItemProvideRadapterFactory () {

SupportedTypes.Add (ItableItemLabelProvider.class);

SupportedTypes.Add (istructuredItemContentProvider.class);

SupportedTypes.Add (ItreeItemContentProvider.class);

SupportedTypes.Add (IIITEMPROPERTYSOURCE.CLASS);

SupportedTypes.Add (IEditingDomainItemProvider.class);

SupportTypes.Add (IIITEMLabelProvider.class);

}

Now let's run this plugin, open the table view, you can see Figure 6. Note that the ITABLETEMLabelProvider element that is not implemented will display the same text in all fields.

Figure 6. Modified Table Editor

The model code generated in Java manipulating the model seems to have added some useful things in the Java code. The system also provides a flexible custom reflection API that is useful for tools. You may notice that this is EGET () and ESET (). In most cases, we don't need to care about it, so we still look at what we are interested in: How to create, save, and load the model. Let us start from the beginning: load the EMF model.

Listing 7. Loading forum

// register the xmi resource factory for the .forummodel extension

Resource.Factory.registry reg = resource.factory.registry.instance;

Map m = reg.GETEXTENSIONTOFACTORP ();

M.PUT ("Forummodel", New XmiResourceFactoryImpl ());

ResourceSet RESSET = New ResourceSetImpl ();

Resource Res = Resset.getResource (Uri.createuri ("Model / forum.forummodel"), TRUE);

Forum forum = (forum) res.getContents (). Get (0);

Listing 7 shows how to associate an extension "Forummodel" that complies with XMI format, then use EMF's ResourceSet and load the Forum model. We know that Forum is the only root element, so you can imagine, res. GetContents (). Get (0) will return one and there is only one forum object. If this is not this, we can also remove an Iterator from getContents (). Iterator (), then check each element.

We can also change a way to create a new Forum, then use the program to assemble, as shown in Listing 8.

Listing 8. Initializing Forum

// Initialize Model and Dependencies

ForumpackageImpl.init ();

// Retrieve The Default Forum Factory Singleton

FORUMFACTORY FACTORY = forumfactory.einstance;

Forum forum = factory.createforum ();

Forum.SetDescription ("Programmatic Forum Example);

Member adminmember = factory.createmember ();

AdminMember.setnickname ("administrator");

Forum.getMembers (). add (adminmember);

Topic Noticetopic = Factory.createtopic ();

NOTICETOPIC.SETTILE ("Notices");

NOTICETOPIC.SETCATEGORY (Topiccategory.Announcement_literal);

NOTICETOPIC.SETCREATOR (AdminMember);

Forum.gettopic (). Add (noticetopic);

In this example, we first initialize the package, then create the ForumFactory, use it to generate all the child objects. After the creation, you can access these objects like a standard JavaBean. However, since we declare the Creator / TopicsCreated relationship between TOPIC and MeMeber as a two-way, when we call NOTICETOPIC.SETCREATOR (AdminMember), you include Noticetopic in the TopicsCreated list of AdminMember.

Once we created and manipulated the EMF model, it is easy to save it as our selected format (see Listing 9).

Listing 9. Save forum

Uri fileuri = uri.createfileuri ("model / forum.ecore");

Resource resource = new xmiResourceFactoryImpl (). Createresource (fileuri); resource.getContents (). Add (forum);

Try {

Resource.save (Collections.empty_Map);

} catch (ioexception e) {

E.PrintStackTrace ();

}

In this example, we provide Uri.CreateFileuri () to provide the desired file name and target format. This example is because it is saved as XMI, so XMIResourceFactoryImpl is used. Once created, all model objects are as long as we wish. In this example, every object other than Forum is included in another class, so we only need to add this command to the ROOT containing all children. If some objects do not contain a relationship, they must also be explicitly added through Resource.getContents (). Add (). Otherwise, it will appear when you call resource.save ().

Conclusion Eclipse Modeling Framework provides a tool for model-driven development. It contains elements that focus your development in the model rather than implementation details. Its main focus is: support customization, notification, reference integrity and other basic characteristics when generating models; generate customizable model editors; default serialization. As shown in example, the process of generating is just simple and straightforward, and all custom code supports customization. A separate tool such as serialization or graphics editor can also be used alone, but all components can be used to play a complete effect. EMF has been applied in many successful projects, which is booming.

Reference

All documents, source code, and up-to-date buildings are included on the EMF Project home page. Download the Java code used in this article with a comment. Download the UML model used herein. Download the Forum.xsd file. IBM Red Books "Eclipse Development Using The Graphical EDITING FRAMEWORK AND THE Eclipse Modeling Framework" has more detailed examples, and more of the more custom features. To create a UML model compatible with EMF, try Omondo's popular UML Eclipse Plug-in. To support XML Schema, you need one XSD Toolkit that is the same as the EMF plugin version. To deeply study XML Schema, you can start from the SCHEMA page of W3C or more detailed "XML Schema Primer". To find more EMF design decisions, you can take a look at the OMG Meta-Object Facility specification. If you have encountered any questions, try the EMF newsgroup. If you have never used Eclipse newsgroups before, please read the use of rules and password applications. On the Open Source Special Zone of DeveloperWorks, you can find more articles written for Eclipse users. You can also see the latest Eclipse technology download on AlphaWorks. On the open source area of ​​Developer Bookstore, you can find hundreds of books related to open source topics, where there are several about Eclipse.

转载请注明原文地址:https://www.9cbs.com/read-94085.html

New Post(0)