Wednesday, 26 October 2016

Cleaner approach to bind an event to dynamic generated element in Jquery

Instead of binding an event in a single line  using Traditional approach which actually difficult to parse quotes , commas and values :
"<td><a href='#'><span id='showHidelinkText"+ id + "' onclick='openJsonData(\"" + id+ "\");return false;'>Show JSON</span></a></td>"



We can use the following approach which appends the child elements to the parent and then append into DOM. After appending the new element into DOM, we can bind on() method on element selector.
Event handlers attached using the on() method will work for both current and FUTURE elements.
This way we can overcome the difficulty for adding or removal of the  parameters & attributes in the dynamic generated section.



var formId = "batchclosurestatusForm";
    var action = "forceCloseStatus";

    if (txnJson != null) {
        var txnObj = $.parseJSON(txnJson);
       
       
            var actionTDElement = $("<td></td>");
            var spanElement = $("<span id="+txnObj._id+" class='iconSpan' > </span>");
           
            var iconElement =  $(document.createElement("a"))
                            .attr({ href: '#'})
                            .addClass("forceClosureAction")
                            .append($("<i class='fa fa-toggle-on' aria-hidden='true'></i>"));
                          
           
            spanElement.append(iconElement);
            actionTDElement.append(spanElement);
       
        rowCount++;
        var newTableRow =
            "<tr id='" + txnObj._id+ "DataRow' class='dataRow'>"
           
                +"<td>"    + txnObj._id + "</td>"
                +"<td>" + txnObj.device_code +"</td>"
                +"<td>" + txnObj.force_closure_by + "</td>"
                +"<td>" + actionTDElement.html() + "</td>"
                   
            +"</tr>";

   
        $('#batchClosureLogTable').append(newTableRow);
        $("#"+txnObj._id).on('click',function(){
            // Do something
           
            alert("hello");
           
        });

Wednesday, 20 November 2013

Session

Session : In the general session refers to a specific period of time. In the context of web application, it refers to  the information exchanged between client and server for a specific duration of time. The information could be User ID to authenticate the user or a state attribute associated with any user request.


The session is generally of 2 types:
1. User session which contains information related to the user such as user ID, user time out session etc.. This is mainly created to authenticate user.
2. State: An information about  particular User request with in session.A session object can have several attributes and each attribute is an Java object identified by String type key.We used to store state within session as attribute when it is very common information required on most of the requests or pages with in application.

How session is created:

Initially when user sends request to server. Server creates a token (session ID in encoded format )and send to client.Now client receives the token and 

There are 4 ways of session tracking:

  • Cookie
  • URL rewriting
  • Hidden variable
  • SSL (Secure Socket Layer)

Session Tracking

To associate a session with a user, a web container can use several methods, all of which involve passing an identifier between the client and the server. The identifier can be maintained on the client as a cookie, or the web component can include the identifier in every URL that is returned to the client.
If your application uses session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response’s encodeURL(URL) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, the method returns the URL unchanged.

Session Management

Session management is the process of keeping track of a user's activity across sessions of interaction with the web application.
Because an HTTP client has no way to signal that it no longer needs a session, each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed by using a session’s getMaxInactiveInterval and setMaxInactiveInterval methods.
  • To ensure that an active session is not timed out, you should periodically access the session by using service methods because this resets the session’s time-to-live counter.
  • When a particular client interaction is finished, you use the session’s invalidate method to invalidate a session on the server side and remove any session data.

Desktop session management[edit]

A desktop session manager is a program that can save and restore desktop sessions. A desktop session is all the windows currently running and their current content. Session management on Linux-based systems is provided by X session manager. On Microsoft Windows systems, no session manager is included in the system, but session management can be provided by third-party applications like twinsplay.

Browser session management[edit]

Session management is particularly useful in a web browser where a user can save all open pages and settings and restore them at a later date. To help recover from a system or application crash, pages and settings can also be restored on next run. Google ChromeMozilla FirefoxInternet ExplorerOmniWeb and Opera are examples of web browsers that support session management. Session management is often managed through the application of cookies.

Web server session management[edit]

Hypertext Transfer Protocol (HTTP) is stateless: a client computer running a web browser must establish a new Transmission Control Protocol (TCP) network connection to the web server with each new HTTP GET or POST request. The web server, therefore, cannot rely on an established TCP network connection for longer than a single HTTP GET or POST operation. Session management is the technique used by the web developer to make the stateless HTTP protocol support session state. For example, once a user has been authenticated to the web server, the user's next HTTP request (GET or POST) should not cause the web server to ask for the user's account and password again. For a discussion of the methods used to accomplish this see HTTP cookie and Session ID.

The session information is stored on the web server using the session identifier Session ID generated as a result of the first (sometimes the first authenticated) request from the end user running a web browser. The "storage" of Session IDs and the associated session data (user name, account number, etc.) on the web server is accomplished using a variety of techniques including, but not limited to, local memory, flat files, and databases.

Advantages of session:
  • User authentication : We have no need to send credentials with every user request instead a session related to User ID has sent from server to client which will be used with subsequently used with the user request to authenticate him.In Servlets session for User ID has maintained by sending a token from server to client which is actually in encoded format and used by the client for other request (named as jsessionid.........).It is identified by browser ID.However you can provide your own high level implementation of session to authenticate user such as session identified by machine IP address.Low level implementation such as identified by user ID only.This implementation can be done by overriding the methods of HttpSession Interface or child interfaces such as HttpSessionListener.
  • Security: We don't need to exchange confidential information such as User credentials between user requests to the server. Instead encrypted token ID sent by the web server is used to authenticate user.
  • Information persistance : We can persist the state information of a user between multiple requests.This information has resides in memory and expired after user session expires.However We can also persist the User session or Session state by writing such information to a file system or Database.We will discuss Session Persistence it later in detail
  • Mesaure User Traffic :The number of user sessions on a site is used in measuring the amount of traffic a Web site gets. The site administrator determines what the time frame of a user session will be (e.g., 30 minutes). If the visitor comes back to the site within that time period, it is still considered one user session because any number of visits within that 30 minutes will only count as one session. If the visitor returns to the site after the allotted time period has expired, say an hour from the initial visit, then it is counted as a separate user session.
    Contrast with unique visitorhitclick-through and page view, which are all other ways that site administrators measure the amount of traffic a Web site gets.
  • Loose Coupling : Since it is stored on server side  but you don't want that data to be maintained client side (in the cookie, in URL parameters (like http://www.foobar.com/myPage?asd=lol&boo=no), and so on...) because you don't want the client to play around with that data without passing through your (server side) code.
    The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented.
  • Transparent to user
Disadvantage of session:
  • Performance overhead in case of large volume of user, because of session data stored in server memory.
  • Overhead involved in serializing and De-Serializing session Data. because In case of StateServer and SQLServer session mode we need to serialize the object before store. 
  • If the worker Process or application domain recycles all session data will be lost. 
  • We can't use it in web Garden scenarios and is not suitable for web farm scenarios also.


There are some topics that need to discuss later
Session Persistance and when to persist session to file or database
Difference between cookie and session
Session in Distributed enviroment
Advantages and Disadvantages of using different session tracking approaches:





There are some questions related to session which generally occur in our mind?

Q. How would the client know about the session start on the server?
Ans : In general sessions are created by URL rewriting, hidden variable, cookies and SSL.

For Users of the site, it detected by watching the url when he sends the request second time
.However if the client use hidden variable approach  then the user will not come to know.

On the browser side (which is actually client),we can use some implicit object of JSP to identify whether a session has been created or not.However we have to pass false argument inside getAttribute() of session object to check otherwise the no arg version of getAttribute() method creates the session if not really exists.

Q. How would the client knows that the session has destroyed at server?
Ans :  Follow above approach or implement a service that read "isSessionAliveHeader" information at server side and return true or false

Q. When to store session in database
The two reasons I can think of are that:
1) If the web service is restarted, the session data is not lost
2) In a load balanced environment, the session data is stored in a central location, meaning any server can serve the request and have access to the session data.
Acessing/Creating session in different technolgies:


  • Servlet: 

      The HttpServletRequest interface provides two methods to get the object of HttpSession:
  1.  public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.
  2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
  1. HttpSession session=request.getSession();  
  2.         session.setAttribute("uname",n);  

