TOPIC 1 Review of UML

Size: px
Start display at page:

Download "TOPIC 1 Review of UML"

Transcription

1 5.1 What is UML? SEG4210 Advanced Software Design and Reengineering TOPIC 1 Review of UML The Unified Modelling Language is a standard graphical language for modelling object oriented software At the end of the 1980s and the beginning of 1990s, the first objectoriented development processes appeared The proliferation of methods and notations tended to cause considerable confusion Two methodologists Rumbaugh and Booch merged their approaches in They worked together at the Rational Software Corporation In 1995, another methodologist, Jacobson, joined the team His work focused on use cases In 1997 the Object Management Group (OMG) started the process of UML standardization SEG Topic 1- Review of UML 2 Classes A class is simply represented as a box with the name of the class inside The diagram may also show the attributes and operations The complete signature of an operation is: operationname(parametername: parametertype ): returntype Naming classes Use capital letters E.g. BankAccount not bankaccount Use singular nouns Use the right level of generality E.g. Municipality, not City Make sure the name has only one meaning E.g. bus has several meanings SEG Topic 1- Review of UML 3 SEG Topic 1- Review of UML 4 Labelling associations Each association can be labelled, to make explicit the nature of the association Analyzing and validating associations Many-to-one A company has many employees, An employee can only work for one company. - This company will not store data about the moonlighting activities of employees! A company can have zero employees - E.g. a shell company It is not possible to be an employee unless you work for a company Employee worksfor 1 Company SEG Topic 1- Review of UML 5 SEG Topic 1- Review of UML 6

2 Analyzing and validating associations Many-to-many A secretary can work for many managers A manager can have many secretaries Secretaries can work in pools Managers can have a group of secretaries Some managers might have zero secretaries. Is it possible for a secretary to have, perhaps temporarily, zero managers? Analyzing and validating associations One-to-one For each company, there is exactly one board of directors A board is the board of only one company A company must always have a board A board must always be of some company Company 1 1 BoardOfDirectors Assistant 1.. supervisor Manager SEG Topic 1- Review of UML 7 SEG Topic 1- Review of UML 8 Analyzing and validating associations Avoid unnecessary one-to-one associations Avoid this do this Association classes Sometimes, an attribute that concerns two associated classes cannot be placed in either of the classes The following are equivalent SEG Topic 1- Review of UML 9 SEG Topic 1- Review of UML 10 Reflexive associations It is possible for an association to connect a class to itself Directionality in associations Associations are by default bi-directional It is possible to limit the direction of an association by adding an arrow at one end SEG Topic 1- Review of UML 11 SEG Topic 1- Review of UML 12

3 Object Diagrams An Example Inheritance Hierarchy A link is an instance of an association In the same way that we say an object is an instance of a class Inheritance The implicit possession by all subclasses of features defined in its superclasses SEG Topic 1- Review of UML 13 SEG Topic 1- Review of UML 14 The Isa Rule Always check generalizations to ensure they obey the isa rule A checking account is an account A village is a municipality Inheritance, Polymorphism and Variables Should Province be a subclass of Country? No, it violates the isa rule A province is a country is invalid! SEG Topic 1- Review of UML 15 SEG Topic 1- Review of UML 16 Avoiding unnecessary generalizations Inappropriate hierarchy of classes, which should be instances MusicVideo VideoRecoding JazzRecording Recording ClassicalRecording AudioRecording BluesRecording RockRecording Avoiding having instances change class An instance should never need to change class Improved class diagram, with its corresponding instance diagram :RecordingCategory video :RecordingCategory audio subcategory music video jazz subcategory classical subcategory blues subcategory subcategory :RecordingCategory :RecordingCategory :RecordingCategory :RecordingCategory :RecordingCategory rock :Recording 9th Symphony Beethoven :Recording Let it be The Beatles SEG Topic 1- Review of UML 17 SEG Topic 1- Review of UML 18

4 5.6 More Advanced Features: Aggregation Aggregations are special associations that represent partwhole relationships. The whole side is often called the assembly or the aggregate This symbol is a shorthand notation association named ispartof Composition A composition is a strong kind of aggregation if the aggregate is destroyed, then the parts are destroyed as well Two alternatives for addresses SEG Topic 1- Review of UML 19 SEG Topic 1- Review of UML 20 Interfaces Introduction to OCL An interface describes a portion of the visible behaviour of a set of objects. An interface is similar to a class, except it lacks instance variables and implemented methods SEG Topic 1- Review of UML 21 SEG Topic 1- Review of UML 22 Use Case Diagrams Example of generalization, extension and inclusion Add Course Offering Register in Course Registrar Actor Add Course Student Enter Grade for Course Find information about course Professor Actor SEG Topic 1- Review of UML 23 SEG Topic 1- Review of UML 24

5 Example Description of a Use Case Sequence diagrams an example Use case: Open file Related use cases: Generalization of: Open file by typing name Open file by browsing Steps: Actor actions System responses 1. Choose Open command 2. File open dialog appears 3. Specify filename 4. Confirm selection 5. Dialog disappears SEG Topic 1- Review of UML 25 SEG Topic 1- Review of UML 26 Sequence Diagrams an example with replicated messages An iteration over objects is indicated by an asterisk preceding the message name Sequence Diagrams an example with object deletion If an object s life ends, this is shown with an X at the end of the lifeline :SpecificFlight :Booking :PassengerRole cancelbooking cancel deletefrompassengerlist deletefromitinerary SEG Topic 1- Review of UML 27 SEG Topic 1- Review of UML 28 State Diagrams an Example of Transitions with Time-outs and Conditions State Diagrams Example with Conditional Transitions - CourseSection class Planned openregistration Cancelled closeregistration OpenNotEnoughStudents cancel cancel classsize >= minimum requesttoregister (astudent) /createregistration Closed closeregistration classsize >= maximum OpenEnoughStudents requesttoregister (astudent) /createregistration SEG Topic 1- Review of UML 29 SEG Topic 1- Review of UML 30

6 State Diagram An Example with Substates CourseSection Class Again State Diagram an Example with Actions Garage Door Opener SEG Topic 1- Review of UML 31 SEG Topic 1- Review of UML 32 Nested Substates and Guard Conditions A Car s Automatic Transmission A state diagram can be nested inside a state. The states of the inner diagram are called substates. Activity Diagrams An Example Course Registration selectreverse Neutral selectneutral selectfirst selectdrive selectsecond selectneutral Reverse reachsecondspeed reachthirdspeed [driveselected] [driveselected] First Second Third dropbelowsecondspeed dropbelowthirdspeed [driveselected] selectfirst selectsecond SEG Topic 1- Review of UML 33 SEG Topic 1- Review of UML 34 Package Diagrams Example of Multi-Layer Systems SEG Topic 1- Review of UML 35 SEG Topic 1- Review of UML 36

7 Component Diagrams An Example of a Distributed System SEG Topic 1- Review of UML 37 SEG Topic 1- Review of UML 38 Example of a Broker System Example of a Pipe-and-Filter System - Sound Processing SEG Topic 1- Review of UML 39 SEG Topic 1- Review of UML 40 Example of the MVC Architecture for a User Interface Example of the Service-Oriented Architecture SEG Topic 1- Review of UML 41 SEG Topic 1- Review of UML 42

8 Abstraction-Occurrence Abstraction-Occurrence Square variant SEG Topic 1- Review of UML 43 SEG Topic 1- Review of UML 44 General Hierarchy Player-Role SEG Topic 1- Review of UML 45 SEG Topic 1- Review of UML 46 Singleton Observer SEG Topic 1- Review of UML 47 SEG Topic 1- Review of UML 48

9 Delegation Façade SEG Topic 1- Review of UML 49 SEG Topic 1- Review of UML 50 Proxy Deployment Diagrams SEG Topic 1- Review of UML 51 SEG Topic 1- Review of UML 52

