Friday, December 11, 2009

Place any window to the center of the screen

Placing the component in the center of the visible are of the screen. This helps to place the component to
the center of the screen as we scroll the page content. It supports following browsers IE 6, IE 7, FireFox, Netscape
Below function, get the page horizontal/vertical scrolling offsets of the page.
getPageScrolling = function ()
{
    var scrollX = 0;
    var scrollY = 0;
    if (document.documentElement &&
            typeof document.documentElement.scrollLeft === "number")
    {   // IE compliant.  IE compliant must be before DOM compliant since IE
        // always returns 0 for the DOM compliant access. IE's hack always
        // returns the correct value.
        scrollX = document.documentElement.scrollLeft;
        scrollY = document.documentElement.scrollTop;
    }
    else if (typeof window.pageYOffset === "number")
    {   // Netscape compliant.
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
    }
    else if (document.body && typeof document.body.scrollLeft === "number")
    {   // DOM compliant. IE will always return 0 in this case.
        scrollX = document.body.scrollLeft;
        scrollY = document.body.scrollTop;
    }
    return { scrollX: scrollX, scrollY: scrollY };
};
Get the viewport width/height of the screen.  This returns the width/height of the visible area of the browser.
getViewportSize = function ()
{
    var width = 0;
    var height = 0;
    if (document.documentElement &&
        typeof document.documentElement.clientWidth === "number")
    {
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
    }
    else if (document.body && typeof document.body.clientWidth === "number")
    {
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }
    else if (typeof window.innerWidth === "number")
    {
        width = window.innerWidth - 18;
        height = window.innerHeight - 18;
    }
    return { width: width, height: height };
};
Function that is used to continuously update the component so that it is always centered in the current viewport.
/**
 * @param component Reference to the DOM element that represents the component
 *        "window" that is being centered.

 * @return  Centering function for component window - creates a closure around the
 *          DOM element that should be centered in the viewport.
 */
getUpdateFn = function (component) {
    return function () {
        // Calculate the Height/Width of the component
        var componentSize = getcomponentSize(component);
        // Calculate the Viewport Height/Width
        var viewportSize = getViewportSize();

        // Calculate the Page Scrolling
        var pageScroll = getPageScrolling();

        // Calculate the coordinates to center component
        var pageX =
            pageScroll.scrollX + ((viewportSize.width - componentSize.width) / 2);
        var pageY =
            pageScroll.scrollY + ((viewportSize.height - componentSize.height) / 2);

        // Update component Window coordinates
        component.style.top = pageY + "px";
        component.style.left = pageX + "px";
    };
};
Get the width/height of the specified component, that needs to placed to the center of the screen.  This returns the current width/height needed to display the specified component.
/**
 * @param component  The component to calculate the width/height of

 * @return  The width/height of the specified component
 */
getcomponentSize = function (component)
{
    return { width: component.offsetWidth, height: component.offsetHeight };
};

Tuesday, December 8, 2009

Upload file to Server


Upload the file to the server using the Http Connection. The File content is read as Input Stream and then uploaded to the server through the connections
public void sendFile(final String uri, final InputStream istream)
throws EvoxException
{
try
{
// Setup HTTP Connection
final URL evoxUrl = new URL(this.evoxServer + uri);
final HttpURLConnection connection =
 (HttpURLConnection) evoxUrl.openConnection();
connection.setRequestMethod(RequestType.POST.name());
connection.setDoInput(true);
connection.setDoOutput(true);
// Get Output Stream
final OutputStream ostream = connection.getOutputStream();
FileUtils.copyStreams(istream, ostream);
ostream.close();
final PrintWriter writer =
 new PrintWriter(connection.getOutputStream());
// Send File
writer.println(ostream);
writer.flush();
writer.close();
connection.getInputStream();
}
catch (IOException exception)
{
 throw new Exception("unable to send file: " + uri,
       exception);
}}
If the file is uploaded to the server make sure you close the connection if not needed, if not it will windup keeping lots of open connections in you applications




Download File From Server

