Java Servlet and JSP Web Application 6

In the previous five posts, I provided an implementation of a typical web application in Java Servlet 3.0 and JSP, although it is in a simplified format (without input checking, validation etc).  In this post, I will conclude the series by borrowing a few drawings from a book at IBM redbooks website Servlet and JSP Programming with IBM WebSphere Studio and VisualAge for Java, in order to highlight a web application component flow (design pattern), a web application structure (component descriptions) and a web application topology (typical target runtime/production environment). I highly recommend the book to everyone.

1. Web Application Component Flow

Web Application Component Flow

Web Application Component Flow

Design Pattern: Model-View-Controller

This design follows the Model-View-Controller design pattern:

  • The JSPs (and HTML pages) provide the view.
  • The servlet is the controller.
  • The command beans represent the model.

The data beans contain the data of the model, and the view beans are helper classes to provide a data channel between the view and the model. The servlet (controller) interacts with the model (the command beans) and the view (the JSPs). The servlet controls the application flow.

2. Web Application Structure

Web Application Structure (J2EE)

Web Application Structure (J2EE)

HTML page

The input page for each step is either a static HTML page or a dynamic HTML page created from a previous step. The HTML page contains one or multiple forms that invoke a servlet for processing of the next interaction. Input data can be validated through JavaScript in the HTML page or passed to the servlet for detailed validation.

Servlet

The servlet gets control from the Application Server to perform basic control of flow. The servlet validates all the data, and returns to the browser if data is incomplete or invalid.
For valid data, processing continues. The servlet sets up and calls command beans that perform the business logic. The servlet initializes the view beans and registers them with the request block so that the JSPs can find the view beans. Depending on the results of the command beans, the servlet calls a JSP for output processing and formatting.

Command beans

Command beans control the processing of the business logic. Business logic may be imbedded in the command bean, or the command bean delegates processing to back-end or enterprise systems, such as relational databases, transaction systems (CICS, MQSeries, IMS, and so forth). A command bean may perform one specific function, or it may contain many methods, each for a specific task. Command beans may be called Task
Wrappers in such a case. Results of back-end processing are stored in data beans.

Data beans

Data beans hold the results of processing that was performed by the command bean or by back-end systems. For example, a data bean could contain an SQL result or the communication area of a CICS transaction. Data beans may not provide the necessary methods for a JSP to access the data; that is where the view beans provide the function.

View beans

View beans provide the contract between the output producing JSPs and the data beans that contain the dynamic data to be displayed in the output. Each view bean contains one or multiple data beans and provides tailored methods so that the JSP has access to the data stored in the data beans.

JSPs

The JSPs generate the output for the browser. In many cases that output again contains forms to enable the user to continue an interaction with the application. JSPs use tags to declare the view beans. Through the view beans, the JSP gets access to all the dynamic data that must be displayed in the output.

3. Web Application Topology

Web Application Topology

Web Application Topology

A program to simulate the Countdown Pedestrian Signals (CPS)

Countdown pedestrian signals (CPS) model is defined in Section 4E.02 of the 2009 Edition of the U.S. FHWA Manual on Uniform Traffic Control Devices with four indications (in fact only three can be used) presented in the following sequence:

  1. A steady WALKING PERSON (symbolizing WALK) signal indication means that a pedestrian facing the signal indication is permitted to start to cross the roadway in the direction of the signal indication, possibly in conflict with turning vehicles. The pedestrian shall yield the right-of-way to vehicles lawfully within the intersection at the time that the WALKING PERSON (symbolizing WALK) signal indication is first shown.
  2. A flashing UPRAISED HAND (symbolizing DONT WALK) signal indication means that a pedestrian shall not start to cross the roadway in the direction of the signal indication, but that any pedestrian who has already started to cross on a steady WALKING PERSON (symbolizing WALK) signal indication shall proceed to the far side of the traveled way of the street or highway, unless otherwise directed by a traffic control device to proceed only to the median of a divided highway or only to some other island or pedestrian refuge area.
  3. A steady UPRAISED HAND (symbolizing DONT WALK) signal indication means that a pedestrian shall not enter the roadway in the direction of the signal indication.
  4. A flashing WALKING PERSON (symbolizing WALK) signal indication has no meaning and shall not be used.