10 Why an extension mechanism? SEG4210 Advanced Software Design and Reengineering TOPIC 2 UML Extension Mechanisms Although UML is very well-defined, there are situations in which it needs to be customized to specific problem domains UML extension mechanisms are used to extend UML by: - adding new model elements, - creating new properties, - and specifying new semantics There are three extension mechanisms: - stereotypes, tagged values, constraints and notes SEG Topic 2- UML Extension Mechanims 2 Stereotypes Stereotypes are used to extend UML to create new model elements that can be used in specific domains E.g. when modeling an elevator control system, we may need to represent some classes, states etc. as «hardware» «software» Stereotypes should always be applied in a consistent way SEG Topic 2- UML Extension Mechanims 3 Stereotypes (cont.) Ways of representing a stereotype: - Place the name of the stereotype above the name of an existing UML element (if any) The name of the stereotype needs to be between (e.g. «node») Don t use double < or > symbols, there are special characters called open and close guillemets - Create new icons «button» CancelButton state Stereotype! CancelButton Stereotype in form of icon SEG Topic 2- UML Extension Mechanims 4 Tagged Values Tagged values Define additional properties for any kind of model elements Can be defined for existing model elements and for stereotypes Are shown as a tag-value pair where the tag represent the property and the value represent the value of the property Tagged values can be useful for adding properties about - code generation - version control - configuration management - authorship - etc. Tagged Values (cont.) A tagged value is shown as a string that is enclosed by brackets { and which consists of: - the tag, a separator (the symbol =), and a value {author = Bob, Version = 2.5 Employee name address Two tagged values SEG Topic 2- UML Extension Mechanims 5 SEG Topic 2- UML Extension Mechanims 6

11 Constraints Constraints are used to extend the semantics of UML by adding new rules, or modifying existing ones. Constraints can also be used to specify conditions that must be held true at all times for the elements of a model. Constraints can be represented using the natural language or OCL (Object Constraint Language) - We will learn more about OCL in future lectures Comments Comments are used to help clarify the models that are being created - e.g. comments may be used for explaining the rationale behind some design decisions A comment is shown as a text string within a note icon. A note icon can also contain an OCL expression Title 1.. Copy Abstraction-occurrence pattern SEG Topic 2- UML Extension Mechanims 7 SEG Topic 2- UML Extension Mechanims 8 The UML Metamodel A metamodel is a model representing the structure and semantics of a particular set of models A UML model is an instance of the UML metamodel The UML metamodel Describes the UML model elements Is defined using a subset of UML Is organized in the form of packages The UML Metamodel (cont.) UML metamodel is defined according to the following concepts: - Abstract Syntax: The metamodel of UML is described using UML class diagrams - Well-formedness rules: Well-formedness rules are used to express constraints on the model elements -E.g. a class cannot have two names - Semantics: describes using the natural language the semantics of the model elements We will learn more about metamodelling in a later lecture SEG Topic 2- UML Extension Mechanims 9 SEG Topic 2- UML Extension Mechanims 10 UML Profiles UML Profiles provide an extension mechanism for building UML models for particular domains - e.g. real-time systems, web development, etc A profile consists of a package that contains one or more related extension mechanisms (such as stereotypes, tagged values and constraints) that are applied to UML model elements Profiles do not extend the UML metamodel. They are also called the UML light-weight extension mechanism UML Profiles (cont.) A UML profile is a specification that does one or more of the following: - Identifies a subset of the UML metamodel (which may be the entire UML metamodel) - Specifies stereotypes and/or tagged values - Specifies well-formedness rules beyond those that already exist - Specifies semantics expressed in natural language SEG Topic 2- UML Extension Mechanims 11 SEG Topic 2- UML Extension Mechanims 12

12 Example of a profile inspired by the research report of Cabot et al. (2003) We would like to create a UML profile for representing basic GUI components. The GUI profile package GUI Profile Class and Association are part of UML metamodel We suppose that our GUI contains the following components: - Forms (which can also be dialog boxes) - Buttons <<stereotype>> Form Class <<stereotype>> Button <<stereotype>> Contains Association <<stereotype>> Invokes Constraints: (in practice, we need to be more precise) A form can invoke a dialog box A form as well as a dialog box can contain buttons <<stereotype>> DialogBox SEG Topic 2- UML Extension Mechanims 13 SEG Topic 2- UML Extension Mechanims 14 Instance Diagram of the GUI Profile <<Form>> MainView 1 <<Invokes>> 1 <<Contains>> <<DialogBox>> OpenDialogBox 1 1 <<Contains>> <<Button>> OkButton 1 1 <<Button>> CancelButton SEG Topic 2- UML Extension Mechanims 15

13 SEG4210 Advanced Software Design and Reengineering TOPIC 3 Advanced UML and Umple Class Access Visibility operators define the scope of the attributes and methods of the class. Possibilities are: - public (+): access is granted to any other classes - protected (#): access is granted to classes that are derived from this class - private(-): access is granted to the defining class only - package(~): access granted to classes in the same package (or nested subpackages) Account - accountnumber # balance + withdraw + deposit + getbalance ~ computeinterest SEG Topic 3 - Advanced UML and Umple 2 Parameterized Classes (Templates) Class templates provide means for generic programming Defining a generic class enables different type-specific versions of such a class to be generated no need to repeatedly writing the class code for each type A class template contains one or more unbound formal parameters Parameterized Classes (Template) Class List represents a collection of objects of a class That class becomes a parameter to the parameterized class - e.g. list of accounts Parameterized class List T T Parameter To use the template, we need to bound its parameters to actual values This creates a bound form, which is the usable class Insert(T) Remove(T) <<bind>> T to Account AccountList In UML, parameterization does not apply only to classes it can also be applied to packages and collaborations SEG Topic 3 - Advanced UML and Umple 3 SEG Topic 3 - Advanced UML and Umple 4 Nested Classes A nested class is a class that is defined within another class Nested classes are used for implementation convenience rather than for information hiding. The nested class belongs to the namespace of the declaring class and may only be used within it Notation Type and Implementation Classes A Type class is used to specify a domain of objects without defining the physical implementation of those objects An Implementation Class defines the physical data structure as implemented in traditional languages (Java, C++, Smalltalk, etc.). An Implementation Class is said to realize a Type if it provides all of the operations defined for the Type an Implementation Class may realize a number of different Types Type and Implementation classes are useful for defining data structures SEG Topic 3 - Advanced UML and Umple 5 SEG Topic 3 - Advanced UML and Umple 6

14 Notation A type is shown with the stereotype «type» An implementation class is shown with the stereotype «implementationclass» The implementation of a type is modeled with the realization relationship Utility Classes A utility is a grouping of global variables and procedures in the form of a class utilities are used for programming convenience A utility class is a class with only class-scope attributes and operations <<realize>> The stereotype <<utility>> is used to indicate that a class is a utility Source: OMG - UML Specification PI <<utility>> Math sin() cos() Utility Class SEG Topic 3 - Advanced UML and Umple 7 SEG Topic 3 - Advanced UML and Umple 8 Enumeration An Enumeration is a user-defined data type The instances of an enumeration are literals (specified by the user) The stereotype <enumeration>> is used to indicate that a class is an enumeration name address phone Contact 1 <<enumeration> PersonRole family member friend colleague literals N-ary Association An n-ary association is an association among three or more classes N equals to the number of classes in the association Each instance of the association is an n-tuple of values from the respective classes A binary association (seen in the previous lectures) is a special case of the n-ary association the multiplicities of n-ary association are less obvious than multiplicities of binary associations It is usually best to use binary associations to keep a model clearer SEG Topic 3 - Advanced UML and Umple 9 SEG Topic 3 - Advanced UML and Umple 10 Example Indicates n-ary association Composite Objects A composite object is an object which is composed of other objects called parts useful for representing real-time systems A composite object is an instance of a composite class - which implies the composition aggregation between the class and its parts Vehicle veh:vehicle Association class Part Class diagram with composition part1:part part2:part object of the class Vehicle SEG Topic 3 - Advanced UML and Umple 11 SEG Topic 3 - Advanced UML and Umple 12

15 Active object Example An active object is one that owns a thread of control e.g. processes and threads A passive object holds data but does not initiate control e.g. Account, Student, etc An active object is shown as a rectangle with a heavy border It is very common that an active object is a composite object (contains other objects) Source: OMG UML Specification SEG Topic 3 - Advanced UML and Umple 13 SEG Topic 3 - Advanced UML and Umple 14 State Diagrams - History Pseudostates Example History pseudostates are used to make the object return to the previously visited hierarchical state instead of starting for the initial state There are two different history pseudostates: - Shallow history means that history applies to the current nesting substate only - states nested more deeply are not affected by the presence of history pseudostates - Shallow history is indicated with an icon labeled H - Deep history applies to all levels of nesting, and is indicated with H Source: OMG UML specification SEG Topic 3 - Advanced UML and Umple 15 SEG Topic 3 - Advanced UML and Umple 16 Optimization techniques (caching) Storing additional data to make calculations faster Also called redundant attributes and redundant associations Redundant attributes After adding a redundant attribute The added element is called in UML: derived element the name of the derived element is preceded by / Example: Whenever the students CGPA must be reported, we have to iterate through all course sections the student has taken This is wasteful if queries are more common than updates CourseSection Student / CGPA CourseSection Student grade grade SEG Topic 3 - Advanced UML and Umple 17 SEG Topic 3 - Advanced UML and Umple 18

16 Redundant attributes (cont.) Any method that logically affects the validity of the redundant data must invalidate the cache Example: when a grade is changed, CGPA is set to NULL Any method that accesses the redundant data must: if the cache is invalid, calculate the redundant value and store it - e.g. calculate the CGPA Always return the redundant value, that is now guaranteed valid Redundant associations We can calculate how many students have earned a certain certificate by - traversing the students and check all their courses; - comparing these to the requirements for certificates However we can maintain an extra association to save the search: - useful if the search is done much more often than updates Course Certificate required for CourseSection Student grade SEG Topic 3 - Advanced UML and Umple 19 SEG Topic 3 - Advanced UML and Umple 20 Redundant associations (cont.) Add a many-to-many association from Certificate to Student Every time a student passes a course, the appropriate method would have to update any certificates for which that course was required But watch out if certificate requirements change! Course Certificate required for CourseSection /achieved Student Points about caching and redundancy They add complexity and reduce maintainability They should only be used when there are performance problems or obvious wastes of resources Do not add these features until you know you are wasting significant unnecessary resources grade SEG Topic 3 - Advanced UML and Umple 21 SEG Topic 3 - Advanced UML and Umple 22 Types of caching Immediate redundancy (eager evaluation) update the redundant value when the data it depends on is updated don t wait for something to query the redundant value maximizes query speed; minimizes update speed - e.g. update the CGPA whenever any grade is changed Background redundancy update redundant value when CPU is idle some redundant values will not need to wait for a query before they are updated Unlimited caching as described earlier store all calculation results whenever a query is made Types of caching (cont.) Limited caching don t keep all redundant values used when redundant values consume much memory keep most recently used or most commonly used Calculation on demand no redundancy at all simplest, easiest to understand design Deferred calculation (lazy evaluation) don t calculate until you know the results of the calculation are needed when a query is made for a value, return instructions for how to compute the value, not the value itself useful if calculating the value is very expensive, yet you are not really sure if you will make use of the queried value SEG Topic 3 - Advanced UML and Umple 23 SEG Topic 3 - Advanced UML and Umple 24

17 Fine tuning the design Several techniques that improve Understandability and Maintainability Add simple methods that call methods with more arguments Sometimes it is useful to have several operations that differ only by the number of arguments Defaults are used for missing arguments Factoring out potential hooks Add extra methods that implement parts of operations where flexibility is needed these are called by template methods subclasses can implement or override hooks Shape draw drawborder predraw postdraw FilledShape postdraw "Template method calls hooks:" self predraw. self drawborder. self postdraw. Hook method to perform basic functionality Hook methods available to be overridden in subclasses VolatileShape predraw Override hook to fill in interior of shape Override hook to cache background of shape so it can be rapidly erased SEG Topic 3 - Advanced UML and Umple 25 SEG Topic 3 - Advanced UML and Umple 26 Improve the abstractions of classes Creating an abstract superclass that contains some of the features of its subclasses Reasons for abstracting out: To make the subclasses simpler - can even be done when there is just one subclass To make the superclass reusable - identify all possible candidates for reusability Improving delegation Delegation occurs when a method does nothing except forward a message to another object i.e. a object delegates responsibility to another Reasons for using delegation: A.To ensure a class only talks to its neighbours Booking deptime SpecificFlight RegularFlight deptime To make the system extensible or more easily configurable - with an abstract superclass we can add new specialized subclasses whenever the need arises - these will just have a few methods to do specialized functions Booking deptime traverses two associations SpecificFlight deptime RegularFlight deptime traverses association traverses association SEG Topic 3 - Advanced UML and Umple 27 SEG Topic 3 - Advanced UML and Umple 28 Improving delegation (cont.) B. To avoid duplicating functionality in more than one class e.g. it would have been bad to have separate instance variables and calculations of dep time in Specific Flight and Regular Flight C. To reuse code without abusing inheritance e.g. stack would contain a list rather than being a subclass of list Stack would have method that delegates size etc. to the contained list ListStackBad:Good:ListStack Reviewing the design Ensure as many methods as possible are private improves information hiding Ensure instance variables are accessed by methods rather than directly unless this causes an efficiency problem Ensure that the only associations traversed by a method are ones connected to its class only one method should traverse an association (others should call it) SEG Topic 3 - Advanced UML and Umple 29 SEG Topic 3 - Advanced UML and Umple 30

18 Reviewing the design (cont.) Ensure interfaces are free of implementation details Make sure each method is cohesive and as short as possible split a method into submethods if possible Consider breaking up classes using inheritance or playerrole framework if it contains (as guidelines): more than 8 attributes more than 5 associations more than 40 operations Umple A programming language family developed in my research lab Adds associations and attributes to programming languages Java PHP Works with Rational Software Modeller and some other tools for diagram generation and code generation Stand-along code-generator is online at SEG Topic 3 - Advanced UML and Umple 31 SEG Topic 3 - Advanced UML and Umple 32 Declaration of classes and attributes class Student { studentnumber; // defaults to String String grade; Integer entryaverage; // implemented as int Associations class Student { id; name; class Course { description; code; class CourseSection { sectionletter; Course; association { CourseSection; Student registrant; SEG Topic 3 - Advanced UML and Umple 33 SEG Topic 3 - Advanced UML and Umple 34 Selected patterns class University { singleton; String name; SEG Topic 3 - Advanced UML and Umple 35

19 What is a Meta-metamodel? SEG4210 Advanced Software Design and Reengineering TOPIC 4 Metamodelling A metamodel describes information about models A meta-metamodel describes information about metamodels Metamodels that are defined using the same metametamodel - Can exchange information - Can be used by the same CASE tools that understand the meta-metamodel SEG Topic 4 - Metamodelling 2 What is MOF? OMG 4-Layer Architecture MOF stands for Meta Object Facility enables meta-metamodeling of UML level metamodels It defines a small set of concepts (such as package, class, method, attribute ) that - allow one to define and manipulate models of metadata (data about data) - are described using a subset UML notation SEG Topic 4 - Metamodelling 3 SEG Topic 4 - Metamodelling 4 OMG 4-Layer Architecture (Cont.) MOF Model SEG Topic 4 - Metamodelling 5 SEG Topic 4 - Metamodelling 6

20 MOF Key Abstract Classes MOF Key Abstract Classes (Cont.) ModelElement common base Class of all M3-level Classes. Every ModelElement has a name Namespace base Class for all M3-level Classes that need to act as containers GeneralizableElement base Class for all M3-level Classes that support generalization (i.e. inheritance) TypedElement base Class for M3-level Classes such as Attribute, Parameter, and Constant whose definition requires a type specification Classifier base Class for all M3-level Classes that (notionally) define types. Examples of Classifier include Class and DataType SEG Topic 4 - Metamodelling 7 SEG Topic 4 - Metamodelling 8 The MOF Model: Main Concrete Classes The key concrete classes (or meta-metaclasses) of MOF are as follows: - Class - Association - Exception (for defining abnormal behaviours) - Attribute - Constant - Constraint The MOF Model: Key associations Contains: relates a ModelElement to the Namespace that contains it Generalizes: relates a GeneralizableElement to its ancestors (superclass and subclass) IsOfType: relates a TypedElement to the Classifier that defines its type - An object is an instance of a class DependsOn : relates a ModelElement to others that its definition depends on - E.g. a package depends on another package SEG Topic 4 - Metamodelling 9 SEG Topic 4 - Metamodelling 10 UML Meta Model Link Association Relationship Generalization discriminator 2.. connection qualifier AssociationClass Comment specialization AssociationEnd isnavigable aggregation multiplicity 0..1 Attribute initialvalue ModelElement name Class Element StructuralFeature multiplicity ownedelement participant Operation isabstract Interface importedelement Feature visibility Primitive {ordered type specification Metaclasses used in class, package, component and deployment diagrams child parent specification DataType GeneralizableElement isroot isleaf isabstract owner BehaviouralFeature Method body Classifier Subsystem Enumeration type 1.. Node Namespace Package ProgrammingLanguageType Parameter Model deploymmentlocation defaultvalue kind {ordered resident Instance Object Component Model Elements An element is an atomic constituent of a model. Element is the top metaclass in the metaclass hierarchy A model element is a named entity in a Model It is the base for all modeling metaclasses in UML - All other modeling metaclasses are either direct or indirect subclasses of ModelElement ModelElement name Element 1.. EnumerationLiteral SEG Topic 4 - Metamodelling 11 SEG Topic 4 - Metamodelling 12

21 Features Feature is an abstract class that declares a behavioral or structural property of - an instance of a Classifier - the Classifier itself A behavioral feature refers to a dynamic feature of a model element - E.g. operation or method A structural feature refers to a static feature of a model element - E.g. attribute Attribute initialvalue StructuralFeature multiplicity Operation isabstract Feature visibility specification {ordered owner BehaviouralFeature Method body Classifier Classifier A classifier is an element that describes behavioral and structural features - E.g. class, data type, interface, component Classifier is an abstract class that - declares a collection of Features, such as Attributes, Methods - has a name, which is unique in the Namespace enclosing the Classifier Class Feature visibility Interface Namespace Classifier {ordered Primitive DataType Structure Subsystem Enumeration 1.. Node deploymmentlocation resident ProgrammingLanguageType Component EnumerationLiteral SEG Topic 4 - Metamodelling 13 SEG Topic 4 - Metamodelling 14 Classifier (cont.) Relationships A classifier defines a namespace and is a generalizable element A relationship is a connection among model elements Relationship Generalization Can have - association ends - parameters - instances AssociationEnd isnavigable aggregation multiplicity participant Feature visibility {ordered type specification owner GeneralizableElement isroot isleaf isabstract Classifier type 1.. Namespace Parameter defaultvalue kind Instance Object UML defines several relationships such as: - Association - Generalization UML defines other types of relationships that are not shown in this diagram, such as: - Dependency - Flow discriminator Association AssociationClass Class SEG Topic 4 - Metamodelling 15 SEG Topic 4 - Metamodelling 16 Namespace A namespace is a part of a model that contains a set of other model elements - E.g. Associations and Classifiers - the name of an owned model element is unique within the namespace Namespace is an abstract metaclass and it subclasses are - Classifier - Package ModelElement name ownedelement GeneralizableElement isroot isleaf isabstract Classifier importedelement Subsystem Namespace Package Model Data Types UML Data types include - primitive built-in types (such as integer and string) - definable enumeration types (such as Boolean whose literals are false and true) Programming languages data types - are specified according to the semantics of a particular programming language - are not portable among languages (except by agreement among the languages) - do not map into other UML classifiers Enumerations are a user-defined data types whose instances are literals (specified by the user) Primitive DataType Enumeration ProgrammingLanguageType 1.. EnumerationLiteral SEG Topic 4 - Metamodelling 17 SEG Topic 4 - Metamodelling 18

22 Namespace Relationship AssociationEnd Classifier Use Case Diagrams Metamodel Package Association isnavigable aggregation multiplicity Class BankSystem Customer 1..2 Account StructuralFeature multiplicity Attribute initialvalue accountnumber balance overdraftlimit withdraw deposit Relationship Generalization discriminator BehaviouralFeature Chequing Saving CreditCard expirydate Method Mapping of UML Models to Metamodel Elements (Example) SEG Topic 4 - Metamodelling 19 SEG Topic 4 - Metamodelling 20 Mapping Use Cases Model to Metamodel Classifier State Machines (Main Metamodel) Classifier UseCase Actor Relationship Open file Generalization discriminator Ordinary User Open file by typing name Open file by browsing Relationship «extend» «include» Include System Administrator Attempt to open file that does not exist Browse for file Relationship Extend SEG Topic 4 - Metamodelling 21 SEG Topic 4 - Metamodelling 22 Mapping State Machines to Metamodel Extension Mechanisms Metamodel State StateVertex State SimpleState 0..1 PseudoState entry Procedure Closed Enter / stop motor pressbutton Opening Enter / run motor forwards closingcompleted pressbutton openingcompleted Transition 0..1 Closing Enter / run motor in reverse pressbutton Open Enter / stop motor Event SEG Topic 4 - Metamodelling 23 SEG Topic 4 - Metamodelling 24

23 Example GeneralizableElement Stereotype LinearShape {ordered Path Line Polygon length {edge->size=1 {length = edge.length->sum RegularPolygon Constraint {edge->first.startpoint = edge->last.endpoint {edge->forall(e1,e2 e1.length = e2.length) edge <<geometry> 1.. LineSegment startpoint: Point endpoint: Point length : int {startpoint <> endpoint SEG Topic 4 - Metamodelling 25

24 SEG4210 Advanced Software Engineering and Reengineering TOPIC 5 Object Constraint Language (OCL) What is OCL? OCL is a formal language used to express constraints. Constraint: An invariant condition that must hold for the system being modeled. Constraints do not have side effects Their evaluation cannot alter the state of the executing system. No expression you can write in OCL allows side effects E.g. there is no way to assign a value to an attribute Expressions can only return a value OCL cannot be used as a programming language SEG Topic 5 - Object Constraint Language 2 More on constraints Constraints are applied to instances of objects of the UML metamodel i.e. to model objects that are instances of Class, Attribute, AssociationEnd, Association, etc. etc. Without OCL, constraints would have to be expressed in natural language This almost always results in ambiguities The evaluation of an OCL constraint is instantaneous. the states of objects in a model cannot change during evaluation. Formal specification languages in general Various other formal languages have also been used in software engineering e.g. Z (pronounced 'zed') Most such languages have proven difficult for the average developer to use The mathematical symbols are not well known and use obscure fonts SEG Topic 5 - Object Constraint Language 3 SEG Topic 5 - Object Constraint Language 4 Formal specification languages, continued Formal specification languages are for modelling not programming Some things in OCL are not necessarily executable. E.g. there is an allinstances operation Implementation issues (e.g. the data structures to be used to implement an association) cannot be referenced As with other formal specification languages, most of OCL represents mathematical concepts from Logic Set theory Places to use OCL in UML models To specify invariants on classes and types in the class model To specify type invariant for stereotypes To describe pre- and post- conditions on operations and methods To describe guards As a navigation language To specify constraints on operations OCL started as a business modeling language within the IBM insurance division SEG Topic 5 - Object Constraint Language 5 SEG Topic 5 - Object Constraint Language 6

25 Comments in OCL A class diagram for discussion (from the OCL specification Comments follow two dashes -- this is a comment Most of the examples on subsequent slides come from the UML 1.5 spec: SEG Topic 5 - Object Constraint Language 7 SEG Topic 5 - Object Constraint Language 8 OCL is a strongly Typed Language Basic types in OCL To be well formed, an OCL expression must conform to type conformance rules E.g., you cannot compare an Integer with a String. Each Classifier within a UML model becomes an OCL type E.g. each class you create OCL includes a set of supplementary predefined types Boolean -> true, false Ops: and, or, xor, not, implies, if-then-else Integer -> 1, -5, 2, 34, 26524,... Ops:, +, -, /, abs() Real -> 1.5, 3.14,... Ops:, +, -, /, floor() String -> 'To be or not to be... Ops: toupper(), concat() SEG Topic 5 - Object Constraint Language 9 SEG Topic 5 - Object Constraint Language 10 Use of enumeration types context Person inv: sex = Sex::male OCL expressions can refer to model elements from the UML metamodel such as Properties Attributes AssociationEnds Methods where isquery is true Examples context AType inv: self.property context Person inv: self.age > 0 SEG Topic 5 - Object Constraint Language 11 SEG Topic 5 - Object Constraint Language 12

26 Collection types and navigation in OCL expressions If self is class C, with attribute a Then self.a evaluates to the object stored in a. If C has a one-to-many association called assoc to another class D Then self.assoc evaluates to a Set whose elements are of type D. If assoc is {ordered then a Sequence results If D has attribute b Then the expression self.assoc.b evaluates to the set of all the b s belonging to D Example expressions context Company inv: self.manager.isunemployed = false -- self.manager evaluates to a Person inv: self.employee->notempty() -- self.employee evaluates to a Set Note: ->notempty() is a call to an OCL built in Collection function Discussed a bit later SEG Topic 5 - Object Constraint Language 13 SEG Topic 5 - Object Constraint Language 14 Some OCL functions defined on all objects oclistypeof(t : OclType) : Boolean true if the type of self and t are the same. E.g. context Person inv: self.oclistypeof( Person ) -- is true inv: self.oclistypeof( Company) -- is false ocliskindof(t : OclType) : Boolean true if t is either the direct type or one of the supertypes of an object. OCL built-in Collection functions You can define Collections by navigation or directly: Set { 1, 2, 5, 88 Set { 'apple', 'orange', 'strawberry' Sequence { 1, 3, 45, 2, 3 Sequence { 'ape', 'nut' The notation ->function() is used to call a built in function on an OCL Collection Do not confuse this with the dot. which is used to access properties and navigate including calling query functions defined in the model SEG Topic 5 - Object Constraint Language 15 SEG Topic 5 - Object Constraint Language 16 Some important OCL built in Collection functions acollection->isempty(), ->notempty acollection->size() acollection->includes(anobject) acollectionofnumbers->sum() acollection->exists(booleanexpression) Returns true if booleanexpression is true for any element of acollection This is the equivalent of the! symbol in mathematical logic Select and reject: Picking subcollections context Company inv: self.employee->select(age > 50)->notEmpty() -- select(age > 50) picks the people over 50 context Company inv: self.employee->select(p p.age > 50)->notEmpty() ->reject() just picks the opposite subset SEG Topic 5 - Object Constraint Language 17 SEG Topic 5 - Object Constraint Language 18

27 Collect: generating parallel collections self.employee->collect(birthdate) Creates a collection of equal size as the set of employees, with the employee dates The result will be a Bag A Bag can contain duplicates! forall: Evaluating some expression on every element of a collection (" in logic) collection->forall( v : Type bool-expr-with-v ) collection->forall( v boolean-expression-with-v ) collection->forall( boolean-expression ) The following are true if everybody in the company is called Jack inv: self.employee->forall( forename = 'Jack' ) inv: self.employee->forall( p p.forename = 'Jack' ) inv: self.employee->forall( p : Person p.forename = 'Jack' ) SEG Topic 5 - Object Constraint Language 19 SEG Topic 5 - Object Constraint Language 20 Some more collection functions c1->includesall(c2) True if every element of c2 is found in c1 c1->excludesall(c2) True if no element of c2 is found in c1 For sets: s1->intersection(s2) The set of those elements found s1 and also in s2 s1->union(s2) The set of those elements found in either s1 or s2 s1->excluding(x) The set s1 with object x omitted. For sequences seq->first() Logical implication context Person inv: (self.wife->notempty() implies self.wife.age >= 18) and (self.husband->notempty() implies self.husband.age >= 18) SEG Topic 5 - Object Constraint Language 21 SEG Topic 5 - Object Constraint Language 22 forall with two variables Considers each pair in the Cartesian product of employees context Company inv: self.employee->forall( e1, e2 : Person e1 <> e2 implies e1.forename <> e2.forename) This is the same as self.employee->forall(e1 self.employee->forall (e2 e1 <> e2 implies e1.forename <> e2.forename))) Let expressions context Person inv: let income : Integer = self.job.salary->sum() let hastitle(t : String) : Boolean = self.job->exists(title = t) in if isunemployed then self.income < 100 else self.income >= 100 and self.hastitle( manager ) endif SEG Topic 5 - Object Constraint Language 23 SEG Topic 5 - Object Constraint Language 24

28 Let expressions that define values for use in other expressions These use the def keyword context Person def: let income : Integer = self.job.salary->sum() let hastitle(t : String) : Boolean = self.job->exists(title = t) An example class invariant The following all say the same thing numberofemployees > 50 self.numberofemployees > 50 context Company inv: self.numberofemployees > 50 context c : Company inv: c.numberofemployees > 50 context c : Company inv enoughemployees: c.numberofemployees > 50 SEG Topic 5 - Object Constraint Language 25 SEG Topic 5 - Object Constraint Language 26 Example preconditions and postconditions context Person::income(d : Date) : Integer post: result = 5000 context Typename::operationName( param1 : Integer ): Integer pre parameterok: param1 > 5 post resultok: result < 0 Use in postconditions You often want to write a postcondition that states what has changed with respect to a precondition Use property@pre to refer to the value of property prior to execution e.g. context Company::hireEmployee(p : Person) pre : not employee->includes(p) post: employee->includes(p) and stockprice() = stockprice@pre() + 10 SEG Topic 5 - Object Constraint Language 27 SEG Topic 5 - Object Constraint Language 28 Precedence Rules for OCL expressions Precedence order for operations, starting with dot and arrow operations:. and -> unary not and unary minus - and / + and binary - if-then-else-endif <, >, <=, >= =, <> and, or and xor implies Examples based on a block handler Parentheses ( and ) can be used to change precedence Often useful simply too make it clearer SEG Topic 5 - Object Constraint Language 29 SEG Topic 5 - Object Constraint Language 30

29 Copyright acknowledgement The preceding diagram and the examples that follow were created by Prof. Lethbridge and appear in the 6th edition of Roger Pressman s Software Engineering: A Practitioner s Approach to bbe published soon Examples OCL expressions in the BlockHandler problem No block will be marked as both unused and used context BlockHandler inv: (self.used->intersection(self.free)) ->isempty() All the sets of blocks held in the queue will be subsets of the collection of currently used blocks context BlockHandler inv: blockqueue->forall(ablockset used->includesall(ablockset.elements )) SEG Topic 5 - Object Constraint Language 31 SEG Topic 5 - Object Constraint Language 32 Examples 2 No elements of the queue will contain the same block numbers. context BlockHandler inv: blockqueue->forall(blockset1, blockset2 blockset1 <> blockset2 implies blockset1.elements.number ->excludesall(blockset2.elements.number)) Examples 3 The collection of used blocks and blocks that are unused will be the total collection of blocks that make up files. context BlockHandler inv: allblocks = used->union(free) The collection of unused blocks will have no duplicate block numbers. context BlockHandler inv: free->isunique(ablock ablock.number) The collection of used blocks will have no duplicate block numbers. context BlockHandler inv: used->isunique(ablock ablock.number) SEG Topic 5 - Object Constraint Language 33 SEG Topic 5 - Object Constraint Language 34 Examples 4 context BlockHandler::removeBlocks() pre: blockqueue->size() >0 post: used = used@pre - (blockqueue@pre->first()).elements and free = free@pre-> union((blockqueue@pre->first().elements) and blockqueue = blockqueue@pre-> excluding(blockqueue@pre->first) If time permits We will do examples on board based on Traffic Light system SEG Topic 5 - Object Constraint Language 35 SEG Topic 5 - Object Constraint Language 36

30 What is Aspect-Oriented Programming? SEG4210 Advanced Software Design and Reengineering TOPIC 6 Aspect Oriented Programming and Aspect/J A way of dividing up a program Sometimes there are aspects of a program that you need to implement in many different classes and methods, e.g. - Logging - Security - Persistence - Caching and redundancy Sometimes you want to design two features separately even though they are going to be coded in the same classes These separate concerns are implemented as aspects SEG Topic 6 - Aspect Oriented Programming 2 Aspects, continued Aspect-Oriented Programming Languages An aspect is said to cross-cut several classes or methods We code each aspect separately without making the code for several classes of methods more complex Each chunk of code we write ends up being much simpler Before running the compiler an aspect weaver merges the aspects together to create the final system Before designing aspects, we have to understand the joint points Places in classes or methods where code for different aspects can be automatically executed Aspect/J Adds AOP to Java The aspect weaver modifies the byte code Developed by Xerox/PARC Some of the following slides come from there Aspectj.org Strong support within Eclipse Aspect/C++ HyperJ SEG Topic 6 - Aspect Oriented Programming 3 SEG Topic 6 - Aspect Oriented Programming 4 Good modularity Even better modularity URL pattern matching in org.apache.tomcat red shows relevant lines of code nicely fits in two boxes (using inheritance) XML parsing in Apache SEG Topic 6 - Aspect Oriented Programming 5 SEG Topic 6 - Aspect Oriented Programming 6

31 SEG Topic 6 - Aspect Oriented Programming 7 Modularity problem Logging in Apache Not even in a small number of places SEG Topic 6 - Aspect Oriented Programming 8 Another modularity problem - session expiration in Apache / ==================================================================== The Apache Software License, Version 1.1 Copyright (c) 1999 The Apache Software Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowlegement: "This product includes software developed by the Apache Software Foundation ( Alternately, this acknowlegement may appear in the software itself, if and wherever such third-party a cknowlegements normally appear. 4. The names "The Jakarta Project", "Tomcat", and "Apache Software Foundation" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact apache@apache.org. 5. Products derived from this software may not be called "Apache" nor may "Apache" appear in their names without prior written permission of the Apache Group. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==================================================================== This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation. For more information on the Apache Software Foundation, please see < [Additional notices, if required by prior licensing conditions] / package org.apache.tomcat.session; import org.apache.tomcat.core.; import o rg.apache.tomcat.util.stringmanager ; import j ava.io.; import java.net.; import java.util.; import j avax.servlet.; import j avax.servlet.http. ; / Core implementation of an application level James Duncan Davidson Jason Hunter [ j James Todd [gonzo@eng.sun.com] / public class A pplicationsession implements H ttpsession { private StringManager sm = StringManager.getManager("org.apache.tomcat.session " ); private Hashtable values = new H ashtable(); private String id; private ServerSession serversession ; private Context context; private long c reationtime = System.currentTimeMillis();; private long t hisaccesstime = creationtime; private long l astaccessed = creationtime; private int inactiveinterval = -1; private boolean valid = true; ApplicationSession(String id, ServerSession serversession, Context context) { this.serversession = s erversession; this.context = context; this.id = id; this.inactiveinterval = context.getsessiontimeout ( ); if (this.inactiveinterval!= -1) { this.inactiveinterval = 60; ServerSession getserversession() { return s erversession; / Called by context when request comes in so that accesses and i nactivities can be dealt with accordingly. / void accessed() { // set last accessed to thisaccesstime as it will be left over // from the previous access lastaccessed = t hisaccesstime ; thisaccesstime = S ystem.currenttimemillis ( ); validate(); void validate() { // if we have an inactive interval, check to see if we've exceeded it if (inactiveinterval!= -1) { int thisinterval = ( i nt)(system.currenttimemillis() - l astaccessed ) / 1000; if (thisinterval > i nactiveinterval ) { invalidate(); // HTTP SESSION IMPLEMENTATION METHODS public String getid ( ) { if (valid) { return id; else { String m sg = s m.getstring("applicationsession.session.ise " ); throw new IllegalStateException(msg ); public long getcreationtime ( ) { if (valid) { return c reationtime ; else { String m sg = s m.getstring("applicationsession.session.ise " ); throw new IllegalStateException(msg ); / public H ttpsessioncontext getsessioncontext ( ) { return new S essioncontextimpl ( ); public long getlastaccessedtime ( ) { if (valid) { return l astaccessed ; else { String m sg = s m.getstring("applicationsession.session.ise " ); throw new IllegalStateException(msg ); public void invalidate() { serversession. removeapplicationsession(context); // remove everything in the session Enumeration enum = values.keys(); while ( e num. hasmoreelements ( )) { String name = (String)enum. n extelement(); removevalue ( name); valid = false; public b oolean isnew() { if (! valid) { String m sg = sm. getstring ("a pplicationsession. session.ise " ); throw new IllegalStateException ( msg ); if (thisaccesstime = = creationtime) { return true; else { return false; / public void putvalue(string name, Object value) { setattribute(name, value); public void setattribute(string name, Object value) { if (! valid) { String m sg = sm. getstring ("a pplicationsession. session.ise " ); throw new IllegalStateException ( msg ); if (name == null) { String m sg = sm. getstring ("a pplicationsession. value.iae " ); throw new IllegalArgumentException( m sg); removevalue ( name); // remove any existing binding if (value!= null && value i nstanceof HttpSessionBindingListener) { HttpSessionBindingEvent e = new HttpSessionBindingEvent ( this, name); ((HttpSessionBindingListener)value).valueBound(e); values.put(name, value); / public Object getvalue(string name) { return g etattribute ( name); public Object getattribute(string name) { if (! valid) { String m sg = sm. getstring ("a pplicationsession. session.ise " ); throw new IllegalStateException(msg ); if (name == null) { String m sg = s m.getstring("applicationsession.value.iae " ); throw new IllegalArgumentException(msg); return values.get(name); / public String[] getvaluenames ( ) { Enumeration e = getattributenames ( ); Vector names = new Vector(); while ( e.hasmoreelements()) { names.addelement(e.nextelement()); String[] v aluenames = new String[names.size()]; names.copyinto(valuenames ); return v aluenames ; public Enumeration g etattributenames() { if (! valid) { String m sg = s m.getstring("applicationsession.session.ise " ); throw new IllegalStateException(msg ); Hashtable valuesclone = ( H ashtable)values.clone ( ); return (Enumeration)valuesClone.keys(); / public void removevalue(string name) { removeattribute(name); public void removeattribute(string name) { if (! valid) { String m sg = s m.getstring("applicationsession.session.ise " ); throw new IllegalStateException(msg ); if (name == null) { String m sg = s m.getstring("applicationsession.value.iae " ); throw new IllegalArgumentException(msg); Object o = values.get(name); if (o instanceof H ttpsessionbindinglistener ) { HttpSessionBindingEvent e = new HttpSessionBindingEvent(this,name ); ((HttpSessionBindingListener)o).valueUnbound(e); values.remove(name); public void setmaxinactiveinterval(int interval) { if (! valid) { String m sg = s m.getstring("applicationsession.session.ise " ); throw new IllegalStateException(msg ); inactiveinterval = interval; public i nt g etmaxinactiveinterval ( ) { if (! valid) { String m sg = s m.getstring("applicationsession.session.ise " ); throw new IllegalStateException(msg ); return i nactiveinterval ; // ApplicationSession package org.apache.tomcat.session; import java.io. I OException; import java.io. O bjectinputstream; import java.io. O bjectoutputstream ; import java.io. S erializable ; import java.util.enumeration; import java.util. H ashtable; import java.util.vector; import j avax. s ervlet. S ervletexception ; import j avax. s ervlet.http.httpsession ; import j avax. s ervlet.http.httpsessionbindingevent ; import j avax. s ervlet.http.httpsessionbindinglistener; import j avax. s ervlet.http.httpsessioncontext; import org.apache.tomcat. c atalina. ; import org.apache.tomcat. u til. StringManager ; / Standard implementation of the <b>session</b> interface. This object is s erializable, so that it can be stored in persistent storage or transferred to a different JVM for distributable session support. <p> <b>implementation NOTE</b>: An instance of this class represents both the internal (Session) and application level ( H ttpsession) view of the session. However, because the class itself is not declared public, Java logic outside of the <code>org.apache.tomcat.session</code> package cannot cast an H ttpsession view of this instance back to a Session Craig R. $Revision: 1.2 $ $Date: 2000/05/15 17:54:10 $ / final class StandardSession implements H ttpsession, Session { // Constructors / Construct a new Session associated with the specified manager The manager with which this Session is associated / public S tandardsession(manager manager) { super(); this.manager = manager; // Instance Variables / The collection of user data attributes associated with this Session. / private Hashtable attributes = new H ashtable(); / The time this session was created, in milliseconds since midnight, January 1, 1970 GMT. / private long c reationtime = 0L; / The session identifier of this Session. / private String id = null; / Descriptive information describing this Session implementation. / private static final String info = "StandardSession/1.0"; / The last accessed time for this Session. / private long l astaccessedtime = creationtime; / The Manager with which this Session is associated. / private Manager manager = null; / The maximum time interval, in seconds, between client requests before the s ervlet container may invalidate this session. A negative time indicates that the session should never time out. / private int maxinactiveinterval = -1; / Flag indicating whether this session is new or not. / private boolean isnew = true; / Flag indicating whether this session is valid or not. / private boolean isvalid = false; / The string manager for this package. / private StringManager sm = StringManager.getManager("org.apache.tomcat.session " ); / The HTTP session context associated with this session. / private static H ttpsessioncontext sessioncontext = null; / The current accessed time for this session. / private long t hisaccessedtime = creationtime; // Session Properties / Set the creation time for this session. This method is called by the Manager when an existing Session instance is time The new creation time / public void setcreationtime(long time) { this.creationtime = time; this.lastaccessedtime = time; this.thisaccessedtime = time; / Return the session identifier for this session. / public String getid ( ) { return (this.id); / Set the session identifier for this id The new session identifier / public void setid(string id) { if ((this.id!= null) && (manager!= null) && (manager i nstanceof ManagerBase )) ((ManagerBase ) manager).remove(this); this.id = id; if ((manager!= null) && (manager instanceof ManagerBase )) ((ManagerBase ) manager).add(this); / Return descriptive information about this Session implementation and the corresponding version number, in the format <code>& l t;description>/<version></code>. / public String getinfo ( ) { return (this.info); / Return the last time the client sent a request associated with this session, as the number of milliseconds since midnight, January 1, 1970 GMT. Actions that your application takes, such as getting or setting a value associated with the session, do not affect the access time. / public long getlastaccessedtime ( ) { return (this.lastaccessedtime ); / Return the Manager within which this Session is valid. / public Manager g etmanager ( ) { return (this.manager); / Set the Manager within which this Session is manager The new Manager / public void setmanager(manager manager) { this.manager = manager; / Return the maximum time interval, in seconds, between client requests before the servlet container will invalidate the session. A negative time indicates that the session should never time IllegalStateException if this method is called on an invalidated session / public i nt g etmaxinactiveinterval ( ) { return (this.maxinactiveinterval); / Set the maximum time interval, in seconds, between client requests before the servlet container will invalidate the session. A negative time indicates that the session should never time interval The new maximum interval / public void setmaxinactiveinterval(int interval) { this.maxinactiveinterval = interval; / Return the <code>httpsession < /code> for which this object is the facade. / public H ttpsession getsession ( ) { return (( H ttpsession) this); // Session Public Methods / Update the accessed time information for this session. This method should be called by the context when a request comes in for a particular session, even if the application does not reference it. / public void access() { this. l astaccessedtime = this. t hisaccessedtime ; this. t hisaccessedtime = System.currentTimeMillis(); this.isnew=false; / Perform the internal processing required to invalidate this session, without triggering an exception if the session has already expired. / public void expire() { // Remove this session from our manager's active sessions if ((manager!= null) && (manager instanceof ManagerBase )) ((ManagerBase ) manager).remove(this); // Unbind any objects associated with this session Vector results = new Vector(); Enumeration attrs = getattributenames ( ); while ( a ttrs.hasmoreelements()) { String a ttr = (String) a ttrs.nextelement(); results.addelement(attr ); Enumeration names = results.elements(); while ( n ames.hasmoreelements()) { String name = (String) n ames.nextelement(); removeattribute(name); // Mark this session as invalid setvalid(false); / Release all object references, and initialize instance variables, in preparation for reuse of this object. / public void recycle() { // Reset the instance variables associated with this Session attributes.clear(); creationtime = 0L; id = null; lastaccessedtime = 0L; manager = null; maxinactiveinterval = -1; isnew = true; isvalid = false; // Tell our Manager that this Session has been recycled if ((manager!= null) && (manager instanceof ManagerBase )) ((ManagerBase ) manager).recycle(this); // Session Package Methods / Return the <code>isvalid < /code> flag for this session. / boolean isvalid ( ) { return (this.isvalid); / Set the <code> i snew</code> flag for this isnew The new value for the <code>isnew < /code> flag / void s etnew(boolean isnew ) { this.isnew = i snew; / Set the <code> i svalid</code> flag for this isvalid The new value for the <code>isvalid < /code> flag / void s etvalid(boolean isvalid ) { this.isvalid = i svalid; // HttpSession Properties / Return the time when this session was created, in milliseconds since midnight, January 1, 1970 IllegalStateException if this method is called on an invalidated session / public long getcreationtime ( ) { return (this.creationtime ); / Return the session context with which this session is As of Version 2.1, this method is deprecated and has no replacement. It will be removed in a future version of the Java S ervlet API. / public H ttpsessioncontext getsessioncontext ( ) { if (sessioncontext == null) sessioncontext = new S tandardsessioncontext ( ); return (sessioncontext); // H ttpsession Public Methods / Return the object bound with the specified name in this session, or <code>null</code> if no object is bound with that name Name of the attribute to be IllegalStateException if this method is called on an invalidated session / public Object getattribute(string name) { return (attributes.get(name)); / Return an <code>enumeration</code> of <code>string</code> objects containing the names of the objects bound to this IllegalStateException if this method is called on an invalidated session / public Enumeration g etattributenames() { return (attributes.keys()); / Return the object bound with the specified name in this session, or <code>null</code> if no object is bound with that name Name of the value to be IllegalStateException if this method is called on an invalidated As of Version 2.2, this method is replaced by <code>getattribute()</code> / public Object getvalue(string name) { return (getattribute(name ) ); / Return the set of names of objects bound to this session. If there are no such objects, a zero-length array is IllegalStateException if this method is called on an invalidated As of Version 2.2, this method is replaced by <code>getattributenames ( )</code> / public String[] getvaluenames ( ) { Vector results = new Vector(); Enumeration attrs = getattributenames ( ); while ( a ttrs.hasmoreelements()) { String a ttr = (String) a ttrs.nextelement(); results.addelement(attr ); String names[] = new String[results.size()]; for ( i nt i = 0; i < names.length; i++) names[i] = (String) results.elementat(i ); return (names); / Invalidates this session and unbinds any objects bound to IllegalStateException if this method is called on an invalidated session / public void invalidate() { // Cause this session to expire expire(); / Return <code>true</code> if the client does not yet know about the session, or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client has disabled the use of cookies, then a session would be new on each IllegalStateException if this method is called on an invalidated session / public b oolean i snew() { return (this.isnew); / Bind an object to this session, using the specified name. If an object of the same name is already bound to this session, the object is replaced. <p> After this method executes, and if the object implements <code> H ttpsessionbindinglistener < /code>, the container calls <code> v aluebound ( )</code> on the name Name to which the object is bound, cannot be value Object to be bound, cannot be IllegalStateException if this method is called on an invalidated As of Version 2.2, this method is replaced by <code>setattribute()</code> / public void putvalue(string name, Object value) { setattribute(name, value); / Remove the object bound with the specified name from this session. If the session does not have an object bound with this name, this method does nothing. <p> After this method executes, and if the object implements <code> H ttpsessionbindinglistener < /code>, the container calls <code> v alueunbound ( )</code> on the name Name of the object to remove from this IllegalStateException if this method is called on an invalidated session / public void removeattribute(string name) { synchronized (attributes) { Object object = attributes.get(name); if (object == null) return; attributes.remove(name); // System.out.println( "Removing attribute " + name ); if (object i nstanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) object).valueunbound (new H ttpsessionbindingevent((httpsession ) this, name)); / Remove the object bound with the specified name from this session. If the session does not have an object bound with this name, this method does nothing. <p> After this method executes, and if the object implements <code> H ttpsessionbindinglistener < /code>, the container calls <code> v alueunbound ( )</code> on the name Name of the object to remove from this IllegalStateException if this method is called on an invalidated As of Version 2.2, this method is replaced by <code>removeattribute ( )</code> / public void removevalue(string name) { removeattribute(name); / Bind an object to this session, using the specified name. If an object of the same name is already bound to this session, the object is replaced. <p> After this method executes, and if the object implements <code> H ttpsessionbindinglistener < /code>, the container calls <code> v aluebound ( )</code> on the name Name to which the object is bound, cannot be value Object to be bound, cannot be IllegalArgumentException if an attempt is made to add a non-serializable object in an environment marked IllegalStateException if this method is called on an invalidated session / public void setattribute(string name, Object value) { if ((manager!= null) && m anager.getdistributable ( ) &&!(value instanceof S erializable )) throw new IllegalArgumentException ( s m.getstring("standardsession.setattribute.iae " )); synchronized (attributes) { removeattribute(name); attributes.put(name, value); if (value instanceof H ttpsessionbindinglistener ) ((HttpSessionBindingListener) value).valuebound (new H ttpsessionbindingevent((httpsession ) this, name)); // HttpSession Private Methods / Read a serialized version of this session object from the specified object input stream. <p> <b>implementation NOTE</b>: The reference to the owning Manager is not restored by this method, and must be set stream The input stream to read ClassNotFoundException if an unknown class is IOException if an input/output error occurs / private void r eadobject(objectinputstream stream) throws C lassnotfoundexception, I OException { // D eserialize the scalar instance variables (except Manager) creationtime = ((Long) s tream.readobject()).longvalue ( ); id = (String) stream.readobject ( ); lastaccessedtime = ((Long) s tream.readobject()).longvalue ( ); maxinactiveinterval = ((Integer) s tream.readobject()).intvalue(); isnew = ((Boolean) s tream.readobject()).booleanvalue(); isvalid = ((Boolean) s tream.readobject()).booleanvalue(); // D eserialize the attribute count and attribute values int n = ((Integer) s tream.readobject()).intvalue(); for ( i nt i = 0; i < n; i++) { String name = (String) s tream.readobject(); Object value = (Object) stream.readobject ( ); attributes.put(name, value); / Write a serialized version of this session object to the specified object output stream. <p> <b>implementation NOTE</b>: The owning Manager will not be stored in the serialized representation of this Session. After calling <code> r eadobject ( )</code>, you must set the associated Manager explicitly. <p> <b>implementation NOTE</b>: Any attribute that is not Serializable will be silently ignored. If you do not want any such attributes, be sure the <code>distributable</code> property of our associated Manager is set to stream The output stream to write IOException if an input/output error occurs / private void w riteobject(objectoutputstream stream) throws I OException { // Write the scalar instance variables (except Manager) stream.writeobject(new L ong(creationtime)); stream.writeobject(id ); stream.writeobject(new L ong(lastaccessedtime)); stream.writeobject(new I nteger(maxinactiveinterval)); stream.writeobject(new B oolean(isnew)); stream.writeobject(new B oolean(isvalid)); // Accumulate the names of s erializable attributes Vector results = new Vector(); Enumeration attrs = getattributenames ( ); while ( a ttrs.hasmoreelements()) { String a ttr = (String) a ttrs.nextelement(); Object value = a ttributes.get(attr); if (value instanceof S erializable ) results.addelement(attr ); // Serialize the attribute count and the attribute values stream.writeobject(new Integer(results.size())); Enumeration names = results.elements(); while ( n ames.hasmoreelements()) { String name = (String) n ames.nextelement(); stream.writeobject(name ); stream.writeobject(attributes.get(name)); crosscut i nvalidate(standardsession s): s & ( i nt g etmaxinactiveinterval ( ) long getcreationtime ( ) Object getattribute(string ) Enumeration g etattributenames() String[] getvaluenames ( ) void invalidate() b oolean i snew() void removeattribute(string) void setattribute(string, Object)); static a dvice(standardsession s): invalidate(s) { before { if (! s.isvalid()) throw new IllegalStateException ( s.sm.getstring("standardsession." + thisjoinpoint.methodname + ".ise " )); // Private Class / This class is a dummy implementation of the <code> H ttpsessioncontext < /code> interface, to conform to the requirement that such an object be returned when <code>httpsession.getsessioncontext ( )</code> is Craig R. As of Java Servlet API 2.1 with no replacement. The interface will be removed in a future version of this API. / final class StandardSessionContext implements HttpSessionContext { private Vector dummy = new Vector(); / Return the session identifiers of all sessions defined within this As of Java Servlet API 2.1 with no replacement. This method must return an empty <code>enumeration</code> and will be removed in a future version of the API. / public Enumeration g etids ( ) { return (dummy.elements()); / Return the <code>httpsession < /code> associated with the specified session id Session identifier for which to look up a As of Java Servlet API 2.1 with no replacement. This method must return null and will be removed in a future version of the API. / public H ttpsession g etsession(string id) { return (null); StandardSession package org.apache.tomcat.session; import java.io. I OException; import java.util.enumeration; import java.util. H ashtable; import java.util.vector; import org.apache.tomcat. c atalina. ; import j avax. s ervlet.http.cookie; import j avax. s ervlet.http.httpsession ; import org.apache.tomcat. u til. StringManager ; import org.w3c.dom.namednodemap; import org.w3c.dom.node; / Standard implementation of the <b>manager</b> interface that provides no session persistence or distributable capabilities, but does support an optional, configurable, maximum number of active sessions allowed. <p> Lifecycle configuration of this component assumes an XML node in the following format: <code> <Manager c lassname="org.apache.tomcat.session.standardmanager " checkinterval = "60" m axactivesessions="-1" maxinactiveinterval = "-1" /> </code> where you can adjust the following parameters, with default values in square brackets: <ul> <li><b>checkinterval < /b> - The interval (in seconds) between background thread checks for expired sessions. [60] <li><b>maxactivesessions < /b> - The maximum number of sessions allowed to be active at once, or -1 for no limit. [-1] <li><b>maxinactiveinterval < /b> - The default maximum number of seconds of inactivity before which the s ervlet container is allowed to time out a session, or -1 for no limit. This value should be overridden from the default session timeout specified in the web application deployment descriptor, if any. [-1] </ Craig R. $Revision: $ $Date: 2000/05/02 21:28:30 $ / public final class S tandardmanager extends ManagerBase implements Lifecycle, Runnable { // Instance Variables / The interval (in seconds) between checks for expired sessions. / private int checkinterval = 60; / Has this component been configured yet? / private boolean configured = false; / The descriptive information about this implementation. / private static final String info = "StandardManager/1.0"; / The maximum number of active Sessions allowed, or -1 for no limit. / protected int maxactivesessions = -1; / The string manager for this package. / private StringManager sm = StringManager.getManager("org.apache.tomcat.session " ); / Has this component been started yet? / private boolean started = false; / The background thread. / private Thread thread = null; / The background thread completion semaphore. / private boolean threaddone = false; / Name to register for the background thread. / private String t hreadname = " S tandardmanager"; // Properties / Return the check interval (in seconds) for this Manager. / public i nt g etcheckinterval ( ) { return (this.checkinterval); / Set the check interval (in seconds) for this checkinterval The new check interval / public void setcheckinterval(int c heckinterval) { this.checkinterval = c heckinterval; / Return descriptive information about this Manager implementation and the corresponding version number, in the format <code><description>/<version&gt ; </code>. / public String getinfo ( ) { return (this.info); / Return the maximum number of active Sessions allowed, or -1 for no limit. / public i nt g etmaxactivesessions ( ) { return (this.maxactivesessions); / Set the maximum number of actives Sessions allowed, or -1 for no max The new maximum number of sessions / public void setmaxactivesessions(int max) { this.maxactivesessions = max; // Public Methods / Construct and return a new session object, based on the default settings specified by this Manager's properties. The session id will be assigned by this method, and available via the g etid() method of the returned session. If a new session cannot be created for any reason, return IllegalStateException if a new session cannot be instantiated for any reason / public Session c reatesession() { if (( m axactivesessions >= 0) && (sessions.size() >= maxactivesessions )) throw new IllegalStateException ( s m.getstring("standardmanager.createsession.ise")); return (super.createsession ( )); // Lifecycle Methods / Configure this component, based on the specified configuration parameters. This method should be called immediately after the component instance is created, and before <code>start()</code> is parameters Configuration parameters for this component (<B>FIXME: What object type should this really IllegalStateException if this component has already been configured and/or LifecycleException i f this component detects a fatal error in the configuration parameters it was given / public void configure(node parameters) throws L ifecycleexception { // Validate and update our current component state if (configured) throw new LifecycleException ( s m.getstring("standardmanager.alreadyconfigured")); configured = true; if (parameters == null) return; // Parse and process our configuration parameters if (!(" M anager".equals(parameters.getnodename ( )))) return; NamedNodeMap attributes = parameters.getattributes(); Node node = null; node = a ttributes.getnameditem("checkinterval " ); if (node!= null) { try { setcheckinterval(integer.parseint(node.getnodevalue ( ))); catch ( T hrowable t) { ; // XXX - Throw exception? node = a ttributes.getnameditem("maxactivesessions " ); if (node!= null) { try { setmaxactivesessions(integer.parseint(node.getnodevalue ( ))); catch ( T hrowable t) { ; // XXX - Throw exception? node = a ttributes.getnameditem("maxinactiveinterval " ); if (node!= null) { try { setmaxinactiveinterval(integer.parseint(node.getnodevalue ( ))); catch ( T hrowable t) { ; // XXX - Throw exception? / Prepare for the beginning of active use of the public methods of this component. This method should be called after <code>configure()</code>, and before any of the public methods of the component are IllegalStateException if this component has not yet been configured (if required for this IllegalStateException if this component has already been LifecycleException if this component detects a fatal error that prevents this component from being used / public void start() throws L ifecycleexception { // Validate and update our current component state if (!configured) throw new LifecycleException ( s m.getstring("standardmanager.notconfigured")); if (started) throw new LifecycleException ( s m.getstring("standardmanager.alreadystarted " )); started = true; // Start the background reaper thread threadstart ( ); / Gracefully terminate the active use of the public methods of this component. This method should be the last one called on a given instance of this IllegalStateException if this component has not been IllegalStateException if this component has already been LifecycleException if this component detects a fatal error that needs to be reported / public void stop() throws LifecycleException { // Validate and update our current component state if (!started) throw new LifecycleException ( s m.getstring("standardmanager.notstarted " )); started = false; // Stop the background reaper thread threadstop(); // Expire all active sessions Session sessions[] = f indsessions ( ); for ( i nt i = 0; i < sessions.length; i++) { StandardSession session = ( S tandardsession) sessions[i]; if (! s ession.isvalid()) continue; session.expire(); // Private Methods / Invalidate all sessions that have expired. / private void p rocessexpires ( ) { long t imenow = S ystem.currenttimemillis ( ); Session sessions[] = f indsessions ( ); for ( i nt i = 0; i < sessions.length; i++) { StandardSession session = ( S tandardsession) sessions[i]; if (! s ession.isvalid()) continue; int maxinactiveinterval = session.getmaxinactiveinterval(); if (maxinactiveinterval < 0) continue; int timeidle = // Truncate, do not round up ( i nt) ((timenow - session.getlastaccessedtime ( )) / 1000L); if (timeidle >= maxinactiveinterval ) session.expire(); / Sleep for the duration specified by the <code> c heckinterval</code> property. / private void t hreadsleep() { try { Thread.sleep(checkInterval 1000L); catch ( I nterruptedexception e) { ; / Start the background thread that will periodically check for session timeouts. / private void t hreadstart() { if (thread!= null) return; threaddone = false; thread = new Thread(this, threadname); thread.setdaemon(true ); thread.start(); / Stop the background thread that is periodically checking for session timeouts. / private void t hreadstop ( ) { if (thread == null) return; threaddone = true; thread.interrupt(); try { thread.join(); catch ( I nterruptedexception e) { ; thread = null; // Background Thread / The background thread that checks for session timeouts and shutdown. / public void run() { // Loop until the termination semaphore is set while (!threaddone) { threadsleep ( ); processexpires(); StandardManager StandardSessionManager package org.apache.tomcat.session; import java.io. I OException; import j avax. s ervlet.http.cookie; import j avax. s ervlet.http.httpsession ; import org.apache.tomcat. c atalina. ; import org.apache.tomcat.core.context; import org.apache.tomcat.core.request; import org.apache.tomcat.core.response; import org.apache.tomcat.core.sessionmanager; import org.apache.tomcat. u til. SessionUtil ; / Specialized implementation of org.apache.tomcat.core.sessionmanager that adapts to the new component-based Manager implementation. <p> XXX - At present, use of <code>standardmanager < /code> is hard coded, and lifecycle configuration is not supported. <p> <b>implementation NOTE</b>: Once we commit to the new Manager/Session paradigm, I would suggest moving the logic implemented here back into the core level. The Tomcat.Next "Manager" interface acts more like a collection class, and has minimal knowledge of the detailed request processing semantics of handling sessions. <p> XXX - At present, there is no way (via the SessionManager i nterface) for a Context to tell the Manager that we create what the default session timeout for this web application (specified in the deployment descriptor) should Craig R. McClanahan / public final class S tandardsessionmanager implements S essionmanager { // Constructors / Create a new SessionManager t hat adapts to the corresponding Manager implementation. / public S tandardsessionmanager ( ) { manager = new StandardManager ( ); if (manager instanceof L ifecycle) { try { ((Lifecycle) manager).configure(null); ((Lifecycle) manager).start(); catch ( L ifecycleexception e) { throw new IllegalStateException ( "" + e); // Instance Variables / The Manager implementation we are actually using. / private Manager manager = null; // Public Methods / Mark the specified session's last accessed time. This should be called for each request by a session The session to be marked / public void accessed(context c tx, Request req, String id) { HttpSession session=findsession ( ctx, id); if( session == null) return; if (session instanceof S ession) ((Session) session).access(); // cache the H ttpsession - avoid another find req. setsession( session ); // XXX should we throw exception or just return null?? public H ttpsession findsession( Context ctx, String id ) { try { Session session = manager.findsession ( id); if(session!=null) return session. g etsession ( ); catch ( I OException e ) { return (null); public H ttpsession createsession(context c tx) { return manager.createsession ( ).getsession(); / Remove all sessions because our associated Context is being shut ctx The context that is being shut down / public void removesessions(context c tx) { // XXX XXX a manager may be shared by multiple // contexts, we just want to remove the sessions of ctx! // The manager will still run after that ( i.e. keep database // connection open if (manager instanceof Lifecycle) { try { ((Lifecycle) manager).stop(); catch ( L ifecycleexception e) { throw new IllegalStateException ( "" + e); / Used by context to configure the session manager's inactivity timeout. The S essionmanager may have some default session time out, the Context on the other hand has it's timeout set by the deployment descriptor ( w eb.xml). This method lets the Context conforgure the session manager according to this minutes The session inactivity timeout in minutes. / public void setsessiontimeout(int minutes) { if(-1!= minutes) { // The manager works with seconds... manager.setmaxinactiveinterval(minutes 60); ServerSessionManager package org.apache.tomcat.session; import org.apache.tomcat.util.; import org.apache.tomcat.core.; import java.io.; import java.net.; import java.util.; import j avax. s ervlet.http.; James Duncan Davidson Jason Hunter [ j James Todd [gonzo@eng.sun.com] / public class S erversessionmanager implements S essionmanager { private StringManager sm = StringManager. getmanager("org.apache.tomcat.session"); private static S erversessionmanager manager; // = new ServerSessionManager(); protected int inactiveinterval = -1; static { manager = new ServerSessionManager(); public static ServerSessionManager getmanager ( ) { return manager; private Hashtable sessions = new H ashtable(); private Reaper reaper; private ServerSessionManager() { reaper = Reaper.getReaper ( ); reaper. s etserversessionmanager(this); reaper.start(); public void accessed( Context ctx, Request r eq, String id ) { ApplicationSession aps=(applicationsession) f indsession( ctx, id); if( aps = =null) return; ServerSession servs = aps.getserversession(); servs.accessed(); aps.accessed(); // cache it - no need to compute it again req.setsession( aps ); public H ttpsession c reatesession(context c tx) { String s essionid = S essionidgenerator.generateid(); ServerSession session = new ServerSession(sessionId ); sessions.put(sessionid, session); if(-1!= i nactiveinterval ) { session.setmaxinactiveinterval(inactiveinterval ); return s ession.getapplicationsession( ctx, true ); public H ttpsession f indsession(context c tx, String id) { ServerSession ssession=(serversession)sessions.get(id ); if(ssession = =null) return null; return s Session.getApplicationSession(ctx, false); // XXX // s ync'd for safty -- no other thread should be getting something // from this while we are reaping. This isn't the most optimal // solution for this, but we'll determine something else later. synchronized void reap() { Enumeration enum = sessions.keys(); while ( e num. hasmoreelements ( )) { Object key = e num. nextelement ( ); ServerSession session = ( S erversession)sessions.get(key); session.reap(); session.validate(); synchronized void removesession ( ServerSession session) { String id = session.getid ( ); session.invalidate(); sessions.remove(id); public void removesessions(context context) { Enumeration enum = sessions.keys(); while ( e num.hasmoreelements ( )) { Object key = e num.nextelement ( ); ServerSession session = ( S erversession)sessions.get(key ); ApplicationSession a ppsession = session.getapplicationsession(context, false); if (appsession!= null) { appsession.invalidate ( ); / Used by context to configure the session manager's inactivity timeout. The S essionmanager may have some default session time out, the Context on the other hand has it's timeout set by the deployment descriptor ( w eb.xml). This method lets the Context conforgure the session manager according to this minutes The session inactivity timeout in minutes. / public void setsessiontimeout(int minutes) { if(-1!= minutes) { // The manager works with seconds... inactiveinterval = (minutes 60); SessionInterceptor package org.apache.tomcat.request; import org.apache.tomcat.core.; import org.apache.tomcat.util.; import java.io.; import java.net.; import java.util.; import j avax. s ervlet.http.; / Will process the request and determine the session Id, and set it in the Request. It also marks the session as accessed. This implementation only handles Cookies sessions, please extend or add new interceptors for other methods. / public class S essioninterceptor extends B aseinterceptor i mplements RequestInterceptor { // GS, separates the session id from the j vm r oute static final char SESSIONID_ROUTE_SEP = '.'; int debug=0; ContextManager cm; public S essioninterceptor ( ) { public void setdebug( int i ) { System.out.println("Set debug to " + i); debug=i; public void setcontextmanager ( C ontextmanager cm ) { this.cm=cm; public i nt r equestmap(request request ) { String s essionid = null; Cookie cookies[]= r equest.getcookies ( ); // assert!=null for( i nt i=0; i<cookies.length; i++ ) { Cookie cookie = cookies[i]; if (cookie.getname().equals("jsessionid " )) { sessionid = cookie.getvalue ( ); sessionid = validatesessionid(request, s essionid); if (sessionid! =null){ request.setrequestedsessionidfromcookie(true); String s ig="; j sessionid = "; int foundat = -1; if( debug>0 ) cm.log(" XXX RURI=" + request.getrequesturi ( )); if (( f oundat= r equest.getrequesturi().indexof(sig))!=-1){ sessionid = request.getrequesturi().substring(foundat+sig.length()); // rewrite URL, do I need to do anything more? request.setrequesturi(request.getrequesturi().substring(0, f oundat)); sessionid = validatesessionid(request, s essionid); if (sessionid! =null){ request.setrequestedsessionidfromurl(true ); return 0; // XXX what is the correct behavior if the session is invalid? // We may still set it and just return session invalid. / Validate and fix the session id. If the session is not valid return null. It will also clean up the session from load-balancing s essionid, or null if not valid / private String v alidatesessionid(request request, String s essionid){ // GS, We piggyback the JVM id on top of the session cookie // Separate them... if( debug>0 ) cm.log(" O rig sessionid " + s essionid ); if (null!= sessionid ) { int idex = s essionid.lastindexof(sessionid_route_sep); if(idex > 0) { sessionid = sessionid.substring(0, i dex ); if (sessionid!= null && s essionid.length ( )!=0) { // GS, We are in a problem here, we may actually get // multiple Session cookies (one for the root // context and one for the real context... or old session // cookie. We must check for validity in the current context. Context ctx = request.getcontext(); SessionManager sm = ctx.getsessionmanager ( ); if(null!= s M.findSession(ctx, s essionid)) { sm.accessed(ctx, request, sessionid ); request.setrequestedsessionid(sessionid ); if( debug>0 ) cm.log(" Final session id " + sessionid ); return s essionid; return null; public i nt beforebody ( Request r request, Response response ) { String r eqsessionid = response. g etsessionid ( ); if( debug>0 ) cm.log("before Body " + reqsessionid ); if( reqsessionid==null) return 0; // GS, set the path attribute to the cookie. This way // multiple session cookies can be used, one for each // context. String s essionpath = r request. getcontext(). g etpath(); if( s essionpath.length() == 0) { sessionpath = "/"; // GS, piggyback the j vm r oute on the session id. if(!sessionpath.equals("/")) { String j vmroute = rrequest.getjvmroute(); if(null!= j vmroute ) { reqsessionid = r eqsessionid + SESSIONID_ROUTE_SEP + jvmroute; Cookie cookie = new Cookie("JSESSIONID", r eqsessionid ); cookie.setmaxage(-1); cookie.setpath(sessionpath); cookie.setversion(1); response.addheader( CookieTools.getCookieHeaderName(cookie), CookieTools.getCookieHeaderValue(cookie ) ); cookie.setversion(0); response.addheader( CookieTools.getCookieHeaderName(cookie), CookieTools.getCookieHeaderValue(cookie ) ); return 0; / Notification of context shutdown / public void contextshutdown ( Context c tx ) throws T omcatexception { if( ctx.getdebug() > 0 ) c tx.log("removing sessions from " + c tx ); ctx.getsessionmanager().removesessions(ctx); ServerSession package org.apache.tomcat.session; import org.apache.tomcat.core.; import org.apache.tomcat. u til. StringManager ; import java.io.; import java.net.; import java.util.; import j avax. s ervlet.; import j avax. s ervlet.http.; / Core implementation of a server James Duncan Davidson James Todd [gonzo@eng.sun.com] / public class S erversession { private StringManager sm = StringManager. getmanager("org.apache.tomcat.session"); private Hashtable values = new H ashtable(); private Hashtable appsessions = new Hashtable ( ); private String id; private long c reationtime = System.currentTimeMillis();; private long t hisaccesstime = creationtime; private long l astaccessed = creationtime; private int inactiveinterval = -1; ServerSession(String id) { this.id = id; public String getid ( ) { return id; public long getcreationtime ( ) { return c reationtime ; public long getlastaccessedtime ( ) { return l astaccessed ; public A pplicationsession getapplicationsession(context context, boolean create) { ApplicationSession a ppsession = ( A pplicationsession)appsessions.get(context ); if (appsession == null && create) { // XXX // sync to ensure valid? appsession = new A pplicationsession(id, this, context); appsessions.put(context, a ppsession ); // XXX // make sure that we haven't gone over the end of our // inactive interval -- if so, invalidate and create // a new a ppsession return a ppsession ; void r emoveapplicationsession(context context) { appsessions.remove(context); / Called by context when request comes in so that accesses and i nactivities can be dealt with accordingly. / void accessed() { // set last accessed to thisaccesstime as it will be left over // from the previous access lastaccessed = t hisaccesstime ; thisaccesstime = S ystem.currenttimemillis ( ); void validate() void validate() { // if we have an inactive interval, check to see if // we've exceeded it if (inactiveinterval! = -1) { int thisinterval = ( i nt)(system. c urrenttimemillis() - l astaccessed ) / 1000; if (thisinterval > i nactiveinterval ) { invalidate(); ServerSessionManager ssm = ServerSessionManager. g etmanager ( ); ssm. removesession ( this); synchronized void invalidate() { Enumeration enum = a ppsessions.keys(); while ( e num. hasmoreelements ( )) { Object key = e num. nextelement ( ); ApplicationSession appsession = ( A pplicationsession ) appsessions. get(key); appsession.invalidate(); public void putvalue(string name, Object value) { if (name == null) { String m sg = sm. getstring ("s erversession.value. i ae"); throw new IllegalArgumentException( m sg); removevalue ( name); // remove any existing binding values.put(name, value); public Object getvalue(string name) { if (name == null) { String m sg = s m.getstring("serversession.value.iae"); throw new IllegalArgumentException(msg); return values.get(name); public Enumeration g etvaluenames() { return values.keys(); public void removevalue(string name) { values.remove(name); public void setmaxinactiveinterval(int interval) { inactiveinterval = interval; public i nt g etmaxinactiveinterval ( ) { return i nactiveinterval ; // XXX // s ync'd for safty -- no other thread should be getting something // from this while we are reaping. This isn't the most optimal // solution for this, but we'll determine something else later. synchronized void reap() { Enumeration enum = a ppsessions.keys ( ); while ( e num.hasmoreelements ( )) { Object key = e num.nextelement ( ); ApplicationSession a ppsession = ( A pplicationsession)appsessions.get(key ); appsession.validate ( ); SEG Topic 6 - Aspect Oriented Programming 9 Problems with lack of modularity in crosscutting concerns Redundant code Many little bits that do the same thing all over the place Difficulty understanding code What do all those little bits do? Difficult to change code You have to change many places consistently Easy to break code (introduce bugs) By forgetting to change something By making changes inconsistently SEG Topic 6 - Aspect Oriented Programming 10 Concepts in an Aspect/J aspect Aspect A new modular unit of code that imlements the designtime aspect Pointcuts These specify the join points Advice Instructions about what to do at join points picked out by a pointcut SEG Topic 6 - Aspect Oriented Programming 11 Figure Editor example operations that move elements factory methods Display 2 Point getx() gety() setx(int) sety(int) moveby(int, int) Line getp1() getp2() setp1(point) setp2(point) moveby(int, int) Figure makepoint(..) makeline(..) FigureElement moveby(int, int) SEG Topic 6 - Aspect Oriented Programming 12 Challenge: Update the display whenever any FigureElement changes Traditional approach Inform the display subsystem to update the screen By inserting a call to display after every possible line of code that changes the way a shape looks Aspect-Oriented approach Create an aspect that automatically performs the updating in the right places Every time you compile the code, you run a the aspect weaver edits the code to add the aspect code in the right places

Object-Oriented Software Engineering Practical Software Development using UML and Java

Object-Oriented Software Engineering Practical Software Development using UML and Java Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 5: Modelling with Classes Lecture 5 5.1 What is UML? The Unified Modelling Language is a standard graphical

More information

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 5: Modelling with Classes

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 5: Modelling with Classes Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 5: Modelling with Classes 5.1 What is UML? The Unified Modelling Language is a standard graphical language

More information

Rubby Casallas Grupo de Construcción de Software Uniandes

Rubby Casallas Grupo de Construcción de Software Uniandes UML OCL 2.0 Rubby Casallas Grupo de Construcción de Software Uniandes Why OCL? A UML diagram, such as a class diagram, is typically not refined enough to provide all the relevant aspects of a specification.

More information

Modelling with Classes. CITS1220 Software Engineering

Modelling with Classes. CITS1220 Software Engineering Modelling with Classes CITS1220 Software Engineering Lecture Overview Classes and UML Associations between classes Special types of association: is-a, has-a, is-part-of Modelling Example Implementing associations

More information

Metamodeling. Janos Sztipanovits ISIS, Vanderbilt University

Metamodeling. Janos Sztipanovits ISIS, Vanderbilt University Metamodeling Janos ISIS, Vanderbilt University janos.sztipanovits@vanderbilt.edusztipanovits@vanderbilt edu Content Overview of Metamodeling Abstract Syntax Metamodeling Concepts Metamodeling languages

More information

Design Engineering. Dr. Marouane Kessentini Department of Computer Science

Design Engineering. Dr. Marouane Kessentini Department of Computer Science Design Engineering Dr. Marouane Kessentini Department of Computer Science 1 Design Starts mostly from/with requirements (evolving mostly from functionalities and other non functional characteristics) How

More information

8.1 Interaction Diagrams. Object-Oriented Software Engineering Practical Software Development using UML and Java. Interactions and messages

8.1 Interaction Diagrams. Object-Oriented Software Engineering Practical Software Development using UML and Java. Interactions and messages 8.1 Interaction Diagrams Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 8: Modelling Interactions and Behaviour Interaction diagrams are used to model the

More information

Object Constraint Language Specification 7

Object Constraint Language Specification 7 Object Constraint Language Specification 7 This chapter introduces and defines the Object Constraint Language (OCL), a formal language used to express constraints. Users of the Unified Modeling Language

More information

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 5: Modelling with Classes

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 5: Modelling with Classes Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 5: Modelling with Classes 5.1 What is UML? The Unified Modelling Language is a standard graphical language

More information

A - 1. CS 494 Object-Oriented Analysis & Design. UML Class Models. Overview. Class Model Perspectives (cont d) Developing Class Models

A - 1. CS 494 Object-Oriented Analysis & Design. UML Class Models. Overview. Class Model Perspectives (cont d) Developing Class Models CS 494 Object-Oriented Analysis & Design UML Class Models Overview How class models are used? Perspectives Classes: attributes and operations Associations Multiplicity Generalization and Inheritance Aggregation

More information

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation Object-Oriented Software Engineering Chapter 2: Review of Object Orientation 2.1 What is Object Orientation? Procedural paradigm: Software is organized around the notion of procedures Procedural abstraction

More information

UML Metamodel version September 1997

UML Metamodel version September 1997 UML Metamodel version. September 997 This is the metamodel of the Unified Modeling Language (UML). It describes the constituents of all well-formed models that may be represented in the UML, using the

More information

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 2: Review of Object Orientation

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 2: Review of Object Orientation Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 2: Review of Object Orientation 2.1 What is Object Orientation? Procedural paradigm: Software is organized

More information

Object Constraint https://www.lri.fr/~linaye/gl.html lina.ye@centralesupelec.fr Sequence 3, 2017-2018 1/45 Plan 1 2 3 4 2/45 Motivation Why OCL Cannot represent all the relevant aspects of a specification

More information

UML Semantics 2. Contents. Section Title. This chapter contains the following sections.

UML Semantics 2. Contents. Section Title. This chapter contains the following sections. UML Semantics 2 Contents This chapter contains the following sections. Section Title Page Part 1 - Background Introduction 2-2 Language Architecture 2-4 Language Formalism 2-7 Part 2 - Foundation Foundation

More information

Introduction to Software Engineering. 5. Modeling Objects and Classes

Introduction to Software Engineering. 5. Modeling Objects and Classes Introduction to Software Engineering 5. Modeling Objects and Classes Roadmap > UML Overview > Classes, attributes and operations > UML Lines and Arrows > Parameterized Classes, Interfaces and Utilities

More information

Software Engineering: A Practitioner s s Approach, 6/e Roger Pressman. Chapter 28 Formal Methods

Software Engineering: A Practitioner s s Approach, 6/e Roger Pressman. Chapter 28 Formal Methods Software Engineering: A Practitioner s s Approach, 6/e Roger Pressman Chapter 28 Formal Methods 1 Problems with Conventional Specification contradictions ambiguities vagueness incompleteness mixed levels

More information

UNIT-II Introduction to UML

UNIT-II Introduction to UML UNIT-II Introduction to UML - P. P. Mahale UML OVERVIEW OF UML :- We need a Modeling Language! We will use the Unified Modeling Language, UML), Provides a standard for artifacts produced during development

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecture 14: Design Workflow Department of Computer Engineering Sharif University of Technology 1 UP iterations and workflow Workflows Requirements Analysis Phases Inception Elaboration

More information

OMG Modeling Glossary B

OMG Modeling Glossary B OMG Modeling Glossary B This glossary defines the terms that are used to describe the Unified Modeling Language (UML) and the Meta Object Facility (MOF). In addition to UML and MOF specific terminology,

More information

Class diagrams. Modeling with UML Chapter 2, part 2. Class Diagrams: details. Class diagram for a simple watch

Class diagrams. Modeling with UML Chapter 2, part 2. Class Diagrams: details. Class diagram for a simple watch Class diagrams Modeling with UML Chapter 2, part 2 CS 4354 Summer II 2015 Jill Seaman Used to describe the internal structure of the system. Also used to describe the application domain. They describe

More information

UML Fundamental. OutLine. NetFusion Tech. Co., Ltd. Jack Lee. Use-case diagram Class diagram Sequence diagram

UML Fundamental. OutLine. NetFusion Tech. Co., Ltd. Jack Lee. Use-case diagram Class diagram Sequence diagram UML Fundamental NetFusion Tech. Co., Ltd. Jack Lee 2008/4/7 1 Use-case diagram Class diagram Sequence diagram OutLine Communication diagram State machine Activity diagram 2 1 What is UML? Unified Modeling

More information

NOTES ON OBJECT-ORIENTED MODELING AND DESIGN

NOTES ON OBJECT-ORIENTED MODELING AND DESIGN NOTES ON OBJECT-ORIENTED MODELING AND DESIGN Stephen W. Clyde Brigham Young University Provo, UT 86402 Abstract: A review of the Object Modeling Technique (OMT) is presented. OMT is an object-oriented

More information

Ingegneria del Software Corso di Laurea in Informatica per il Management. Introduction to UML

Ingegneria del Software Corso di Laurea in Informatica per il Management. Introduction to UML Ingegneria del Software Corso di Laurea in Informatica per il Management Introduction to UML Davide Rossi Dipartimento di Informatica Università di Bologna Modeling A model is an (abstract) representation

More information

Index. business modeling syntax 181 business process modeling 57 business rule 40

Index. business modeling syntax 181 business process modeling 57 business rule 40 OCL.book Page 203 Tuesday, July 22, 2003 9:48 PM Index Symbols OclAny, of 167 = OclAny, of 167 @pre 34, 86, 155 ^ 34, 156 ^^ 157 A abstract syntax 93 accumulator 153 action in statechart 56 activity

More information

7 OCL Language Description

7 OCL Language Description 7 OCL Language Description This chapter introduces the Object Constraint Language (OCL), a formal language used to describe expressions on UML models. These expressions typically specify invariant conditions

More information

Metamodeling with Metamodels. Using. UML/MOF including OCL

Metamodeling with Metamodels. Using. UML/MOF including OCL Metamodeling with Metamodels Using UML/MOF including OCL Introducing Metamodels (Wikipedia) A metamodel is a model of a model An instantiation of metamodel gives a model Metamodeling is the process of

More information

UNIT II. Syllabus. a. An Overview of the UML: Visualizing, Specifying, Constructing, Documenting

UNIT II. Syllabus. a. An Overview of the UML: Visualizing, Specifying, Constructing, Documenting UNIT II Syllabus Introduction to UML (08 Hrs, 16 Marks) a. An Overview of the UML: Visualizing, Specifying, Constructing, Documenting b. Background, UML Basics c. Introducing UML 2.0 A Conceptual Model

More information

Unified Modeling Language 2

Unified Modeling Language 2 Unified Modeling Language 2 Profiles 166 Usage scenarios Metamodel customization for adapting terminology to a specific platform or domain adding (visual) notation adding and specializing semantics adding

More information

Introduction to Software Engineering. 5. Modeling Objects and Classes

Introduction to Software Engineering. 5. Modeling Objects and Classes Introduction to Software Engineering 5. Modeling Objects and Classes Roadmap > UML Overview > Classes, attributes and operations > UML Lines and Arrows > Parameterized Classes, Interfaces and Utilities

More information

UNIT I. 3. Write a short notes on process view of 4+1 architecture. 4. Why is object-oriented approach superior to procedural approach?

UNIT I. 3. Write a short notes on process view of 4+1 architecture. 4. Why is object-oriented approach superior to procedural approach? Department: Information Technology Questions Bank Class: B.E. (I.T) Prof. Bhujbal Dnyaneshwar K. Subject: Object Oriented Modeling & Design dnyanesh.bhujbal11@gmail.com ------------------------------------------------------------------------------------------------------------

More information

UML REFERENCE SHEETS. 2013, 2014 Michael Marking; all rights reserved, including moral rights. Web site:

UML REFERENCE SHEETS. 2013, 2014 Michael Marking; all rights reserved, including moral rights. Web site: UML Reference Sheets 2013, 2014 Michael Marking; all rights reserved, including moral rights. Web site: http://www.tatanka.com/ Revision Information This document was last revised 2014.03.02. The current

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

UML Modeling I. Instructor: Yongjie Zheng September 3, CS 490MT/5555 Software Methods and Tools

UML Modeling I. Instructor: Yongjie Zheng September 3, CS 490MT/5555 Software Methods and Tools UML Modeling I Instructor: Yongjie Zheng September 3, 2015 CS 490MT/5555 Software Methods and Tools Object-Oriented Design: Topics & Skills Rational Unified Process Unified Modeling Languages (UML) Provide

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

12 Tutorial on UML. TIMe TIMe Electronic Textbook

12 Tutorial on UML. TIMe TIMe Electronic Textbook TIMe TIMe Electronic Textbook 12 Tutorial on UML Introduction......................................................2.................................................3 Diagrams in UML..................................................3

More information

Object-Oriented and Classical Software Engineering

Object-Oriented and Classical Software Engineering Slide 16.1 Object-Oriented and Classical Software Engineering Seventh Edition, WCB/McGraw-Hill, 2007 Stephen R. Schach srs@vuse.vanderbilt.edu CHAPTER 16 Slide 16.2 MORE ON UML 1 Chapter Overview Slide

More information

Object Constraint Language Specification

Object Constraint Language Specification Object Constraint Language Specification version 1.1 1 September 1997 Rational Software Microsoft Hewlett-Packard Oracle Sterling Software MCI Systemhouse Unisys ICON Computing IntelliCorp i-logix IBM

More information

OO Analysis and Design with UML 2 and UP

OO Analysis and Design with UML 2 and UP OO Analysis and Design with UML 2 and UP Dr. Jim Arlow, Zuhlke Engineering Limited Clear View Training 2008 v2.5 1 UML principles Clear View Training 2008 v2.5 2 1.2 What is UML? Unified Modelling Language

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Ecma International Policy on Submission, Inclusion and Licensing of Software

Ecma International Policy on Submission, Inclusion and Licensing of Software Ecma International Policy on Submission, Inclusion and Licensing of Software Experimental TC39 Policy This Ecma International Policy on Submission, Inclusion and Licensing of Software ( Policy ) is being

More information

Basic Structural Modeling. Copyright Joey Paquet,

Basic Structural Modeling. Copyright Joey Paquet, Basic Structural Modeling Copyright Joey Paquet, 2000 1 Part I Classes Copyright Joey Paquet, 2000 2 Classes Description of a set of objects sharing the same attributes, operations and semantics Abstraction

More information

Architectural Models and Styles Component-Based Software Engineering ECE493-Topic 5 Winter 2007 Lecture 12 The Object Constraint Language (Part A)

Architectural Models and Styles Component-Based Software Engineering ECE493-Topic 5 Winter 2007 Lecture 12 The Object Constraint Language (Part A) Component-Based Software Engineering ECE493-Topic 5 Winter 2007 Lecture 12 The Object Constraint Language (Part A) Ladan Tahvildari Assistant Professor Dept. of Elect. & Comp. Eng. University of Waterloo

More information

Enterprise Architect. User Guide Series. UML Models. Author: Sparx Systems. Date: 30/06/2017. Version: 1.0 CREATED WITH

Enterprise Architect. User Guide Series. UML Models. Author: Sparx Systems. Date: 30/06/2017. Version: 1.0 CREATED WITH Enterprise Architect User Guide Series UML Models Author: Sparx Systems Date: 30/06/2017 Version: 1.0 CREATED WITH Table of Contents UML Models UML Diagrams UML Structural Models Class Diagram Composite

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

LABORATORY 1 REVISION

LABORATORY 1 REVISION UTCN Computer Science Department Software Design 2012/2013 LABORATORY 1 REVISION ================================================================== I. UML Revision This section focuses on reviewing the

More information

Object-Oriented Systems Development: Using the Unified Modeling Language

Object-Oriented Systems Development: Using the Unified Modeling Language Object-Oriented Systems Development: Using the Unified Modeling Language Chapter 5: Unified Modeling Language Goals Modeling. Unified modeling language. Class diagram. Use case diagram. Interaction diagrams.

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Lesson 11. W.C.Udwela Department of Mathematics & Computer Science

Lesson 11. W.C.Udwela Department of Mathematics & Computer Science Lesson 11 INTRODUCING UML W.C.Udwela Department of Mathematics & Computer Science Why we model? Central part of all the activities We build model to Communicate Visualize and control Better understand

More information

What is OCL? OCL/Context

What is OCL? OCL/Context What is? Software Engineering Lecture 5: Prof. Dr. Peter Thiemann Universität Freiburg SS 20 = object constraint language standard query language of UML 2 specify expressions and constraints in object-oriented

More information

Chapter 10. Object-Oriented Analysis and Modeling Using the UML. McGraw-Hill/Irwin

Chapter 10. Object-Oriented Analysis and Modeling Using the UML. McGraw-Hill/Irwin Chapter 10 Object-Oriented Analysis and Modeling Using the UML McGraw-Hill/Irwin Copyright 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Objectives 10-2 Define object modeling and explain

More information

UNIT 5 - UML STATE DIAGRAMS AND MODELING

UNIT 5 - UML STATE DIAGRAMS AND MODELING UNIT 5 - UML STATE DIAGRAMS AND MODELING UML state diagrams and modeling - Operation contracts- Mapping design to code UML deployment and component diagrams UML state diagrams: State diagrams are used

More information

Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects,

Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects, Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects, Classes, Class Diagrams Values and Attributes Operations

More information

Ecma International Policy on Submission, Inclusion and Licensing of Software

Ecma International Policy on Submission, Inclusion and Licensing of Software Ecma International Policy on Submission, Inclusion and Licensing of Software Experimental TC39 Policy This Ecma International Policy on Submission, Inclusion and Licensing of Software ( Policy ) is being

More information

administrivia today UML start design patterns Tuesday, September 28, 2010

administrivia today UML start design patterns Tuesday, September 28, 2010 administrivia Assignment 2? promise to get past assignment 1 back soon exam on monday review slides are posted your responsibility to review covers through last week today UML start design patterns 1 Unified

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING Wednesady 23 rd March 2016 Afternoon Answer any FOUR questions out of SIX. All

More information

For 100% Result Oriented IGNOU Coaching and Project Training Call CPD TM : ,

For 100% Result Oriented IGNOU Coaching and Project Training Call CPD TM : , Course Code : MCS-032 Course Title : Object Oriented Analysis and Design Assignment Number : MCA (3)/032/Assign/2014-15 Assignment Marks : 100 Weightage : 25% Last Dates for Submission : 15th October,

More information

Bar Code Discovery. Administrator's Guide

Bar Code Discovery. Administrator's Guide Bar Code Discovery Administrator's Guide November 2012 www.lexmark.com Contents 2 Contents Overview...3 Configuring the application...4 Configuring the application...4 Configuring Bar Code Discovery...4

More information

Appendix A - Glossary(of OO software term s)

Appendix A - Glossary(of OO software term s) Appendix A - Glossary(of OO software term s) Abstract Class A class that does not supply an implementation for its entire interface, and so consequently, cannot be instantiated. ActiveX Microsoft s component

More information

S T R U C T U R A L M O D E L I N G ( M O D E L I N G A S Y S T E M ' S L O G I C A L S T R U C T U R E U S I N G C L A S S E S A N D C L A S S D I A

S T R U C T U R A L M O D E L I N G ( M O D E L I N G A S Y S T E M ' S L O G I C A L S T R U C T U R E U S I N G C L A S S E S A N D C L A S S D I A S T R U C T U R A L M O D E L I N G ( M O D E L I N G A S Y S T E M ' S L O G I C A L S T R U C T U R E U S I N G C L A S S E S A N D C L A S S D I A G R A M S ) WHAT IS CLASS DIAGRAM? A class diagram

More information

INTERNAL ASSESSMENT TEST III Answer Schema

INTERNAL ASSESSMENT TEST III Answer Schema INTERNAL ASSESSMENT TEST III Answer Schema Subject& Code: Object-Oriented Modeling and Design (15CS551) Sem: V ISE (A & B) Q. No. Questions Marks 1. a. Ans Explain the steps or iterations involved in object

More information

Overview of Class Diagrams & Examples

Overview of Class Diagrams & Examples Overview of Class Diagrams & Examples 1 A class diagram is a static model of a system (mainly software, but can include other types of components. It shows the structure of the software in terms of the

More information

UmpleRun: a Dynamic Analysis Tool for Textually Modeled State Machines using Umple

UmpleRun: a Dynamic Analysis Tool for Textually Modeled State Machines using Umple UmpleRun: a Dynamic Analysis Tool for Textually Modeled State Machines using Umple Hamoud Aljamaan, Miguel Garzon, Timothy Lethbridge CRuiSE (Complexity Reduction in Software Engineering) Research Group

More information

Object-Oriented Analysis and Design. Pre-UML Situation. The Unified Modeling Language. Unification Efforts

Object-Oriented Analysis and Design. Pre-UML Situation. The Unified Modeling Language. Unification Efforts Object-Oriented Analysis and Design Analysis vs. Design Analysis Activities Finding the Objects/ Classes An Analysis Example The Unified Modeling Language Pre-UML Situation Early 90s Explosion of OO methods/notations

More information

Self-review Questions

Self-review Questions 7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance

More information

PRODUCT SPECIFIC LICENSE TERMS Sybase Enterprise Portal Version 5 Application Edition ( Program )

PRODUCT SPECIFIC LICENSE TERMS Sybase Enterprise Portal Version 5 Application Edition ( Program ) PRODUCT SPECIFIC LICENSE TERMS Sybase Enterprise Portal Version 5 Application Edition ( Program ) IN ADDITION TO THE LICENSE TERMS SET OUT IN THE SYBASE LICENSE AGREEMENT, THE FOLLOWING ADDITIONAL OR DIFFERENT

More information

Chapter 2: The Object-Oriented Design Process

Chapter 2: The Object-Oriented Design Process Chapter 2: The Object-Oriented Design Process In this chapter, we will learn the development of software based on object-oriented design methodology. Chapter Topics From Problem to Code The Object and

More information

Software Engineering

Software Engineering Software Engineering Lecture 15: OCL Peter Thiemann University of Freiburg, Germany 01.07.2013 Peter Thiemann (Univ. Freiburg) Software Engineering 01.07.2013 1 / 28 What is OCL? OCL = Object Constraint

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT Object Oriented Programming Examiner s Report March 2017 A1. a) Explain what is meant by the following terms:

More information

OCL Support in MOF Repositories

OCL Support in MOF Repositories OCL Support in MOF Repositories Joachim Hoessler, Michael Soden Department of Computer Science Technical University Berlin hoessler@cs.tu-berlin.de, soden@cs.tu-berlin.de Abstract From metamodels that

More information

RECODER - The Architecture of a Refactoring System

RECODER - The Architecture of a Refactoring System RECODER - The Architecture of a Refactoring System Andreas Ludwig Prof. U. Aßmann http://recoder.sf.net Overview ➊Programming in the Large Problems, Concepts, The Approach ➋The Architecture of RECODER

More information

OCL parsing / type checking in the context of GF and KeY. Kristofer Johannisson

OCL parsing / type checking in the context of GF and KeY. Kristofer Johannisson OCL parsing / type checking in the context of GF and KeY Kristofer Johannisson 1 I. Introduction 2 Typechecking? context OwnerPIN inv: maxpinsize > 0 and maxtries > 0 and triesremaining >= 0 and triesremaining

More information

Oral Questions. Unit-1 Concepts. Oral Question/Assignment/Gate Question with Answer

Oral Questions. Unit-1 Concepts. Oral Question/Assignment/Gate Question with Answer Unit-1 Concepts Oral Question/Assignment/Gate Question with Answer The Meta-Object Facility (MOF) is an Object Management Group (OMG) standard for model-driven engineering Object Management Group (OMG)

More information

UML PROFILING AND DSL

UML PROFILING AND DSL UML PROFILING AND DSL version 17.0.1 user guide No Magic, Inc. 2011 All material contained herein is considered proprietary information owned by No Magic, Inc. and is not to be shared, copied, or reproduced

More information

Chapter 6: Entity-Relationship Model. The Next Step: Designing DB Schema. Identifying Entities and their Attributes. The E-R Model.

Chapter 6: Entity-Relationship Model. The Next Step: Designing DB Schema. Identifying Entities and their Attributes. The E-R Model. Chapter 6: Entity-Relationship Model The Next Step: Designing DB Schema Our Story So Far: Relational Tables Databases are structured collections of organized data The Relational model is the most common

More information

Credit where Credit is Due. Lecture 4: Fundamentals of Object Technology. Goals for this Lecture. Real-World Objects

Credit where Credit is Due. Lecture 4: Fundamentals of Object Technology. Goals for this Lecture. Real-World Objects Lecture 4: Fundamentals of Object Technology Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2003 Credit where Credit is Due Some material presented in this lecture

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

UML 2.0 State Machines

UML 2.0 State Machines UML 2.0 State Machines Frederic.Mallet@unice.fr Université Nice Sophia Antipolis M1 Formalisms for the functional and temporal analysis With R. de Simone Objectives UML, OMG and MDA Main diagrams in UML

More information

Hans Karlsen. MDriven The book. Doing effective Business by taking control of Information. Hans Karlsen, Stockholm, Sweden

Hans Karlsen. MDriven The book. Doing effective Business by taking control of Information. Hans Karlsen, Stockholm, Sweden Hans Karlsen MDriven The book Doing effective Business by taking control of Information Hans Karlsen, Stockholm, Sweden 2016-01-23 Part 8 Object Constraint Language 1 What is Object Constraint Language

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecturer: Raman Ramsin Lecture 10: Analysis Packages 1 Analysis Workflow: Packages The analysis workflow consists of the following activities: Architectural analysis Analyze a use

More information

Specification-based Testing of Embedded Systems H. Schlingloff, SEFM 2008

Specification-based Testing of Embedded Systems H. Schlingloff, SEFM 2008 SEFM School 2008 Specification-based Testing of Embedded Systems Prof. Dr. Holger Schlingloff Humboldt-Universität zu Berlin and Fraunhofer FIRST, Berlin Lecture 4: Mutations, OCL etc. Course Outline L1:

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Chapter 12 Outline Overview of Object Database Concepts Object-Relational Features Object Database Extensions to SQL ODMG Object Model and the Object Definition Language ODL Object Database Conceptual

More information

SLIDES: Introductory Modeling Example Employing UML and OCL [UML: Unified Modeling Language, OCL:Object Constarint Language]

SLIDES: Introductory Modeling Example Employing UML and OCL [UML: Unified Modeling Language, OCL:Object Constarint Language] Lecture day 2016-04-07 SLIDES: Introductory Modeling Example Employing UML and OCL [UML: Unified Modeling Language, OCL:Object Constarint Language] - System design in an object-oriented way employing USE

More information

Agenda. More on the Unified Modeling Language. UML diagram types. Packages

Agenda. More on the Unified Modeling Language. UML diagram types. Packages Agenda More on the Unified Modeling Language Perdita Stevens, University of Edinburgh July 2010 And the rest... deployment diagrams, component diagrams, object diagrams, timing diagrams, etc. OCL and alternatives

More information

UML 2.0 UML 2.0. Scott Uk-Jin Lee. Division of Computer Science, College of Computing Hanyang University ERICA Campus

UML 2.0 UML 2.0. Scott Uk-Jin Lee. Division of Computer Science, College of Computing Hanyang University ERICA Campus UML 2.0 Division of Computer Science, College of Computing Hanyang University ERICA Campus Introduction to UML 2.0 UML Unified Modeling Language Visual language for specifying, constructing and documenting

More information

Topics in Object-Oriented Design Patterns

Topics in Object-Oriented Design Patterns Software design Topics in Object-Oriented Design Patterns Material mainly from the book Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides; slides originally by Spiros Mancoridis;

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

The Next Step: Designing DB Schema. Chapter 6: Entity-Relationship Model. The E-R Model. Identifying Entities and their Attributes.

The Next Step: Designing DB Schema. Chapter 6: Entity-Relationship Model. The E-R Model. Identifying Entities and their Attributes. Chapter 6: Entity-Relationship Model Our Story So Far: Relational Tables Databases are structured collections of organized data The Relational model is the most common data organization model The Relational

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

PRODUCT SPECIFIC LICENSE TERMS Sybase Enterprise Portal Version 5 Enterprise Edition ( Program )

PRODUCT SPECIFIC LICENSE TERMS Sybase Enterprise Portal Version 5 Enterprise Edition ( Program ) PRODUCT SPECIFIC LICENSE TERMS Sybase Enterprise Portal Version 5 Enterprise Edition ( Program ) IN ADDITION TO THE LICENSE TERMS SET OUT IN THE SYBASE LICENSE AGREEMENT, THE FOLLOWING ADDITIONAL OR DIFFERENT

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Business Rules NextAge Consulting Pete Halsted

Business Rules NextAge Consulting Pete Halsted Business Rules NextAge Consulting Pete Halsted 110 East Center St. #1035 Madison, SD 57042 pete@thenextage.com www.thenextage.com www.thenextage.com/wordpress Table of Contents Table of Contents BSD 3

More information

OCL 2.0 Specification Version 2.0

OCL 2.0 Specification Version 2.0 Date: June 2005 OCL 2.0 Specification Version 2.0 ptc/2005-06-06 UML OCL2 Specification Copyright 200-2003 Adaptive Ltd. Copyright 200-2003 Boldsoft Copyright 200-2003 France Telecom Copyright 200-2003

More information

Software Service Engineering

Software Service Engineering Software Service Engineering Lecture 4: Unified Modeling Language Doctor Guangyu Gao Some contents and notes selected from Fowler, M. UML Distilled, 3rd edition. Addison-Wesley Unified Modeling Language

More information

Element. ModelElement. GeneralizableElement isroot : Boolean isleaf : Boolean isabstract : Boolean. +type. Method body : ProcedureExpression

Element. ModelElement. GeneralizableElement isroot : Boolean isleaf : Boolean isabstract : Boolean. +type. Method body : ProcedureExpression Element name : Name +constrainedelement.. ElementOwnership visibility : VisibilityKind +ownedelement +stereotypeconstraint Feature ownerscope : ScopeKind visibility : VisibilityKind +feature +namespace

More information