We could retrieve/ download the file from the server and save it locally in to the PC.

public void downLoadFileFromDevice() throws IOException
{
final FacesContext ctx = FacesContext.getCurrentInstance();
if (!ctx.getResponseComplete())
{
InputStream fileFromEvox = null;
try
{
fileFromServer = receiveFile (“serverName/filename”);
}
catch (Exception e)
{
// Error Message.
 return;
}
final String contentType = "application/x-zip-compressed";
final StringBuilder sbuff = new StringBuilder(30);
sbuff.append(“newfilefromserver.xyz”);
final HttpServletResponse response = (HttpServletResponse)ctx
 .getExternalContext().getResponse();
response.setContentType(contentType);
response.setHeader("Content-Disposition",
 "attachment;filename=\"" + sbuff.toString() + "\"");
ServletOutputStream out = null;
InputStream istream = null;
try
{
istream = new BufferedInputStream(fileFromServer);
out = response.getOutputStream();
final byte[] buf = new byte[4096];
for (int c = istream.read(buf); c != -1; c =                
istream.read(buf))
{
out.write(buf, 0, c);
}}finally{
if(istream != null)
{istream.close();}
}
 out.flush();
 ctx.responseComplete();
}}
Receive file helps to establish the connections to the server and receives the file in the InputStream format

public InputStream receiveFile(final String uri)
throws EvoxException
{
try
{
final URL serverUrl = new URL(this.evoxServer + uri);
final HttpURLConnection connection =
 (HttpURLConnection) serverUrl.openConnection();
connection.setRequestMethod(RequestType.GET.name());
connection.setDoInput(true);
connection.setDoOutput(false);
// Read the Response
return connection.getInputStream();
}
catch (IOException exception)
{
throw new Exception("unable to receive file: " + uri,
 exception);
}}

Debug JSf LifeCycle

You can use a PhaseListener to trace the phases of the JSF lifecycle and execute some processes where required. But you can also use a "dummy" PhaseListener to debug the phases to see what is happening in which phase. Here is a basic example of such a LifeCycleListener:
package mypackage;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener; 
public class LifeCycleListener implements PhaseListener { 
    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    } 
    public void beforePhase(PhaseEvent event) {
        System.out.println("START PHASE " + event.getPhaseId());
    } 
    public void afterPhase(PhaseEvent event) {
        System.out.println("END PHASE " + event.getPhaseId());
    } 
}
Add the following lines to the faces-config.xml to activate the LifeCycleListener.
    mypackage.LifeCycleListener
This produces like the following in the system output:
START PHASE RESTORE_VIEW 1
END PHASE RESTORE_VIEW 1
START PHASE APPLY_REQUEST_VALUES 2
END PHASE APPLY_REQUEST_VALUES 2
START PHASE PROCESS_VALIDATIONS 3
END PHASE PROCESS_VALIDATIONS 3
START PHASE UPDATE_MODEL_VALUES 4
END PHASE UPDATE_MODEL_VALUES 4
START PHASE INVOKE_APPLICATION 5
END PHASE INVOKE_APPLICATION 5
START PHASE RENDER_RESPONSE 6
END PHASE RENDER_RESPONSE 6

Monday, December 7, 2009

FireShot

Unlike other extensions, this plugin provides a set of editing and annotation tools, which let users quickly modify captures and insert text and graphical annotations. Such functionality will be especially useful for web designers, testers and content reviewers.

Screenshots can be saved to disk (PNG, GIF, JPEG, BMP), printed (NEW), copied to clipboard, e-mailed and sent to external editor for further processing. Works both in IE and Firefox

Download at : http://screenshot-program.com/fireshot/

Page level Caching of data

Instead of making the calls repeatedly to the server which might not change, we could cache the data in the scope. By doing something similar in the controller.
    final FacesContext context = FacesContext.getCurrentInstance();
    final HttpServletRequest request = (HttpServletRequest)
            context.getExternalContext().getRequest();
    String data = (String) request.getAttribute(“requestData”);
    if (data == null)
    {
       data = Go retrieve data from the server;
       request.setAttribute(“requestData”, data);
    }
