Wednesday, June 1, 2011

Applying Agile Techniques to Software Architecture

Introduction
The agile methodologies are getting widely accepted all over the world. However, there is still a lot of discussion and debate on how to apply those methodologies to the architectural space. Most conflicting issues arise between the ‘big design upfront – an approach that is strongly discouraged by the agile approach practitioners and the traditional approach to architectural design. In this post you will read on how you can achieve technical excellence, streamlined development practices, and a constant and ever-increasing flow of business by integrating the agile approach in to your software architecture. This can be achieved with a set of team dynamics, conceptual practices, and specific technologies that are proposed herein.

Architectural dynamic utilized in Agile teams
One of the 12 principles of the Agile Manifesto states that “the best architectures, requirements, and designs emerge from self-organizing teams.” This is something that is considered as a foundation here, especially with regard to the shared specialization.
The architecture is an activity that is historically performed with emphasis on the early stages of a project. The agile development on the other hand, lays its focus on emergent design and iterative production. Thereby, it creates a series of interesting challenges down the road.
The basic characteristic of the agile approach is that it believes in shared responsibility. Unlike the traditional approach wherein a software architect was considered wholly responsible for creating the software architecture and higher-level design, in case of the agile approach this responsibility of the software architect is diluted. In this approach, the software architecture is developed by the whole team. Hence, it helps in preserving its multi disciplinary nature. Now, that doesn’t mean the role of software architect is no longer considered important. It goes without saying that the software architect will still remain the person who will conceptualize the idea of the software architecture however, he will explain the design to the team members and they all will contribute in its development. The benefit here is that the entire team participates in understanding the implications of the design and continuously evaluates them.
It is a fact that key considerations such as the modularity strategy, how communication is handled within and outside the application, and how data and services are accessed and abstracted are better analyzed when a team sits and discusses about them rather than an individual handling them all simultaneously. In this way, the team members contribute their suggestions, their fears and concerns. Hence, the probability of failure is reduced to a great extent.
These challenges are usually tackled by holding regular meeting of the team members for architectural discussion and revision. These review and design meetings comprise a lot of white boarding and open talk. Also, it helps to have the most important guidelines permanently exposed in the meeting area. These could include diagrams, checklists or reference charts around the walls, and semi-permanent flip charts that can be used as posters.