Commonly used methods of HttpSession interface

  1. public String getId():Returns a string containing the unique identifier value.
  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
  4. public void invalidate():Invalidates this session then unbinds any objects bound to it
  5. public void setAttribute(String Key,Object value)
  6. public void getAttribute(String Key)



In struts 2.0:

There are 3 ways to access session in Struts 2.0

  • Using ActionContext class  -  ActionContext.getContext().getSession()
Map session = ActionContext.getContext().getSession();
session.put("logined","true");
       session.put("context", new Date());
  • Using ServletActionContext class - ServletActionContext.getRequest().getSession().put("myId", myProp); (Worst approach)
                In general this isn't recommended as it will tie our action to the servlet specification.
           HttpSession session = ServletActionContext.getRequest().getSession();
session.setAttribute("logined","true");
       session.setAttribute("context", new Date());

  • Using SessionAware Interface (Best approach) i.e injecting session object by SessionAware interceptor.
     You need to make your action implement SessionAware to get access to the session:
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.SessionAware;

public class MyAction extends extends ActionSupport implements SessionAware {
  
  // For SessionAware
  Map<String, Object> session;
  @Override
  public void setSession(Map<String, Object> session) {
    this.session = session;
  }
  
}
Once you've done that, you can access the session with code like this:
public String execute() {
  int division = ...

  // Write to the session
  session.put("division",(Integer)division);
  
  // Read from the session
  if (session.containsKey("division"))
    division=(Integer)session.get("division");
  
  return "success";
}
Generally in struts 2 third approach is preferred because

 Loose coupling by injecting session 
