Tuesday, December 25, 2007

why a servlet is preferred for JDBC

Servlet is preferred for JDBC code and not a static initializer block in a Class because the latter will be able to provide connections only when the static initializer block is run not before that ...
on the other hand ... servlet can be loaded on startup

Google : Open Social

Really interesting stuff ...
one can even make web sites that uses "Open Social API"
benefits of open social for
  • developer .. they have more clients
  • consumers ... they have more apps
Makes sense !! heres how ....

http://code.google.com/apis/opensocial/

enables one to make application that can be used accross social networks !!

Wednesday, December 12, 2007

All about ADF tables


How do i make a ADF TreeTable ??
Saying it in very simple terms ... (i) first make POJOs ... using parent POJO and child POJO make a tree like hierarchy (ii) then using the ADF model classes convert them into ADF treeTable model !


Step one sounds easy .. can i have more details on step two ?
In ADF we have the following hierarchy...

java.lang.Object
   javax.faces.model.DataModel
      oracle.adf.view.faces.model.CollectionModel
         oracle.adf.view.faces.model.TreeModel
            oracle.adf.view.faces.model.ChildPropertyTreeModel

javax.faces.model.DataModel
has default constructor
inherits directly from java.lang.Object
The data collection underlying a DataModel instance is modeled as a collection of row objects that can be accessed by a zero-relative cursor (row index). The APIs provide mechanisms to position to a specified zero-relative row index, and to retrieve an object that represents the data that corresponds to the current row index.
DataModel is an abstraction around arbitrary data binding technologies that can be used to adapt a variety of data sources for use by JavaServer Faces components that support per-row processing for their child components
has a property rowIndex that starts from 0 ... up to max_no_of_child
has other methods like getRowData() getRowCount() .. setWrappedData() and getWrappedData() .. they set the object representing the data collection wrapped by this DataModel


oracle.adf.view.faces.model.CollectionModel
implements no RowKeyIndex
has default ctor
The data model that is used by ADF Table components. This extends the faces DataModel class and adds on support for rowKeys and sorting.


*** oracle.adf.view.faces.model.TreeModel ***
It just has a default constructor ...

rows in a treeModel may contain other rows...
to figure out if current row is a container use method isContainer()
If a row is a container, use the enterContainer() method to access its child rows. Once the enterContainer() method is called all the CollectionModel API's methods (like DataModel.getRowCount()) operate on the child collection. To return back to the parent row, use the exitContainer() method.

|-Root1 (rowKey="r1", rowIndex=0)
| |-Folder1 (rowKey="r1f1", rowIndex=0)
| | |-Node1 (rowKey="r1f1n1", rowIndex=0)
| | |-Node2 (rowKey="r1f1n2", rowIndex=1)
| | |-Node3 (rowKey="r1f1n3", rowIndex=2)
| |
| |-Folder2 (rowKey="r1f2", rowIndex=1)
| |-Node4 (rowKey="r1f2n1", rowIndex=0)
|
|-Root2 (rowKey="r2", rowIndex=1)
|-Root3 (rowKey="r3", rowIndex=2)
|-Root4 (rowKey="r4", rowIndex=3)

so each row has a setRowKey() and setRowIndex() ... rowKey is inherited from CollectionModel and rowIndex from DataModel... the rowKey is unique accross the whole table ... rowIndex is relative to its parent ...
use setRowKey(null) to reach the root ...

To access Node4 use:

setRowIndex(0); // isContainer()==true
enterContainer(); // enter Root1, getRowCount()==2
setRowIndex(1); // isContainer()==true
enterContainer(); // enter Folder2, getRowCount()==1
setRowIndex(0); // isContainer()==false
getRowData(); // To access a particular row in the list, first make that row current, and then call the getRowData() method on the Table

Or, more simply:
setRowKey("r1f2n1");
getRowData();

*** oracle.adf.view.faces.model.ChildPropertyTreeModel ***
It extends TreeModel

Creates a TreeModel from a List of beans. To use this class you must have a tree of beans (or Maps). The structure of your tree must be a List (or array) of root beans, and each bean must have a getter method (or Map property) that returns the children List. All elements of your tree must be the same type.




