Thursday, June 4, 2015

Improve knowledge about JavaScript Object Notation -DataTypes and Objects

There are following datatypes supported by JSON format:
TypeDescription
Numberdouble- precision floating-point format in JavaScript
Stringdouble-quoted Unicode with backslash escaping
Booleantrue or false
Arrayan ordered sequence of values
Valueit can be a string, a number, true or false, null etc
Objectan unordered collection of key:value pairs
Whitespacecan be used between any pair of tokens
nullempty

Number

  • It is a double precision floating-point format in JavaScript and it depends on implementation.
  • Octal and hexadecimal formats are not used.
  • No NaN or Infinity is used in Number.
The following table shows number types:
TypeDescription
IntegerDigits 1-9, 0 and positive or negative
FractionFractions like .3, .9
ExponentExponent like e, e+, e-,E, E+, E-

SYNTAX:

var json-object-name = { string : number_value, .......}

EXAMPLE:

Example showing Number Datatype, value should not be quoted:
var obj = {marks: 97}

String

  • It is a sequence of zero or more double quoted Unicode characters with backslash escaping.
  • Character is a single character string i.e. a string with length 1.
The table shows string types:
TypeDescription
"double quotation
\reverse solidus
/solidus
bbackspace
fform feed
nnew line
rcarriage return
thorizontal tab
ufour hexadecimal digits

SYNTAX:

var json-object-name = { string : "string value", .......}

EXAMPLE:

Example showing String Datatype:
var obj = {name: 'Amit'}

Boolean

It includes true or false values.

SYNTAX:

var json-object-name = { string : true/false, .......}

EXAMPLE:

var obj = {name: 'Amit', marks: 97, distinction: true}

Array

  • It is an ordered collection of values.
  • These are enclosed square brackets which means that array begins with .[. and ends with .]..
  • The values are separated by ,(comma).
  • Array indexing can be started at 0 or 1.
  • Arrays should be used when the key names are sequential integers.

SYNTAX:

[ value, .......]

EXAMPLE:

Example showing array containing multiple objects:
{
  "books": [
   { "language":"Java" , "edition":"second" },
   { "language":"C++" , "lastName":"fifth" },
   { "language":"C" , "lastName":"third" }
  ]
}

Object

  • It is an unordered set of name/value pairs.
  • Object are enclosed in curly braces that is it starts with '{' and ends with '}'.
  • Each name is followed by ':'(colon) and the name/value pairs are separated by , (comma).
  • The keys must be strings and should be different from each other.
  • Objects should be used when the key names are arbitrary strings

SYNTAX:

{ string : value, .......}

EXAMPLE:

Example showing Object:
{
 "id": "011A",
 "language": "JAVA",
 "price": 500,
}

Whitespace

It can be inserted between any pair of tokens. It can be added to make code more readable. Example shows declaration with and without whitespace:

SYNTAX:

{string:"   ",....}

EXAMPLE:

var i= "   sachin";
var j = "  saurav"

null

It means empty type.

SYNTAX:

null

EXAMPLE:

var i = null;

if(i==1) 
{
   document.write("<h1>value is 1</h1>"); 
}
else
{
   document.write("<h1>value is null</h1>");
}

JSON Value

It includes:
  • number (integer or floating point)
  • string
  • boolean
  • array
  • object
  • null

SYNTAX:

String | Number | Object | Array | TRUE | FALSE | NULL


Creating Simple Objects

JSON objects can be created with Javascript. Let us see various ways of creating JSON objects using Javascript:
  • Creation of an empty Object:
var JSONObj = {};
  • Creation of new Object:
var JSONObj = new Object();
  • Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attributes is accessed by using '.' Operator:
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
This is an example which shows creation of an object in javascript using JSON, save the below code asjson_object.htm:
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language="javascript" >

  var JSONObj = { "name" : "tutorialspoint.com", "year"  : 2005 };
  document.write("<h1>JSON with JavaScript example</h1>");
  document.write("<br>");
  document.write("<h3>Website Name="+JSONObj.name+"</h3>");  
  document.write("<h3>Year="+JSONObj.year+"</h3>");  

</script>
</head>
<body>
</body>
</html>
Now let's try to open json_object.htm using IE or any other javascript enabled browser, this produces the following result:
json objects

Creating Array Objects

Below example shows creation of an array object in javascript using JSON, save the below code asjson_array_object.htm:
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >

document.writeln("<h2>JSON array object</h2>");

var books = { "Pascal" : [ 
      { "Name"  : "Pascal Made Simple", "price" : 700 },
      { "Name"  : "Guide to Pascal", "price" : 400 }
   ],                       
   "Scala"  : [
      { "Name"  : "Scala for the Impatient", "price" : 1000 }, 
      { "Name"  : "Scala in Depth", "price" : 1300 }
   ]    
}    

var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{ 
   document.writeln("<td>");
   document.writeln("<table border='1' width=100 >");
   document.writeln("<tr><td><b>Name</b></td><td width=50>"
   + books.Pascal[i].Name+"</td></tr>");
   document.writeln("<tr><td><b>Price</b></td><td width=50>"
   + books.Pascal[i].price +"</td></tr>");
   document.writeln("</table>");
   document.writeln("</td>");
}

for(i=0;i<books.Scala.length;i++)
{
   document.writeln("<td>");
   document.writeln("<table border='1' width=100 >");
   document.writeln("<tr><td><b>Name</b></td><td width=50>"
   + books.Scala[i].Name+"</td></tr>");
   document.writeln("<tr><td><b>Price</b></td><td width=50>"
   + books.Scala[i].price+"</td></tr>");
   document.writeln("</table>");
   document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open json_array_object.htm using IE or any other javascript enabled browser, this produces the following result:
json array objects




Improve knowledge about JavaScript Object Notation

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers which include C, C++, Java, Python, Perl etc.
  • JSON stands for JavaScript Object Notation.
  • This format was specified by Douglas Crockford.
  • This was designed for human-readable data interchange
  • It has been extended from the JavaScript scripting language.
  • The filename extension is .json
  • JSON Internet Media type is application/json
  • The Uniform Type Identifier is public.json

Uses of JSON

  • It is used when writing JavaScript based application which includes browser extension and websites.
  • JSON format is used for serializing & transmitting structured data over network connection.
  • This is primarily used to transmit data between server and web application.
  • Web Services and API.s use JSON format to provide public data.
  • It can be used with modern programming languages.

Characteristics of JSON

  • Easy to read and write JSON.
  • Lightweight text based interchange format
  • Language independent.

Simple Example in JSON

Example shows Books information stored using JSON considering language of books and there editions:
{
    "book": [
    {
       "id":"01",
       "language": "Java",
       "edition": "third",
       "author": "Herbert Schildt"
    },
    {
       "id":"07",
       "language": "C++",
       "edition": "second"
       "author": "E.Balagurusamy"
    }]
}
After understanding the above program we will try another example, let's save the below code asjson.htm:
<html>
<head>
<title>JSON example</title>
<script language="javascript" >
  
  var object1 = { "language" : "Java", "author"  : "herbert schildt" };
  document.write("<h1>JSON with JavaScript example</h1>");
  document.write("<br>");
  document.write("<h3>Language = " + object1.language+"</h3>");  
  document.write("<h3>Author = " + object1.author+"</h3>");   

  var object2 = { "language" : "C++", "author"  : "E-Balagurusamy" };
  document.write("<br>");
  document.write("<h3>Language = " + object2.language+"</h3>");  
  document.write("<h3>Author = " + object2.author+"</h3>");   
  
  document.write("<hr />");
  document.write(object2.language + " programming language can be studied " +
  "from book written by " + object2.author);
  document.write("<hr />");
  
</script>
</head>
<body>
</body>
</html>

JSON - Syntax

Let's have a quick look on JSON basic syntax. JSON syntax is basically considered as subset of JavaScript syntax, it includes the following:
  • Data is represented in name/value pairs
  • Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).
  • Square brackets hold arrays and values are separated by ,(comma).
Below is a simple example:
{
    "book": [
    {
       "id":"01",
       "language": "Java",
       "edition": "third",
       "author": "Herbert Schildt"
    },
    {
       "id":"07",
       "language": "C++",
       "edition": "second"
       "author": "E.Balagurusamy"
    }]
}

Wednesday, June 3, 2015

Improve knowledge about Servlets - Client HTTP Request

