CSC/ECE 517 Fall 2010/ch3 3a SN

From Expertiza_Wiki
Revision as of 02:34, 7 October 2010 by Nbarman (talk | contribs)
Jump to navigation Jump to search

Web Frameworks in Object Oriented Languages

An Introduction To Web Frameworks

We, like many others, came to this topic with merely a fuzzy notion of what constitutes a “web framework.” We were not alone. We are confident a framework is not a language with which to write a web site, or a tool to help generate website content. Combing a number of comments from [1], we offer the following:

“A framework is a supplementary, extendable and tested layer built atop a programming language. It implements common design patterns (oft recurring procedures) thereby allowing programmers to focus on higher-level tasks.”

The balance of this page explores some common, and not so common instantiations of this concept.The advantage of web frameworks is that the developer does not have to handle the low level details like protocols, sockets or process and thread management. Frameworks primarily provide libraries for database access, templates for frameworks and also session management. They also focus on code reuse.


Previously, web frameworks were mostly server side technology. But nowadays, with the introduction of interrelated web developement techniques like AJAX, web frameworks have increased their domain to the client side development also. As an example of this new trend, web frameworks can now use the browser at the client side as a full blown execution environment.

Web Framework Architecture

Before we move on to the web frameworks in different languages, it is imperative for us to understand the basic structure of a web framework.

The Model-View-Controller Architecture

The MVC architecture is a way of demodulizing an application or a part of its interface into three constituent parts

The Model

To manage information and notify the observers when that information changes. As such, a model can contain only data and functionality that are related. So two unrelated groups of data and functionality need two different models

The View

Typically deals with how the user will be able to see the output. A view attaches itself to the model and renders its contents to the display surface. Changes in the model will automatically be incorporated and displayed in the views

The Controller

Mainly responsible for mapping user end action to the application response. It typically accepts input from the user and instructs the model and the views to perform actions based on that action

        Input --> Processing --> Output
        Controller --> Model --> View
                                    [5]. Diagram for MVC

Push-based vs. Pull-based

Frameworks normally follow a “push-based” architecture. They have actions that work on the data and process them and then render or push the data to the views in order for the user to see the result. Examples of web frameworks using this architecture include Rubyon Rails and Spring MVC. The opposite of this is the “pull-based” architecture, sometimes also known as “component-based” architecture. These start from the views which can then pull results from various controllers. Struts2 and others like JBoss use this approach

A Tool Versus a Language

As alluded to above, we distinguish between a tool and a language. A hammer is a tool, as is Adobe’s Photoshop. A language is a more general construct generically capable of creating tools, such as Photoshop. Herein the focus is on tools, as most languages of necessity operate at a level of generality not commensurate with the highly repetitive creative and algorithmic underpinnings of Web programs

We now examine some of the available web frameworks in various Object Oriented languages

Web Frameworks for Java

Over the years many web frameworks have been developed for the Java language, which is structured to support web frameworks to a high degree. Those frameworks had their own separate architecture and many evolved over the years to newer and better versions. Here, we shall look at only a few important frameworks for Java

Java Server Faces

JSF is a Java based web framework intended to simplify development of web based user interfaces Some of the features of JSF can be outlined as follows:

  • Managed Beans, which is a dependency injection system and is also called as “Backing Beans” or “Page Beans”
  • A template based component system for component creation without the need of Java classes
  • Build in AJAX support
  • Included along with the Unified Expression Language (EL), which runs at the core of all JSF functions
  • Default HTML and web application specific UI components
  • A server side event model for dispatching and attaching listeners to core system functionality
  • Automatic State management
  • XML based Tag Libraries are also included
   <html> 
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
   <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> 
   <f:view>
   <body>
   <h:form>

Please enter your name and password.

Name:
   <h:inputText value="#{user.name}"/>
Password:
   <h:inputSecret value="#{user.password}"/>

   <h:commandButton value="Login" action="login"/>

   </h:form></body>
   </f:view> </html>
  
                      []http://hale.homeip.net/jsf/jsfcode.htm


Apache Struts