Patterns and practices followed in Agile architecture
The big design approach leaves us with several inconveniences. To avoid this one of the most common approach suggested it “sashimi” approach. Here separate design for each part is not developed instead, small codes are developed with the intent to connect all the pieces and then the main functionality is constructed. This will give you the same end to end set up that you wanted. The objective is to do away with complexities of big building architectural components. Since there are repetitions of some of the processes become unnecessarily big and unmanageable.
However one challenge that is faced with to replace this support system with architectural pieces is to define a decoupled API. At the outset developing the API becomes the most critical thing to do. For similar reasons it is advised to star with absolutely no implementation. Even if you use a third party component it is advised that you follow a similar practice.
Architectural Pattern
Concentric approach has also emerged as a most common approach for agile development of software for architecture. The first step is to analyze and develop technical vision of the desired solution. This technical vision enables you not only to compare your own progress but also to guide you as to what your subsequent action should be. Thus it is important to establish a logical continuity in your entire planning. The second step would be to decompose the entire step into as many small manageable steps as possible. This not only makes the job easier in terms of division of responsibility but also to check progress and to check whether the person to whom the responsibility was given has lived up to it or not. This also helps in adding up new functionality if needed. This helps us do away with the requirement of having to redo the entire program all over again.
The next step is to describe each such decomposition in terms of architectural styles. This helps us make this decomposition more understandable to people who are not directly linked with the project. The trickiest part is to define the layers. The layers have to be so defined that they represent the decomposed components of the project. If they are clearly defined then it becomes easier for the person to whom the responsibility is entrusted to understand and execute the work better. This also makes it easier to distribute the work among teams so that development of each part can be closely monitored and handled. This also helps understand which a particular component is lagging.
The next level is the packaging of the software to turn them into independent saleable software packages. This helps to turn them into independently recognizable software packages.
The next step is to finally develop the program languages and introduce the same to the stake holders.
However one should keep in their mind that all these different steps in the architecture can be undertaken in an independent basis as well. The latter would be in congruence with the needs and goals of the project!
Quality Attributes required in architecture
It is a common aspect in the world of architecture of what are the aspects which one should consider in a system design. There are several qualities and attributes which are essential. In perspective of agility one should keep in mind the attributes which must be managed in view of the backlog of the product. The implementation should be done on an incremental basis. In specific terms it means the management of a mix of needs, both the quality attribute requirements as well as features. Interestingly, the several qualities attribute lead to a trade off decisions and analysis where the usual prioritization might not prove to be enough!
The authors suggest that in order to manage quality attribute in an effective manner, one need to consider the latter as a goal whereas the requirements as a support system and user stories to the goal. It is important for the stories to have some normal acceptance criterion which re defined clearly. This is vital such that the tests that are implements can be neatly written out. For instance, some of the requirements are performance which need the resource usage and response time.
Validation of the architecture
The validation and testing of the architecture are the last stage of this section. From the authors point of view there are automated quality-attribute requirements testing, test-driven development, environment-configuration management, automated integration testing, and application-configuration management and automated deployment.
The authors are of the belief that interfaces should be defined as in the first section. Unit tests which can be executed should be used in the definitions. These specifications will have a dual role. Firstly they will safeguard for multi component and local refactoring and secondly they will be the point of entry for identifying defects in the reporting of the incident. The basic idea is that the implementation needs to be correct or changed in sync with the defect! However one should bear in mind that there are several changes in the architecture that will not be noticeable in unit tests!
In order to have a good management of the changes which should exceed the contracts of unit tests, one needs automated tests. The latter is a must for quality attributes and integration. While automated tests are difficult to create, their results are superior. These tests need to be such that they have a lower frequency which is a result of their resource usage.
Some of the examples include the following:
· Scalability: There is an acceptable amount of response time in the event of increase in system load. There is a planned capacity along with tool support which is a must for these tests. In this case both the server and client site needs to be kept in mind. The deployment also needs to be automated in the testing environment.
· Flexibility: The layers pattern needs to be instantiated. The tests need to be configured such that the acceptance needs to layer by layer, starting from the top layer only!
·
For the above to come true, one need to manage the configuration in two levels, one which is dependent on the environment and one is not. The automated deployment will be enabled in case of environment dependent configuration and focuses on the local and physical resource configuration! For the remaining configuration, there will be an issue that is the variability of the available functionality!
Technologies and techniques
It is vital to use the appropriate techniques and technologies in order to achieve the needed discipline through automation.
The agile world is one which has given more importance to human and their interactions rather than to tools and processes. in lieu of the above a helpful set of tools have been devised which make tedious and manual jobs away from individuals and make the execution frequent and fast. The latter is simple use to the constant feedback which is provided making it easier for human beings to act.
In order to attain the first level of technology, it usually includes frameworks and regular testing tools. Some of the unit testing tools includes xUnit to Cucumber apart from others. There are others like Selenium which is functional testing tools apart from several others which have a host of technologies needed for stress and performance testing. All of these run successfully on a built server as well individually at varying frequencies.
In a nutshell, while the basic development proactive is undertaken, it is supplemented with a specific unit test, stress level and acceptance to validate the architecture. There are style analysis, afferent and efferent coupling, cyclomatic complexity, code coverage statistics, lined of code per module and other such checks which were introduced in the second level. These tools are used in NDepend, StyleCop, FXCop, CheckStyle, JDepend, and Lattix among others. In the area of dynamic languages like Python, JavaScript and Ruby, there in an inherent problem in the implementation. However this should be filled up soon!
The third step is about metrics involving maintainability and flexibility regarding the project life cycle. In this arena, Visual Studio Team System has made immense progress.
It has been seen that a model needs to be in place for validation of a model of architecture. The important factor is for the automation of the process for the extraction of the required Meta data which is needed to validate the references, module composition and code. In addition, the distinguishing aspect of the module or code view of the system, starting from the runtime view in the evaluation period is vital! Lastly, learning about the performance of levels of reverse engineering is also done. The final step in the process involves the configuration and deployment in the varying staging
It is essential to have the project relevant and appropriate techniques in each fold and step of the main plan. The latter ensures that the controls are planted in the proper places with commencement of the project.
Conclusion
Symbyo Technologies strongly belief that the consideration of the architecture is the most fundamental aspect which creates value to the software projects. Additionally, the agile teams have immense techniques, tools and mechanics which are on offering for the software architecture society. Interestingly, these contributions have been considered one of the best in its area. It provides immense benefits to the users and enhances one’s results and project value!


,, ,

Monday, May 30, 2011

Technical Debt

Technical Debt – What it means?

According to Ward Cunningham, technical debt is a culmination of all those internal things in your software that you choose not to do but that can become a major problem in future if left undone. These little issues that are often postponed are not visibly prominent issues.

The software program or the application might seem all perfect with high quality but in true sense, the application is all good superficially. These problems are hidden and only a proper scrutiny of the software system will help recognize them. While the Quality Assurance team (QA) might say that the application has quality and a few defects, the technical debt still prevails. If this technical debt is not managed or reduced at the right time, chances are that it will eventually increase the cost of writing/ maintaining the code. This will outweigh its benefit or value to the end consumer.

Technical debt is more or less like a credit card that keeps on adding to the outstanding balance at a very high rate of interest. In case of technical debt however, the costs don’t indicate money but the time and efforts needed to work around the problems. In simpler terms, the more time the team takes to pay off the technical debt i.e. work around to solve the little underlying problems, the more the interest is accumulated in the form of additional workarounds. This will ultimately cause the business to suffer with higher costs.

Truly speaking, the technical debt might not really involve money but it actually can cause financial losses. That’s because the time and effort the developers spend on cracking the code to solve the problem can be spent more productively to add value to the business. The codes are often quite complicated making it again very difficult to find the bugs. This time-consuming process leaves the developers with less time to work on something more valuable hence causing the business and the organization on a whole to suffer financially.

Why does Technical Debt get accumulated?