In the above case we cache the data "requstData" in the requestMap and retrieve them. We do make call to the server for the data if the requestMap doesn't have the persisted data in it. This helps to reduce unnecessary calls to the server.

Disable Page Validation on Ajax Calls

All page validations could be disabled, while making ajax calls. In certain business logic we might need to refresh data regularly from the server, which would make repeated round trip calls to the server, which might cause the page validations to fire; when calls made to server.
We could handle above scenario as
[a4j:support id="refreshBtnAjax" event="onclick"
           onsubmit="Lifecycle.setValidateForm(false);" 
           oncomplete="Lifecycle.setValidateForm(true);"                           
           actionListener="#{controller.action}"
           reRender="ComponentName" immediate="true"/]
Could disable the validation on submitting the ajax request and enabling the validations when the ajax request is complete.

JSF Ajax reRender Issue

While Re-rendering ajax region certain fields are not re-rendered properly, even though the bean/controller has the current and perfect data, that is because the component tree needs to be re-build to get that. which could be done by
In Page:
[h:commandButton]
     [a4j:support id="refreshBtnAjax" event="onclick"                               
        actionListener="#{Controller.clearData}"
        reRender="panelGroupToRefresh" immediate="true"/]
                          Re-Render
[/h:commandButton]

In Controller/ Backing Bean:
Find the component in the page that needs to be re-rendered and clear it from the component tree so that, it could be rebuilt.
public void clearData(final ActionEvent event){
   Place your business logic here
  
   final UIComponent component =
        FacesContext.getCurrentInstance().getViewRoot()
             .findComponent("form:panelGroupToRefresh");
   if (component != null) {
      component.getChildren().clear();
   }
}
This helps to re-render or refresh the data immediately when we press the button or refresh data at regular interval of time, which ever is preferred.

New Features in Struts 2.0 for AJAX


One of the useful enhancements in Struts 2.0 is the introduction of AJAX Theme
The Ajax theme extends the xhtml theme with AJAX features.
The theme uses the popular DOJO AJAX/JavaScript toolkit.
The new AJAX features include:
• AJAX Client Side Validation
• Remote form submission support (works with the submit tag as well)
• An advanced div template that provides dynamic reloading of 
   partial HTML
• An advanced a template that provides the ability to 
    load and evaluate JavaScript remotely
• An AJAX-only tabbed Panel implementation
• A rich pub-sub event model
• Interactive auto complete tag
The framework provides a set of tags to help you ajaxify your applications,
on Dojo.
To use the Ajax tags you need to set the "theme" attribute to "Ajax".
Use the head tag to configure the page for the Ajax theme.

JSF Controller accessibility in other Controller

  
   Define configuration files for the backing bean/controller as follows.
 
    [managed-bean id="Controller"]
        [managed-bean-name]Controller[/managed-bean-name]
        [managed-bean-class]
            Path.Controller
        [/managed-bean-class]
        [managed-bean-scope]request[/managed-bean-scope]
        [managed-property]
            [property-name]injectedData[/property-name]
            [value]#{InjectedController}[/value]
        [/managed-property]
    [/managed-bean]
    
Then, the  data need to be injected to this backing bean is define separately.
    [managed-bean id="InjectedController"]
        [managed-bean-name] InjectedController [/managed-bean-name]
        [managed-bean-class]
            Path. InjectedController
        [/managed-bean-class]
        [managed-bean-scope]request[/managed-bean-scope]
    [/managed-bean]

 Need to make sure that there should be proper getter and setter methods for the 
 injectedData in the Controller Class mentioned below, which helps to access the injectedData in the pages

   Public class Controller {
      ...
           Public getInjectedData(){
             ...
           }
           Public setInjectedData(dataTyle data){
              this.injectedData = data;
           }
    }

JSF with JavaScript

