Monday, 25 November 2013

Browser Compatible Issues & Script issues solutions




Z-index:

Adding z-index:
The first example, Stacking without z-index, explains how stacking is arranged by default. If you want to specify a different stacking order, you have to position an element and use the z-index property.
This property is assigned with an integer value (positive or negative), which represents the position of the element along the z-axis. If you are not familiar with the z-axis, imagine the page has several layers one above the other. Each layer is numbered. A layer with a greater number is rendered above layers with smaller numbers.
Warning! z-index only has an effect if an element is positioned.
  • bottom: furthest from the observer
  • ...
  • Layer -3
  • Layer -2
  • Layer -1
  • Layer 0 default rendering layer
  • Layer 1
  • Layer 2
  • Layer 3
  • ...
  • top: closest to the observer
Notes:
  • When no z-index property is specified, elements are rendered on the default rendering layer 0 (zero).
  • If several elements share the same z-index value (i.e. they are placed on the same layer), stacking rules explained in the section Stacking without z-index apply.
In the next example, the layers' stacking order is rearranged using z-index. The z-index of DIV#5 has no effect since it is not a positioned element.
Example source code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head><style type="text/css">

div {
   opacity: 0.7;
   font: 12px Arial;
}

span.bold { font-weight: bold; }

#normdiv {
   z-index: 8;
   height: 70px;
   border: 1px dashed #999966;
   background-color: #ffffcc;
   margin: 0px 50px 0px 50px;
   text-align: center;
}

#reldiv1 {
   z-index: 3;
   height: 100px;
   position: relative;
   top: 30px;
   border: 1px dashed #669966;
   background-color: #ccffcc;
   margin: 0px 50px 0px 50px;
   text-align: center;
}

#reldiv2 {
   z-index: 2;
   height: 100px;
   position: relative;
   top: 15px;
   left: 20px;
   border: 1px dashed #669966;
   background-color: #ccffcc;
   margin: 0px 50px 0px 50px;
   text-align: center;
}

#absdiv1 {
   z-index: 5;
   position: absolute;
   width: 150px;
   height: 350px;
   top: 10px;
   left: 10px;
   border: 1px dashed #990000;
   background-color: #ffdddd;
   text-align: center;
}

#absdiv2 {
   z-index: 1;
   position: absolute;
   width: 150px;
   height: 350px;
   top: 10px;
   right: 10px;
   border: 1px dashed #990000;
   background-color: #ffdddd;
   text-align: center;
}

</style></head>

<body>

<br /><br />

<div id="absdiv1">
   <br /><span class="bold">DIV #1</span>
   <br />position: absolute;
   <br />z-index: 5;
</div>

<div id="reldiv1">
   <br /><span class="bold">DIV #2</span>
   <br />position: relative;
   <br />z-index: 3;
</div>

<div id="reldiv2">
   <br /><span class="bold">DIV #3</span>
   <br />position: relative;
   <br />z-index: 2;
</div>

<div id="absdiv2">
   <br /><span class="bold">DIV #4</span>
   <br />position: absolute;
   <br />z-index: 1;
</div>

<div id="normdiv">
   <br /><span class="bold">DIV #5</span>
   <br />no positioning
   <br />z-index: 8;
</div>

</body></html>
See also
  • Stacking without z-index : Default stacking rules
  • Stacking and float : How floating elements are handled
  • The stacking context : Notes on the stacking context
  • Stacking context example 1 : 2-level HTML hierarchy, z-index on the last level
  • Stacking context example 2 : 2-level HTML hierarchy, z-index on all levels
  • Stacking context example 3 : 3-level HTML hierarchy, z-index on the second level



Overlay issue:
Close button wont work Some time’s :
We need to change the javascript:parent.close() method to javascript:close();
Then it wont take parent object and it will close.

Print Button Implementation:
1.            Take div for header and footer and content and for css also(what ever u want to print) and give id for the div’s.
2.            Call the javascript method or Jquery method on keydown event for print, here we need to capture the ctrl+p event also using event key (if Required)
jQuery(document).keydown(function(event) {
                  //alert('ctrl+p');
            if(event.ctrlKey && event.keyCode == 80) {
           
                   console.log("Hey! Ctrl+P event captured!");
                   event.preventDefault();
                   event.returnValue=false;
                   printCorePage();
                  }
        });