Apache Struts is a web framework that supports Java EE features. It mainly extends the Java Servlet API to encourage developers to adopt the MVC architecture. The goal of struts is to separate the model from the view and the controller. The model, as mentioned earlier, primarily deals with the application logic, the view deals with the HTML pages displayed to the user and the controller handles the flow of information between the model and the view. Struts basically provides the controller through a servlet known as ActionServlet and enables the construction of views in JSPor XML. The model code becomes the responsibility of the web application programmer. A central configuration file known as “struts-config.xml” is created that binds together the model, view and the controller.

Struts also supports internationalization through web forms and has a mechanism for implementing templates known as “Tiles” that allows the presentation layer to be composed from independent header, footer, and content components. A sample struts code snippet which implements a form view is as follows

               <%@ page language="java" %>
               <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
                <html><head>
               <title>Sample Struts Application</title>
               </head>
               <body>
               <!—Typical struts tag -->
       	<html:form action="Name" name="nameForm" type="example.NameForm">
Name: <html:text property="name"/>
<html:submit />

</html:form>

               </body></html>
                                [] http://www.allapplabs.com/struts/struts_example.htm

Apache CXF

This is an open source web services framework for Java. The name is derived from the initial letters of “Celtrix” developed by IONA Technologies and “XFire” developed by a team at Codehaus . The CXF design include clean separation of front ends, like JAX-WS from the core code and it also includes Embeddable Web service component like Spring Framwrok and Geronimo


Java Web Services Development Pack

It is a free SDK for developing Web Applications and Web services in Java. It has now been replaced by Glassfish and most of the components of JWSDK are now in Glassfish and several are in Java SE 6.

Some of the APIs included in JWSDK are

  • Java API for XML Processing (JAXP), v 1.3
  • Java Architecture for XML Binding (JAXB), v 1.0 and 2.0
  • Java-RPC v1.1, which is a combination of Java RMI over web services
  • Java API for XML based Services,v 2.0, a Java programming API for creating web services
  • SAAJ, SOAP with Attachments API for Java, to send XML documents by Java
  • Java API for XML Registry, to interact with metadata registries
  • Web services Registry


.NET Framework

The Microsoft .NET framework is a web framework that can be applied to multiple programming languages and also to Object Oriented languages like C#. The Base Class Library of .NET provides a large number of features like user interfaces, database connectivity and so on that programmers can use to produce applications by combining with their own code.

The .NET runtime environment is commonly known as Common Language Runtime (CLR). It provides the advantage of an application virtual machine. It also provides a host of other functions like security, memory management and exception handling. The Base Class Library and the CLR together constitute the .NET framework.

Assemblies

In .NET, an assembly is a compiled code that is used for deployment, versioning and security. Assemblies can be of two types

  • .EXE type which are called process assemblies
  • .DLL type which are called library assemblies.

An assembly can have one or more code files which are called modules. Moreover, it can have more than one module. Modules can be created using different languages and so it is possible to create an assembly by combining several languages. However this is restricted in Visual Studio

Metadata

Metadata, as the definition goes, is data about data. Thus, the .NET metadata refers to certain data structures embedded within it that describes the high level structure of the code. The .NET compiler will generate the metadata and store it in an assembly. This helps in checking method parameter types when we call the method. Developers can also add metadata to their code through attributes.

                  using System.Runtime.InteropServices; //reference the name
                  public class
                  Form1 : System.Windows.Forms.Form	
                  {
                   [DllImport("user32.dll")]
                   public static
                   extern bool
                   MessageBeep(intSound); }
                         	[]http://www.codeguru.com

The above C#.NET code demonstrate some part of the .NET and the Forms interface

.NET Framework 1.0

The first version of the .NET framework which was released on 13th February 2002 and was supported on Windows 98, NT 4.0 and XP. Mainstream and extended support by Microdoft ended on 10th July 2007 and 14th July 2009 respectively NET Framework 1.1

This is the upgrade of the previous version which was published on April 3 2003. It is also the first version to be included as a part of the Windows operating system along with Windows Server 2003. The mainstream support ended on 14th October 2008 and extended support ends on October 8 2013. It is also the last available version for Windows NT 4.0