Tree VS TreeModel
The Tree component displays a multi-root hierarchy in a simple UI... the TreeTabel displays a single-root hierarchy

You may find the oracle.adf.view.faces.model.ChildPropertyTreeModel class useful when constructing a TreeModel

*** the ***
The "nodeStamp" facet of the Tree is used to display the data for each element in the tree. The Tree does not create components per element; instead, the "nodeStamp" is repeatedly rendered (stamped) once per element. Because of this stamping behavior, only certain types of components are supported as children inside a Tree. Supported components include all components with no behavior and most components that implement the EditableValueHolder or ActionSource interfaces.
The Tree renders expand/collapse icons that the user can click on to expand or collapse a subtree. When these icons are clicked, the Tree generates a DisclosureEvent

The immediate children of a Table component must all be < af:column > components.
Use the "header" facet on a Column to create the column header.
The child components of each Column display the data for each row in that column.... that means it may be a textbox , a label , a textArea etc ...
Column does not create child components per row; instead, each child is repeatedly rendered (stamped) once per row... that means if there are 10 rows then the column elemnt will not create 10 children insteand 10 times rows will be created and each time one element for the column is created

Because of this stamping behavior, some components many not work inside the table. Anything that is just pure output, with no behavior, will work without problems, as will components that don't "mutate" even as they deliver events

one can have column groups ...

Columns can be rendered as row headers by setting the "rowHeader" attribute on < column > to be true. Row header columns must be the first columns in a table.

Range Navigation
When the list being displayed by a Table is huge, you can enable the Table to break up the list into ranges and display a single range at a time. Range controls are provided on the Table to let the user scroll to the next range, or to go back to the previous range.
thi smay also generate RangeChangeEvent

Displaying Details
You can configure the Table to display or hide additional details of a particular row in response to a user gesture. When the details feature is enabled, a new column containing a toggle (per row) will render in the Table. When a toggle is activated, the details for that row are displayed. When a toggle is deactivated, the details for the row are hidden. The user can also display or hide the details for all rows at the same time (the controls for this feature are enabled by setting the "allDetailsEnabled" property to true.)

To enable the details feature set the "detailStamp" facet on the Table. Place the components that are used to show the details (of a row), inside this facet. In the following example, the Person's age is displayed in the details section:







Usually, the default behavior of the Table (with respect to displaying and hiding details) is sufficient. In some cases, however, it might be desirable to programmatically display or hide the details for a particular row. This can be done via the RowKeySet object obtained from the Table by calling the getDisclosureState() method. First, make the relevant row current by calling setRowIndex(...) or setRowKey(...) on the Table, and then call add() or remove() on the RowKeySet object. Adding the row to the set displays the details of the row. Removing the row hides them.



*** ***
The ADF Table component uses a model to access the data in the underlying list. The specific model class is oracle.adf.view.faces.model.CollectionModel . You may also use other model instances, e.g., java.util.List , array, and javax.faces.model.DataModel . The Table will automatically convert the instance into a CollectionModel ...??? not sure how will that happen as there is only one constructor for the CollectionModel and thats the default constructor ???



*** the ***
single-root hierarchy
TreeTable's children must be ADF Column components
the tree table has a "nodeStamp" and a "pathStamp" facet ... Like the Tree, the TreeTable has a "nodeStamp" facet which renders the "Object Name" Column. The TreeTable has a "pathStamp" facet for rendering the focus path.


*** obvious ***
ifmy af:table is inside af:panelcollection .. first panelcollection is made then the table

Tuesday, December 11, 2007

ANT and versioning

http://www.josesandoval.com/2007/12/java-automatically-increment-build.html

Software Engineering

hhhhhhhhmmmmmmmmmmmm
what THEY say ...
The idea is to create a language around the problem you're trying to solve in order to make it easier to solve the problem.
what I understood ...
yes i kind of agree to that ... as far as my experience with product development goes succesfull product development companies have made there own properiatory frameworks first and then used to it to solve the problem in hand ..
so what do they gain by making this framework ... ? wouldnt one save time by using existing framework .. ??
my take is they visualize a big problem break it down to small ones by making small components / classes / APIs and solve each of them individually
They even sav time .. how ?? if a bug comes in the framework they can solve it in less time rather than delegating it to some one else !