When a browser requests for a web page, it sends lot of information to the web server which can not be read directly because this information travel as a part of header of HTTP request. You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you would use very frequently in web programming:
HeaderDescription
AcceptThis header specifies the MIME types that the browser or other clients can handle. Values of image/png or image/jpegare the two most common possibilities.
Accept-CharsetThis header specifies the character sets the browser can use to display the information. For example ISO-8859-1.
Accept-EncodingThis header specifies the types of encodings that the browser knows how to handle. Values of gzip or compress are the two most common possibilities.
Accept-LanguageThis header specifies the client's preferred languages in case the servlet can produce results in more than one language. For example en, en-us, ru, etc.
AuthorizationThis header is used by clients to identify themselves when accessing password-protected Web pages.
ConnectionThis header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alive means that persistent connections should be used
Content-LengthThis header is applicable only to POST requests and gives the size of the POST data in bytes.
CookieThis header returns cookies to servers that previously sent them to the browser.
HostThis header specifies the host and port as given in the original URL.
If-Modified-SinceThis header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available.
If-Unmodified-SinceThis header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date.
RefererThis header indicates the URL of the referring Web page. For example, if you are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referer header when the browser requests Web page 2.
User-AgentThis header identifies the browser or other client making the request and can be used to return different content to different types of browsers.

Methods to read HTTP Header:

There are following methods which can be used to read HTTP header in your servlet program. These methods are available with HttpServletRequest object.
S.N.Method & Description
1
Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this request.
2
Enumeration getAttributeNames()
Returns an Enumeration containing the names of the attributes available to this request.
3
Enumeration getHeaderNames()
Returns an enumeration of all the header names this request contains.
4
Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request.
5
HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
6
HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.
7
Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.
8
Object getAttribute(String name)
Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.
9
ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream.
10
String getAuthType()
Returns the name of the authentication scheme used to protect the servlet, for example, "BASIC" or "SSL," or null if the JSP was not protected.
11
String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.
12
String getContentType()
Returns the MIME type of the body of the request, or null if the type is not known.
13
String getContextPath()
Returns the portion of the request URI that indicates the context of the request.
14
String getHeader(String name)
Returns the value of the specified request header as a String.
15
String getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
16
String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist.
17
String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request.
18
String getProtocol()
Returns the name and version of the protocol the request.
19
String getQueryString()
Returns the query string that is contained in the request URL after the path.
20
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
21
String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
22
String getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.
23
String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.
24
String getRequestedSessionId()
Returns the session ID specified by the client.
25
String getServletPath()
Returns the part of this request's URL that calls the JSP.
26
String[] getParameterValues(String name)
Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
27
boolean isSecure()
Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
28
int getContentLength()
Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known.
29
int getIntHeader(String name)
Returns the value of the specified request header as an int.
30
int getServerPort()
Returns the port number on which this request was received.

HTTP Header Request Example:

Following is the example which uses getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and usingnextElement() method to get each parameter name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 
// Extend HttpServlet class
public class DisplayHeader extends HttpServlet {
 
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
   String title = "HTTP Header Request Example";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n"+
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<h1 align=\"center\">" + title + "</h1>\n" +
        "<table width=\"100%\" border=\"1\" align=\"center\">\n" +
        "<tr bgcolor=\"#949494\">\n" +
        "<th>Header Name</th><th>Header Value(s)</th>\n"+
        "</tr>\n");
 
      Enumeration headerNames = request.getHeaderNames();
      
      while(headerNames.hasMoreElements()) {
         String paramName = (String)headerNames.nextElement();
         out.print("<tr><td>" + paramName + "</td>\n");
         String paramValue = request.getHeader(paramName);
         out.println("<td> " + paramValue + "</td></tr>\n");
      }
      out.println("</table>\n</body></html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}
Now calling the above servlet would generate following result:

HTTP Header Request Example

Header NameHeader Value(s)
accept*/*
accept-languageen-us
user-agentMozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; MS-RTC LM 8)
accept-encodinggzip, deflate
hostlocalhost:8080
connectionKeep-Alive
cache-controlno-cache

Created upload function and file upload progress bar

Our new project is Document Management System. A document management system (DMS) is a system (based on computer programs in the case of the management of digital documents) used to track, manage and store documents. Most are capable of keeping a record of the various versions created and modified by different users (history tracking). The term has some overlap with the concepts of content management systems. It is often viewed as a component of enterprise content management (ECM) systems and related to digital asset management, document imaging, workflow systems and records management systems. So I also assign to this project in my supervisor. So I also created some parts in this project. I created upload function and file upload progress bar for this project.All steps are mention below.