In the initial phase, writing a code is quicker because the developers write codes without tidying up, without writing unit tests and without doing any Test Driven Development. Hence, the team churns out more number of stories in relatively less time. Writing software requires them to give a decent amount of time for it`s development. A software development process requires working on different levels. It involves addressing the problem as they show up in a case to case basis. However, the underlying problems don’t show up quickly. Doing the right thing, the right way takes more time, especially in the beginning.

Where does the Technical Debt come from?

Inexperienced developers: Software developer has to constantly upgrade his or her skill set depending on the market trends. This seldom happens. As a matter of fact, many developers write codes for languages like JAVA or C# or Ruby without having the basic knowledge of what a good Object Oriented Code is. As a result, they end up writing codes that are inappropriate or are typically meant for languages they are familiar with like Visual Basic, etc. The onus for this lies on the company too. Many a time’s companies in order to maximize their profits use code developers who are inexperienced i.e. cheap. This practise in turn effects the code and at the end the reputation of the company and hence must be avoided as much as possible.

Deadline pressure: The pressure of delivering the product within a stipulated time is often a reason for several little underlying problems go unnoticed. Due to their commitment to release the program or application of iteration on a specified date, the developers overlook minor errors and expedite things. These minor errors can in future become major ones causing the application to become unresponsive. Unfortunately, the management also supports the developers without realising that it could end up in high managerial costs.

Untidy, hard-to-read code: When the code that is initially written is not a tidy one, the next developer who works on it will also not feel compelled to tidy it up or write a clean code himself. This results in a small mess becoming bigger every time a new developer works on it.
Specialisation: When a code is a specialized one, the developers often back out even if the find that code is a bad one. One, they don’t feel qualified to work on that code and secondly, they don not want to take any extra effort of tidying up a specialized code.

Over complication: Software developers often tend to over complicate things in order to stay safe from any future problem. They try to visualize the problems that may arise and try to develop codes for such potential problems. In this way, they end up writing codes that go in an entirely different direction without giving them any benefit. Many a times, the code doesn’t really fit the need as it is for a problem that doesn’t even exist. Over design and over complication often takes extra time and effort without any use.

Over simplification: Contrary to poplar belief over simplification can be also a major cause for a software`s downfall. Software developers sometimes in order to avoid writing excess code language for a program sometimes make the program over simplified which can turn out be just as bad as the point given before this ‘over complication. Sometimes due to this over simplification the software fails to perform when set a little different set of parameters. Software must be flexible enough to be able to cope with at least a decent change of the kind of data. So it highly important that a kind of balance is maintained between the two above points which is actually essential for the success of any software.

Bad design: Some codes are simply designed poorly. Building on a poorly designed code or working on the code without tidying it up makes the problem even worse.

Finding a solution to the problem

There is no one certain way to solve the problem. As a matter of fact, the solution will take several iterations. It is important to show a level of patience and adopt a multi-pronged approach to reach the solution. Some of the methods have been discussed in brief below.

Planks in the solution:

1. The basic step to solve the problem is to first train the developers in the language that is to be used. Only a proper understanding of the language will help the software developers to write a code that is less prone to have any inherent problems. Also, in order to be successful, it is essential that the trained developers are tested and supported by the pros in that area so that the training results to be effective.
2. The developers and the managers have to be informed about the current problems. Also, the impact of these problems on the business costs has to be ascertained in order to know the significance of the problems. This will clearly indicate the level of problem and the value of solving the problem. The management should also make it clear that it acknowledges the problem and is prepared to start paying off the technical debt that has inevitably arisen.
3. The training sessions on the code smells, Refactoring, Unit Test, Test driven Development have to concisely deal with the inherent problems and aim at reaching a solution. A combination of classroom sessions, web based books and material will enhance the training.
4. The software developers should be given some time (at least 2 hours a week) from their office hours to practice their skills. This practice should be on throw-away codes so that the developers can experiment and come up with new ideas of solving a problem. Time to practice and study is perhaps the best way to diagnose a problem and make the developers confident for solving it in real-time.
5. Using tools such as static analysis, Unit test, continuous integration, and automated acceptance tests helps the teams find, reduce and measure their technical debt load. However, measuring this should not imply that the team will be punished or rewarded for the results. If that happens, even these figures can be manipulated and the end result will only be destructive for the Company.
6. Developers who had undergone and successfully completed their training and also show a visibly higher level of proficiency in their skills should be rewarded. They could be given some token gifts instead of money as such things will give them some recognition and motivate others to develop.
7. Bi-weekly meetings should be conducted over lunch to help the developers meet and discuss the various technical issues that they face. The lunch often helps in getting more attendance and the more the developers, the more technical issues will be solved. Also, people form the senior management should also randomly attend these meets to indicate the support of the management to the software developers.
8. Lastly, a technical debt backlog should be maintained that has records of any technical debt that arises. Whenever a technical issue is reported that can’t be addressed immediately, the developer should be asked to write a Technical Debt card. This will help the Company track the Technical Debt and prioritize its work accordingly.


As is clear from the above, every business has a situation that consists of a problem and an opportunity. The success of the organization hence, lies on how it deals with the problem and how it cashes in on the opportunity.

