Friday, January 18, 2008

What makes "Spring Framework" tick,and that too in a big way-Part 1

The most telling aspect or area where Java Developers & for that matter the architects, are heavily tested is developing and designing middleware & server-side components.And I have developed many such kind of applications using EJB in the past.And even though there has been lot of growth from EJB2.1 to EJB3.0 specifications(particularly,annotations),the areas where personally I had a hard time using it has been unit testing the code and implementing effective transaction management.Some might argue ,Iam blaming it because I cant use it effectively and Iam not at all questioning its virtue and value and Iam still and will use it,being a standard framework defined by the Java Community Process (JCP) and supported by all major J2EE vendors,my focus is how best other lightweight solutions like Spring,Hibernate or for that matter Google Guice(even though I didnt get an opportunity to use & implement Guice in any enterprise applications so far),has made my life easier with respect to TDD and implementing Transaction management,security and persistence in distributed computing.

Lightweight vs Heavyweight frameworks

A software framework is a re-usable design for a software system (or subsystem). A software framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. Various parts of the framework may be exposed through an API.

Lightweight framework : Applications developed using lightweight framework do not have to depend on framework interfaces or abstract classes to "hook" components into the application in which category frameworks like Spring,Google Guice fall into compared to Heavyweight frameworks ,that require the extension of framework classes or the implementation of framework interfaces in order to take advantage of their middleware features. EJB2 is probably the most popular example of a heavyweight framework(And I do know the growth and support in EJB3 for POJOs,discussed later,which makes it lightweight and starting to become popular because of EJB3 Annotations along with JPA ).EJB is a heavyweight model for objects that don’t need to offer remote access.

Test first development has become much more popular in the last few years, and usually produces impressive results. Writing effective unit tests for an application isn’t just a question of putting in the time and effort; it can be severely constrained by high-level architecture. This is one of the biggest frustrations with EJB. Due to its heavy dependence on the EJB container, business logic coded in EJB is very hard to test.Code that is hard to test is usually also hard to re-engineer, reuse in different contexts, and refactor(though one might argue with me citing the existence of lightweight frameworks like MockEJB)and considering testability is an essential characteristic of agile projects.

Spring Framework
Spring is an open source project led by SpringSource & Interface21 and brainchild of Rod Johnson.Spring is a light-weight framework for the development of enterprise-ready applications. Spring can be used to configure declarative transaction management, remote access to your logic using RMI or web services, mailing facilities and various options in persisting your data to a database. Spring framework can be used in modular fashion, it allows to use in parts and leave the other components which is not required by the application.The Spring framework is a layered architecture consisting of seven well-defined modules.Here is a brief description of the seven modules,

Inversion of Control (IoC) Container: Also called the Core Container, creates and configures application objects and wires them together. This means that resources and collaborating objects are provided to objects, so the objects do not need to look them up. This moves an important responsibility out of your code and makes it easier to write and test code.

Aspect-Oriented Programming (AOP) framework:Works with cross-cutting concerns—one solution to a problem that’s used in multiple places. The Spring AOP framework links cross-cutting concerns to the invocation of specific methods on specific objects (not classes) in such a way
that your code is unaware of their presence. The Spring Framework uses cross-cutting concerns and AOP to let your application deal with transactions without having a single line of transaction management code in your code base.

Data Access framework: Hides the complexity of using persistence APIs such as JDBC,Hibernate, and many others. Spring solves problems that have been haunting data-access developers for years: how to get hold of a database connection, how to make sure that the connection is closed, how to deal with exceptions, and how to do transaction management. When using the Spring Framework, all these issues are taken care of by the framework.

Transaction Management framework: Provides a very efficient way to add transaction management to your applications without affecting your code base. Adding transaction management is a matter of configuration, and it makes the lives of application developers much easier.Spring Framework simplifies it dramatically.And along with Unit Testing,this is the area I would be dwelling upon here.

Resource Abstraction framework: Offers a wonderful feature for conveniently locating files when configuring your applications. Chapter 2 discusses resource abstraction.

Validation framework: Hides the details of validating objects in web applications or rich client applications. It also deals with internationalization (i18n) and localization (l10n).

Spring Web MVC(Another significant framework,one of my fav): Provides a Model-View-Controller (MVC) framework that lets you build powerful web applications with ease. It handles the mapping of requests to controllers and of controllers to views. It has excellent form-handling and form-validation capabilities, and integrates with all popular view technologies, including JSP, Velocity, FreeMarker, XSLT,JasperReports, Excel, and PDFs.

Spring Web Flow:Makes implementing web-based wizards and complex workflow processes very easy and straightforward. Spring Web Flow is a conversation-based MVC framework.Spring Web Flow is distributed separately and can be downloaded via the Spring Framework website.

Acegi Security System: Adds authentication and authorization to objects in your application using AOP. Acegi can secure any web application, even those that do not use the Spring Framework.It offers a wide range of authentication and authorization options that will fit your most exotic security needs. Adding security checks to your application is straightforward and a
matter of configuration; you don’t need to write any code, except in some special use cases.Acegi is distributed separately and can be downloaded from http://acegisecurity.org/downloads.html.

Remote Access framework: Adds client-server capabilities to applications through configuration.Objects on the server can be exported as remotely available services. On the client, you can call these services transparently, also through configuration. Remotely accessing services
over the network thus becomes very easy. Spring’s Remote Access framework supports HTTPbased protocols and remote method invocation (RMI), and can access Enterprise JavaBeans as a client.

Spring Web Services: Takes the complexity out of web services and separates the concerns into manageable units. Most web service frameworks generate web service end points and definitions based on Java classes, which get you going really fast, but become very hard to manage as your project evolves. To solve this problem, Spring Web Services takes a layered approach and
separates the transport from the actual web service implementation by looking at web services as a messaging mechanism. Handling the XML message, executing business logic, and generating an XML response are all separate concerns that can be conveniently managed. Spring Web Services is distributed separately and can be downloaded via the Spring Framework website

Spring JMX: Exports objects via Java Management Extensions (JMX) through configuration.Spring JMX is closely related to Spring’s Remote Access framework. These objects can then be managed via JMX clients to change the value of properties, execute methods, or report statistics.
JMX allows you to reconfigure application objects remotely and without needing to restart the application.

OK lets start exploring the easiness ,robustness & scalability features being supported by Spring in Unit Testing and Transaction Management of the enterprise applications.

Test Driven Development with Spring Framework
To understand its use, we need to know what a POJO(Plain Old Java Object) is,POJO is a Java Object that doesn't implement any special interfaces or call any framework classes,remember the definition of Lightweight Framework.The benefits of POJO comes from decoupling the application code from the infrastructure frameworks.POJOs accelerate development, we can test our business logic outside of the application server(important criteria in TDD) and without a database.We dont have to package the code and deploy it in the application server and also we dont have to keep the database schema constantly in sync with the object model or spend time waiting for slow-running database tests to finish.
The Spring framework,provides services for POJOs such as transaction management,dependency injection,support for POJO remoting and security for POJOs(Acegi).

Dependency Injection
Dependency Injection is one of the core features of Spring Framework.
Dependency injection (DI) refers to the process of supplying an external dependency to a software component and is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency.

Conventionally, if an object needs to gain access to a particular service, the object takes responsibility to get hold of that service: either it holds a direct reference to the location of that service, or it goes to a known 'service locator' (in EJB2)and requests that it be passed back a reference to an implementation of a specified type of service. By contrast, using dependency injection, the object simply provides a property that can hold a reference to that type of service; and when the object is created a reference to an implementation of that type of service will automatically be injected into that property - by an external mechanism. The dependency injection approach offers more flexibility because it becomes easier to create alternative implementations of a given service type, and then to specify which implementation is to be used via a configuration file, without any change to the objects that use the service. This is especially useful in unit testing, because it is easy to inject a mock implementation of a service into the object being tested. On the other hand, excessive use of dependency injection can make applications more complex and harder to maintain: in order to understand the application's behaviour the developer needs to look at the configuration as well as the code, and the configuration is "invisible" to IDE-supported reference analysis and refactoring unless the IDE specifically supports the dependency injection framework.To use it,you must configure Spring's bean factory