There's always a big difference between setting out to invent new solutions and setting out to invent new problems... confused ?? allow me to explain ... rather than solving a big problem first try to break it into new problems .. smaller and more specific ones .. then soolve each of them ... if new design or constraints come up then they too can be solved with similar approach ...
I wonder if its "Decorator Pattern" ;o)

Dont waste a lot of time and money in solving yesterdays problem ... i hope it makes sense .. and thats what JAVA is upto ...

cheerz !!

Saturday, December 8, 2007

More JSF

For a web application, all objects held in the application scope must be handled in a threadsafe manner; because all users and all requests have access to the objects in this scope, it's very likely that more than one thread will access the same object. Objects in the session scope must also be threadsafe, because they are shared by all requests from the same user. If the user makes parallel requests, e.g., by submitting the same form over and over without waiting for the response, making requests from multiple browsers tied to the same session, or requesting pages that contain references (e.g., frame references) to other pages that modify session scope objects, a session scope object's state can be corrupted.

When you use JSP as the presentation layer technology for JSF, you don't use the JSF API at all for creating and rendering components. Instead, you use the custom actions from the JSF custom tag libraries to say which components you need, and the tag handlers use the JSF API to create and render the corresponding component objects for you.

The first action element in the page, , is very important. The combination of the components that make up a specific user interface screen is called a view in JSF. A view contains an instance of the javax.faces.component.UIViewRoot class. This class is a nonvisual component type that acts as a container for all the other components in the view. Components representing UI widgets, such as input fields and buttons, are children of the UIViewRoot and can have children of their own. Together, the components form a tree, with the UIViewRoot at the top. The action element represents the UIViewRoot component and you must make sure it encloses all other JSF action elements in the page; otherwise, they aren't included in the view.

Note that there's a one-to-one relationship between a JSF view and an HTTP response. Hence, you must use only one element in the JSP page. A JSP page can, as you may know, include other JSP pages dynamically. Such included pages represent subviews in JSF, and are represented by an element.

The next JSF action element, , represents a form component, acting as a container for input components that hold values that should be processed together. Within the element

The element names for all these actions are composed from a component type name and renderer type name. The core JSF components represent pure behavior and know nothing about how they are represented on a screen. This task instead falls on renderers associated with each component, making it possible to represent the same type of component in different ways. Take < h : inputText >, for example. It represents an input field component, i.e., a component type that holds a value that can be changed by the user. Such a component can be rendered in different ways. The < h : inputText > action associates the input component with a text renderer, which renders the component as an HTML < input > element with the type attribute set to text. Another action element named < h : inputSecret > associates an input component with a renderer of type "secret," which renders the component as an HTML < input > element with the type attribute set to password.

< h : commandButton >
component Type : command
Renderer type : Button

< h : commandLink >
component Type : command
Renderer type : Link

< h : panelGroup >
component Type : panel
Renderer type : Group

< h : panelGrid >
component Type : panel
Renderer type : grid

< h : selectOneMenu >
component Type : selectOne
Renderer type : menu

Most component types can be combined with more than one renderer type, and each valid combination is supported by an action element following the naming convention.

So why doesn't the element name follow the same convention? Because the only renderer type for the form component type is the form renderer. To avoid action element names like , JSF uses an abbreviated element name when the component type and the renderer type have the same name

JSF Overview

The UIComponentBase class is the base class for all JSF UI components. Subclasses represent specific interface elements, such as text fields, links and buttons, labels, menus and selection lists.

The components fire events in response to user actions (such as clicking a button) and event listeners attached to the components handle the events (for example, by updating a database). Instead of implementing and registering listeners for each component, most JSF applications take advantage of shortcuts in the form of method bindings. A method binding is similar to a value binding, but it binds a component to an application method instead of an application property value. For instance, the UICommand component has a property that takes a method binding value. When the component fires an ActionEvent, a default ActionListener provided by JSF and automatically attached to the component invokes the method that the method binding points to. All the component writer needs to do is implement the method.