.NET Framework 2.0

It was released with Visual Studio 2005, Microsoft SQL Server 2005, and BizTalk 2006 on 22nd January 2006. The SDK for 2.0 is available for free from Microsoft. It can be included with Visual Studio 2005 and Microsoft SQL Server 2005. The 2.0 version contains numerous API changes and other features like generics, partial classes, nullable types and iterators.

NET Framework 3.0

.NET Framework 3.0 was released on 21 November 2006. It has a new set of managed code API integrated with Windows Vista and Windows Server 2008 operating systems. It uses the CLR from the 2.0 version and as such there are no major architectural changes in this version. It contained some new components like Windows Presentation Foundation for graphics, Windows Communication Foundation for web services, Windows Workflow Foundation for task automation and Windows Cardspace which provides authentication services.

.NET version 4.0

It was realeased on 29th September 2008. This version targeted at parallel computing and includes Parallel Extensions for parallel computing support. Other notable features of this release are implicit line continuations, dynamic dispatch, named parameters, support for IronRuby and IronPython, support for Code Contracts and so on.


Frameworks for C++

Wt (Web toolkit)

Wt, also pronounced as “witty”, is an open source web application framework for the C++ language.It was developed by Emweb and has an widget centric API using a widget tree structure and also an event driven signal/slot programming model. Here, the MVC structure is pushed to the level of individual components rather than at the level of a page. The library also supports web specific features like pretty URLs and also browser history navigation. The library uses AJAX for communicating with AJAX capable browsers, while using plain HTML form postbacks for other user agents. For AJAX capable browsers, it is automatically upgraded for more interactivity. The library has been used in embedded system environments because of the adaptability of C++ in such an environment and has been highly optimized for performance as a consequence.

    #include "HelloApplication.h"
    #include "QtObject.h"
    QtObject::QtObject(HelloApplication *wt, QObject *parent)
    : QObject(parent),
    wt_(wt)
    { }
    void QtObject::passGreet(const QString& name)
    {   emit greet(name); }
    void QtObject::doGreet(const QString& name)
    {  wt_->doGreet(name); }
                         []http://www.webtoolkit.eu/wt#/src

CppCMS

CppCMS is another open source web framework for the C++ language developed by Artyom Beils. The primary motive of this framework is to build performance demanding web applications for C++. It may also be used for embedded web applications for consumer devices. The framework is mainly for posix-compatible platforms and is available under LGPL license.



Ruby-based Frameworks