Benefits of Dependency Injection


It eliminates the need to call lookup APIs,because a components dependencies are passed to it,we no longer have to write tedious JNDI code and components depend mainly on interfaces rather than on concrete implementations.

Types of dependency injection
Constructor injection,setter&getter injection and Method injection.

Spring’s org.springframework.test package has
number of base classes to simplify testing.
AbstractDependencyInjectionSpringContextTests - can do both setter or field-based dependency injection,cached context files
AbstractTransactionalDataSourceSpringContextTests -
allows you to easily clear data from tables and rolls back any data entered into the database.

Testing approaches
Generally speaking, testing should be used to ensure the following aspects of an application:
Correctness: You want to ensure the correctness of your application. For example, suppose that you have written a calculate() method on a Calculator class. You want to make sure that certain input for this method results in a correct calculation result.
Completeness: Testing can be used to ensure that your application is complete by verifying that all required operations have been executed. Suppose you have a signup process that includes creating an invoice for newly signed-up members. You want to test whether a member is actually added to the database, and also if an invoice has been created for that user.
Quality: Testing can ensure the quality of your application, and this goes beyond software quality metrics. A well-tested piece of software creates confidence with developers. When existing code needs to be changed, it’s less likely that developers will be afraid of unintentionally
breaking the software or reintroducing bugs.

Unit Testing
This so-called plain old Java object (POJO) approach to Java coding, combined with defining interfaces for important parts of your application provides the basis for thorough testing. The Spring Framework promotes exactly this approach (we could also say the Spring Framework makes this approach possible). By separating your code into well-defined interfaces and objects, you have already defined the units that are eligible for unit testing.
One goal of unit testing is to ensure that each unit of an application functions correctly in isolation.Another goal is to define a framework, harness, or contract (all referring to a strict set of rules that must be respected) that must be satisfied by the unit test. As long as the tests can be run successfully,
the unit is considered to work properly. (If there are bugs in the test code, the unit will function properly according to this buggy test code.)

Unit testing offers a number of benefits for developers:
Facilitate change: As previously mentioned, having a set of unit tests for a specific piece of code provides confidence in refactoring existing code. The unit tests will ensure the module continues to function correctly according to the available tests as long as the tests succeed.
Given there are enough tests for all the code in the application, this promotes and facilitates changing implementation details of units in the application. An important aspect of facilitating change is preventing solved problems or bugs from reentering the code.
Simplify integration: Unit testing provides a bottom-up testing approach, which ensures that low-level units function properly according to their tests. This makes it easier to write integration tests at a later stage. There is no need to have two tests for units.
Promote well-defined separation: In order for you to be able to completely and efficiently write unit tests, your code needs to be separated into well-defined units. Each unit needs to be tested in isolation and should therefore allow the replacement of dependencies with test specific ones. Thus, writing unit tests promotes the separation of your application into well-defined units.

Test-driven development (TDD) is a way of implementing code by writing a unit test before implementing the actual class.
Using Spring for Testing
When working with Spring for building your applications, you will typically use one or more XML configuration files for defining your application context. These configuration files are not Java files and will therefore not be compiled. Of course, if you include the Spring DTD or use Spring’s namespace support, some aspects of your configuration files will be validated. But issues such as defining a nonexisting class as the class for a bean in your application context or setting a nonexisting property on a bean definition are discovered only when you actually load the application context at runtime. This is where integration testing comes into the picture.The goal of integration testing is to test how the individually tested units of your application collaborate with each other. When working with Spring, you wire those dependencies together using Spring’s configuration files. In order to test part of your whole application, you typically want to load the Spring application context and test one or more beans configured in that application.

Spring provides three convenient test base classes for integration testing of your Spring applications: AbstractDependencyInjectionSpringContextTests, AbstractTransactionalSpringContextTests, and AbstractTransactionalDataSourceSpringContextTests. These classes are discussed in the following sections.

The org.springframework.test.AbstractDependencyInjectionSpringContextTests base class is the test class you will typically use when testing parts of your application that do not require access to a database or any other transactional support. You should extend this class by first implementing the getConfigLocations() method, which should return an array of application context locations to be loaded by the test. When the test is executed, the specified configurations will be loaded as an application context.
The major advantage of using this base class is that the application context will be loaded only once for each test method. If you were to load the application yourself in the setUp() method of a test, the application context would be reloaded for every test method. This is especially useful when loading configurations that require a lot of initialization, such as a Hibernate session factory.

Another convenient test base class is org.springframework.test.AbstractTransactionalSpringContextTests, which builds on top of the functionality offered by the AbstractDependencyInjectionSpringContextTests test base class. Each test method that is executed by a subclass of this base class will automatically participate in a transaction. Because the default is to roll back
the transaction after each test method execution, no actual modifications will be made to any transactional resources. This makes it the perfect choice for performing integration tests using a transactional data source.
Using this base class allows you to integration test functionality that will make modifications to the database without having to worry about the changes affecting any other test methods. It also allows you test code that requires a transactional context. And you can write data to the database without worrying about cleaning it up afterwards.As mentioned, all modifications to the database are rolled back at the end of each test method execution.

A third convenient test base class is org.springframework.test.AbstractTransactionalDataSourceSpringContextTests, which builds on top of the functionality provided by AbstractTransactional
SpringContextTests. In order to use this base class, you need to include a DataSource definition in the application context loaded by this test. The data source is automatically injected, as explained earlier.
The main feature offered by this base class is that it provides you with a JdbcTemplate as a protected field, which you can use to modify the data source, within the transactional context. You could, for instance, insert some data that the test needs in order to succeed. Because the statements to the JdbcTemplate are also executed within the transactional context, you do not need to worry about cleaning up the database or modifying the existing data.Another advantage of using this base class is that you can define fields for this test that are populated
automatically by Spring based on your application context.Spring also provides support for testing your J2EE-specific application code. Because much of your web application code is very much tied to J2EE classes, it is hard to test. For instance, testing a servlet or a Spring controller implementation requires you to somehow mock the HttpServletRequest and HttpServletResponse classes.

Transaction Management using Spring
Two main issues make database transactions complicated for developers to work with and difficult for database vendors to implement:
Concurrency control: Databases need to protect against data loss or ghost data, yet allow concurrent access to the same data. Generally, developers can choose an isolation level to control the level of protection. Another form of concurrency control is protecting against lost updates.

Synchronization between transactions: Complex applications often need a way to synchronize two or more databases or other resources so that their local transactions are guaranteed to commit or roll back in a group. The technique used for this is called two-phase commit (or 2PC), distributed transactions, or global transactions.
The first step in setting up transaction management with Spring is choosing a transaction management strategy. This basically means selecting which of the transaction-management APIs in Java you want to use.The main interface of this API is org.springframework.transaction.PlatformTransactionManager.
Spring provides a number of implementations of this interface that support the most popular transaction-management APIs in Java.Like,org.springframework.jdbc.datasource. DataSourceTransactionManager,org.springframework.orm.hibernate.HibernateTransactionManager
org.springframework.orm.hibernate3.HibernateTransactionManager.
The Spring Bean factory does more than simply instantiate objects.It can also wrap the objects that it creates with interceptors.These interceptors are how Spring provides a simple,yet effective AOP(Aspect-Oriented Programming)implementation.AOP is the foundation of Spring Transaction Management.To make a POJO transactional you configure the bean factory to wrap it with TransactionInterceptor.One option is to use the @Transactional annotation on the interace,implementation class or individual methods.Another option is to write XML bean definitions that explicitly apply the TransactionInterceptor to the POJO.The XML is more verbose than the annotation but has the advantage of leaving the source code unchanged.It also works with older JDKs that dont' support annotations.