3.            First apply for css and apply for header and apply for content and apply for Footer.(content)
4.            Using, document.getElementById(“idname”).innerHTML = content
5.            If any content is not required then block the content.
                Using, document.getElementById("printmenu").style.display = "none";

UI Tips:


Importing java file into jsp:

<%@page import="com.uboc.banking.bo.UserControl"%>
-------------------------------------------------------------------------
Importing tag-lib into jsp:

<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

-------------------------------------------------------------------------

Prototype.js error :

Add jquery conflict code in jquery

$.noConflict();

($ depends upon jquery symbol)

-------------------------------------------------------------------------


Object expected: Script error

Import is missing for that variable, So import the required class


-----------------------------------------------------------------------
Object extected : Script error

Some time need to import the core matric's lib

---------------------------------------------------------------------------

To restrict the Hyperlinks in a page Code:

var div = document.getElementById("printableContentBlock");
                                var anchorList = div.getElementsByTagName('a');

                                  for(var i = 0; i < anchorList.length; i++) {
                                                anchorList[i].disabled = true;
                                                anchorList[i].onclick = '';
                                    anchorList[i].removeAttribute('href');
                                                }
                                window.print();
         window.close();
      }
----------------------------------------------------------------------------


Object expected: script error in IE

ex: firstusageconfirmpayment.do

Solution: need to import the function implementation file

Ex: Tip is not defiend in FF

Solution: Need to import the below js file :

<script language="JavaScript" src="/js/wz_tooltip<%=cacheVersion%>.js"></script>

----------------------------------------------------------------------------

Script Error: "actualTitle" is null in FF

Object expected: script error in IE

1. Check the title of landing Page
2. And change the Title div id

----------------------------------------------------------------------------




Detect which browser our script is running

Detect which browser our script is running :

BrowserFinding.html:

<html>
<html>
<head>
<script>
function detectBrowser(){
  var val = navigator.userAgent.toLowerCase();
  if(val.indexOf("firefox") > -1)
  {
  alert("This is Firefox. Write Firefox code here........")
  }
  else if(val.indexOf("chrome") > -1)
  {
  alert("This is Google Chrome. Write Google Chrome code here.............")
  }
  else if(val.indexOf("opera") > -1)
  {
  alert("This is Opera. Write Opera code here..............")
  }
  else if(val.indexOf("msie") > -1)
  {
  alert("This is Internet Explorer. Write Internet Explorer code here..........")
  }
  else if(val.indexOf("safari") > -1)
  {
  alert("This is Safari. Write Safari code here..........")
  }
};
window.onload=detectBrowser();
</script>
</head>
<body>
</body>
</html>

Output: 

In IE :
          This is Internet Explorer. Write Internet Explorer code  here.........
In FF:
          This is Firefox. Write Firefox code  here.........
In Chrome:
          This is Google Chrome. Write Google Chrome code  here........

Reading the xml File and Loading into the database

There are so many ways to read the xml file. In that 2 ways here i am going to explain. i.e.
1. Reading the xml files using DOM Parser
2. Reading the xml files using SAX Parser







Difference Between DOM and SAX Parsers:


Parses node by node Stores the entire XML document into memory before processing
Doesn’t store the XML in memory Occupies more memory
We cant insert or delete a node We can insert or delete nodes
Top to bottom traversing Traverse in any direction.
SAX is an event based parser DOM is a tree model parser
SAX is a Simple API for XML Document Object Model (DOM) API
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
 
doesn’t preserve comments preserves comments
SAX generally runs a little faster than DOM SAX generally runs a little faster than DO


SAX Parser:

  •     It’s an event based parsing it contains default handler for handling the events.
  •     SAX parser pareses the xml document and it finds the Start tag “<” and end tag”>” it calls                 corresponding handler method.
  •     Sample Example of reading XML File – SAX Parser