“Dynamic” is the technical and functional way to describe Ruby. With its full object orientation, to the extents of unbounded polymorphism (http://en.wikipedia.org/wiki/Duck_typing), and automatic, dynamic creation of functions, it is possible to tersely represent complex relationships. This section deals with frameworks that leverage this flexible language’s power.

Ruby On Rails

“Ruby on Rails® is an open-source web framework that’s optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration.” [2]

The Rails framework provides an extensive functionality set built atop the Ruby language. Its ORM soul, unbounded polymorphism dynamicity, coupled with an extensive collection of readily-accessible and free “Gems” (function plug-ins) make this an attractive and quite popular framework. By preferring convention over configuration major functionality is available to quite novice users. A specific example is the set of “scaffolding” scripts that prototype code for common MVC scenarios.

The following example code of shows all that is necessary to validate the instantiation of a Post object. Generation of user error messages is handled automatically.

   class Post < ActiveRecord::Base
    has_many :cheers

    validates_presence_of :posttext
    validates_presence_of :username
    validates_presence_of :parentpost

     ... class methods ...

    end

Merb and others...

In Ruby, Rails outshines all others in terms of adoption and acceptance, however there are other less well known contenders. Foremost among them is Merb, whose main claim is its agnosticism with respect to database type (like Rails its core is ORM). Possibly one of Merb’s nicest features is its documentation page (http://merbivore.com/documentation/current/doc/rdoc/stack/index.html), a touchstone reference for those interested in pursuing usability in documentation.

With minor syntax differences, this Merb viewer, that simply shows a list of items, is functionally identical to one built with rails. [3]

Article controller, index action

<% @articles.each do |article| %> <% end %>
Title Author Actions
<%=h article.title %> <%=h article.author %> <%= link_to 'Show', resource(article) %> <%= link_to 'Edit', resource(article, :edit) %> <%= delete_button(article, "Delete #{article.title}") %>
   <%= link_to 'New', resource(:articles, :new) %>

For those interested in pursuing other avenues for coding web applications in Ruby, particularly light-weight ones, Rob Bazinet’s review [1] of 10 alternatives is excellent reading.

PHP-based Frameworks

PHP[2] is a scripting language embeddable into HTML. The language’s core purpose is allowing web developers flexibility to create dynamic webpages quickly. Its syntax borrows primarily from C, Perl, and Java.

CakePHP

In description, CakePHP is in the same camp as Ruby on Rails: it affords a framework for rapid webspace development using the MVC paridigm with an ORM foundation, and prefers robust convention management to configuration. Unlike Rails it is written in PHP [3], a common web scripting language embeddable into HTML. One of Cake’s main differentiation claims, is that all the code was written by their own development team, hinting at a more consistent intellectual foundation.

A simple validation example that extends a model, then adds validation parameters is shown below. As with Rails, Cake by convention displays the validation messages to this form’s user, with no extra coding on the the part of the developer. [6]

 <?php
 class User extends AppModel {
  var $name = 'User';
  var $validate = array(
 'login' => 'alphaNumeric',
 'email' => 'email',
 'born' => 'date'
  );
  }
 ?>

NOLOH

Not-One-Line-of-HTML is the provocative moniker for this entrant to the field of web frameworks. As the name suggests, the framework’s aim is to eliminate the onerous HTML coding typically associated with webspace development. They do this by extending PHP, and in the process eliminate the need to code JavaScript and Ajax, pulling everything into the framework instead. Rejecting the MVC paradigm, NOLOH manages the user state internally through the user’s interactions with the web page, letting user actions indicate to the server what actions to perform. This eliminates client-side code, as the following simple example illustrates. As NOLOH is fully object oriented, not the inheritance syntax. [7]

  class SomePanel extends Panel
  {
  function SomePanel()
  {
  parent::Panel();
  //Instantiate a button
  $button = new Button();
  //Add the button to the Controls of the Panel
  $this->Controls->Add($button );
  /*Sets the Click event of the button to a ServerEvent
  that will call the function SomeFunc when the button is clicked*/
  $button->Click = new ServerEvent($this, "SomeFunc");
  }
  function SomeFunc()
  {
  System::Alert("Triggered an Event");
  }
  }

As expected of a language, the proceeding two examples are by no means the sum of PHP-based web frameworks. An extensive list of PHP-derived MVC frameworks, maintained by the PHP developers, is available [4], and while all the entries are not object oriented, they provide a valuable overview of the extent of PHP applications.

Python-based Frameworks

Like many other languages whose fame is based on rapid, easy-to-write-and-read code, Python[5] is a dynamic language, with all the associated free-form programming goodies associated therewith. Unlike Ruby or Perl, Python is compilable (the usual implication being speed), yet still retains abilities as a scripting language. In addition to the above, Python is extendable in C/C++ for applications requiring the performance only low-level code can facilitate.

Grok

As with all the other entrants in this chapter, Grok [(http://grok.zope.org/),Grok] claims easy coding and powerful capability as its value. While it is a Python-language tool, it more generally derives from the venerable Zope (http://www.zope.org/) Python framework. Zope’s main differentiation is the “through-the-web” development paradigm it espouses, and has been around since 1997 - quite a long time for a web language. Grok is designed to “stand on the shoulders” of the Zope body of knowledge (the Zope Development Toolkit - ZDT), but be a tool that “caveman” will gravitate too. Specifically the ZDT is a configuration-oriented system, which while powerful is a hard sell to entry-level users. Grok’s goal is to reverse that, providing a powerful, flexible web-development tool capable of bashing the daily host of web problems - kind of like a cavemen’s club: simple, powerful, and intuitive to use.

Note that Grok is not an MVC architecuter, in that while it has models and views, it lacks controllers. Instead, they prefer to use the concept of “adapter,” a device that allows the view to either directly access the model, or extend it if necessary. They main purpose behind this architecture decision is that the ZDT architects consider extending classes through these so-called adapters is superior to either extending the class functionality through inheritance or more potentially nefarious methods such as monkey patching[6]

To get a feeling for Grok coding, the following shows a few snippets from a simple wiki application written with Grok. The first snippet is a shows the basic model, while the second shows adapters that provide functionality. [8]


   import grok
   import grokwiki.page
   class Wiki(grok.Application, grok.Container):
   """This is Grok's sample wiki application."""
   class Index(grok.View):
   def render(self):
   self.redirect(self.url('home'))
    ... other methods ...
  @grok.subscribe(Wiki, grok.IObjectAddedEvent)
  def setupHomepage(wiki, event):
  """Creates a home page for every wiki."""
  page = grokwiki.page.WikiPage()
  wiki['home'] = page
  import re
  import grok
  from z3c.flashmessage.interfaces import IMessageReceiver
  from zope import component
  LINK_PATTERN = re.compile('\[\[(.*?)\]\]')
  find_wiki_links = LINK_PATTERN.findall
  class WikiPage(grok.Model):
  def __init__(self):
  self.text = u"GROK EMPTY WIKI PAGE. FILL!"
  def update(self, text):
  links = find_wiki_links(text)
   for link in links:
   if link not in self.__parent__:
   self.__parent__[link] = WikiPage()
   self.text = text
   class Index(grok.View):
   def update(self):
   wiki_url = self.url(self.context.__parent__)
   self.rendered_text, replacements = (
   LINK_PATTERN.subn(r'<a href="%s/\1">\1</a>' % wiki_url,
                            self.context.text))
   class Edit(grok.View):
   def update(self):
   text = self.request.form.get('wikidata')
   if not text:
   return # Just render the template
   # Update the text and redirect
   self.context.update(text)
   self.flash('Saved.')
   self.redirect(self.url(self.context))
    ... other methods ...


CubicWeb

Unlike most other web frameworks, CubicWeb (http://www.cubicweb.org/) uses their own terminology to describe their particular approach to web development. A perusal of their discussions and examples indicate a general inclination towards the MVC architecture with an ORM back-end, with the interesting exception that they group the a set of models, views, and logic (their name for a controller) together into a “cube.” This unit of functionality is then available as an object to other applications: a concept not seen in the other frameworks in this chapter.

Another interesting feature is the “semantic” claim of the framework. Almost everything in the framework is a dynamic object, and they are stored in a registry as “appobjects”. These appobjects are dynamically used at runtime, but are selected not on static mapping, but on dynamic scoring,as more than one object can share the same registry key. At run time the appobjec with the higher “score” is used to perform a particular function. After selection from the ORM back-end, CubicWeb’s views display that information: a view is nothing more than a appobject dedicated to rendering some data - to HTML, XML, PDF, etc.

To create a blog in CubicWeb, one would first create a new cube.

cubicweb-ctl newcube --directory=~/src/cubes blog

Then define the two data types, a “blog” and a “blog entry”.

from yams.buildobjs import EntityType, String, SubjectRelation, Date

   class Blog(EntityType):
    title = String(maxsize=50, required=True)
    description = String()
    class BlogEntry(EntityType):
    title = String(required=True, fulltextindexed=True, maxsize=256)
    publish_date = Date(default='TODAY')
    content = String(required=True, fulltextindexed=True)
    entry_of = SubjectRelation('Blog', cardinality='?*')

The semantic part of the whole package has to do with the system understanding what you are creating. To actual interact with a blog, one creates and instance of the data model above, and starts that instance.

   cubicweb-ctl create blog blogdemo
   cubicweb-ctl start -D blogdemo

Then, pointing a browser to http://localhost:8080/ allows the user to login (because by default users must be authenticated), and start creating blogs and blog entries. All this, simply from the definition of the data structure (the schema). This is one concept worth exploring. (For further details of this paraphrased example, see [9].)

Acronyms Used Throughout

  • MVC: Model View Controller [7]
  • ORM: Object relational mapping [8]