Home

openArchitectureWare User Guide

image

Contents

1. A UIContentNode is a meta class used by xtext An UIContentNode represents an element visualized in eclipse Here is the declaration of UIContentNode pseudo code package tree eclass UIContentNode UIContentNode parent UIContentNode children String label String image emf EObject context A content node can have children and or a parent the tree structure is not used for find references The label is used for the label in eclipse and the image points to an image relative to the icons folder in the editor project The icon instances are automatically cached and managed The context points to the actual model element This is used to get the file line and offset of the declaration If you don t fill it you cannot click on the item in order to get to it 7 7 2 2 Go to Declaration This action can be invoked via F3 as well as by holding CTRL hovering over an identifier and left click the mouse The default implementation goes to the declaration of a crossreference You can implement or overwrite this action for all grammar elements emf EObject findDeclaration String identifier emf EObject grammarElement emf EObject modelElement Have a look at the generated extensions to see how it works oAW Version 4 2 122 Xtext Reference from oAW 4 2 7 7 3 Outline View The outline view is constructed using a tree of UIContentNode see above Each time the outline view i
2. package abstract boolean Kalal subPackag amp leugenp ad age visibility String r Figure 14 3 Class Types Package oAW Version 4 2 Classic Reference MbdelElement from org openarchgectureware meta uml documentation String lt lt library gt gt Namespace from org openarchrectureware core meta core lt lt incomplete gt gt Class namespace abstract boolean leafboolean visibility String lt lt incomplete gt gt Component Subsystem namespace component subsystem visibility String abstract boolean component 0 1 Figure 14 4 Components em e e Operations And Attributes BehavioredEkment MbdelElement discriminator lt lt incomplete gt gt Operation namespace from org openarchitectureware meta uml lt lt incomplete gt gt visibility String ownerScope String multiplicityMin int 1 multiplicityMax int 1 readOnly boolean fal se Type LX operation N operation thrower attribute lt lt incomplete gt gt Class namespace abstract boolean exception leatboolean visibility String Figure 14 5 Operations and Attributes from org openarchrectureware meta um from org openarchitectureware meta uml documentation String A oAW Version 4 2 158 Classic
3. The root element is named workflow then there are some property declarations followed by the declaration of two components Here is a tree representation of the resulting Java object graph obj Workflow obj oaw emf XmiReader model string home user model xmi obj oaw xpand2 Generator obj Outlet path string home user target Figure 5 1 Java Object Graph The configuration language expresses four different concepts 5 3 1 Properties Borrowing from Apache Ant we use the concept of properties Properties can be declared anywhere in a workflow file They will be available after declaration We have two different kinds of properties 1 simple properties 2 property files Here is an example lt workflow gt lt property name baseDir value gt lt property file S baseDir my properties gt lt component class my Comp srcDir baseDir modelName model pathToModel S pathToModel gt lt workflow gt First there is a simple property baseDir with the value defined This property can be used in any attributes in the workflow file The second property statement imports a property file Property files use the well known Java properties file syntax There is one feature we added You can use previously declared properties inside the properties file Example model myModel oAW Version 4 2 57 Workflow Reference path
4. This template contains only an empty definition for Model elements The namespace of the Model metaclass must be known for the generator so we import the corresponding package Otherwise we would have to fully qualify Model As you could expect this template does not really do anything yet At this time your project structure should look like this Package Explorer X Hierarchy Navigator src 8 oaw4 demo classic uml meta log4j properties E metamappings xml D workflow oaw workflow properties lt model lt HS magicdraw mdi1 B UML_Standard_Profile xml B AuthorBookExampleMD11 mdzip templates D Root xpt HA JRE System Library jre1 5 0_07 X S Plug in Dependencies L META INF oAW Version 4 2 172 Classic UML Tutorial 15 11 Execute the workflow We have not defined anything useful in our template yet However we now execute the workflow to prove that everything is right configured Execute the workflow by selecting workflow oaw and select Run As gt oAW Workflow from the context menu The output should be like this 0 ON a a a a a a a a a a E E a 0 NFO openArchitectureWare v4 c 2005 2006 openarchitectureware org and contributors 0 NEO SSR Se ee eee 0 NFO running workflow C dev ide workspace oaw v4 projects oaw4 demo classic uml src workflow oaw 0 NFO 540 NFO Starting workflow org openarchitectureware workflow oawclassic classicstart oaw 540 NFO
5. lt component gt In the example there are two outlets configured The first one has no name and is therefore handled as the default outlet Default outlets are triggered by omitting an outlet name FILE test note txt this goes to the default outlet ENDF ILE The configured base path is main src gen so the file from above would go to main src gen test note txt The second outlet has a name TO_SRC specified Additionally the flag overwrite is set to false defaults to true The following Xpand fragment FILE test note txt TO_SRC this goes to the TO_SRC outlet ENDF ILE would cause the generator to write the contents to main src test note txt if the file does not already exist the overwrite flag Another option called append defaults to false causes the generator to append the generated text to an existing file If overwrite is set to false this flag has no effect oAW Version 4 2 97 Xtend Xpand Check Reference 6 5 5 5 Beautifier Beautifying the generated code is a good idea It s very important that generated code look good because developers should be able to understand it On the other hand template files should look good too It is thus best practice to write nice looking template files and not to care how the generated code looks and then you run a beautifier over the generated code to fix that problem Of course if a beautifier is
6. zC Zar 2 6 platform resourcejoaw4 demo emf uml2 generator srejtest profile uml E lt Profile gt KN lt Element Import gt Class lt Stereotype gt test T 5 lt Extension gt Class_test pathmap UIML_METAMODELS UML metamodel uml pathmap UML PROFILES Ecore profile url pathmap TUAL PROFILES Standard profile uml E E Figure 9 6 Loading the Profile Now to make the following stuff work you first have to select the profile and select the Profile gt Define operation from the UML2 Editor menu This creates all kinds of additional model elements about which you shouldn t care for the moment Now finally you can select your cars package the one from the example model and select Package gt Apply Profile from the UML2 Editor menu Select your test profile to be applied For the purpose of this example you should now apply the test stereotype to the PersonCar class Select the class and the select Element gt Apply Stereotype from the UML2 Editor menu This should result in the following model oAW Version 4 2 132 UML2 Example example profiled url X o platform resource oaw4 demo emf uml2 generator srcfexample profiled uml E lt Model gt B lt Package gt cars lt Class gt PersonCar lt Generalization gt Car H lt Class gt Car lt Operation gt drive eN lt Profile Application gt test fi UML platform fr
7. oAW Version 4 2 109 Chapter 7 Xtext Reference from oAW 4 2 7 1 Introduction Does this sound familiar to you Oh I need to rename this misspelled property within our domainmodel Ok so let s startup this big UML monster and by the way let s get a new cup of coffee Cool it has been started up already Grabbing the mouse clicking through the different diagrams and graph visualizations Ahhh there is the name of the property right down there in the properties view Let s change it export it to XMI drinking coffee starting the oAW generator in a jiffy Oh it s not allowed for the property to be named that way a constraint says that properties names Should start with a lower case letter Ok let s change that and again reexport Some moments later everything seems to works tests are green Ok let s check it in Oh someoneelse has also modified the model Aaarrrgggh Think of this Want to change a properties name Ok open the respective text file rename the properties name and save it The editor complains about a violated constraint Ok fix the issue save again and generate Check the changes into SVN CVS Oh there is a conflict ok let s simply merge it using Diff And now Let s have a cup of coffee Xtext is a textual DSL development framework Providing the ability to describe your DSL using a simple EBNF notation Xtext will create a parser a metamodel and a specific Eclipse texteditor
8. Wie esses jy eCheck Eann resource not found tprojectName resourceName check ok oAW Version 4 2 147 Recipe Framework When implementing the evaluator you can basically do the same things as in the evaluate operation in normal checks However in order to set the ok or fail why flags you have to call the respective operations on the check passed as the parameter to the operation 12 2 3 4 Making checks available to the Eclipse plugin In order to allow the Eclipse runtime to execute your checks it has to find the respective classes when deserializing the recipe file This is a bit tricky in Eclipse since each plugin has its own classloader So assume you want to define your own checks and want to use them in Eclipse what you have to do is implement your own plugin that extends a given extension point in the Recipe Browser plugin The following XML is the plugin descriptor of the org openarchitectureware recipe eclipseChecks plugin EclipseChecksPlugin a sample plugin that comes with the recipe framework and provides a number of Eclipse capable checks lt xml version 1 0 encoding UTF 8 gt lt eclipse version 3 0 gt lt plugin id org openarchitectureware recipe eclipseChecks name plugin_name version 4 0 0 provider name provider_name class org openarchitectureware recipe eclipseChecks plugin EclipseChecksPlugin gt Here we now define the jar file that
9. oAW Version 4 2 119 Xtext Reference from oAW 4 2 Location Description src dsIname xtxt he grammar file containing the grammar rules describing your DSL src generate oaw he workflow file for the Xtext generator src generator properties Properties passed to the Xtext generator src base package name Checks chk The Check file used by the parser and within the editor Used to add semantic constraints to your language src gen base package name he generated Check file contains checks automatically derived from the GenChecks chk grammar src base package name he Extension file is used imported by all aother extensions and Extensions ext heck files It reexports the extensions from GenExtensions ext contained in src gen You can specify use more conrete parameter ypes or overwrite use the same signature the extensions from GenExtensions ext here src gen base package name generated extensions reexported by Extensions ext GenExtensions ext src base package name Linking ext Used by Linker ext from src gen base package name parser Linker ext Default linking semantic is generated in GenLinking ext sre gen and can be overwritten here src gen base package name ontains the default linking semantic for each cross reference GenLinking ext Example Void link_featureName my MetaType this let ents this allElements typeSelect my ReferredType this setFeatureName ents select el
10. In Java only the dynamic type of the this element is considered for paramters the static type is used this is called single dispatch Here is a Java example class MyClass boolean equals Object o if o instanceof MyClass return equals MyClass o0 return super equals o boolean equals MyType mt implementation The method equals Object o must not been overwritten if Java would support multiple dispatch 6 3 10 Casting The expression language is statically type checked Allthough there are many concepts that help the programmer to have really good static type information sometimes one knows more about the real type than the system To explicitely give the system such an information casts are available Casts are 100 static so you don t need them if you never statically typecheck your expressions The syntax for casts is very Java like oAW Version 4 2 76 Xtend Xpand Check Reference String unTypedList get 0 toUpperCase 6 4 Xtend Like the expressions sub language that summarizes the syntax of expressions for all the other textual languages delivered with the openArchitectureWare framework there is another commonly used language called Xtend This language provides the possibility to define rich libraries of independent operations and no invasive metamodel extensions based on either Java methods or oAW expressions Those libraries can be referen
11. Java Eclipse SDK Users user Desktop temp ull Irt HS O Q BH G 3 GV Ole F Oe ero E Slama Raa E nena ee New Project Select a wizard Wizards t 1 t 1 1 1 f 1 L L gt amp General gt GCVS i gt Eclipse Modeling Framework gt EB gt J2EE gt Java l gt openArchitectureWare t gt Plug in Development gt Z web Y Xtext DSL Wizards l mydsl Project gt Examples t 1 f L fo B Outline X An outline is not available m v Finish Location T Figure 2 21 New DSL project ald wey The wizard creates an Eclipse plug in project containing the needed dependencies to the dsl bundle the generator bundle and the oAW bundles It also generates a workflow which invokes the workflow from our generator as well as an empty model file Let s fill the model file with some information oAW Version 4 2 44 Xtext Tutorial e088 Java mydslproject src model dsi Eclipse SDK Users user Desktop temp li Eelt 0 Q gee B OGVI O f F OOo E ava Z Package Expl 83 _ Js Hierarchy at B Outline X lm ha PNI ga V datatypes ga yY statues ering e Y amp mydslproject datatype Integer Z String Y src Integer E model ds da Y Person D yas g s name Y sre gen entity Person L ome Y TH default package String name address
12. metamodel ecore The first one will return the type object not java lang Object but oaw s object At this point the type Object best fits the request so it will act as the desired type The second metamodel returns an oaw type called oaw eclipse emf ecore EObject The typesystem will check if the returned type is a specialization of the current best fit type object It is because it extends object Every meta type has to extend object At this time the typesystem assumes oaw eclipse emf ecore EObject to be the desired type The third metamodel will return metamodel MyType which is the desired type But unfortunately it doesn t extend org eclipse emf ecore EObject as it has nothing to do with those Java types Instead it extends emf EObject which extends object We need to swap the configuration of the two metamodels to get the desired type lt component class oaw xpand2 Generator gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelFile value my java package metamodel ecore gt lt metaModel gt lt metaModel class oaw type impl java JavaMetaModel gt lt component gt 6 3 Expressions The oAW expression sub language is a syntactical mixture of Java and OCL This documentation provides a detailed description of each available expression But let s start with some simple examples Accessing a property myModelElement name oAW V
13. openArchitectureWare User Guide Version 4 2 openArchitectureWare openArchitectureW are User Guide 2007 09 15 Copyright 2004 2007 Sven Efftinge Peter Friese Arno Haase Clemens Kadura Bernd Kolb Dieter Moroff Karsten Thoms Markus V lter Copies of this document may be made for your own use and for distribution to others provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice whether distributed in print or electronically Table of Contents I gt Getting Started reee ate re EEA EEE E aad tec cata seas vad cave EEE saeco asia waaay vai coe EEEE RAKES 1 t EMF Tutorial TTT 2 1 1 Installing the pre built STS TT 2 1 2 Tutorial OVErview niaaa Bataan cae ave deel ates EE ae saben taut Heke dette 2 1 3 Defining an EMF metamodel 4 icc cece raS a Tab cae Zak ZNR TT concent dade vas RST aT leaded RTT 2 1 3 1 Creating an EME project oreina i seatevnd Rela EE AE EEE AE E ES 3 1 322 Defining the Gnetamodel serieou cawdseudssvess cose oe a Aae en eea A ERKEN AP eiea 3 14 Generating the EMP ee 7 1 5 Setting up the generator project acte eee eee eeeeeeeeeeeeeeeseeeeeeeeeeeeeeeseseeeeeeeeeeeeeeeeeeeeeneee 10 1 6 Defining an Example Data Node ssssss eee eeeecececececececececececeeecececeeeeeceeeeeeeeeeeeeeeeeees 12 1 7 Using Dynamic EME ssesvevesccesey sites va sutessny er rearea eee a eea A EEEa E tenes ete aa 14 1 8 Generating Code From the
14. parameter 5 3 2 3 Controlling the Workflow There is an implicit way of controlling the workflow if there are errors reported from any of the checkConfiguration operations of any workflow component the workflow will not start running There is also an explicit way of terminating the execution of the workflow if any invoke operation throws a WorkflowInterruptedExcept ion a runtime exception the workflow will terminate immediately 5 3 2 3 1 Workflow AO It is sometimes necessary to enhance existing workflow component declarations with additional properties This is exemplified in the Template AOP example To implement such an Advice Component you have to extend the AbstractW orkflowAdvice class You have to implement all the necessary getters and setters for the properties you want to be able to specify for that advice also you have to implement the weave Operation In this operation which takes the advised component as a parameter you have to set the advised parameters public class GeneratorAdvice extends AbstractWorkflowAdvice private String advices public String getAdvices return advices public void setAdvices String advices this advices advices Override public void weave WorkflowComponent c Generator gen Generator c oAW Version 4 2 62 Workflow Reference gen setAdvices advices In the workflow file things are straight forward You have to spe
15. recipe core build extend your own class that has to be called E oAW recipe plugin update example BC impl C1Implementation Y Z oAW recipe simpleChecks build 5 oAW umMetamodel 1 generate PE AA unlinked 9 ba da we gt 4 resource not found scmHelloWorld src example BC 1 fimpl C1 Implementation java helloworld recipes scmHelloWorld Figure 12 1 Recipe Example 1 The generator creates a so called recipes file How this file is created will be shown below The recipe file contains the checks that need to be executed on the code base In the context menu of a recipes file you ll find an item called Open Recipe File that opens the checks in the respective browser Note that the file has to have a recipes extension otherwise the plugin will not open the file 2 Here you can see failed checks The messages tell you that you have to write the implementation class and the second item you ll have to make sure it extends from the generated base class 3 Here you can see a check that worked well oAW Version 4 2 142 Recipe Framework 4 Each check contains a number of parameters the table shows the parameters of the selected check For example the name of the class to be generated the one from which you have to inherit etc This is basically for your information If you double click on a certain row the value of the parameter is copied to the clipboard and you can past it to whe
16. Eclipse nosie neneiia iaoe iae iiare iri ai 125 8 3 1 Profiles in Eclipse ericneiicineiinniireiii iia i a i ia ia i 125 8 4 Runtime Configuration sese 125 BAT WOK Te 125 9 UMES Example ss anne i a a a a a Av a a a a Ae 127 OTs Setting p Eclipse T 127 R Setting p the projecten ieia E cee HRS EEA ER EEES 127 Q Creating BIA 1 Model Tesiri veiniga aE T AE EEEE ETRE E eS 128 9 3 1 Modelling the Content sissien an e iiai VEE ANE Ea a V 129 G Code generation oio eiieeii e A EE N av eesti redder EEEREN E A ER E AEE wine 129 94 Ts Definin the template S reinn aen e aeeie n ena ea LE E eTii EEE ASEN 129 0 4 2 Defining the Workflow srren iare enei Ma eee eee 130 S Profile Support Sd ve ee eee ee ieee eee ieee eA ee 131 05 1 Detining a Profile ys 2 5 saves ots ie eae ioe ane A E enw selena R aes me soeti tee 131 0 5 2 Applying the Proteo wes seissc sides kak ete econ ek aut EEE AEE aA EEE beet ead EEEE 131 9 5 3 Generating Code avis ate ses essen ave see ER ots EERE E gongs Ea etd te EEE E N 133 10 GMEDZ Adapter acelin teas jens de subtle ee i e a Mad E AE E O penal Staub E E e ia aces 135 TOD Introduction i cate skeet cs o oe e eei e eE aE IEE EO CE E NEE EAE EA AA 135 10 2 Installation TTT 135 10 3 Settms Up Eclipse egotie et ree eae ee eG eae 135 10 4 Settna Up GMB sets eeraa e ia ae a i ea a ate e ai aaae ataia iaaa o iaia eaaa ale 135 10 4 1 Setting validation Options ss aS aea Soc 25Y ARZ Tea 7 Yea 7 YZS aX ae e e CRS
17. Here is an example MyModel imports Import typest Type Imports import name ID Type Overwrite the allElements extension in Extensions ext to something like this extension mydsl GenExtensions reexport extension org openarchitectureware xtext registry Reg allElements emf EObject this wholeModel union MyModel eRootContainer imports for each import get RootNode i get the root from the registry wholeModel get the whole model as a list i wholeModel emf EObject this eRootContainer union eRootContainer eAllContents As the allElements extension is used everywhere the imported model elements will automatically be available for code completion navigation checking etc oAW Version 4 2 124 Chapter 8 UML2 Adapter 8 1 Introduction The UML2Adapter for oAW is available since version 4 1 It is based upon Eclipse s UML2 2 0 framework and provides a type mapping from the UML 2 1 metamodel implementation to the oA W type system Hence one can access the whole UML2 metamodel from Check Xtend and Xpand Additionally and more important the adapter dynamically maps stereotypes applied to model elements to oAW types and TaggedValues to oAW properties You don t have to implement additional Java classes anymore Just export your models and applied profiles That s all 8 2 Installation First you need to install the UML2 feature fr
18. Migrating the grammar The grammar language has changed a bit 1 The Abstract keyword has been removed All you need to do is remove it from your grammar 2 The boolean assignment operator prior it was conflicted with the optional cardinality So we changed it to 4 1 2 2 Migrating the core project Within the main project the Extensions ext and Check chk files have been added They replace the old Llangname Checks ch resp langname Extensions ext files You just have to copy and paste the content from the old files to the new ones start the generator once if you don t see the new files 4 1 2 3 Migrating the editor The editor project has some more changes 1 The Plugin class as well as the Editor class names start with a capital rename them if necessary 2 The method getPluginQ in the Editor class is public now 3 The content of the langname EditorExtensions ext has been separated into several files 4 The label and image extensions can be copy and pasted to EditorExtension ext 5 The content assist logic is contained in ContentAssist ext Although your old projects should work now it s recommended to read the updated Xtext reference documentation oAW Version 4 2 53 Part Il Reference Chapter 5 Workflow Reference 5 1 Introduction The oAW4 workflow engine is a declarative configurable generator engine It provides a simple XML based configuration language with w
19. Project cccecresce8 ocetsens ce ciran Enen aan EEEa E EE tio EEEa ENEE EnEn eq ceseauceeesebeacreaens ste 11 1 12 Project properties ee etenn eare Sees aree a A Ae rad teat A ede atone A 12 1 13 Cr ate a sample data model viossiyeeiehstidveg davtgdesstaspehaeadesuessbidbsbad stgvessk apebsd de suetstideeesd ntedesstispeoleatest 13 LI Sample data madel 5 aoaie taga ccocuntentwostadeck hevticotatl S294924 HRA rivers T RS94 2022 E Ea AE aaa 13 1 15 Add metamodel dependency cs ticesclteecacedtescocekeeecedhgstcosentayeosesteteecedbopededaertewseddapeotenberacceteneceedaenaceess 16 1 16 Sample data model is c c42reccisosstttecoctnhereotebieeehedeuradoctbesyeabenteadenetsfeeenbeutacenel Decastiieconsbisedeedausedenshsversia 17 1 17 What has happened Sofar s 015 cescdsonteevolsdidbebedatasdorsibapetaedtaruolsdsabebslitetdesth sayebinghaguolsdidbebed ana tdosshisects 23 2 1 Metasmodel as UML diagrams i cstetccescadee ce ieasttcaseld teed cceatbcosel bees sdadtteeselstacs eaa ai ei eiea 30 2 2 Create XteXt PLOJECUS sans esse een hs ae ede eden SO es eles ease ede A E i i i 30 2 3 Xtext wizard dialog ess estes oiii i e es soos eee E i E i E A i a ei 31 24 Package explorer munerne e ei i E A EE A ee e dete AEE AEE EE E EAE 32 2 3 Createnew Ecore model sorce ie iii i iE E E E i a A A E 32 2 6 Starting th Xtext Semerator osceni iniii iiaii iieii iiaei i iien iii 34 2 7 Starting a runtime Workbench cesedi iii i i i 34 2 8 Run debu
20. Reference 14 2 2 Statechart Support Behavior topState stateMachine guard String transition Figure 14 6 State Charts MbdelElement M from org openarchitectureware meta um gt lt documertation String Event Transition targetVertex lt lt incomplete gt gt State Vertex parameter String guard String inTransition trigger subVertex A sourceVertex outTransition SignalEvent signal String internalTransition lt lt incomplete gt gt Action g T aera em State entryAction 0 1 exitActionState exitAction y oA ponpon a aaie doAction 1 SimpleState A container espace ActionState dia E S Figure 14 7 States Main oAW Version 4 2 159 Classic Reference States Andere Figure 14 8 State Vertex Subtypes Figure 14 9 Actions oAW Version 4 2 160 Classic Reference 14 2 3 Activity Diagram Support Behavior from org openarchiectureware meta uml StateMachine from org openarchitecturew are meta umi state Activity from org openarchkecturew are meta uml2 activ ty Figure 14 10 Activity Nodes BasicAcivities ActivityParameterNode ActivityFinallN ode InitialN ode Parameter from org openarchiectureware meta umi classifier par
21. String param JAVA my Type staticMethod java lang String The signature is the same as for any other extension The implementation is redirected to a public static method in a Java class It s syntax is JAVA fully qualified Type staticMethod my ParamTypel my ParamType2 EHD Note that you cannot use any imported namespaces You have to specify the type its method and the parameter types in a fully qualified way Example If you have defined the following Java extension Void dumeisetring s JAVA my Helper dump java lang String and you have the following Java class package my oAW Version 4 2 80 Xtend Xpand Check Reference public class Helper public final static void dump String aString System out println aString the expressions dump Hello world Hello World dump both result are invoking the Java method void dump String aString 6 4 7 Create Extensions Model Transformation Since Version 4 1 the Xtend language supports additional support for model transformation The new concept is called create extension and is explained a bit more comprehensive as usual Elements contained in a model are usually referenced multiple times Consider the following model structure 7 Ci EZ A package P contains two classes C1 and C2 C1 contains a reference R of type C2 P references C2 We could write the followi
22. Y H Address java Integer age Y Address v G Address Address address street city e Kona entity Address la a zip String street getCity a String zip Z getStreet String city getZip setCity String Z setStreet Strir setZip String Y B Person java Person B mydsiproject oaw SK address lt workf Low gt a age lt component file org example dsl generator oaw gt fe gwm lt modelFile value model dsl gt lt targetDir value src gen gt getAddress lt component gt Z getAge lt workflow gt getName setAddress A setAge Intege Z setName Strir gt BAJRE System Library JVM 1 5 0 M aaa gt mh rusrinDovenderces IS Problems arado ea B console saren O G X YB O gt Z META INF Reference Address ia build properties aS Dar o Writable insert 16 15 ajl ney Figure 2 22 Textual modelling Now we can run the workflow by right clicking it Choose Run As gt oAW Workflow oAW Version 4 2 45 Xtext Tutorial 6 SKa Java mydslproject src model dsl Eclipse SDK Users user Desktop temp PETTEE Q SHe 6 3 19G6 9710 as E S a B Outline X m datatypes Ee datatype String v perme datatype Integer S String Y src Integer B model ds da ig Y Person mydslproject New gt name age Ope
23. lt workflow gt lt property file workflow properties gt lt component id xmiParser oAW Version 4 2 14 EMF Tutorial class org openarchitectureware emf XmiReader gt lt modelFile value modelFile gt lt metaModelPackage value data DataPackage gt lt outputSlot value model gt lt firstElementOnly value true gt lt component gt lt workflow gt The workflow tries to load stuff from the classpath so for example the data DataPackage class is resolved from the classpath as is the model file specified in the properties modelFile example data This instantiates the example model and stores in in a workflow slot named model Note that in the metamodelPackage slot you have to specify the EMF package object here data DataPackage not the Java package which would be data here 1 8 2 Running the workflow Before you actually run the workflow make sure you have a log4j configuration in the classpath for example you can put the following 10g43j properties file directly into your source folder Set root logger level to DEBUG and its only appender to Al log4j rootLogger INFO Al Al is set to be a ConsoleAppender log4j appender Al org apache log4j ConsoleAppender log4j appender Al layout org apache log4 j PatternLayout o log4j appender A1 layout ConversionPattern 4r 5p dp mon Also please make sure your metamodel can be found on the classpath
24. outline view error marker support and folding as shown in the following screenshots oAW Version 4 2 35 Xtext Tutorial S r String Sentity Person String String name gt Person String lastName Address Address address Sentity Address L String street String zip String city Address Person String o L b E Probl d L et Pee R Figure 2 9 Code Completion datatype gt oA lt Undo Typing sentity Person Revert File String na String la Address ad Show In Open Declaration String st Cut String zi Copy String ci Paste Shift Right Shift Left Toggle Comment Z Problems 53 _ 0 errors O warning Add to Snippets Figure 2 10 Find References Action References In Workspace oAW Version 4 2 36 Xtext Tutorial datatype String 25 Outline 3 Sentity Person String gt String name y Person gt String lastName o name Address address lastName address Sentity Address L y Address gt String street street C String zip i gt String city ezp city 7 Problems Javadoc B Declaration lt x Reference String TINAY oH of String mydsiproject src model dsl line 4 String mydsiproject src model ds line 10 mydslproject src model dsl line 5 Figure 2 11 Find References result 15 datatype String entity Pe
25. see the Xpand documentation One specifies on which join points the contributed code should be executed by specifying something like a query on all available join points Such a query is called a point cut around pointcut expression A pointcut consists of a fully qualified name and a list of parameter declarations oAW Version 4 2 84 Xtend Xpand Check Reference 6 4 10 1 1 Extensions Name The extension name part of a point cut must match the fully qualified name of the join point s definition Such expressions are case sensitive The asterisk character is used to specify wildcards Some examples my Extension definition extensions with the specified name org oaw extensions prefixed with org oaw Operation extensions containing the word Operation in it all extensions WARNING BE CAREFUL WHEN USING THE WILCARD AS YOU WILL GET AN ENDLESS RECURSION IF YOU WEAVE AN EXTENSION WHICH IS CALLED INSIDE THE ADVICE 6 4 10 1 2 Parameter Types The parameters of the extensions we want to add our advice to can also be specified in the point cut The rule is that the type of the specified parameter must be the same or a super type of the corresponding parameter type the dynamic type at runtime of the definition to be called Additionally one can set the wildcard at the end of the parameter list to specify that there might be none or more parameters of any kind Som
26. xml gt The prSrcPaths property points to a comma separated list of directories The protected region resolver will scan these directories for files containing activated protected regions There are several file names which are excluded by default RCS SCCS CVS CVS adm RCSLOG cvslog tags TAGS make state nse_depinfo Sutin vel QS eS i T HY GiyN cere IT roel ello roe eelaal Wen Woe SoA S eLo SS T E ASYN If you don t want to exclude any of these you must set prDefaultExcludes to false oAW Version 4 2 98 Xtend Xpand Check Reference lt prDefaultExcludes value false gt If you want to add additional excludes you should use the prExcludes property lt prExcludes value xml hbm gt Note It s bad practice to mix generated and non generated code in one artifact Instead of using protected regions you should try to leverage the target language s extension features inheritance inclusion references etc wherever possible It is very rare that the use of protected regions is an appropriate solution 6 5 6 Example for AOP and Xpand This example shows how to use aspect oriented programming techniques in Xpand templates It is applicable to EMF based and Classic systems However we explain the idea based on the emfExample hence you should read that before 6 5 7 The Problem There are many circumstances when te
27. 18 Export Plug ins 1 Choose Deployable plug ins and fragments oAW Version 4 2 41 Xtext Tutorial e080 Export Select Export the selected plug ins and or fragments in a form suitable for deploying in A an Eclipse product Select an export destination type filter text gt amp General gt amp EB gt J2EE gt amp Java gt amp Mylyn Y amp Plug in Development Ge Deployable features B Eclipse product gt amp Team gt amp Web gt Web Services gt amp Other o C m Figure 2 19 Export Plug ins 2 Choose the directory where you ve installed Eclipse mark all three projects and click the Finish button oAW Version 4 2 42 Xtext Tutorial e08e Export Deployable plug ins and fragments Export the selected projects into a form suitable for deploying in an Eclipse product a Available Plug ins and Fragments M lt gt my ds 1 0 0 S 4 my dsl editor 1 0 0 Vv lt my dsl generator 1 0 0 3 out of 3 selected Destination Options JAR Signing Directory path to my eclipse e O Archive file N Browse ECE i Figure 2 20 Export Plug ins 3 When the export process has finished restart your workbench Now choose a different workspace Within the new workspace you can create a new mydsl project using the generated wizard oAW Version 4 2 43 Xtext Tutorial ANDO
28. 4 Poseidon 5 Rational Rose Unisys Plugin 1 3 2 MI 1 0 Rational Rose Unisys Plugin 1 3 2 MI 1 1 Rational Rose Unisys Plugin 1 3 4 1 3 6 XMI 1 1 Star UML Together DE argoum1 ArgoUMLAdapter largouml_xmi 12_all xml aris ARISAdapter faris_xmi1 1_all xml artisan ArtisanAdapter artisan xmi13_al1 xml ea l EAAdapter ea25_xmill_all xml ea41_xmil2_all xml ea5_xmill_all xml EA61UnisysXmil2Adapter ea6l1_unisys_xmil2_cls xml EA61Xmil2Adapter ea6l_xmil2_cls xml innovator InnovatorAdapter innovator_xmill_all xml magicdraw MagicDrawAdapter12 IMmagicdraw_xmil2_all xml Imagicdraw_MagicDrawAdapter21 IMmagicdraw_xmi21_all xml metamill MetamillAdapter metamill31_xmil2_all xml ter poseidonl6_xmil2_all xml pOSE1a0 poseidon PoseidonAda n G PoseidonAdapter poseidon20_xmil2_all xml poseidon PoseidonAdapter poseidon30_xmil2_all xml n G poseidon PoseidonAdapter poseidon31_xmil2_all xml on apter poseidon40_xmil2_all xml poseidon PoseidonAd poseidon PoseidonAdapter poseidon40_xmil2_all xml rose RoseAda rose_unisys132_xmil0_all xml rose RoseAda rose_unisys132_xmill_all xml rose RoseAda rose_unisys134_xmill_all xml staruml StarUMLAdapter staruml_xmill_all xml together TogetherAdapter together_xmill_all xml xde XdeAdapter xde2_xmill_all xml Package Prefix org openarchitectureware core frontends xmi toolsupport uml oAW Version 4 2 155 Classic Re
29. Adding a new check file For more information on checks please refer to the Check documentation Chapter 6 Xtend Xpand Check Reference oAW Version 4 2 138 Chapter 11 RSM RSA Adapter 11 1 Introduction The IBM Rational Software Architect Modeler RSA RSM is a uml modeling tool It s based on Eclipse and the Eclipse s UML 2 0 project The uml models stored in a special file format These model files have the file extension emx uml profiles are stored in files with the extension epx The files from version 6 0 of RSA RSM can be opened with a special API only With the introduction of version 7 0 the models and profiles can be opened directly with the UML2 2 0 framework Usually RSA RSM profiles are deployed in plugins the referenced to these profiles are written with a special URI called pathmap people working with Rational Rose might know this The RSA RSM adapter brings the functionality of the UML2 adapter written by Sven to RSA RSM The adapter for oAW is available since version 4 1 It is based upon Eclipse s UML2 2 0 framework and provides a type mapping from the UML 2 1 metamodel implementation to the oAW type system Hence one can access the whole UML2 metamodel from Check Xtend and Xpand Additionally and more important the adapter dynamically maps stereotypes stored in RSA RSM specific model files epx which are applied to model elements to oAW types and stereotype properties TaggedValues to oAW properties Yo
30. EMF Tutorial DataModel attribute name String name String type String reference EntityReference name String toMany boolean 1 3 1 Creating an EMF project Figure 1 1 Sample metamodel Create an EMF project as depicted below Select a wizard Create an empty Java project setting up the classpath to use EMF Wizards Class amp Interface g Java Project 3 Java Project from Existing Ant Buildfile 77 Plug in Project T L General L Connection Profiles D gt cys L amp Eclipse Modeling Framework i EMF Model Lei EMF Project ie gt EJB iH gt Example EMF Model Creation Wizards Cancel Figure 1 2 Create EMF project It is important that you create an EMF project not just a simple or a Java project Name it oaw4 demo emf datamodel 1 3 2 Defining the meta model Create a new source folder metamodel in that project Create a new Ecore model in that source folder named data ecore Use EPackage as the model object oAW Version 4 2 3 EMF Tutorial Select a wizard Create a new Ecore model Wizards gt CYS gt Eclipse Modeling Framework H E EJB J gt Example EMF Model Creation Wizards amp Data Graph Model amp f Ecore to Ecore Model a5 Ecore to XML Model iS XSD Model Saf XSD to Ecore Model I2EE H E Java L Java Emitter Templates HL opend rchitectureWare Cancel Figure 1 3 Create new Ec
31. Export gt Eclipse UML2 The exported files have to be in the root of the src folder in the metamodel project created above This is how the project looks like after this step assuming you d called your model entity um12 oAW Version 4 2 151 UML2Ecore Reference oaw4 demo util umlZecore architecturware cvs source Eley gt Et i 5 entity uml2 1 1 ASCII kkv 0 UML_Standard_Profile MagicDraw_Profile profile UML_Standard_Profile UML_Standard_Profile prof BA JRE System Library JRE 1 5 BA Plug in Dependencies E ZR gt META INF DHE H Figure 13 3 Project layout Before you can actually run the generator you have to make sure that your project has a plugin dependency to the uml2ecore plugin Double Click on the plugin s manifest file select the Dependencies tab and click add Select the org openarchitectureware uml2ecore plugin The result looks like this g Package Explorer 3 Navigator JUnit m oaw4 demo util uml2ecore So Q G B z Depen dencies EGR gt src L 7 kail gt entity mdzip Binary Required Plug ins i H entity uml2 1 1 ASCII kkv Specify the list of plug ins required for the operation of this plug in UML_Standard_Profile MagicDraw_Profile profile uml2 1 1 Sr org openarchitectureware util umiZecore iim b 61 UML_Standard_Profile UML_Standard_Profile profile uml2 whoaw 1 1 ASCII kkv H A JRE System Library JRE 1 5 E Plug in Dependencies z
32. How the parsers work in general As stated before the grammar is not only used as input for the parser generator but it is also used to compute a meta model for your DSL We will first talk about how an Xtext parser works in general before we look at how a meta model is beeing constructed The parsing of text is devided in two separate tasks the lexing and the parsing The lexer is responsible of creating a sequence of tokens from a character stream Such tokens are identifiers keywords whitespace comments operators etc Xtext comes with a set of built in lexer rules which can be extended or overwritten if necessary You have already seen some of them e g ID The parser get s the stream of tokens and creates a parse tree out of them The type rules from the example are essentially parser rules Now let s have a look at how the meta model is constructed 7 4 3 Type Rules We ve already seen how the Type Rules works in general The rule s name is used as the name of the meta type generated by Xtext 7 4 3 1 Assignment tokens Properties Each assignment token within an Xtext grammar is not only used to create a corresponding assignment action in the parser but also to compute the properties of the current meta type Properties can refer to the simple types such as String Boolean or Integer as well as to other complex meta types i e other rules It depends on the assignment operator and the type of the token on the right what t
33. R contained in C1 A start create C2 referenced from R I start create R2 contained in C2 1 start create C1 referenced from R1 OOPS C1 is already in creation and will not complete until the stack is reduced Deadlock The problem is that the cache caches the return value but C1 was not returned so far because it is still in construction The solution create extensions The syntax is as follows create Package toPackage EPackage x this classifiers addAll x eClassifiers toClass create Class toClass EClass x this attributes addAll x eReferences toReference create Reference toReference EReference x oAW Version 4 2 82 Xtend Xpand Check Reference this setType x eType toClass This is not only a shorter syntax but it also has the needed semantics The created model element will be added to the cache before evaluating the body The return value is always the reference to the created and maybe not completely initialized element 6 4 8 Calling Extensions From Java The previous section showed how to implement Extensions in Java This section shows how to call Extensions from Java setup XtendFacade f XtendFacade create my path MyExtensionFile use f call sayHello new Object World The called extension file looks like this sayHello String s ERETTE VP se eye This example uses only features of the BuiltinMetaModel in th
34. Rae ead VEe 135 oAW Version 4 2 vi openArchitectureW are User Guide 10 4 2 Setting template Options 2 0 0 0 eeeeeeeseseeecececececececececeeeaececeaeaeaececeaeaeaeaeaeeeeeaeeeas 136 10 4 3 Loading the extension model sese 137 IB RSM RSA Adapter orosei ei ai dy bek eas eaea a iee S ee nea Saa ESR 139 TIT Introduction ssion neinei iee akae EET ai EESE AOE R EESE Na Rii 139 11 22 Installation sosie ian aaiae a e rae a E E AA aaa E EAE NAE aie eee 139 11 3 Setting up IBM Rational Software Architect Modeller sss 139 11 3 1 Runtime Configuration desides eaten aa aE ieee aiden lentes 140 11 3 2 Workflow using profiles from plugins sees ee eee 140 11 3 3 Workflow using profiles from workspace projects esse ee ee ee eee 141 11 3 4 Puture enhance ments TTT 141 12 Recipe Framework if v2 sscaieicd aeea e e E ede ee E E oE a eeni ri TRE EEE 142 12 1 Introductory Example and Plugin sss sees sese ee ee ee ee ee ee eee 142 12 1 51 Installing the Plugin oore Ses eeei eather lien eet 143 12 1 2 Referencing the JAR Tiles reei deve seeg besos eaa e Eea a Ea eias 144 122 Exec tins Recipe Checks ebre stace Fos acea n one EEE Ees e Sees RESTE E rE EEE EERE 144 12 2 1 Running Checks within your workflow sese 144 12 2 2 Running Checks within Ant asya Zy eneee erre eera HAT rata Zh 144 12 2 3 Implementing your OWN Checks sese eee eee 145 12 2 4 Framework COMPpoONents 2 0 0 cece cece cecececececeeeeeeeeeeeeeeeeeeeeeeeeee
35. Starting org openarchitectureware workflow oawclassic ClassicOAWSetup 56 NFO classic oAW environment is set up instantiator environment in ie meta environment in me 56 NFO Starting org openarchitectureware core frontends xmi workflow XMIInstantiator 56 NFO Loading XMI from AuthorBookExampleMD10 mdzip using map magicdraw_xmi21_all xml and metamap metamappings xml eli NFO Starting mapping instantiator 57 NFO 58 NFO Parsing metamap metamappings xml 72 NFO Parsing of metamap took 0 14s 72 NFO 1692 INFO Parsing design AuthorBookExampleMD10 mdzip 1702 INFO Loading model 2163 INFO Initializing XMI support for XMI version 2 1 2163 INFO Scanning for referenced modules 2183 INFO Found reference to module UML_Standard_Profile xml 2193 INFO Model loaded in 0 491s 2193 INFO 2193 INFO Loading modules 2984 INFO Scanning for referenced modules 3064 INFO Modules loaded in 0 871s 3064 INFO 3074 INFO Merging 3114 INFO Modules merged in 0 04s 3114 INFO 3234 INFO Parsed design in 1 542s 3234 INFO 3234 INFO Loading extensions 3304 INFO Extensions loaded in 0 07s 3304 INFO 3304 INFO Loading design 3314 WARN ignoring node 65973 ownedMember cannot coerce to ModelElement 3314 WARN ignoring node 66017 ownedMember cannot coerce to ModelElement 3314 WARN ignoring node 66061 ownedMember cannot coerce to ModelElement 3314 WARN ignoring node 66119 ownedMember cannot coerce to ModelElement 3314 WA
36. UML2Met aModel gt lt metaModel class oaw uml2 profile ProfileMetaModel gt lt profile value file umlmda profile project path profiles UMLMDAP rofile epx gt lt metaModel gt lt component gt 11 3 4 Future enhancements The next version of the RSA RSM adapter will support profiles found in the classpath of the generator project In addition profiles can be added more selectively oAW Version 4 2 141 Chapter 12 Recipe Framework 12 1 Introductory Example and Plugin Currently it not feasible in MDSD to generate 100 of an application Usually you generate some kind of implementation skeleton into which developers integrate their own manually written code For example the generator generates an abstract base class from which developers extend their implementation classes which contains the application logic The screenshot above shows an example and also illustrates the use of the Recipe Plugin Let s look at the various items in the screenshot Zi 8 x File Edit Source Refactor Navigate Search Project Run W Help a Lar SO e O A SSHS aev c ES amp Ge IE Package Explorer XN A BE outine 52 E sears E B An outline is not available E ua gt scmGenerator cvs sourceforge net S LS gt scmHelloWorld cvs sourceforge net S gt sre a h gt example 2 99 gt BC1 impl E Ih CalculatorImplementatia H BC2 impl H tests lig gt s
37. Version 4 2 116 Xtext Reference from oAW 4 2 operator the feature the value is assigned to will be of type String You could also use the boolean operator and the type will be Boolean If an identifier conflicts with a keyword or another lexer rule it can be escaped with the character 7 5 3 String Token There is also a built in String Token Here is an example Attribute type DataType name ID description STRING With this one can optionally specify a description for an entity like this entity Customer string name string street should include the street number too int age bool isPremiumCustomer By default the two string literal syntaxes my text and my text are supported Note that unlike in Java also multiline strings are supported entity Customer string name string street should include the street number too And if you don t want to specify it you should consider specifying it somewhere else int age bool isPremiumCustomer 7 5 4 Integer Token Sometimes you want to assign Integers Xtext supports it with the built in lexer rule INT Index index INT The default pattern is It can be overwritten see next section but you have to take car that the coercion Integer valueOf String is used works 7 5 5 Comments There are two different kinds of comments automatically available in any Xte
38. a workflow component that creates the recipes Your custom workflow component has to extend the RecipeCreationComponent base class and overwrite the createRecipes operation The operation has to return the collection of recipes that should stored into the recipe file In the workflow file you then have to configure this component with the name of the application project in Eclipse the souce path where the manually write code can be found and the name of the recipe file to be written Please take a look a the emfHelloWorld example It contains an extensive example of how to use the recipes in oAW 4 12 2 2 Running Checks within Ant You can also check the recipes using ant Of course you cannot use those nice and cool interactive checks and you also can t use Eclipse based checks They can be in the recipes file since the ant tasks skips them automatically The following piece of ant code shows how to run the checks should be self explanatory Note that you have to use all the jar files from the recipe ant project lt xml version 1 0 encoding ISO 8859 1 gt lt project name scm hello world generate default generate gt lt property file build properties gt lt path id ant runtime classpath gt lt pathelement location GENROOT gt lt fileset dir GENROOT includes jar gt lt fileset dir OAWROOT dist includes jar gt lt fileset dir RECIPE CORE DIR dist include
39. and get ID operations Alternatively you can also extend the base class Abst ractWorkflowComponent which handles the ID setter getter for you 5 2 3 More convenience There is another base class for workflow components called AbstractWorkflowComponent2 Its main feature is that it has a property called skipOnErrors If set to true it will not execute if the workflow s issues collection contains errors This is convenient if you want to be able to skip code generation when the preceding model verification finds errors Note that instead of implementing invoke and checkConfiguration subclasses of Abst ractWorkflowComponent2 have to implement invokeInternal and checkConfigurationInternal This is necessary to allow the framework to intercept the invocation and stop it when there are errors in the workflow 5 3 Workflow Configuration A workflow is wired up using an XML configuration language based on the dependency injection pattern DI Here is an example not working just an example lt workflow gt lt property name genPath value home user target gt lt property name model value home user model xmi gt lt component class oaw emf XmiReader gt lt model value model gt lt component gt lt component class oaw xpand2 Generator gt lt outlet gt lt path value genPath gt lt outlet gt lt component gt lt workflow gt oAW Version 4 2 56 Workflow Reference
40. any other statement specifically 1F statements may be nested IF expression a sequence of statements ELSEIF expression a sequence of statements L ELSE a sequence of statements ENDIF 6 5 3 9 PROTECT Protected Regions are used to mark sections in the generated code that shall not be overridden again by the subsequent generator run These sections typically contain manually written code PROTECT CSTART expression CEND expression ID expression DISABLE a sequence of statements ENDPROTECT The values of CSTART and CEND expressions are used to enclose the protected regions marker in the output They should build valid comment beginning and end strings corresponding to the generated target language e g and for Java The following is an example for Java PROTECT CSTART CEND ID ElementsUniqueID here goes some content oAW Version 4 2 92 Xtend Xpand Check Reference ENDPROTECT The rp is set by the Ip expression and must be globally unique at least for one complete pass of the generator Generated target code looks like this public class Person PROTECTED REGION ID Person ENABLED START this pr is enabled therefore the contents will always be preserved If you want to get the default contents from the template you must remove the ENABLED keyword or even remove the whole file PROTECTED REGION EN
41. association containing them From the view of a class a referenced class is at the opposite end Normally it must be considered whether the association i e the opposite association end to the referenced class is navigable writtenBook lt lt AssociationEnd gt gt Opposite name writtenBook MultiplicityMin 0 MultiplicityMax 1 isNavigable true Class lt lt Entity gt gt Book IN lt lt Association gt Also the templates for associations between classes are very common so we define them in a central template file Association xpt in the templates java folder We want to keep the usage of the association template for the calling class template simple and hide this complex stuff about association ends So we define simple entry points for class elements We also make use of further extensions to facilitate template development 15 18 1 Association Extensions The extensions for functions used for associations are put into a seperate file Create the file templates java Associations ext with this content import org openarchitectureware meta uml classifier extension java NamingConventions String fqn AssociationEnd ae ae isMultiple ae Class fqn java util Collection lt ae Class fqn gt String iterator Asisociatdonind ae o Vsiava utile bberaton lt tac Cllass fqn ual oAW Version 4 2 180 Classic UML Tutorial As you can see we will creat
42. bydefault has an xmi extension Note that openArchitectureWare can work completely with dynamic models there s no reason to generate code However if you want to programmatically work with the model the generated metaclasses not the editors are really helpful Please also keep in mind in subsequent parts of the tutorial you ll specify the metaModelPackage in various component configurations in the workflow file like this lt metaModel id mm class org openarchitectureware type emf EmfMetaModel gt lt metaModelPackage value data DataPackage gt lt metaModel gt In case of dynamic EMF there has no metamodel package been generated So you have to specify the meta model file instead that is the ecore file you just created Note that the ecore file has to be in the classpath to make this work lt metaModel id mm class org openarchitectureware type emf EmfMetaModel gt lt metaModelFile value data ecore gt lt metaModel gt 1 8 Generating Code From the Example Model 1 8 1 The workflow definition To run the openArchitectureWare generator you have to define a workflow It controls which steps loading models checking them generating code the generator executes For details on how workflow files work please take a look at the Workflow Reference Documentation Create a workflow oaw and a workflow properties in the src folder The contents of these files is shown below
43. care about the EvaluationContext Its only needed by the framework 12 2 3 3 Eclipse Checks Eclip se checks are a bit special If the check were implemented in the way described above you d have a lot of dependencies to all the Eclipse plugins jars You d have these dependencies as soon as you d instantiate the check i e also in the generator when you configure the check In order to avoid this we have to decouple the configuration of a check in the generator and its evaluation later in Eclipse oAW Version 4 2 146 Recipe Framework 1 During configuration we don t want any Eclipse dependencies since we don t want to import half of Eclipse into out ant based code generator 2 However when evaluating the check we obviously need the Eclipse dependencies otherwise we couldn t take advantage of Eclipse based checks in the first place An Eclipse check is thus implemented in the following way First of all our check has to extend the EclipseCheck base class public class ResourceExistenceCheck extends EclipseCheck Again we add a serial version uid to make sure deserialization will work private static final long serialVersionUID 2L In the constructor we decide whether we want to have this check evaluated whenever the Eclipse workspace changes EvalTrigger ON_CHANGE or not We also store some of the parameters in the parameter facility of the frame
44. checks Let s look at what you need to do In order to simplify life your recipe creation component should use the RecipeCreat ionComponent base class public class RecipeCreator extends RecipeCreationComponent You then have to override the createRecipes operation protected Collection createRecipes Object modelSlotContent Siecle Cj jecie ET Eeewsiela We now create a list that we use to collect all the checks we want to pass back to the framework List checks new ArrayList Since we need to implement such a check for each Entity in the model we have to find all entities and iterate over them Collection entities EcoreUtil2 findAl1lByType DataModel modelSlotContent eAllContents Rab Ea learSiSum iy for Iterator iter entities iterator iter hasNext Entity e Entity iter next We then create a composite check whose purpose is to act as a container for the more specific checks that follow It will show as the root of a tree in the Recipe Framework view ElementCompositeCheck ecc new ElementCompositeCheck e manual implementation of entity Then we add a check that verifies the exsitence of a certain class in a given project in a certain directory The name of the class it needs to check for can be obtained from our EntityHelper JavaClassExistenceCheck javaClassExistenceCheck new JavaClassExistenceCheck you have to provide an impleme
45. conde EN shy E EE EEEo va ATER EEE a EE A Ea S 56 5 2 2 Workflow Components with IDS sees 56 5 2 3 M re CONVEMENCE ienes nsco esre nsei ig e anr vaedessdcceucdsedenanevess 56 5 3 Workflow Configuration sees ee ee ee e e e e e e e eee 56 5 3 1 Properties nin a e ioir iiien iie eE erii ei iE a er E ie Eaei iah 57 5 3 2 Component Implementation and Workflow Execution sse sese ee ee ee ee ee ee ee ee eee 61 5 39 Invoking a Workflows ieser ev eee yeietioins EEE E EE ated ania edd 63 6 Xtend Xpand Check Reference oiean saasaa av egeceaed loess sev ededstes agecs EAEE 65 Ols Introd UCtO Ms arasi EE e Zr Naia es aes Ce Epa aT ETag Dede sed gees Nea TET Seco 65 6 2 Type SyStem sis cede a iE AE resins vedods Weedehtidenen av E A leeds Avedon EA aveeeess does EEE 65 6 Dols TY Pes ia E E EEEE EEEE ER weed AEE EEEE A R inet anes Medea EREE A ea 65 02 2 Built Types e ie E T 66 6 2 3 MetaModel Implementations aka Meta Meta Model sese 67 6 2 4 Using different MetaModel implementations aka MetaMetaModels sss 68 6 3 AE XPTESSIONS 245 Sessa wave sans dane deiedce e a a ci TO teas desea da Gods os Be datedanes ai ee E e eE Ses 69 6 3 1 Literals and special operators for built in types eee 70 6 3 2 Special Collection operations i nasstress e iaie aeien aeria 72 6 3 3 I ER PTESSION ne eero reae s teas tadocesGalevuntts cadens 250d Ee AOE EEE OEE ETE E EE e ottovs 74 603A eni ren EXPLESSIOM sie eea aiea dud tae ee eae E data es tad au shes se
46. contains our checks will be important below lt runtime gt lt library name oaw recipe eclipsechecks jar gt lt export name gt lt library gt lt runtime gt The required plugins mainly depend on the implementations of the CheckEvaluators of course however you have to make sure the dependencies contains the org openarchitectureware recipe plugin since you re going to extend an extension point defined therein lt requires gt lt import plugin org eclipse ui gt lt import plugin org eclipse core runtime gt lt import plugin org eclipse core resources gt lt import plugin org openarchitectureware recipe gt lt import plugin org eclipse jdt core gt lt requires gt This is the important line here you specify that you extend the check extension point of the Recipe Browser Plugin If you don t do this deserialization of the recipe file will fail and you ll get nasty errors And yes you need the dummy element otherwise the class loading magic will not work lt extension point org openarchitectureware recipe check gt lt dummy gt lt extension gt lt plugin gt When you need to use the checks outside of Eclipse e g in the generator for configuration serialization purposes you just add the plugin s jar to your generator classpath You don t need all the Eclipse plugin s jars referenced in the requires section since these things will
47. controlled 5 3 2 1 The Workflow Context Workflow components have to communicate among each other For example if an XMIReader component reads a model that a constraint checker component wants to check the model must be passed from the reader to the checker The way this happens is as follows In the invoke operation a workflow component has access to the so called workflow context This context contains any number of named slots In order to communicate two components agree on a slot name the first component puts an object into that slot and the second component takes it from there Basically slots are named variables global to the workflow The slot names are configured from the workflow file Here is an example lt xml version 1 0 encoding windows 1252 gt lt workflow gt lt property file workflow properties gt lt component id xmiParser class org openarchitectureware emf XmiReader gt lt outputSlot value model gt lt component gt lt component id checker class datamodel generator Checker gt lt modelSlot value model gt lt component gt lt workflow gt As you can see both these workflow components use the slot named model Below is the abbreviated implementation of the xmiReader It stores the model data structure into the workflow context in the slot whose name was configured in the workflow file public class XmiReader implements WorkflowComponent private String
48. defines a number of parameters and calls another workflow file the one in the generator project We ll take a look at it below 17 4 1 Running the example is achieved by running the example oaw file It creates an implementation of the state machine in the src gen folder in the example project Take a look at the file to understand the implementation of the state machine In the man src folder there s a manually written subclass that implements the actions referenced from the state machine There s also a unit test that you can run to verify that it works It also shows you how to use the generated state machine oAW Version 4 2 191 EMF State Machine 17 5 The Generator 17 5 1 Workflow The workflow file in oaw4 demo emf statemachine generator src has four steps e first it reads the model from the XMI file e then it verifies a number of constraints e then it generates the code e and finally it creates a recipes file 17 5 2 Constraints A number of constraints are defined Take a look at their definition in structure chk to learn about the constraints check language 17 5 3 Transformation There is a transformation called trafo ext in the src folder which adds an emergency stop transition to each state 17 5 4 Templates In the src templates folder you can find the code generation templates 17 5 5 Recipe Creation In src recipe you there s an SMRecipeCreator workflow component that creates recipes for t
49. for Entity We also have to add a new Import so that oAW can resolve Entity IMPORT oaw4 demo classic uml meta DEFINE Root FOR Entity EXPAND java JavaBean BeanClass ENDDEF INE As you remember while looping through the model for each element in the model tree a definition called Root is called Before adding this we had a definition for Packages Models and all other objects Now when evaluating elements of type Entity this definition matches In this definition we call the definition named Beanclass from the template file savaBean xpt As the template JavaBean xpt is defined in the package java we also have to qualifiy this namespace As an alternative we could import the namespace java The definition is implicitely called for the current element which is of course an Entity oAW Version 4 2 175 Classic UML Tutorial 15 15 The first generated code Run the generator again as a shortcut you could type Ctrl F11 Now your project should contain the folder src gen which contains four files Author java Book java Copy java and Library java Open Author java It does only contain the class definition since the template was that simple public class Author 15 16 Defining property declarations and accessor methods Now we want to extend the JavaBean template to create instance variables property getters and setters Generating declarations for instance variab
50. for you 7 2 Installation Xtext is contained in the openArchitectureWare SDK The easiest way to install is to download and unzip the Eclipse 3 3 for RCP Plug in Developers from eclipse s download site http www eclipse org downloads Afterwards download the org openarchitectureware all_in_one_feature 4 2 0 zip release and extract it to the directory where you have unziped the Eclipse release i e the Eclipse installation dir Make sure that you start Eclipse with a Java VM Version greater than 5 0 7 3 Getting started You should have a look at the Xtext tutorial screencast TODO link to screencast This will give you a good overview of how Xtext basically works Come back to this document to find out about additional details 7 4 The Grammar Language At the heart of Xtext lays its grammar language It s a lot like an extended Backus Naur Form but it not only describes the concrete syntax but also the abstract syntax metamodel oAW Version 4 2 110 Xtext Reference from oAW 4 2 A grammar file consists of a list of so called Rules 7 4 1 Example This is an example for a Rule describing something called an entity IE AE SY 8 entity name ID featurest t Feature myn Entity is both the name of the rule and the name of the metatype corresponding to this rule After the colon the description of the rule is following A description is made up of tokens The first token is a KeywordToke
51. in Tokens we have already seen the IdentifierToken and the KeywordToken Sometimes this is not sufficient so we might want to create our own Tokens Therefore we have the so called String Rule which is implemented as a parser rule it s not a lexer rule Example String Javaldentifier Ty 9 moji The contents of the String Rule is simply concatenated and returned as a string One can refer to a String Rule in the same manner we refere to any other rule So just for the case you want to declare datatypes using your DSL and therein specify how it is mapped to Java not Platform independent i know but expressive and pragmatic you could do so using the following rules Attribute type DataType name ID DataType datatype name ID mappedto javaType Javaldentifier String Javaldentifier TD P aD A respective model could look like this entity Customer string name string street int age bool isPremiumCustomer oAW Version 4 2 115 Xtext Reference from oAW 4 2 datatype string mappedto java util String datatype int mappedto int datatype bool mappedto boolean You could of course point to a custom typemapping implementation if you need to support multiple platforms like e g SQL WSDL Java Additionally you should consider to define the datatypes in a separate file so the users of your DSL can import and use them 7 5 Lexer Rules As mentioned b
52. is the workflow file you should put it into the source folder The file should be generally understandable if you read the oAW EMF Example docs lt xml version 1 0 encoding ISO 8859 1 gt lt workflow gt You need to setup the UML2 stuff registering URI maps Factories etc This can be done declaring a bean in before of the xmiReader component lt bean class oaw uml2 Setup standardUML2Setup true gt lt component class oaw emf XmiReader gt lt modelFile value example uml gt lt outputSlot value model gt lt component gt The xmiReader reads the model and stores the content a list containing the model element in a slot named model As usual you might want to clean the target directory lt component id dirCleaner class oaw workflow common DirectoryCleaner directories src gen gt and in the generator we also configure the EMF meta model for oAW together with the UML2 metamodel package because the UML2 metamodel refers to it lt component id generator class oaw xpand2 Generator skipOnErrors true gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelPackage value org eclipse emf ecore EcorePackage gt lt metaModel gt lt metaModel class oaw uml2 UML2Met aModel gt lt expand value templates Root Root FOR model gt lt outlet path srce gen gt lt postprocessor class oaw xpand2 output JavaBeautifier gt lt out
53. it an override 6 5 8 2 Workflow File Let s take a look at the workflow file to run this generator lt workflow gt lt cartridge file workflow oaw gt lt component adviceTarget generator id reflectionAdvice class oaw xpand2 GeneratorAdvice gt lt advices value templates Advices gt lt component gt lt workflow gt Mainly what we do here is to call the original workflow file It is available from the classpath After this cartridge call we define an additional workflow component a socalled advice component It specifies generator as it s adviceTarget That means that all the properties we define inside this advice component will instead be added to the component referenced by name in the adviceTarget in our case the generator So in effect we add the lt advices value templates Advices gt to the original generator component without invasively modifying its own definition This contributes the advice templates to the generator 6 5 8 3 Running the new generator Running the generator produces the following code public abstract class PersonImplBase oAW Version 4 2 100 Xtend Xpand Check Reference Og ils GHiresieske cimed Weer TG nameInfo new AttrInfo name String class oybloylaved Gieeie ales TT IGE name2Info new AttriInfo name2 String class private String name private String name2 public void setName String value this name val
54. itself we ll need that property in the next section the one on recipes The best practice for this use case is to implement the derived property as a Java method as above The following piece of code declares properties for Entity package datamodel import data Entity public class EntityHelper public static String className Entity e return e getName Implementation public static String classFileName Entity e return className e java In addition to access the properties from the template files we define an extension that uses the helper methods The helper ext file is located right next to the helper class shown above i e in the datamodel package import data String className Entity e JAVA datamodel EntityHelper className data Entity String classFileName Entity e JAVA datamodel EntityHelper classFileName data Entity In addition to these new properties being accessible from Java code by invoking EntityHelper className someEntity we can now write the following template EXTENSION templates java EXTENSION datamodel generator util util EXTENSION datamodel helper DEFINE Root FOR data DataModel EXPAND Entity FOREACH entity ENDDEF INE DEFINE Entity FOR data Entity FILE classFileName generated at timestamp public abstract class className FOREACH attribute AS a private
55. just a name JA cxample data X gt Resource Set B e platform resource oaw4 demo emf datamodel generator src example data gt Model lt gt Entity Person lt gt Attribute name Bam Entity Reference autos gt Entity vehicle lt gt Attribute plate Selection Parent List Tree Table Tree with Columns E Properties 52 gt a amp 3 Ea ml Property Value Name autos Target Entity Vehicle To Many TE true Figure 1 14 Sample data model Again to avoid any typos here is the XMI for example data oAW Version 4 2 13 EMF Tutorial lt xml version 1 0 encoding UTF 8 gt lt data DataModel xmi version 2 0 xmlns xmi http www omg org XMI xmlns data http www openarchitectureware org oaw4 demo emf datamodel gt lt entity name Person gt lt attribute name name type String gt lt reference name autos toMany true target entity 1 gt lt entity gt lt entity name Vehicle gt lt attribute name plate type String gt lt entity gt lt data DataModel gt 1 7 Using Dynamic EMF Instead of generating editors and metaclasses you can also use dynamic EMF This works by selecting in the opened metamodel the root class of the model you want to create here DataModel and then selecting from the context menu This opens an editor that can dynamically edit the respective instance The created file
56. layer over different meta meta models e g EMF s Ecore Eclipse s UML JavaBeans XML Schema etc Additionally it offers a powerful statically typed expressions language which is used in the various textual languages 6 2 Type System The abstraction layer on API basis is called a type system It provides access to built in types and different registered metamodel implementations These registered metamodel implementations offer access to the types they provide The first part of this documentation describes the type system The expression sub language is described afterwards in the second part of this documentation This differentiation is necessary because the type system and the expression language are two different things The type system is a kind of reflection layer that can be extended with metamodel implementations The expression language defines a concrete syntax for executable expressions using the type system The Java API described here is located in the org openarchitectureware type package and is a part of the subproject core expressions 6 2 1 Types Every object e g model elements values etc has a type A type contains properties and operations In addition it might inherit from other types multiple inheritance 6 2 1 1 Type Names Types have a simple Name e g string and an optional namespace used to distingish between two types with the same name e g my metamodel The delimiter for name space fra
57. literals are true false Operators are true amp amp false AND true false OR true NOT 6 3 1 7 Integer and Real The syntax for integer literals is as expected integer literals 3 57278 veal literals JaA Oa w5 Additionally we have the common arithmetic operators 4 addition 5 subtraction 6 ff ERIE ron 3 64 divide Unary minus operator iD ATLL N eA W Furthermore the well known compare operators are defined gt 5 greater than lt 5 smaller than gt 23 greater equals than lt 12 smaller equals than 6 3 1 8 Collections There is a literal for lists 1 2 3 4 a list with four integers There is no other special concrete syntax for collections If you need a set you have to call the toSet operation on the list literal 1 2 4 4 toSet a set with 3 integers oAW Version 4 2 71 Xtend Xpand Check Reference 6 3 2 Special Collection operations Like OCL the oAW expression sub language defines several special operations on collections Those operations are not members of the type system therefore you can t use them in a reflective manner 6 3 2 1 select Sometimes an expression yields a large collection but onje is only interested in a special subset of the collection The expression sub language has special constructs to specify a s
58. metaclasses directly since they are often specific to the specific code generation target and thus should not pollute the metamodel It is possible to define such extensions external to the metaclasses For details see the Extend Language Documentation we provide an simple example here 1 10 1 Expression Extensions Assume we wanted to change the Attributes part of the template as follows FOREACH attribute AS a private a type a name public void a setterName a type value this a name value oAW Version 4 2 20 EMF Tutorial public a type a getterName return this a name ENDFOREACH To make this work we need to define the setterName and getterName operations We do this by writing a so called extension file we call it java ext It must have the ext suffix to be recognized by oAW the java name is because it contains Java generation specific properties We put this file directly into the templates directory under src i e directly next to the Root xpt file The extension filelooks as follows First we have to import the data metamodel otherwise we d not be able to use the Attribute metaclass MG Pi dat ary We can then define the two new operations setterName and getterName Note that they take the type on which they re called as their first parameter a kind of explicitly this After the colon we use an expression that return
59. minimize environmental problems 15 2 Installing the sample Make sure that you installed the openArchitectureWare feature properly in your Eclipse environment openArchitectureWare depends on EMF so check that you have installed it If you need further information on oAW installation please look at http www openarchitectureware org staticpages index php documentation Instead of working through this tutorial you can also install the packaged example by downloading the oaw samples classic uml 4 x x package It contains one Eclipse project which you have to import into your workspace To make the projects compile and run you may have to define to use the oAW Classic Metamodel in the project properties E Properties for oaw4 demo classic uml type filter text openArchitectureware Info Builders CVS Enable project specific settings Java Build Path Java Code Style Java Compiler Javadoc Location Select metamodel contributor openArchitectureware Plug in Development Project References Refactoring History Enable openArchitectureWare nature oAW Classic Metamodel New Remove Down Restore Defaults Apply Figure 15 1 Configure oA W Classic Metamodel 15 3 Example overview The purpose of this tutorial is to demonstrate the very simplest way to use oAW4 in combination with an non EMF UML2 capable UML tool to create code from a model that contains some classes The project is really simple so it i
60. only be used during evaluation oAW Version 4 2 148 Recipe Framework 12 2 4 Framework components lrecipe core ME core Needed whenever oe do anything with recipes a oe core Contains the ant task to check recipes Needed only for recipe evaluation in ant recipe simpleChecks recipe core Contains a number of more or less pee ccna sample checks recipe plugin es recipe core Contains the Eclipse Recipe Browser hecks 12 2 5 List of currently available Checks This table contains a list of all currently available checks We are working on additional ones Contributions are always welcome This list might thus not always be up to date just take a look at the code to find out more Classname Purpose lorg openarchitectureware recipe checks hecks whether a given file ile FileExistenceCheck exists lorg openarchitectureware recipe checks hecks whether a given ile FileContents Check substring can be found in a ertain file lorg openarchitectureware recipe hecks whether a given leclipseChecks checks JavaClassExistenceCheck ava Class exists lorg openarchitectureware recipe hecks whether a given leclipseChecks checks JavaSupertypeCheck ava class extends a certain lorg openarchitectureware recipe leclipseChecks checks ResourceExistenceCheck oAW Version 4 2 149 Chapter 13 UML2Ecore Reference 13 1 What s this Building meta models with EMF s internal tools is tedious Using the tree vi
61. openarchitectureware meta uml import org openarchitectureware meta uml classifier String asParameter ModelElement elem p t elem NameS toFirstUpper String asSetter ModelElement elem set t telem NameS toFirstUpper String asGetter ModelElement elem get telem NameS toFirstUpper String asInstanceVar ModelElement elem With openArchitectureWare3 it was needed to code functionality of the metamodel in metaclasses The functions in the Extension file could be defined for type Attribute instead of Modelzlement but we want to use these functions for other types later on too oAW Version 4 2 177 Classic UML Tutorial elem NameS toFirstLower In extension files import statements for used types are necessary too The function declarations are single lined and can use any expressions calls of other extension functions included Open Attribute xpt and make use of these functions In template files the usage of extensions must be declared by the EXTENSION keyword The modified template file will be this IMPORT org openarchitectureware meta uml classifier EXTENSION java NamingConventions DEFINE PropertyDeclaration FOR Attribute private Type NameS asInstanceVar ENDDEF INE DEFINE Getter FOR Attribute public Type NameS asGetter return this asInstanceVar ENDDEF INE DEFINE Setter FOR
62. outputSlot null public void setOutputSlot String outputSlot this outputSlot outputSlot public void invoke WorkflowContext ctx ProgressMonitor monitor Issues issues Object theModel readModel ctx put outputSlot theModel The checker component reads the model from that slot public class Checker implements WorkflowComponent private String modelSlot public final void setModelSlot String ms this modelSlot ms oAW Version 4 2 61 Workflow Reference public final void invoke WorkflowContext ctx ProgressMonitor monitor Issues issues Object model ctx get modelSlot check model 5 3 2 2 Issues Issues provide a way to report errors and warnings There are two places where issues are used in component implementations 1 Inside the checkConfiguration operation you can report errors or warnings This operation is called before the workflow starts running 2 Inside the invoke operation you can report errors or warnings that occur during the execution of the workflow Typical examples are constraint violations The Issues API is pretty straightforward you can call addError and addWarning The operations have three parameters the reporting component a message as well as the model element that caused the problem if there is one The operations are also available in a two parameter version omitting the first reporting component
63. protected regions 92 disbale 93 enable 93 R REM 94 S separator 91 expression 91 T template polymorphism 89 template file 89 W whitespace omit 94 X Xpand 87 XpandException 93 oAW Version 4 2 198
64. that should be implemented are specific for associations the check file should be named AssociationChecks chk Create this file in templates java import org openarchitectureware meta uml classifier context AssociationEnd ERROR Class NameS gt Opposite Class NameS Navigable association ends must have a role name isNavigable isUnnamed true context AssociationEnd WARNING Class NameS gt Opposite Class NameS Not navigable association ends should have no role name isNavigable true isUnnamed The syntax is rather simple Both constraints should be checked for the metaclass AssociationEnd so the appropriate namespace has to be imported The expression following the colon is the constraint If it is not fulfilled the message is printed When error messages are printed the workflow will be interrupted oAW Version 4 2 184 Classic UML Tutorial 15 19 4 Checking the model To execute the constraint checks the generator workflow has to be extended The constraint check is configured by a workflow component CheckComponent Insert this code into workflow oaw right between the cartridge classicinit oaw and the dircleaner component lt component class org openarchitectureware check CheckComponent gt lt metaModel class org openarchitectureware type impl java JavaMetaModel gt lt typeStrategy class org openarchitectureware type impl oawclassic OAWClassicStrategy convertProperties
65. the target type is handled as the first parameter So assume you have the following metamodel Figure 6 1 Sample metamodel Assume further you d have a model which contains a collection of a B and c instances in the property listofAs You can then write the following template DEFINE someOtherDefine FOR SomeMetaClass EXPAND implClass FOREACH listOfAs ENDDEF INE oAW Version 4 2 89 Xtend Xpand Check Reference DEFINE implClass FOR A this is the code generated for the super class A ENDDEF INE DEFINE implClass FOR B this is the code generated for the subclass B ENDDEF INE DEFINE implClass FOR C this is the code generated for the subclass C ENDDEF INE So for each s in the list the template defined for sB is executed for each c in the collection the template defined for C is invoked and for all others which are then instances of a the default template is executed 6 5 3 4 FILE The FILE statement redirects the output generated from its body statements to the specified target FILE expression outletName a sequence of statements ENDF ILE The target is a file in the file system whose name is specified by the expression relative to the specified target directory for that generator run The expression for the target specification can be a concatenation using the operator Additionally you can specify an identifier a legal Ja
66. this should result in the following both declarations to one association Copy java private oaw4 demo classic uml entity Library owner to many association Author java private java util Collection lt oaw4 demo classic uml entity Book gt writtenBook Both types are now expressed by this statement simple isn t it private ae fqn ae asInstanceVar The next template definition is also interesting The definition AccessorMethods FOR Class dispatches to the definitions ToOneAccessorMethods OF ToManyAccessorMethods depending on the cardinality of the association To distinguish both types we make use of the select expression which is defined for expression The statement EXPAND ToOneAccessorMethods FOREACH AssociationEnd Opposite select ae ae isMultiple amp amp ae isNavigable means that the definition TooneAccessorMethods should be expanded for each opposite association end which is not to many and navigable So for unnavigable associations no accessor method will be created The definitions for the accessor methods have nothing new so we do not explain them in detail now 15 18 3 Extending the JavaBeans template Now we want to use the new templates from the JavaBeans template so that the classes get instance variables for referenced classes and appropriate accessor methods Modify the template file JavaBeans xpt by adding these two statements to the class defini
67. will be overwritten by the generator wipeout src gen true Specifies whether the src gen folders should be deleted before generation generator project name If this property is set to something a project wizard will be generated referencing the generator project workspace dir he root of the workspace core project name name of the main project core project sre src src folder of the main project core project src gen srce gen src gen folder of the main project editor generate true should an editor be generated at all editor project name name of the editor project core project name editor editor project srce src folder of the editor project core project src editor project src gen src gen folder of the editor project core project src gen 7 6 2 Generated and manual code Any textual artifacts located in the src dir of any project will always stay untouched The generator just creates them the first time when they don t exist Files generated to the src gen directory should never be touched The whole directory will be wiped out the next time one starts the generator 7 6 3 The different projects and artifacts Xtext generates artifact into two different projects 7 6 3 1 The main project The name of the main project can be specified in the wizard This project contains the main language artifacts and is 100 eclipse independent The default locations of the most important resources are
68. write the result of the transformation out to an ecore file src org openarchitectureware uml2ecore uml2ecoreWorkflow oaw You could now take a look at the constraints against the UML model There are currently quite few of them in the code but at least it shows how to write constraints against UML2 models src org openarchitectureware uml2ecore uml2Constraints chk The transformation itself is located in um12ecore ext While the transformation is not too complicated it is also not trivial and illustrates many of the facettes of the Xtend transformation language src org openarchitectureware uml2ecore uml2ecore ext oAW Version 4 2 194 Model To Model To see how global variables are used take a lodkhaUthi 2offxbahywle gt declaration in the workflow file as well as the nsuri function in uml2exore ext To see JAVA extensions in action take a look at io ext and IoExtensions java 18 5 Using the transformer Usage of the transformer can be seen from the uml2ecore user s guide mentioned a couple of times already However you can also take a look at the stuff in the testing section 18 6 Testing an M2M transformation M2M transformations can become quite intricate especially if UML2 is involved Therefore testing such a transformation is essential Note that you should resist the the temptation to write tests in the form of generic constraints such as for each Class in the UML2 model there has to be an EC
69. 2 Xi List of Tables 6 1 Properties a aie heim ee ae ila ie en eatin ee a ae ae 102 6 2 Operations a sas Sensis tesa cents OEREO EAE case es cheap R EEE Ea A chads nd eee vogedh ot eae eee oats a eee 102 6 37 PrOpPertleS sw veeeiad aegis teen en ai ace ates tea a ei ai eed ee tee alanis tate 102 6 4 Operations sasa TO tele cet a Aelia oie ee ee et a eee ee 103 6 5 Operations ni eaee ent tnd EEE A EE EE ed een i Thad to a eae eee ate eee 104 6 6 Operations iaie te eae ties aie aes ee a ei ee ee ae ie ee 104 O27 Operations F Jecke be scbede te accaces oa sth edes cree ay eteoks tote reteas a hued a aaaea a TAa are aA Eaa a eaae teh ATS 105 6 83 Properties serrie sob eae erea e A e eea ea aeea oq ebpvssad ects anateeteded boise ebiessis eoseauitesheess 105 6 9 Operations mresa rererere renen ca ei ea EENE a TE TENE SOTEER EEEa ATETEA TE EEE ATETA Eea e TEER TE ea Sarona atts 106 6 10 ODErati on S s heen eserin eeen eE hean Een ER ane TETEA debut cad sa AE EEEn lbebeds datas anh sa EE ESELA AK TETKA SEEE 107 Olle Properties arenor inos iyeuh reas EERE REEE oa E EEA ETRE EAE ce EEEE ETAR EAE EaR 107 6 12 QPEratiOns sirean ea dance ous enen dubs EEIE Eaa EEEn E e dares nas ERA eda S EESE NESA 107 GLB Properties meserna lerre ta EE E a AE AE EEEE EEE EU EEEE E OE E ER EEEE AE 108 6 14 Operations ions atoni tentene atine arr a i a n a a a a a ne aaeeea n tio 108 6V5 Operations a 1aTSSS 4422974 T4ZEsT aT dE Eao 12T S297947 S9 741A aT La
70. 4 2 143 Recipe Framework downloading it from the oAW update site If the plugin is installed in this way it can only evaluate the relatively trivial checks in the recipe simpleChecks project To check useful things you ll have to extend the plugin you have to contribute the checks that should be executed For this purpose the org openarchitectureware recip plugin provides the check extension point A number of useful checks that can be evaluated in Eclipse are contained in the org openarchitectureware recipe eclipseChecks plugin You should install that one too It also comes automatically from the update site In general this means whenever you develop your own checks and want to evaluate them in Eclipse you have to contain them in a plugin and extend the above mentioned extension point Otherwise it will not work 12 1 2 Referencing the JAR files In order for the workflow to find the recipe JARs they need to be on the classpath The easiest way to achieve that is to make your generator project a plugin project and reference the recipe plugins in the plugin dependencies all the oAW plugins with recipe in their name This will update your classpath and add the necessary JARs If for some reason you don t want your projects to be plugins you have to reference the JAR files of the above mentioned plugins manually 12 2 Executing Recipe Checks 12 2 1 Running Checks within your workflow You have to write
71. 5 4 1 1 Definition Name The definition name part of a point cut must match the fully qualified name of the join point s definition Such expressions are case sensitive The asterisk character is used to specify wildcards Some examples my Template definition definitions with the specified name org oaw definitions prefixed with org oaw Operation definitions containing the word Operation in it a all definitions 6 5 4 1 2 Parameter Types The parameters of the definitions we want to add our advice to can also be specified in the point cut The rule is that the type of the specified parameter must be the same or a super type of the corresponding parameter type the dynamic type at runtime of the definition to be called Additionally one can set the wildcard at the end of the parameter list to specify that there might be none or more parameters of any kind Some examples my Templ def templ def without parameters my Templ def String s templ def with exactly one parameter of type String my Templ def String s templ def with one or more parameters where the first parameter is of type String my Templ def templ def with any number of parameters 6 5 4 1 3 Target Type Finally we have to specify the target type This is straightforward my Templ def FOR Object templ def for any target type my Templ def FOR Entity templ def objects of type E
72. 6 2 Installation yere sje eyi periniek ONET OR NOTRe Rd NOTRE OT OTRE i r 20 188 1623 Working with EE r ose eee ccc sr egect tredir a oe Gag EREE sts docs Ak een utes R ARa 188 TA AMPS tate Machine saarinen avec TTT 190 171 Introd UCt On sissi i eiia t tn gees Set oes EEN R ae AAE ETER ENEE EREA a eae 190 17 25 R EIT 190 17 3 Metamodel reren onie iie E R Heed EE A E AERE Agedee EE AA EE ERER 190 17 4 Fxample Statemac hine 7 rda Od EE 28 eben eed es wei a 191 17 4 1 Running the TR 191 175 The Generator sorient einer ee weal eae ee eden 192 17 5 A 1 10 2 OW varii sae ce Soe oats eere tea ts Medea ca Ni e ede nese ld aE NG aai a 192 17 5 2 COMSULAMIUS vires cis oc gedaan te gh Seas Me sewcel ate ocke ped cave Teed sad a E e o EE E a ede EOE EE 192 1725 36 Transformation snin sists fuss ceteeusaxt ten etek Seed eeste E O Siete ceedeuh este Se uesestens mt sbened 192 17 35 42 Templates cities teil ate ei ities de ee aA lee eats 192 175 5 Recipe Creation deea ee A EE a Meh E A sels T 192 17 5 6 sACKnowled Sements nyn a na oeiia taie EE REEE A E EE A EEE R 192 18 Model To Model with UML2 Example sss sese eee eee 193 TSA Introduction erie ee ea iE E a a E Ee eai E E A i O Tiaa a E N 193 18 2 Why this example aroe teeraa ae eanit ai ei ee al Genie 193 18 3 Settins Up Eclipseen teier HT 194 oAW Version 4 2 viii openArchitectureW are User Guide 18 4 The Building Blocks of the Transformer sss sese sese sese ee ee e
73. 7 USING EXTENSIONS 2 2 22 2 essceecy sseesuue E Seva neue seeeubdeeeeees EE E EEEE aE EED AEE kE Eorpa 177 15 17 1 Declaring functions with the Xtend language ses ee eee e eee 177 15 17 2 Calling Java functions as extensions 0 0 0 0 eee eee eee 178 15 18 Working with associations 0 0 0 0 eee e e e Ee aE E Er E E kaaret 180 15 18 1 Association EXtensions se rneer ireen n Eaa E eaa Eri oa a e ETTA 180 15 18 2 Writing a template for associations esse eee e e e eee 181 15 18 3 Extending the JavaBeans template sese eee eee 182 15 184 Generator restltss si sect abreststoxtantoulat isis TR2 9 eieaa otete enata H TRT E O ER 2994 182 15419 Constraint Checking Tersier genei aiee iiie pe eda iit 183 15 19 1 Alternatives for implementing constraints sse eee ee ee ee e ee ee ee ee e ee ee eee 184 15 19 2 Constraints to implement in the example sse ee eee ee e ee eee 184 15 19 3 Creating the Check Tle 2 desacetebsveretheieids iss onanii enet aeii T EnEV Eier 184 1519 4 Checking the Model sisisi Gist ious aaeeio tea OEE a Eea E E nii 185 15 19 5 Testing the c nstraints seserinis iii iei iore siar i arresi 185 15 20 Further development of this tutorial sese 185 TMi Samples ei yechile bes eede he ves Oy cece a eea e e e cadens sduseds che sddugusuvelios ys dedunend Gulgepe re 187 16 Using the Emfatic Ecore Editor sese 188 16 1 Introduction iesiri iiien de ldenndcchecdececdeesevedanese dedcnandiecdecpeceedeasevedanesededdeandect 188 1
74. AW Version 4 2 104 Xtend Xpand Check Reference Table 6 7 Operations 6 6 6 collection Super type object Table 6 8 Properties eturns the size of this Collection eturns true if this Collection is empty oAW Version 4 2 105 Xtend Xpand Check Reference Table 6 9 Operations Return type Collection Collection Collection String Collection 6 6 7 List Super type Collection removes the specified element from this Collection if contained modifies it returns this Collection Later U onverts this collection to List containsAll Collection returns true if this collection contains leach element contained in the specified collection otherwise false returns this Collection removeAll Object removes all elements contained in the specified collection from this Collection if contained modifies it returns this Collection addAll Collection adds all elements to the Collection pee ee it returns this Collection j i concatenates each contained element using toString separated by the specified String contains Object returns true if this collection contains the specified object otherwise false returns this Collection intersect Collection returns a new Set containing only the elements contained in this and the specified Collection without Collection returns a new Set containing all elements from this Collection without the elements from s
75. As gt oAW Workflow oAW Version 4 2 51 oAW 4 Eclipse Integration Java Component xpt Eclipse SDK lea me Package Explorer X IMPORT scm E IMPORT scm ia DEFINE Root FOR scm 1m EXPAND ComponentPojo EXPAND Exception Roo EHDDEF IHE comp Tex helloWorld recipes E oaw4 demo classic scr oo oaw4 demo classic urr running workfloi Starting workf Run As Because it is a normal launch configuration you could run or even debug it using the normal Eclipse functionality oAW Version 4 2 52 Chapter 4 Migration This chapter describes how to migrate between the various versions of oAW 4 1 Migrate from oAW 4 1 2 to oAW 4 2 Here s what you need to do when migrating from oAW 4 1 2 to oAW 4 2 4 1 1 Plugin Dependencies org openarchitectureware core check has been merged with org openarchitectureware core expressions So this dependency can simply be removed Remove plugin dependencies to all org openarchitectureware core plugins and add a dependency to the new org openarchitectureware dependencies plugin This plugin bundles all dependent plugins and reexports these 4 1 2 Xtext Although we have many cool new features in Xtext from oAW 4 2 we needed to rework most of the API This is a step by step migration tutorial Please use the Xtext forum if you have any trouble migrating to the latest version 4 1 2 1
76. As of now you don t have to change any of these oAW Version 4 2 8 EMF Tutorial fA data genmodel X amp fs Data S lt Datamodel name EString g entity Entity B E Entity name EString 9 attribute Attribute reference EntityReference Attribute name EString type EString EntityReference name EString toMany EBoolean target Entity Figure 1 7 Structure of the genmodel You can now generate the other projects x Generate Model Code Generate Edit Code Generate Editor Code Generate Test Code Generate All Open Ecore Open GenModel a f Y Undo Mh pad amp gt Redo S b of Cut E Copy Paste Set SDO Defaults Run As Debug As Profile As Validate Team Compare With Replace With Refresh Show Properties View Figure 1 8 Generate editing projects You now have all the generated additional projects oAW Version 4 2 EMF Tutorial Package Explorer X Hierarchy E X oaw4 demo emf datamodel GS src metamodel data ecore B T S JRE System Library J25E 1 5 BA Plug in Dependencies l E META INF model ii build properties B plugin properties B plugin xml E E oaw4 demo emf datamodel edit H E oaw4 demo emf datamodel editor H E oaw4 demo emf datamodel tests Figure 1 9 Generated projects We won t look any deeper at these additional projects for now Ho
77. Attribute public void asSetter Type NameS asParameter this asInstanceVar asParameter ENDDEF INE Run the generator and open Author java The file looks almost the same since the replacements for instance variables getter and setter method names are equivalent The only difference are the parameters for setter methods They are now prefixed with the character p public void setId String plId this id pld 15 17 2 Calling Java functions as extensions More complex computations are often easier and more understandable by means of the Java programming language So the Xtend language allows to define functions by referencing a Java function The methods that should be called must be declared public static In our example we miss the declaration of packages and files are written in the root directory We now want to declare some functions that help us to compute the full package name of classes their corresponding path and the fully qualified name Create a new package oaw4 demo classic uml extend and a class Classutil In this class we define a function getPackageName that computes the full package of a Class remember that we operate on the metamodel s class named org openarchitectureware meta uml classifier Class not java lang Class package oaw4 demo classic uml extend import org openarchitectureware meta uml classifier Class import org open
78. Code Style RSA RSM profiles Java Compiler Javadoc Location Remove opendrchitectureware Select metamodel contributor Plug in Development Project References Refactoring History Enable open rchitectureWare nature Restore Defaults Apply Figure 11 1 Project properties with RSA RSM profiles added 11 3 1 Runtime Configuration At runtime you just need the org openarchitectureware rsdp adapter 4 1 0 jar You can use Eclipse s dependency mechanism from the PDE as described in the installation section on the getting started page or copy or reference the respective jar directly It doesn t matter you just have to take care that it is on the classpath 11 3 2 Workflow using profiles from plugins If you have written some Check Xtend or Xpand files and now want to execute them you have to provide the right configuration You need to configure the UML2 metamodel and a profile metamodel for each profile you used directly A typical configuration looks like this lt workflow gt lt property name umlmda profile plugin path value C winapp eclipse v3 2 UMLMDA eclipse plugins org umlmda u nl jonevone mile 2 0 0 lt initializes resourcemaps urimaps etc gt lt component class org openarchitectureware rsdp workflow RSASetup gt lt pathMapEntry gt lt alias value UMLMDA_PROFILE gt lt path value umlmda profile plugin path profiles gt lt pathMapEntry gt lt init value true gt lt compo
79. D Protected regions are generated in enabled state by default Unless you manually disable them by removing the ENABLED keyword they will always be preserved If you want the generator to generate disabled protected regions you need to add the DISABLE keyword inside the declaration PROTECT CSTART CEND ID this name DISABLE 6 5 3 10 LET ET lets you specify local variables LET expression AS variableName a sequence of statements ENDLET During the expansion of the body of the LET block the value of the expression is bound to the specified variable Note that the expression will only be evaluated once independent from the number of usages of the variable within the Let block Example LET packageName className AS fqn the fully qualified name is fqn ENDLET 6 5 3 11 ERROR The ERROR statement aborts the evaluation of the templates by throwing an xpandException with the specified message ERROR expression Note that you should use this facility very sparingly since it is better practice to check for invalid models using constraints on the metamodel and not in the templates 6 5 3 12 Comments Comments are only allowed outside of tags REM text comment oAW Version 4 2 93 Xtend Xpand Check Reference ENDREM Comments may not contain a REM tag thi
80. DEF INE A template file consists of any number of IMPORT statements followed by any number of EXTENSION statements followed by one or more DEFINE blocks called definitions 6 5 3 Statements of the Xpand language 6 5 3 1 IMPORT If you are tired of always typing the fully qualified names of your types and definitions you can import a namespace using the IMPORT statement IMPORT meta model This one imports the namespace meta model If your template contains such a statement you can use the unqualified names of all types and template files contained in that namespace This is similar to a Java import statement import meta model 6 5 3 2 EXTENSION Metamodels are typically described in a structural way graphical or hierarchical etc A shortcoming of this is that it s difficult to specify additional behaviour query operations derived properties etc Also it s a good idea not to pollute the meta model with target platform specific information e g Java type names packages getter and setter names etc Extensions provide a flexible and convenient way of defining additional features of meta classes You do this by using the Extend language See the corresponding reference documentation for details oAW Version 4 2 88 Xtend Xpand Check Reference An EXTENSION import points to the Extend file containing the required extensions EXTENSION my ExtensionFile Not
81. EBUG skipped resource exists exists skipped mode was batch only check 70 DEBUG skipped resource exists exists skipped mode was batch only check 80 DEBUG skipped resource exists exists skipped mode was batch only check 80 DEBUG skipped resource exists exists skipped mode was batch only check 90 DEBUG skipped resource exists exists skipped mode was batch only check 90 DEBUG skipped resource exists exists skipped mode was batch only check 90 DEBUG skipped resource exists exists skipped mode was batch only BUILD SUCCESSFUL Total time 1 second If there are errors they will be output as a ERROR level message 12 2 3 Implementing your own Checks 12 2 3 1 Hello World The following piece of code is the simplest check you could possibly write package org openarchitectureware recipe checks test import org openarchitectureware recipe core AtomicCheck import org openarchitectureware recipe eval EvaluationContext public class HelloWorldCheck extends AtomicCheck private static final long serialVersionUID 1L public HelloWorldCheck super hello world this check always succeeds oAW Version 4 2 145 Recipe Framework D ublic void evaluate EvaluationContext c ok A couple of notes e You can define any kind of constructor you want passing any parameters you like You have to pass at least two parameters
82. EClass name EntityReference gt lt eStructuralFeatures xsi type ecore EAttribute name name eType ecore EDataType http www eclipse org emf 2002 Ecore EString gt lt eStructuralFeatures xsi type ecore EAttribute name toMany eType ecore EDataType http www eclipse org emf 2002 Ecore EBoolean gt lt eStructuralFeatures xsi type ecore EReference name target lowerBound 1 eType Entity gt lt eClassifiers gt lt ecore EPackage gt 1 4 Generating the EMF tooling In addition to providing the Ecore meta meta model EMF also comes with support for building more or less usable editors These are generated automatically from the metamodel we just defined In order to define example models which we ll do below we have to generate these editors Also we have to generate the implementation classes for our metamodel To generate all these things we have to define a markup model that contains a number of specifics to control the generation of the various artifacts This markup model is called genmodel So we have to define the genmodel first Select the data ecore model in the explorer and right mouse click to New gt Other gt Eclipse Modelling Framework gt EMF Model Follow the following five steps note that they are also illustrated in the next figure 1 select EMF model 2 define the name 3 select the folder 4 select ecore model as source 5 press the Load button and then Fin
83. EE A RAEE A aR teas 116 5226 Identifier Le orroe oera EEEE E EE REE EE EE ates teeta seas 116 1 5 3 oting RST eaea ae n E Aa AE AE AEE ta ASN E N E EE AANER ES 117 BSA Integer Token TTT 117 PDs COMMONS ear aer EEE AE EEE EA Braces KE a E aE NE EEEE EEE NRA 117 E20 Whitespace oe iea ae a eaa a AN a eee TEA Aleta aeaa eat aiaa 118 7 5 7 Native rules Overwriting built in lexer rules sees eee ee eee 118 1 6 Th generator TTT 118 T 6 V Configuring the Generator 59747992 einne ieni E aE E aaae aR oeeie Eo eein 119 7 6 2 Generated and manual code 1 rerssgsc cece eresie eei eein eaei a ienie Eirene Ea 119 7 6 3 The different projects and artifacts sese eee 119 Aude Pimping the editor serria eee D E EE e kier TE EEEE EEE Ekaa ES EED Ek ean 121 Til ly Code Completion rae e tees Eee aE AE Ee E EE E EKE ESEE 121 EADS NAVISION nesine orne orate tae aae ata aa ae aaae 2022992 H e oaaae ta 122 TRS Outline VIEW ipren eirioes aeee p a a Ean p arata oea rap iata Asara 123 Tol A Syntax Highlighting iier einir erie aiaa eea oa ae aiaeei ies 123 TBE COOKDOOK EEEE ETT 123 7 8 1 Modeling In Multiple Files 2 0 0 eee eeecccccececececececeeeeeeeceeeeeeeeeeeeeeeeeeeeeerees 123 S UMLZ Adapter 1 1 2o s4 beter ais toisheveioidalebccssustesgidauestelessvevossaletdessiaivds a riae a as eiis ipia aiaeeiiee 125 8 1 Introduction vicete i iii r a i aee a a e i i i a 125 8 2 Installation vreta d ci eee od aei aeaa aiar deee Eea re EE ari a iae ii 125 8 3 Setting up
84. Example Model sss sese eee 14 1 8 1 The workflow definition Sirni tirsisti o eia e a bested vedens 14 1 8 2 Running the Workflow 0 45 sisscecdiestansstsepconaagetenestabechedigttawasesggeadad aa ere biii e 15 18 3 Templates 155644292 ala 5 KAH L RRIAT e ea A a a aa E E ATES 17 1 8 4 Running the generator again eee 19 1 9 Checking Constraints with the Checks Language sss sees eee eee eee 19 1 9 1 Defining the constraint seene yscsevenstantagssteceebat acti eossasbesase i eiai a E aE 19 1 9 2 Integration into the workflow Dle sese eee eee eee 19 1 10 Extensions eon pester diet aia eee EE E E EAER a E E E E eat 20 1 10 1 Expression S LT 20 1 10 2 Jaya EXtEnSi ns snini a R a a sile es 21 1 11 Integrating Recipes cssrsccsssiriecieeii iieii iiini e i e iiaeiai 23 1 11 1 Adjusting project Settings sss eee eee eee eee eee 23 1 11 2 Adapting the existing generator esse ee ee ee eee ee eee eee 23 1 11 3 Implementing the Recipes soricina ine veces E a veces iyaa a Nai 25 LALA Worktlow Inte gration 210 a iccjsvs doce avd anaana e Aa aE Ovoes 26 1 11 5 Running the Workflow and seeing the Effect sse eee 26 1 12 Transforming Models ioreciicsccieas Avecs avew seen Polat yink vanegs avers we dora Colecsdins genres E eS 27 1 12 1 Model Modifications in Java CESR pag S cSd TREO CNC ANTES ZR cR iE Ce 27 2 Xtext Tutorial site wean Aas a ee AE ea ea re EA ie ae 29 2 1 Installing the pre built tutorial sese eee 29 2 2 Tutoria
85. In our case this can be achieved by adding the oaw4 demo emf datamodel project to the plug in dependencies of oaw4 demo emf datamodel generator To do this double click the file oaw4 demo emf datamodel generator META INF MANIFEST MF The manifest editor will appear Go to the Dependencies tab and click on Add to add a new dependency In the dialog appearing choose oaw3 demo emf datamodel oAW Version 4 2 15 EMF Tutorial example data F Dependencies Required Plug ins Specify the list of plug ins required for the operation of this plug in gt gt org openarchitectureware core check C 5 org openarchitectureware core emftools LC gt org openarchitectureware core xpand2 Remove U D foan Plug in Selection Select a Plug in datamod oaw4 demo emf datamodel 1 0 0 Total 3 Figure 1 15 Add metamodel dependency Do not forget to save the manifest file Now you can run the workflow from within Eclipse oAW Version 4 2 16 EMF Tutorial Package Explorer X ES w oaw4 demo emf datamodel ea oaw demo emf datamodel generator src example data B log4i properties D ann p B workfloy New _ _ ka BA JRE System Open F3 z Plug in Depe Open With gt ae META INF showin Alt Shift w gt 7 MANIFE and build proper Copy Ctrl C Paste CIN 3 Delete Delete Build Path E Refactor Alt Sh
86. MI xmlns xsi http www w3 org 2001 XMLSchema instance xmlns ecore http www eclipse org emf 2002 Ecore name data nsURI http www openarchitectureware org oaw4 demo emf datamodel nsPrefix data gt lt eClassifiers xsi type ecore EClass name DataModel gt lt eStructuralFeatures xsi type ecore EAttribute name name eType ecore EDataType http www eclipse org emf 2002 Ecore EString gt lt eStructuralFeatures xsi type ecore EReference name entity upperBound 1 eType Entity containment true gt lt eClassifiers gt lt eClassifiers xsi type ecore EClass name Entity gt lt eStructuralFeatures xsi type ecore EAttribute name name eType ecore EDataType http www eclipse org emf 2002 Ecore EString gt lt eStructuralFeatures xsi type ecore EReference name attribute lowerBound 1 upperBound 1 eType Attribute containment true gt lt eStructuralFeatures xsi type ecore EReference name reference upperBound 1 eType EntityReference containment true gt lt eClassifiers gt lt eClassifiers xsi type ecore EClass name Attribute gt lt eStructuralFeatures xsi type ecore EAttribute name name eType ecore EDataType http www eclipse org emf 2002 Ecore EString gt lt eStructuralFeatures xsi type ecore EAttribute name type eType ecore EDataType http www eclipse org emf 2002 Ecore EString gt lt eClassifiers gt lt eClassifiers xsi type ecore
87. Model gt lt metaModelFile value metamodel2 ecore gt lt metaModel gt lt invoke value my example Trafo transform inputSlot gt lt outputSlot value transformedModel gt lt value my Advices my Advices2 gt lt component gt 6 4 10 3 Model to Model transformation with Xtend This example uses Eclipse EMF as the basis for model to model transformations It builds on the emfExample documented elsewhere Please read and install the emfExample first The idea in this example is to transform the data model introduced in the EMF example into itself This might seem boring but the example is in fact quite illustrative 6 4 10 4 Workflow By now you should know the role and structure of workflow files Therefore the interesting aspect of the workflow file below is the XtendComponent lt workflow gt lt property file workflow properties gt lt component class oaw xtend XtendComponent gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelPackage value data DataPackage gt lt metaModel gt lt invoke value test Trafo duplicate rootElement gt lt outputSlot value newModel gt lt component gt lt workflow gt As usual we have to define the metamodel that should be used and since we want to transform a data model into a data model we need to specify only the data DataPackage as the metamodel We hen specify which function to invoke for the tran
88. ModelElement Note that you would need to import the namespace of the template file if there is one For instance if the template file resides in the java package my templates there are two alternatives You could either write IMPORT my templates EXPAND TemplateFile definitionName FOR myModelElement or EXPAND my templates TemplateFile definitionName FOR myModelElement 6 5 3 6 FOR vs FOREACH If FOR or FOREACH is omitted the other template is called FOR this EXPAND TemplateFile definitionName equals EXPAND TemplateFile definitionName FOR this If For is specified the definition is executed for the result of the target expression EXPAND myDef FOR entity If FOREACH is specified the target expression must evaluate to a collection type The other definition is executed for each element of that collection EXPAND myDef FOREACH entity allAttributes 6 5 3 6 1 Specifying a Separator If a definition is to be expanded rorEaAcH element of the target expression it s possible to specify a SEPARATOR expression EXPAND paramTypeAndName FOREACH params SEPARATOR The result of the separator expression will be written to the output between each evaluation of the target definition not after each one but rather only in between two elements This comes in handy for things such as comma se
89. N E EEE AIEE ESSAS E EE ESTER 108 6 6 13 oaw SSEAELSPLOPSLEY ssi sdedectecens cadens cove E E cece vices EEEE evens seine goin bee s sete 108 9 5 Voted steele EE tedees eRe cd cht E E EIE ceacea bles sles cueede ck cede adedens 108 6 6 19 oct Eae Ad VA CEC OME SHE so05 owe cisco S E ead cae dad dew an A esd sate eases cuneate 108 6 6 16 EL PDS LANDED ON essre deiwe n ceciedise en s taeite vais cies onions ceive aiedadisie viele vie EESE ae delve vated S 109 6 6 17 KPANAZ E L oe ssinsVadeweds vase ae teinie do E SEEE wuts paiswee teen es SEN EE EEES E EEOSE onl 109 doptextReterence from OA W 4 2 TTT 110 B TN Introduction ee oeo oeseri ia anaa e aae aaa bebe gon a aa E ai a aa a E eanais ai 110 Hes EL ET Te tassels tere ESET E ET E EEE E E E EA taut N AE E A RAE EE rons 110 Tor Getting started wiee tro E E E E EE EE A E A i E O E E A AE E Noa 110 TA The Grammar Lan Su age gorien sis oy bebe eE A EE ERE E AE EA ERE E ERE vans 110 AASV Example not ea a a i E RE A E Ee AE R ERKE R E 111 7 4 2 How the parsers work in general eee eee 112 oAW Version 4 2 v openArchitectureW are User Guide TAS Type Rules scisnieceeis eee eee betel ede wee Wiel ee ee ee ade 112 TAA Bram Rule minieren iniit le dek secede dean es soda re degsue ule desevededecsihs Sousa iih 114 TAS Stems Rule reisien i seesedededsuns Wisk Mosivdeotshs Wein E Ea 115 Ted Lezer RUlE Sioe ieinu iiia ee S TTT A aiea a ER odes aes 116 TSI Keyword N Le 2 rysie iaren ii atita ARE EAE RA
90. NE Entity FOR data Entity FILE name java public class name FOREACH attribute AS a bad practice private a type a name ENDFOREACH ENDF ILE ENDDEF INE We have to extend the workflow oaw file in order to use the template just written lt xml version 1 0 encoding windows 1252 gt lt workflow gt lt property file workflow properties gt lt component id xmiParser class org openarchitectureware emf XmiReader gt lt component gt First we clean up the directory where we want to put the generated code lt component id dirCleaner class org openarchitectureware workflow common DirectoryCleaner gt lt directories value srcGenPath gt lt component gt Then we start the generator component It s configuration is slightly involved lt component id generator class org openarchitectureware xpand2 Generator gt First of all you have to define the meta model In our case we use the EmfMet aModel since we want to work with EMF models Also you have to specific the class name of the EMF package that represents that metamodel It must be on the classpath lt metaModel id mm class org openarchitectureware type emf EmfMetaModel gt lt metaModelPackage value data DataPackage gt lt metaModel gt Then you have to define the entry statement for Xpand Knowing that the model slot co
91. NF JE MANIFEST MF B build properties C3 yay Figure 2 4 Package explorer 2 3 2 Defining the grammar The wizard created and automatically opened an Xtext grammar file myds1 xtxt Therein we have to specify the grammar for our textual DSL Using Xtext s grammar language one defines the abstract syntax i e the meta model and the conrete syntax of the the language This allows for very short turn arounds when refactoring and or improving the DSL T mydsl xtxt 53 N DI B outline Ph SModel types Type Ctyp ype O Trae Type Datatype Entity G Type G Datatype Datatype G Entity datatype name ID Feature SEntity entity name ID Cfeatures Feature gt Feature type TypelID name ID Figure 2 5 Create new Ecore model oAW Version 4 2 32 Xtext Tutorial The root element of all expressions made in our new DSL is called a Model The is the name of the parser rule which is invoked for each textual model to be parsed The parser rule Model creates and returns an instance of the corresponding meta model element also called Model A Model just consists of a list of types rule Type In the model the list of types can be accessed through the reference types When it comes to code generation one can evaluate expressions such as myModel types to get the types of a model A Type corresponds to an abstract meta type because it just refers to two other rules wi
92. O extends org openarchitectureware meta uml classifier Class 15 8 2 Metamappings By now the generator will not know that the stereotype lt lt Entity gt gt has to be mapped to the metaclass oaw4 demo classic uml meta Entity By default these elements are mapped to their UML base classes in case of Entity this is Class To map stereotypes to metaclasses a xml file has to be created called the metamapping file Create the file met amappings xm1 in your source folder lt xml version 1 0 encoding UTF 8 gt lt DOCTYPE MetaMap SYSTEM http www openarchitectureware org dtds metamap dtd gt lt MetaMap gt lt Mapping gt lt Map gt Entity lt Map gt lt To gt oaw4 demo classic uml meta Entity lt To gt lt Mapping gt lt Mapping gt lt Map gt DAO lt Map gt lt To gt oaw4 demo classic uml meta DAO lt To gt lt Mapping gt lt Mapping gt lt Map gt Key lt Map gt lt To gt oaw4 demo classic uml meta Key lt To gt lt Mapping gt lt MetaMap gt 15 9 Log4j configuration Later when running the generator you would like to see some output messages Therefore you have to define a log4j properties Create this file in the source folder Set root logger level to INFO and its only appender to Al oAW Version 4 2 169 Classic UML Tutorial log4j rootLogger INFO Al Al is set to be a ConsoleAppender log4j appender Al org apache log4j ConsoleAppende
93. RN ignoring node 68759 ownedMember cannot coerce to ModelElement 3314 WARN ignoring node 70438 ownedMember cannot coerce to ModelElement 3324 WARN ignoring node 65945 ownedMember cannot coerce to ModelElement 3334 WARN ignoring node 65952 ownedMember cannot coerce to ModelElement 3334 WARN ignoring node 65959 ownedMember cannot coerce to ModelElement 3334 WARN ignoring node 65966 ownedMember cannot coerce to ModelElement 3405 INFO Design loaded in 0 101s 3405 INFO 3405 INFO Applying tool specific design modifications 3415 INFO Design modified in 0 01s 3415 INFO 3415 INFO Instantiating metamodel 3485 WARN lt lt Model gt gt no Name 27940994 ignoring value for nonexisting property Documentation Author Karsten oAW Version 4 2 173 Classic UML Tutorial Created 27 02 06 08 47 EE IN Comment 3525 INFO Metamodel instantiated in 0 1s 3525 INFO 2025 INFO Instantiated design in 2 9545 3525 INFO 3525 INFO MetaModel Summary 3525 INFO 3525 INFO 3525 INFO 3x Association org openarchitectureware meta uml classifier Association 3525 INFO 6x AssociationEnd org openarchitectureware meta uml classifier AssociationEnd 3525 INFO 4x Attribute org openarchitectureware meta uml classifier Attribute 3525 INFO x DAO oaw4 demo classic uml meta DAO 3525 INFO 4x Entity oaw4 demo classic uml meta Entity 3525 INFO 4x Key oaw4 demo classic uml meta Key 3525 INFO x M
94. String prefix This one gets the grammarElement which should be completed passed in as the first parameter an xtext Element can be of the following types x xtext RuleName a call to a lexer rule e g ID xtext Keyword x xtext Assignment Overwrite rules are as follows 1 if the first one returns null for a given xtext Assignment or does not exist the second one ng is called 2 if the second one returns null for a given xtext Keyword or does not exist a default keyword oAW Version 4 2 121 Xtext Reference from oAW 4 2 bs proposal will be added Note that only propals with wich match case in sensitive the current prefix will be proposed in the editor S 7 7 2 Navigation The implementation for the navigation actions is implemented via extensions too As for Code completion the same pattern applies There is a GenNavigation ext extension file in the src gen folder which can be overwritten or specialized using the Navigation ext file in the src folder reexporting the generated extensions There are two different Actions supported by Xtext 7 7 2 1 Find References This action ca be invoked via CTRL SHIFT G or use the corresponding action int context menu The default implementation returns the crossreferences for a modelelement The signature to overwrite specialize is List UIContentNode findReferences String s Object grammarelement Object element
95. ToLowerCase false gt lt met aModel gt lt checkFile value java AssociationChecks gt lt expression value me getElements ModelElement gt lt abortOnError value true gt lt component gt Also the constraint checker has to know which metamodel it should use It is the same configuration as for the Generator component 9 The checkFile property specifies the qualified name of the check file Finally the expression property defines for which elements to constraints should be applied In our case we select all elements in the MetaEnvironment However for our special case it would be satisfactory to select only all elements of type AssociationEnd For larger projects it could be of advantage to select the right subset of elements for improving performance 15 19 5 Testing the constraints Start the generator The generator should run without complaining because all constraints are fulfilled in the example model for now Now open the model we will change the model in a way that both constraints are not fulfilled First edit the association between Book and Author Take the association end named author and remove the name Set the navigable flag to false for the opposite end named writtenBooks Save the model and re run the generator The generator now produces the expected messages and stops execution because there is one constraint error and one warning 4316 INFO Starting org openarchitectureware
96. ToModel baseDir model xmi 5 3 1 1 Components The wired up object graph consists of so called components A workflow component is a special kind of a component A component is declared by an XML element The name represents the property of the parent component holding this component Example lt component class MyBean gt lt bean class MyBean gt lt component gt The Java class MyBean needs to have a corresponding property accessor E g public class MyBean public void setBean MyBean b bean b There are currently the following possibilities for declaring the property accessors 5 3 1 1 1 Accessor methods As we have seen one possibility for declaring a dependency is to declare a corresponding setter Method public void set lt propertyname gt lt PropertyType gt e If you want to set multiple multiple values for the same property you should define an adder method public void add lt propertyname gt lt PropertyType gt e In some cases you may want to have key value pairs specified This is done by providing the following method public void put Object k Object v 5 3 1 2 Component creation The corresponding Java class specified using the class attribute needs to have a default constructor declared If the class attribute is omitted the Java class determined from the accessor method will be used For the preceding ex
97. a The Key attribute is id of type String oAW Version 4 2 167 Classic UML Tutorial b The library has a string attribute name 12 Draw an association from Library to Copy a The association end at class Library is named owner is navigable the multiplicity is b The association end at class Book is named ownedBook is navigable and the multiplicity is Save your model packed format in the model folder of your project and give the file the name AuthorBookExampleMD11 mdzip The tool adapter will automatically recognize that it is zipped and read the appropriate ZIP entry Create a subfolder model mdi1 From the profiles directory of your MagicDraw installation copy the UML_Standard_Profile xml to there 15 8 Defining the metamodel Models are instances of a Metamodel In order to get openArchitectureWare to do something useful it needs to know the used metamodel Using oAW Classic the metamodel is implemented by metaclasses In UML they are represented in the model by stereotypes The recently defined model already uses the stereotypes Dao Entity and Key Entities are some kind of business objects which have some attributes They are represented in UML as classes Exactly one attribute is a special one a Key attribute Daos are classes which manage Entities We want to express this relationship by using a dependency from pao to Entity in our model In UML this metamodel looks like this subsets Requ
98. a type a name public void a setterName a type value this a name value public a type a getterName return this a name ENDFOREACH ENDF ILE ENDDEF INE For completeness the following illustration shows the resulting directory and file structure oAW Version 4 2 22 EMF Tutorial H S T Hierarchy E E oaw4 demo emf datamodel 4 3 oaw4 demo emf datamodel generator GS src 8 datamodel w J EntityHelper java B datamodel generator util J Templateutils java D util ext templates B java ext D Root xpt checks chk example data log4j properties B workflow oaw workflow properties S JRE System Library jre1 5 0_11 MA Plug in Dependencies gt META INF t MANIFEST MF wal J gt src gen E PersonImplementation java YehicleImplementation java lard build properties Figure 1 17 What has happened so far 1 11 Integrating Recipes Let s assume we wanted to allow developers to add their own business logic to the entites maybe adding a couple of derived properties In that case we have to integrate the generated code with manually written fragments Let s further assume that you just like me don t like protected regions because the end up in versioning chaos In such case you might want to let the generator create a base class that contains all generated aspec
99. ae isMultiple amp amp ae isNavigable ENDDEF INE DEFINE ToOneAccessorMethods FOR AssociationEnd public void asSetter Class fqn asParameter this asInstanceVar asParameter public Class fqn asGetter return this asInstanceVar ENDDEF INE DEFINE ToManyAccessorMethods FOR AssociationEnd public void add NameS toFirstUpper Class fqn asParameter this asInstanceVar add asParameter public void remove NameS toFirstUpper Class fqn asParameter this asInstanceVar remove asParameter public iterator asGetter return this asInstanceVar iterator ENDDEF INE At first we see that this template uses both extensions NamingConventions and Associations Next a template ReferenceVariables is declared The template makes use of a FOREACH loop of a different kind than we saw before One more specific thing here is the statement oAW Version 4 2 181 Classic UML Tutorial FOREACH AssociationEnd Opposite select ae ae isNavigable This returns all navigable opposite end of each association end a class has The body of the loop declares a reference variable for an association For both alternatives to one and to many the function fan the one defined for association ends is called to determine the right type In our example
100. agePath NameS java package packageName public class Name IF hasSuperClass extends SuperClass fqn ENDIF implements java io Serializable Once again run the generator and refresh your src gen folder Now the classes are generated in the expected directory structure Package Explorer X Hierarchy Navigator a g src 8 oaw4 demo classic umI meta log4j properties metamappings xml P workflow oaw workflow properties lt model lt HS magicdraw mdi1 B UML_Standard_Profile xml B AuthorBookExampleMD11 mdzip amp templates D Root xpt BA JRE System Library jre1 5 0_07 BA Plug in Dependencies amp META INF mj D H oAW Version 4 2 179 Classic UML Tutorial The generated classes now contain the correct package statement package oaw4 demo classic uml entity public class Author implements java io Serializable 15 18 Working with associations In the model we have defined some associations of different kind In the next step we evaluate these associations and create references accessor methods and modification methods As you can see there exists a m n association between Author and Book There exists an association from Library to Copy with the multiplicity 1 n The association from Book to Copy is not navigable These associations must be handled differently Ordinary associations in UML consist of three elements Two association ends and one
101. ameter multiplicityMin int 1 multiplicityMaxint 1 Figure 14 11 Nodes Basic Activities oAW Version 4 2 Classic Reference Fundamental Nodes Behavior from org openarchkectureware meta umi MbdelElement from org openarchiecturew are meta uml Ss documentation String A readOnly boolean false activity Action from org openarchkectureware meta uml2 activ ty Figure 14 12 Fundamental Nodes Fundamental Groups lt lt library gt gt Element from org openarchkectureware core meta core readOnly boolean false activity activity 7 0 1 containedNode subGroup superGroup lt gt subGroup Figure 14 13 Fundamental Groups oAW Version 4 2 162 Classic Reference MbdelElement from org openarchaecturew are meta um documentation String ObjectFlow Figure 14 14 Flows oAW Version 4 2 163 Chapter 15 Classic UML Tutorial 15 1 Introduction This example shows the usage of openArchitectureWare 4 with integration of an UML tool In openArchitectureWare 4 we call this Classic style as the underlying metamodel has to be the Classic UML metamodel that was introduced by oAW 3 For the example Magic Draw 11 5 Community Edition is used but the example can easily be adapted to any supported UML tool It is strongly recommended to work through this tutorial with MagicDraw to
102. ample we could write lt component class MyBean gt lt bean gt lt component gt because the setter method uses the MyBean type as its parameter type This is especially useful for more complex configurations of workflow components Note that we will probably add factory support in the future oAW Version 4 2 58 Workflow Reference 5 3 1 3 References A component can have an attribute id If this is the case we can refer to this component throughout the following workflow configuration Example lt workflow gt lt component class my Checker gt lt metaModel id mm class my MetaModel metaModelPackage org oaw metamodel gt lt component gt lt component class my Generator gt lt metaModel idRef mm gt lt component gt lt workflow gt In this example an object with the id mm an instance of my MetaModel is first declared and then referenced using the attribute idRef Note that this object will only be instantiated once and then reused It is not allowed to specify any other attributes besides idRef for object references 5 3 1 4 Simple Parameters Elements with only one attribute value are simple parameters Simple parameters may not have any child elements Example lt workflow gt lt component class my Checker myParam foo gt lt anotherParam value bar gt lt component gt As you can see there are two ways to specify a simpl
103. anei o ei E E a Ea ee iis EREA OE ei E bade 156 1422 ASSOCIATIONS cisecccccdbetlecets ewes 48 2914 a oea a E a KE E a a aves A a aa a H LET ae 157 14 3 Class Ty pes Te TTT 157 IE E EE ETS TTT 158 145 Op rations and Att DUtes TTT 158 14 6 State Charts inanitia deeds sean se e iia a a e i a i ti a a a 159 T T States Maim ohuen eera ene ee eirin aa Ea a aerie o EEEo eian oian decd 159 14 8 State Vertex SUbtyp S i see YK 992 K 294 iiien i iier eii er i Ari EEE ETE EEEE E a 160 Ie LST 160 ENI L oy Sones Scanned Saba oe chnny ceeded coca noedebiiens ob cada evegton yo dvadhobece oube da ctasgesetoouse suaanehdaeteacen deans 161 14 11 Nodes Basic ACtiviticS Aarona aoa EE EEA TEE LEESE TS EEEE AA aA 161 14 122 Fundamental Nodes srianan neiii i lores AN EEN E E ERE N ae EEEREN E E N eae 162 14 13 F nda ment l Groups en onien aia i e EEE EEEE E AEE EE AN E Mea heen eas 162 1414 Se 163 15 1 Configure oAW Classic Metamodel enren torien nnana a e a i VOTE i 164 15 2 Example Modelnr nonsi rea E NEEE ENE E ON E TE NE EE AVEA 165 15 3 Creatine the tutorial project erri sree rninn eE eE E A EAT E E E V E AVE a 165 15 4 Defining plug in dependencies for OAW Classic sss eee eee 166 15 5 R KET Tels TTT 166 15 6 Putorial Metamodel a ennei ii dees TEREORA EA EEE EE RAE OR EEEE EE 168 16 1 Editing a metamodel with the EMFatic editor sss sees 189 8 1 Model example esar ieee ae hei EERE a ee eh Oe Geek eA aes ee eles 196 oAW Version 4
104. architectureware meta uml classifier Package SER SHL TSTST Glia sisiU tame public static String getPackageName Class cls SENING ESSE Ws for Package pck cls Package pck null pck pck SuperPackage oAW Version 4 2 178 Classic UML Tutorial reculi pek Names O a result lengetem St T 9 Wl 5 return result We declare this function in NamingConventions ext and two more functions that use it Add these function declarations String packageName Class cls JAVA oaw4 demo classic uml extend ClassUtil getPackageName org openarchitectureware meta uml classifier Class String packagePath Class cls packageName cls replaceAll Sitieaine sem Class ceils packageName cls length gt 0 packageName cls cls NameS cls NameS The additional functions are used to compute the path to files based on a class and to get the full qualified name of a class We want to make use of these functions to declare the package compute the desired file path and to extend from the super class if a class has one in our example model this is not the case yet If no super class exists the Bean class should declare to implement the serializable interface Open the gavaBean xpt template file and modify it like follows IMPORT org openarchitectureware meta uml classifier IMPORT java EXTENSION java NamingConventions DEFINE BeanClass FOR Class FILE pack
105. ated for all elements in a collection The forall operation allows specifying a Boolean expression which must be true for all objects in a collection in order for the forall operation to return true collection forAll v boolean expression with v The result of forA11 is true if boolean expression with v is true for all the elements contained in a collection If boolean expression with v IS false for one or more of the elements in the collection then the forAll expression evaluates to false Example 3 4 500 forAll i i lt 10 evaluates to false 500 lt 5 is false 6 3 2 7 exists Often you will need to know whether there is at least one element in a collection for which a boolean is true The exists operation allows you to specify a Boolean expression which must be true for at least one object in a collection collection exists v boolean expression with v The result of the exists operation is true if boolean expression with v iS true for at least one element of collection If the boolean expression with v is false for all elements in collection then the complete expression evaluates to false Example oAW Version 4 2 73 Xtend Xpand Check Reference 3 4 500 exists i i lt 10 evaluates to true e g 3 lt 5 is true 6 3 2 8 sortBy If you want to sort a list of elements you can use the higher order function sort By The list you invoke the sort By oper
106. atesite milestone site xml Go to the project s homepage and find the current location if either of the sites don t work Restart your Eclipse workbench when Eclipse asks you to do so 10 3 Setting up Eclipse You need to import one project into your workspace It is called org openarchitectureware adapter gmf2 You can do that using the import wizard Do a right click in the Project Explorer and choose Import Now select Plug ins and Fragments from the Plug in development section Import the bundle as a project with source folders 10 4 Setting up GMF 10 4 1 Setting validation options Next open your gmfgen file and set the following properties in the your GenDiagram Element e Set Validation Decorators in the section Diagram to true e Set Validation Enabled in the section Diagram to org openarchitectureware adapter gmf2 templates oAW Version 4 2 135 GMF2 Adapter Resource Set E L platform resource sample gmf model My gmFgen gt Gen Editor Generator demo diagram Eee ae Gen Diagram StatemachineEditPart Gen Plugin My Plugin gt Gen Editor View demo diagram part lt gt Gen Navigator MyNavigatorContentProvider gt Gen Diagram Updater MyDiagramUpdater lt gt Property Sheet demo diagram sheet Selection Parent List Tree Table Tree with Columns fai Problems Javadoc B Declaration E Properties 53 GMF Dashboard l Error Leg Search E History Prope
107. ation on is sorted by the results of the given expression Example myListOfEntity sortBy entity entity name In the example the list of entities is sorted by the name of the entities Note that there is no such comparable type in oaw If the values returned from the expression are instances of java util Comparable the compareTo method is used otherwise toString is invoked and the the result is used More Examples the following expression return t rue ME ass WAN Is OIE Se AV T AAA BB C sortBy ele length C BB AAA Sy oy ly 2 Pe Sereby ele 44 27 375 5 3 1 2 sortBy ele 2 e 5 3 2 1 6 3 3 If expression There are two different flavours of conditional expressions The first one is the so called if expression Syntax condition thenExpression elseExpression Example name null name unknown 6 3 4 switch expression The other one is called switch expression Syntax switch expression case expression thenExpression default catchAllExpression The default part is mandatory because switch is an expression therefore it needs to evaluate to something in any case Example switch person name case Hansen Du kanns platt schnacken default Du kanns mi nech verstohn There is an abbreviation for Boolean expressions since 4 1 2 oAW Version 4 2 74 Xtend Xpand Chec
108. ave to explain to the checker what meta meta model and which meta model we use lt metaModel id mm class org openarchitectureware type emf EmfMetaModel gt lt metaModelPackage value data DataPackage gt lt metaModel gt We then have to provide the checks file The component tries to load the file by appending chk to the name and searching the classpath that s why it has to be located in the classpath lt checkFile value checks gt Finally we have to tell the engine on which part of the model the checks should work In general you can use the lt expressionvalue gt element to define an arbitrary expression on slot contents For our purpose where we want to use the complete EMF data structure in the model slot we can use the shortcut emfAllChildrenSlot property which returns the complete subtree below a specific slot s content element including the slot content element itself lt emfAllChildrenSlot value model gt lt component gt Running the workflow produces an error in case the length of the name is not greater than one Again it makes sense to add the skiponError true to those subsequent component invocations that need to be skipped in case the constraint check found errors typically code generators or transformers 1 10 Extensions It is often the case that you need additional properties in the templates these properties should not be added to the
109. aw 11 5 or above can do that this tool MD11 5 is also the one we tested the uml2ecore utility with Note that we do not use any profiles in the uml2ecore utiliy Although using profiles might make the metamodel a bit more expressive we decided not to use a specific profile to reduce the potential for compatibility problems with the various tools 13 4 Setting up your meta model project You should first create a new Generator project select File gt New gt Other gt openArchitectureWare Generator Project Then open your UML2 tool of choice we ll use MagicDraw here and draw a class diagram that resembles your metamodel Here s the one we ve drawn as an example for this document oAW Version 4 2 150 UML2Ecore Reference PrimitiveTy Figure 13 1 UML2Ecore sample metamodel class diagram This is the usual meta model for entities and such Nothing special Also the name of the model defines the name of the ecore metamodel here s the MagicDraw tree view to illustrate this B Contain a Vererbu SH Diagra lt gt Erweiter Containment B aum d g x E entitymm bee 7 Beziehungen E UML Standard Profile UML_Standard_Profile xml E Attribute B Entity E Model 7 Named PrimitiveT ype ES fo ol Figure 13 2 UML2Ecore sample metamodel MagicDraw containment tree You now have to save export this model in EclipseUML2 format In MagicDraw you do this by selecting File gt
110. c String getName return this name jollelake Ayenicl Gee wel sterner atl 4 thars Ce T public void setName String name this name name 15 17 Using Extensions A very powerful new feature of openArchitectureWare 4 are extensions With extensions the Xpand template engine can be extended with functions without the need to modify the metamodel LA very common use of extensions are the use of naming conventions navigation computation of package path and filenames for artifacts etc openArchitectureWare extensions are declared in files ending with ext The declaration of extension functions can be by means of oAW expressions or by calling Java functions The latter have to be declared public and static TODO Make correct references to other chapters We will not cover the syntax of expressions very deep so if you are interested to get more information look at the reference manuals r25_extendReference pdf and r10_expressionsReference pdf Also in the other tutorials you can see more examples for the usage of expressions 15 17 1 Declaring functions with the Xtend language For our example we want to use extensions to introduce some naming conventions for instance variables parameters and the computation of the package and path for classes Now create a file NamingConventions ext in the templates java folder In this extension we declare some functions that are helpful for name conversions 2 import org
111. ced from all other textual languages that are based on the expressions framework 6 4 1 Extend files An extend file must reside in the Java class path of the used execution context Additionally it s file extension must be ext Let s have a look at an extend file import my metamodel extension other ExtensionFile Documentation ey anExpressionExtension String stringParam doingStuff with stringParam H java extensions are just mappings ah String aJavaExtension String param JAVA my JavaClass staticMethod java lang String f The example shows the following statements 1 import statements 2 extension import statements 3 expression or java extensions 6 4 2 Comments We have single and multi line comments The syntax for single line comments is my comment Multi line comments are written like this My multi line comment 6 4 3 Import Statements Using the import statement one can import name spaces of different types see expressions framework reference documentation oAW Version 4 2 77 Xtend Xpand Check Reference Syntax is import my imported namespace Extend does not support static imports or any similar concept Therefore the following is incorrect syntax import my imported namespace WRONG import my Type WRONG 6 4 4 Extension Import Statement You can import another exten
112. check CheckComponent 4667 ERROR Workflow interrupted Reason Errors during validation 4667 WARN Book gt Author Not navigable association ends should have no role name lt lt AssociationEnd gt gt writtenBook 4667 ERROR Author gt Book Navigable association ends must have a role name lt lt AssociationEnd gt gt 15 20 Further development of this tutorial This tutorial is not finished I plan to extend it to show more basic things about oAW usage If you have any suggestions let me know them Some features that will be handled in the future are e Extending the metamodel manually 3 Itis possible to declare the used metamodel once and reference it the second time oAW Version 4 2 185 Classic UML Tutorial e Usage of MMUtil functions in metamodel classes e Generating the metaclasses with the Metamodel Generator e Demonstration of some oAW expression language features e g collection filter list operations oAW Version 4 2 186 Part Ill Samples Chapter 16 Using the Emfatic Ecore Editor 16 1 Introduction Metamodelling based on EMF s tree views is not a very good solution A better solution is a textual representation for Ecore models The IBM Emfatic plugin provides this support 16 2 Installation Install the Emfatic plugins from http www alphaworks ibm com tech emfatic 16 3 Working with Emfatic If you already have an ecore file such as our examples data ecore you can righ
113. cify the advice s component class to be the advice component and use the special property adviceTarget to identify the target component lt workflow gt lt cartridge file workflow oaw gt lt component adviceTarget generator class oaw xpand2 GeneratorAdvice gt lt advices value templates Advices gt lt component gt lt workflow gt 5 3 3 Invoking a workflow If you have described your generator process in a workflow file you might want to run it There are different possibilities for doing so 5 3 3 1 Starting the WorkflowRunner The class org openarchitectureware workflow WorkflowRunner is the main entry point if you want to run the workflow from the command line Take a look at the following example java org openarch WorkflowRunner path workflow oaw You can override properties using the p option java org openarch WorkflowRunner pbasedir base path workflow oaw 5 3 3 2 Starting with Ant We also have an Ant task Here s an example lt target name generate gt lt taskdef name workflow classname org openarchitectureware workflow ant WorkflowAntTask gt lt workflow file path workflow oaw gt lt param name baseDir value base gt lt workflow gt lt target gt The Workflow ant task extends the Java ant task Therefore you have all the properties known from that task classpath etc 5 3 3 3 Starting from you own code You ca
114. ckage statemachine abstract class Named attr String name class State extends AbstractState val Action entryAction val Action exitAction class StartState extends AbstractState oAW Version 4 2 190 EMF State Machine class StopState extends AbstractState class Transition extends Named ref AbstractState 1 target val Action action ref Event event class Action extends Named class Event extends Named class CompositeEvent extends Event val Event children class StateMachine extends Named val AbstractState states val Event events abstract class AbstractState extends Named wadi THT IT T e oy From the ecore file you have to generate the implementation classes as usual with EMF 17 4 Example Statemachine In the caw4 demo emf statemachine xample src folder you can find an xample statemachin file that contains a simple example state machine You can view it as an EMF tree view after generating the EMF editors To generate code from it run the example oaw workflow file right next to it It looks as follows lt workflow gt lt cartridge file workflow oaw gt lt modelFile value example statemachine gt lt srcGenPath value srce gen gt lt appProject value oaw4 demo emf statemachine example gt lt srcPath value man srec gt lt cartridge gt lt workflow gt As you can see it only
115. contained in Model s reference types which is of type Entity typeSelect Entity The definition javaBean is declared for elements of type Entity Therein we open a file lt lt FILE The path name of the file is defined through an expression In this case it corresponds to the name of the entity suffixed with java It s going to be generated into the src gen directory directly All text contained between lt lt FILE gt gt and lt lt ENDFILE gt gt will go to the new file Xpand provides control statements FOR IF ELSEIF as well as evaluation of expression in order to create the desired code See the core languages reference documentation for details oAW Version 4 2 40 Xtext Tutorial 2 6 Installing everything into Eclipse Now we ve defined a DSL and a corresponding Generator We don t need to use it in Eclipse you can run the generator from ant maven command line etc as well we ll now show you how to install everything into Eclipse in order to start a new project based on your DSL and generator Right click on any project in the navigator view Choose export e008 Java Eclipse r O 8H G6 3 e6 gt iS my dsl gt 2 my dsl editor gt mw New gt Open in New Window Show In X W L Copy 38C Copy Qualified Name 5 Paste V X Delete Build Path K Source KES b Refactor XST K s Import o Refresh FS Close Project Figure 2
116. cts not in the original collection it is not a sub collection we can use a collect operation The collect operation uses the same syntax as the select and reject and is written like this collection collect v expression with v collect again iterates over the target collection and evaluates the given expression on each element In contrast to select the evaluation result is collected in a list When an iteration is finished the list with all results is returned Example oAW Version 4 2 72 Xtend Xpand Check Reference namedElements collect ne ne name returns a list of strings 6 3 2 5 Shorthand for collect and more than that As navigation through many objects is very common there is a shorthand notation for collect that makes the expressions more readable Instead of self employee collect ele birthdate one can also write self employee birthdate In general when a property is applied to a collection of Objects it will automatically be interpreted as a collect over the members of the collection with the specified property The syntax is a shorthand for collect if the feature does not return a collection itself But sometimes we have the following self buildings rooms windows returns a list of windows This syntax works but one cannot express it using the collect operation in an easy way 6 3 2 6 forall Often a boolean expression has to be evalu
117. d a aa aaa Lad a eari ies tiat 108 6 16 Operations oes poteo tipene nton ai aiea ae ae LU lucehegt beers at ataa eaea eno tioi 108 GUE Properties prr banero r a a aea ea TTT 109 0 18 le 109 6 19 K aT S T 109 6 20 Operations 2iie pein vested Wek eda foeebens E a a se sdela ess Means a aaa a ESNEA 109 6 21 Properties oni Petes Sestaen E EE se E E A E e i oud dive aude deden Sebel yeaa 109 13 1 UML2Ecore Cartridge properties 2 0 0 0 siirinsesi iniii iiini iniiaiee ea 153 14 1 Available UML tool adapters cesses resent ERRER 155 oAW Version 4 2 Xil Part I Getting Started Chapter 1 EMF Tutorial This example uses Eclipse EMF as the basis for code generation One of the essential new features of oAW4 is EMF support While not all aspects of EMF as good and nice to use as one would wish the large amount of available 3rd party tools makes EMF a good basis Specifically better tools for building EMF metamodels are on the horizon already To get a deeper understanding of EMF we recommend that you first read the EMF tutorial at s http www 128 ibm com developerworks library os ecemf1 s http www 128 ibm com developerworks library os ecemf2 s http www 128 ibm com developerworks library os ecemf3 You can also run the tutorial without completely understanding EMF but the tutorial might feel unnecessarily complex 1 1 Installing the pre built tutorial You need to have openArchitectureWare 4 2 instal
118. d file using the extension statement The syntax is extension fully qualified ExtensionFileName Note that no file extension ext is specified 6 4 4 1 Reexporting Extensions If you want to export extensions from another extension file together with your local extensions you can add the keyword reexport to the end of the respective extension import statement extension fully qualified ExtensionFileName reexport 6 4 5 Extensions The syntax of a simple expression extension is as follows ReturnType extensionName ParamTypel paramNamel ParamType2 expression using params Example String getterName NamedElement ele get tele name firstUpper 6 4 5 1 Extension Invocation There are two different ways of how to invoke an extension It can be invoked like a function getterName myNamedElement The other way to invoke an extension is through the member syntax myNamedElement getterName For any invocation in member syntax the target expression the member is mapped to the first parameter Therefore both syntax forms do the same thing It s important to understand that extensions are not members of the type system hence they are not accessible through reflection and you cannot specialize or overwrite operations using them The expression evaluation engine first looks for an appropriate operation before looking for an extension in o
119. del notation ecore platform pluginforg emf ecore model Ecore ecore Selection Parent List T Tree Table Tree with Columns ia Problems Javadoc B Declaration i GME Dashboard Error Log a Search a History Property Value Cycle Time f 1000 Cyclic 2 true Diagram i Gen ale SERTA TA v Figure 10 4 Setting properties on the CheckContainer element Finally you can add a list of Check Elemens In each of them you have to specify the plugin ID and the relative path to the check file from the plugin root H Package Explorer xd vs oS a ae 5 Resource Set iniia sanne ana Ti _ i an gt sample gmf checks lt L platform resource sample gmF model My gmfgen GB src gt Gen Editor Generator demo diagram checks E 4 Check Container true Check checks sampleCheck chk ES IS platform resource sample gmF model My genmodel ES platform resource sample gmF model My ecore sampleCheck chk ES BA JRE System Library jre1 6 0_02 H E META INF P classpath h 2 7 Problems Javadoc B Declaration E Properties Xi GMF Dashboard Error Log A Search a UL Selection Parent List Tree Table Tree with Columns Property Value Check File Relative From Plugin Root t Ichecks sampleCheck chk Container Check Container true Plugin Id t sample gmf checks Figure 10 5
120. del xmi gt lt xmlMapFile value toolMappingFile gt lt metaMapFile value metaMapFile gt lt toolAdapterClassname value toolAdapterClassname gt lt moduleFile value moduleFile gt lt component gt lt cartridge file org openarchitectureware workflow oawclassic classicinit oaw gt lt metaEnvironmentSlot value me gt lt cartridge gt lt component id dirCleaner class org openarchitectureware workflow common DirectoryCleaner gt lt directories value srcGenPath gt lt component gt lt component id generator class org openarchitectureware xpand2 Generator gt lt metaModel class org openarchitectureware type impl java JavaMetaModel gt lt typeStrategy oAW Version 4 2 170 Classic UML Tutorial class org openarchitectureware type impl oawclassic OAWClassicStrategy convertPropertiesToLowerCase false gt lt metaModel gt lt expand value Root Root FOREACH me getElements Model gt lt genPath value srcGenPath gt lt srcPath value srcGenPath gt lt beautifier class org openarchitectureware xpand2 output JavaBeautifier gt lt beautifier class org openarchitectureware xpand2 output XmlBeautifier gt lt fileEncoding value ISO 8859 1 gt lt component gt lt cartridge file org openarchitectureware workflow oawclassic classicfinish oaw gt lt instantiatorEnvironmentSlot value ie gt lt dumpfile value dumpf
121. e 2 gt META INF B gt MANIFEST MF 1 1 ASCII kkv Figure 13 4 Dependencies In the current version you also need a dependency to the org openarchitectureware util stdlib project Later versions of the um12ecore plugin will reexport that dependency so that you will not need to add it you your projects manually 13 5 Invoking the Generator As usual you have to write a workflow file It also has to reside in your project s source folder Here s how it looks lt xml version 1 0 gt lt workflow gt lt cartridge file org openarchitectureware util uml2ecore uml2ecoreWorkflow oaw um12ModelFile org openarchitectureware uml2ecore test data entity uml2 outputPath out nsUriPrefix http www openarchitectureware org includedPackages Data addNameAttribute false gt lt workflow gt As you might expect it simply calls a cartridge supplied by uml2ecore plugin You have to define the following properties oAW Version 4 2 152 UML2Ecore Reference Table 13 1 UML2Ecore Cartridge properties Property uml2ModelFile addNameAttribute includedPackages outputPath resourcePerToplevelPackage nameUnnamedNavigableAssociationEnds the is the name of your UML2 file that contains the model as usual the file is looked for in the classpath that s why you had to move it into the source folder true false the determines whether automatic namespace management and nami
122. e Java 5 style collections for to many associations If you don t want to use generics you could easily replace or modify the extension file and all associations will change to your style We see in this extension file that other extensions can be referenced using the extension keyword In this case we need the function fan that was defined for classes For associations another function fan is defined but now for AssociationEnds For to one associations the fully qualified name of the associated class is returned for to many references a generic collection for that class In the template code classes and association ends will both use the fan function to print out the referenced type 15 18 2 Writing a template for associations Now it is time to write the template for associations Create the file Association xpt Now fill in the content we will explain some statements right after IMPORT org openarchitectureware meta uml classifier EXTENSION java NamingConventions EXTENSION java Associations DEFINE ReferenceVariables FOR Class FOREACH AssociationEnd Opposite select ae ae isNavigable AS ae private ae fqn ae asInstanceVar ENDFOREACH ENDDEF INE DEFINE AccessorMethods FOR Class EXPAND ToOneAccessorMethods FOREACH AssociationEnd Opposite select ae ae isMultiple amp amp ae isNavigable EXPAND ToManyAccessorMethods FOREACH AssociationEnd Opposite select ae
123. e ee ee eee 194 18 5 Using the transformer 2 2 cciscniecseasiooetincnbeesenessdetdacsivdsehens ootdactovecenesedensdensvdcenens ONE 195 18 6 Testing an M2M transformation sss sese ee eee eee eee e eee 195 GOSS ary 21 goentee iis Soe a sabes E cel becadvgetssdcdel totadedecssde celle cade cebshdedeuteadueess 197 WIN OX ire cise esee As cetetaee deste Gicee Maes ciate he ak dente ta alae ea a acces beta ea teecs ha yaa ct stenes eeu denttattaas hava etadeh 198 oAW Version 4 2 ix List of Figures 1 1 Sample metamodel ener opri EEEE EERE E E EE acne ena ieeel eden en ee 3 1 25 Create EMF project iwicseieias See ete Mate ell ate eat ads ies daa ea hae el ante 3 13 Create NeW Ecore model oa aeea ee weaas EEEE ae vgean tad dg Sete EOE lasers R a eiaa 4 1 4 Adjust namespace settings airera RSS aa EEE EAA OEE RAEAN tute aa aaa e Eaa tee 5 1 5 Metamodel structive iien n o ten a EEEE E eet ahah dd ETE A E E E 6 1 6 Creating the lea TTT 8 1 7 Structure of the genmodel 4302 3 isteveus ernen TRES ar O E e ERE AERE E AT E bene 9 1 8 Generate editing projects inv oerte eeo cote au e Seinuose reae Evan eSEE RE ET Ease Ea e ebous beceteauee Centa Pepea ceeds 9 19 Gen rated projects isece enterri cctesend EYE ATEEK Er ia R eepeedee cesetuectosebeaetesend careanedonceesneattesedeaed 10 1 10 Launch runtime platform ares eens cesendee ccsatneteese be scresend ou E eena Ean Eee ino E raia Ekee ae ean ereina ats 10 111 Create new OA W
124. e examples my Templ extension extension without parameters my Templ extension String s extension with exactly one parameter of type String my Templ extension String s templ def with one or more parameters where the first parameter is of type String my Templ extension templ def with any number of parameters 6 4 10 1 3 Proceeding Inside an advice you might want to call the underlying definition This can be done using the implicit variable ctx which is of the type xtend AdviceContext and provides an operation proceed which invokes the underlying definition with the original parameters Note that you might have changed any mutable object in the advice before If you want to control what parameters are to be passed to the definition you can use the operation proceed List Object params There is no type checking here Additionally there are some inspection properties like name paramTypes etc available 6 4 10 2 Workflow configuration To weave the defined advices into the different join points you need to configure the XtendComponent with the qualified names of the Extension files containing the advices Example lt component class oaw xtend XtendComponent gt oAW Version 4 2 85 Xtend Xpand Check Reference lt metaModel class oaw type emf EmfMetaModel gt lt metaModelFile value metamodell ecore gt lt metamodel gt lt metaModel class oaw type emf EmfMeta
125. e id this parsed_featureName first his is et all instances of the referred type using the allElements extension Select the first one where the id equals the parsed value by default an identifier Both extensions id and allElements can be overwritten or specialized in the Extensions ext file The link_ featurename extension can be overwritten in Linking ext src gen base package name IMetamodel derived from the grammar dsIname ecore src gen base package name parser Generated Antlr parser artifacts x 7 6 3 2 The editor project The name of the editor project is derived from the main project s name by appending the suffix editor to it The editor project contains the Eclipse Texteditor specific informations Note that it uses a generic xtext editor plugin which does most of the job These are the most important resources oAW Version 4 2 120 Xtext Reference from oAW 4 2 Location Description src base package name he Xtend file is used by the outline view If you want to customize the dsIname EditorExtensions ext abels of the outline view you can do that here src gen base package name ontains all the important DSL specific information You should subclass dsIname Utilities java it in order to overwrite the default behaviours src base package name If you have sublcassed the Utilities class make sure to change the dsIname EditorPlugin java respective instantiation he
126. e paramter 1 using an XML attribute 2 using a nested XML element with an attribute value Both methods are equivalent although declaring an attribute way saves a few keystrokes However the attributes class id and file are reserved so they cannot be used Parameters are injected unsing the same accessor methods as described for components The only difference is that they are not instantiated using a default constructor but instead using a so called converter 5 3 1 4 1 Converters There are currently converter implementations registered for the following Java types 1 Object 2 String 3 String uses s split oAW Version 4 2 59 Workflow Reference 4 Boolean both primitive and wrapper 5 Integer both primitive and wrapper 5 3 1 5 Including other workflow files a k a cartridges If an element has a property file it is handled as an inclusion Using an inclusion one can inject a graph described in another workflow file Here is an example file 1 mybean oaw lt anyname class MyClass gt file 2 workflow oaw lt comp class MyBean gt lt bean file mybean oaw gt lt comp gt One can pass properties and components into the included file in the usual way file 1 mybean oaw lt anyname class MyClass aProp myParam gt lt bean idRef myComponent gt lt anyname gt file 2 workflow oaw lt comp class MyBean gt lt bean file m
127. e that are not of any handled type When the model contains Package instances the definition Root FOR Package Will be called for these instances This is polymorphism at work When the package contains subpackages the definition is called recursively 15 13 Creating a template for JavaBeans AS we want to create JavaBean style classes from the entities in our model we now want to create the template file for this Create a new folder java within the folder templates create the file JavaBean xpt there For a first step this template will simply create a file with the name of the class IMPORT org openarchitectureware meta uml classifier DEFINE BeanClass FOR Class FILE NameS Jjava public class Name ENDF ILE ENDDEF INE Note that we have named the definition Beanclass and it is defined for elements of type class So this template will not only fit for elements of type Entity but can be used for any class In the FILE statement we access the name of the current element by property Names This is specific to the oAW classic metamodel The property Names returns the name of the element as String The property Name itself is of type Object for backward compatibility But in templates we usually want the name as a String object 15 14 Calling the JavaBean template from Root xpt By now this template is not called We have to extend the Root xpt template file Add a definition Root defined
128. e that extension files have to reside on the Java classpath too Therefore they use the same namespace mechanism and syntax as types and template files 6 5 3 3 DEFINE The central concept of Xpand is the DEFINE block also called a template This is the smallest identifiable unit in a template file The tag consists of a name an optional comma separated parameter list as well as the name of the meta model class for which the template is defined DEFINE templateName formalParameterList FOR MetaClass a sequence of statements ENDDEF INE To some extent templates can be seen as special methods of the meta class there is always an implicit this parameter which can be used to address the underlying model element in our example above this model element is MetaClass As in Java a formal parameter list entry consists of the type followed by the name of that parameter The body of a template can contain a sequence of other statements including any text A full parametric polymorphism is available for templates If there are two templates with the same name that are defined for two meta classes which inherit from the same super class Xpand will use the corresponding subclass template in case the template is called for the super class Vice versa the super class s template would be used in case a subclass template is not available Note that this not only works for the target type but for all parameters Technically
129. e this lt component class oaw xtend XtendComponent gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelFile value metamodell ecore gt lt metamodel gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelFile value metamodel2 ecore gt lt metaModel gt lt invoke value my example Trafo transform inputSlot gt lt outputSlot value transformedModel gt lt component gt Note that you can mix and use any kinds of metamodels not only EMF metamodels 6 4 10 Aspect Oriented Programming in Xtend since 4 2 Using the workflow engine it is now possible to package e g zip a written generator and deliver it as a kind of black box If you want to use such a generator but need to change some things without modifiying any code you can make use of Xtend s around advices The following advice is weaved around every invokation of an extensions which name starts with my generator around my generator log inveking ctx name CEEX proceed H Around advices let you change behaviour in an non invasive way you don t need to touch the packaged extensions 6 4 10 1 Join Point and Point Cut Syntax AOP is basically about weaving code into different points inside the call graph of a software module Such points are called Join Points In Xtend the join points are the extenion invocations Note that Xpand offers a simliar feature
130. ecker component is good for in the above mentioned workflow Now comes the point The test constraints are not generic Instead they do have knowledge about the input model which generic constraints don t they just operate with knowledge about the meta model So this file contains constraints such as There has to be a class called Entity in the resulting model Or There must be an EReference owned by Attribute called type pointing to the class called PrimitiveType Make sure that the constraints again coverage check all relevant aspects of the transformation test org openarchitectureware uml2ecore test tests chk oAW Version 4 2 196 Glossary D DSL Ecore EMF GMF MDA Domain Specific Language Add description here Add description here Graphical Modeling Framework Add description here oAW Version 4 2 197 Index Symbols xpt file extension 88 174 A AOP 94 join point 95 point cut 95 AROUND 94 C CEND 92 classpath 89 collection 92 collection type 91 comments 93 CSTART 92 D DEFINE 89 E ELSEIF 92 ENDIF 92 ERROR 93 EXPAND 90 expression statements 94 Extend 88 EXTENSION 88 F FILE 90 FOR 91 FOREACH 91 92 G guillemets 87 IF 92 IMPORT 88 ITERATOR 92 J join point 95 L LET 93 N namespace import 91 newline 94 O outlet 90 P point cut 95 polymorphism 89 PROTECT 92
131. ecute them you have to provide the right configuration oAW Version 4 2 125 UML2 Adapter You need to configure the UML2 metamodel and a profile metamodel for each profile you used directly A typical configuration looks like this lt workflow gt lt bean class lt component cl lt component gt lt component cl oaw uml12 Setup standardUml12Setup true gt lass oaw emf XmiReader gt lass oaw xpand2 Generator gt lt metaModel class oaw uml2 UML2Met aModel gt lt metaModel class oaw uml2 profile ProfileMetaModel gt lt profile value myProfile profile uml2 gt lt metaModel gt lt component gt lt workflow gt Note the bean configuration in the second line It statically configures the XmiReader to use the right factories for uml and uml2 files This is very important If you are invoking several oAW components you should use the id idRef mechanism lt workflow gt lt bean class lt component cl lt component gt lt component cl lt metaModel lt metaModel oaw uml2 Setup standardUml12Setup true gt lass oaw emf XmiReader gt lass oaw xpand2 Generator gt id uml class oaw uml2 UML2MetaModel gt id profile class oaw uml2 profile ProfileMetaModel gt lt profi le value myProfile profile uml gt lt metaModel gt lt component gt lt component class oaw xpand2 Generator gt lt metaModel idR
132. eeeeeeeeeeeeeeeees 149 12 2 5 List of currently available Checks sese 149 13 UME2E core Reference inise lerari erostaan EO EO EE SE EEEO A ais 150 13 1 Whats this i isciner ness meniren an aee ee a aeaaeae aE Oe aaa O ETENE ae Oaie 150 13 2 Setting up Eclipse snit iernii eretat trie esia ieee aA a EE aat eead 150 13 3 UML Tool Support T 150 13 4 Setting up your meta model project sss 150 13 5 Invoking the Gemerator cct iuter iseti iinei tiiir iiiki diirei iie iiiar dikei 152 13 6 The generated Model crescci iieri iieii iis 9 VOTE de 153 IST TTT 154 13 8 Modularizing the meta model file sese 154 T4 Glassie RETerem Ce viz o eeir te ET E Meads longs ees ehh ee Senna ee ae eee 155 14 1 Available UML Tool Adapters snesen ea iiini tenses coronene E EEE TERE RR 155 14 2 The Classic UME Metam6del 20 3 csccssstvu enren eeina 2 caeg ted nish ERR ee See 156 14 2 1 Core and Class Diagram Support seren arinrin riir A i a 156 14 2 2 Statechart SUpport ron iieii ee ese EEEE a eee dacs eee EEEE A enes eee 159 14 2 3 Activity Diagram Support icc ccc 3scceces rei a sab enceedspenecescbendendtvenecs sah cuce odovere 161 15 Classic UME Tutorial T 164 PSA MOU CHI ON sees ash Sess eat sas sate E e EE EEE E conde S EREE E LEE gure eden 164 15 2 Installing TET 164 15 3 Example Overview ein ee e eee ses wt aE e e E a ea aeae eae 164 15A Settins Up the project x lt ire erenn e iii ede ee ee ee ae 165 15 5 Defining Dependencies
133. ef uml gt lt metaModel idRef profile gt lt component gt oAW Version 4 2 126 Chapter 9 UML2 Example 9 1 Setting up Eclipse Before you can use oAW with Eclipse UML2 you first have to install the UML2 plugins into your Eclipse installation 9 2 Setting up the project Create a new openArchitectureWare plugin project You have to add the following dependencies to the manifest file e org openarchitectureware uml2 adapter To tell the oAW Eclipse plugins that this project is a UML2 specific one you need to specify that in the oAW preferences Open the project properties select the openArchitectureWare tab and select the UML2 profiles metamodel Properties for oaw4 demo emf uml2 generator j ili 5 x type filter text openArchitectureware er a Enable opend rchitectureWare nature Iv INOers Java Build Path Enable project specific settings lv Java Code Style Java Compiler UML2 profiles New avadoc Location opena rchitectureware Plug in Development Remove Select metamodel contributor Project References Refactoring History Restore Defaults Apply o cne Figure 9 1 Configure UML2 profiles metamodel oAW Version 4 2 127 UML2 Example Note that if you want to transform an UML2 model into a normal EMF model you need to add the UML2 metamodel and the EMF metamodels The order is important The UML2 profiles entr
134. efore we Xtext provides some common built in lexer rules Let s start with the two simplest 7 5 1 Keyword Token All static characters or words keywords can be specified directly in the grammar using the usual string literal syntax We never need the value of keyword because we know it it s static But sometimes there are optional keywords like e g the modifiers in Java The existence of a keyword can be assigned using the boolean assignment operator However if you want to assign the value of the keyword to a property just use the assignment operator Example E abstract abstract entity name ID lt extends ID 7 gm features Feature myn With this the type Entity will have the boolean property abstract which is set to true if the respective keyword has been specified for an entity I ve added the extends part because an abstract entity wouldn t make sense without inheritance Note that operators such as lt in the example are keywords too 7 5 2 Identifier Token We also have seen the identifier token ID This is the token rule expressed in Antlr grammar syntax CUA DU oval UM see Sy Meh Yoo Da 5 WAN AE ALG a VOI So an identifier is a word starting with a character or underscore followed by optionally additional characters underscores or digits The return value of the Identifier token is a String So if you use the usual assignment oAW
135. election out of a specific collection These are the select and reject operations The select specifies a subset of a collection A select is an operation on a collection and is specified as follows collection select v boolean expression with v Select returns a sublist of the specified collection The list contains all elements for which the evaluation of boolean expression with v results in true Example 1 2 3 4 select i i gt 3 returns 3 4 6 3 2 2 typeSelect A special version of a select expression is typeSelect Rather than providing a boolean expression a class name is here provided collection typeSelect classname typeSelect returns that sublist of the specified collection that contains only objects which are an instance of the specified class also inherited 6 3 2 3 reject The reject operation is similar to the select operation but with reject we get the subset of all the elements of the collection for which the expression evaluates to false The reject syntax is identical to the select syntax collection reject v boolean expression with v Example i gt 3 Ob Pe ect ai aS returns 1 72 6 3 2 4 collect As shown in the previous section the select and reject operations always result in a sub collection of the original collection Sometimes one wants to specify a collection which is derived from another collection but which contains obje
136. ems Couldn t resolve reference to Foo model ds mydslprojer Duplicate feature name model dsl mydsiprojer Duplicate feature name model ds mydslprojer Figure 2 16 Breaking constraints The constraints are not only checked within the editor but are checked when invoking the parser from oA W s workflow engine as well There are more things we could do to enhance the editor e g outline view code completion or navigation Have a look at the reference documentation to see how this works 2 5 Generating code Now that we have a DSL we may want to do something useful with it DSLs are essentially small programming languages A programming language has to be understandable by a computer There are basically two ways to make a language understandable by a computer The first one is to write a compiler which transforms expressions made in one language into another language which is already understandable by a computer For example a Java compiler transforms Java programs to ByteCode programms ByteCode is understandable because there are VMs which translate expressions in Java ByteCode into more native instructions This is usually done at runtime Translating a language at runtime is called interpretation ignoring special cases like Just in Time compilation here oAW Version 4 2 39 Xtext Tutorial With Xtext models one can either create a compiler a k a generator or an interpreter Although there are good reasons for b
137. er gt lt modelFile value modelFile gt lt metaModelPackage value data DataPackage gt lt outputSlot value model gt lt firstElementOnly value true gt lt component gt lt gull jel SCULE UD I gt The parameters we pass should be self explanatory The reciperile parameter is where the checks will written to it must have the recipes extension lt component id recipe class datamodel generator RecipeCreator gt lt appProject value oaw4 demo emf datamodel generator gt lt srcPath value man sre gt lt modelSlot value model gt lt recipeFile value recipes recipes gt lt component gt lt workflow gt 1 11 5 Running the Workflow and seeing the Effect We can now run the workflow After running it you should see a recipes recipes file in the root of your project Right clicking on it reveals the button Since the manual implementation of the vehicle Entity is missing we get the respective error oAW Version 4 2 26 EMF Tutorial We can now implement the class manually in the man src folder public class Vehicle extends VehicleImplBase After doing that the remaining errors in the recipe view should go away automatically 1 12 Transforming Models It is often necessary to transform models before generating code from it There are actually two forms of transformations 1 An actual model transformation generates a co
138. ereotyped ENDF ILE oAW Version 4 2 133 UML2 Example ENDDEF INE As you can see the stereotype acts just like a type and even the polymorphic dispatch between the base type uml Class and the stereotype works Adapting the workflow file is also straight forward workflowWithProfile oaw here s the modified generator component lt component id generator class oaw xpand2 Generator skipOnErrors true gt lt metaModel class oaw type emf EmfMetaModel metaModelPackage org eclipse emf ecore EcorePackage gt lt metaModel class oaw uml2 UML2Met aModel gt lt metaModel id profile class oaw uml2 profile ProfileMetaModel gt lt profile value test profile uml gt lt metaModel gt lt expand value templates RootWithProfile Root FOR model gt lt outlet path src gen gt lt postprocessor class oaw xpand2 output JavaBeautifier gt lt outlet gt lt component gt The only thing we have to do is add a new metamodel that refernces the profile we just created oAW Version 4 2 134 Chapter 10 GMF2 Adapter 10 1 Introduction The GMF Adapter integrates the oAW Check language with GMF2 10 2 Installation First you need to install the GMF from eclipse org http download eclipse org modeling gmf downloads drops R 2 0 200706210000 index php The oAW gmfadapter is available from the oAW updatesite http www openarchitectureware org upd
139. erge which is currently only evaluated by the MagicDraw adapter The existing tool adapter classes and mapping files can be found beneath the package org openarchitectureware core frontends xmi toolsupport uml1 lt TOOL gt oAW Version 4 2 171 Classic UML Tutorial For example to set up this project for Poseidon 4 5 the appropriate settings are toolAdapterClassname org openarchitectureware core frontends xmi toolsupport uml poseidon PoseidonAdapter toolMappingFile poseidon40_xmil2_all xml 15 10 3 Create the root template In the workflow the generator has been configured to start with the this definition lt expand value Root Root FOREACH me getElements Model gt This means that the generator will look for a template file Root xpt in the classpath where a definition named Root is found for all elements that are selected by the expression me getElements Model In case of UML models there exists solely one element of type Mode1 that will be selected Now create the file Root xpt in the templates folder Remember We have configured our Eclipse project that the folder templates is a classpath folder You will see that the new file is recognized as an oAW template file as it has a template file icon templates iv For the beginning the template will be simple IMPORT org openarchitectureware core meta core DEFINE Root FOR Model ENDDEF INE
140. ersion 4 2 69 Xtend Xpand Check Reference Accessing an operation myModelElement doStuff simple arithmetic Lo AL eZ boolean expressions just an example U text 6tartawitht t 2 amp 1 false 6 3 1 Literals and special operators for built in types There are several literals for built in types 6 3 1 1 object There are naturally no literals for object but we have two operators equals objl obj2 not equals objl obj2 6 3 1 2 void The only possible instance of Void is the null reference Therefore we have one literal null 6 3 1 3 Type literals The literal for types is just the name of the type no class suffix etc Example String the type string my special Type evaluates to the type my special Type 6 3 1 4 StaticProperty literals The literal for static properties aka enum literals is correlative to type literals Mya COlO ns RED 6 3 1 5 String There are two different literal syntaxes with the same semantics Se string Iiteral a String literal both are okay oAW Version 4 2 70 Xtend Xpand Check Reference For Strings the expression sub language supports the plus operator that is overloaded with concatenation my element ele name is really cool Note that multi line Strings are supported 6 3 1 6 Boolean The boolean
141. es they can have parameters StaticProperties are the equivalent to enums or constants They must be invoked statically and they don t have parameters 6 2 2 Built In Types As mentioned before the expressions framework has several built in types that define operations and properties In the following we ll give a rough overview of the types and their features We won t document all of the operations here because the built in types will evolve over time and we want to derive the documentation from the implementation model driven For a complete reference consult the generated API documentation http www openarchitectureware org api built ins 6 2 2 1 Object Object defines a couple of basic operations like equations Every type has to extend object 6 2 2 2 void The void type can be specified as the return type for operations although it s not recommended because whenever possible expressions should be free of side effects whenever possible 6 2 2 3 Simple types Datatypes The type system doesn t have a concept data type Data types are just types As in OCL we support the following types String Boolean Integer Real e string A rich and convenient string library is especially important for code generation The type system supports the operator for concatenation the usual java lang String operations length etc and some oAW Version 4 2 66 Xtend Xpand Check Reference special operations li
142. es apes che E eeea Eh 74 6 325 Chain EXPres SION Derti EE E EEE EE on chester vette vebeccenteuag hin eteee fades 75 6 3 0 Croata EXPLESSIOM TTT 75 6 3 T FEE EX UT HHH EE os celta E e ince 75 0 3 8 GLOBAEVAR expression soebie ieri koai EREE R E EREE A EE A A ERa e 75 6 3 9 Multi methods multiple dispatch sss eee eee 76 oAW Version 4 2 iv openArchitectureW are User Guide 6 3 10 Castings sicccvser begesevdel neti io aed ies en ene We ead 76 OAL Mien raei e a E cede hab TTT TTT 77 GALL Extend files norimis nioen ieie ooe ere E nE E cede hase EE S AETR KERT ENa ERS Ke 77 6 472 COMMENTS TTT 77 6 4 3 Import Statements icc ssid nE EE eels ieee ad cs ieeee sees eh EENE IRR ESERE aeiae TI 6 4 4 Extension Import Statement 00 0 0 Se ZES TR RSS Teas VE STRESS a Vara Tota e 78 04 5 EXtENSI ONS oiie ieia EE ER EE EA A EEE Whs eden ictal E E E eed 78 6 4 6 Java Extensions civ fenaities Ma i REE EEE A ee ee 80 6 4 7 Create Extensions Model Transformation sss esse sees eee eee e 81 6 4 8 Calling Extensions From H 83 6 4 9 WorkflowComponent ac sse c2cdesieckteSbeads i EREE EEEE EA ER ERS N ieee 84 6 4 10 Aspect Oriented Programming in Xtend since 4 2 sss sese 84 6 5 Xpand 2 cicacs vse vs ga decouss se aa a a dasevbcood eset reaevaedeetiesge sk eoezaged EEr AS ER EER ated EAEE EEES 87 6 5 1 Template files ees TTT 88 6 5 2 General structure of template files 00 0 eee eeeeeeeeeneneeeeeeeneneneneneeeneeaeaeaeaeaeaeaee
143. esource oaw4 demo emf uml2 generator src test profile uml lt Profile gt test H UML E testvo test s UML base Class Class S7 lt Element Import gt Class lt Stereotype gt test HA lt Extension gt Class_test pathmap UML_METAMODELS UML metamodel uml pathmap UML_PROFILES Ecore profile uml pathmap UML_PROFILES Standard profile uml ii E E F Figure 9 7 Defining the Profile 9 5 3 Generating Code Note that all the stuff above was not in any way related to oAW it was just the bare bones means of creating and applying a profile to a UML2 model There are two things we have to change The workflow specifically the configuration of the generator component needs to know about the profile and the template needs to generate different code if a class has the test stereotype applied Let s look at the second aspect first Here s the modified template in RootwithProfile xpt DEFINE Root FOR uml Model EXPAND PackageRoot FOREACH List uml Package ownedElement ENDDEF INE DEFINE PackageRoot FOR uml Package EXPAND ClassRoot FOREACH List uml Class ownedType ENDDEF INE DEFINE ClassRoot FOR uml Class FILE namet java public class name ENDF ILE ENDDEF INE DEFINE ClassRoot FOR test test FILE namet java public class name st
144. ew based editors doesn t scale Once you re at more than say 30 metaclasses things become hard to work with The same is true for GMF s Ecore editor Since you cannot easily factor a large meta model into several diagrams the diagram get cluttered and layouting becomes almost impossible One way to solve this problem is to use UML tools to draw the meta model and then transform the UML model into an Ecore instance The oAW uml2ecore utiliy transforms a suitably structured Eclipse UML2 model which can be created using various tools into an ecore file Note that this tool also serves as a tutorial for writing model to model transformations This aspect however is documented elsewhere This document only shows how to use the uml2ecore tool 13 2 Setting up Eclipse You need an installation of oAW 4 1 including the UML2 support Run the UML2 example available for download on the oAW download page to verify that you have all the UML2 stuff installed The only additional thing required is that you install the uml2ecore plugin into your Eclipse installation The plugin is part of the oAW 4 1 2 distribution 13 3 UML Tool Support Of course you could use UML2 s supplied tree editors for drawing the UML2 model that should be transformed into Ecore However this is useless since then you re back to square one tree editors So you need to use an UML tool that is able to export the model in the Eclipse UML2 2 0 format For example MagicDr
145. extension model Right click into the gmfgen editor and choose the Add extension model action Browse your file system and got to Your eclipse installation directory Navigate to plugins org openarchitectureware adapter gmf2 extensionmodel_1 0 0 model and choose oawGmfExtension ecore Select the CheckContainer when asked for the Root Class Add Your Extension Domain Model To GMFGen Select Extension Domain Model Load extension model and select root element to create in GMFGen Model URI Browse File System Browse Workspace Find In Workspace ware adapter gmf2 extensionmodel_1 0 0 model oawGmfExtension ecore Root Class CheckContainer Check Figure 10 3 Adding the extension model In the CheckContainer element you have to set the diagram from your gmfgen Normally there is just one to select You can also choose whether you d like to run the validation in a cyclic mode or not The cycle time attribute is the time in ms Default is one second oAW Version 4 2 137 GMF2 Adapter E my gmfgen 77 tS Resource Set 8 L platform resource sample gmf model My gmfgen gt Gen Editor Generator demo diagram gt Check Container true B platform resource sample gmf model My genmodel B E platform resource sample gmf model My ecore IS platform pluginforg eclipse grmt runtime notation model notation genmodel 1 platform plugin org eclipse gmf runtime notation mo
146. external DSLs using Xtext The process we re going to go through will start by defining an Xtext grammar for our DSL generate a parser a meta model and a corresponding text editor out of it Afterwards we will see how to refine the DSL and it s editor using provided facilities In the end we will see how one can generate code out of textual models The actual content of this example is rather trivial we will generate Java classes following the Java Beans conventions The model will contain entities such as Person or Address including some attributes and relationships among them a rather typical data model From these entities in the model we want to generate the Beans for implementation in Java In a real setting we might also want to generate persistence mappings etc We will not do this for this simple introduction 2 3 Defining the DSL We ll define a DSL for simple domain models following some concepts of Domain Driven Design We don t want to define too much semantic for each of these concepts here because this tutorial is about how to develope a DSL not why In addition most of the semantics of a DSL s concept is usually implemented in a generator or an interpreter which is not the focus of this turorial We use this example because the concepts are well known even if the meaning is not formally defined So we don t need to explain them or motivate the example but can focus on other things The following UML diagram shows t
147. ference 14 2 The Classic UML Metamodel 14 2 1 Core and Class Diagram Support lt lt library gt gt lt lt library gt gt Element Namespace from org openarchkectureware core meta core from org openarchiectureware core meta core Dependency gt supplier dependency UMLNamespace documentation String jee a MbdelElkement documentation String requirement S L BehavioredEkment A behaviour context Figure 14 1 Core Elements oAW Version 4 2 156 Classic Reference Association MbdelElement from org openarchkectureware meta uml documentation String lt lt incomplete gt gt AssociationE nd lt lt incomplete gt gt association Association visibility String navigable boolean pespocitionend icazs qeDeletey aggregate Value String P aggregate boolean compositionboolean multiplicityMin int 0 multiplicityMaxint 1 subP ackage tisRequired boolean SSS il associationEnd lt lt incomplete gt gt Class namespace abstract boolean leatboolean visibility String Figure 14 2 Associations Class and Stuff UMLNamesp from org openarchkecturew are meta um E ae from org openarchrectureware meta uml documentation String lt lt incomplete gt gt Class namespace
148. ference configured the Ecore metamodel using the EMF MetaModel implementation shipped with the core part of the openArchitectureWare 4 release A mandatory configuration is the expand property It expects a syntax similar to that of the ExPAND statement described above The only difference is that we omit the Expanp keyword because we write it as the property s name Examples lt expand value Template define FOR mySlot gt or lt expand value Template define foo FOREACH mySlot1 mySlot2 gt The expressions are evaluated using the workflow context Each slot is mapped to a variable For the examples above the workflow context needs to contain elements in the slots mySlot mySlot1 and myslot2 It s also possible to specify some complex expressions here If for instance the slot myModel contains a collection of model elements one could write lt expand value Template define FOREACH myModel typeSelect Entity gt This selects all elements of type Entity contained in the collection stored in the mymoae1 slot 6 5 5 4 Output configuration The second mandatory configuration is the specification of so called outlets a concept borrowed from AndroMDA Outlets are responsible for writing the generated files to disk Example lt component class oaw xpand2 Generator2 gt lt outlet path main srce gen gt lt outlet name TO_SRC path main src overwrite false gt
149. fic file types in that project 3 7 1 Problem markers During the build process all found problems are marked in the editors as well as listed in the Problems view oAW Version 4 2 50 oAW 4 Eclipse Integration j cv vr Jj Mr D Root xpt EP Component xpt X L mp ORT scm mm comp IMPORT scm mm ex DEFINE Root FOR scm mm 5CMTop x EXPAND ComponentPojo Root FOREACH A11ElementsOfModel EXPAND Exception Root FOREACH AllElementsOfModel type ENDDEF IHE Jei 22 errors 68 warnings 0 infos Description Resource In Folder Couldn t find definition ComponentPojo Root for Component xpt oaw4 demo cla Couldn t find operation decoratorProxyFilename ComponentProxy xpt oaw4 demo cla Error parsing extensions Unable to load extensi ComponentProxy xpt oaw4 demo cla LS String expected ComponentProxy xpt Dawud demo da In the current implementation analysations take place when Eclipse runs an incremental or full build That means problem markers are actualized when a file is saved for instance If you are in doubt about the actuality of problem markers you should clean your project and let it rebuild again Note that if you change signatures of e g extensions the referencing artifacts Xpand templates etc are not analysed automatically 3 8 Running a workflow You can start a workflow by right clicking on a workflow file oaw and selecting Run
150. fix asInteger U Returns an Integer object holding the value of the specified String from ava 1 5 onesies Giz ie if this string contains substring Converts the first character in this String to upper case using the rules lof the default locale from Java Converts the first character in this String to lower case using the rules lof the default locale from Java replaceFirst String String Replaces the first substring of this string that matches the given regular expression with the given replacement startsWith String Tests if this string starts with the ttoCharList splits this String into a List String ee Strings of length 1 matches String ells whether or not this string atches the given regular expression from Java 1 4 oAW Version 4 2 103 Xtend Xpand Check Reference 6 6 3 Integer Super type Real Table 6 5 Operations sanc ooo y upTo Integer Integer 6 6 4 Boolean Super type Object Table 6 6 Operations Boolean L U 6 6 5 Real Super type object Description returns a List of Integers starting with the value of the target expression up tothe value of the first parameter incremented by the second parameter E g l upTo 10 2 evaluates to 1 3 5 7 9 returns a List of Integers starting with the value of the target expression up tothe value of the specified Integer incremented by one e g l upTo 5 evaluates to 1 2 3 4 5 o
151. g configurations dialog ardi cao ETH TR ddd OTT ET Ee na n i CT a d e a i 35 2 9 Code Completions ersen gi ien E EEEE Ee EEEE E EERE Ea EEA EEE ENEE ER E sae TRE 36 2 10 Find References Acton cecccssvcescaste dessa civ edccaeresuccd i RAE ERANA EE a 36 211 Find References result TTT 37 2 12 Foldin gennin aar E E ERTER EE e EEEE E E NEE e EER A 37 2 13 Errors according to the grammar i e syntax Errors sese ee ee ee eee 37 2 14 Validating the model with Check p ocieceiensoi igeni i i eE E EEE ER E 38 2 15 Defining extensionsi Ea e a ae et ed Ma ee a e aeS 39 2 16 Breaking Constraints snini Ae e odeebewt pa Eae aea e Er ei paedeartt Eee ee a Teea tent es 39 247 Xpand templates o eian As Ade Ee a a 40 EY Export Plus ms T asgi aioa e ee eei oee a e e ii eE E EE bait a EE iea a a EEY 41 DAO Export Plug ins 2 mopoa a a e e Subsets autos Ea e ee e aE ee eae eE Sa ei aE 42 2 20 EXport T TE eaea a aa ge tildes Sides a E oe aeaa a ae aaa R a aae a oih 43 2 21 NEw DSEx rO HHT oie A E a E E E Oa 44 222 L RIE modellini esn e oh gad ag eE a a oti aE a ca 45 22 L the WOrKIOW vieio tiene THT THH aa ene aaea a ea a a 46 224 Worktlow completed Tea a a a A a aAa dace ve T 47 Sule Java Object Graph aeiia eiae Masih aie a a ata Mable ete a a e aa r iaei ae aea 57 6 1 Sample metamodel TTT 89 9 1 Configure UML2 profiles metamodel sss 127 9 2 Creating a new UML2 node ass xsegga zasad Egg yada KETAT iiiaae a ieii 128 oAW Version 4 2 x openA
152. gments is a double colon A fully qualified name looks like this my fully qualified MetaType The namespace and name used by a specific type is defined by the corresponding Met aMode1 implementation The EmfMet aModel for instance maps EPackages to namespace and EClassifiers to names Therefore the name of the Ecore element EClassifier is called ecore EClassifier If you don t want to use namespaces for whatever reason you can always implement your own metamodel and map the names accordingly oAW Version 4 2 65 Xtend Xpand Check Reference 6 2 1 2 Collection Type Names The built in type system also contains the following collection types collection List and set Because the expressions language is statically type checked and we don t like casts and classCast Exceptions we introduced the concept of parameterized types The typesystem doesn t support full featured generics because we don t need them The syntax is Collection my Type List my Type Set my Type 6 2 1 3 Features Each type offers features The type resp the metamodel is responsible for mapping the features There are three different kinds of features e Properties e Operations e StaticProperties Properties are straight forward They have a name and a type They can be invoked on instances of the corresponding type The same is true for Operations But in contrast to properti
153. gt lt outlet name TO_SRC path main src overwrite false gt lt beautifier class oaw xpand2 output JavaBeautifier gt lt beautifier class oaw xpand2 output XmlBeautifier gt lt protected regions configuration gt lt prSrcPathes value main src gt lt prDefaultExcludes value false gt lt prExcludes value xml gt lt component gt Let s go through the different properties one by one 6 5 5 1 Main configuration The first thing to note is that the qualified Java name of the component is org openarchitectureware xpand2 Generator2 One can use the shortcut oaw instead of a preceding org openarchitectureware The workflow engine will resolve it 6 5 5 2 Encoding For Xpand it s important to have the file encoding in mind because of the guillemet characters used to delimit keywords and property access The fileEncoding property specifies the file encoding to use for reading the templates reading the protected regions and writing the generated files This property defaults to the default file encoding of your JVM 6 5 5 3 Metamodel The property met aModel is used to tell the generator engine on which metamodels the xpand templates should be evaluated One can specify more than one metamodel here Metamodel implementations are required by the expression framework see Expression Language Reference used by Xpand2 In the example above we oAW Version 4 2 96 Xtend Xpand Check Re
154. he type actually is There are three different assignment operators e Standard assignment The type will be computed from the token on the right e Boolean assignment The type will be Boolean e Add assignment The type will be List The list s inner type depends on the type returned by the token on the right Example IME AIESY E isAbstract abstract entity name ID featurest Feature myn The meta type entity will have three properties 1 Boolean isAbstract 2 String name oAW Version 4 2 112 Xtext Reference from oAW 4 2 3 List Feature features 7 4 3 2 Cross References Parsers construct parse trees not graphs This means that the outcome of a parser has no crossreferences only so called containment references Composition In order to get cross links in your model one usually has to add third task the linking However Xtext supports specifying the linking information in the grammar so that the meta model contains cross references and the generated linker links the model elements automatically for most cases Linking semantic can be arbritrary complex Xtext generates a default semantic find by id which can be selektively overwritten We will see how this can be done later in this document Let s concentrate on what the grammar language supports mney entity name ID extends superType Entity gm features Feature myn Have a look at
155. he abstract syntax of the DSL we re going to define oAW Version 4 2 29 Xtext Tutorial Figure 2 1 Meta model as UML diagram 2 3 1 Creating Xtext projects To get started we need to create some projects Therefore we use the provided Xtext wizard 6806 New Project Select a wizard lt gt P Wizards type filter text g Java Project Z Java Project from Existing Ant Buildfile 3 Plug in Project gt amp General gt amp cvs gt Eclipse Modeling Framework gt amp Java Y amp openArchitectureware 3 openArchitectureWare Project E3 Xtext Projects gt Plug in Development gt amp Web Figure 2 2 Create Xtext projects oAW Version 4 2 30 Xtext Tutorial e808 Xtext projects wizard This wizard creates a pair of projects for your Xtext DSL Main project name _my ds Language name mydsl DSL File extension dsl nsURI http www example org my dsl Base package org example dsl Create generator project v 2 lt Back Next gt C Cancel d E Finish oe Figure 2 3 Xtext wizard dialog The wizard dialog lets you specify a number of properties used for different things See the Xtext reference documentation for detailed information about what the different properties mean For the moment just ensure that everything looks like shown in the screenshot above i e stay with the defaults and click Finish The wizard generates three pr
156. he manual implementation of the state machine Recipe Creation 17 5 6 Acknowledgements Thanks to the folks at Rohde amp Schwarz Bick Mobilfunk for letting us use this example oAW Version 4 2 192 Chapter 18 Model To Model with UML2 Example 18 1 Introduction This tutorial introduces various somewhat advanced topics of working with openArchitecureWare We don t generate code we transform models Specifically the tutorial covers the following e real model to model transformations e how to test m2m transformations e working with Eclipse UML2 specifically transforming away from it e using global variables e implementing JAVA extensions Note that this tutorial actually documents the uml2ecore utility that can be used to transform metamodels drawn with an UML2 tool into an Ecore instance This tool is available for download as a plugin on the oAW download page Please make sure you first read the u O_uml2ecore reference That document explains what to tool does this is more or less a precondition to making sense how the tool does it which is what this document explains Also note that many of the gory details are actually documented as code comments in the various oAW files of the example So make sure you have the code available as you read this document 18 2 Why this example In general we needed an example for real m2m transformations And obviously since we already had the uml2ecore tool it makes sen
157. hich all kinds of generator workflows can be described A generator workflow consists of a number of so called workflow components that are executed sequentially in a single JVM 5 2 Workflow components At the heart of the workflow engine lies the WorkflowComponent A WorkflowComponent represents a part of a generator process Such parts are typically model parsers model validators model transformers and code generators oAW 4 ships with different WorkflowComponents which should be used where suitable but you can also implement your own The only thing you have to do is to implement the org openarchitectureware workflow WorkflowComponent interface public interface WorkflowComponent param ctx W current workflow context param monitor a implementors should provide some feedback about the progress E using this monitor param issues AY public void invoke WorkflowContext ctx ProgressMonitor monitor Issues issues Is called by the container after configuration so the component can validate the configuration before invocation U param issues implementors should report configuration issues to this S public void checkConfiguration Issues issues The invoke operation performs the component s actual work checkConfiguration is used to check whether the component is configured correctly before the workflow starts More on these two operations later A workflow description co
158. hitectureware core xpand2 The Xpand template engine e org openarchitectureware core check oAW language Check for defining constraints 15 6 Create source folders Create two folders model and templates in the project root not in src and add this folders as classpath folders in the project properties dialog Libraries tab By doing this the model and the templates can be found in the project s classpath without placing the files in the source folder Properties for oaw4 demo classic uml type filter text Java Build Path li wi Info Builders CS Source 2 Projects BA Libraries amp Order and Export Java Build Path Java Code Style Class Folder Selection Java Compiler Add JARS Javadoc Location f Choose class folders to be added to the build path Add External JARs Project References gt Oe 0aw4 demo classic uml mae MJS model QOS src Add Library amp templates Add Class Folder Figure 15 5 Creating source folders oAW Version 4 2 166 Classic UML Tutorial 15 7 Create the model This section explains how to create the model from scratch using MagicDraw 10 11 If you are using another UML tool this is a guideline to create the model but the tool can differ in some details You can skip this section if you have MagicDraw downloaded the sample project and use the model from the sample project Start your UML Tool and create the model from the screenshot abo
159. ift T gt y Import lt L Export Javadoc Declaration x Oinfos oo Refresh FS Resource Path Validate 1 item Debug As E JE 2 JUnit Plug in Test Alt Shift P Profile As P Ju 3 Init Test Alt Shift X T K eam 4 oAW Workflow Compare With E Replace With gt Q Run Source EI Q External Tools Properties Alt Enter workflow oaw oaw4 demo emf Figure 1 16 Sample data model The following should be the output 0 NFO seca nese anaes SS SS SS SSS SSS SSS SSS SS SS SSS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SES SSS SESS SES IEA NFO openArchitectureWare 4 1 2 Build v20070314 WA NFO c 2005 2007 openarchitectureware org and contributors c INNO T SS SS Se yA NFO running workflow D oAW emftutorial oaw4 demo emf datamodel generator src workflow oaw 171 NFO 750 NFO xmiParser file example data gt slot model 875 NFO workflow completed in 125ms 1 8 3 Templates No code is generated yet This is not surprising since we did not yet add any templates Let s change this Create a package templates in the srcfolder and within the package a file called Root xpt The Root xpt looks as follows By the way if you need to type the guillemots and the editor provides keyboard shortcuts with Ctrl lt and Ctrl gt DEFINE Root FOR data DataModel EXPAND Entity FOREACH entity ENDDEF INE oAW Version 4 2 17 EMF Tutorial DEFI
160. ile gt lt cartridge gt lt workflow gt 15 10 2 Workflow Properties The workflow includes a properties file in which the concrete configuration is stored Create the file workflow properties like this Note all paths must be found in the classpath the metamappings file metaMapFile metamappings xml model xmi name of the XMI export toolMappingFile tool mapping file to use toolAdapterClassname tool adapter implementation moduleFile profile files MagicDraw 10 model xmi AuthorBookExampleMD10 mdzip toolMappingFile magicdraw_xmi21_all xml toolAdapterClassname org openarchitectureware core frontends xmi toolsupport uml magicdraw MagicDrawAdapter21 moduleFile magicdraw md10 UML_Standard_Profile xml model xmi AuthorBookExampleMD11 mdzip toolMappingFile magicdraw_xmi21_all xml toolAdapterClassname org openarchitectureware core frontends xmi toolsupport uml magicdraw MagicDrawAdapter21 moduleFile magicdraw md11 UML_Standard_Profile xml path to create the generated output to srcGenPath src gen path where the dump file is created dumpfile bin dump 15 10 2 1 Setting up for use with other UML tools This configuration file is designed for use with MagicDraw Other UML tools can be easily configured by changing the properties model xmi toolAdapterClassname toolMappingFile and moduleFile The property moduleFile specifies additional modules to load and m
161. ile gt New gt Project gt openArchitectureWare gt openArchitectureWare Project oAW Version 4 2 11 EMF Tutorial Properties for oaw4 demo emf datamodel generator type filter text openArchitectureWare Resource BeanInfo Path Builders Java Build Path Java Code Style Java Compiler Java Editor Javadoc Location opend rchitectureWare Plug in Development Profile Compliance and vV Project References Server Task Tags Validation C Enable project specific settings Configure Workspace Settings H E Restore Defaults Apply Figure 1 12 Project properties 1 6 Defining an Example Data Model Select the src folder and then choose New gt Other gt Example EMF Model Creation Wizards gt Data Model Create a new data model call it example data On the last page of the wizard select Model as model object oAW Version 4 2 12 EMF Tutorial Select a wizard Create a new Data model Wizards type Filter text T L Connection Profiles Be cvs H Eclipse Modeling Framework H E EB Example EMF Model Creation Wizards X Data Graph Model Data Model 7 Ecore Model i tg Ecore to Ecore Model 5 Ecore to XML Model SY XSD Model Sa XSD to Ecore Model R I2EE gt Java Figure 1 13 Create a sample data model Next populate this very model as following Please note that in the case of attributes you have to define a type as well i e String not
162. in the src folder of our project It is important that this file resides in the classpath The file has the following content import data context Attribute ERROR Names must be more than one char long name length gt 1 This constraint says that for the metaclass data Attribute we require that the name be more than one characters long If this expression evaluates to false the error message given before the colon will be reported A checks file can contain any number of such constraints They will be evaluated for all instances of the respective metaclass To show a somewhat more involved constraint example this one ensures that the names of the attributes have to be unique context Entity ERROR Names of Entity attributes must be unique attribute forAll al attribute notExists a2 al a2 amp amp al name a2 name 1 9 2 Integration into the workflow file The following piece of XML is the workflow file we d already used above lt xml version 1 0 encoding windows 1252 gt lt workflow gt lt property file workflow properties gt oAW Version 4 2 19 EMF Tutorial lt component id xmiParser class org openarchitectureware emf XmiReader gt lt component gt After reading the model we add an additional component namely the CheckComponent lt component class org openarchitectureware check CheckComponent gt As with the code generator we h
163. ing s FOR String gt gt log invoking lt lt targetDef name gt gt with this lt lt targetDef proceed gt gt lt lt ENDAROUND gt gt 6 6 Built in types API documentation 6 6 1 Object Super type none Table 6 1 Properties Name Deserption O O Table 6 2 Operations ga ooo compareTo Object Compares this object with the specified object for order Returns a negative integer zero or a positive integer as this object is less than equal to or greater than the specified 6 6 2 String Super type object Table 6 3 Properties Integer he length of this string oAW Version 4 2 102 Xtend Xpand Check Reference Table 6 4 Operations Return type String Converts all of the characters in this String to upper case using the rules lof the default locale from Java Converts all of the characters in this String to lower case using the rules lof the default locale from Java Splits this string around matches of the given regular expression from ava 1 4 Returns a copy of the string with leading and trailing whitespace omitted from Java 1 4 Object concatenates two strings replaceAll String String Replaces each substring of this string that matches the given regular expression with the given replacement subString Integer Integer Tests if this string ends with the peptone ie prefix lendsWith String Tests if this string ends with the eee ie pre
164. irement Enti managedEnti lt lt Dependency gt gt 4 Figure 15 6 Tutorial Metamodel We have to provide the metaclasses that make up our DSL The base metaclasses class and Attribute are provided by openArchitectureWare within the package org openarchitectureware meta uml and its subpackages 15 8 1 Defining the metaclasses Create a package oaw4 demo classic uml meta This package will contain our metaclasses which realize the UML profile we want to use As you can see from the model above we use the Stereotypes Entity Key and DAO For these Stereotypes we need metaclasses oAW Version 4 2 168 Classic UML Tutorial Metaclasses are derived from UML metaclasses oAW4 provides implementation classes for UML metaclasses For example an Entity is represented by classes so the right metaclass to extend is Class while Keys are a specialization from Attribute In the simplest case you will only have to create the classes Entity Key and pao and derive them from the base metaclasses Class and Attribute defined in package org openarchitecture meta uml classifier package oaw4 demo classic uml meta public class Entity extends org openarchitectureware meta uml classifier Class nothing to do in the simplest case package oaw4 demo classic uml meta public class Key extends org openarchitectureware meta uml classifier Attribute package oaw4 demo classic uml meta public class DA
165. is case the feature from the StringTypeImpl Here is another example that uses the JavaBeansMetaModel strategy This strategy provides as additional feature the access to properties using the getter and setter methods For more information about type systems see the Expressions Reference Documentation We have one JavaBean like meta model class package mypackage public class MyBeanMetaClass private String myProp public String getMyProp return myProp public void setMyProp String s myProp s Additional to the already builtin metamodel type system we register the JavaMetaModel with the JavaBeansStrategy for our facade Now we can use also this strategy in our extension setup facade XtendFacade f XtendFacade create myext JavaBeanExtension setup additional type system JavaMetaModel jmm new JavaMetaModel JavaMM new JavaBeansStrategy f registerMetaModel jmm use the facade MyBeanMetaClass jb MyBeanMetaClass jb setMyProp test f call readMyProp new Object jb The called extension file looks like this oAW Version 4 2 83 Xtend Xpand Check Reference import mypackage readMyProp MyBeanMetaClass jb jb myProp 6 4 9 WorkflowComponent With the additional support for model transformation it makes sense to invoke Xtend within a workflow A typical workflow configuration of the Xtend component looks lik
166. ish oAW Version 4 2 7 EMF Tutorial ae New EMF Model Select a wizard Ea TE BH select a Model Importer Create the Ecore and generat Create the Ecore model based on other Ecore or EMOF models EMF Model Create the generator f Wizards Model Importers type filter text AD Annotated Java G Class Ecore model 3 SY Interface Rose class model 28 Java Project i S XML Schema 3 Java Project from Exi Plug in Project Y gt General H E Connection Profiles He cvs E S Eclipse Modeling Fra IE EMF Model ei EMF Project 7 Empty EMF Projeq HG EJB Example EMF Model q IE Data Graph Model 7 Ecore Model ig Ecore to Ecore Md z Ecore to XML Mod 1 Ecore Import S X5SD Model Saf XSD to Ecore Mod Enter or select the par oaw4 demo emF data E model amp src i Finish Cancel File name data genmodel a 2 New EMF Model A X Specify one or more ecore or emof URIs and try to load them Model URIs Browse File System Browse Workspace platform resourcejoaw4 demo emf datamodel metamodel data ecore 4 Figure 1 6 Creating the genmodel As a consequence voull get the finished EMF genmodel It is a kind of wrapper around the original metamodel thus it has the same structure but the model elements have different properties
167. ith UML2 Example You need an installation of oAW 4 1 including the UML2 support Run the UML2 example available for download on the oAW download page to verify that you have all the UML2 stuff installed Then download the sample code for this tutorial and put the project into your workspace Should look something like this then El Ty gt org openarchitectureware utilumlZecore architecturwe SI src E amp R org openarchitectureware umlZecore J 1OExtensions java 1 2 ASCII kkv AK TypeMapper java 1 2 ASCII kky EQ iovext 1 2 ASCII kkv Q uml2Constraints chk 1 2 ASCII kkv E umiZecore ext 1 2 ASCII kkv umlZecoreWorkflow oaw 1 3 ASCII kky BA JRE System Library JRE 1 5 BA Plug in Dependencies a test E org openarchitectureware umlZecore test Elf data kel entity mdzip 1 1 Binary entity mdzip bak entity uml2 1 1 ASCII kkv L model jpg 1 1 Binary W umML_Standard_Profile MagicDraw_Profile p 81 UML_Standard_Profile UML_Standard_Prof E runtests oaw 1 2 ASCII kkv Q tests chk 1 2 ASCII kkv EA testUtilext 1 2 ASCII kkv META INF H E stuff lon build properties 1 1 ASCII kkv 7 1 18 4 The Building Blocks of the Transformer The first thing you should look at after reading the uml2ecore user guide is the workflow file It reads the UML2 model checks a couple of constraints against it and then invokes the transformation We then
168. ivate void handleEntity Entity e DataFactory f for Iterator iter EcoreUtil2 clone e getAttribute iterator iter hasNext Attribute a Attribute iter next oAW Version 4 2 27 EMF Tutorial We create a new attribute with the same type and a name with a 2 postfixed We then add this new attribute to the entity Attribute a2 f createAttribute a2 setName a getName 2 a2 setType a getType e getAttribute add a2 To execute this component we just have to add it to the workflow lt component class datamodel generator Transformer gt lt modelSlot value model gt lt component gt We have to specify the model slot The super class SimpleJavaTransformerComponent provides the slot setter and passes the object from that slot to the doTransform operation oAW Version 4 2 28 Chapter 2 Xtext Tutorial This tutorial shows how easy it is to define an external DSL 2 1 Installing the pre built tutorial The tutorial is based on the Xtext framework as it is contained in oAW 4 2 Make sure that you have installed oAW 4 2 into an Eclipse 3 3 workbench running on Java gt 5 The easiest way to get a working IDE is to download the Eclipse 3 3 distribution for RCP Plug in developers from eclipse org and the oAW all in one release from oAW s website 2 2 Tutorial overview The purpose of this tutorial is to illustrate definition of
169. k Reference switch case booleanExpression thenExpression default catchAllExpression 6 3 5 Chain expression Expressions and functional languages should be free of side effects as far as possible But sometimes there you need invocations that do have side effects In some cases expressions even don t have a return type i e the return type void If you need to call such operations you can use the chain expression Syntax anExpr gt anotherExpr gt lastExpr Each expression is evaluated in sequence but only the result of the last expression is returned Example pers setName test gt pers This chain expression will set the name of the person first before it returns the person object itself 6 3 6 create expression The create expression is used to instantiate new objects of a given type new TypeName 6 3 7 let expression The let expression lets you define local variables Syntax is as follows let v expression in expression with v This is especially useful together with a chain and a create expressions Example let p new Person in p name John Doe gt page 42 gt I VINGIY Neale D 6 3 8 GLOBALVAR expression Sometimes you don t want to pass everything down the call stack by parameter Therefore we have the GLOBALVAR expression There are two things you need to do to use global variables within one of the openArchite
170. ke toFirstUpper toFirstLower regular expressions etc often needed in code generation templates s Boolean Boolean Offers the usual operators Java syntax amp amp Il etc Integer and Real Integer and Real offer the usual compare operators lt gt lt gt and simple arithmetics Note that Integer extends Real 6 2 2 4 Collection types The type system has three different Collection types collection is the base type it provides several operations known from java util Collection The other two types List Set correspond to their java util equivalents too 6 2 2 5 Types types The type system describes itself hence there are types for the different concepts These types are needed for reflective programming To avoid confusion with meta types with the same name it s not unusual to have a meta type called operation for instance we have prefixed all of the types with the namespace oaw We have oaw Type oaw Feature oaw Property e oaw StaticProperty oaw Operation 6 2 3 MetaModel Implementations aka Meta Meta Model By default the type system only knows the built in types In order to register your own meta types e g Entity or State you need to register a respective MetaModel implementation with the type system Within a MetaModel implementation the oAW typesystem elements Type Property Operation are mapped to an arbitrary other typesystem Java reflection
171. l It is not recommended to use this alternative This alternative is for backward compatibility in oAW3 metaclasses usually used this method to check model constraints e Using the new Check language oAW4 has a new language named Check that can be used to check model constraints In this example we will focus on this method You may want to read the reference manual of the Check language r30_checkReference pdf for more information TODO Reference to Check chapter e Using a third party library e g an OCL library The example t35_oclExample pdf shows how to integrate an OCL library for model validation This is out of scope for this example TODO Reference to OCL Adapter We want to implement constraint checks by using the Check language The syntax for check files is similar to those for Extensions as it uses also the oAW Expressions framework Check files have the file extension chk and must be found on the classpath 15 19 2 Constraints to implement in the example In our example we want to implement the following constraint 1 Each navigable association end must have a role name 2 Unnavigable association ends should have no role name Constraint 1 must be fulfilled otherwise an error message should be printed and the generation process should not be started If constraint 2 is not fulfilled a warn message should be printed but the generation process should not be stopped 15 19 3 Creating the Check file As the constraints
172. l OVEr vie Weis seis o isi sinc ele TE e see oped eb uae E E EE aleve e be wee ned anes 29 23 B TET the DS Erytrei Bek abs Gases a auto Eed chinale sas E oan e E Sea noose 29 2 3 Creating Xtext projects aiia eee E E E E eel Le dae 30 2 3 27 Defining the sramimar sooie eee eed Ea ae eee Re E 32 2 3 55 Starting the SeNerator oiri saad esearch eae Cus utes ee Bat oe AR K ea 33 2 3 4 Starting a runtime Workbench THH 34 2 4 Retining the DST Trene e tial Oe eta oh tae A a E eee 35 244 Validation with Check enion ei re ay hai Ea A ee a a 38 25s Generating Coden stares Mads es Rl seal eet Se AN Oh E E OE asin dt ae eb ech ae 39 2 5 1 Code generation with Xpand THT 40 2 6 Installing everything into Eclipse sese eee eee eee 41 A EAEE santa ts katy sl bak nota cad shah wan sah bed cua gous tach ind cash Sod laca se scaaslisbu lows iadaaned sg avedeae TT 47 3 OAW 4 Eclipse Integration senesnio ereina in iiaee iie riia ii eiiie 48 oAW Version 4 2 iii openArchitectureW are User Guide 3 L INtrOMUCHION seisoa einan eos iecadiedee ee achive se sa eae oe ends ade 48 3 2 Installation cis sss sees cocade ste dsbet io e EE EEI bes ical daaas es E soe EE aad 48 33 OVEIVICW oieracea EEEE EEE RA EE En Meala dais ele E soe a eda ies iecades 48 3 4 Fil AECOratiONs macio n i E tin vebva cha vlsdandeveleds eashace vin ESETE ES REEE AEETI 48 33 Edito S e ee e a Sees chs eee Raa OEA Aa AE Ea aa OREA EAE aaa EEEE 48 3 51 Syntax COONS vre ae
173. l preceding whitespace up to the newline character excluded is removed Additionally all following whitespace including the first newline character r n is handled as one character is also removed 6 5 4 Aspect Oriented Programming in Xpand Using the workflow engine it is now possible to package e g zip a written generator and deliver it as a kind of black box If you want to use such a generator but need to change some small generation stuff you can make use of the AROUND aspects AROUND qualifiedDefinitionName parameterList FOR type a sequence of statements ENDAROUND AROUND lets you add templates in an non invasive way you don t need to touch the generator templates Because aspects are invasive a template file containing aRouND aspects must be wrapped by configuration see next section oAW Version 4 2 94 Xtend Xpand Check Reference 6 5 4 1 Join Point and Point Cut Syntax AOP is basically about weaving code into different points inside the call graph of a software module Such points are called Join Points In Xpand there is only one join point so far a call to a definition You specify on which join points the contributed code should be executed by specifying something like a query on all available join points Such a query is called a point cut AROUND pointcut eo EEE ENDAROUND A pointcut consists of a fully qualified name parameter types and the target type 6
174. lass in the Ecore model While this statement is true it is also on the same level of genericity as the transformation itself It s therefore not much less complex and therefore as error prone as the transformation itself Instead what you should do is the following e Define a reference model This model should contain all the possible alternatives of creating input models i e should cover the complete variability of the meta model s Then run the transformation on that reference model s Finally write model specific constraints that verify the particular result of the transformation So in our example we have a small meta model modelled in UML using abstract and nonabstract classes inheritance attributes 1 n and 1 1 references bidirectional and unidirectional The model in our case is drawn with MagicDraw 11 5 and exported as an UML2 model You find all the model contents in the following location test org openarchitectureware uml2ecore test data Here s a screenshot of the model oAW Version 4 2 195 Model To Model Figure 18 1 Model example You now run the transformation using a workflow file that looks as follows test org openarchitectureware uml2ecore test runtests oaw This workflow basically just invokes the transformation just as any other user of the transformation However in addition after the transformation has finished we validate test specific constraints This is what the additional constraint ch
175. led Please consider http www eclipse org gmt oaw download for details You can also install the code for the tutorial It can be downloaded from the URL above it is part of the the EMF samples ZIP file Installing the demos is easy Just add the projects to your workspace Note that in the openArchitectureWare preferences either globally for the workspace or specific for the sample projects you have to select EMF metamodels for these examples to work 1 2 Tutorial overview The purpose of this tutorial is to illustrate code generation with openArchitectureWare from EMF models The process we re going to go through will start by defining a meta model using EMF tooling coming up with some example data writing code generation templates running the generator and finally adding some constraint checks The actual content of the example is rather trivial we will generate Java classes following the Java Beans conventions The model will contain entities such as Person or Vehicle including some attributes and relationships among them a rather typical data model From these entities in the model we want to generate the Beans for implementation in Java In a real setting we might also want to generate persistence mappings etc We will not to this for this simple introduction 1 3 Defining an EMF metamodel To illustrate the metamodel before we deal with the intricacies of EMF here is the metamodel in UML oAW Version 4 2 2
176. les as well as their getter and setter methods is a very recurring task for attributes so we want this in a central template file Create the file attribute xpt in folder java IMPORT org openarchitectureware meta uml classifier DEFINE PropertyDeclaration FOR Attribute private Type NameS NameS ENDDEF INE DEFINE Getter FOR Attribute public Type NameS get NameS toFirstUpper return this NameS ENDDEF INE DEFINE Setter FOR Attribute public void set NameS toFirstUpper Type NameS NameS this NameS NameS ENDDEF INE Of course we also have to call these templates from our JavaBean template We want to call the templates PropertyDeclaration Getter and Setter for each attribute a class has So open your JavaBean xpt template and extend it like follows IMPORT org openarchitectureware meta uml classifier DEFINE BeanClass FOR Class FILE NameS Jjava public class Name EXPAND Attribute PropertyDeclaration FOREACH Attribute EXPAND Attribute Getter FOREACH Attribute EXPAND Attribute Setter FOREACH Attribute ENDF ILE ENDDEF INE Once again run the generator Now your generated files have properties public class Author oriye e T private String name oAW Version 4 2 176 Classic UML Tutorial public String getId ereUl ENES LE publi
177. let gt lt component gt oAW Version 4 2 130 UML2 Example If you run the workflow by right clicking on the oaw file and select Run As gt oAW Workflow the two Java classes should be generated 9 5 Profile Support openArchitectureWare 4 is shipped with a special UML2Profiles metamodel implementation The implementation maps Stereotypes to Types and Tagged Values to simple properties It also supports Enumerations defined in the profile and Stereotype hierarchies 9 5 1 Defining a Profile To define a profile you can use a variety of UML2 based modelling tools Assuming they do actually correctly create profile definitions which is not always the case as we had to learn painfully creating a profile and exporting it correctly is straight forward In this section we explain the manual way which is good for explaining what happens but completely useless for practical use You don t want to build realisitically sized models using the mechanisms explained below You start be creating a new UML2 file as shown above In the example we ll call it test profile uml The root element however will be a Profile not a Package Don t forget to actually assign a name to the profile It should be test too As a child of that Profile you then create a Packaged Element Stereotype you ll have to scroll a bit in the Add Child menu For the sake of example we ll call it test too In our case we want to make the
178. lt 0 00si th ete di adhe ea ee 166 15 6 Create Source folders oe 3 fo sutceat a ews dis ale E aae a E E KE bein stunted CabALY tases be 166 15 75 Create the Les cvs sevs eere ae eie aoi Wissel sbesvondtetbll cheeses ised stessoce cobble cbies 167 15 8 Dehining the metamod l srce renere ea cteteetade adel a iE aaa ai E aeia e a i E a i satel 168 15 851 Detining the eL no i a e a a E E E E E E e A 168 1528 2 Metamappings een e a EE E EA EE E E A E e E tedetes 169 15 9 Los4j configuration s eee eiieeii te iaie e aiaa TTT eia iae an 169 oAW Version 4 2 vii openArchitectureW are User Guide 15 10 Creating the generator workflow and the first template sss eee sees ee eee eee ee eee 170 15 10 1 The workflow Script s1 c ccc c scseceiesedeeceee cece deseiedecseshevedesebedeee cs ia a 170 15 10 2 Workflow Properties s 2c0 500s0seveeees Egaye saae e a e eS 171 15 10 3 Create the root template ionii ees eeeeeseeeeenerenereneeeeeesaeaeaeaeaeaeaeaeaeaeaeaeaeaeea 172 15 11 Execute the worktlow jcns vanities deh nae a ee eae 173 15 12 Looping through the model aaas ada titeit iae ene ERE veka ged sans Maceo EEEE ER 174 15 13 Creating a template for JavaBean sese eee 175 15 14 Calling the JavaBean template from Root xpt esse 175 15 15 The first senerated COde cara aeaaee EE a EE EERE ETARE RERE E EEEE SORES Ea EVERE Vaes 176 15 16 Defining property declarations and accessor methods sss sss 176 15 1
179. m templates helper NamingHelper for Package names implBasePackageName SCMComponent c c PackageName impl and for Check editor D Root xpt EE limport scm mm base import scm mm bc context SCMOperation ERROR you can only use exceptions Exception foraAll e SCMA bstractException isInstanc context SCMOperation ERROR class must be specified this hasClass 3 5 2 Code completion The Editors provide extensive code completion support by pressing Ctrl Space similar to what is known from the Java editor Available types properties and operation as well as extensions from ext Files will be found The Xpand editor provides additionally support for the Xpand language statements 0 x IMPORT sem imm comp IMPORT scm mm ex DEFINE Root FOR scm mm 5CMTop EX exists String Boolean CustomModelElement EXPAND EXTENSION 3 5 3 Xpand tag delimiter creation support In the Xpand editor there is an additional keystroke available to create the opening and closing tag brackets the guillemots and Ctrl lt creates and Ctrl gt creates oAW Version 4 2 49 oAW 4 Eclipse Integration 3 6 Preference pages 3 6 1 Meta model contributors The openArchitectureWare framework version 4 supports several types of meta metamodels From older versions the classic UML metamodels may be known Currently also JavaBeans metamodels a
180. me Entity e return e getName ImplBase public static String baseClassFileName Entity e return baseClassName e java public static String implementationClassName Entity e return e getName Note the additional property implementationClassName This is the name of the class that developers have to write manually While we expect that the generated code goes into the src gen directory we want the manually written code in man src Here is the generated base class for the Person entity generated at 1138622360609 public abstract class PersonImplBase private String name public void setName String value this name value public String getName return this name The manually written subclass could look as follows public class Person extends PersonImplBase oAW Version 4 2 24 EMF Tutorial Now here s the issue how do you make sure that developers actually write this class that it has the right name and that it actually extends the generated base class This is where the recipe framework comes into play We want to define rules that allow Eclipse to verfy that these programming guidelines have been met by developers 1 11 3 Implementing the Recipes As of now there is no specific language to implement those recipe checks you have to write a bunch of Java code In summary you have to implement a workflow component that produces the
181. mplate AOP is useful Here are two examples Scenario 1 Assume you have a nice generator that generates certain artefacts The generator or cartridge might be a third party product delivered in a single JAR file Still you might want to adapt certain aspects of the generation process without modifying the original generator Scenario 2 You are building a family of generators that can generate variations of the generate code e g implementations for different embedded platforms In such a scenario you need to be able to express those differences variabilities sensibly without creating a non understandable chaos of if statements in the templates 6 5 8 Example To illustrate the idea of extending a generator without touching it let s create a new project called oaw4 demo emf datamodel generator aop The idea is that it will extend the original oaw4 demo emf datamodel generator project introducedin the emfExample So this new projects needs to have a project dependency to the former one 6 5 8 1 Templates An AO system always needs to define a joinpoint model this is you have to define at which locations of a template program you can add additional template code In Xpand the joinpoints are simply templates i e DEFINE ENDDEFINE blocks An aspect template can be declared AROUND previously existing templates If you take a look at the oaw4 demo emf datamode1 generator project s source folder you can find the R
182. mpletely new model usually based on a different metamodel from an input model The transformation has no side effects wrt to the input model 2 A model modification completes extends finishes modifies a model No additional model is created Please take a look at the xTend Example tutorial to understand model transformations with the xTend language 1 12 1 Model Modifications in Java One way of doing modifications is to use Java Take a look at the following piece of Java code We extend froma class called simpleJavaTransformerComponent Instead of directly implementing the work f lowComponent interface we inherit from a more comfortable base class and implement the doModification operation public class Transformer extends SimpleJavaModificationComponent protected void doModification WorkflowContext ctx ProgressMonitor monitor Issues issues Object model We know that we have a Dat aModel object in the model slot you can see in a moment where the model comes from DataModel dm DataModel model We then get us the factory to create new model elements what this code does exactly you should learn from the EMF docs DataFactory f DataPackage eINSTANCE getDataFactory We then iterate over all entities for Iterator iter dm getEntity iterator iter hasNext Entity e Entity iter next handleEntity e f For each Entity pr
183. n This tutorial does not explain too much it s rather a guide through the example code We expect that you know how to work with openArchitectureWare and EMF If that s not the case you should read and play with the emfHelloWorld example first the tutorial entitled Generating Code from EMF Models 17 2 Installation You need to have openArchitectureWare 4 2 installed Please consider http www eclipse org gmt oaw download for details You can also install the code for the tutorial It can be downlaoded from the URL above it is part of the the EMF samples ZIP file Installing the demos is easy Just add the projects to your workspace Note that in the openArchitectureWare preferences either globally for the workspace or specific for the sample projects you have to select EMF metamodels for these examples to work In the emf examples package you can find the following three projects oaw4 demo emf statemachine contains the metamodel oaw4 demo emf statemachine generator contains the code generator e oaw4 demo emf statemachine example contains an example state machine as well as a manually written unit test 17 3 Metamodel The metamodel looks more or less as you d expect from a state machine metamodel The following is the representation of the metamodel in Emfatic syntax You can find it in the oaw4 demo emf statemachine model package namespace uri http oaw statemachine prefix statemachine pa
184. n F3 address Open With gt Y Address Show In XSW K street zip Copy C city Copy Qualified Name 5 Paste V Delete Build Path gt Refactor XET gt s Import t Export a Refresh FS Fe EREE RA K Assign Working Sets src gen gt 6 6 Validate LC al Mark as Landmark OST S amp Remove from Context XS1 K J 71 Run on Server OXXR Tp Sar As gt B 2 oAW Workflow _ BA Plug in Depende ae K c T X AY 8 7 D E 8 Team gt Open Run Dialog d S maite Compare With gt Q Open External Tools Dialog oi build properties L Replace With gt Source b Properties g mydslproject oaw mydslproject src a 9 SEP P Figure 2 23 Start the workflow The generator finished successfully and the src gen folder contains the generated Java classes oAW Version 4 2 Xtext Tutorial Te e Java mydslproject src model dsl Eclipse SDK Users user Desktop temp Ile K O Q 8 6 B GV O o F e ero E sava Z Package Expl 83 _ fg Hierarchy 0 E model ds C PBI B outline 52 D 5 amp datatypes r p7 B datatype String z Y amp mydsiproject datatype Integer String Y src Integer B model ds Y Person m jsl S Nas P Y src gen entity Person L age Y default package String name address v D Address java Integer age Y Z Address wv Address Address address street a city 7 L zip Rian entity Address a Sey
185. n also run the generator from your own application code Two things to note 1 the contents of the properties map override the properties defined in the workflow 2 The slotContents map allows you to fill stuff into the workflow from your application This is a typical use case you run oAW from within your app because you already have a model in memory oAW Version 4 2 63 Workflow Reference String wfFile somePath workflow oaw Map properties new HashMap Map slotContents new HashMap new WorkflowRunner run wfFile new NullProgressMonitor properties slotContents 5 3 3 4 Starting from Eclipse You can also run a workflow file from within Eclipse if you have installed the oAW plugins Just right click on the workflow file whatever oaw and select Run As gt oAW Workflow See the plugin documentation for details oAW Version 4 2 Chapter 6 Xtend Xpand Check Reference 6 1 Introduction The oAW4 generator framework provides textual languages that are useful in different contexts in the MDSD process e g checks extensions code generation model transformation Each oAW language Check Xtend and Xpand is built up on a common expression language and type system Therefore they can operate on the same models metamodels and meta metamodels and you don t need to learn the syntax again and again because it is always the same The expressions framework provides a uniform abstraction
186. n an Xtext grammar file describing your little language Next up you need to start Xtext s generator in order to get a parser a metamodel and an editor To do so just right click the workflow file oaw located next to the grammar file and choose Run As gt Run Workflow in Eclipse of course The generator will read the grammar file in and create a bunch of files Some of them located in the src gen directories others located in the src directory IMPORTANT You should now after first generation open the properties file and set the overwritePluginRes true option to false oAW Version 4 2 118 Xtext Reference from oAW 4 2 7 6 1 Configuring the generator The generator can be configured with the following properties definied in generate properties property name default description grammar he grammar file to generate the code from debug grammar false Specifies whether a debug grammar should be generated A debug grammar is an antlr grammar without any action code so it can be interpreted within Antlrworks language name he name of the DSL Is used throughout the generated code language nsURI http A unique URI used within the derived ecore package www oaw org xtext dsl language name language fileextension he file extension the generated editor is configured for language name overwrite pluginresources false lT this is set to true the plugin resources META INF MANIFEST MF plugin xml
187. n which says that a description of an entity starts with the keyword entity A so called Assignment follows name ID The left hand refers to a property of the Metatype in this case it s the property name of type Entity The left hand side is a call to the built in token ID Which means Identifier and allows character sequences of the form a zA Z_ a zA Z_0 9 The parser will assign the Identifier to the specified property name Then enclosed in curly brackets and both are essentially keyword tokens one or more features can be declared features Feature This one again is an assignment This time the token points to another rule called Feature and each feature is added note operator to the Entity s reference called features The Feature rule itself could be described like this Peature s type ID name ID so that the following description of an entity would be valid according to the grammar entity Customer String name String street Integer age Boolean isPremiumCustomer Note that the types String Integer Boolean used in this description of a customer are simple identifiers they don t have been mapped to e g Java types or something else So according to the grammar this would also be valid so far entity X KCR ORF XOX cjbdlfjerifuerfijerf dkjdhferifheirhf oAW Version 4 2 111 Xtext Reference from oAW 4 2 7 4 2
188. name size 1 context Feature ERROR Duplicate feature name entity features select ele name name size 1 Figure 2 14 Validating the model with Check The first thing you usually do in a check file is to import the used meta models import myds1 The next line extension org example dsl Extensions imports an extension file Extension files contain so called extensions which are essentially functions The syntax of a check starts with the keyword context followed by the meta type e g Type we want to apply the constraint to Then one has to specify whether the severity is ERROR or WARNING using the appropriate keyword A message for the user follows Note that you can use the model element which is actually checked through the imlied this variable This means we could have written Duplicate type this name instead The condition which should hold i e evaluate to true for all instances of the given type is separated by a colon The expressions used here and in the message are oAW expressions See the reference documentation of the core languages Check is one of them for details We use two extensions here The first one is called all1Elements and has been generated by Xtext It returns a list of all model elements containd in the model typeSelect Type selects all elements which are of type Type From that list we select all elements which have the same name as the actually checked model element The constraint
189. nd EMF based metamodels are supported out of the box Additional Metamodel contributors can be registered through an extension point The editors need to know with what kind of metamodels you are working Therefore one can configure the metamodel contributors on workspace and on project level 3 6 2 Global preferences If you work always with the same type of metamodels you can specify the metamodel contributors in the global preference page It is available under Windows gt Preferences in the openArchitecture Ware section 3 6 3 Preferences per project In the project property page there is also an openArchitectureWare section available Therein you can enable the openArchitectureWare Nature see below and set project specific metamodel contributor settings Properties for oaw4 demo classic scm generator jo x type filter text openArchitectureware ees Info Builders Enable opendrchitectureWare nature IV cvs lt rare lt Java Build Path Enable project specific settings Iv E Java Code Style Select metamodel contributor Joaw Classic Metamodel lt Y Java Compiler JavaBeans Metamodel Javadoc Location o Ww Classic Metamodel openarchitectureware MF Metamodels Project References Restore Defaults Apply cme 3 7 oAW Nature and oAW Builder You have seen in the last screenshot that you can switch the openArchitectureWare nature on If you do so you enable analysation support for all oAW speci
190. ne na EN AE E RENERE o a casas EAE eens Les ee hae 48 39 2 Code TTS ee vtec ene a kire aaee ORERE A ASEE ERE EEAS teases Geen as 49 3 5 3 Xpand tag delimiter creation support sese ee eee e ee eee 49 3 0 Preference Pagesa ne Eai NAT N EA EAEAN AEE NA AREEN OEA TAEAE EREA 50 3 6 1 Meta model Contributors eiras naea a EEEE EE EEEN EE A Erara 50 3 60 26 Global preferences orrn en ionene anren e aeae ERR eraa aee nees eet 50 3 0 3 Preferences per PrOjeCt ror erneer neeaae eitia ETETE EES EAEE EAR EEEE EEEE EnS 50 3 7 oAW Nature and OAW Builder 2 0 00 cee ececcececcceneeeeseecececececeaaeaeneececececeaauaneesececeeeaqaaeegss 50 Sef R Problem Markers ieee os sd eee ady eden ree dates ig do eens de Soak ade Bea sgua dees ved EEE Eiio 50 3 8 RUNMING a WOPKELOW a wi2sccesadessSevehcnamesees E Aa O bees REE E EE cided cesadetebeattce ebessguansdecsd ces 31 Ais MAS PAG OR e eree ee ta Seus vies eases e E eas Pea pees eee pas Sate E pasa Seen ada cece E cee gab ee tiant 53 4 1 Migrate from OAW 4 1 2 to OAW 4 2 Loess ee eee een E Aa E E E EEren ESE asint 53 4 11 Pligin Dependencies isrener e E a aa Oa deasteneabacate 53 A I C D T E PE E E A E EEA 53 TW REPETEN CE TTT 54 5 Workflow Reference se maent meitsen aen aa a aa s na s eae e aa a a e adast 55 Dis Introduction ierra ns nieee leases woke EE E O OAOE ie E E ETES ene EEA 55 5 2 Workflow cOMpOneNtS ess sirip aarre ispio aa aiina anaiei E iesecdsespawecaseeesens 55 SDV W OTT OW oaen tes Bebe ve
191. nent gt lt component class oaw emf XmiReader gt lt component gt lt component class oaw xpand2 Generator gt lt metaModel class oaw uml2 UML2Met aModel gt oAW Version 4 2 140 RSM RSA Adapter lt metaModel class oaw uml2 profile ProfileMetaModel gt lt profile value pathmap UMLMDA_PROFILE UMLMDAProfile epx gt lt metaModel gt lt component gt lt workflow gt 11 3 3 Workflow using profiles from workspace projects If the RSA RSM profiles are installed in a workspace project rather in a plugin it can be accessed with a workflow below lt workflow gt lt property name umlmda profile project path value C devel umlmda rsm7 org umlmda um12 profile gt lt initializes resourcemaps urimaps etc gt lt component class org openarchitectureware rsdp workflow RSASetup gt lt umlExtensionProject class org openarchitectureware rsdp workflow UmlExtensionProje ie lt projectName value UMLMDAProfile gt lt path value umlmda profile project path gt lt umlExtensionProject gt lt init value true gt lt component gt lt component class oaw emf XmiReader gt lt modelFile value model gt lt outputSlot value model gt lt component gt lt component class oaw xpand2 Generator skipOnErrors true gt lt metaModel class oaw type emf EmfMetaModel metaModelPackage org eclipse emf ecore EcorePackage gt lt metaModel class oaw uml2
192. ng extensions in order to transform an Ecore EMF model to our metamodel Package Class Reference toPackage EPackage x let p new Package p ownedMember addAll x eClassifiers toClass gt Pr toClass EClass x let c new Class c attributes addAll x eReferences toReference gt C toReference EReference x let r new Reference r setType x eType toClass gt r For an ecore model of the structure from above the result would be ir CIECZ I What happend The C2 class has been created 2 times one time for the package containment and another time for the Reference s reference We can solve the problem by adding the cached keyword to the second extension oAW Version 4 2 81 Xtend Xpand Check Reference cached toClass EClass x let c new Class c attributes addAll c eAttributes toAttribute gt Cr The process goes like this 1 start create P a start create C1 contained in P i start create R contained in C1 A start create C2 referenced from R B end result C2 is cached ii end R b end C1 c start get cached C2 contained in P 2 end P So this works very well We will get the intended structure But what about circular dependencies For instance C2 could contain a Reference R2 of type C1 bidirectional references The transformation would occurr like this 1 start create P a start create C1 contained in P i start create
193. ng is turned on see the end of this document For the simple example please set the value to be false the nsUriPrefix is used to assemble the namespace URI The name of the meta model as well as the insPrefix will be derived from the UML model name so in our example the nsPrefix and the name of the generated EPackage will be enttymm The complete Inamespace URL also required by Ecore is created by concatenating the nsUriPrefix given here and the name The resulting namespace URL in the example will thus be http www voelter de entitymm determines which packages the transformer should consider when transforming the model note that the contents of all the packages will be put into the root EPackage It set to true the generator will write a separate ecore file for each of the top level packages in you UML model Useful for modularizing meta models see the lend of this chapter If set to true all unnamed navigable association ends will be initialized with the name of the target type You can now run this workflow by selecting Run As gt oAW Workflow The name of the generated Ecore file will correspond to the name of the root Model element in the UML model 13 6 The generated Model Here s a screenshot of the generated model oAW Version 4 2 153 UML2Ecore Reference 1 wF oaw entity ecore le platform resource oaw4 demo util umlZecore entity ecore E entitymm E Type gt Named H E
194. not available or if white space has syntactical meaning as in Python you would have to write your templates with that in mind using the minus character before closing brackets as described in a preceding section The Xpand workflow component can be configured with multiple beautifiers lt beautifier class org openarchitectureware xpand2 output JavaBeautifier gt lt beautifier class org openarchitectureware xpand2 output XmlBeautifier gt These are the two beautifiers delivered with Xpand If you want to use your own beautifier you would just need to implement the following Java interface package org openarchitectureware xpand2 output public interface PostProcessor public void beforeWriteAndClose FileHandle handle public void afterClose FileHandle handle The beforeWriteAndClose method is called for each ENDFILE statement 6 5 5 5 1 JavaBeautifier The JavaBeautifier is based on the Eclipse Java formatter provides base beautifying for Java files 6 5 5 5 2 Xm IBeautifier The XmlBeautifier is based on dom4j and provides a single option ileExtensions defaults to xml xsl wsdd wsdl used to specify which files should be pretty printed 6 5 5 6 Protected Region Configuration Finally you need to configure the protected region resolver if you want to use protected regions lt prSrcPaths value main sre gt lt prDefaultExcludes value false gt lt prExcludes value
195. nsists of a list of configured WorkflowComponents Here s an example lt workflow gt lt component class my first WorkflowComponent gt lt aProp value test gt lt component gt lt component class my second WorkflowComponent gt lt anotherProp value test2 gt lt component gt lt component class my third WorkflowComponent gt lt prop value test gt lt component gt oAW Version 4 2 55 Workflow Reference lt workflow gt The workflow shown above consists of three different workflow components The order of the declaration is important The workflow engine will execute the components in the specified order To allow the workflow engine to instantiate the workflow component classes WorkflowComponent implementations must have a default constructor 5 2 1 Workflow A workflow is just a composite implementation of the WorkflowComponent interface The invoke and checkConfiguration methods delegate to the contained workflow components The Workflow class declares an adder 1 method public void addComponent WorkflowComponent comp lt para gt which is used by the workflow factory in order to wire up a workflow see next section Workflow Configuration 5 2 2 Workflow Components with IDs If you want your workflow components to have an ID so that you can recognize its output in the log you have to implement the interface WorkflowComponentWithID and the setID
196. ntainement reference are unique uml2ecore also comes with a utility extension called org openarchitectureware util stdlib naming that can calculate the namespace and the qualifiedName for every model element that has a name Another convenience is the parameter nameUnnamedNavigableAssociationEnds Often you specify a relationship between two metaclasses and give the target end the name of the target metaclass Let s say you specify an association from metaclass Application tO Component It is likely that the target end will be called component By setting the parameter to true all unnamed navigable association ends will get the name of the target class If there is more than one unnamed association only the first one will be modified This would lead to a failing constraint afterwards since at least after this modification all navigable association ends must be named 13 8 Modularizing the meta model file You can modularize the meta model If you specify the resourcePerToplevelPackage t rue parameter to the cartridge call you ll get a separate ecore file for each top level package as well as a separate constraint check file oAW Version 4 2 154 Chapter 14 Classic Reference 14 1 Available UML Tool Adapters Table 14 1 Available UML tool adapters 5 x Enterprise Architect 6 1 MID Innovator MagicDraw 8 9 MagicDraw 10 12 Metamill Poseidon 1 6 Poseidon 2 x Poseidon 3 0 Poseidon 3 1 Poseidon
197. ntains an instance of data DataModel the XMIReader had put the first element of the model into that slot and we know from the data that it is a DataModel we can write the following statement Again notice that model refers to a slot name here lt expand value templates Root Root FOR model gt We then specify where the generator should put the generated code and that this generated code should be processed by a code beautifier lt outlet path srcGenPath gt lt postprocessor class org openarchitectureware xpand2 output JavaBeautifier gt lt outlet gt oAW Version 4 2 18 EMF Tutorial Now we are almost done lt component gt lt workflow gt You also need to add the srcGenPath to the workflow properties file modelFile example data srcGenPath srce gen 1 8 4 Running the generator again So if you restart the generator now you should get a file generated that looks like this public class Person bad practice public String lastName 1 9 Checking Constraints with the Checks Language An alternative to checking constraints with pure Java is the declarative constraint checking language Check For details of this language take a look at the Check Language Reference We will provide a simple example here 1 9 1 Defining the constraint We start by defining the constraint itself We create a new file called checks chk
198. ntation class appProject srcPath EntityHelper implementationClassName e i We then define a second check that checks that the class whose existence has been verified with the check above actually inherits from the generated base class Again we use the Ent ityHelper to come up with the names Note that they will be consistent with the names used in the code generation templates because both use the same Ent ityHelper implementation JavaSupertypeCheck javaSuperclassCheck new JavaSupertypeCheck oAW Version 4 2 25 EMF Tutorial the implementation class has to extend the generated base class appProject EntityHelper implementationClassName e EntityHelper baseClassName e i We then add the two specific checks to the composite check ecc addChild javaClassExistenceCheck ecc addChild javaSuperclassCheck add the composite check to the list of checks we return to the framework checks add ecc and return all the created checks to the framework after we finish iteration over Entities return checks 1 11 4 Workflow Integration Here s the modified workflow file We integrate our new component as the last step in the workflow lt xml version 1 0 encoding windows 1252 gt lt workflow gt lt property file workflow properties gt lt component id xmiParser class org openarchitectureware emf XmiRead
199. ntity 6 5 4 2 Proceeding Inside an advice you might want to call the underlying definition This can be done using the implicit variable targetDef which is of the type xpand2 Definition and provides an operation proceed which invokes the oAW Version 4 2 95 Xtend Xpand Check Reference underlying definition with the original parameters Note that you might have changed any mutable object in the advice before If you want to control what parameters are to be passed to the definition you can use the operation proceed Object target List params There is no type checking here Additionally there are some inspection properties like name paramTypes etc available 6 5 5 Generator Workflow Component This section describes the workflow component that is provided to perform the code generation i e run the templates You should have a basic idea of how the workflow engine works see Workflow Reference A simple generator component configuration could look as follows lt component class oaw xpand2 Generator gt lt fileEncoding value ISO 8859 1 gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelPackage value org eclipse emf ecore EcorePackage gt lt metaModel gt lt expand value example Java all FOR myModel gt S aG Com ture eon gt lt advices value example Advicesl example Advices2 gt lt GHEE COE we Mesie ein gt lt outlet path main src gen
200. ntity gt Type amp attributes Attribute H Attribute gt Named gt entity Entity gt type PrimitiveType 3 H Named name EString Model gt Named ox types Type H PrimitiveType gt Type U Problems Javadoc Declaration Search Console Progress Plug in Dependencies Error Lor Propert Value EFactory Instance i entitymm Name aZ entitymm Ns Prefix entitymm Ns URI tZ http www voelter defentitymm Figure 13 5 Generated Ecore model The generator also creates a constraints file called entitymmconstraints chk which contains a number of constraints currently these are specifically the checks for the minimum multiplicity in references an error is reported if the minimum multiplicity is one but the reference is null or empty respectively You can integrate the generated constraints file into your workflow using the usual approach 13 7 Naming It is often the case the basically all model elements in a model should have a name It might not always be necessary from a domain perspective but it s really useful for debugging Of course you can add a superclass called Named with a single attribute name to all you classes However if you set the addNameAt tribute parameter to be true when calling the uml2ecore cartridge every class which does not inherit from another class gets an additioal name attribute Also constraints that make sure that names within a namespace i e a co
201. o do something with the elements contained in our model A common pattern in the Root template when using UML models is to loop through the model to find the elements that should be expanded A model is an instance of Namespace and all elements directly contained by the model can be accessed through the association OwnedElement The owned elements can be of various types Classes Packages Datatypes and so on Packages are also instances of Namespace so they also have a ownedElement association We use the feature to recursively resolve any element contained in the model tree Now extend the Root xpt template file IM IM DE EN DE EN PORT org openarchitectureware core meta core PORT org openarchitectureware meta uml classifier FINE Root FOR Model EXPAND Root FOREACH OwnedElement DDR R INE FINE Root FOR Package EXPAND Root FOREACH OwnedElement DDEFINE oAW Version 4 2 174 Classic UML Tutorial DEFINE Root FOR Object ENDDEF INE Note that we have added a new import statement because the metaclass Package is in package org openarchitectureware meta uml classifier First the definition Root FOR Model will be called by the generator This will call the definition named Root for all elements that the Model instance contains Look at the last definition This is a catcher for all elements that are found while traversing through the tre
202. oAW Version 4 2 113 Xtext Reference from oAW 4 2 It is also possible to define concrete supertypes like this R E 3 type ID name ID Reference Reference ref containment type ID name ID lt gt oppositeName ID In this case Feature wouldn t be abstract but would be the supertype of Reference If you need multiple inheritance you can simply add an abstract rule Such a rule must not be called from anothe rule Example Model TypeA TypeA TypeC TypeA A TypeB Bes By Vp DAGE 3 WER CommonSuper TypeB TypeC just for the typehierarchy The resulting type hierarchy will look like this Model TypeA TypeB extends TypeA CommonSuper TypeC extends CommonSuper CommonSuper 7 4 4 Enum Rule The enum rule is used to define enumerations For example if you would like to hardwire the possible datatypes for attributes into the language you could just write Attribute type DataType name ID Enum DataType String string Integer int Boolean bool So that this would be valid entity Customer string name string street int age oAW Version 4 2 114 Xtext Reference from oAW 4 2 bool isPremiumCustomer but this would not entity Customer X name type X is not known String street type String is not known case sensitivity 7 4 5 String Rule Xtend provides built
203. odel org openarchitectureware core meta core Model 3525 INFO 7x Package org openarchitectureware meta uml classifier Package 3525 INFO 2x PrimitiveType org openarchitectureware meta uml classifier PrimitiveType 3525 INFO 3525 INFO Starting workflow org openarchitectureware workflow oawclassic classicinit oaw 3525 INFO Starting org openarchitectureware workflow oawclassic ModelInitializer 3525 INFO initializing model elements calling initializeModelElements 3535 INFO Starting org openarchitectureware workflow oawclassic ModelChecker 3535 INFO checking model elements calling checkConstraints 3545 INFO Starting org openarchitectureware check CheckComponent 3765 INFO Starting dirCleaner org openarchitectureware workflow common DirectoryCleaner 3765 INFO Cleaning C dev ide workspace oaw v4 projects oaw4 demo classic uml src gen 3875 INFO Starting generator org openarchitectureware xpand2 Generator 3915 INFO Starting workflow org openarchitectureware workflow oawclassic classicfinish oaw 3915 INFO Starting org openarchitectureware workflow oawclassic MessageOutput 3915 INFO Starting org openarchitectureware workflow oawclassic DumpWriter 3915 INFO writing dump to bin dump 3925 INFO workflow completed in 3385ms Congratulations You have just set up the whole environment to get openArchitectureWare running Now let s do the interesting stuff 15 12 Looping through the model Later on we want t
204. ojects The first one my ds1 is the language project Therein we ll define the grammar and Xtext s generator will place the meta model and the parser in it The second one is named my ds1 editor and contains the Eclipse text editor for our DSL For now it is empty because we haven t defined a DSL and started the generator so far The third project my ds1 generator is called the generator project Actually this is not directly related to Xtext but to oAW in general That means that the Xtext generator doesn t generate a single file into this project However the wizard has placed a workflow file using the DSL parser which we will generate in a second as well as a default Xpand template So we don t need to do any configuration manually Your navigator should look similar to the one in this screenshot oAW Version 4 2 31 Xtext Tutorial Z Package Exp 3 fg Hierarchy D eo alag v if mydsl v src P generate oaw generate properties mydsl xtxt E src gen gt E JRE System Library JVM 1 5 0 M gt BA Plug in Dependencies Y Z META INF MANIFEST MF R build properties Y E my dsl editor G src E src gen Y icons XE default gif gt JRE System Library JVM 1 5 0 M gt BA Plug in Dependencies Y Z META INF MANIFEST MF R build properties Y E my dsl generator Y src vy org example ds P generator oaw D Main xpt gt E JRE System Library JVM 1 5 0 M gt BA Plug in Dependencies Y META I
205. om eclipse org http download eclipse org tools uml12 updates site interim xml The oAW uml2adapter is available from the oAW updatesite http www openarchitectureware org updatesite milestone site xml Go to the project s homepage and find the current location if either of the sites don t work Restart your Eclipse workbench when Eclipse asks you to do so 8 3 Setting up Eclipse You need to configure your project or the whole workspace to use the UML2Adapter Right click on the project and choose properties from the pop up menu Therein open the openArchitectureWare tab activate the checkboxes nature and specific metamodel contributors and add the UMLProfiles metamodel contributor 8 3 1 Profiles in Eclipse If you want Eclipse to register be aware of your specific profile in order to provide static type checking and code completion in the editors the profiles profile uml or profile um12 need to be on the project s classpath e g are contained in a src folder 8 4 Runtime Configuration At runtime you just need the org openarchitectureware um12 adapter 4 1 0 jar You can use Eclipse s dependency mechanism from the PDE as described in the installation section on the getting started page or copy or reference the respective jar directly It doesn t matter you just have to take care that it is on the classpath 8 4 1 Workflow If you have written some Check Xtend or Xpand files and now want to ex
206. on create DataModel this duplicate DataModel s entity addAll s entity duplicate gt setName S name The duplication function for Entities is also a create Extension this time it creates a new Entity for each old Entity passed in Again it copies the name and adds duplicates of the attributes and references to the new one create Entity this duplicate Entity old attribute addAll old attribute duplicate reference addAll old reference duplicate setName old name The function that copies the attribute is rather straight forward but create Attribute this duplicate Attribute old setName old name gt setType old type the one for the references is more interesting Note that a reference while being owned by some Entity also references another Entity as its target So how do you make sure you don t duplicate the target twice Xtend provides explicit support for this kind of situation Create extensions are only executed once per tuple of parameters So if for example the Entity behind the target reference had already been duplicated by calling the duplicate function with the respective parameter the next time it will be called the exact same object will be returned This is very useful for graph transformations create EntityReference this duplicate EntityReference old setName old name gt setTarget old target duplicate For mo
207. on with the small red cross re evaluates all the failed checks and only those The third button is a filter button if selected the tree view hides the checks that are ok In the view s drop down menu activated with the small downward pointing triangle there are two entries the green run button labelled reevaluate all reevaluates all checks even those that have been successful before And finally the reload button reloads the recipe file and reevaluates everything There are two important automation steps e First of all you should make sure that when you run the generator typically through an ant file the workspace will be refreshed after the ant run you can configure this in Eclipse If you do this the view will automatically reload the recipe file and reevaluate all the checks e There are certain kinds of checks that automatically re evaluate if the workspace changes This means that for example if you add the implementation class in the above example as soon as you save the class file the check will evaluate to true The question which checks will be evaluated automatically has to be defined in the check definition see below 12 1 1 Installing the Plugin There are two steps The first one installs the plugin itself i e the Recipe Browser View etc The respective plugin is org openarchitectureware recipe As usual you install it by copying it into the Eclipse plugin directory or just oAW Version
208. oot xpt template file Inside you can find a template called Imp1 that generates the implementation of the Java Bean DEFINE Entity FOR data Entity FILE baseClassFileName generated at timestamp public abstract class baseClassName EXPAND Impl ENDF ILE ENDDEF INE oAW Version 4 2 99 Xtend Xpand Check Reference DEFINE Impl FOR data Entity EXPAND GettersAndSetters ENDDEF INE DEFINE Impl FOR data PersistentEntity EXPAND GettersAndSetters public void save ENDDEF INE What we now want to do is as follows Whenever the Jmp template is executed we want to run an additional template that generates additional code for example some kind of meta information for frameworks the specific code is not important for the example here So in our new project we define the following template file AROUND Impl FOR data Entity FOREACH attribute AS a public static final AttriInfo a name Info new AttriInfo a name a type class ENDFOREACH targetDef proceed ENDAROUND So this new template wraps around the exiting template called Imp1 It first generates additional code and then forwards the execution to the original template using targetDef proceed So in effect this is a BEFORE advice Moving the proceed statement to the beginning makes it an AFTER advice ommitting it makes
209. ore model This opens the Ecore Editor You will see a root package with name nu11 Open the Properties View context menu Set the following properties for the package e Name data e Ns prefix data e Ns URI http www openarchitectureware org oaw4 demo emf datamodel oAW Version 4 2 4 EMF Tutorial Java oaw4 demo emf datamodel metamodel data ecore Eclipse SDK File Edit Navigate Search Project Run Sample Ecore Editor Window Help O SHE TeV Ares E C y data ecore X S platform resource oaw4 demo emf datamodel metamodel data ecore E Properties 53 Property Value EFactory Instance by data Name data Ns Prefix data Ns URI http www openarchitectureware org oaw4 demo emF datamodel Selected Object data Figure 1 4 Adjust namespace settings Create the following Ecore model Make sure you set the following properties exactly as described next Within the data package create these Eclass elements with their attributes 2 String EClass name F Attribute name Attribute EType Sring Sring Sring Sring EntityReference a Many oMany EBoolean Now it is time to create references between the model elements Add childs of type EReferences as follows To add children right click on the element to which you want to add children and select the type of the child from the list To configure the properties open the properties dialog by selecting Show Properties View a
210. oth approaches we will just discuss how one creates a generator in this tutorial 2 5 1 Code generation with Xpand The Xtext wizard already created a generator project for us We re going to write an Xpand template which generates simple JavaBeans from our entities It s assumed that there is a Java datatype corresponding to the datatypes used in the models e g st ring So we don t need to care about mapping data types So just open the Xpand template Main xpt and and modifiy it like this a lt T Main xpt x oe Outline 72 K D IMPORT mydsl a ka Y KIS DEFINE main FOR Model mydsl EXPAND javaBean FOREACH types typeSelect Entity main Model ENDDEFINE javaBean Entity DEFINE javaBean FOR Entity FILE name java public class name FOREACH features AS f private f type name f name public f type name get f name toFirstUpper return f name public void set f name toFirstUpper C f type name f name L this f name f name name String Feature ENDFOREACH ENDFILE ENDDEFINE Figure 2 17 Xpand template The definition main is invoked from the workflow file It s declared for elements of type myds1 Model which corresponds to the root node of our DSL models Within this definition another definition javaBean is called lt lt EXPAND javaBean for each model element FOREACH
211. parated parameter lists An EvaluationException will be thrown if the specified target expression cannot be evaluated to an existing element of the instantiated model or no suitable DEFINE block can be found oAW Version 4 2 91 Xtend Xpand Check Reference 6 5 3 7 FOREACH This statement expands the body of the rorzacu block for each element of the target collection that results from the expression The current element is bound to a variable with the specified name in the current context FOREACH expression AS variableName ITERATOR iterName SEPARATOR expression a sequence of statements using variableName to access the current element of the iteration ENDFOREACH The body of a rorzacu block can contain any other statements specifically FoREACH statements may be nested If ITERATOR name is specified an object of the type xpand2 Iterator see API doc for details is accessible using the specified name The SEPARATOR expression works in the same way as the one for EXPAND Example FOREACH A B C AS c ITERATOR iter SEPARATOR iter counterl c ENDFOREACH The evaluation of the above statement results in the following text 6 5 3 8 IF The iF statement supports conditional expansion Any number of ELSEIF statements are allowed The ELSE block is optional Every 1F statement must be closed with an ENDIF The body of an IF block can contain
212. pe Datatype Entity P genef New K gen myds Open amp src gen Open With gt K BAJRESysten Show In xw p eID gt BA Plug in s Feature Y gt META IN Copy C _ d MAN Copy Qualified Name R area Paste sey DJ name ID ve spenna X Delete src gen Build Path K Y icons Refactor XET K XE defa K BAJRESysten y Import K BA Plug in DE 3 Export Y Z META IN MANI Refresh FS E bulld prof Assign Working Sets Y L my dsl genera Y src Validate v forge Mark as Landmark ONET D amp Remove from Context OEL s Filter matched 0 of 5 items gt BAJRES k gt L Run on Server tO a ae ste gt BA Plu N 9 Debug As gt MDP Workflow it e Profile As gt TE Team gt Open Run Dialoa Figure 2 6 Starting the Xtext generator 2 3 4 Starting a runtime workbench We now can start a so called runtime workbench in order to see our newly defined DSL and it s editor in action To do so click the Debug Action in the toolbar like it is shown in the next screenshot Select the entry called Open Debug Dialog Java my a si src myasi xu Or a 18 G lee ty D 1 generate oaw Debug As Figure 2 7 Starting a runtime workbench oAW Version 4 2 34 Xtext Tutorial 00 Debug Create manage and run configurations Create a configuration to launch an Eclipse application in debug mode SEax ex Name New configura
213. pecified Collection returns a new Set containing all elements from this and the specified Collection add Object adds an element to the Collection modifies it returns this Collection oAW Version 4 2 106 Xtend Xpand Check Reference Table 6 10 Operations Description 6 6 8 set Super type Collection 6 6 9 oaw Type Super type object Table 6 11 Properties Description allStaticProperties Description 6 6 10 oaw Feature Super type Object oAW Version 4 2 107 Xtend Xpand Check Reference Table 6 13 Properties owner returnType documentation 6 6 11 oaw Property Super type oaw Feature Table 6 14 Operations SC S 6 6 12 oaw Operation Super type oaw Feature Table 6 15 Operations e 6 6 13 oaw StaticProperty Super type oaw Feature Table 6 16 Operations 6 6 14 void Super type object 6 6 15 xtend AdviceContext Super type object oAW Version 4 2 108 Xtend Xpand Check Reference Table 6 17 Properties paramNames name paramTypes proceed e 6 6 16 xpand2 Definition Super type Object Table 6 19 Properties 6 6 17 xpand2 Iterator Super type object Table 6 21 Properties paramNames paramTypes itargetType Description toString poses Od Description firstIteration lastIteration counterl elements
214. ple above 6 2 3 2 Eclipse IDE MetaModelContributors You should know that for each Metamodel implementation you use at runtime you need to have a so called MetamodelContributor extension for the plugins to work with If you just use one of the standard Metamodel implementations EMF UML2 or Java you don t have to worry about it since oaw is shipped with respective MetamodelContributors see the corresponding docs for details If you need to implement your own MetamodelContributor you should have a look at the Eclipse plug in reference doc 6 2 3 3 Configuring Metamodel implementations with the workflow You need to configure your oaw language components with the respective metamodel implementations A possible configuation of the xpand2 generator component looks like this lt component class oaw xpand2 Generator gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelPackage value my generated MetaModellPackage gt lt metaModel gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelFile value my java package metamodel2 ecore gt lt met aModel gt lt component gt In this example the EmfMet aModel implementation is configured two times This means that we want to use two metamodels at the same time both based on EMF The metaModelPackage property is a property that is specific to the EmfMet aModel located in the core emftools project It points to the generated EPackage interface The
215. pse Plug In dependencies Alternatively you could create a Plug In project instead of these both steps oAW Version 4 2 165 Classic UML Tutorial 15 5 Defining Dependencies In the new project there is now a META INF MANIFEST MF Open it go to the Dependencies page and add the following dependencies alae tm Hierarchy 2 oaw4 demo classic uml 5 6 Dependencies S oaw4 demo classic uml architecturware cv src Required Plug ins E model Specify the list of plug ins required for the operation of this plug in 5 templates p org openarchitectureware classic umIMetamodel Y BA JRE System Library jre1 5 0_07 3p org openarchitectureware classic core S Plug in Dependencies Sr org openarchitectureware classic workflow Gy META INF Sr org openarchitectureware classic xmilnstantiator IY MANIFEST MF 1 3 ASCII kkv Sr org openarchitectureware core xpand2 a sre gen S org openarchitectureware core check Figure 15 4 Defining plug in dependencies for oAW Classic e org openarchitectureware classic umlMetamodel The classic UML metamodel classes e org openarchitectureware classic core Framework classes for oA W classic e org openarchitectureware classic workflow OAW classic workflow components and cartridges e org openarchitectureware classic xmilInstantiator Parser component for UML tools e org openarchitectureware classic libraries Required 3rd party libraries e org openarc
216. r Al uses PatternLayout log4j appender Al layout org apache log4j PatternLayout o log4j appender A1 layout ConversionPattern 4r 5p m n 15 10 Creating the generator workflow and the first template 15 10 1 The workflow script The next step is to create a workflow script The workflow has to accomplish the following tasks e Initialize the environment for using the classic metamodel e Parse the tool specific xmi file and instantiate the metamodel e Initialize all instantiated elements e Run the generator to create code e Tear down Print messages collected through the generator run For all these tasks pre defined workflow scripts and components can be included in the workflow The following workflow script does all these tasks and should fit for the first steps Later on you may need to customize the workflow script to integrate further components like model modifiers Therefore the script itself is not bundled as a cartridge lt xml version 1 0 encoding UTF 8 gt lt workflow gt lt property file workflow properties gt lt cartridge file org openarchitectureware workflow oawclassic classicstart oaw gt lt metaEnvironmentSlot value me gt lt instantiatorEnvironmentSlot value ie gt lt cartridge gt lt component class org openarchitectureware core frontends xmi workflow XMIInstantiator gt lt instantiatorEnvironmentSlot value ie gt lt modelFile value mo
217. rc gen 2 19 gt example B gt BC1 ff gt impl IO I gt CannotAdd java AS BB gt ICi java ASCII kkv E R gt ICalculator java AS 83 gt BC2 ile gt exsys client H H E model o build properties 1 4 ASCII kkv D build xml 1 3 ASCII S S c w E B gt dump dump 70 Problems Javadoc Declaration Search Console Progress Error Log Properties R Recipes 23 K x G E3 gt helloworld recipes Binary 7 example BC1 C1 manual implementation of componi Name Value 4 gt you have to provide an implementation class a _type org openarchitectureware recipe ecl 7 daen E GZ the implementation class has to extend the generated componen gt type org openarchitectureware recipe ch example BC2 C2 manu lementation of component className example BC1 impl C1Implementation ok E S G 75 example BC2 Decider implementation of component 4 element vexample BC1 C1 31E oAW antlrinstantiator build E rexample BC1 Calculator Manual implementation of component a projectName scmHelloWorld g oAW antSupport build srcPath src YZ oAW core build 4 oAW metamodelG tor build P a S AW eno S Sel iian the generator generates a base class forcomponents in this case S OA recipe ant 7 um example BC1 impl C1ImplementationBase From this base classyou have to Y oAW
218. rchitectureW are User Guide 9 3 Selecting the Model Object ionene oieri iaai i EA E E A e aia 129 OA Example model smirio E Eaa cade EES ESEE TES AEE E REE 129 9 5 Modelling a Prone s miissen arie a n a adel Waa E ae aa E see EES 131 9 6 Loading the Profile ssnin ernai aa erada a aa e ETa han e Se raen e TaESA ET 132 9 7 Defining the Profile errire aiee o ea A E ER EE o TAEAE ERa A E OA EEEE A ESE E ia 133 T01 Validation settings i eeen eaire iets RE AAS EE VERE E eh heh aden eee 136 10 2 Template settings TT 136 10 3 Adding th extension model orreee desk tain EA EREA ive Wiel eich ha Aaaa 137 10 4 Setting properties on the CheckContainer element eee eee eee eee eee 138 105 Adding a new check H TT 138 11 1 Project properties with RSA RSM profiles added sss sss sese 140 12 1 Recipe Example e n tee crsfenececehtacc dss aceheterageeetet age EEVEE OE A TEELE AEE ERE S EERE ESE p EEEa 142 12 2 Usin the Recipe plugin nona e e E O Ee EERE EREDETRE DEE ki en e EER ereo E eaS 143 13 1 UML2Ecore sample metamodel class diagram sese esse 151 13 2 UML2Ecore sample metamodel MagicDraw containment tree sss sese sese ee ee eee eee eee 151 13 33 Project layout Gere sclece Tose ped oae e Jobe bad sat E EE AEA E A aI OES AET taea ESEA utddee gauges 152 IZA Dependencies roepane eae ot eats do r AE EEE E Hya aeaa HER ame sK 152 13 5 Generated Ecore Model uitiorum a eiri aaae e e E ea a a aa a aaO tA 154 14 1 Core El ments iosten
219. re 7 6 3 3 The generator project The name of the generator project is derived from the main project s name by appending the suffix generator to it The generator project is intended to contain all needed generator resources such as Xpand templates platform specific Xtend files etc These are the most important resources Location Description src base package name he generators workflow preconfigured with the generated DSL generator oaw arser and the Xpand component As this is just a proposal feel free to hange add the workflow as you see fit src gen base package name he proposed td Xpand template file Main xpt 7 7 Pimping the editor The generated editor supports a number of features known from other eclipse editors Although most of them have a decent default implementation we will see how to tweak and enhance each of them 7 7 1 Code Completion Code Completion is controlled using oAW extensions The default implementation provides keyword proposals as well as proposals for cross references Have a look at the extension file contentAssist ext Therein a comment describes how to customize the default behaviour There are two types of extensions one can define 1 completeMetaType_feature ModelElement ele String prefix This one is called for assignments only It gets the underlying Modelelement and the current prefix passed in 2 completeMetaType xtext Element grammarEle ModelElement ele
220. re information about the Xtend language please see the Xtend Reference documentation 6 5 Xpand2 The openArchitectureWare framework contains a special language called Xpand that is used in templates to control the output generation This documentation describes the general syntax and semantics of the Xpand language Typing the guillemets and used in the templates is supported by the Eclipse editor which provides keyboard shortcuts with Ctrl lt and Ctrl gt oAW Version 4 2 87 Xtend Xpand Check Reference 6 5 1 Template files and encoding Templates are stored in files with the extension xpt Template files must reside on the Java classpath of the generator process Almost all characters used in the standard syntax are part of ASCII and should therefore be available in any encoding The only limitation are the tag brackets guillemets for which the characters Unicode 00551 and Unicode 00551 are used So for reading templates an encoding should be used that supports these characters e g ISO 8859 1 OF OUTF 8 Names of properties templates namespaces etc must only contain letters numbers and underscores 6 5 2 General structure of template files Here is a first example of a template IMPORT meta model EXTENSION my ExtensionFile DEFINE javaClass FOR Entity FILE fileName package javaPackage public class name implementation ENDF ILE END
221. rever you need 5 Here you can see a descriptive text that explains what you have to do in order to fix the failed check 6 Here is the manually written code in the src folder You can see the class calculatorImplementation this is why the check that verifies its presence is successful There is no clImplementation why the check that checks its presence fails 7 This is the generated code folder src gen It contains the generated base classes There are a couple of options to work with those recipes as shown in the next illustration ac Declaration Search Console Progress Etror Log Properties R Recipes x x G Si S e BC1 C1 manual implementation of component Name Value Reevaluate All have to provide an implementation ass _type org open es Reload Recipe File implementation class has to extend t 2 2 Evaluate en _type org ope e BC2 C2 manual implementation of componen className example BC1 impl C1 Implementation e BC2 Decider manual implementation of component o o o oo o 3 i element example BC1 C1 e BC1 Calculator manual implementation of component projectName scmHelloWorld srcPath src the generator generates a base class forcomponents in this case Figure 12 2 Using the Recipe plugin If you right click on a check in the treeview you can reevaluate the check explicity The buttons at the top right of the view has three buttons the first on collapses the tree view The play butt
222. rson entity Address UL Figure 2 12 Folding x datatypes String Sentity Person String name String lastName Address address Sentity Address String street String zip String city Ei Problems 83 _ Javadoc 1 error 0 warnings 0 infos y tz Errors 1 item mismatched input datatypes expecting Figure 2 13 Errors according to the grammar i e syntax errors oAW Version 4 2 37 Xtext Tutorial 2 4 1 Validation with Check The most important thing every DSL designer should do in addition to defining the grammar is to specify so called checks A check also called invariant is expressed in oAW s Check language and is a declarative constraint for all model elements of a certain type There are some built in checks Xtext derives from the grammar such as verifying that a referenced element in our example the reference from Feature type to Type could found We can t and don t want to add all the checks to the grammar because it would get too complex Instead the Xtext generator has created an empty check file for us where we are supposed to add our semantic constraints Let s ensure that each Type has a unique name and within an Entity each Feature has a unique name as well Extensions ext GenExtensions ext cari import mydsl extension org example dsl Extensions context Type ERROR Duplicate type name allElements typeSelect Type select ele name
223. rty Value Diagram Contains Shortcuts To IS Live Validation UI Feedback L false Shortcuts Provided For S Synchronized iM true Units Pixel Validation Decorators ive true validation Enabled TE true Diagram Element Figure 10 1 Validation settings 10 4 2 Setting template options Now select your Gen Editor Generator and set the following properties e Set Dynamic Templates to true e Set Template Directory in the section Diagram to true Resource Set IS L platform resource sample gmf model My gmFgen EER Gen Editor Generator demo diagram lt gt Gen Diagram StatemachineEditPart gt Gen Plugin My Plugin gt Gen Editor View demo diagram part gt Gen Navigator MyNavigatorContentProvider lt 4 Gen Diagram Updater MyDiagramUpdater lt gt Property Sheet demo diagram sheet Selection Parent List Tree Table Tree with Columns 7 Problems l Javadoc B Declaration E Properties 3 L GMF Dashboard Error Log A Search l E History l Property Value Copyright Text Z xxy Diagram File Extension 72 demo_diagram Domain File Extension 72 demo _ Domain Gen Model My Dynamic Templates lve true Model ID I My Package Name Prefix 72 demo diagram _ Same File For Diagram And Model T false Template Directory 72 Jorg openarchitectureware adapter qmf2 templates Figure 10 2 Template settings oAW Version 4 2 136 GMF2 Adapter 10 4 3 Loading the
224. s When you open Eclipse and import a project into the workspace you can see several file decorating images There are specific images for a O 4 le Rro It e Workflow files caw extension E E oo gt oaw4 demo cla n generator cvs sour cefor Hal e Xpand2 template files xpt extension S gt src S I gt scm l E l R scm workFlow oaw 1 9 ASCII kkv s Extension files ext extension E scm workflow properties 1 4 ASCII kky fa ML cern rare wng gt en pugu e Check files chk extension E gt scm templates T gt Root xpt 1 5 ASCII kkv Q gt 5CMChecks chk 1 2 ASCII kkv E gt 5CMComponent ext 1 1 ASCII kkv E gt SCMNamingConvention ext 1 4 ASCII S i gt scm templates comp M Component xot 1 8 ASCII kkv 3 5 Editors When you double clip on one of the above mentioned file types special editors will open that provide appropriate syntax coloring 3 5 1 Syntax coloring Here are examples for the Xpand editor oAW Version 4 2 48 oAW 4 Eclipse Integration D Root xpt D Component xpt 72 IMPORT scm mm comp IMPORT scm imm ex DEFINE Root FOR scm mm SCMTop EXPAND ComponentPojo Root FOREACH 41lElementsOfModel typesele EXPAND Exception Root FOREACH AllElementsOfModel typeSelect 5 ENHDDEF IHE for the Extensions editor D Root xpt EJ SCMNamingConyvention ext X import scm mm base extension sc
225. s jar gt lt fileset dir RECIPE SIMPLECHECKS DIR dist includes jar gt lt fileset dir RECIPE ANT DIR dist includes jar gt lt fileset dir RECIPE ANT DIR lib includes jar gt lt fileset dir RECIPE ECLIPSECHECKS DIR includes jar gt lt path gt lt target name check depends gt oAW Version 4 2 144 Recipe Framework lt taskdef name check classname org openarchitectureware recipe ant RecipeCheckTask gt lt classpath refid ant runtime classpath gt lt taskdef gt lt check recipeFile L workspace xy helloWorld recipes gt lt target gt lt project gt The checks use log4j logging to output the messages So you can set the log level using the log4j properties file The following output shows all the checks being successful Buildfile 1 exampleWorkspace v4 scmHelloWorld build xml check check 0 INFO checking recipes from file L runtime EclipseApplication xy helloWorld recipes BUILD SUCCESSFUL Total time 1 second If you set the log level to DEBUG there s more you can see that all the Eclipse checks are skipped Buildfile 1 exampleWorkspace v4 scmHelloWorld build xml check check 0 INFO checking recipes from file L runtime EclipseApplication xy helloWorld recipes check 60 DEBUG skipped resource exists exists skipped mode was batch only check 70 D
226. s Ecore or XML Schema 6 2 3 1 Example JavaMetaModel For instance if you want to have the following JavaBean act as a Metatype i e Your model contains instances of the type public class Attribute private String name private String type public String getName return name public void setName String name this name name public String getType return type public void setType String type this type type oAW Version 4 2 67 Xtend Xpand Check Reference You need to use the JavaMetaModel implementation which uses the ordinairy Java reflection layer in order to map access to the model So if you have the following expression in e g Xpand myattr name toFirstUpper and myattr is the name of a local variable pointing to an instance of Attribute The oaw typesystem asks the metamodel implementations if they know a type for the instance of Attribute If you have the gavaMet aModel registered it will return an oaw Type which maps to the underlying Java class When the type is asked if it knows a property name and it will inspect the Java class using the Java reflection API The JavaMetaModel implementation shipped with oaw can be configured with a strategy GOF95 Pattern in order to control or change the mapping For instance the JavaBeansStrategy maps getter and setter methods to simple properties so we would use this strategy for the exam
227. s the to be defined value String setterName Attribute ele set tele name toFirstUpper String getterName Attribute ele get tele name toFirstUpper To make these extensions work we have to add the following line to the beginning of the Root xpt template file EXTENSION templates java 1 10 2 Java Extensions In case you cannot express the business logic for the expression with the expression language you can fall back to Java Take a loot at the following extension definition file It s called util ext and is located in src datamodel generator util String timestamp JAVA datamodel generator util TemplateUtils timestamp Here we define an extension that is independent of a specific model element since it does not have a formal parameter The implementation of the extension is delegated to a static operation of a Java class Here is it s implementation public class TemplateUtils public static String timestamp return String valueOf System currentTimeMillis I This element can be used independent of any model element it s available globally Sometimes it s necessary to access extensions not just from templates and Wombat scripts but also from Java code The following example is of this kind we want to define properties that derive the name of the oAW Version 4 2 21 EMF Tutorial implementation class from the entity name
228. s 88 6 5 3 Statements of the Xpand language eee eee 88 6 5 4 Aspect Oriented Programming in Xpand sss sese sese ee eee eee 94 6 5 5 Generator Workflow Component eee eee eee eee 96 6 5 6 Example for AOP and Xpand sirere sisun aent ina eia at s eine eitt 99 63 e The Problem ciiraim te eieiei e inn ta E EE AE NEA EEEE 99 63 8 Examples erone aeaaeai areae ne Wisk E Ae A alent isd E E EAEE 99 639 More AO aoe ire eoa ieee EE AEAEE ES ON ea EE AOE E OEE ETa EEEa 101 6 6 Built in types API documentation sss sees sese ee eee eee ee eee 102 650 1 OB3 SCE merren iinet ee a e i a ea a taaa e EN E 102 6 6 2 SELIG PEE E E T E sign ds E T EI E E I E 102 6 6 3 Sah L T a E E E E E TNA E T E N E TT 104 6 6 4 BOG Lea Menna rera E Meise ad ea een tee A 104 5 Real siege ha eee we lance ee sale se RAEE A a A R E couse aveeete nee 104 EDD COTS CET Orcs Series ata slide ag te seca sae eae L Ia swe eed Hee ees 105 BBL E E E veces sei locas E E eae sve doen ap vested ae peace regen ae eee doe 106 610 85 SS sos ew eh cosets ERE AE eh hated and ATT dere eae oe ites Weta ern wee oo 107 6 6 9s Gans Type detec cddnced nenen ove douarsadoues vue Soa ond sa Cones hake data ccnees i chases EE Needs waeeaek 107 MOIO oats Peat ur iiron r s ANAE NE sae dee aa cased ated sbvcdedgbaaegecs a cees 107 6 6 11 caw TPE LOPS EYE AEC THER ATE eis ER ECET EEOSE EEANN EE RR ANEESHA EE THESE OR ER g s eee Haa dRe 108 6 6 12 oaw POP SHAT TON sins its etisisin ble cate EEE REEE oe o
229. s Debug As gt BB 4 Java Applet AK ShIFtHX A Debug S T 5 Java Application Alt Shift X J Y Figure 1 10 Launch runtime platform If you are using a Mac or nix you should now open the workspace preference page and change the default encoding to ISO 8859 114 4 Window gt Preferences gt General gt Workspace gt Text file encoding This is necessary to have the guillemot brackets available oAW Version 4 2 10 EMF Tutorial Import the oaw4 demo emf datamodel project from your original workspace Note that importing the project does not physically move the files so you can have the project be part of both workspaces at the same time Create a new openArchitecture Ware Project called oaw4 demo emf datamodel generator Do not choose the option Generate a simple example Select a wizard Wizards HG J2EE E Java Java Emitter Templates amp open rchitectureWare IQ Check File B Workflow File D xPand Template B xTend File ex Xtext Projects amp Plug in Development Server amp SOL Development gt User Assistance H D E ib B 06 Cancel Figure 1 11 Create new oA W project Your openArchitectureWare project will already be configured for use of EMF models You can check this in the project properties dialog 5 File gt Import gt General gt Existing Project into Workspace Unless you checked the option Copy projects into workspace 1 F
230. s association is not navigable An example for to one associations can be seen in the copy class public class Copy implements java io Serializable private oaw4 demo classic uml entity Library owner public void setOwner oaw4 demo classic uml entity Library pOwner this owner pOwner public oaw4 demo classic uml entity Library getOwner return this owner The template code is really small but now you could only have to model classes and their associations and you get the right JavaBeans code from the model Our JavaBeans template is not specifix for entities you could use it to generate JavaBeans code for just any modelled class But we only call this template for classes stereotyped with lt lt Entity gt gt for now You remember that the model contains another class lt lt DAO gt gt LibraryDao for which no code is generated yet 15 19 Constraint Checking It is very important that a generator produces correct output Therefore the input information must be valid i e the model must be consistent To prove this the metamodel is enriched by constraints that check the consistence of the model oAW Version 4 2 183 Classic UML Tutorial 15 19 1 Alternatives for implementing constraints Constraints can be provided in three different ways e Overriding the checkconstraints method of the metaclasses The checkConstraints method is only available for metaclasses based on the classic metamode
231. s created the following extension is called UIContentNode outlineTree emf EObject model It is expected to be declared in outline ext which by default exports a generic implementation from GenOut line ext the same pattern again You can either reuse the generic extension and just provide a label and image extension for your model elements should be added in EditorExtensions ext However if you want to control the structure of the outline tree you can overwrite the extension outlineTree emf EObject model in outline ext 7 7 4 Syntax Highlighting The default syntax highlighting distincts between comments string literals keywords and the rest If you just want to specify which words to be coloured as keywords you can extend the basepackage Languagename Utilities java class from the editor plugin You need to overwrite the following method DON T CHANGE IT DIRECTLY BECAUSE IT WILL BE OVERWRITTEN THE NEXT TIME YOU START THE GENERATOR public String allKeywords Each String returned by the method represents a keyword The utiltities method is created within the LanguageName EditorPlugin java So make sure that you change the following lines too OLD gt private MyLangUtilities utilities new MyLangUtilities private MyCustomUtilities utilities new MyCustomUtilities public LanguageUtilities getUtilities return utilities If you want to change the s
232. s ensure that the size of the reulted list is equal to 1 i e the resulted list only containes the currently checked model element The second extension is used in the check for features Basically the condition is very similar to the one we discussed before The only difference is that we don t want to check whether the name is unique within the whole model but within all features of the current feature s entity To access the feature s entity we have defined an extension entity in the file org example ds1 Extension ext like so oAW Version 4 2 38 Xtext Tutorial Q Checks chk GenExtensions ext m import mydsl extension org example dsl GenExtensions reexport Entity entity Feature this eContainer Figure 2 15 Defining extensions Note that we reexport all extenions from GenExtensions here That s why we can refer to allElements from within the check file We can now start the runtime workbench again without starting Xtext s generator once more because we didn t change the grammar file Try to break one of the constraints 5 Outline R m Vv datatype String 7 Sentity Person String G String name gt Person G String name K Address String lastName Address address Sentity Address L e Foo street String zip String city B Problems ZN a Javadoc 2 Declaration 4 Search 3 Fam 3 errors 0 warnings 0 infos Resource Path y t Errors 3 it
233. s implies that comments are not nestable A comment may not have a white space between the REM keyword and its brackets Example REM LET expression AS variableName ENDREM a sequence of statements REM variableName stuff ENDLET ENDREM 6 5 3 13 Expression Statement Expressions support processing of the information provided by the instantiated meta model Xpand provides powerful expressions for selection aggregation and navigation Xpand uses the expressions sub language in almost any statement that we have seen so far The expression statement just evaluates the contained expression and writes the result to the output using java lang Object s toString method Example public class this name All expressions defined by the oAW expressions sub language are also available in Xpand You can invoke imported extensions See the Expressions and Extend Language Reference for more details 6 5 3 14 Controlling generation of white space If you want to omit the output of superfluous whitespace you can add a minus sign just before any closing bracket Example FILE InterfaceName java IF hasPackage package InterfacePackageName ENDIF ENDF ILE The generated file would start with two new lines one after the FILE and one after the IF statement if the minus characters had not been set In general If a statement or comment ends with such a minus al
234. s the right place to start when you are new to openArchitectureWare 4 and want to use UML tools like MagicDraw Poseidon Rational Rose etc In this example we want to generate code from this model oAW Version 4 2 164 Classic UML Tutorial euse lt lt use gt gt lt lt use gt gt kaan writtenBook pis ownedBook Figure 15 2 Example Model As a result we want to create some JavaBean style classes which have properties with getter setter methods 15 4 Setting up the project Create a new Java Project called oaw4 demo classic uml and select the option to create seperate source and output folders New Java Project Create a Java project j Create a Java project in the workspace or in an external location L 7 Project name oaw4 demo classic uml Contents Create new project in workspace Create project from existing source C oaw4workshop oaw4sample workspace2 oaw JDK Compliance Use default compiler compliance Currently 1 4 Configure default Use a project specific compliance 1 4 m Project layout Use project folder as root for sources and class files Create separate source and output folders Configure default cma o O conc Figure 15 3 Creating the tutorial project Afterwards select from the context menu PDE tools gt Convert Projects to Plug in Projects since we want to define our dependencies via Ecli
235. s user Desktop tenp mydslproject src aen CompositeComponent Generator generating org example dsl Main main FOR theMode Generator Written 2 files to outlet default src gen WorkflowRunner workflow completed in 257ms Ln aldats Figure 2 24 Workflow completed That s it for now Feel free to play around with this small example If you like it I ld propose you have a look at the reference documentation and try to create your own DSL Have fun oAW Version 4 2 47 Chapter 3 oAW 4 Eclipse Integration 3 1 Introduction This document describes the various functionalities that the openArchitectureWare plugins contribute to the Eclipse installation It is intended as user instruction for the work with Eclipse You need to read other documentation to understand the openArchitectureWare framework itself 3 2 Installation It is assumed that you already have installed the oAW core and the oAW plugin feature from the updatesite as described in the Installation documentation There are some more eclipse plugins available that belong to special sub projects such as the Recipe framework They are not subject of this document and will be described in it s specific documentation 3 3 Overview The openArchitectureWare core plugins provide editors for the different languages and a launch shortcut to start workflow files Let s first have a look at the different oAW specific files 3 4 File decoration
236. se to document this one Also including some information of working with UML2 is also important However there s one really good reason why looking at this example is important If you work with UML2 models you ll soon realize that the UML2 metamodel is very intricate non intuitive and complicated So it is very good practice to transform away from the UML2 model as early as possible Especially if you want to enhance your model using model modifications remember the emergency stop feature in the statemachine example this approach is recommended While read access to UML2 models is tedious write access is almost impossible to get correct and in some aspects also impossible with generic EMF tools such as oAW So if you work with a UML2 model always begin by transforming into your own domainspecific metamodel In this example we transform into an instance of Ecore in order to get the meta model since the uml2ecore tool is used for EMF meta modelling in UML tools So in your application projects the transformation would not create an instance of Ecore but an instance of your domain specific metamodel which in turn might have been created with uml2ecore The only difference to the example given here is that you d use as a meta model not Ecore but rather your own one This has effects on the meta model declarations in the workflow file everything else is similar oAW Version 4 2 193 Model To Model 18 3 Setting up Eclipse w
237. second metamodel is configured using the ecore file You don t need to have a generated Ecore model for oaw in order to work The EmfMet aModel works with dynamic EMF models just as it works with generated EMF models 6 2 4 Using different MetaModel implementations aka MetaMetaModels With oAW you can work on different kinds of Model representations at the same time in a transparent manner One can work with EMF models XML DOM models and simple JavaBeans in the same Xpand Template You just need to configure the respective MetaModel implementations oAW Version 4 2 68 Xtend Xpand Check Reference If you want to do so you need to know how the type lookup works Let s assume that we have an EMF metamodel and a model based on some Java classes Then the following would be a possible configuration lt component class oaw xpand2 Generator gt lt metaModel class oaw type impl java JavaMetaModel gt lt metaModel class oaw type emf EmfMetaModel gt lt metaModelFile value my java package metamodel ecore gt lt metaModel gt lt component gt When the oaw runtime needs to access a property of a given object it asks the metamodels in the configured order Let s assume that our model element is an instance of the Java type org eclipse emf ecore EObject and it s a dynamic instance of an EMF EClass MyType We have three Metamodels 1 Built Ins always the first one 2 JavaMetaModel 3 EMFMetaModel
238. sformation The statement test Trafo duplicate rootElement means to invoke e the duplicate function taking the contents of the rootElement slot as a parameter s the function can be found in the Trafo ext file e and that in turn is in the classpath in the test package 6 4 10 5 The Transformation The transformation as mentioned above can be found in the Trafo ext file in the test package in the src folder Let s walk through the file So first we import the metamodel oAW Version 4 2 86 Xtend Xpand Check Reference import data The next function is a so called create extension Create extensions as a sideeffect when called create an instance of the type given after the create keyword In our case the duplicate function creates an instance of Dat aModel This newly created object can be referrred to in the transformation by this which is why this is specified behind the type Since this can be ommitted we don t have to mention it explicitly in the transformation The function also takes an instance of DataModel as its only parameter That object is referred to in the transformation as s So this function sets the name of the newly created Dat aMode1 to be the name of the original one and then adds duplicates of all entities of the original one to the new one To create the duplicates of the entities the duplicate operation is called for each Entity That is the next function in the transformati
239. sing the ecore editors To inspect the model they provide a somewhat better view so you might try 9 4 Code generation 9 4 1 Defining the templates Inside the source folder of our project create a templates package Inside that package folder create a template file Root xpt that has the following content First we define the entry template that is called Root Since we expect a UML model element to be the top element to the model we define it for um1 Mode1 Note the use of the uml Namespace prefix as defined in the UML2 metamodel Inside that template we iterate over all owned elements of the model and expand a template for the packages defined in it DEFINE Root FOR uml Model oAW Version 4 2 129 UML2 Example EXPAND PackageRoot FOREACH ownedElement ENDDEF INE In the package template we again iterate over all owned elements and call a template that handles classes At this point we expect that only classes are in that package DEFINE PackageRoot FOR uml Package EXPAND ClassRoot FOREACH ownedType ENDDEF INE This template handles classes It opens a file that has the same name as the class suffixed by java Into that file we generate an empty class body DEFINE ClassRoot FOR uml Class FILE namet java public class name ENDF ILE ENDDEF INE 9 4 2 Defining the workflow In order to generate code we need a workflow definition Here
240. stereotype be applicable to UML classes they are defined as part of the UML2 metamodel So we have to import that metamodel first So what you do is to select your profile object and then go to the UML2 Editor menu in the Eclipse menu bar and select Profile gt Reference Metaclass Select uml class You can then select your stereotype and select Stereotype gt Create Extension from the UML2 Editor menu Select um1 class This should lead to the following model Save it you re done with the profile definition A example profiled uml 79 test profile uml_ X S El platform resource oaw4 demo enf urnl2 generator src test profile uml Al lt Profile gt test thes lt Element Inport gt C a E Stereotype gt test S lt Property gt base_Class Class 2 Al lt Extension gt Class_test gt lt Extension End gt extension_best test pathmap UML METSMODELS UML metamodel uml pathmap UML_PROFILES Ecore profile uml pathmap TUAL PROFILES Standard profile uml ass H A F Figure 9 5 Modelling a Profile 9 5 2 Applying the Profile To make any use of the profile we have to apply it to some kind of model To do that we copy the example um1 model to a example profiled uml We then open that file and load a resource namely the profile we just defined This then looks somewhat like this oAW Version 4 2 131 UML2 Example example profiled uml X
241. t click on the file and select the Generate Emfatic Source item The following code is generated from our data ecore file into a file called data emf After changing the source in the emf file you can right click that file and select Generate Ecore Model to transfer it back oAW Version 4 2 188 Using the Emfatic Ecore Editor E namespace uri http fav openarchitectureware org oaw4 demo emf datamodel prefix data package data class DataModel attr String name val Entity entity Class Entity val Attribute attribute attr String name val EntityReference reference class Attribute attr String name attr String type class EntityReference ref Entity 1 target attr String name attr boolean toMany Class PersistentEntity extends Entity attr String tableName Figure 16 1 Editing a metamodel with the EMFatic editor The syntax should be self explaining One remark To render containment relationships emfatic uses the val keyword not ref see in the screenshot in the Entities attributes for example oAW Version 4 2 189 Chapter 17 EMF State Machine 17 1 Introduction This example shows how to implement a state machine generator using EMF and openArchitectureWare Note that the implementation of the state machine in Java is probably the slowest and clumsiest way to implement a state machine The focus was not on optimizing the performance of the state machien implementatio
242. t the bottom of any of the context menus Note that this is not an EMF tutorial For more details on how to build EMF meta models please refer to the EMF documentation 7 Attributes are childs of type EAttribute Fill the Name and the EType properties 3Note there are a couple of Z s don t miss the minus Also the containment flag is essential If containment is true you will be able to create childs of the referenced type otherwise you can only reference them oAW Version 4 2 5 EMF Tutorial EClass Reference name Reference attribute Reference attribute name alue pay a eowerbouna H A S H H H H 91 C H H 1 OOOO i eo h a T H HT H HT f f f f f f f f U platform resource oaw4 demo emf datamodel metamodel data ecore data 3 H DataModel name EString 2 entity Entity 3 H Entity o name EString 2 attribute Attribute amp reference EntityReference H Attribute name EString type EString H EntityReference o name EString toMany EBoolean rea arget Entity 1 aa Figure 1 5 Metamodel structure EMF saves the model we created above in its own dialect of XMI To avoid any ambiguities here is the complete XMI source for the metamodel It goes into the file data ecore oAW Version 4 2 6 EMF Tutorial lt xml version 1 0 encoding UTF 8 gt lt ecore EPackage xmi version 2 0 xmlns xmi http www omg org X
243. tcureWare languages Check Xtend or Xpand 6 3 8 1 Using GLOBALVARS to configure workflows Each workflow component using the expression framework Xpand Check and Xtend can be configured with global variables Here is an example lt workflow gt a Sewn oAW Version 4 2 75 Xtend Xpand Check Reference lt component class oaw xpand2 Generator gt usual stuff see ref doc lt globalVarDef name MyPSM value slotNameOfPSM gt lt globalVarDef name ImplClassSuffix value Impl gt lt component gt lt workflow gt If you have injected global variables into the respective component you can call them using the following syntax GLOBALVAR ImplClassSuffix Note we don t have any static typeinformation Therefore ob ject is assumed So you have to down cast the global var to the intended type String GLOBALVAR ImplClassSuffix It is good practice to type it once using an Extension and then always refer to that extension String implClassSuffix GLOBALVAR ImplClassSuffix usage of the typed global var extension ImplName Class c namet timplClassSuffix 6 3 9 Multi methods multiple dispatch The expressions language supports multiple dispatching This means that when there is a bunch of overloaded operations the decision which operation has to be resolved is based on the dynamic type of all parameters the implicit this included
244. te Realization realization realization Specifier duplicate gt realization Realizer duplicate gt 6 4 5 3 Recursion There is only one exception For recursive extensions the return type cannot be inferred therefore you need to specify it explicitely String fullyQualifiedName NamedElement n n parent null n name fullyQualifiedName n parent n name Recursive extensions are non deterministic in a static context therefore it is necessary to specify a return type oAW Version 4 2 79 Xtend Xpand Check Reference 6 4 5 4 Cached Extensions If you call an extension without side effects very often you would like to cache the result for each set of parameters in order improve the performance You can just add the keyword cached to the extension in order to acieve this cached String getterName NamedElement ele get tele name firstUpper The getterName will be computed only once for each NamedElement 6 4 5 5 Private Extensions By default all extensions are public i e they are visible from outside the extension file If you want to hide extensions you can add the keyword private in front of them private internalHelper NamedElement ele implementation 6 4 6 Java Extensions In some rare cases one does want to call a Java method from inside an expression This can be done by providing a Java extension Void myJavaExtension
245. the optional extends clause Therein the rule name on the right is surrounded by squared paranthesis That s it By default the parser expects an ID to point to the refered element If you want to refer with another klind of token you can optionally specifiy it sepearted by a vertical bar extends superType Entity MyComplexTokenRule Where MyComplexTokenRule must be either a NativeLexerRule or a StringRule explaination follows 7 4 3 3 Meta Type Inheritance We ve seen how to define simple concrete meta types it s features One can also define type hierarchies using Xtext s grammar language Sometimes you want to abstract rules in order to let a feature contain elements of different types We have seen the Feature rule in the example If you would like to have two different kinds of Feature e g Attribute and Reference you could create an abstract type rule like this TT R Attribute Reference Attribute type ID name ID Reference ref containment type ID name ID lt gt oppositeName ID The transformation creating the meta model automatically normalizes the type hierarchy This means that properties defined in all subtypes will automatically be moved to the common super type In this case the abstract type Feature would be created containing the two features name and type Attribute and Reference would be subtypes of Feature inheriting those properties
246. ther words operations have higher precedence oAW Version 4 2 78 Xtend Xpand Check Reference 6 4 5 2 Type Inference For most extensions you don t need to specify the return type because it can be derived from the specified expression The special thing is that the static return type of such an extension depends on the context of use For instance if you have the following extension asList Object 0 o the invocation of aS Ary text has the static type List String This means you can call asList text get 0 toUpperCase The expression is statically type safe There is always a return value whether you specify it or not even if you specify explicitely Void See the following example modelTarget ownedElements addA11NotNull modelSource contents duplicate In this example duplicate dispatches polymorphicly Two of the extentions might look like Void duplicate Realization realization realization Specifier duplicate gt realization Realizer duplicate create target Class duplicate source Class If a Realisation is contained in the contents list of modelSource the Realizer of the Realization will be added to the ownedElements list of the modelTarget If you do not want to add in the case that the contained element is a Realization you might change the extention to Void duplica
247. thout assigning the result to a property like Model does So the list of Types consists of Datatypes and or Entities A Datatype Starts with keyword datatype followed by an identifier 1p The value of the identifier is assigned to the Datatype s property name ID is a built in rule and is similar to a Java identifier i e a word starting with a letter followed by alphanumerical characters and or underscores An Entity Starts with keyword entity followed by an identifier 1D which is assigned to the property name as well In addition an entity contains declarations of owned features The list of declarations is assigned to the reference called features and it is surrounded by curly brackets and Last but not least a Feature consists of an Identifier 1p which refers to a Type and another identifier which specifies the name of the Feature Make sure to read the reference documentation in order understand how a metamodel is derived from a grammar and how the linking for cross references actually works 2 3 3 Starting the generator Now that we have defined an Xtext grammar for our simple DSL we can start Xtext s generator by right clicking the workflow file generate oaw It will create the meta model and the parser as well as fill the editor project with the needed artifacts oAW Version 4 2 33 Xtext Tutorial Model Ctypes Type v i mydsl v src Ty
248. tion public class Name IF hasSuperClass extends SuperClass fqn ENDIF EXPAND Attribute PropertyDeclaration FOREACH Attribute EXPAND Attribute Getter FOREACH Attribute EXPAND Attribute Setter FOREACH Attribute EXPAND Association ReferenceVariables EXPAND Association AccessorMethods 15 18 4 Generator result Run the generator again After successful generation open Book java This file should have the following contents package oaw4 demo classic uml entity public class Book implements java io Serializable private String isbn private String title private java util Collection lt oaw4 demo classic uml entity Author gt author oAW Version 4 2 182 Classic UML Tutorial jolie Sieresiorey eyeyewsiosy return thas He public String getTitle return this title public yore Setisbm String pisbn this isbn plIsbn public void setTitle String pTitle this title pTitle public void addAuthor oaw4 demo classic uml entity Author pAuthor Ents aAuchorvacddi pAuUthor 7 public void removeAuthor oaw4 demo classic uml entity Author pAuthor this author remove pAuthor public java util Iterator lt oaw4 demo classic uml entity Author gt getAuthor return this author iterator In this file we have a to many association named author to entity Author No code exists for the association to the copy class since thi
249. tion Emain Arguments Plug ins BS Configuration Tracing B Environment S Common Workspace Data type filter text Y Eclipse Application Z New_configuration amp Eclipse Data Tools Location workspace_loc runtime New_configuration B HTTP Preview E Java Applet Clear workspace C log only D Java Application Ju junit it JUnit Plug in Test Program to Run Y IE oAW Workflow P generate oaw OSGi Framework ral Remote Java Application R lt Run on Server Java Runtime Environment J Task Context Plug in Tes Java Executable default java Juj Task Context Test v Ask for confirmation before clearing LO Run a product org eclipse sdk ide O Run an application _ org eclipse ui ide workbench i r C Juj Task Context Test Runtime JRE JVM 1 5 0 MacOS X Default is Installed JREs Bootstrap Entries l l Sa Apply Revert Filter matched 16 of 16 items Co Gap Figure 2 8 Run debug configurations dialog When the dialog opens select Eclipse Application on the left and create a new configuration by clicking the new icon the upper left icon Leave everything as it s initially configured and press Debug 2 4 Refining the DSL The generated editor already provides a lot of default funtionality which has only been derived from the grammar Some of them are code completion Got To Declaration Find References
250. to the super constructor the first one is the name a short name of the check The second parameter is the somewhat longer message You can call setLongDescription if you want to set the explanatory text e You can pass a third parameter to the super constructor and that is one of the two constants in EvalTrigger By default the EvalTrigger ON_REQUEST is used which means that the check is only evaluated upon explicit request If you pass EvalTrigger ON_CHANGE the check will be automatically re evaulated if the Eclipse workspace changes e You should define a serial version uid since Java serialization is used for the recipe file e In the evaluate method you do the check itself We will explain more on that later 12 2 3 2 More sensible Checks More sensible checks distinguish themselves in two respects e First you ll typically pass some parameters to the constructor which you ll store in member variables and then use in the evaluate operation e You can store parameters for display in the table view in the plugin You can use the setParameter name value setParameter name value operation for that More on that below s The evaluation will contain a certain business logic An example public void evaluate EvaluationContext c af something ts net right oj 4 fail something has gone wrong if some condition is met ok By the way you don t need to
251. ts and developers have to inherit from this class to add their own logic Let s first change the generator accordingly 1 11 1 Adjusting project settings We will now use openArchitectureWare s Recipe framework to achieve our task Since this framework is an add on we need to set up an additional dependency to it for our generator project Otherwise the required classes won t be found Open the projects Manifest file mETA INF MANIFEST MF go to the Dependencies page and add the org openarchitectureware recip plugins 1 11 2 Adapting the existing generator Let s first look at the template Here we have to change the name of the generated class and we have to make it abstract DEFINE Entity FOR data Entity FILE baseClassFileName generated at timestamp public abstract class baseClassName oAW Version 4 2 23 EMF Tutorial FOREACH attribute AS a ENDFOREACH ENDF ILE ENDDEF INE To make this work our extensions must be adapted we now need baseClassName and baseClassFileName import data String baseClassName Entity e JAVA datamodel EntityHelper baseClassName data Entity String baseClassFileName Entity e JAVA datamodel EntityHelper baseClassFileName data Entity The implementation helper class must be adapted too package datamodel import data Entity public class EntityHelper public static String baseClassNa
252. u don t have to implement additional Java classes anymore Just export your models and applied profiles That s all 11 2 Installation Using the RSA RSM adapter with Eclipse you first need to install the UML2 feature from Eclipse org http download eclipse org tools uml12 updates site interim xml The oAW uml2adapter is available from the oAW updatesite http www openarchitectureware org updatesite milestone site xml Go to the project s homepage and find the current location if either of the sites don t work Restart your Eclipse workbench when Eclipse asks you to do so 11 3 Setting up IBM Rational Software Architect Modeller You need to configure your project or the whole workspace to use the RSA RSM adapter Right click on the project and choose properties from the pop up menu Open the openArchitectureWare tab activate the checkboxes nature and specific metamodel contributors and add the RSA RSM Profiles metamodel contributor All profiles installed in plugins using the com ibm xtools uml2 ms1 UMLProfiles extension point are added as metamodels for more information about creating your own profiles with RSA RSM see help for Extending Rational Software Modeler functionality oAW Version 4 2 139 RSM RSA Adapter amp Properties for my generator project2 type filter text openArchitectureware Info BeanInfo Path Builders Enable project specific settings Java Build Path Java
253. ue public String getName return this name public void setName2 String value this name2 value public String getName2 return this name2 6 5 9 More AO In general the syntax for the AROUND construct is as follows lt lt AROUND fullyQualifiedDefinitionNameWithWildcards Paramlist FOR TypeName gt gt do Stuff lt lt ENDAROUND gt gt Here are some examples lt lt AROUND FOR Object gt gt matches all templates lt lt AROUND define FOR Object gt gt matches all templates with define at the end of it s name and any number of parameters lt lt AROUND org oaw FOR Entity gt gt matches all templates with namespace org oaw that do not have any parameters and whose type is Entity or a subclass lt lt AROUND String s FOR Object gt gt matches all templates that have exactly one string parameter lt lt AROUND String s FOR Object gt gt matches all templates that have at least one st ring parameter lt lt AROUND my Template definition String s FOR Entity gt gt oAW Version 4 2 101 Xtend Xpand Check Reference matches exactly this single definition Inside an AROUND there s the variable targetDef which has the type xpand2 Definition On this variable you can call proceed and also query a number of other things lt lt AROUND my Template definition Str
254. va identifier for the name of the outlet See the configuration section for a description of outlets The body of a FILE statement can contain any other statements Example FILE InterfaceName java package InterfacePackageName generated class Do not modify public interface InterfaceName EXPAND Operation InterfaceImplementation FOREACH Operation ENDF ILE FILE ImplName java MY_OUTLET package ImplPackageName public class ImplName extends Imp1lBaseName implements InterfaceName TODO implement it ENDF ILE 6 5 3 5 EXPAND The EXPAND statement expands another DEFINE block in a separate variable context inserts its output at the current location and continues with the next statement This is similar in concept to a subroutine call EXPAND definitionName parameterList FOR expression FOREACH expression SEPARATOR expression The various alternative syntaxes are explained below oAW Version 4 2 90 Xtend Xpand Check Reference 6 5 3 5 1 Names If the definitionName is a simple unqualified name the corresponding DEFINE block must be in the same template file If the called definition is not contained in the same template file the name of the template file must be specified As usual the double colon is used to delimit namespaces EXPAND TemplateFile definitionName FOR my
255. ve You have to create the Stereotypes Entity and Key To define the model above follow these steps 1 Create the stereotype Entity with base class Class 2 Create the stereotype Key with base class Property 3 Create the stereotype pao with base class Class 4 Create a package structure in your project oaw4 demo classic uml entity 5 Create a class diagramm in the package entity 6 Create a class Author a Assign the stereotype Entity b Create an attribute ia of type st ring Please select for String the datatype from your model not from UML Standard Profile Assign the stereotype Key for this attribute c Create an attribute name of type String 7 Create the class Book with stereotype Entity The Key attribute is isbn of type string The second attribute is the title 8 Draw an association between these two classes a The association end at class Author is named author is navigable and the multiplicity is Z b The other association end is writtenBook with multiplicity 0 and is navigable 9 Create the class copy of stereotype Entity a The Key attribute is inventoryNumber of type String b Add attribute location of type String 10 Draw a directed association from Copy to Book a The association end at class Book is named book is navigable with multplicity b The opposite end at copy is unnamed not navigable and multiplicity 0 11 Create the class Library of stereotype Entity
256. wever there is one important thing to point out The generator also generated the implementation classes for the metamodel If you take a look into oaw4 demo emf datamodel src folder you can find classes actually interfaces at the top level that represent the concepts defined in your metamodel These can be used to access the model For some more details on how to use the EMF model APIs as well as the reflective cousins take a look at http voelterblog blogspot com 2005 12 codeblogck emf_10 html 1 5 Setting up the generator project To make working with Eclipse EMF a bit less painless we d have to export the plugins restart Eclipse etc etc we start another Eclipse in the IDE This instance is called the Runtime Workbench Therefore select the oaw4 demo emf datamodel edit1 project and choose from the context menu Run As gt Eclipse Application Java oaw4 demo emf datamodel metamodel data genmodel Eclipse SDK File Edit Source Refactor Navigate Search Project Kapi Generator Window Help 3 RE lt gt gt G Ta HO Q EEG amp Run Last Launched Ctrl F11 x 7 Debug Last Launched Fil Package Explorer X Hierarchy Run History E E S ED 1 Run on Server Alt Shift X R a w caw4 demo emf datamodel Oprun 2 Eclipse Application Alt Shift X E CES O14 demo emF datamodel edit d 3 Equine Alt Shift O E E oaw4 demo emf datamodel editor Debug History i mea 7 E E oaw4 demo emf datamodel test
257. work Note that we do no implement the evaluate operation public ResourceExistenceCheck String message String projectName String resourceName super resource exists exists message EvalTrigger ON_CHANGE 1 setProjectName projectName setResourceName resourceName private void setProjectName String projectName setParameter projectName projectName private void setResourceName String resourceName setParameter resourceName resourceName In order to provide the evaluation functionality you have to implement an IcheckEvaluator It has to have the same qualified name as the Check itself postfixed with Evaluator During the evaluation of the check the class is loaded dynamically based on its name A wrong name will result in a runtime error during evaluation the Eclipse Plugin public class ResourceExistenceCheckEvaluator implements ICheckEvaluator public void evaluate AtomicCheck check String projectName check getParameter projectName getValue toString String resourceName check getParameter resourceName getValue toString IWorkspace workspace ResourcesPlugin getWorkspace IResource project workspace getRoot getProject projectName if project null check fail project not found projectName IFile f workspace getRoot getFile new Path projectName resourceName String n f getLocation toOSString age
258. xt language oAW Version 4 2 117 Xtext Reference from oAW 4 2 single line comments and mutli line comments G Note that those comments are ignored by the language s parser by default i e they are not contained in the AST returned from the parser If you don t want ignored comments or you ant to have a different syntax you need to overwrite the default implementation name is SL_COMMENT resp ML_COMMENT 7 5 6 Whitespace Every textual model contains whitespace As most languages simply ignore whitespace Xtext does so by default too If you want to have semantic whitespace in your language like e g python you have to overwrite the builtin whitespace rule name is WS 7 5 7 Native rules Overwriting built in lexer rules If you want to overwrite one or more of the built in lexer rules or add an additional one the so called native rule is your friend Example overwriting SL_COMMENTS we don t want Java syntax but bash syntax Native SL_COMMENT TUE ce Ua U iev yee Velen UN ET eT RST enaa lE EIET ETTR eA fully qualified names as a lexer rule Native FON ID ID The syntax is DER ive PDI STRING The string contains a valid ANTLR 3 lexer rule expression see http www antlr org wikii display A en f 7 6 The generator It s assumed that you ve used the Xtext Projects Wizard and that you have successfully writte
259. y must be first in the list 9 3 Creating a UML2 Model You start by defining a uml2 model i e an instance of the UML2 metamodel In the new Java project in the source folder you create a UML2 model that you should call example uml E rew 5 Select a wizard lt gt Create a new UML2 model f Wizards A Example EMF Model Creation Wizards S Data Graph Model lg Data Model Ecore Model A Ecore to Ecore Model Ecore to XML Model lo Types Model Pad EE 5 XSD Model Sw XSD to Ecore Model H Java H Java Emitter Templates H E Plug in Development E Simple XML 57 Back Finish Cancel Figure 9 2 Creating a new UML2 model You then have to select the model object Make sure its a Model not a Profile oAW Version 4 2 128 UML2 Example UML2 Model Select a model object to create y nea Model Object XML Encoding UTF 8 Figure 9 3 Selecting the Model object 9 3 1 Modelling the content You should then build a model that looks somewhat like this T example umiz x LS Resource Set platform resource oaw4 demo emf uml2 generator src example uml2 H gt Package vehicles Class Car Operation drive Class PersonCar 4 Generalization false Figure 9 4 Example model By the way if you rename the um1 file to ecore you can edit the model u
260. ybean oaw gt lt myParam value foo gt lt myComponent class MyBean gt lt bean gt lt comp gt As you can see simple parameters are mapped to properties in the included workflow file and components can be accessed using the idRef attribute Properties defined in the included workflow description will be overwritten by the passed properties The root element of a workflow description can have any name because there is no parent defining an accessor method Additionally you have to specify the attribute class for a root element There is only one exception If the root element is named workflow the engine knows that it has to instantiate the type org openarchitectureware Workflow Of course you can specify your own subtype of org openarchitectureware Workflow using the class attribute if you need to for any reason 5 3 1 6 InheritAll Feature If you don t want to explicitely pass the parameters to an included workflow description you can use the inheritAll attribute This will make all the properties and beans that are visible to the actual workflow file also visible to the included workflow file lt component file my included workflow oaw inheritAll true gt oAW Version 4 2 60 Workflow Reference 5 3 2 Component Implementation and Workflow Execution This section describes how to implement workflow components how they can communicate with each other and how the workflow execution can be
261. yntax of comments and string literals you have to provide an alternative implementation of GeneratedPartitionScanner Don t touch the class directly but use the Utilities method to return a different instance 7 8 Cookbook This part of the documentation deals with the discussion and solution of different requirements and problems 7 8 1 Modeling In Multiple Files If you have uge models or want to separate parts of your models from others for other reasons e g provide a kind of library You need to tweak Xtext a bit because there is no first class support for this as for now However Xtext has a built in registry where you can get parsed models by name oAW Version 4 2 123 Xtext Reference from oAW 4 2 7 8 1 1 The Registry Xtext automatically manages a built in registry That is it caches parsed models by there filename and provides an API both Java and Xtend to access cached models The registry is contained in the org openarchitectureware xtext core base bundle The Java API sonsists of a handful of static methods from org openarchitectureware xtext registry Registry java The extensions are contained in org openarchitectureware xtext registry Reg ext This part of the framework will definitely be enhanced in te future so expect API changes here 7 8 1 2 Using the Registry All you have to do is to declare some kind of import statemnent in our DSL and overwrite the allElements extension from GenExtensions ext
262. zip String street Y getCity getStreet T mydslproject oaw SR lt workflow gt lt component file org example dsl generator oaw gt lt modelFile value model dsl gt lt targetDir value src gen gt setCity String setStreet Strir setZip String D L getZipU e Y H Person java lt component gt y Person lt workf Low gt address o age pond Bea ch lt terminated gt slproject oaw Java Application System Libr Lea S Aeres lava VM ee 5 spear r 12 7 40 13 DAY ax K Ex AJ e woo getAge WorkflowRunner Z getName WorkflowRunner openArchitectureWare 4 2 0 Build 200709112234NGT setAddress A WorkflowRunner Cc 2005 2007 openarchitectureware org and contributors WorkflowRunner setAge int Riaz WorkflowRunner running workflow mydslproject oaw setName Strir WorkflowRunner gt BA Plug in Dependencies gt Z META INF R build properties gt E JRE System Library JVM 1 5 0 M CompositeComponent CompositeComponent CompositeComponent CompositeComponent ConditionalComponent Workflow executing workflow org example dsl generator oaw in myc Workflow executing workflow org example dsl parser Parser oaw iy ParserComponent mydsl parser IfComponent executing if org example dsl parser Parser oaw in or CheckComponent mydsl checker expression theModel eAllContents CompositeComponent DirectoryCleaner cleaning directory src gen DirectoryCleaner Cleaning CUser

Download Pdf Manuals

image

Related Search

Related Contents

Manual de instruções  PSTN GATEWAY (WG-205) In SIP User's Manual  Sterling Plumbing 100 User's Manual  Zebra ML-2452-PNL9M3-036 network antenna  ClearView+ Speech  TDE1032-14_FR-NL-GB-IT_CORR TUV  Cornerstone Administrator`s Manual  Samsung 510T User Manual  LeeBoy Legend Electric Screed Manual 2005  Epson V600 User's Manual  

Copyright © All rights reserved.
Failed to retrieve file