The Problem: The crux lies in the technicalities of the codes that are developed by the software developers. The code bases of the projects are accumulating technical debt. This has made the entire system to slow down. This basic problem is costing the business financial losses as the valuable time and efforts of the developers is wasted in trying to fix the bugs that arise due to the technical debt.

The Opportunity: With the technical debt becoming prominent, the company has a reason to improve the technical skills of its developers which will in turn help the company to develop new products and deals with the technical issues in-house.
, , , ,

Sunday, May 29, 2011

Is NFC the Future of Mobile Payment ?

Last week, Google unveiled Google Wallet in a joint venture with Mastercard. The initiative will allow customers to pay for goods by waving their mobile phones at check-out terminals.

In the past few thousand years, the way we pay has changed just three times—from coins, to paper money, to plastic cards. Now many believe we are on the brink of the next big shit. Mobile Payment based on NFC Technology. But can NFC really become the future of mobile payment ?


In order to be the De Facto standard of mobile payment, NFC would certainly have to overcome a few obstacles as well as stand up to challenges from other technologies in the field of mobile-payments. A major obstacle for NFC phones is that in order to function as a payment tool the merchants would need to upgrade their POS readers.

In New York and San Francisco some of the merchants like Macy’s, Subway and American Eagle Outfitters have done the necessary upgrades thus allowing their customers with Nexus S phone to make payments through phones in these cities. However NFC still faces a big challenge of convincing the phone manufacturers to put NFC chips in their phones. The manufacturers on their part would be skeptical about using NFC chips until more merchants upgrade their POS terminals to handle NFC payments. On the other hand even the retailers might not be open to the idea of spending more money on upgrades until more number of consumers begins to use NFC enabled phones.

There are one or more biometric technologies which might offer some kind of challenge to NFC. Few of leading companies in that field like Square are planning to offer a new system which enables customers to pay simply by stating their names. In order to avail this service you need to register with the merchant wherein you will have to provide your credit card details. However, when you enter a shop, all you need to do is to state your name in order to pay for your purchases. This concept can be extended in future, where you can make payments through MasterCard or Visa by registering your voice with them. With advanced voice recognition technologies available these days, it wouldn’t be completely farfetched to think that sometime in future it might be possible to make payments by simply stating your name, address and the purchase amount into the microphone at the sales counter which would verify your identity against your registered voiceprint. It could be extended, for added security, with a camera transmitting your image along with your voice for facial recognition.

Though NFC is surely gaining popularity as a payment device, it’s the users who will give the ultimate verdict on which technology will win in the long run. It will depend on what the customers find more user-friendly and convenient. With many other several tasks that the mobile phones already perform, Mobile use as payment device might just become another one of them.
,,,,,

Thursday, February 24, 2011

Using Styles, Themes, and Painters with LWUIT







Contents
  • Style
  • A Style for Each State
  • Using Style
  • The Theme Creator
  • UIID
  • Spinner
  • Table
  • Conclusion
  • Resources
Lightweight User Interface Toolkit (LWUIT) version 1.3, released in December 2009, consolidates the modifications over version 1.1 initiated in version 1.2 and incorporates some new ones too. It also introduces three new components -- Tree, Table and Spinner. The use of the Tree widget is demonstrated through the LWUIT Demo that comes with the LWUIT download bundle. In this article we examine the changes with respect to Style and go on to check out Table and Spinner.
The demo applications have been developed on the Sprint Wireless Toolkit 3.3.2 (SWTK). Not only does this toolkit support LWUIT extremely well, it also has an interesting array of device emulators like those for HTC Touch and Samsung Instinct. If you intend to try out LWUIT, I would strongly suggest that you install the Sprint WTK on your computer.

Style

The idea behind Style is to centrally define the visual attributes for each widget (component). In addition to its physical design, such as its shape, the appearance of a widget can be defined in terms of a number of common features or attributes. In LWUIT 1.1 the settable attributes for a component were:
  • Background and foreground colors.
  • Fonts for writing text on it.
  • Background transparency.
  • Background image.
  • Margin and padding.
  • Background painters.
  • Border.
The additional attributes defined under LWUIT 1.3 are:
  • Background type -- specifies whether the background has an image or a color gradient. An image can be tiled, scaled or aligned (unscaled with alignment). A gradient for background can be linear (vertical/horizontal) or radial.
  • Background alignment -- if an image (tiled or aligned) is used for the background, the alignment (top/bottom/left/right/center) is defined by this attribute.
  • Background gradient start and end colors.
A Style object holds all these attributes for each state of each component that is used in an application, and has appropriate accessor methods. In addition this class also has the ability to inform a registered listener when a style object associated with a given component is altered.

A Style for Each State

In the early days of LWUIT, that is up to version 1.1, there used to be just one Style object for each widget to be displayed. This single Style object had separate attributes corresponding to the different widget states. For example, the background color for the unselected (unfocused) state would be defined as bgColor and that for the selected (focused) state as bgSelectionColor. The code for setting these colors would look like this.
 
        //when the widget does not have focus
        //the background will be red
        myComponent.getStyle().setBgColor(0xff0000);
 
        //when the widget has focus
        //the background will be blue
        myComponent.getStyle().setBgSelectionColor(0x0000ff);
 