Thumbnail image of Figure 4E-1

This simulation program (output shown belows) simplifies the model into two main indications sequence (WALK and DON’T WALK). It demonstrates the techniques of rotation of image views and the implemtation of count down LED clock class in JavaFX. It can easily be changed to include the additional transition indication into the full three indications sequence in the official model.

Output of Pedestrian Signal Light Simulation with Countdown Clock

Output of Pedestrian Signal Light Simulation with Countdown Clock

The program takes the system clock and slices it into milli seconds for the count down pulses. The model also divides the ONE minute into two 30 seconds intervals: one 30 seconds for WALK and another 30 seconds for DONT WALK. It can be further enhanced with the pulse sounds if you like.

(Acknowledgement: Part of code of the clock class originates from Oracle’s digital clock sample).

PedestrianSignal.java

/**
 * Purpose: A program to simulate the pedestrian signal light
 *    with a thirty second count-down LED clock.
 * Resources: walk.jpg and dont_walk.jpg (you can download from anywhere on web)
 *
 * Author:  https://henry416.wordpress.com
 *
 * Compile: javac -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar" PedestriannSignal.java
 * Execute: java -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar";. PedestriannSignal
 */
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.effect.Effect;
import javafx.scene.effect.Glow;
import javafx.scene.effect.InnerShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.transform.Scale;
import javafx.scene.transform.Shear;
import javafx.util.Duration;
import java.util.Calendar;
 public class PedestrianSignal extends Application {
    private Clock clock;
    private Calendar calendar = Calendar.getInstance();
    private Image img_dont_walk = new Image("dont_walk.jpg");
    private Image img_walk = new Image("walk.jpg");
    private ImageView iv = new ImageView();

     @Override public void start(Stage stage) {
         calendar.setTimeInMillis(System.currentTimeMillis());
         int seconds = 60-calendar.get(Calendar.SECOND);
         Group root = new Group();
         Scene scene = new Scene(root);
         scene.setFill(Color.BLACK);
         VBox box = new VBox();

         // load the image
            if (seconds>30)
              { iv.setImage(img_dont_walk);}
            else
              { iv.setImage(img_walk);}

         // resizes the image to have width of 120 while preserving the ratio and using
         // higher quality filtering method; this ImageView is also cached to
         // improve performance
         iv.setImage(img_walk);
         iv.setFitWidth(120);
         iv.setPreserveRatio(true);
         iv.setSmooth(true);
         iv.setCache(true);

         box.getChildren().add(iv);

         // add digital clock
         clock = new Clock(Color.ORANGERED, Color.rgb(50,50,50));
         clock.setLayoutX(45);
         clock.setLayoutY(186);
         clock.getTransforms().add(new Scale(0.83f, 0.83f, 0, 0));
         // add clock to bo
         box.getChildren().add(clock);
         root.getChildren().add(box);

         stage.setTitle("Pedestrian Test");
         stage.setWidth(120);
         stage.setHeight(300);
         stage.setScene(scene);
         stage.sizeToScene();
         stage.show();
     }
    public void play() {
        clock.play();
    }
    @Override public void stop() {
        clock.stop();
    }
    /**
     * Clock made of 6 of the Digit classes for hours, minutes and seconds.
     */
    public class Clock extends Parent {
        private Digit[] digits;
        private Timeline delayTimeline, secondTimeline;
        public Clock(Color onColor, Color offColor) {
            // create effect for on LEDs
            Glow onEffect = new Glow(1.7f);
            onEffect.setInput(new InnerShadow());
            // create effect for on dot LEDs
            Glow onDotEffect = new Glow(1.7f);
            onDotEffect.setInput(new InnerShadow(5,Color.BLACK));
            // create effect for off LEDs
            InnerShadow offEffect = new InnerShadow();
            // create digits
            digits = new Digit[2];
            for (int i = 0; i < 2; i++) {
                Digit digit = new Digit(onColor, offColor, onEffect, offEffect);
                digit.setLayoutX(i * 80 + ((i + 1) % 2) * 20);
                digits[i] = digit;
                getChildren().add(digit);
            }
            // update digits to current time and start timer to update every second
            refreshClocks();
            play();
        }
        private void refreshClocks() {
            calendar.setTimeInMillis(System.currentTimeMillis());
            int seconds = 60-calendar.get(Calendar.SECOND);
            // load the image
            if (seconds>30)
              { iv.setImage(img_dont_walk);}
            else
              { iv.setImage(img_walk);}

            if (seconds >30)
              { seconds = seconds -30; }
            digits[0].showNumber(seconds / 10);
            digits[1].showNumber(seconds % 10);
        }
        public void play() {
            // wait till start of next second then start a timeline to call refreshClocks() every second
            delayTimeline = new Timeline();
            delayTimeline.getKeyFrames().add(
                    new KeyFrame(new Duration(1000 - (System.currentTimeMillis() % 1000)), new EventHandler<ActionEvent>() {
                        @Override public void handle(ActionEvent event) {
                            if (secondTimeline != null) {
                                secondTimeline.stop();
                            }
                            secondTimeline = new Timeline();
                            secondTimeline.setCycleCount(Timeline.INDEFINITE);
                            secondTimeline.getKeyFrames().add(
                                    new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
                                        @Override public void handle(ActionEvent event) {
                                            refreshClocks();
                                        }
                                    }));
                            secondTimeline.play();
                        }
                    })
            );
            delayTimeline.play();
        }
        public void stop(){
            delayTimeline.stop();
            if (secondTimeline != null) {
                secondTimeline.stop();
            }
        }
    }
    /**
     * Simple 7 segment LED style digit. It supports the numbers 0 through 9.
     */
    public static class Digit extends Parent {
        private static final boolean[][] DIGIT_COMBINATIONS = new boolean[][]{
                new boolean[]{true, false, true, true, true, true, true},
                new boolean[]{false, false, false, false, true, false, true},
                new boolean[]{true, true, true, false, true, true, false},
                new boolean[]{true, true, true, false, true, false, true},
                new boolean[]{false, true, false, true, true, false, true},
                new boolean[]{true, true, true, true, false, false, true},
                new boolean[]{true, true, true, true, false, true, true},
                new boolean[]{true, false, false, false, true, false, true},
                new boolean[]{true, true, true, true, true, true, true},
                new boolean[]{true, true, true, true, true, false, true}};
        private final Polygon[] polygons = new Polygon[]{
                new Polygon(2, 0, 52, 0, 42, 10, 12, 10),
                new Polygon(12, 49, 42, 49, 52, 54, 42, 59, 12f, 59f, 2f, 54f),
                new Polygon(12, 98, 42, 98, 52, 108, 2, 108),
                new Polygon(0, 2, 10, 12, 10, 47, 0, 52),
                new Polygon(44, 12, 54, 2, 54, 52, 44, 47),
                new Polygon(0, 56, 10, 61, 10, 96, 0, 106),
                new Polygon(44, 61, 54, 56, 54, 106, 44, 96)};
        private final Color onColor;
        private final Color offColor;
        private final Effect onEffect;
        private final Effect offEffect;
        public Digit(Color onColor, Color offColor, Effect onEffect, Effect offEffect) {
            this.onColor = onColor;
            this.offColor = offColor;
            this.onEffect = onEffect;
            this.offEffect = offEffect;
            getChildren().addAll(polygons);
            getTransforms().add(new Shear(-0.1,0));
            showNumber(0);
        }
        public void showNumber(Integer num) {
            if (num < 0 || num > 9) num = 0; // default to 0 for non-valid numbers
            for (int i = 0; i < 7; i++) {
                polygons[i].setFill(DIGIT_COMBINATIONS[num][i] ? onColor : offColor);
                polygons[i].setEffect(DIGIT_COMBINATIONS[num][i] ? onEffect : offEffect);
            }
        }
    }
     public static void main(String[] args) {
         Application.launch(args);
     }
 }