Spring doesn't implement transactions itself but is,instead, a wrapper around other transaction management APIs.Unlike EJB3,it gives you the flexibility of using either JTA or the transaction management APIs provided by ORM frameworks such as Hibernate.

In the next article of this series,we will explore more about Transaction Management in Spring and as well as AOP(Aspect Oriented Programming).

Suggested Video Tutorial

Spring 2.x by Rod Johnson (Founder of Spring framework)

Integration Testing with Spring by Rod Johnson

Spring vs EJB3.0 by Debu Panda


Spring Experience Video by Adrian Colyer
Adrian Colyer is the leader of the AspectJ open source project and a well-known industry expert on the topic of aspect-oriented programming (AOP)



Suggested Reading:


http://java.sys-con.com/read/180374.htm


http://static.springframework.org/spring/docs/2.5.1/reference/testing.html



http://static.springframework.org/spring/docs/1.2.x/reference/transaction.html



http://mike.hostetlerhome.com/2007/07/06/easier-unit-testing-in-spring/



http://dev2dev.bea.com/pub/a/2005/07/spring_transactions.html


Recommended Books



You can get this book from Here

Tuesday, January 15, 2008

Rich Internet Applications - One more Buzz word (Adobe Flex)

Along with SOA,BPM the other buzz word with regards to J2EE Application development in Java community now-a-days is about Rich Internet Applications-RIA.
Personally I do think strategically this is the most important aspect that needs to be covered or looked into by a seasoned Java/J2EE Architect ,that how best he can improve the usability and appearance of the corporate applications he is working on, because ultimately what matters to the users is better,scalable and enhanced GUI.Along with Web Services(SOA),Mobile Computing,BPM(Business Process Management),this is one area where Iam really focussed and I suggest every Senior Java/J2EE guys to consider having a look at.To start with,I guess every Java person ,who is interested in GUI development does try to acquaint himself with technologies with HTML,DHTML,CSS,JavaScript,Java AWT,Swing ,XHTML etc....And there is ever growing interest in building AJAX style web applications using different frameworks and technologies which I will harbor upon in this article down the line.So what is this RIA is all about?

To start with the basic definition of RIA is ,Rich Internet applications (RIA) are web applications that have the features and functionality of traditional desktop applications. RIAs typically transfer the processing necessary for the user interface to the web client but keep the bulk of the data (i.e., maintaining the state of the program, the data etc) back on the application server.
RIAs typically:
* run in a web browser, or do not require software installation
* run locally in a secure environment called a sandbox
Compared to RIAs,traditional web applications centered all activity around a client-server architecture with a thin client. Under this system all processing is done on the server, and the client is only used to display static (in this case HTML) content. The biggest drawback with this system is that all interaction with the application must pass through the server, which requires data to be sent to the server, the server to respond, and the page to be reloaded on the client with the response. By using a client side technology which can execute instructions on the client's computer, RIAs can circumvent this slow and synchronous loop for many user interactions.

All RIAs share one characteristic: they introduce an intermediate layer of code, often called a client engine, between the user and the server. This client engine is usually downloaded at the beginning of the application, and may be supplemented by further code downloads as the application progresses. The client engine acts as an extension of the browser, and usually takes over responsibility for rendering the application's user interface and for server communication.

Benefits
Because RIAs employ a client engine to interact with the user, they are:
* Richer. They can offer user-interface behaviors not obtainable using only the HTML widgets available to standard browser-based Web applications. This richer functionality may include anything that can be implemented in the technology being used on the client side, including drag and drop, using a slider to change data, calculations performed only by the client and which do not need to be sent back to the server, for example, a mortgage calculator.

* More responsive. The interface behaviors are typically much more responsive than those of a standard Web browser that must always interact with a remote server.

The most sophisticated examples of RIAs exhibit a look and feel approaching that of a desktop environment. Using a client engine can also produce other performance benefits:
* Client/Server balance. The demand for client and server computing resources is better balanced, so that the Web server need not be the workhorse that it is with a traditional Web application. This frees server resources, allowing the same server hardware to handle more client sessions concurrently.

* Asynchronous communication. The client engine can interact with the server without waiting for the user to perform an interface action such as clicking on a button or link. This allows the user to view and interact with the page asynchronously from the client engine's communication with the server. This option allows RIA designers to move data between the client and the server without making the user wait. Perhaps the most common application of this is prefetching, in which an application anticipates a future need for certain data, and downloads it to the client before the user requests it, thereby speeding up a subsequent response. Google Maps uses this technique to move adjacent map segments to the client before the user scrolls their view.

* Network efficiency. The network traffic may also be significantly reduced because an application-specific client engine can be more intelligent than a standard Web browser when deciding what data needs to be exchanged with servers. This can speed up individual requests or responses because less data is being transferred for each interaction, and overall network load is reduced. However, use of asynchronous prefetching techniques can neutralize or even reverse this potential benefit. Because the code cannot anticipate exactly what every user will do next, it is common for such techniques to download extra data, not all of which is actually needed, to many or all clients.

Shortcomings and restrictions

Shortcomings and restrictions associated with RIAs are:

* Sandbox. Because RIAs run within a sandbox, they have restricted access to system resources. If assumptions about access to resources are incorrect, RIAs may fail to operate correctly.

* Disabled scripting. JavaScript or another scripting language is often required. If the user has disabled active scripting in their browser, the RIA may not function properly, if at all.

* Client processing speed. To achieve platform independence, some RIAs use client-side scripts written in interpreted languages such as JavaScript, with a consequential loss of performance. This is not an issue with compiled client languages such as Java, where performance is comparable to that of traditional compiled languages, or with Flash movies, in which the bulk of the operations are performed by the native code of the Flash player.

* Script download time. Although it does not have to be installed, the additional client-side intelligence (or client engine) of RIA applications needs to be delivered by the server to the client. While much of this is usually automatically cached it needs to be transferred at least once. Depending on the size and type of delivery, script download time may be unpleasantly long. RIA developers can lessen the impact of this delay by compressing the scripts, and by staging their delivery over multiple pages of an application.

* Loss of integrity. If the application-base is X/HTML, conflicts arise between the goal of an application (which naturally wants to be in control of its presentation and behaviour) and the goals of X/HTML (which naturally wants to give away control). The DOM interface for X/HTML makes it possible to create RIAs, but by doing so makes it impossible to guarantee correct function. Because an RIA client can modify the RIA's basic structure and override presentation and behaviour, it can cause failure of the application to work properly on the client side. Eventually, this problem could be solved by new client-side mechanisms that granted an RIA client more limited permission to modify only those resources within the scope of its application. (Standard software running natively does not have this problem because by definition a program automatically possesses all rights to all its allocated resources).

* Loss of visibility to search engines. Search engines may not be able to index the text content of the application.

* Dependence on an Internet connection. While the ideal network-enabled replacement for a desktop application would allow users to be "occasionally connected" wandering in and out of hot-spots or from office to office, today the typical RIA requires network connectivity.And I think this year will decide whether RIA are here to stay or it goes off like smoke without fire.

Ok enough of talking about RIA,its benefits and shortcomings.Lets talk about what we are really concerned about, which framework or technology is the best for RIA,I think that should be the primary focus now rather than considering the potential or growth of RIA.There are many choices for us and they are:Adobe Flex/Flash,Ajax,JSF(yes it can also be used),JavaFX,Dojo,Swing,Google Web Toolkit,Google Gears,Eclipse RIA & Microsoft Silverlight.I guess with so many choices,the obvious question will be which one is the most efficient and best one for RIA.

Personally I do like Adobe Flex,The Flex SDK comes with a set of user interface components including buttons, list boxes, trees, data grids, several text controls, and various layout containers. Charts and graphs are available as an add-on. Other features like web services, drag and drop, modal dialogs, animation effects, application states, form validation, and other interactions round out the application framework.I do go through its documentation like Flex 2 Developers Guide,Building & Deploying Flex 2 applications,I must say this tool is here to stay.

