Saturday, August 27, 2011

Notes for OCPJP

Section 7: Fundamentals

JSP
Jsps are servlets that are written in HTML, and is a server side web component, that can be used to generate dynamic web pages.
JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content. The main features of JSP technology are as follows:
• A language for developing JSP pages, which are text-based documents that
describe how to process a request and construct a response
• An expression language for accessing server-side objects
• Mechanisms for defining extensions to the JSP language
A JSP page is a text document that contains two types of text: static data, which
can be expressed in any text-based format (such as HTML, SVG, WML, and XML), and JSP elements, which construct dynamic content.
The recommended file extension for the source file of a JSP page is .jsp.

JSP Vs Servlet
Servlets generates HTML from Java code, where as Jsp embeds Java code inside static HTML.
Servlets are suited to decide to handle business logic, where as Jsp pages are well suited to display contents.

The MVC architecture
The MVC architecture is a widely used architectural approach for interactive applications that distributes functionality among application objects so as to minimize the degree of coupling between the objects. To achieve this, it divides applications into three layers: model, view, and controller. Each layer handles specific tasks and has responsibilities to the other layers:
• The model represents business data, along with business logic or operations that govern access and modification of this business data. The model notifies views when it changes and lets the view query the model about its state. It also lets the controller access application functionality encapsulated by the model.
• The view renders the contents of a model. It gets data from the model and specifies how that data should be presented. It updates data presentation when the model changes. A view also forwards user input to a controller.
• The controller defines application behavior. It dispatches user requests and selects views for presentation. It interprets user inputs and maps them into actions to be performed by the model. In a web application, user inputs are HTTP GET and POST requests. A controller selects the next view to display based on the user interactions and the outcome of the model operations.

Components of JSP
                 There are 3 main components of JSP
*HTML code
*JSP tags
*JSP implicit objects

1)HTML code
 This component of JSP page decides the static presentation layout of the page.

2)JSP tags
 This component is used to embed programming logic in HTML pages.They are broadly classified into six types.
•Declaration tags
•Expression tags
•Scriptlet tags
•Directive tags
•Comment tags
•Action tags

3)JSP Implicit objects
   There are 9 implicit objects
•request
•response
•pageContext
•session
•application
•out
•config
•page
•exception

Life cycle of JSP page
A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology.
When a request is mapped to a JSP page, the web container first checks whether the JSP page's servlet is older than the JSP page. If the servlet is older, the web container translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.
Event sequence of the JSP page life cycle:
 (1) JSP page translation
 (2) JSP page compilation
 (3) load class
 (4) create instance
 (5) call the jspInit method
 (6) call the _jspService method
 (7) call the jspDestroy method.

1. JSP Page Translation:
A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

2. JSP Page Compilation:
The generated java servlet file is compiled into a java servlet class.
Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

3. Class Loading:
The java servlet class that was compiled from the JSP source is loaded into the container.

4. Execution phase:
In the execution phase the container manages one or more instances of this class in response to requests and other events.
The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

5. Initialization:
jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

6. _jspService() execution:
This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.

7. jspDestroy() execution:
This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

OCPJP(J2SE 5) Syllabus

Section 1: Declarations, Initialization and Scoping



·         Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
·         Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
·         Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
·         Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.
·         Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.
Section 2: Flow Control



·         Develop code that implements an if or switch statement; and identify legal argument types for these statements.
·         Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.
·         Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
·         Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
·         Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.
·         Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.
Section 3: API Contents



·         Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
·         Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader,BufferedWriter, File, FileReader, FileWriter and PrintWriter.
·         Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
·         Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.
Section 4: Concurrency



·         Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
·         Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
·         Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.
Section 5: OO Concepts



·         Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
·         Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
·         Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
·         Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass or overloaded constructors.
·         Develop code that implements "is-a" and/or "has-a" relationships.
Section 6: Collections / Generics



·         Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
·         Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
·         Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions.
·         Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
·         Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.
Section 7: Fundamentals



·         Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
·         Given an example of a class and a command-line, determine the expected runtime behavior.
·         Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
·         Given a code example, recognize the point at which an object becomes eligible for garbage collection, and determine what is and is not guaranteed by the garbage collection system. Recognize the behaviors of System.gc and finalization.
·         Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
·         Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.