Advantage:
  • It is faster than DOM parser because it will not load the XML document into the memory .
  • Sax is an event based parser.





sample.xml:


<?xml version="1.0" encoding="UTF-8"?>
<Bank>
      <Account type="saving">
            <Id>1001</Id>
            <Name>Jack Robinson</Name>
            <Amt>10000</Amt>
      </Account>
      <Account type="current">
            <Id>1002</Id>
            <Name>Sony Corporation</Name>
            <Amt>1000000</Amt>
      </Account>
</Bank>


SampleVO.java

package parser;

public class Account {

       private String name;
       private int id;
       private int amt;
       private String type;

       public Account() {
       }

       public Account(String name, int id, int amt, String type) {
              this.name = name;
              this.amt = amt;
              this.id = id;
              this.type = type;
       }

       public int getAmt() {
              return amt;
       }

       public void setAmt(int amt) {
              this.amt = amt;
       }

       public int getId() {
              return id;
       }

       public void setId(int id) {
              this.id = id;
       }

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }

       public String getType() {
              return type;
       }

       public void setType(String type) {
              this.type = type;
       }

       public String toString() {
              StringBuffer sb = new StringBuffer();
              sb.append("Account Details - ");
              sb.append("Name:" + getName());
              sb.append(", ");
              sb.append("Type:" + getType());
              sb.append(", ");
              sb.append("Id:" + getId());
              sb.append(", ");
              sb.append("Age:" + getAmt());
              sb.append(".");

              return sb.toString();
       }
}




Sample Code for implementing SAX parser in Java

ReadXMLFileUsingSaxparser.java:




package parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFileUsingSaxparser extends DefaultHandler {

       private Account acct;
       private String temp;
       private ArrayList<Account> accList = new ArrayList<Account>();

       /** The main method sets things up for parsing */
       public static void main(String[] args) throws IOException, SAXException,
                     ParserConfigurationException {
            
              //Create a "parser factory" for creating SAX parsers
              SAXParserFactory spfac = SAXParserFactory.newInstance();

              //Now use the parser factory to create a SAXParser object
              SAXParser sp = spfac.newSAXParser();

              //Create an instance of this class; it defines all the handler methods
              ReadXMLFileUsingSaxparser handler = new ReadXMLFileUsingSaxparser();

              //Finally, tell the parser to parse the input and notify the handler
              sp.parse("bank.xml", handler);
            
              handler.readList();

       }


       /*
        * When the parser encounters plain text (not XML elements),
        * it calls(this method, which accumulates them in a string buffer
        */
       public void characters(char[] buffer, int start, int length) {
              temp = new String(buffer, start, length);
       }
     

       /*
        * Every time the parser encounters the beginning of a new element,
        * it calls this method, which resets the string buffer
        */
       public void startElement(String uri, String localName,
                     String qName, Attributes attributes) throws SAXException {
              temp = "";
              if (qName.equalsIgnoreCase("Account")) {
                     acct = new Account();
                     acct.setType(attributes.getValue("type"));

              }
       }

       /*
        * When the parser encounters the end of an element, it calls this method
        */
       public void endElement(String uri, String localName, String qName)
                     throws SAXException {

              if (qName.equalsIgnoreCase("Account")) {
                     // add it to the list
                     accList.add(acct);

              } else if (qName.equalsIgnoreCase("Name")) {
                     acct.setName(temp);
              } else if (qName.equalsIgnoreCase("Id")) {
                     acct.setId(Integer.parseInt(temp));
              } else if (qName.equalsIgnoreCase("Amt")) {
                     acct.setAmt(Integer.parseInt(temp));
              }

       }

       private void readList() {
              System.out.println("No of  the accounts in bank '" + accList.size()  + "'.");
              Iterator<Account> it = accList.iterator();
              while (it.hasNext()) {
                     System.out.println(it.next().toString());
              }
       }
     
}

Output:

No of  the accounts in bank '2'.
Account Details - Name:Jack Robinson, Type:saving, Id:1001, Age:10000.
Account Details - Name:Sony Corporation, Type:current, Id:1002, Age:1000000.