but declaring the scope as session (or others) means that a unique instance is created for each user and remains available as long as the user actively uses the application

Elements with the prefix h (short for HTML) represents the standard JSF UI components combined with HTML renderers; elements with the prefix f (short for Faces) represent validators, event listeners, etc. that can be attached to the UI components

The basic hierarchy is and inside it is

When JSP page is invoked for first time then
< h : inputText value="#{abc.emailID}" / >
i) the corresponding UIInput element is created
ii) Its property value bound to the bean value specified by the binding expression
iii) component is asked to render itslef ... i.e. renderer called !
iv) It evaluates value binding expression and if bean doesnt exist ( based on scope ) then JSF creates it!
v) The input component pulls its value from the property of the bean specified by the rest of the value binding expression and uses it as the value of the HTML < input > element it renders

When the user enters values in the form and clicks the Submit button, JSF processes the request by asking each component to get its value from the request .. so basically JSF doesnt talk to HTTPRequest .. but components ... Each input component sets the bean property it's bound to, and the command component fires an event that causes the method it's bound to be invoked. The method typically saves the new values to a database or does some other backend processing.

This is a very simplified description of what really occurs at runtime. As you will learn, there's a lot more that may happen when a form is submitted, such as input value conversion and validation, error message queuing, forced redisplay of the same page without updating any bean properties, and more. simple description helps understand understand the basics of how the application code and the JSF components fit together.

Java Calendar VS Date

Although Date is deprecated but still we cant use a java.util.calendar abstract class when we are looking forward to make a String like "8th December 2007" coz all the members of the Calendar class are int types
so code like
Calendar cal = new GregorianCalendar();
or
Calendar cal=Calendar.getInstance();
int i = cal.get(Calendar.VAR_OF_I);
will always give integer ....
// Gotcha warning: months go from 0 to 11

GregorianCalendar is the actual implementation of the abstract Calendar class and supplies good behavior

If you want to compare it to a different date time, you've got all you need in the date variable. If you want to display the value, use a date formatter to build a String in the desired format, & that's it.

One can convert Calendar object to Date object using getTime() method.

Think of java.util.Date as an abstract instant in time. It has no time zone, calendar, clock or any other structuring we've put on time. A Date only knows how many milliseconds had elapsed since Jan 1, 1970 00:00 UTC when this instant occurred
Date testDate = calendarObject.getTime();

The bottom line: if you just need to keep track of a date/time as most people do, just use a Date. If you need to also remember a specific time zone with it, choose Calendar. If you need to specifically use western calendar system, use GregorianCalendar.

using java.util.Date has one more advantage if one wants to move objects around over RMI. Calendar and Gregorian Calendar do not implement serializable. one could sub-class GregorianCalendar and make it serializable.

Even the Java Date object assumes that the date value stored is GMT. The value of the datetime that is displayed will depend on your location, or the location of the system that is generating that representation. For example, if I have an application on my machine in London and I view that Date object I would see 01April2002:10:00, now if that same Date object was used by a webserver on the east coast of the US to generate a web page it would generate 01April2002:05:00

To convert Calendar object to String

Calendar cal = Calendar.getInstance(TimeZone.getDefault());
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getDefault());
String currentTime = sdf.format(cal.getTime());

Convert java.util.Date to java.sql.Date

java.sql.Date stores only date information, not times. Simply converting a java.util.Date into a java.sql.Date will silently set the time to midnight. So, to store date/times to be manipulated as java.util.Date objects, don’t do this

// BUG: loses time of day
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));

do this instead:

preparedStatement.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
java.sql.Timestamp is not a date

java.sql.Timestamp extends java.util.Date, but it should not be used as a Date. In JDK 1.3.1, Timestamp.getTime() (inherited from Date) returns the time to the nearest second only, but JDK 1.4.2 and JDK 1.5 it returns the time to the nearest millisecond as expected. So in JDK 1.3, when reading a timestamp from a ResultSet, don’t do this

// Java 1.3
java.util.Date d = resultSet.getTimestamp(1);
long millis = d.getTime(); // BUG: loses fractional seconds in JDK 1.3