action class is directly tied to the ActionContext which is Struts2 specific way. One of the prime goal of Struts2 is to decouple Action classes from underlying HTTP context as well with other direct dependencies. Also writing test cases for plain POJO is way easy and better than the other way.
By implementing SessionAware interface you are indicating Struts2 that you want session as a simple map object, this not only making code much decoupled but easy to maintain and test
However first approach is preferred while writing interceptors because
Basically, for Actions you should use SessionAware (since you don't
have access to the ActionContext from within a standard Action). But
if you are writing an Interceptor, you would use ActionContext to get
access to the Session data.


Monday, 18 November 2013

Reading HTTP request headers from a servlet

Reference:


When a browser requests a web page, it generally sends some additional headers which specify things such as:
  • any cookies set for that page;
  • which browser or "agent" is making request, along with information about the operating system, installed browser plugins etc;
  • the referrer (generally the link that the user clicked on that provoked the request);
  • what types of content the browser can deal with.
It's beyond the scope of this tutorial to give all the details of every possibly HTTP request header. And it's actually quite rare to need to read request headers. If necessary, it is recommended that you look at the HTTP protocol specification if you need more details. However, we'll look at a couple of useful cases here by way of example.

Reading a request header

Usually, we'll know the name of the request header that we want to read. In this case, it is a simple matter of calling getHeader() on theHttpServletRequest object that was passed to our doGet()/doPost() method. For example, here is how to read the user-agent header, which essentially tells us which browser (IE, Mozilla, Safari etc) and operating system is making the request:
public final void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
  String agent = req.getHeader("user-agent");
  if (agent != null && agent.indexOf("MSIE") > -1) {
    // Internet Explorer mode
  } else {
    // Non-Internet Explorer mode
  }
}
Note that we should be careful of null values being returned for a given header if it wasn't sent by the client. Note that for a given header, knowing what the actual format of data that we might get can be something of a black art and the user-agent string is one of the worst offenders...!

Some useful headers

Although it is not so usual to need to read request headers, here are some possibly useful cases:
user-agent
As mentioned above, the user-agent can give us the browser (or robot) and version, plus some information about plugins installed. A big problem with this header is the wide variety of formats that different agents use in practice. (See the link for details and examples.)
referer
The referer header (yes, with the word "referrer" misspelt) indicates the link that caused the current item to be requested.

What not to use request heaeders for

You should remember that, like pretty much anything sent in a request to your server, request headers are untrusted data. It is trivial to program a client to set any old string it likes in any request header. You should interpret request headers as a statement about "how the client would like its data", and not as the basis for security-related decisions. The BBC discovered this the embarrasing way when they attempted towithhold iPhone content on the basis of the user-agent string. (For similar reasons, you should take phrases such as "hot link prevention" with a pinch of salt.)

Thursday, 3 October 2013

Ways to create JSON object


1.
String response = "[
    {"result":
    {"3":{"Hold":"0","Live":"1","Verification":"0","Conversion":"0","All":"1","Delivered":"0"},
    "2":{"Hold":"0","Live":"0","Verification":"1","Conversion":"0","All":"1","Delivered":"0"},
    "1":{"Hold":"1","Live":"0","Verification":"1","Conversion":"0","All":"2","Delivered":"0"}},"errCode":"0","isSuccess":"true"}
    ]"



JSONArray jsonArrayResponse = new JSONArray(response);

//display
"[
    {"result":
    {"3":{"Hold":"0","Live":"1","Verification":"0","Conversion":"0","All":"1","Delivered":"0"},
    "2":{"Hold":"0","Live":"0","Verification":"1","Conversion":"0","All":"1","Delivered":"0"},
    "1":{"Hold":"1","Live":"0","Verification":"1","Conversion":"0","All":"2","Delivered":"0"}},"errCode":"0","isSuccess":"true"}
    ]"





2.
JSON jsonObj = jsonArrayResponse.getJSONObject(0).getJSONObject("result");




//display {"3":{"Hold":"0","Live":"1","Verification":"0","Conversion":"0","All":"1","Delivered":"0"},
    "2":{"Hold":"0","Live":"0","Verification":"1","Conversion":"0","All":"1","Delivered":"0"},
    "1":{"Hold":"1","Live":"0","Verification":"1","Conversion":"0","All":"2","Delivered":"0"}},"errCode":"0","isSuccess":"true"}

3.
JSONObject x = (JSONObject) jsonObj.get("3");
//display
{"Hold":"0","Live":"1","Verification":"0","Conversion":"0","All":"1","Delivered":"0"}
               
JSONObject cvb = new JSONObject(jsonObj.get("3").toString());

{"Hold":"0","Live":"1","Verification":"0","Conversion":"0","All":"1","Delivered":"0"}

String hold1 =    cvb.get("Hold").toString();

// display 0
           
String hold =    x.get("Hold").toString();

//display 0

System.out.println(x);



One additional method


4. jsonObj = JSONFactoryUtil.createJSONObject(result);