However, as of version 1.2, this has changed. Components now have distinct styles for each of their permissible states. Most components would have a selectedStyle and an unselectedStyle. Components like buttons and those that extend the Button class will have an additional style corresponding to the pressed state -- the pressedStyle. So, the above code sample will now look as follows.
 
        //when the widget does not have focus
        //the background will be red
        myComponent.getUnselectedStyle().setBgColor(0xff0000);
 
        //when the widget has focus
        //the background will be blue
        myComponent.getSelectedStyle().setBgColor(0x0000ff);
 
Note that we have used two different versions of the getter method -- one for each style. Actually, the Component class has a getStyle method too, which returns the appropriate style depending upon the state of the component. This capability leads to simpler coding especially for methods that render components.
When a component is created, a default Style object gets associated with it as its unselectedStyle. The other styles are created when accessed for the first time through the corresponding setter or getter methods.
There are several ways for setting and modifying attributes as shown in the following list.
  • By using the get*Style().set* combination as above.
  • By creating a new style with the desired attributes and then invoking the set*Style method to set the new style.
  • Style for an entire set of widgets can be set through the UIManager instance. The relevant technique is
·          
·                 //method for setting unselected style
·                 UIManager.getInstance().setComponentStyle
·                         (String id, Style style)
·          
·                 //method for setting selected style
·                 UIManager.getInstance().setComponentSelectedStyle
·                         (String id, Style style)
·          
However, currently this approach works for selected and unselected styles.
  • Through a Theme.
In the following section we shall check out a simple demo application which shows how styling can be done under LWUIT 1.3.

Using Style

Our application will have a single form with three widgets and will look like the Figure 1:





















Figure 1. Style Update Demo.
The screenshot above shows a screen with two labels and one button. Labels, by default, cannot receive focus and the topmost widget is such a label. The second label has been explicitly made focusable as shown by the code snippet below.
 
        //create a label
        Label focusLabel = new Label("Focusable");
 
        //and make it focusable
        focusLabel.setFocusable(true);
 
In Figure 1 we see the second label in the selected state. The applicable style is set as follows:
 
        //modify default style to set attributes 
        //for selected state of focus label
        focusLabel.getSelectedStyle().setBgColor(0x555555);
        focusLabel.getSelectedStyle().setFont(font);
        focusLabel.getSelectedStyle().setBorder
                (Border.createBevelRaised());
 
The first label and the button are unselected and their appearances are styled through the same Style object. This object has the following attributes:
 
        //create a common style for unselected state
        Style unselStyle = new Style();
        unselStyle.setFont(font);
        unselStyle.setBgTransparency(64);
        unselStyle.setFgColor(0xffc605);
        unselStyle.setBorder(Border.createEtchedRaised());
 
This style is set as the unselected one for all labels by calling the setComponentStyle(String id, Style style) method. This is shown below.
 
        //set unselected style for labels
        UIManager.getInstance().setComponentStyle
                ("Label", unselStyle);
 
The unselected style for the button is set in the following way using the same style object that is used for labels.
 
        //create button
        Button button = new Button("Button");
 
        //set style for unselected state of button
        button.setStyle(unselStyle);
 
Figure 2 shows the same screen as above with the button in the selected state.





















Figure 2. The button is selected.
We can see that both labels are unselected and their appearances are the same. The button, which has focus, looks just like focusLabel in Figure 1. This is ensured by creating a style with attributes that have the same values that were used for the selected style of focusLabel. This new style -- buttonSelStyle -- is then installed as the selected style for the button.
 
        //create selected style for button
        Style buttonSelStyle = new Style();
        buttonSelStyle.setBgColor(0x555555);
        buttonSelStyle.setFont(font);
        buttonSelStyle.setBorder(Border.createBevelRaised());
        ...
        //set style for selected state of button
        button.setSelectedStyle(buttonSelStyle);
 
In a similar manner we create and set a style for the pressed state of the button:
 
        //create pressed style for button
        Style buttonPrStyle = new Style();
        buttonPrStyle.setBgColor(0xff0055);
        buttonPrStyle.setFont(font);
        buttonPrStyle.setBgTransparency(127);
        buttonPrStyle.setBorder(Border.createRoundBorder
                (12, 5, 0xff0000));
        ...
        //set style for pressed state of button
        button.setPressedStyle(buttonPrStyle);
 
The result of pressing the button can be seen in Figure 3 below.





















Figure 3. The button is pressed.
In the demo application above, style attributes have been set programatically to show some fundamental aspects of styling. In real life applications, though, it would be advisable to apply themes.

The Theme Creator

In the beginning there was the Resource Editor -- a very handy tool for creating and editing resource files. In Decemeber 2008 it was renamed LWUIT Designer, and in the latest release it has become the Theme Creator. While the essential functionality remains the same, both the LWUIT Designer 1.2 and the Theme Creator allow the creation of three distinct styles, as we can see in Figure 4.



















Figure 4. Creating a theme with three styles.
The Theme Creator now provides support for SVG images too. This is shown in Figure 5.





















Figure 5. SVG support.