To get the full date including milliseconds, you have to do this :

java.sql.Timestamp timestamp = resultSet.getTimestamp(1);
java.util.Date d = new java.util.Date(timestamp.getTime() +
timestamp.getNanos() / 1000000);

In JDK 1.4.2 and JDK 1.5, you can just do this, depending on what you’re going to do with the Date:

// Java 1.4+
java.util.Date d = resultSet.getTimestamp(1);

But this might be safer since it avoids any other potential Timestamp problems

// Java 1.4+
java.util.Date d = new java.util.Date(resultSet.getTimestamp(1).getTime());

If your code needs to run on JDK 1.3 and later, you’ll have to do this:

java.sql.Timestamp timestamp = resultSet.getTimestamp(1);
long millis = (timestamp.getTime() / 1000) * 1000 + timestamp.getNanos() / 1000000;
java.util.Date d = new java.util.Date(millis);

JSF Intro

What is JSF ??
JSF is a specification with implementations offered by multiple vendors. It defines a set of user interface (UI) components—basically, a one-to-one mapping to the HTML form element set plus a few extras—that can be used right out of the box, as well as an Application Programming Interface (API) for extending the standard components or developing brand new components.

JSF is not limited to HTML or any other markup language. Renderers that are separate from the UI components control the actual markup sent to the client, so the same UI component coupled with different renderers can produce very different output—for instance, either HTML and WML elements

JSF gives you lots of flexibility in how you actually develop the user interface. All JSF implementations are required to support JavaServer Pages (JSP) as a presentation layer technology, with JSF components represented by JSP custom action elements (also commonly known as custom tags). The JSF API, however, is flexible enough to support other presentation technologies besides JSP. For instance, you can use pure Java code to create JSF components, which is similar to how a Swing UI is developed. Alternatively, you can bind JSF components to nodes in templates described by plain HTML files,

JSF brings a component-based model to web application development that is similar to the model that's been used in standalone GUI applications for years. Each component has an id attribute for the elements representing dynamic content so that it can be changed !

JSF UI components declare what events they can fire, such as "value changed" and "button clicked" events, and external event listeners (representing the Controller) attached to the components handle these events

An event listener may set properties of the JSF components—for instance, adjust the set of rows shown in a table—or invoke backend code that processes the submitted data (say, verify that a credit card is valid or update a database).

A separate renderer class (representing the View) renders each JSF UI component, making it possible to render instances of the same component type in different ways (e.g., either as a button or a link, or using different markup languages) just by attaching different renderers.

Besides the UI components, JSF also defines artifacts like validators and converters, each with a well-defined
purpose

The best fit for JSF is a true web application—a web site with a lot of user interaction—rather than a web site with some dynamic content.

JSF does not necessarily replace current technologies. It's a complement that brings structure and maintainability to the application user interface. The following sections describe how JSF fits with some established Java web application technologies

As you have already seen, JSF plays nicely with JSP. In fact, all JSF implementations must support JSP and provide tag libraries with custom actions for representing the standard JSF UI components in JSP pages.

Struts and similar frameworks as application frameworks, and to JSF as a user interface framework. this to emphasize that they have different objectives. An application framework's objective is to support the development of complete applications; it's concerned with the Big Picture. This type of framework acts as a traffic cop, routing HTTP requests to request handling code and internal view requests to response rendering code based on mappings between symbolic names and the different types of application components. An application framework doesn't care about details, such as how the user interface is rendered, or make any distinction between user actions that only affect the user interface (e.g., asking for the next set of rows to be displayed in a table) and actions that need to be processed by backend code (e.g., processing an order on an e-commerce site). Struts, for instance, can use JSP, Velocity, XSLT, or any other presentation layer technology to render a response. The Struts servlet just routes requests to application classes that process them and then tell Struts which page to display next.

A user interface framework, on the other hand, focuses on the user interface details and isn't concerned with how the rest of the application is implemented. It defines a detailed API for user interface components, for how user actions result in user interface events and how these events are handled, how the components are tied to the business data they visualize, and so on.