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.