UIID

Every component can have its own unique id which is used for styling as we have seen. All components in the library have their ids. When creating a custom component, a new id should be alloted. Sometimes, components are built up using existing ones and these constituent parts can have ids different from their original ones. Consider the case of a component that uses a label to form a part. If we want to give this part a distinct id for styling, the getUIID method of Component class would have had to be overridden in the days of LWUIT 1.1. A new method -- setUIID -- was provided in LWUIT 1.2 to do the same thing in a simpler and more intuitive way. So now we can write:
 
        Label newMyPart = new Label();
        newMyPart.setUIID("NewMyPart");
 

Spinner

A spinner is similar to a combo box in the sense that it shows a single value from a list of values. However, spinner does not show a drop down list for selection. Instead the up or down key has to be used to scroll through the list. Also, a spinner can show only a date, time or numerical value. Figure 6 shows a form with two components: a button and a spinner. The button has been added to show how different styles take effect depending on whether the spinner has focus or not. Here the spinner is shown in the unselected state.





















The Spinner class does not have an accessible constructor. One of the factory methods has to be used to get an instance of spinner. In this case we create a spinner to display time in twenty-four hour format showing hours, minutes and seconds. The method used is: createTime(int min, int max, int currentValue, int step, boolean twentyFourHours, boolean showSeconds). The first two parameters specify the minimum and maximum values for the list. The third parameter defines the value to be shown initially. The unit for all the three is seconds since midnight. The fourth is the difference between two successive values in seconds. The fifth and sixth parameters define the display format.
The image on the right of the time display is called the spinnerHandle and is meant to indicate that the display can spin. The following code snippet shows how the spinner is created and the spinnerHandle is set. A word about the value initially shown in Figure 6 above: while creating the spinner instance, the value specified for initial display is 180, which corresponds to three minutes or, in the given format, 00:03:00. However, note that the step size has been specified as 40 which means 180 is not in the list. The time displayed corresponds to 160 which is the highest value not exceeding 180.
 
        //create spinner with seconds display
        spinner = Spinner.createTime(0, 7200, 180, 40, true, true);
 
        //set image to visually indicate it is spinnable
        try
        {
                spinner.setSpinnerHandle(Image.createImage("/handle.png"));
        }
        catch(java.io.IOException ioe)
        {
        }
 
In Figure 6 we see the spinner in the unselected state. There is a dark olive green background on which the numerical display is rendered in blue. The background represents the spinner container and its unselected appearance is set as follows:
 
        //affects look when spinner does not have focus
        spinner.getUnselectedStyle().setBgColor(0x556b3f);
        spinner.getUnselectedStyle().setBorder(Border.createBevelRaised());
 
The first step in setting style for the time display is to get the DefaultListCellRenderer instance for the spinner. The style attributes can then be set as shown below.
 
        //create a font
        Font font = Font.createSystemFont(Font.FACE_PROPORTIONAL,
                Font.STYLE_BOLD,Font.SIZE_LARGE);
 
        ...
 
        //affects look when spinner does not have focus
        spinner.getUnselectedStyle().setBgColor(0x556b3f);
        spinner.getUnselectedStyle().setBorder(Border.createBevelRaised());
 
        ...
 
        //renderer for the cell containing display
        DefaultListCellRenderer dlcr = 
                (DefaultListCellRenderer)spinner.getRenderer();
 
        //affects steady state look
        dlcr.getSelectedStyle().setBgColor(0x0000ff);
        dlcr.getSelectedStyle().setFgColor(0);
        dlcr.getSelectedStyle().setFont(font);
        dlcr.getSelectedStyle().setPadding(Component.RIGHT, 7);
 
        //affects look during scrolling
        dlcr.getUnselectedStyle().setBgTransparency(0);
        dlcr.getUnselectedStyle().setFgColor(0);
        dlcr.getUnselectedStyle().setFont(font);
 
The code above also sets the renderer style for the unselected state. This style becomes effective when the spinner value scrolls. To see how that works, press the down key. Now, the spinner gets focus and its appearance changes as specified by the code below.
 
        //affects look when spinner has focus
        spinner.getSelectedStyle().setBgColor(0x0000ff);
        spinner.getSelectedStyle().setBorder
                (Border.createRoundBorder(12, 5, 0xff0000));
 
The spinner now looks like what's shown in Figure 7.






















Figure 7. Spinner is selected.
Although the spinner now has focus, it will not respond to the up or the down key. At this stage the scrolling keys will toggle focus between the spinner and the button. To direct the scrolling key events to control the spinner display, the select key has to be pressed while the spinner has focus. Generally speaking, the select key can be used to toggle the applicability of scrolling keys between a form itself and a component with focus contained in the form. The scrolling keys can now be used to sequentially change the time displayed.
What remains now is to see how we can retrieve the value selected on the spinner. The demo does this in different ways. One way is through a command. We add the Show command to the form and, in the actionPerformed method, call into the getValue method of Spinner class.
 
        //create and add 'Exit' command to the form
        //the command id is 1
        demoForm.addCommand(new Command("Exit", 1));
 
        //create and add command to show spinner value
        //the command id is 2
        demoForm.addCommand(new Command("Show", 2));
 
        //this MIDlet is the listener for the form's command
        demoForm.setCommandListener(this);
 
        ...
 
        //act on the commands and the click
        public void actionPerformed(ActionEvent ae)
        {
                Command cmd = ae.getCommand();
 
                if(cmd != null)
                {
                        switch (cmd.getId())
                        {
                                //'Exit' command
                                case 1:
                                notifyDestroyed();
                                        break;
 
                                //'Show' command
                                case 2:
                                System.out.println("Value 
                                                shown through command : " 
                                                + spinner.getValue());
                        }
 
                        return;
                }
 
                ...
        }
 