JavaScript Basics

JavaScript is the premier client-side scripting language used today on the Web. It’s widely used in tasks ranging from the validation of form data to the creation of complex user interfaces.JavaScript can be used to manipulate the very markup in the documents in which it is contained.
Our first look at JavaScript is the ever-popular “Hello World” example.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>JavaScript Hello World</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<h1 align="center">First JavaScript</h1>
<hr />
<script type="text/javascript">
  document.write("Hello World from JavaScript!");
</script>
</body>
</html>
Notice how the script is included directly in the markup using the <script> element that encloses the simple one-line script:
document.write("Hello World from JavaScript!");
If we wanted to bold the text we could modify the script to output not only some text but also some markup. However, we need to be careful when the world of JavaScript and the world of markup in XHTML, or HTML, intersect—they are two different technologies. For example, consider if we substituted the following <script> block in the preceding document, hoping that it would emphasize the text.
<script type="text/javascript">
<strong>
   document.write("Hello World from JavaScript!");
</strong>
</script>
Doing so should throw an error in our browser window. The reason is that <strong> tags are markup, not JavaScript. Because the browser treats everything enclosed in <script> tags as JavaScript, it naturally throws an error when it encounters something that is out of place.

To output the string properly we could either include the <strong> element directly within the output string, like so,
document.write("<strong>Hello World</strong> from
<font color='red'>JavaScript</font>!");
or we could surround the output of the <script> element in a <strong> element like this:
<strong>
<script type="text/javascript">
   document.write("Hello World from JavaScript!");
</script>
</strong>

Adding JavaScript to XHTML Documents
As suggested by the previous example, the <script> element is commonly used to add script to a document. However, there are four standard ways to include script in an (X)HTML document:
--Within the <script> element
--As a linked file via the src attribute of the <script> element
--Within an XHTML event handler attribute such as onclick
--Via the pseudo-URL javascript: syntax referenced by a link

The <script> Element
The primary method to include JavaScript within HTML or XHTML is the <script> element. A script-aware browser assumes that all text within the <script> tag is to be interpreted as some form of scripting language; by default this is generally JavaScript.
Traditionally, the way to indicate the scripting language in use is to specify the language attribute for the tag. For example,
<script language="JavaScript">
----
----
</script>
is used to indicate the enclosed content is to be interpreted as JavaScript. Other values are possible; for example,
<script language="VBS">
-----
-----
</script>
would be used to indicate VBScript is in use. A browser should ignore the contents of the <script> element when it does not understand the value of its language attribute.

Using the <script> Element
You can use as many <script> elements as you like. Documents will be read and possibly executed as they are encountered, unless the execution of the script is deferred for later. The next example shows the use of three simple printing scripts that run one after another.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>JavaScript and the Script Tag</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<h1>Ready start</h1>
<script type="text/javascript">
      alert("First Script Ran");
</script>
<h2>Running...</h2>
<script type="text/javascript">
      alert("Second Script Ran");
</script>
<h2>Keep running</h2>
<script type="text/javascript">
      alert("Third Script Ran");
</script>
<h1>Stop!</h1>
</body>
</html>

Script in the <head>
A special location for the <script> element is within the <head> tag of an (X)HTML document. Because of the sequential nature of Web documents, the <head> is always read in first, so scripts located here are often referenced later on by scripts in the <body> of the document. Very often scripts within the <head> of a document are used to define variables or functions that may be used later on in the document.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>JavaScript in the Head</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">
function alertTest()
{
  alert("Danger! Danger! JavaScript Ahead");
}
</script>
</head>
<body>
<h2 align="center">Script in the Head</h2>
<hr />
<script type="text/javascript">
 alertTest();
</script>
</body>
</html>

Script Hiding
Most browsers tend to display the content enclosed by any tags they don’t understand, so it is important to mask code from browsers that do not understand JavaScript. Otherwise, the JavaScript would show up as text in the page for these browsers.One easy way to mask JavaScript is to use HTML comments around the script code.
For example:
<script type="text/javascript">
<!--
  put your JavaScript here
//-->
</script>
The <noscript> Element
In the situation that a browser does not support JavaScript or that JavaScript is turned off, you should provide an alternative version or at least a warning message telling the user what happened. The <noscript> element can be used to accomplish this very easily. All JavaScript-aware browsers should ignore the contents of <noscript> unless scripting is off. Browsers that aren’t JavaScript-aware will show the enclosed message
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>noscript Demo</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<script type="text/javascript">
<!--
      alert("Your JavaScript is on!");
//-->
</script>
<noscript>
      <em>Either your browser does not support JavaScript or it is currently disabled.</em>
</noscript>
</body>
</html>

Event Handlers
To make a page more interactive, you can add JavaScript commands that wait for a user to perform a certain action. Typically, these scripts are executed in response to form actions and mouse movements. To specify these scripts, we set up various event handlers, generally by setting an attribute of an (X)HTML element to reference a script. We refer to these attributes collectively as event handlers—they perform some action in response to a user interface event. All of these attributes start with the word “on,” indicating the event in response to which they’re executed, for example, onclick, ondblclick, and onmouseover.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>JavaScript and HTML Events Example</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<form action="#" method="get">
<input type="button" value="press me"
       onclick="alert('Hello from JavaScript!');" />
</form>
</body>
</html>

Uses:
Some of the common uses of JavaScript include:
--Form validation
--Page embellishments and special effects
--Navigation systems
--Basic mathematical calculations
--Dynamic document generation
--Manipulation of structured documents
--JavaScript does have its limits. It does not support robust error-handling features, strong typing, or facilities useful for building large-scale applications








Firewalls

A firewall is a combination of hardware and software that serves as a gateway between the private network and the Internet. Predefined access and scope of use are required, and all other requests are blocked. An effective firewall should protect both the export and import of data from and to the private network.
If designed effectively, a firewall can look at every piece of data that passes into or out of a private network and decide whether to allow the passage based on the following:
• User identification
• Point of origin
• Point of destination
• The information contents
By careful examination of the packet that is trying to exit from or enter into the private network, a firewall can choose one of the following actions:
• Reject the incoming packet
• Send a warning to the network administrator
• Send a message to the sender of the message that the attempt has failed
• Allow the message to enter the private network
Types of Firewalls
Based on their functions, firewalls have been broadly classified into two groups
Packet filter firewalls control the data traffic (the export and import of data) based on datagrams.The filter examines fields in Internet Protocol (IP) packets such as source and destination IP addresses and source and desti- nation ports. By checking these fields, the packet filter can allow or deny pas- sage of packets. Factors that influence the rejection or acceptance of a datagram are based on the network application requested, protocol type, and the source and destination of the datagram. A packet filter firewall can be programmed to ac- cept or reject a datagram based on the host that initiated the datagram.
Packet filter firewalls may not be very efficient since they have to examine each packet individually, and they may be difficult to install. They may provide a false sense of security, and they usually cannot accurately record all of the ac- tions taking place at the firewall. This makes it difficult for network administra- tors to find out how intruders are trying to break into the private network.
           Application (proxy) firewalls are regarded as more secure and flexible and are therefore more expensive than packet filter firewalls. These firewalls are in- stalled in the host computer. A dedicated PC or a workstation may perform this task. An application firewall controls the private network applications, such as e-mail, Telnet, and FTP at the individual or group level by focusing on the type of action and the time period in which the action is taking place. By concentrat- ing on the time period, these firewalls can be very effective because many unau- thorized attempts take place at night or after hours. Application firewalls are able to log actions that take place at the firewall. By using these data, network ad- ministrators are able to identify potential breaches to security that may be di- rected to the private network. Application firewalls can also filter viruses, a ma- jor security threat in the e-commerce environment. Because application firewalls perform a great deal of work to check for unauthorized activities in a network,they have a relatively slow processing speed. This in turn may bring down the performance of the whole network.
In large organizations, proxy servers are also used in addition to firewalls for
protecting the security and integrity of a network.A proxy server is a server that acts as an intermediary between a workstation user and the Internet so that the organization can ensure security, administrative con trol, and caching services. Proxy servers separate the organization’s network from the outside network, and a firewall server protects the organization’s network from unauthorized outside access.

MVC - MVP : Difference between these design patterns?

In traditional UI development - developer used to create a  View  using window or usercontrol or page and then write all logical code ...