There are, however, more specific and compelling reasons to adopt Flex. Flex builds on the advances made in the Java/J2EE community over the last decade. New Java converts to the Flex programming model will find the framework, language, and tools easy to learn, as there is a familiarity in the Flex IDE and the language structures, like the Flex Collections API. The Flex development tools offer the clearest link for current Java developers. The Flex IDE is built on Eclipse, which can be used as the stand-alone Flex Builder product or as an Eclipse plug-in. Virtually all Java developers have had some exposure to the Eclipse development environment. This is a huge benefit that speeds and enhances the learning process.

In addition to the IDE, Flex also has Ant Tasks for automated builds of Flex applications, whether they are integrated with a Java application or stand-alone. Once again, Ant is a technology Java developers have all been exposed to in the Java community. With Adobe's comprehensive suite of tools, integrating Flex into your skill set is natural and enjoyable.

In a multi-tiered model, Flex applications serve as the presentation tier. Unlike page-based HTML applications, Flex applications provide a stateful client where significant changes to the view don't require loading a new page. Similarly, Flex and Flash Player provide many useful ways to send and load data to and from server-side components without requiring the client to reload the view. Though this functionality offered advantages over HTML and JavaScript development in the past, the increased support for XMLHttpRequest in major browsers has made asynchronous data loading a common practice in HTML-based development too.

There are frameworks ranging from testing to MVC in Adobe Flex. A good example of this is the Cairngorm MVC framework. Cairngorm is written in ActionScript 3.0 and follows many of the Core J2EE patterns. It provides Flex developers with an MVC framework for structuring their Flex presentation code and the interactions with the business services. Flex also provides API's for multiple methods of integrating with backend services, including LiveCycle Data Services ES (Data Services), Web Services, and HTTP.

