COMP434/534B Software Design Component-based software architectures Course Structure Two six week modules First term (me) Introduction to Sun s JavaBeans framework One two hour lecture per week for the whole class (Tue 9-11am KG.09) One one hour meeting per week with part 5 students (Wed 4-5pm KG.06) Lab (for first term) - GB13 (Linux) Second term (Mark Utting) TBA First term Gain experience with programming and using JavaBeans components Assignment I (25%) - design and program some JavaBeans Test (25%) Part 5 students do an extra assignment (25%) Web page: www.cs.waikato.ac.nz/~mhall/434 Components Characteristic properties of components (from Component Software by Clemens Szyperski): A component is a unit of independent deployment Well separated from its environment Encapsulates its constituent features A component is a unit of third-party composition To be composed with other (possibly third-party) components, it needs to be sufficiently self contained Clear specs of what it requires and provides It is never partially deployed Components Components Characteristics of objects: An object is a unit of instantiation; it has a unique identity An object has state (which can be persistent) An object encapsulates its state and behaviour A class provides a construction plan that describes the state space, initial state and behaviour of a new object A component is likely to come to life through objects Therefore a component would normally consist of one or more classes Good components demand a commitment to interfaces Blackbox reuse reuse of implementation without relying on anything but interfaces and specifications A definition: software component A software component is a unit of composition with contractually specified interfaces and explicit context dependencies only. A software component can be deployed independently and is subject to composition by third parties. -Formulated at the 1996 European Conference on Object- Oriented Programming Explicit context dependencies Specification of what the component needs from the deployment environment 1
What is a JavaBean? Properties, Events and Methods JavaBeans components are self-contained, reusable software units Can be visually composed into composite components, applets, applications etc. using visual application builder tools JavaBeans spec prescribes programming conventions and dynamic discovery mechanisms that: Minimize design and implementation effort for small software components Support the design, implementation and assembly of sophisticated components Properties, Events and Methods are fundamental to understanding and using JavaBeans components Property is a subset of a component s state You may change the behaviour or appearance of a component by modifying its properties (eg. Title, label, position, scale etc) Event Is a notification generated by a component when there is some change in its state (eg. Quote bean monitors real-time info from stock exchange and generates events when the price of a stock changes) Methods Can be invoked to execute code in a component (eg. Graph bean has a method that can be invoked to add a new data point to the display) Introspection and Builder Tools Builder tools interrogate beans to discover info about properties, events and methods Introspection - the mechanism or process of discovering an object s characteristics java.lang.reflect provides general mechanisms for low-level examination of objects Can dynamically determine (and potentially invoke) an objects methods java.beans.introspector can be used by a builder tool or IDE to discover a bean s configurable characteristics and allow their modification at design time What s the difference between a Bean and any other Class? Any Java class that adheres to certain conventions regarding property and event interface definitions can be a JavaBean Every Bean requires a zero argument constructor. Builder tools need to be able to instantiate a bean in the absence of knowledge of its properties Beans do not have any public member variables Beans provide access methods so that its properties may be read and written Beans must provide support for introspection Beans publish their attributes and behaviours by adhering to introspection naming conventions JavaBeans API JavaBeans Design Issues The JavaBeans API includes several interfaces and classes in the java.beans package; plus some interfaces and classes from other Java API areas including: The Java event model: java.util.eventobject, java.util.eventlistener, java.awt.event Object serialization (object persistence): java.io.serializable, java.io.object* Reflection: java.lang.reflect Beans are like other user-defined data types, but with the following additional features that make them amenable to runtime composition: No args constructor Implementing java.io.serializable Enables IDE/builder tool to save a bean as part of a project Following JavaBeans design conventions Set/get methods for properties Add/Remove methods for events Being thread safe Java is multithreaded. Screen-updating threads asynchronously invoke a Bean s rendering method (paint()), which is typically dependent on certain state variables, which in turn can be user modifiable 2
The BeanBuilder Starting the BeanBuilder Tool available free from Sun s JavaSoft site (http://java.sun.com/products/javabeans/beanbuilder/) Allows you to configure and interconnect a set of Beans Change the properties of a Bean Link two or more Beans Watch beans execute Comes with a palette of Swing UI components Can load and use arbitrary Beans Useful for testing your own Beans Getting the BeanBuilder Download from: http://www.cs.waikato.ac.nz/~mhall/434/bbuilder-0_6- alpha.zip Or, from Sun s web site if you prefer Unpack the archive jar xvf bbuilder-0_6-alpha.zip (unpacks to a directory called beanbuilder-0_6-alpha ) To start the BeanBuilder Set up your Java environment as per the instructions on the assignment handout cd beanbuilder-0_6-alpha ant Benefits of Java Components Benefits of Java Components Write once, run anywhere paradigm A set of Beans, supporting classes and associated resources can be packaged into a Java Archive (JAR) file Provides a convenient mechanism to deliver software components to users Beans can be manipulated and connected at design time as binary executables Bean developer can explicitly control the properties, events, and methods that are presented via a builder tool helps the user focus on the essential features of the component and not be distracted or confused by other capabilities Developers can make use of existing ranges of off the shelf components Promotes reuse and interoperability Property editors and customizers can be provided for users Help the user configure a complex component A component can be designed so that it operates correctly in different locales Makes a Bean usable by an international audience A Bean can be written that provides access to legacy code Build apps that combine functionality written in Java with existing systems 3
A Simple Bean (Spectrum.java) Simple component that displays a square 100 pixels wide and 100 pixels high and fills it with the colours of the spectrum One boolean property named vertical If set to true, the colours are arranged in a vertical direction, otherwise the colours are arranged in a horizontal direction Packaged as spectrum.spectrum Create a directory called spectrum and place the source file Spectrum.java in it A Simple Bean (Spectrum) package spectrum; import java.awt.*; import javax.swing.jpanel; public class Spectrum extends JPanel { private boolean vertical; public Spectrum() { vertical = true; Dimension d = new Dimension(50,50); setminimumsize(d); setpreferredsize(d); setmaximumsize(d); public boolean getvertical() { return vertical; public void setvertical(boolean vertical) { this.vertical = vertical; repaint();... Spectrum continued public void paint(graphics g) { float saturation = 1.0f; float brightness = 1.0f; Dimension d = getsize(); if(vertical) { for(int y = 0; y < d.height; y++) { float hue = (float)y/(d.height - 1); g.setcolor(color.gethsbcolor(hue, saturation, brightness)) g.drawline(0, y, d.width - 1, y); else { for(int x = 0; x < d.width; x++) { float hue = (float)x/(d.width - 1); g.setcolor(color.gethsbcolor(hue, saturation, brightness)); g.drawline(x, 0, x, d.height - 1); Spectrum continued Compile the source code cd to the parent directory of spectrum and type: javac spectrum/spectrum.java Check that the.class file has been created in the spectrum directory Create a manifest template file All beans must be specified in a manifest template file Forms the basis of a manifest file, which is the first element in a JAR file and describes its contents Indicates that the Spectrum.class is a Bean Name the file spectrum.mft and place it in the spectrum directory: Name: spectrum/spectrum.class Java-Bean: True Create a JAR file Spectrum continued Most builder tools import Beans that are stored in JAR files Create the JAR file with the following command: jar cfm spectrum.jar spectrum/spectrum.mft spectrum/*.class Start the BeanBuilder Load the spectrum.jar into the BeanBuilder using the Load jar File option under the File menu The JAR Utility The jar utility provided with the JDK (java development kit) allows you to create and manage JAR files Syntax: jar options files Option: c - create an archive f - the first element in files is the name of the archive to be created/extracted m - the second element in files is the name of the manifest file t - tabulate the contents of the archive v - provide verbose output x - extract files from an archive O - do not use compression M - do not create a manifest file 4
Introspection Naming Conventions The BeanBuilder and other builder tools/ides use introspection to determine the properties of a Bean This relies on rules for naming methods that read and write properties Simple properties Contain one value that may be either a simple type or an object public T getn() public void setn(t value) Eg: public void setsize(int newsize) public int getsize() Introspection Naming Conventions Boolean properties A boolean property contains one value that may be either true or false public boolean isn() public boolean getn() public void setn(boolean value) Introspection Naming Conventions Indexed properties Contains several values that may either be simple types or objects public T getn(int index) public T [] getn() public void setn(int index, T value) public void setn(t[] values) Note: the Properties window of the BeanBuilder does not handle indexed properties (we will see how to use custom property editors or customizers for this later) Assignment I (25%) Aim: explore the basics of Java component programming Due: Friday, 25th August (end of the first week of the teaching recess) Develop some JavaBeans that could be used to build an application for accessing and monitoring currency exchange data Can use the BeanBuilder to test connecting and configuring your beans. Minimum requirements: Assignment I A CurrencyExchange Bean represent the source of currency exchange data Read exchange values from a file and make them available to listeners A QuoteProducer Bean listen to data from the currency exchange and pass on values pertaining to a particular currency Will also allow a threshold to be set on the change in value of a currency A Summarizer Bean general purpose component for computing min, max and average over a user specified window of most recently received values A Displayer Bean general purpose component for displaying textual information (title string and info string) Used to display info from QuoteProducer or Summarizer Assignment I Deliverables Source code Executables (class files) Design write up Including description of the approach taken, assumptions made, program structure, algorithms, class hierarchy etc. A solid assignment that meets minimum requirements can achieve a grade of B+ Additional beans, further enhancements etc. can be used to improve beyond B+. 5
Assignment I Setting up your environment Java 1.5.0 available in the lab Type the following: java-config -s sun-jdk-1.5.0.07 source $HOME/.gentoo/java-env Add the last line above to your.profile 6