Could define a composition component for as below to support the javascript in JSF and use them in normal xhtml / jsf pages.
So we would have the flexibility of rendering and not rendering the Javascript in the pages with the JSF life-cycle.
Javascript.xhtml (below, replace "[" with "<")

[ui-composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:c="http://java.sun.com/jstl/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"]

    [c:choose]
      [c:when test="#{not empty path}"]

    [script type="text/javascriptt"                    
      srcc="#{facesContext.externalContext.requestContextPath}
           #{path}"]
    [/script]
       [/c:when]
       [c:0therwise]
          [script type="text/javascript"]
              [ui:insert /]
          [/script]
       [/c:otherwise]
   [/c:ch00se]

[/ui:composition]

In JSF/xhtml page, we could render javascript functions as below.
[h:form]
[yournameSpace:javascriptt]
   Function hello(){ alert(‘hello…’); }
[/yournamespace:javascript]

[yournameSpace:javascript rendered=”#{condition}”]
   Function hello1(){ alert(‘hello…’); }
[/yournamespace:javascript]
[/h:form]

So we have the flexibility to render/ not-render/ re-Render by AJAX.
Handling data between the JSF & Javascript will be easy

Java Vs Python

There are three main language characteristics that make programmers more productive with Python than with Java.



Java
  1. statically typed
In Java, all variable names (along with their types) must be explicitly declared. Attempting to assign an object of the wrong type to a variable name triggers a type exception. That's what it means to say that Java is a statically typed language.
Java container objects (e.g. Vector and ArrayList) hold objects of the generic type Object, but cannot hold primitives such as int. To store an int in a Vector, you must first convert the int to an Integer. When you retrieve an object from a container, it doesn't remember its type, and must be explicitly cast to the desired type.

  1. verbose
"abounding in words; using or containing more words than are necessary"

  1. not compact

Python
  1. dynamically typed
In Python, you never declare anything. An assignment statement binds a name to an object, and the object can be of any type. If a name is assigned to an object of one type, it may later be assigned to an object of a different type. That's what it means to say that Python is a dynamically typed language.
Python container objects (e.g. lists and dictionaries) can hold objects of any type, including numbers and lists. When you retrieve an object from a container, it remembers its type, so no casting is required.

  1. concise (aka terse)
"expressing much in a few words. Implies clean-cut brevity, attained by excision of the superfluous"

  1. compact
In The New Hacker's Dictionary, Eric S. Raymond gives the following definition for "compact":
Compact adj. Of a design, describes the valuable property that it can all be apprehended at once in one's head. This generally means the thing created from the design can be used with greater facility and fewer errors than an equivalent tool that is not compact.


Thursday, August 20, 2009

Evaluate Your JavaScript

Usually people have hard time in evaluating their JavaScript code, I found a interesting tool which helps to evaluate the Javascript JSLint - The JavaScript Code Quality Tool. Its quiet easy to use; navigate to
http://www.jslint.com/
Example:
This will help ensure our code is compatible with IE 6 and IE 7.

Strict white space

Assume a browser

Disallow undefined variables

Disallow == and !=

Alternatively, you can add this line to your javascript. This will ensure these values are "checked".

JSF Life Cycle

The six phases of the JSF application lifecycle are as follows (note the event processing at each phase):
  1. Restore View
  2. Apply request values; process events
  3. Process validations; process events
  4. Update model values; process events
  5. Invoke application; process events
  6. Render response

The six phases show the order in which JSF typically processes a form GUI. The list shows the phases in their likely order of execution with event processing at each phase, but the JSF lifecycle is hardly set in stone. You can change the order of execution by skipping phases or leaving the lifecycle altogether. For example, if an invalid request value were copied to a component, the current view would be redisplayed, and some of the phases might not execute. In this case, you could issue a FacesContext.responseComplete method invocation to redirect the user to a different page, then use the request dispatcher (retrieved from the request object in the FacesContext) to forward to an appropriate Web resource. Alternately, you could call FacesContext.renderResponse to re-render the original view.

Focusing your efforts

Some developers using JSF may never write a component or extend the framework, while others may focus on just those tasks. While the JSF lifecycle will be the same for almost any project, you'll likely tap into it at different stages based on your role in the project. If you're concentrating more on the overall application development, you'll likely be concerned with the middle phases of the request processing lifecycle:
  • Apply requests values
  • Process validations
  • Update model values
  • Invoke application
If you're concentrating on JSF component development, you'll probably focus on the first and last phases of the lifecycle:
  • Restore view
  • Render response
In the sections that follow, I'll walk you through every phase of the JSF request processing lifecycle, including event handling and validation. Once you have a basic understanding of each phase, I'll introduce a sample application that shows how they all come together. Before we get started, take a look at Figure 1, a diagram of the JSF lifecycle.
From - http://www.ibm.com/developerworks/library/j-jsf2/




Jackson JSON Processor


The Jackson JSON Processor is used for marshalling and unmarshaling JSON strings. It is capable of converting JSON strings into Java objects and vice versa. THis biderctional conversion simplifies passing information between java classes and javascript code. Other processors exist, such as XStream, that marshal and unmarshal XML and JSON. The Jackson JSON Processor is by far the fastest one out there.



Using Java Beans

Code examples based ion release 0.98.

When working with Java Beans, the following restrictions are used by the Jackson JSON Processor. The bean has an empty public constructor, methods exposed follow the set/get/is construct, and the class CANNOT be an inner class.



Construcitng a bean and exporting it via an ObjectMapper is the preferred approach. With proper planning, you might not even need to copy information into the target Java Bean for transformation.

Code sample to generate JSON form a java bean.

ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
mapper.writeValue(sw, myDS);
String testStr = sw.toString();
System.out.println("json Bef3 [" + testStr + "]");

Code sample to unmarshal JSON into a java bean.
ObjectMapper mapper = new ObjectMapper();
DailySchedule sample = mapper.readValue(testStr, DailySchedule.class);

The same ObjectMapper may be used.


Agile Unified Process

The Agile Unified Process (Agile UP) is a streamlined approach to software development based on IBM's Rational Unified Process (RUP). The Agile UP lifecycle is serial in the large, iterative in the small, delivering incremental releases over time.

Agile UP Disciplines

Disciplines are performed in an iterative manner, defining the activities which development team members perform to build, validate, and deliver working software which meets the needs of their stakeholders. The disciplines are:

Discipline

Overview

Model

The goal of this discipline is to understand the business of the organization, the problem domain being addressed by the project, and to identify a viable solution to address the problem domain.

Implementation

The goal of this discipline is to transform your model(s) into executable code and to perform a basic level of testing, in particular unit testing.

Test

The goal of this discipline is to perform an objective evaluation to ensure quality. This includes finding defects, validating that the system works as designed, and verifying that the requirements are met.

Deployment

The goal of this discipline is to plan for the delivery of the system and to execute the plan to make the system available to end users.

Configuration Management

The goal of this discipline is to manage access to your project work products. This includes not only tracking work product versions over time but also controlling and managing changes to them.

Project Management

The goal of this discipline is to direct the activities that takes place on the project. This includes managing risks, directing people (assigning tasks, tracking progress, etc.), and coordinating with people and systems outside the scope of the project to be sure that it is delivered on time and within budget.

Environment

The goal of this discipline is to support the rest of the effort by ensuring that the proper process, guidance (standards and guidelines), and tools (hardware, software, etc.) are available for the team as needed.

AGILE UP PHASE

The Agile UP is characterized as being "serial in the large", something that you can see via its four phases which you move through in a serial manner.

Phase

Goals

Milestone

1. Inception

To identify the initial scope of the project, a potential architecture for your system, and to obtain initial project funding and stakeholder acceptance.

Lifecycle Objectives (LCO)

2. Elaboration

To prove the architecture of the system.

Lifecycle Architecture (LCA)

3. Construction

To build working software on a regular, incremental basis which meets the highest-priority needs of your project stakeholders.

Initial Operational Capability (IOC)

4. Transition

To validate and deploy your system into your production environment.

Product Release (PR)