Tuesday, July 19, 2011

Playing video using html5

                    Prior to HTML 5 it was difficult to write code for playing video. Developer used to write code based on browser types and OS. In HTML 5 new tag has been introduced to support videos. Its very straight forward to use not much of coding involved in using it.


<video id="myVideo" poster="start.jpg" autoplay="autoplay" width="100px" height="150px"
    audio="muted" loop="loop" controls="controls" src="video.mp4" preload="auto">
</video>

Attribute                                   Description
autoplay=autoplay                     If present, then the video will start playing as soon as it is ready
poster=url                                 URL of image which should be shown when video is not playing.
preload=auto/metadata/none     Video should be loaded when the page loads. This value is ignored if                                                       autoplay is true. auto: loads complete video,
                                                  metadata: only metadata of video gets loaded, none: nothing will be loaded.
src=url                                      Location of video file. Additional Source tag also can be used to specfiy the                                                   video source file.
                                                         <source src="video.mp4" type="video/mp4"/>
width=pixels                             Specifies the width of video player window.
height=<NUM>pixels               Specifies the height of video player window.
controls=controls                      Displays the different controls, like play button, previous, next controls.
audio=muted                             If muted value given means video will start in mute mode.
loop=loop                                Video will start over again, every time it is finished

<source src="video.mp4" type="video/mp4" />

src=url                                      Location of video file.
type:MIME Type                      Specify the MIME type of the video file. e.g. video/mp4 etc
  
<video id="myVideo" poster="start.jpg" autoplay="autoplay" width="100px" height="150px"
    audio="muted" loop="loop" controls="controls" preload="auto">
<source src="video.mp4" type="video/mp4" />   
</video>

Limitations:
1. Can only be played in Latest Browsers which supports html 5.

Browser Support:

Internet Explorer Firefox Opera Google Chrome Safari

Friday, July 15, 2011

Client Side performance Improvement Opportunities

Many of the web application face major challenge for performance. There are various ways to improve performance of the website. It can be Server Side Code Improvement (e.g. code analysis and refactoring, db side changes etc), Hardware Side (improve on hardware configuration, increasing number of servers etc) and Client Side. When  i say client side here i mean User Interface (such as Image, JS, css etc). I am going to explain in this article about various opportunities for performance improvements from Client side. This is not very exhaustive list but some of the items which can be controlled and taken care easily.

o Avoid complete page refresh wherever possible. You can use AJAX calls. This way we can reduce amount of the network data to be transferred and complete page refresh.

o Use "GET" for AJAX request where ever possible if data being transferred is not sensitive, amount of data is less, or you are getting data from server. Reason behind this is POST request creates two connections for single submit one for header and other for body. But GET does this task in single connection. Get performs better then POST request.

o Minify the JS/CSS file. This will reduce the JS/CSS file size, which will be downloaded faster from server. Minifying JS/CSS removes unnecessary blank lines, comments. Which helps in reducing the file size. Less file size means less data to be downloaded from server.

o Reduce the number of js/css file, combine them in single and use them. Less number of file mean fewer HTTP request to server for downloading them.

o Optimize the image file. This process will reduce the image file size by little compromise on quality of the image. Check in Google there are online image optimizer available e.g.  http://tools.dynamicdrive.com/imageoptimizer/

o Put css in top and java script at the bottom of the code.

o Specify dimensions that match those of the images themselves. Create image of required size and use them rather than fixing size using height and width attribute in <img height="100px" width="100px" /> tag. E.g. if your application needs 100X100 image and you have same image but of different height X width say 300X300 than don’t set height and width to 100X100 in image tag for your need. Create image of required size and use it. This is because browser still downloads bigger size image.

o Specifying a width and height for all images allows for faster rendering by eliminating the need for unnecessary reflows and repaints. But make sure above point is taken care when you specify the image height and width.

o Avoid empty image tag. E.g. <img src="" /> or var img=new Image(); img.src="";

o Use png image on top of gif images.