LiveCycle Data Services ES deploys in a Servlet/J2EE container and provides significant server-side infrastructure to Flex applications. Data Services offers a number of features, including remoting, publish/subscribe messaging, and data management (client-server synchronization, paging, notification, Hibernate adapter, etc). The simplest use allows a Java developer to expose Plain Old Java Objects (POJO's) as back-end services via a simple configuration. Objects are transferred to the client in a compact binary format called AMF3 and converted to ActionScript 3.0 classes, which is far more efficient in the transferring and rendering time than other implementations, like XML. Combining Data Services with the popular Java POJO-based frameworks, like Hibernate and Spring, creates a truly powerful combination for building enterprise applications.

Things you need to get started with Adobe Flex
Flex Builder 2
Flex Builder 2 is the new development tool that (although it is not necessary for Flex development because any text editor can be used) offers the most complete development environment for rapidly creating Flex applications. Because Flex Builder 2 has been built on top of the mature Eclipse IDE, it will be very familiar to developers who have already been developing software in other languages using Eclipse as their tool of choice. Eclipse is a development environment that was built with extendability in mind, and this can also work to the benefit of Flex developers because it can be customized to suit the needs of the Flex developer. Chapter 2 provides a more comprehensive look into Flex Builder 2.

Flex Free SDK 2
The Flex Software Development Kit (SDK) is a free download from Adobe and includes the Flex framework (component class library), compiler, and debugger. Using the text editor of your choice, you can create the ActionScript and MXML files for your application, and then compile to SWF using the SDK. The SDK allows for data communication via Web services, HTTP services, and Flash remoting with ColdFusion as the back-end server.

Flex Data Services (FDS)
FDS is the server version of Flex that must be installed under any Java 2 Enterprise Edition (J2EE) server. FDS is essentially the next generation of Flex 1.5, which was sold only as a server.

As well as a full commercial edition, the FDS server is available in an Express edition, which is free and available for commercial use (but is limited to one CPU without clustering).

FDS is made up of several components and capabilities, including the following:
Flex Messaging Services (FMS)
Publish-subscribe messaging
Data push
RPC services
Flex Messaging Services
FMS is one of the pieces that make up FDS, and it allows for the creation of applications that support real-time messaging, as well as collaboration. The messaging service has support for Java Message Service (JMS), as well as other existing messaging services, allowing for the creation of cross-platform chat applications.

Publish-Subscribe Messaging
FMS uses the producer/consumer publish-subscribe metaphor, which allows for the creation of co-browsing applications. To understand what is meant by a co-browser application, imagine a company’s customer service representative being able to make edits to a form on the user’s screen in real time while the user watches.

Data Push
Data push is the capability for the server to push data changes to the client without any user interaction or polling of the servers. This can be critical when an application has hundreds or thousands of users connected, and they can all see changes to business-critical data in real time. This is a feature that is available only when using the FDS server.

RPC Services
Remote procedure call (RPC) services are the suite of services used to connect to external data. They include the following:

WebService - The WebService component can be used to access any Web service that complies with the WSDL 1.1 standard and returns data formatted as Simple Object Access Protocol (SOAP) messages over HTTP.

HTTPService - The HTTPService component can send HTTP GET, POST, HEAD, OPTIONS, PUT, TRACE, or DELETE requests. It does not support multipart requests.

RemoteObjects - The RemoteObject component uses Action Message Format (AMF) to transfer data that is a binary format and is the fastest of the RPC services. It is an ideal way to interact with server-side Java objects that are within the FDS server’s source path. It can also be used to connect to local or even remote ColdFusion servers. Both Java objects and ColdFusion components can be mapped to ActionScript objects, allowing for seamless integration between the server-side and client-side objects.

The WebService and HTTPService components are included for free with the Flex SDK, whereas the RemoteObject component is available only for use with the FDS server (Commercial or Free Express Edition) or ColdFusion 7.02.

Flex Charting
The Flex charting components are a set of rich charting components that enable easy development of professional dashboard and business intelligence (BI) systems. The charting components are sold as a stand-alone product or bundled with Flex Builder 2

Flex 2 Programming Model
The Flex 2 Programming Model consists of MXML, ActionScript, and the Flex class library. To build a full-fledged application, you must have a good knowledge of all these technologies. To start off, you are introduced to the basics of MXML. Then you are shown how ActionScript and MXML work together to create powerful, rich user interfaces.

The third element of the programming model is the Flex 2 Framework, which contains Flex components, managers, and behaviors. This component-based development model allows developers to incorporate pre-built components, extend the component library by creating new components, or combine pre-built components to create composite components.

MXML
The first element of the programming model, MXML, is an XML language that defines the user interface for an application. MXML is also used to define non-visual aspects such as server-side data sources and bindings between the user interface and the server side.

To write a Flex application, you must be able to write MXML and ActionScript. As mentioned earlier, MXML is an XML language that is used to lay out your user interface.

MXML is very similar to HTML in that it provides tags for user interface elements. If you have worked with HTML, then MXML should be very familiar to you. MXML has a much broader tag set than HTML, and defines visual components such as data grids, buttons, combo boxes, trees, tab navigators, and menus, as well as non-visual components, Web service connections, data binding, and effects.

The biggest difference between HTML and MXML is the MXML-defined file that is compiled into a Shockwave file (SWF) and rendered by the Flash Player. MXML can be written in a single file or in multiple files. MXML requires that you close off every tag that you declare in your Flex application. Otherwise, the Flex compiler will throw an error.

The tag is always the root tag of a Flex application. The tag defines a Panel container that includes a title, title bar, status message, border, and an area for its children (that is, the control). The tag is a Label control that simply displays text.

ActionScript
The second element of the programming model, ActionScript, extends the functionality of a Flex application. ActionScript provides control and object-manipulation features that are not available in strict MXML.

The ActionScript programming language is used in Adobe’s Flash Player. Included are built-in objects and functions that allow you to create your own objects and functions like many object-oriented programming (OOP) languages.

ActionScript 3.0 offers a robust programming model that is more familiar to developers with basic knowledge of OOP. ActionScript is executed by the ActionScript Virtual Machine (AVM), which is part of the Flash Player. The code is compiled into a bytecode format by the compiler, such as the one built into Flex Builder 2.

ActionScript and JavaScript are very similar, so being familiar with JavaScript will make your life easier when using ActionScript. JavaScript is derived from The European Computers Manufacturers Association (ECMA) document ECMA-262, which is the international standard for the JavaScript language. ActionScript is based upon the ECMA-262 Edition 4 specification, so this is where the similarities come in between the two languages.

ActionScript 3.0 contains a lot of new features, such as run-time exceptions, run-time types, sealed classes, method closures, ECMAScript for XML (E4X), regular expressions, namespaces, and new primitive types. All these new features allow the developer to speed up the development process.

One important point to note is that Flex Builder 2 converts all MXML files into ActionScript before the code is compiled into bytecode for use with the AVM.

ActionScript in MXML
Flex developers will find that ActionScript extends the capabilities of Flex when developing applications. In ActionScript, you can define event listeners, create new classes, handle callback functions, and define getters and setters, packages, and components.

Following are some of the ways that ActionScript can be used in Flex applications:

ActionScript is inserted between the tags. This code can be comprised of new functions, error handling, or events, and can perform any other tasks your Flex application may require.

Create new components in ActionScript.

Create new components and compile into SWC files (which are external components compiled to be reused in many applications).
Extend existing components with ActionScript classes.
Take advantage of ActionScript support for OOP concepts such as code reuse, inheritance, encapsulation, and polymorphism.
Use global ActionScript functions that are available in any part of an SWF file where ActionScript is used, or in any user-defined class.
Use the standard Flex components that comprise the Flex Class Libraries. All the components and libraries are written in ActionScript.

Overview of ActionScript Compilation Process
A Flex application can consist of MXML files, ActionScript classes, SWF files, and SWC files.

The Flex compiler transforms the main MXML file and its children into a single ActionScript class linking in all the reference-imported classes. Once the transformation is complete, the end result is a single SWF file that can be deployed on the server.

Every time you make changes to your application, a new SWF file is generated. You may find it more convenient to remove the reusable components and compile those into SWC files, which can be included in a library path for your application.

Statements and expressions must be wrapped in functions; otherwise, you will receive a compiler error. Also, you cannot define classes or interfaces in the tag, because the MXML file you have defined is a class in itself.

You may have noticed the odd CDATA construct. This is used to tell the compiler not to interpret the script block as XML, but rather as ActionScript. The tag must be located at the top-level component tag of the MXML file. Multiple tags can be defined, but for readability, it’s recommended to have them in one location.

In MXML, you can use ActionScript to refer to visual or non-visual components. You do this by specifying the id property of the component in MXML. Then you use id to refer to the component in ActionScript.

If you want to access the control, you must refer to the id property in ActionScript. To do this, the following code must be used:
var str:String = lbl1.text;

The code gets the value from the Label control named lbl1.

Import and Include
There is a noticeable difference between the terms “importing” and “including” in reference to ActionScript. Importing is adding a reference to a class file or package so that you can access the objects and properties of the external classes, as shown in the following example:

import mx.controls.TextInput;

Including ActionScript is copying the lines of code of an external ActionScript file into another. This can either be done in the tag using the include directive, or the tag to add the ActionScript into your Flex applications.

Introduction to ActionScript Components
This section provides a brief overview of how to create reusable components using ActionScript. Later in this book, you will build more complex components using MXML and ActionScript.

Custom components can contain graphical elements, define some kind of business logic, or extend existing components in the Flex framework. Defining your own components in ActionScript has several advantages:

Divide your application into individual models that can be developed and maintained separately.

Implement commonly used logic within the components.

Build a collection of components that can be reused among all your Flex applications.

When creating custom components, you may find it useful to extend the component from the Flex class hierarchy. This allows you to inherit functionality already built into the Flex components.

As shown in the following example, you can define a custom TextInput and derive it from the Flex TextInput control:


package myComponents
{
public class MyTextInput extends TextInput
{
public function MyTextInput()
{
...
}
...
}
}

The filename of the control MyTextInput must be in a filename called MyTextInput.as and stored at the root of your Flex application in a subdirectory name myComponents. As you may have already picked up, the package name reflects the location of the component, myComponents.

Flex Class Library
The Flex 2 Framework contains Flex managers, components, and behaviors. The component-based model allows developers to incorporate pre-built components, create new ones, or combine components into composite components.

The following lists some of the common packages that you will use in your Flex application:
mx.controls - Flex user interface controls

mx.collections - Flex collection components

mx.charts - Flex charting components

mx.utils - Flex utility classes

flash.events - Flex event classes

flash.net - Flex classes for sending and receiving from the network, such as URL downloading and Flash Remoting

Just have a look at the Adobe Developer Connection,http://www.adobe.com/devnet/ria/ and you will surely agree that it is the most useful tool and for samples visit here,http://www.adobe.com/devnet/flex/index.html?tab:samples=1

Monday, January 14, 2008

Implementing "Drag and Drop" feature in Web Applications

Today I would like to shed some light on how best can we implement drag n feature in web applications.Gone are the days of lame users who used to browse web sites just to gather some information,send mails,watch movies,online shopping etc.Now-a-days users want more and more interaction and savvy stuff to be seen on the websites.With the advent of new technologies,users tastes have also changed and so to their needs and demands.I personally like the liveliness of new Yahoo mail,Personal google mail or iGoogle.This makes me wonder about the sleekness of drag and drop feature implementation in these sites and how easy it has become to implement such scenarios using frameworks & APIs like Yahoo UI(very informative),Google Web Toolkit(my personal best),Ajax,Dojo,SWT,Scriptaculous or for that matter the cumbersome JavaScript(JavaScript is not everyone's language of choice),phew so many choices and options.
If you are a Web Developer,now a days it has become a de-facto standard or necessity for you to have experience in implementing drag and drop features in the web applications you are dealing at customer sites.Here I would like to present different solutions that can be used(& how) to develop drag and drop features in a website.

First, the basic definition of Ajax is ,AJAX (Asynchronous JavaScript and XML), or Ajax, is a group of inter-related web development techniques used for creating interactive web applications. A primary characteristic is the increased responsiveness and interactiveness of web pages achieved by exchanging small amounts of data with the server "behind the scenes" so that the entire web page does not have to be reloaded each time the user performs an action. This is intended to increase the web page's interactivity, speed, functionality, and usability.

AJAX is asynchronous in that extra data is requested from the server and loaded in the background without interfering with the display and behavior of the existing page. JavaScript is the scripting language in which AJAX function calls are usually made.[1] Data is retrieved using the XMLHttpRequest object that is available to scripting languages run in modern browsers. There is, however, no requirement that the asynchronous content be formatted in XML.

AJAX is a cross-platform technique usable on many different operating systems, computer architectures, and web browsers as it is based on open standards such as JavaScript and the DOM. There are free and open source implementations of suitable frameworks and libraries.

To start with let us learn how can we implement AJAX style drag and drop using Scriptaculous,is a collection of Web 2.0 style JavaScript libraries that help web developers to easily add visual and ajax effects to projects.It provides easy-to-use cross-browser support user interface Javascript libraries.For example visit here,Demo.
First download the latest version and extract it folder of your choice and then put prototype.js, scriptaculous.js, builder.js, effects.js, dragdrop.js, slider.js and controls.js in a directory of your website, e.g. /javascripts and then provide a link to the scripts in the head of your document like,

script src="javascripts/prototype.js" type="text/javascript"
script src="javascripts/scriptaculous.js" type="text/javascript"

By default, scriptaculous.js loads all of the other javascript files necessary for effects, drag-and-drop, sliders, and all of the other script.aculo.us features.
You can also use effects inside event handlers and you can pass extra options to the effect like ‘duration’, ‘fps’ (frames per second), and ‘delay’.
"div onclick="new Effect.BlindUp(this, {duration: 16})"
For the source code for implementing a simple shopping cart using Script.aculo.us,visit here

2)Next in line is DOJO,Dojo is an Open Source toolkit that allows you to easily build dynamic capabilities into web pages and any other environment that supports JavaScript. Dojo provides components that let you make your sites more useable, responsive, and functional. With Dojo you can build degradeable user interfaces more easily, prototype interactive widgets quickly, animate transitions, and build AJAX-based requests simply. Dojo layers these capabilities onto a lightweight packaging system which forms the core of Dojo. When you write scripts with Dojo, you can include as few or as many of the available APIs as you need, and your app will only include what it uses.
Easily extensible Drag and Drop support in DOJO is provided by this API,dojo.dnd.*
For the list of classes and methods in this API , visit http://manual.dojotoolkit.org/dnd.html
For a simple example on implementing drag and drop using DOJO,visit here.

3)Yahoo UI -Drag & Drop
The Yahoo! User Interface (YUI) Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX. The YUI Library also includes several core CSS resources. All components in the YUI Library have been released as open source under a BSD license and are free for all uses.
Download YUI version 2.4.1, including full API documentation and more than 230 functional examples from Sourceforge.
For an example to implement drag and drop using Yahoo UI , visit here