A second method is to register the MIDlet as the ActionListener for the spinner. If we now click on the spinner, the actionPerformed method of the MIDlet will be invoked. The necessary action can then be taken.
 
        
        //this MIDlet is the action listener for spinner
        spinner.addActionListener(this);
 
        ...
 
        //act on the commands and the click
        public void actionPerformed(ActionEvent ae)
        {
                Command cmd = ae.getCommand();
 
                if(cmd != null)
                {
                        ...
 
                        return;
                }
 
                if(ae.getSource() == spinner)
                {
                        System.out.println("Value shown on click : "
                         + spinner.getValue());
                }
        }
 
The third approach used in the demo is to add the MIDlet to the spinner as the SelectionListener. For this technique to work, the MIDlet has to implement the SelectionListener interface so that its selectionChanged method is called whenever the spinner selection is changed.
 
        //this MIDlet is the selection listener for spinner
        spinner.addSelectionListener(this);
 
        ...
 
        public void selectionChanged(int oldSelected, int newSelected)
        {
                if(oldSelected != newSelected)
                {
                        ListModel model = spinner.getModel();
                        System.out.println("Selection changed from " + 
                                model.getItemAt(oldSelected) + " to " +  
                                model.getItemAt(newSelected));
                }
        }
 
When we click on a list, its selection changes, and this causes the selectionChanged method of the registered SelectionListener to be called in addition to the actionPerformed method of its ActionListener. As Spinner is a subclass of List, it behaves in a similar fashion and clicking on it results in the printing of the selection change message for the demo. For a spinner, however, we do not consider this to be a valid selection change since the value remains the same. The if clause in the above code listing takes care of this issue. The resultant console printouts for all three approaches are shown in Figure 8.











Figure 8. Message printouts.

Table

A table displays information in the form of a grid. The topmost row describes the name of the data in each column. These are the Headers. The rest of the table displays data and is comprised of Cells. The headers are instances of Label and are meant to be uneditable. The cells can be either editable or uneditable. Editable cells are instances of TextField while uneditable cells are instances of Label. However, uneditable does not mean unmodifiable as we shall see when we discuss the demo application.
Figure 9 shows a table with 5 rows and 3 columns. The topmost row holds the headers. The rest of the rows hold cells that display data. Here we have two kinds of data: text in the leftmost column (column 0) and numbers in the other columns (columns 1 and 2).





















Figure 9. A table.
The contents of a table are determined by an underlying model -- the table model. LWUIT defines the TableModel interface that must be implemented by a table model; the default implementation included in the library is the DefaultTableModel class. So the first step in creating a table is to set up the model. This model is then passed as a parameter to the table constructor. The relevant code for our application is:
 
        //define headers
        String[] columns = new String[] {"Items", "Good", "Scrap"};
 
        //define data
        Object[][] data = new Object[][] {{"Plate-01", 
                new Integer(1605), new Integer(57)}, {"Plate-02", 
                new  Integer(5001), new Integer(326)}, {"Coil-01", 
                new Integer(417), new Integer(124)}, {"Coil-02", 
                new Integer(451), new  Integer(22)}};
 
        //create model with uneditable cells
        //as specified by last parameter
        //for editable cells last parameter must be 'true'
        DefaultTableModel model = new DefaultTableModel(columns, 
                data, false);
 
        //create table
        table = new Table(model);
 
The cells of our table are labels and the default alignment is Label.LEFT. There is a method in the Table class to set cell alignment -- setCellAlignment. However, this is not a static method and works only for new cells created for an existing table. The default alignment for headers is Label.CENTER To change the alignment of cells, we need to access each label that forms a cell and set its alignment. Another point to be noted is that, for some form layouts, the sizing of the last column may not work properly. We have used a kind of rendering prototype to ensure proper sizing. All this is shown in the code snippet below.
 
        //create a font
        Font font = Font.createSystemFont(Font.FACE_PROPORTIONAL,
                Font.STYLE_BOLD,Font.SIZE_LARGE);
 
        //width of 'rendering prototype'
        int w = font.stringWidth("WWWW");
 
        ...
 
        //does not affect alignment of cells already created as
        //table is constructed with cells with default alignment
        //works only for cells created later
        //this happens, for example, if new data is set
        table.setCellAlignment(Label.CENTER);
 
        TableLayout layout = (TableLayout)table.getLayout();
        Component c = null;
 
        //'getRowCount' does not take into account the header row
        //so add 1 to get total number of rows
        int rows = ((DefaultTableModel)table.getModel()).
                                getRowCount() + 1;
        int cols = ((DefaultTableModel)table.getModel()).
                                getColumnCount();
 
        for(int i = 0; i < rows; i++)
        {
                for(int j = 0; j < cols; j++)
                {
                        //get the component for cell at
                        //specified row and column
                        c = layout.getComponentAt(i,j);
 
                        if(i == 0)
                        {
                                //set border for headers
                                c.getUnselectedStyle().setBorder
                                        (Border.createLineBorder
                                        (1, 0xff0000));
                                if(j == cols - 1)
                                {
                                        //use prototype
                                        //to size the last column
                                        c.setPreferredSize(new Dimension(w, 
                                                c.getPreferredH()));
                                }
                        }
                        else
                        {
                                //necessary because cells were originally
                                //created with default (left) alignment
                                ((Label)c).setAlignment(Label.CENTER);
                        }
                }
        }
 