o Use pngcrush to optimize the image before using them. http://pmt.sourceforge.net/pngcrush/

o Avoid 404 errors, this means make sure there are no reference to missing files in your jsp.

o Use Image Sprite. Image Sprite is collection of many images into single image. This way only one server call will be made and many images can be downloaded. Using css we can render the images from sprite image. There are websites using which you can generate css for sprite images. e.g. http://www.spritebox.net/
below image is sprite image, where two images are combined in single image.




below css will split the image into two separate image.
img.im1{width:51px;height:32px;background-position:-1px -1px;background-repeat:no-repeat;background:url(sprites.JPG); }
img.im2{width:52px;height:33px;background-position:-54px -1px;background-repeat:no-repeat;background:url(sprites.JPG); }


you need to use these class in <img> tag as shown below:
<img class="im1" src="img_trans.gif"  width="1" height="1" />
<img class="im2" src="img_trans.gif" width="1" height="1" />
here src is one transparent image, this is required to be mentioned... below is snap how it comes in browser.



Tuesday, July 5, 2011

AJAX Integration with DOJO

 Dojo is an open source framework which provides various inbuilt functions for AJAX, Widgets, Events, and Effects etc. These functions make life easier for the developer. They provide complete abstraction from the complexity involved behind the scene. I am going to cover AJAX feature provided by Dojo in this article.
Normally when we code for AJAX we think of creating request, forming the data which needs to be sent to server, error handling, timeout scenarios, response handling etc. We can’t escape from any of these points when we write coding and due to this code becomes complex and cumbersome to understand and maintain. Dojo provides cleaner and easier approach to create a code for handling AJAX calls.
Dojo Basics:
Two types of request are sent to server for any AJAX request, Post and Get. Dojo provides two function for these two types dojo.xhrGet and dojo.xhrPost methods. These two functions have all the AJAX capabilities in built. It takes care of creating request, forming the data which needs to be sent to server, error handling, timeout scenarios, response handling etc.
dojo.xhrGet({
    url: "/pojoProj/ dojoCall.jsp",
    load: function(result) {
        alert(result);
     }
});

                There are various arguments available for these functions, I have shown below how to use them while coding and their description.

dojo.xhrGet({ // Function Name, this can be dojo.xhrGet/ dojo.xhrPost
// url, This is the Server URL to which AJAX request will go.
                url: "/pojoProj/search.jsp",
                // content, This is the parameter which will be passed to above URL,  to access these parameter use normal request.getParameter(“studentName”). Based on type POST/GET parameter will be send to server either as post data or url string.
                content: {                           
studentName: dojouser,
                                class: 12,
                },
//timeout, This value is milliseconds; request will wait for specified time than after that it will treat as failure.                               
                timeout: 10000,

                //
                form: dojo.byId(<<formName>>),

                //load is called after successful response.  This function will not be called in case of any error or exception.
load: function(resp) {
                                if(<<condition>>){
                                                <<actions>>
                                }else{
                                                <<actions>>
                                }
                },
                // The error handler, this function will be called in case of failure. You can use first argument to display error message if there are any.
                error: function(errorMessage) {
                                alert(errorMessage);
                },
// handle will be called always, in case of success and failure of the request.
                handle: function (response, ioArgs) {
                                alert("hello");
                }
});

Create web project and create two jsp for testing below code. Below example is only for plain text response, in coming blogs i will explain different ways of handling the response like JSON, XML...
Complete Code Sample:
Index.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script language="javascript" src="js/dojo/dojo_uncompressed.js"></script>
<script>
function findStudent() {
                var stdName=dojo.byId("stdId").value;
                dojo.xhrGet({
                                url: "/dojo_json_sampleapp/dojoCall.jsp",
                                content: {
                                                stdname:stdName
                                },                                            
                                timeout: 10000,
                                load: function(resp) {
                                if(resp.trim() != ""){
                                                dojo.byId("respNode").innerHTML = stdName+" is in "+resp;
                                }else{
                                                dojo.byId("respNode").innerHTML = "Student detail is not available for "+stdName;
                                }
                                },
                                error: function(errorMessage) {
                                                alert(errorMessage);
                                }
                });
}