4)And finally,Google Web Toolkit(my fav)
Google Web Toolkit (GWT) is an open source Java software development framework that makes writing AJAX applications like Google Maps and Gmail easy for developers who don't speak browser quirks as a second language.
With GWT, you can develop and debug AJAX applications in the Java language using the Java development tools of your choice. When you deploy your application to production, the GWT compiler translates your Java application to browser-compliant JavaScript and HTML.Download GWT from here.
Here's the GWT development cycle:
1. Use your favorite Java IDE to write and debug an application in the Java language, using as many (or as few) GWT libraries as you find useful.
2. Use GWT's Java-to-JavaScript compiler to distill your application into a set of JavaScript and HTML files that you can serve with any web server.
3. Confirm that your application works in each browser that you want to support, which usually takes no additional work.
Some of the benefits of developing with GWT:
* You can use all of your favorite Java development tools (Eclipse, IntelliJ, JProfiler, JUnit) for AJAX development.
* Static type checking in the Java language boosts productivity while reducing errors.
* Common JavaScript errors (typos, type mismatches) are easily caught at compile time rather than by users at runtime.
* Code prompting/completion is widely available.
* Automated Java refactoring is pretty snazzy these days.
* Java-based OO designs are easier to communicate and understand, thus making your AJAX code base more comprehensible with less documentation

http://code.google.com/p/gwt-dnd/,is GWT extension library which adds drag-and-drop support to new or existing applications built with the Google Web Toolkit (GWT).Visit here to know how to add GWT to Eclipse IDE.And sample source code is here

Other options are,Mochikit

Also read this article for implementing drag and drop using Java 2.
http://www.javaworld.com/javaworld/jw-03-1999/jw-03-dragndrop.html

Suggested Video Tutorial
Google Web Toolkit

Saturday, January 12, 2008

Tata Nano-just $2500 car unveiled in India

The Tata’s world’s cheapest Rs 1-lakh($2500) car was launched(unveiled) recently at the 9th Auto Expo in New Delhi by Chairman Ratan Tata. The car is named as “NANO”



Mr. Ratan Tata said that this car meets all safety and emission norms and emissions are lower than 2 wheelers. The car has 21% more interior space than much popular Maruti 800, which makes it more special. The car would be indeed launched at a price 1 lakh + VAT + Transportation.

Speaking at the unveiling ceremony at the 9th Auto Expo in New Delhi, Mr. Ratan N. Tata said,“I observed families riding on two-wheelers , the father driving the scooter, his young kid standing in front of him, his wife seated behind him holding a little baby. It led me to wonder whether one could conceive of a safe, affordable, all-weather form of transport for such a family. Tata Motors Engineers and Designers gave all their energy and efforts for about four years to realise this goal. Today, we indeed have a People’s Car, which is affordable and yet built to meet safety requirements and emission norms, to be fuel efficient and low on emissions. We are happy to present the People’s Car to India and we hope it brings the joy, pride and utility of owning a car to many families who need personal mobility.”

Specifications and features of 1 lakh car Nano:

* Stylish, comfortable

Yet with a length of 3.1 metres, width of 1.5 metres and height of 1.6 metres, with adequate ground clearance, it can effortlessly manoeuvre on busy roads in cities as well as in rural areas. Its mono-volume design, with wheels at the corners and the powertrain at the rear, enables it to uniquely combine both space and manoeuvrability, which will set a new benchmark among small cars.

When launched, the car will be available in both standard and deluxe versions. Both versions will offer a wide range of body colours, and other accessories so that the car can be customised to an individual’s preferences.

* Fuel-efficient engine

The People’s Car has a rear-wheel drive, all-aluminium, two-cylinder, 623 cc, 33 PS, multi point fuel injection petrol engine. This is the first time that a two-cylinder gasoline engine is being used in a car with single balancer shaft. The lean design strategy has helped minimise weight, which helps maximise performance per unit of energy consumed and delivers high fuel efficiency. Performance is controlled by a specially designed electronic engine management system.

* Meets all safety requirements

The People’s Car’s safety performance exceeds current regulatory requirements. With an all sheet-metal body, it has a strong passenger compartment, with safety features such as crumple zones, intrusion-resistant doors, seat belts, strong seats and anchorages, and the rear tailgate glass bonded to the body. Tubeless tyres further enhance safety.

* Environment-friendly

The People’s Car’s tailpipe emission performance exceeds regulatory requirements. In terms of overall pollutants, it has a lower pollution level than two-wheelers being manufactured in India today. The high fuel efficiency also ensures that the car has low carbon dioxide emissions, thereby providing the twin benefits of an affordable transportation solution with a low carbon footprint.
(For more information visit www.tatapeoplescar.com )

Nano, the world’s cheapest car, is expected to be commercially launched in the second half of 2008.

The 1 lakh car was a major concern for the environmentalists and other who raised concern about the pollution and concession caused by the car if it was wide accepted in the market. The target audience of the car is basically two wheeler buyers who would like to own a car and also second hand small car buyers. Mr Tata refuted these claims and said that the car would be least polluting and as far as congestion is concerned, something that needs to be acted upon is the infrastructure. Stopping someone from making a car that would be affordable to common people nation wide is not an answer.

The car if successful will definitely revolutionize the four wheeler segment in the country and around the world.

Some pictures of "Nano"


Friday, January 11, 2008

Things to watch out for Java Developer in 2008-Part 3

In continuation of the series of articles I started discussing about the technologies to watch out for Java Developer in 2008,in this final part I would like mention about
Google Android and SOA(Security).
I would like to start with SOA security.SOA has been such a buzzword since last year and more & more enterprises are now turning to a new IT architectural approach called Service-Oriented Architecture (SOA).And there in lies the challenge for managing the security of SOA enterprise applications.Security in IT can be broadly classified as network security,
platform security, and application security .Application security is the main area of focus in SOA architecture

The basic definition of SOA is ,Service Oriented Architecture (SOA) is an architectural style that guides all aspects of creating and using business processes, packaged as services, throughout their lifecycle, as well as defining and provisioning the IT infrastructure that allows different applications to exchange data and participate in business processes loosely coupled from the operating systems and programming languages underlying those applications. SOA represents a model in which functionality is decomposed into distinct units (services), which can be distributed over a network and can be combined together and reused to create business applications.These services communicate with each other by passing data from one service to another, or by coordinating an activity between two or more services.