The header strings and the cell data are held within the table model. The TableModel interface defines methods to access these variables. Note that there is only a getter method for the column names while there is a getter as well as a setter method for the cell values. The Show command on our demo form uses the getValueAt method to print out a cell value on the console.
 
        //act on the commands
        public void actionPerformed(ActionEvent ae)
        {
                Command cmd = ae.getCommand();
 
                switch (cmd.getId())
                {
                        ...
 
                        //'Show' command
                        case 2:
                                //get the table model instance
                                DefaultTableModel dtm = 
                                        (DefaultTableModel)
                                        table.getModel();
 
                                //get the value at the specified cell
                                //use actual row number - 1 
                                //since actual first row is not for data
                                Object val = dtm.getValueAt(0, 2);
 
                                //print value
                                System.out.println
                                        ("Plate-01 Scrap : " + val);
 
                                ...
 
                }
        }
 
The printout is shown in Figure 10.












Figure 10. Accessing cell data.
The setValueAt method can be used to programatically change data in a cell -- even for uneditable cells. In our demo application the Show command is replaced with a Modify command which changes the data in the cell for Plate-02 Scrap from 326 to 750. The setValueAt method leads to the creation of a new label to replace the existing one. As we have already set cell alignment to Label.CENTER, the new value remains properly aligned.
 
                //create and add command to show value
                //the command id is 2
                //demoForm.addCommand(new Command("Show", 2));
 
                //create and add command to change value
                //the command id is 2
                demoForm.addCommand(new Command("Modify", 2));
 
                ...
        }
 
        ...
 
        //act on the commands
        public void actionPerformed(ActionEvent ae)
        {
                Command cmd = ae.getCommand();
 
                switch (cmd.getId())
                {
                        //'Exit' command
                        case 1:
                                notifyDestroyed();
                                break;
 
                        //'Show' command
                        /*case 2:
                                //get the table model instance
                                DefaultTableModel dtm = 
                                        (DefaultTableModel)
                                        table.getModel();
 
                                //get the value at the specified cell
                                //use actual row number - 1 
                                //since actual first row is not for data
                                Object val = dtm.getValueAt(0, 2);
 
                                //print value
                                System.out.println
                                                ("Plate-01 Scrap : " 
                                                + val);*/
 
                        //'Modify' command
                        case 2:
                                //get the table model instance
                                DefaultTableModel dtm = 
                                        (DefaultTableModel)
                                        table.getModel();
 
                                //set the value at the specified cell
                                //use actual row number - 1 
                                //since actual first row is not for data
                                dtm.setValueAt(1, 2, new Integer(750));
                }
        }
 
In Figure 11 we can see the new value for Plate-02 Scrap.






















Figure 11. Cell data modified.
In the demo application for table, the only styling done programmatically is for the set of borders for the headers. The rest of the styling has been defined in a theme. The theme file is shown below in Figure 12. A word of caution here. This theme file has been created by the Theme Creator that comes with LWUIT 1.3. The Resource Editor that comes with the SWTK is of an earlier vintage and will not be able to open this file.















Figure 12. Theme file for the demo app.

Conclusion

We have seen how the approach to styling has been modified since LWUIT 1.1. We have also checked out the new Theme Creator and two new components that have been introduced in LWUIT 1.3. However, there are a number of interesting new features that have not been discussed here. These are listed in What's new in This Release in the LWUIT 1.3 download bundle.

Resources

  • src_codes.zip -- source code and resources for the demo applications.
  • LWUIT 1.1 for Java ME Developers -- useful for a detailed introduction to LWUIT basics as most of the fundamentals remain valid for LWUIT 1.3.
  • Lightweight User Interface Toolkit (LWUIT) project home -- has a link for source code and for download.
  • Shai Almog's blog on Java & LWUIT

Source: http://today.java.net/article/2010/04/19/using-styles-themes-and-painters-lwuit
----------------------------------------------------
If you search for Software outsourcing Company, Symbyo Right Sourcing™ is a unique approach to outsourcing that offers the best of both worlds by blending onsite, onshore and offshore resources and locations into one smooth global delivery model.
Symbyo offers Oracle Consulting and Microsoft .NET Consulting services, Offshore Oracle outsourcing services and Microsoft .NET Development services and offshore .Net outsourcing services.

,,,,