dojo.ready(function(){
                dojo.connect(dojo.byId("stdId"),"onkeyup",findStudent);
});
</script>
</head>
<body>
                Student Name: <input type="text" name="studentName" id="stdId" value="" />
                <p>Student Details: <span id="respNode"> </span></p>
</body>
</html>

Search.jsp
<%
if("pojo1".equals(request.getParameter("stdname"))){
      System.out.println(" 11111 ");
      out.print("4th standard");
}else if("pojo2".equals(request.getParameter("stdname"))){
      System.out.println(" 22222 ");
      out.print("5th standard");
}else{
      System.out.println(" 33333 ");
      out.print("");
}
%>

You can download the dojo js file from this url:  http://dojotoolkit.org/

Important Notes:
1. Use get method if you don't have large data to be submitted to server and if you are retrieving data from the server. As get creates only one connection to the server for complete request. Post creates two connection one for header and one for body. You will have better performance in Get.


Thursday, June 30, 2011

Use JSTL Tag to avoid Cross Site Scripting issue

JSTL is very common word across web developer who work on dynamic content display in JSP page creation. It may be common practice now a days but thought it would worth sharing this information. This information will be helpful...

Lots of developer use normal scriptlet to print dynamic values from user in JSP.

e.g.
String langId = request.getParameter("langId");
<%=langId %>

     This might be fast way to do the coding but not the safest way. This approach will make your website vulnerable to security threats
like Cross Site Scripting. And can be easily used by malicious user to do some fishing in your website. Malicious User's can use this loop hole to redirect to some
fishing website and capture critical user data.

To address this issue there are many approaches available but one of the better and simpler approach is to use JSTL tags. These tags takes care of these above mentioned issues on its own. No additional coding is required.

If you use <c:out value="${param.langId}"/> instead of <%=langId %>, will resolve cross site scripting issue. So I would recommend use of jstl tags.

There is attribute to c:out tag escapeXml, it can have "false" or "true" values.
true = declare the conversion of XML entities, this is the default
false = declare NO conversion of XML entities, normal script execution will be done, similar as of scriptlet.



I did small POC for verifying JSTL tags.Below screen shot is one of the simple example for showing alert in application by passing scripts as part of parameter.
You can see the below screen shot where in url i passed alert as parameter value to langId=-1--%253e%253csCrIpT%253ealert("XSS")%253c%2fsCrIpT%253e, where in code
scriptlet is being used. I was able to execute the script code passed in parameter. You can see the alert which poped up due to use of scriptlet application code.











When i changed the above <%=langId %> to <c:out value="${param.langId}"/> application did not show the alert which came in previous example.

This is because c:out tag does not try to render the value as valid javascript tag, but it print the value <script> in UI.

Hope this information helps...

Also check SQL injection/CSRF  and CSS with Filter post, i will be posting some more security vulnerabilities posts in coming days, and their solutions. 

Monday, June 27, 2011

String and String Buffer Comparison

Thinking java String concatenation internally uses StringBuffer to do the concatenation operation, we do concatenation as mentioned below in java code,


String str=a+b; a and b is string objects.


java compiler compiles above code in this fashion:


String str=(new StringBuffer()).append(a).append(b).toString());

    Above code creates two objects, and as you must be knowing that java maintains the string data in char array which is also an object so it creates 1 more object. So in total 3 objects gets created for one concatenation operation. Please note that object creation is one of the costliest operation in java.

    I created one test program just to see the performance difference and results were dramatic... i ran both loop in same program 1 million times. See the time difference... So based on below result its  recommended to use StringBuffer.append whenever you are doing any concatenation operation in java...

    time taken by string: 78080 (ms)
    time taken by String buffer: 31 (ms)


Components of Big Data - Hadoop System

In this blog i will explain important components which are part of Hadoop System. I will give very brief overview of these components. Be...