Web services were developed as a way to enable the creation of reusable code, simplify development, and streamline system integration. While these goals were met, the open standards that emerged have not yet fully addressed security. Specifically, XML, SOAP, WSDL, and UDDI are open standards that enable the transmission and description of data and procedure calls between systems.And none of these open standards have inherent security model.So why do we need open standards?The answer is,Open standards must be adopted to enable integration across enterprises.
Orchestration of business processes across multiple suppliers, partners,
and customers must be possible,thats why.

In the context of SOA, instead of securing a single application, you should
secure the architecture. On one hand, you need to keep the services open so that applications, both internal and external, can easily reuse them. On the other hand, unless these services are properly secured, they can be misused to cause security breaches. How do we secure services without reducing reusability?So how best can we secure our SOA applications?
The answer is ,standards such as WS-Security, SAML, WS-Trust and WS-SecurityPolicy and Application-oriented Networking (AON).

SOA adopts three approaches for application security and they are Message-level security,Security as a service,Policy-driven security.
WS-Security allows message-level security to be implemented with SOAP.
A security service can offer applications the ability to authenticate, authorize,
encrypt/decrypt messages, sign messages/verify signatures,and log messages.It may also scrub messages to protect applications against known and unknown vulnerabilities.SOA supports standards such as Security Assertion Markup Language (SAML) and WS-Trust that can be used to implement such a service.

A security policy declaration becomes handy in enabling Security requirements and mechanisms not to be hard-wired into applications.Thats where security policy comes in handy.It separates security logic from business logic, leaving the former to security specialists. It becomes easier to ensure consistency of security enforcement across multiple applications.
WS-SecurityPolicy is the standard that is emerging to make this new approach possible
Other standards are,WS-Federation Web Services Federation Language
This specification defines mechanisms to allow different security realms to federate by allowing and brokering trust of identities, attributes, authentication between participating Web services.
WS-Security Describes enhancements to SOAP messaging to provide quality of protection through message integrity, message confidentiality, and single message authentication.
WS-SecureConversation Defines extensions that build on WS-Security to provide secure communication. Specifically, it defines mechanisms for establishing and sharing security contexts, and deriving session keys from security contexts.
WS-Trust Defines extensions that build on WS-Security to request and issue security tokens and to manage trust relationships.
XML-Encryption Specifies a process for encrypting data and representing the result in XML.
Application-oriented Networking (AON) Application-oriented networking has arisen in response to increasing use of XML messaging (combined with related standards such as XSLT, XPath and XQuery) to link miscellaneous applications, data sources and other computing assets. Many of the operations required to mediate between these different participants, or to monitor their exchanges, can be built into network devices that are optimized for the purpose. The rules and policies for performing these operations, also expressed in XML, are specified separately and downloaded as required

For further understanding,read the following articles.
“Web Services Architecture,”is available at
http:// www.w3.org/TR/2004/NOTE-ws-arch-20040211/.

“Security in a Web Services World: A Proposed Architecture and Roadmap,” a white paper published in 2002 by IBM and Microsoft, is available at http://www.ibm.com/developerworks/library/ws-secmap/.

Apache WSS4J,a publicly available extension of Apache Axis 1.x to add limited support for security, is available at http://ws.apache.org/wss4j/.

Apache Rampart, a publicly available extension of Apache Axis2 to add limited support for security, is available at http://ws.apache.org/axis2/modules/
rampart/1_0/security-module.html.

Cisco’s Application-Oriented Networking (AON) product page is at
http://www.cisco.com/go/aon.

B)I must say Iam excited to conclude this series of "Things to watch out for Java Developer in 2008" by talking about Google Android
.With so much buzz and excitement around smartphones specially Apple iPhone,will Google be left behind to become a leader in that niche market as well.I must say I always keep an eye with whatever Google comes up with,be it the Google Maps,Google Web Toolkit,the Search Engine itself and Google Earth Sky.And AT&T is the last remaining major wireless carrier in the United States to not publicly endorse Google's Android initiative. Sprint,Nextel,Sybase,Motorola,Qualcomm,HTC and T-Mobile had both come out in favor of the platform when they joined the Open Handset Alliance, a multinational group with over 30 members dedicated to promoting Android, in November last year.And thats why developing applications for mobile devices(mobile computing) is something every Java Developer(me definitely) should also consider seriously now and adding technologies like Blackberry Java Development Environment,IBM J9 & Google Android to their career graph.I must say Iam completely bowled over by Google Android.
In comes Google Android,
the first complete,open and free mobile platform.
Android is the first truly open and comprehensive platform for mobile devices. It includes an operating system, user-interface and applications -- all of the software to run a mobile phone, but without the proprietary obstacles that have hindered mobile innovation.The Android platform is a software stack for mobile devices including an operating system, middleware and key applications. Developers can create applications for the platform using the Android SDK. Applications are written using the Java programming language and run on Dalvik, a custom virtual machine designed for embedded use which runs on top of a Linux kernel.The features of Android are,
* Application framework enabling reuse and replacement of components
* Dalvik virtual machine optimized for mobile devices
* Integrated browser based on the open source WebKit engine
* Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
* SQLite for structured data storage
* Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
* GSM Telephony (hardware dependent)
* Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
* Camera, GPS, compass, and accelerometer (hardware dependent)
* Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE
The architecture of Android SDK is,
To develop Android applications using the code and tools in the Android SDK, you need a suitable development computer and development environment, as described below.
Supported Operating Systems
* Windows XP or Vista
* Mac OS X 10.4.8 or later (x86 only)
* Linux (tested on Linux Ubuntu Dapper Drake)
Supported Development Environments
Eclipse IDE Eclipse 3.2, 3.3 (Europa)
Eclipse JDT plugin (included in most Eclipse IDE packages)
+ WST (optional, included in most Eclipse IDE packages)
JDK 5 or JDK 6 (JRE alone is not sufficient)
o Not compatible with Gnu Compiler for Java (gcj)
o Android Development Tools plugin (optional)
o Not compatible with Gnu Compiler for Java (gcj)
o Apache Ant 1.6.5 or later for Linux and Mac, 1.7 or later for Windows


Suggested Reading

http://code.google.com/android/

Suggested Video Tutorial
Android Architecture-part 2


Android APIs


Android Demo


Thats all for now!

Speak up! Say whatever you have to say

Wednesday, January 9, 2008

Things to watch out for in 2008 for Java Developer - Part 2

In the first part of this series " Things to watch out for in 2008 for Java Developer-Part 1", I did mention about Scala,Groovy and Gant.And in continuation of that series,in this part let me discuss about other technologies ,which I think will take huge strides in J2EE application development,if not already.I assume the readers of this article did read the Part 1 article,though its not a primer for this part.

To start with,let me start with defining what scripting language is (thanks to Guillaume Laforge,project manager for Groovy and the initiator of Grails).
"Usually, scripting languages refer to languages which are interpreted, but not compiled. They are mostly used and live on the command-line, in shell environments, like bash. Those languages are often used to script some live applications, objects or components, to manipulate them programmatically, and potentially interactively.And scripting languages come in handy for prototyping spikes, for small to mid-sized projects where the expressivity matters more, or for integrating some customized logic to be interpreted or changed at runtime for bigger enterprise applications"

And I would like to start with Jython
Though it has been available as open-source from Sourceforge since 2000,what perplexes me is the lack of interest and usage of this software.I agree it has evolved from Python and not many Java J2EE n-tier enterprise applications tend to use it(I might be wrong,but I personally never come across any requirements which need Jython),I dont see it losing in race with JRuby or Groovy,though they are also one to watch out for,but given how easy it is to learn and on its roadmap(next release v2.5) this year(hopefully) has extensive support for JDK5.0 features like annotations,generics the buzz words now and almost all enterprises turning towards Java 5 (excluding some old beasts who never dare treading on with evolving world) I would definitely like to add this to my skills repertoire . And for the following reasons,Jython is an implementation of Python that has been seamlessly integrated with the Java platform. Python is a powerful object-oriented scripting language used primarily in UNIX environments.
Jython is extremely useful because it provides the productivity features of a mature
scripting language while running on a JVM. Unlike a Python program, a Jython
program can run in any environment that supports a JVM.And you would agree if you see the below excerpts,and I thank Weiqi Gao for his article here.Since Python (the language implemented by Jython) has a richer set of features than JavaScript, Jython provides more convenience for the exploratory Java programmer. Let's try out some examples in Jython:

* Java classes and packages can be imported using the Python import statement (Note the extra work Jython does for you, compared to Java):
>>> import java # Import the java 'module' so that we can use names therein
>>> java # This works now

>>> java.awt # Surprise, this works too

>>> from java.awt import * # Import all names from the java.awt 'module' into he current 'module'
>>> Frame # We can now refer to java.awt.Frame as simply Frame
Instantiating a Java object is straightforward (you don't need the 'new' when instantiating an object in Python):
*
>>> f = Frame("A Java Frame in Jython")
>>> b = Button("Hello")
>>> f.add(b); f.pack() JavaBeans style properties (defined by getter and setter methods) can be accessed directly:
*
>>> f.visible = 1 # In Python, 1 is true, 0 is false Java interfaces can be implemented with Python code:
*
>>> class MyActionListener (java.awt.event.ActionListener):
... def actionPerformed(self, event): # Note the extra self argument
... print("World")
>>> listener = MyActionListener()
>>> b.addActionListener(listener) Java classes can be extended with Python code, (however Python's multiple inheritance does not apply when Java classes are extended):
*
>>> class MyWindowListener (java.awt.event.WindowAdapter):
... def windowClosing(self, event):
... from sys import exit; exit() # Calling Python's sys.exit() to rather than Java's System.exit()
>>> adapter = MyWindowListener()
>>> f.addWindowListener(adapter)

Jython makes creating Java arrays easier through the jarray module:

>>> from jarray import array, zeros
>>> array([1,2,3], 'i')
array([1, 2, 3], int)
>>> from java.util import HashMap
>>> a = array([HashMap(), HashMap()], HashMap)
array([{}, {}], java.util.HashMap)

Jython goes one step further than Rhino in JavaBeans scripting. All properties and event listener methods can be assigned at object construction time using keyword arguments:

>>> f = Frame("A Java Frame in Jython", visible=1, windowClosing=exit)

This is roughly equivalent to the following Java code

Frame f = new Frame("A java Frame in Jython");
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exit();
}
});


B)Next in line is other scripting language in Java,JRuby, though I didnt mention about it in my part 1 article,I would like write something about it,that way we can compare it with Jython as well here.
For the popularity,Ruby on Rails has gained so far,it comes as no surprise as to so much interest in JRuby.Ruby is a full-featured object-oriented language. But there are many significant differences compared to Java. Ruby is dynamically typed and runs in a source-code interpreter, and it conveniently supports metaprogramming as well as the procedural and functional paradigms. Java has static typing. You declare the type of each variable, and then, during compilation, you get an error message if you use a variable of the wrong type. Ruby, on the other hand, has dynamic typing: You don't declare types for variables or functions, and no type-check occurs until runtime, when you get an error if you call a method that doesn't exist. Even then, Ruby doesn't care about an object's class, just whether it has a method of the name used in the method call and JRuby is a Java implementation of the Ruby platform. Ruby
can run directly on mainstream operating systems with a C runtime, and is starting to run on .NET's CLR. When you program in JRuby you primarily use Ruby's libraries which are implemented in Java, and may also use Java's libraries at your discretion. If you stick to Ruby's libraries, or at least wrap any foreign elements, you can run Ruby
programs on the C, Java, or (in time) .NET runtimes. So you can use JRuby to both run Ruby programs on the JVM and as a language for scripting the JVM. The fact that JRuby is a Ruby platform on the JVM means that in JRuby you have two kinds of objects - JRuby objects and Java objects.There are times when you need to know whether you're dealing with a Java string or a JRuby string.
Some JRuby examples are , http://www.codecommit.com/blog/java/rapid-prototyping-with-jruby
Thanks to Martin Fowler

C)And I would like end Part 2 with Rake.
Rake is a software build tool similar to Ant.The tool is written in the Ruby programming language and the Rakefiles (equivalent of Makefiles in make) use Ruby syntax. It was originated by Jim Weirich.
Rake uses Ruby's anonymous function blocks to define various tasks, allowing the use of the Ruby syntax. There's a library of common tasks available, for example, functions to do common file-manipulation tasks and a library to remove compiled files (the "clean" task). Like Make, Rake can also synthesize tasks based on patterns (for example, automatically building a file compilation task based on filename patterns). Rake is now part of the standard library form Ruby version 1.9.
And go through this article by Martin Fowler for clear understanding about Rake.
http://martinfowler.com/articles/rake.html

Monday, January 7, 2008

Things to watch out for in 2008 for Java Developer- Part 1

Life of a seasoned Java Developer is never the same , I did hear this quote some time back "Life is like a Wave with Tides and currents"-I will add "Life of a Java Developer is like a Wave" not even everyday.He has to constantly keep an eye on emerging technologies ,which one to choose ,which one will further increase his caliber and which one will promptly for sure increase his contract tenure(if you are a consultant)and which one will keep him in the good eyes of his supervisor.Now that another year has started and with it comes different challenges to face for a Java Developer,so much development and so
many tools or frameworks are coming in J2EE environment,I choose to discuss and mention about the technologies which I think will take 2008 by storm and they are Scala,Groovy,Raven,Gant,Jython,Rake,Google Android not necessarily in that order.
The salient features of these technologies are :

1)Scala- Scala -http://www.scala-lang.org/ is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. It is also fully interoperable with Java.
Scala is the successor of Funnel, a language based on join calculus.

Scala is object-oriented

Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits. Class abstractions are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance.
Scala is functional

Scala is also a functional language in the sense that every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. Scala's case classes and its built-in support for pattern matching model algebraic types used in many functional programming languages.

Furthermore, Scala's notion of pattern matching naturally extends to the processing of XML data with the help of right-ignoring sequence patterns. In this context, sequence comprehensions are useful for formulating queries. These features make Scala ideal for developing applications like web services (external link).

2)Groovy http://groovy.codehaus.org/
"Groovy is like a super version of Java. It can leverage Java's enterprise capabilities but also has cool productivity features like closures, builders and dynamic typing. If you are a developer, tester or script guru, you have to love Groovy."

Groovy...

* is an agile and dynamic language for the Java Virtual Machine
* builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
* makes modern programming features available to Java developers with almost-zero learning curve
* supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain
* makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
* increases developer productivity by reducing scaffolding code when
developing web, GUI, database or console applications
* simplifies testing by supporting unit testing and mocking out-of-the-box
* seamlessly integrates with all existing Java objects and libraries
* compiles straight to Java bytecode so you can use it anywhere you can use Java
For further understanding, go through this article published in Java Lobby,it atleast gets you started on this language. http://www.javalobby.org/articles/groovy-intro1/

I tried to find out how different is this from Ruby,which is also Object oriented scripting language and then I came across some blogs/articles like this one by Jon Tirsén ,I must say I particularly liked this bit of info , "Groovy’s got a bunch of really nice Rubyesque features like closures, syntax for advanced data structures, inline strings and so on but it’s also very tightly integrated into the Java platform. You can compile a Groovy script directly into a .class file and that’s just going to be like any class in Java and vice versa you can reuse any Java class and library within Groovy"
3)Gant - http://gant.codehaus.org/

Gant is a build tool for scripting Ant tasks using Groovy instead of XML to specify the build logic. A Gant build specification is a Groovy script and so can bring all the power of Groovy to bear directly, something not possible with Ant scripts. Whilst it might be seen as a competitor to Ant, Gant uses Ant tasks for many of the actions, so Gant is really an alternative way of doing builds using Ant, but using a programming language rather than XML to specify the build rules.