Thursday, 7 November 2013

Duplicate Form Submission Prevent and Solutions

Here Duplicate form submission  applied in login page only. If we want we can extend to some other modules also.
For this we need one Login.jsp, struts.xml,LoginAction.action,invalidToken.jsp,and struts2-Core jar. 

Step 1: Login.jsp
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Duplicate Request Page</title> </head> <body>

<s:form action="loginAct" id="loginForm" method="post" >
   <input type="text" name="strUserID" id="strUserID" value="User ID"/><br/><br/>
   <input type="password" name="strPassword" id="strPassword" value="Password"  /><br/>
   <s:token/>
</s:form>

</body>
</html>

Step 2: Add below interceptors in your struts.xml file

<interceptors>
      <interceptor-stack name="defaultSecurityStack">
        <interceptor-ref name="token">
          <param name="excludeMethods">*</param>
          <param name="includeMethods">loginExecute</param>
        </interceptor-ref>
        <interceptor-ref name="SessionCheckInterceptor"/>
        <interceptor-ref name="ClearCachingInterceptor"/>
        <interceptor-ref name="defaultStack"/>
      </interceptor-stack>

      <interceptor name="SessionCheckInterceptor" class="com.test.SessionCheckInterceptor" />
      <interceptor name="ClearCachingInterceptor" class="com.test.CachingHeadersInterceptor" />
</interceptors>

    <default-interceptor-ref name="defaultSecurityStack" />

<global-results>
      <result name="error">/error</result>
      <result name="sessionexpired" >sessionExpired.jsp</result>
      <result name="invalid.token">invalidToken.jsp</result>
</global-results>

Here, SessionCheckInterceptor and ClearCachingInterceptor are application oriented Interceptors(Own interceptors).
First, defaultSecurityStack will call and then it will create the token and then moved to action.
Here, exclude all the methods in your application using <param name="excludeMethods">*</param> tag.
but include only one method using <param name="includeMethods">loginExecute</param>.
If we want to include any other methods we can add in "includeMethods".
If we get any invalid token then it will check in Global result and execute the invalidToken.jsp page.

Step 3: Create invalidToken.jsp page 

<html> 
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> 
<title>Duplicate Request Page</title> 
</head> 
<body> 
<h3>Duplicate request detected.</h3>
 <ul>
 <li>Back button usage to submit form again</li>
 <li>Double click on Submit button</li> 
 <li>Using "Reload" Option in browser</li>
</ul> <br> 
<s:if test="hasActionErrors()"> <s:actionerror/> 
</s:if>
</body> 
</html>

Step 4: Need Action Page

public class LoginAction extends ActionSupport
public String loginExecute(){


String sForward="failure";

strUserID=strUserID.trim();
strPassword=strPassword.trim();

Map<String, Object> session = ActionContext.getContext().getSession();
try{
sForward = checkEmptyUserID(session, strUserID, strPassword);
userLoginDetails(sForward);
}catch(Exception exception){
exception = exception;
return ERROR;

}
return sForward;
}
Step 5: Need a Pojo class for username,password in Login page.


Explanation: 

First Login.jsp creates the token on submit of the form. And then Interceptor
will work. Lets see how token interceptors will work to handle multiple form 
submissions: 

  1. When a request is made to the update action, Struts2 tags API generates a unique token and set it to the session. The same token is sent in the HTML response as hidden field.
  2. When the form is submitted with token, it is intercepted by token interceptor where it tries to fetch the token from the session and validate that it’s same as the token received in the request form. If token is found in session and validated then the request is forwarded to the next interceptor in the chain. Token interceptor also removes the token from the session.
  3. When the same form is submitted again, token interceptor will not find it in the session. So it will add an action error message and return invalid.token result as response. You can see this message in above invalidToken.jsp. This way token interceptor make sure that a form with token is processed only once by the action.





Omniroute step by step setup

 Omniroute step by step setup Step 1 : Install node js and omniroute using below command.  npm install -g omniroute Step 2 : Start the ser...