Sunday, October 7, 2007
JavaFx - New RIA[Rich Interactive Applications] for content Driven web!
Open Source
https://openjfx.dev.java.net/
- The JavaFX Pad Application
- References
http://java.sun.com/developer/technicalArticles/scripting/javafxpart1/
More from experts:
JavaFX Script, is an open-source scripting language designed to facilitate rapid content authoring. JavaFX Script provides a highly-expressive syntax for declarative construction of 2D graphics and dynamic user interfaces. Although JavaFX Script is statically typed, the language is heavily inspired by popular dynamic programming languages like Python and incorporates compelling syntactic features like support for list comprehensions and first-class functions.
JavaFX isn't a completely independent runtime; it is essentially designed as a layer that sits on top of Java in order to make Java better-suited for rich application development. There are advantages and disadvantages to this approach. Sun clearly went to great lengths to make sure that JavaFX uses as much existing Java infrastructure as possible in order to simplify the process of integration. As a result, JavaFX feels like a very natural extension of the Java ecosystem. Developers can use Java libraries directly in JavaFX Script, and the language's declarative syntax for interface development is tightly bound to Swing and Java2D. The downside is that JavaFX Script doesn't really give developers the ability to do much they couldn't do already, its function is primarily to make existing Java technologies easier to use together.
As a result of JavaFX's dependence on existing Java technologies, developers with Java expertise will find that their existing skills easily translate over to JavaFX development. The broad availability of existing libraries for Java also ensures that a lot of useful functionality is available in JavaFX right out of the box. Additionally, since JavaFX runs on top of the JRE, it is highly portable and can target a wide variety of platforms.
Although JavaFX has a lot of potential, the technology also has a lot of weaknesses. JavaFX Script fixes many of Java's most frustrating syntactic deficiencies, but at the present time, very few convenience mechanisms are provided to support the kind of functionality currently required by modern interactive web applications. In particular, I think that JavaFX Script really needs some heavy syntactic sugar for consuming and manipulating remote XML and JSON content. One thing it does seem to handle relatively well, however, is integration of embedded HTML for application styling and content.
Wait and see how it progresses.......................
Saturday, October 6, 2007
SOA - Only XML ?
•XML documents: Rendering a request or response as an XML document tends to be both CPU and memory intensive
•Networking: Passing textually-encoded XML documents is a poor use of bandwidth
•Connection Management: Connectionless HTTP is far more expensive than a socket
•Parsing: Validation and parsing of XML documents is extremely CPU intensive
•Summary: Big money, high latency
Appropriate Uses
•Exposing Platform-Independent Services
–XML-based services are the one thing that Java and Microsoft .NET can agree on
•Loose Coupling
–The service provider and the service consumer can be completely unknown to each other
•Public Network Capable
–Securable at the low level (e.g. HTTPS) and the high level (document signing, encryption, etc.)
•Defensible Uses
–Among separate applications
–Among different organizations
Other Options
XML-based SOA has appropriate uses
•SOA and its underlying principles do not require SOAP, XML, HTTP, etc.
•Java has a rich set of built-in capabilities for supporting SOA withinan application, such as:
–JMS –Message bus-based SOA
–RMI –Synchronous Java-centric remote invocation
•When the internal (Java) and external (XML) service interfaces are identical, then layer the XML-based interfaces on top ofthe higher-performing and more efficient Java API, and use the Java API within the app
Choose appropos Data Access!
•JDBC API –a CLI view of RDBMS data
•Apache iBATIS–simplifying common JDBC usage patterns
•EJB v1, v2 –a "record oriented"approach
•Object Relational Mapping (ORM)
–Hibernate, Castor
–JDO v2 (Including KODO, OpenAccess)
–EJB v3 (Including Hibernate, Toplink, KODO)
Data Access: JDBC
•The "assembly language"of RDBMS –you can do anything, but you have to do everything
•Best choice when the form of the data being accessed is unknown, such as in a reporting engine in which the number and types of result columns are unknown
•Good choice for dealing with extremely large result sets and accessing rarely-used driver functionality
•Worst choice for rapid application development
•Worst choice for large engineering teams and large code bases
•Worst choice for building maintainable applications
Data Access: ORM
•The "object oriented"model for RDBMS –you only deal with objects, but the ORM has to deal with the RDBMS
•Best choice when the form of the data being accessed is well known, and the wide-spread use of the data throughout the application logic far exceeds the investment in defining the object schema and its mapping to the database
•Good choice for enabling data caching
•Definitely nota silver bullet
–Still requires good development processes and careful design
–Using ORM, some common application use cases are very inefficient compared to hand-coded JDBC
Why the Choice is so Critical
•I have witnessed more applications fail to meet their business goals due to poor choices around data access than any other category
•Once a choice is made, it tends to be reflected in every aspect of the application, making later changes more difficult and incredibly costly
•The predictability and cost of scalability of a large-scale application is tightly bound to the application’s data access model
Choosing a Data Access Model
•Understand the high-level requirements
–The "-ilities": Scalability, Reliability, Availability, …
•Visualize the data flows in the running system
–For each page or service request, what actually goes through to the database, and why?
•Understand the impact of concurrent users
–How will database contention be minimized?
–How will cache effectiveness be maximized?
•Understand the application’s data granularity
–Set-centric or identity-centric?
Java EE 5 - First Look!
1. XML deployment descriptors can be java-coded using annotations. Spring already provides this feature as bean configurations can also be java-coded as well.
2.Dependency Injection can be used in all levels - EJB container,Web container and application clients
3.Java Persistence API - can be used either in Java EE or Java SE applications .This replaces Entity Beans from EJB 3.0 [Java EE 5 ]
4.Java Server Faces - GUI Component Framework[since 1.4]
Everything is considered under Service Oriented Architecture - SOA
- Synchronous Services - EJB[remote/local] - session/entity or Spring Remote/local, Web Services
- Asynchronous Services - Java Messaging Service [Topic/Queue]
Friday, October 5, 2007
Inversion of Control-Don't call me;I'll call you!
Programming to interfaces is a new way of Enterprise architecture for multi-layered, test driven, loosely coupled systems.
Service oriented Architecture - [SOA]
There are various ways of inversioning the control.The leightweight containers try to invert "hard-wire" coupling of interface-concreate implementation to "configurable" injection so that the "atomic" independent services are developed that can be used without knowing the actual implementation details. The service client can just concentrate on the Service API for their usage.
This kind of "IoC" is also called "Dependency Injection".
Following are the Java Community Dependency injection methods
1.Constructors injection
- Pica Container, Spring
2.Setter Injection
- Spring
3.Interface Injection
- Avlon
Spring - Setter Injection : Dependency Injection
This is the most widely used IOC methodology adopted by Spring and supported by various other IoC frameworks
The injections can be java-coded or XML configured as bean definitions.
Singleton/Non-Singleton beans are created and managed by Spring Framework.
Detailed code example on the way.....
Refer for more details : http://martinfowler.com/articles/injection.html
Monday, July 30, 2007
How to design correct validation module for your J2EE application?
Validation is an important aspect of any J2EE applications.Several approaches are currently used in different layers.In most of the applications, the validation is commonly kept at Presentation tier-both at server side (struts validator) as well client side(java script). And few places the logic is embedded with business tier - for SOA systems.
There is strong argument that validation,especially user inputs validations are not core business logic and they should NOT be coupled with business tier. Also keeping them at inner layers results in performance bottleneck.This sounds good especially if business tieris going to serve only web interface. However in current business scenario, service layer should be built robustly so that in future it can be used to serve multiple clients - web services, web interface, any batch processes etc
This also leads to Domain Driven validation - Validation at Service/Domain layer.
The first thought on keeping the validation at domain layer is that - Domain object should be always "VALID". Hence it cannot contain any invalid data and validate itself. This is self contradictory.
This pretty much leaves us a single option - Validation @ Service Tier
Okay...what are the approaches? Any patterns
Consider an example.An admin functionality to Add/Edit/Delete and View User Details.The application has following layers
- Web MVC - Struts - UserAction (Struts Action) and UserForm (Struts Form)
- Service & Data Access - Spring - UserDTO (POJO for data transfer),UserService (Service), UserManager(DAO) and Domain object User
- Field Level Validations- UserName(content,length),Password(content,length,combinations),Email,FirstName,LastName,Status
- Object Level Validations - Mandatory fields,Specific combinations (User can only be added in Active status etc)
- validateSearch - Only Field level validations. ie, all input fields (whatever entered) should be alphanumeric,email should be valid.If any of the fields are invalid add warning message and carry forward the search.
- validateAdd - Field level and object level validations
- validateUpdate - Field level and object level validations
Solution 1
Summary:- Inject Dynamic Proxy validation service layer for exisiting service calls-On successful validation, the actual service methods will be called
- Custom Validation classes specific to Domain objects can be created and injected in Spring application context
- Need to explore how to collect validation errors.
- Pure Spring way
- Declarative and validation implementation can be changed anytime without affecting any structure
- Scalability & Robustness
- Code-Reusability
- Performance issue to make dynamic proxy calls
- Already Service calls are routed as dynamic proxies for Transaction Management and this will add additional layer
- Over kill for more of user input validations?! [w.r.to LCN application nature]
Solution 2
Summary:- Define Validator classes that implements Spring Framework Validator interface, specific to domain objects
- Invoke validate() method with specific validation type[SEARCH,INSERT,UPDATE] on corresponding Service methods;
- Use Data Binder and MessageCodesResolver to retrieve the ErrorMessages
- Devise mechanism to automatically map the Spring Error Messages to Struts ActionErrors
- Utilization of Spring infrastructure and possible extention
- Framework dependent.
- Framework is rudimentary and need to define lot of custom methods for our application
Solution 3
Summary:- Define custom Validator class containing validate() method for each domain object at service layer
- Invoke validate() method with specific validation type[SEARCH,INSERT,UPDATE] on corresponding Service methods;
- Consolidate validation errors on ServiceMessage object which can be saved to struts specific ActionErrors
- Code Reusage can be acheived by having utility methods like EmailValidator, NumericValidator,AlphaNeumericValidator etc
UserAction.java - Struts ActionAdvantages
class UserAction extends Action{
ActionForward searchUser(){
UserForm uform=(UserForm)form;
UserDTO dto=new UserDTO();
BeanUtils.copy(uform,dto);
UserService userSvc=getUserService(); dto=userSvc.findUser(dto);
}
ActionForward addUser(){
UserForm uform=(UserForm)form;
UserDTO dto=new UserDTO();
BeanUtils.copy(uform,dto);
UserService userSvc=getUserService();
ServiceMessage svcMsg=userSvc.addUser(dto);
if(svcMsg.getErrorMessage().size()>0){
ActionMessages errors=new ActionMessages()
//Copy the keys to actione messages
copyErrors(svcMgs.getErrorMessage(),errors);
//All set. Now the JSP html:errors will print the Error Messages defined in ApplicationResource.properties
saveErrors(request,errors) }
}
}
UserService.java - Service Interface
class UserService{
UserDTO findUser(UserDTO dto){
UserValidator validator=new UserValidator();
validator.setValidationType(ValidationConstants.SEARCH);
boolean isValid=validator.validate(dto);
if(isValid){
UserManager manager=new UserManager();
dto=manager.findUsers(dto);
}else{
validator.getErrorMessages();
}
return dto;
}
ServiceMessages addUser(UserDTO dto){
UserValidator validator=new UserValidator();
validator.setValidationType(ValidationConstants.INSERT);
boolean isValid=validator.validate(dto);
if(isValid){
UserManager manager=new UserManager();
manager.addUsers(dto);
}else{
ServiceMessages svcMsg=validator.getErrorMessages();
}
return svcMsg; }
}
UserValidator.java
class UserValidator implements Validator{
String validationType;
ServiceMessage serviceMessage
boolean validate(UserDTO dto){
boolean isValid=false;
if(getValidationType().equals(ValidationConstants.INSERT)){
if(StringUtils.isEmpty(dto.getUserName()){
serviceMessage.add(Type.ERROR,"username.empty");
} }
return isValid;}
}
ServiceMessage.java
class ServiceMessage {
List errorMessage;List warningMessage;
void add(String type,String key){
if(type.equals(Type.ERROR){
errorMessages.add(key);
}else if(type.equals(Type.WARNING){
warningMessage.add(key);
}
}
}
- Service Layer to offer centralized validation irrespective of the client
- Independent of any frameworks
- Code-Reusability
- Kind of - Re-inventing wheel
- Possible Performance impact-as Service calls are coslier than just Web tier calls.
Sunday, July 29, 2007
Nava-Why Strings are Immutable?
[code]
String x="Nava";
x=x+" World";
S.O.P(x); // Nava World
/* Here actually three String objects are created--"Nava", "World" and "Nava World" and x is refrenced to third object, whereas other two String objects do not have any references which can be considered as "Lost" */
[/code]
I used to wonder, why such a concept "immutability" used in Java for String object.....and finally got elucidated.
Strings are the most commonly used objects in any programming languages, especially in Java. In terms of memory usage, they are on the top most place.
JVM designers well considered this aspect and constructed a special area of memory called the "String constant pool". When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.The existing String simply has an additional reference.
Ah! I hear how you appreciate.. why making String objects immutable is such a good idea.If several reference variables refer to the same String,without even knowing it, it would be bad if any of them could change the String's value.
Cool..but what if one overides the String Object? ..well String is a FINAL class :-)