New standard for C was published

ISO/IEC 9899:2011 specifies the form and establishes the interpretation of programs written in the C programming language.It specifies

  • the representation of C programs;
  • the syntax and constraints of the C language;
  • the semantic rules for interpreting C programs;
  • the representation of input data to be processed by C programs;
  • the representation of output data produced by C programs;
  • the restrictions and limits imposed by a conforming implementation of C.

ISO/IEC 9899:2011 is designed to promote the portability of C programs among a variety of data-processing systems. It is intended for use by implementers and programmers.

Backus–Naur Form

Backus-Naur Form: BNF

In computer science, BNF (Backus Normal Form or Backus–Naur Form) is a notation technique for context-free grammars, often used to describe the syntax of languages used in computing, such as computer programming languages, document formats, instruction sets and communication protocols. It is applied wherever exact descriptions of languages are needed, for instance, in official language specifications, in manuals, and in textbooks on programming language theory.

Good reference: http://cuiwww.unige.ch/db-research/Enseignement/analyseinfo/BNFweb.html

Augmented BNF for Syntax Specifications: ABNF

( A bit of history Original STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES)

The definition of ABNF are http://www.ietf.org/rfc/rfc2234.txt and http://tools.ietf.org/html/rfc4234

Example: BASIC 64

! -----------------------------------------------------------------------
! BASIC '64
!
! Beginner's All-purpose Symbolic Instruction Code
!
!    "It is practically impossible to teach good programming style to students
!     that have had prior exposure to BASIC; as potential programmers they are
!     mentally mutilated beyond hope of regeneration."
!
!     - Edsger W. Dijkstra
!
! BASIC is one of the oldest programming language and one of the most popular.
! It was developed in 1964 by John G. Kemeny and Thomas E. Kurtz to teach
! students the basics of programming concepts. At the advent of the microcomputer,
! BASIC was implemented on numerous platforms such as the Commodore, Atari,
! Apple II, Altair, IBM PC computers. Over time, BASIC evolved into GW-BASIC,
! QBasic, Visual Basic, and recently Visual Basic .NET.
!
! In practically all programming languages, the reserved word/symbol that denotes
! a comment is treated as a form of whitespace - having no effect in the manner in
! which the program runs. Once such type of comment is used to indicate the remainder
! of the line is to be ignored. These can be added to the end of any line without
! changing the meaning of the program. In C++, it is the '//' symbol;
! in BASIC '64 it is 'REM'.
!
! However, in the BASIC programming language, the line comment is treated like a
! statement. For instance, if 'REM' was a normal line comment:
!
!    10  PRINT "Hello World" REM Common first program
!
! would be a valid statement. However, in BASIC, this is illegal. In the example
! above, the comment must be added as an additional statement.
!
!    10  PRINT "Hello World" : REM Common first program
!
! As a result, the Line Comment terminal that is used in the GOLD Parser cannot be
! used here. In the grammar below, a 'Remark' terminal was created that accepts all
! series of printable characters starting with the characters "REM ". In some
! implementations of BASIC, any string starting with "REM" is a comment statement.
! Examples include "REMARK", "REMARKABLE" and "REMODEL". This grammar requires the space.
!
! This grammar does not include the editor statements such as NEW, SAVE, LOAD, etc...
!
! Note: This is an ad hoc version of the language. If there are any flaws, please
! e-mail GOLDParser@DevinCook.com and I will update the grammar. Most likely I have
! included features not available in BASIC '64.
! -----------------------------------------------------------------------

"Name"    = 'BASIC (Beginners All-purpose Symbolic Instruction Code)'
"Author"  = 'John G. Kemeny and Thomas E. Kurtz'
"Version" = '1964 - Original - before Microsoft enhanced the language for the IBM PC.'
"About"   = 'BASIC is one of most common and popular teaching languages ever created. '

"Case Sensitive" = False
"Start Symbol"   = <Lines>

{String Chars} = {Printable} - ["]
{WS}           = {Whitespace} - {CR} - {LF}

NewLine        = {CR}{LF}|{CR}
Whitespace     = {WS}+

Remark         = REM{Space}{Printable}*
ID             = {Letter}[$%]?
String         = '"'{String Chars}*'"'
Integer        = {digit}+
Real           = {digit}+.{digit}+ 

<Lines>       ::= Integer <Statements> NewLine <Lines>
                | Integer <Statements> NewLine

<Statements>  ::= <Statement> ':' <Statements>
                | <Statement>

<Statement>   ::= CLOSE '#' Integer
                | DATA <Constant List>
                | DIM ID '(' <Integer List> ')'
                | END
                | FOR ID '=' <Expression> TO <Expression>
                | FOR ID '=' <Expression> TO <Expression> STEP Integer
                | GOTO <Expression>
                | GOSUB <Expression>
                | IF <Expression> THEN <Statement>
                | INPUT <ID List>
                | INPUT '#' Integer ',' <ID List>
                | LET Id '=' <Expression>
                | NEXT <ID List>
                | OPEN <Value> FOR <Access> AS '#' Integer
                | POKE <Value List>
                | PRINT <Print list>
                | PRINT '#' Integer ',' <Print List>
                | READ <ID List>
                | RETURN
                | RESTORE
                | RUN
                | STOP
                | SYS <Value>
                | WAIT <Value List>
                | Remark

<Access>   ::= INPUT
             | OUPUT

<ID List>  ::= ID ',' <ID List>
             | ID 

<Value List>      ::= <Value> ',' <Value List>
                    | <Value> 

<Constant List>   ::= <Constant> ',' <Constant List>
                    | <Constant> 

<Integer List>    ::= Integer ',' <Integer List>
                    | Integer

<Expression List> ::= <Expression> ',' <Expression List>
                    | <Expression> 

<Print List>      ::= <Expression> ';' <Print List>
                    | <Expression>
                    |  

<Expression>  ::= <And Exp> OR <Expression>
                | <And Exp> 

<And Exp>     ::= <Not Exp> AND <And Exp>
                | <Not Exp> 

<Not Exp>     ::= NOT <Compare Exp>
                | <Compare Exp> 

<Compare Exp> ::= <Add Exp> '='  <Compare Exp>
                | <Add Exp> '<>' <Compare Exp>
                | <Add Exp> '><' <Compare Exp>
                | <Add Exp> '>'  <Compare Exp>
                | <Add Exp> '>=' <Compare Exp>
                | <Add Exp> '<'  <Compare Exp>
                | <Add Exp> '<=' <Compare Exp>
                | <Add Exp> 

<Add Exp>     ::= <Mult Exp> '+' <Add Exp>
                | <Mult Exp> '-' <Add Exp>
                | <Mult Exp> 

<Mult Exp>    ::= <Negate Exp> '*' <Mult Exp>
                | <Negate Exp> '/' <Mult Exp>
                | <Negate Exp> 

<Negate Exp>  ::= '-' <Power Exp>
                | <Power Exp> 

<Power Exp>   ::= <Power Exp> '^' <Value>
                | <Value> 

<Value>       ::= '(' <Expression> ')'
                | ID
                | ID '(' <Expression List> ')'
                | <Constant> 

<Constant> ::= Integer
             | String
             | Real

Other Examples

Java, C, ISO 7185 STANDARD PASCAL, SQL (various flavours)

Deep Dive of Computer Related Degrees

ACM (Association of Computing Machinery) and IEEE (Institute of Electrical and Electronics Engineers), the highest professional body governing computer science and engineering related careers published the detailed report in 2005 : Computing Curricula 2005 The Overview Report covering undergraduate degree programs in Computer Engineering, Computer Science, Information Systems, Information Technology, Software Engineering which is the only formal source of descriptions of various streams. Please don’t rely solely on those marketing documents from universities and colleges. Use the above document to make well-informed decisions when choosing universities / colleges and comparing them in how they implement the courses and degrees. You will see the how much those degrees worth, and which one is the most cost-effective school.

ACM and IEEE will make updates in the upcoming Computing Curriculum: Computer Science 2013 (CS2013) ACM/IEEE-CS Joint Task Force

The following is the detail areas of the  specialization (please always refer to the original document for any clarification)

Area Performance Capability

CE

CS

IS

IT

SE

Algorithms Prove theoretical results

3

5

1

0

3

Develop solutions to programming problems

3

5

1

1

3

Develop proof-of-concept programs

3

5

3

1

3

Determine if faster solutions possible

3

5

1

1

3

Application programs Design a word processor program

3

4

1

0

4

Use word processor features well

3

3

5

5

3

Train and support word processor users

2

2

4

5

2

Design a spreadsheet program (e.g., Excel)

3

4

1

0

4

Use spreadsheet features well

2

2

5

5

3

Train and support spreadsheet users

2

2

4

5

2

Computer programming Do small-scale programming

5

5

3

3

5

Do large-scale programming

3

4

2

2

5

Do systems programming

4

4

1

1

4

Develop new software systems

3

4

3

1

5

Create safety-critical systems

4

3

0

0

5

Manage safety-critical projects

3

2

0

0

5

Hardware and devices Design embedded systems

5

1

0

0

1

Implement embedded systems

5

2

1

1

3

Design computer peripherals

5

1

0

0

1

Design complex sensor systems

5

1

0

0

1

Design a chip

5

1

0

0

1

Program a chip

5

1

0

0

1

Design a computer

5

1

0

0

1

Human-computer interface Create a software user interface

3

4

4

5

4

Produce graphics or game software

2

5

0

0

5

Design a human-friendly device

4

2

0

1

3

Information systems Define information system requirements

2

2

5

3

4

Design information systems

2

3

5

3

3

Implement information systems

3

3

4

3

5

Train users to use information systems

1

1

4

5

1

Maintain and modify information systems

3

3

5

4

3

Information management Design a database mgt system (e.g., Oracle)

2

5

1

0

4

(Database) Model and design a database

2

2

5

5

2

Implement information retrieval software

1

5

3

3

4

Select database products

1

3

5

5

3

Configure database products

1

2

5

5

2

Manage databases

1

2

5

5

2

Train and support database users

2

2

5

5

2

IT resource planning Develop corporate information plan

0

0

5

3

0

Develop computer resource plan

2

2

5

5

2

Schedule/budget resource upgrades

2

2

5

5

2

Install/upgrade computers

4

3

3

5

3

Install/upgrade computer software

3

3

3

5

3

Intelligent systems Design auto-reasoning systems

2

4

0

0

2

Implement intelligent systems

2

4

0

0

4

Networking and Design network configuration

3

3

3

4

2

communications Select network components

2

2

4

5

2

Install computer network

2

1

3

5

2

Manage computer networks

3

3

3

5

3

Implement communication software

5

4

1

1

4

Manage communication resources

1

0

3

5

0

Implement mobile computing system

5

3

0

1

3

Manage mobile computing resources

3

2

2

4

2

Systems Development Manage an organization’s web presence

2

2

4

5

2

Through Integration Configure & integrate e-commerce software

2

3

4

5

4

Develop multimedia solutions

2

3

4

5

3

Configure & integrate e-learning systems

1

2

5

5

3

Develop business solutions

1

2

5

3

2

Evaluate new forms of search engine

2

4

4

4

4