Contribution:
jsf
Headline
Web programming with Technology:JSF
Motivation
This contribution covers the popular approach for web programming with Technology:JSF. Technology:JSF has a great support for the development of user interfaces in the MVC context. This implementation is considered as a typical Language:Java based implementation with an amount of related and commonly used technologies like the Technology:Hibernate persistence API and the Technology:GlassFish application server.
Illustration
The main architecture is based on the MVC pattern. Technology:JSF itself is focussed on the view and the controller. The user interface (view) is provided by facelets, which is based on the Language:XHTML dialect. A facelet contains the necessary GUI components for the specific view and connects them to the corresponding methods of the backend Java Beans (model). The data provided by the Java Beans is stored within a Technology:MySQL database, accessible through Technology:Hibernate with the help of DAOs (data access objects). The following sections provide a specific description of the involved parts.
GUI development
Facelets provide Language:HTML page generation. Since the XML tags for the JSF components can not be displayed by the browser, they have to be changed to corresponding HTML tags via component aliasing. The following example shows the JSF components needed for total and cut of a company:
<h:outputLabel for="total" value="Total:"/>
<h:outputText id="total" value="#{companyBean.total}"/>
<h:commandButton value="cut" actionListener="#{companyBean.cut()}"/>
The three elements model the GUI components for the label "Total", the textfield for the Feature:Total and the button for the Feature:Cut. For example, the
<h:commandButton .../>
<input .../>
There is no need to implement the controller since it is provided by the Technology:Servlet API used within the JSF framework.
Managed Beans
The previously introduced command button "cut" invokes the corresponding method
cut
CompanyBean
@ManagedBean(name = "companyBean")
@RequestScoped
public class CompanyBean {
...
// This is the set of employees for the whole company (loaded previously by the method "loadCompany(int id))".
private Set<Employee> employees;
...
// The method returns the current value for total of the loaded company.
public double getTotal() {
return total;
}
// The method cuts all employees of the loaded company.
public void cut() {
// Here we retrieve the session and begin the transaction with Hibernate.
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
// The employeeDAO manages the database interaction.
EmployeeDAO employeeDAO = daoFactory.getEmployeeDAO();
// This loop iterates over the previously loaded employees and persists the new salary values.
for (Employee employee : employees) {
employee.setSalary(employee.getSalary() / 2);
employeeDAO.makePersistent(employee);
}
total = total / 2;
// Finally, we commit and close the transaction.
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
}
...
}
The class
CompanyBean
getTotal()
cut()
The two annotations for the class provide the following features:
@ManagedBean
name
@RequestScope
CompanyBean
The application server Technology:GlassFish provides the necessary container for the beans and manages the application.
Persistence
The principle of the DAO pattern is the exchangeability of the persistence layer. This is provided by a
DAOFactory
T findById(ID id, boolean lock);
List<T> findAll();
List<T> findByExample(T exampleInstance);
T makePersistent(T entity);
void makeTransient(T entity);
The
T
Company
Department
Employee
@ManagedBean(name = "companyBean")
@RequestScoped
public class CompanyBean {
...
public void cut() {
// There has to be a transaction before creating hibernate requests.
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
// Retrieve the Hibernate DAOFactory for creating the employee DAO.
DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
EmployeeDAO employeeDAO = daoFactory.getEmployeeDAO();
// Cut all employees and save them.
for (Employee employee : employees) {
employee.setSalary(employee.getSalary() / 2);
employeeDAO.makePersistent(employee);
}
// Calculate new total value.
total = total / 2;
// The transaction commits the data and ends.
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
}
...
}
There is an issue to be solved in the future: The transaction should be invoked by annotations or any automated transaction management instead of using corresponding methods with the help of
HibernateUtil
Architecture
The facelets (company.xhtml, department.xhtml, employee.xhtml) are located in the folder jsf/web/. There is a template.xhtml as well, which arranges the main UI components of each view. The folder jsf/web/resources/css/ contains the corresponding Language:CSS files.
The navigation between the different facelets is managed with the help of the file faces-config.xml, while the starting page and the class for the controller servlet is defined in the web.xml.
The jsf/src/java/ folder contains all relevant code for the realization of the main features (except Feature:Browsing):
- The hibernate.cfg.xml defines the necessary data for the DBMS connection and the classes for hibernate mapping.
- The folder src/java/company/beans/jsf/ contains the three beans (CompanyBean.java, DepartmentBean.java, EmployeeBean.java) necessary for handling the companies, departments and employees.
- The this!!jsf/src/java/company/classes folder contains the relevant classes for the instantiation of the Feature:Hierarchical company.
- The this!!jsf/src/java/company/dao folder contains all necessary classes and factories for the exchangablility of the data model corresponding to the DAO design pattern.
Usage
You need an sql-server to use this application. In this tutorial both will be handled by XAMPP (http://www.apachefriends.org/en/xampp.html).
You can use the company.sql and sampleCompany.sql of Contribution:html5tree for the jsf project.
- Download and install XAMPP
- Open the "XAMPP Control Panel" and start "Apache" and "MySQL"
- Use the guideline of Contribution:mySqlMany up to "Populate tables..."
- To start the application, you have to download the sources from github
- Open the project with Technology:NetBeans (http://netbeans.org/)
- Select the project, right click and run
- The glassfish-server (and a browser window) with the application will start automatically
Language:
Java
Headline
Illustration
Let's show "Hello World" for Java.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Contribution:
html5tree
Intent
Web programming based on the Language:HTML5 ecosystem using Ajax style and a tree view
Motivation
This web application extends the html5ajax implementation with a tree view, thereby improving the Feature:Browsing. This is necessary to guarantee a clear overview while deleting, moving and creating departments and employees due to Feature:Restructuring. Language:JavaScript is very suitable for trees, because it allows client side Technology:DOM manipulation. This is necessary for creating fast, expandable tree structures. We have used the Technology:jQuery library to gain proper Technology:DOM manipulation.
Illustration
The first part of this illustration shows, how the tree view is created. The second part illustrates the deletion of a department as it is part of the Feature:Restructuring feature.
Tree creation
As shown in Contribution:html5ajax, the data is stored within a Technology:MySQL database. After the client creates the initial request, a server side Language:PHP script called this!!server/treeServer.php prepares the data for a Language:JSON response. The initial Technology:XMLHttpRequest is rather simple:
...
treeModel.load = function(strategy, id) {
treeModel.initCompany(id);
treeModel.company.action = "load";
requestUnit.sendRequest(strategy, treeModel.url, treeModel.company);
}
...
The
requestUnit
Server
The server side Language:PHP script treeServer.php creates the objects necessary for the tree. Therefore, it loads the entities from the database with the ids and names, bacause there is no need for total oder address values within the tree display. The following function illustrates the initialization of the Feature:Hierarchical_company:
...
function perform($jsonObject) {
$action = $jsonObject->action;
switch ($action) {
case "load":
return loadCompany($jsonObject);
}
}
function loadCompany($jsonObject) {
// The $jsonObject contains the request of the client.
$id = $jsonObject->id;
// This is the SQL statement to get the company with a given id.
$request = "SELECT * FROM company WHERE id = $id";
$result = mysql query($request);
$row = mysql fetch object($result);
// These few commands create a new company and set the id and the name.
$company = new Company();
$company->setId($row->id);
$company->setName($row->name);
// The subdepartments are added to the company.
$company->setDepartments(loadDepartmentsForCompany($id));
return $company;
}
...
The
perform($jsonObject)
$company
...
echo json encode(perform($jsonObject));
...
Client
In the introduction of the tree creation section we have introduced the parameter
strategy
refresh
...
// This method refreshs the tree view.
treeView.refresh = function() {
// The content variable contains the generated html string for a nested unordered list.
content = "<ul>";
// If there are subdepartments, create a list item with a 'plus' symbol
if (treeModel.response.departments.length > 0) {
// The 'plus' symbol is the button for expanding the tree.
content += "<li> <input id=\"0\" "
+ "type=\"image\" src=\"symbols/plus.gif\" "
+ "onclick=\"treeNavigation.toggleList(this)\">";
// The name of the company is the button for company load.
content += "<input type=\"button\" class=\"companyButton\" value=\""
+ treeModel.response.name
+ "\" onclick=\"controller.loadCompany("
+ treeModel.response.id
+ ")\">";
// The subdepartments are added as sublists of the company list item.
content += treeView.showDepartments(treeModel.response.departments);
content += "</li>";
// If there are no subdepartments, create a list item with a 'dot' symbol
} else {
content += "<li> <img src=\"symbols/leaf.gif\"> <b>"
+ treeModel.response.name
+ "</b></li>";
}
content += "</ul>";
// This replaces the content of the tree division with the generated html code in 'content'.
document.querySelector('#tree').innerHTML = content;
}
...
Every tree item is a list item of a nested unordered list and consists of two visible parts, a symbol and a name. The symbol refers to the position of the item within the tree. There are dots for leafs and plus and minus symbols for unexpanded and expanded tree items. The name is a link, which refers to a load function. This function returns a complete data set for the requested entity.
Delete department
The following part illustrates an example for the deletion of a department according to the Feature:Restructuring. Please visit Contribution:html5ajax to get an overview over loading company entities with XMLHttpRequest and JSON. Keep in mind, that there is no need to load subdepartments or employees for a specific department, since the tree provides the structure to pick these subelements.
After a department is selected, the user can press the delete button to invoke the corresponding client side delete method implemented in departmentModel.js:
departmentModel.deleteEntity = function(strategy) {
departmentModel.initDepartment(departmentModel.response.id);
departmentModel.department.action = "delete";
requestUnit.sendRequest(strategy, departmentModel.url, departmentModel.department);
}
This method will send a request in the JSON format, which contains all necessary informations to delete a department with a given id. Most of the JSON messages in the web application are simplified versions of the messages in Contribution:html5ajax.
This request is received by the server side Language:PHP script, which deletes the department with the id 1. The cascading delete anchored in the database provides a recursive deletion for all containing subdepartments. Hence, the following shows the simple delete request:
$request = "DELETE FROM department WHERE id = " . $id;
mysql query($request);
Architecture
The basic architecture is similar to the architecture of Contribution:html5ajax. It is based on the MVC architectural pattern in combination with a client-server architecture. The key difference is the encapsulation of all views within one Language:HTML file named index.html, controlled by different Language:JavaScript files, which are located in this!!client/javascript/view and the this!!client/javascript/controller.js.
Usage
You need a web and Technology:MySQL server to run this application. In this tutorial both will be taken care of by XAMPP: http://www.apachefriends.org/en/xampp.html
This tutorial adopts some parts of Contribution:mySqlMany. The company.sql and sampleCompany.sql are modified for this project. They are located in the "sqlScripts" folder.
- Download and install XAMPP
- Open the "XAMPP Control Panel" and start "Apache" and "MySQL"
- Use the guideline of Contribution:mySqlMany up to "Populate tables..." with the modified sql scripts.
- To start the application, you need to download all project files except the README
- Put the files into the htdocs directory of your XAMPP (a new subdirectory in "htdocs" is recommended)
- Run index.html
- Download (http://netbeans.org/) and install Technology:NetBeans
- "Open project" and select the html5tree folder
Concept:
API
Headline
An interface for reusable functionality
Details
API stands for Application Programming Interface.
An API should not be confused with particular implementations of the API.
The reference to the term interface should be understood in a broad sense as opposed to concrete interface constructs in programming languages.
Concept:
GUI
Concept:
Web programming
Contribution:
mySqlMany
Headline
A MySQL database with SQL scripts
Motivation
A relational schema provides the data model of the system:Company. Some functional requirements of the system are modeled as SQL statements.
Relationships
- See Contribution:mySqlOne for a slightly simpler variation which does not support multiple companies.
- Various contributions (see the backlinks) use the present contribution (or its variant Contribution:mySqlOne) for their database components.
Usage
Concept:
DBMS
Feature:
Browsing
Headline
Browse companies in a UI
Rationale
- Simplicity: The interface is supposed to be simple in that it is not meant to result in a GUI programming challenge. Anyone modestly familiar with a given GUI technology should be able to provide the GUI for the system:Company. Anyone modestly familiar with the basic concepts of GUI programming should be able to understand the GUI part of the implementation without much effort. Clearly, the GUI should be functionally correct and architecturally sound as well as usable. Any form of tuning should be avoided in the interest of simplicity.
- Data model-driven: Companies are essentially hierarchical structures that break down into departments and employees. Hence, the GUI should bind companies, departments, and employees, and there should be navigation support to operate at all the levels of departmental nesting. All properties of companies, departments, and employees must be reachable by navigation.
- Focus on navigation as opposed to editing: Read-only navigation is sufficient except that the application of the cut operation should be supported at any level of hierarchical navigation. No other modifications need to be supported. See feature:Editing for GUI expressiveness that goes beyond navigation. Implementations may make editable basic properties for names, addresses, and salaries. Such over-achievement of the present feature is not encouraged though.
- Layer-based versus tree-based approach: In the layer-based approach, a company, a department, or an employee is shown at the time. Accordingly, there is a company view, a department view, and an employee view. Navigation begins at the company view and selection of view components transfers to other views. In the layer-based approach, the state of navigation can be essentially viewed as a (possibly incomplete) path from the company root to an inner department or employee. Navigation may maintain this path like a stack. In the tree-based approach, the company structure is shown as a tree in terms of the company's departmental nesting. Folding and unfolding may be applied to such a view. When additional relationships for mentoring, see Feature:Mentoring, are involved, then a directed graph as opposed to a plain tree needs to be visualized.
Description
The following description applies well to classic GUI as well as web-based GUI approaches.
Data binding for the layer-based approach
Labels are shown in italics in the sequel.
Order of bindings per view suggest order in the actual layout.
- The Company view:
- A labeled, read-only text field for the Name of the company.
- A labeled, listbox for the Departments of the company.
- The Department view:
- A labeled, read-only text field for the Name of the department.
- A labeled, read-only text field for the name of the department's Manager.
- A labeled, listbox for the Employees of the company.
- A labeled, listbox for the Sub-departments of the company.
- The Employee view:
- A labeled, read-only text field for the Name of the employee.
- A labeled, read-only text field for the Address of the employee.
- A labeled, read-only text field for the Salary of the employee.
Navigation in the GUI is to be supported as follows:
- The Company view:
- The Close Window handler terminates the application.
- When selecting a department from the Departments listbox, the corresponding Department view is invoked.
- The Department view:
- There is a Back button that navigates back to the previous view.
- The Close Window handler copies the action of the Back button.
- The Close Window terminates the application.
- When selecting an employee from the Employees listbox, the corresponding Employee view is invoked.
- When selecting a department from the Sub-departments listbox, the corresponding Department view is invoked.
- The Employee view:
- There is a Back button that navigates back to the previous view.
- The Close Window handler copies the action of the Back button.
Operations
Feature:Total and Feature:Cut are to be supported by the GUI.
For instance, the layer-based approach may support these operations as follows:
- The Company view:
- There is a labeled, read-only text field for the company's Total.
- A Cut button is attached to the Total field.
- The Department view:
- There is a labeled, read-only text field for the department's Total.
- A Cut button is attached to the Total field.
- The Employee view:
- A Cut button is attached to the Salary field.
Feature:
Cut
Headline
Cut the salaries of all employees in half
Description
For a given company, the salaries of all employees are to be cut in half. Let's assume that the management of the company is interested in a salary cut as a response to a financial crisis. Clearly, any real company is likely to respond to a financial crisis in a much less simplistic manner.
Motivation
The feature may be implemented as a transformation, potentially making use of a suitable transformation or data manipulation language. Conceptually, the feature corresponds to a relatively simple and regular kind of transformation, i.e., an iterator-based transformation, which iterates over a company' employees and updates the salaries of the individual employees along the way. It shall be interesting to see how different software languages, technologies, and implementations deal with the conceptual simplicity of the problem at hand.
Illustration
The feature is illustrated with a statement in Language:SQL to be applied to an instance of a straightforward relational schema for companies where we assume that all employees belong to a single company:
UPDATE employee
SET salary = salary / 2;
The snippet originates from Contribution:mySqlMany.
Relationships
- See Feature:Total for a query scenario instead of a transformation scenario.
- In fact, Feature:Total is likely to be helpful in a demonstration of Feature:Salary cut.
- The present feature should be applicable to any data model of companies, specifically Feature:Flat company and Feature:Hierarchical_company.
Guidelines
- The name of an operation for cutting salaries thereof should involve the term "cut". This guideline is met by the above illustration, if we assume that the shown SQL statement is stored in a SQL script with name "Cut.sql". Likewise, if OO programming was used for implementation, then the names of the corresponding methods should involve the term "cut".
- A suitable demonstration of the feature's implementation should cut the salaries of a sample company. This guideline is met by the above illustration, if we assume that the shown SQL statement is executed on a database which readily contains company data. Queries according to Feature:Total may be used to compare salaries before and after the cut. All such database preparation, data manipulation, and query execution should preferably be scripted. By contrast, if OO programming was used, then the demonstration could be delivered in the form of unit tests.
Feature:
Hierarchical company
Headline
Support nested departments in companies
Description
The data model of the system:Company is required to support companies and employees, just as in the case of Feature:Flat company, but in addition, employees are organized in nested departments. A company breaks down into (top-level) departments, each of which may recursively break down into (sub-) departments. Such nesting of departments enables the hierarchical organization of companies. The features Feature:Flat company and Feature:Hierarchical company are mutually exclusive and either of them must be selected for any realization of System:Company. Some features, e.g., Feature:Depth, may effectively require Feature:Hierarchical company.
Motivation
The specific contribution of hierarchical companies is that they require a recursive treatment of departments as they aggregate both, sub-departments and employees. When using an abstraction mechanism of a programming language for modeling departments (e.g., classes or types), then the corresponding abstraction has to be accordingly recursive. When processing hierarchical companies, then the corresponding functionality must be accordingly recursive, too.
There is more than one way of modeling such hierarchical companies. One approach is to use separate (homogenous) containers for the sub-departments and the employees of a department. Another approach is to use one (heterogeneous) container for both kinds of sub-units: sub-departments and employees. In the former case, (recursive) data composition is used; in the latter case, data variation is taken into account. Data composition alone may be particularly simple to implement in some contexts, e.g., with non-virtual methods in the context of OO programming and object composition. Functionality may be implemented differently because of data variation. For instance, in the context of OO programming, data variation may correspond to type generalization giving rise to subtype polymorphism and virtual methods. Further, added data variation may enable extra extensibility of genericity.
Illustration
The feature is illustrated with a data model in Language:Haskell. Algebraic data types are used for the type of departments; a type synonym cannot be used because departments can be nested and thus, a recursive type is needed:
type Company = (Name, [Department])
data Department = Department Name Manager [Department] [Employee]
type Employee = (Name, Address, Salary)
type Manager = Employee
type Name = String
type Address = String
type Salary = Float
A sample company takes the following form:
sampleCompany :: Company
sampleCompany =
( "Acme Corporation",
[
Department "Research"
("Craig", "Redmond", 123456)
[]
[
("Erik", "Utrecht", 12345),
("Ralf", "Koblenz", 1234)
],
Department "Development"
("Ray", "Redmond", 234567)
[
Department "Dev1"
("Klaus", "Boston", 23456)
[
Department "Dev1.1"
("Karl", "Riga", 2345)
[]
[("Joe", "Wifi City", 2344)]
]
[]
]
[]
]
)
These snippets originate from Contribution:haskellComposition.
Hence, there are two top-level departments, "Research" and "Development". The "Development" department further breaks down further into sub-departments. All departments have managers. Some departments have employees. Each employee has a name, an address, and a salary.
An alternative illustration of the feature shows departments with data variation such that there is a general type of sub-units with derivations for employees and sub-departments, i.e., employee units and sub-department units:
data Department = Department Name Manager [SubUnit]
data SubUnit = EUnit Employee | DUnit Department
The snippet originates from Contribution:haskellVariation.
Feature:
Total
Headline
Sum up the salaries of all employees
Description
The salaries of a company's employees are to be summed up. Let's assume that the management of the company is interested in the salary total as a simple indicator for the amount of money paid to the employees, be it for a press release or otherwise. Clearly, any real company faces other expenses per employee, which are not totaled in this manner.
Motivation
The feature may be implemented as a query, potentially making use of a suitable query language. Conceptually, the feature corresponds to a relatively simple and regular kind of query, i.e., an iterator-based query, which iterates over a company' employees and aggregates the salaries of the individual employees along the way. It shall be interesting to see how different software languages, technologies, and implementations deal with the conceptual simplicity of the problem at hand.
Illustration
Totaling salaries in SQL
Consider the following Language:SQL query which can be applied to an instance of a straightforward relational schema for companies. We assume that all employees belong to a single company; The snippet originates from Contribution:mySqlMany.
SELECT SUM(salary) FROM employee;
Totaling salaries in Haskell
Consider the following Language:Haskell functions which are applied to a simple representation of companies.
-- Total all salaries in a company
total :: Company -> Float
total = sum . salaries
-- Extract all salaries in a company
salaries :: Company -> [Salary]
salaries (n, es) = salariesEs es
-- Extract all salaries of lists of employees
salariesEs :: [Employee] -> [Salary]
salariesEs [] = []
salariesEs (e:es) = getSalary e : salariesEs es
-- Extract the salary from an employee
getSalary :: Employee -> Salary
getSalary ( , , s) = s
Relationships
- See Feature:Cut for a transformation scenario instead of a query scenario.
- See Feature:Depth for a more advanced query scenario.
- The present feature should be applicable to any data model of companies, specifically Feature:Flat company and Feature:Hierarchical_company.
Guidelines
- The name of an operation for summing up salaries thereof should involve the term "total". This guideline is met by the above illustration, if we assume that the shown SQL statement is stored in a SQL script with name "Total.sql". By contrast, if OO programming was used for implementation, then the names of the corresponding methods should involve the term "total".
- A suitable demonstration of the feature's implementation should total the salaries of a sample company. This guideline is met by the above illustration, if we assume that the shown SQL statement is executed on a database which readily contains company data. All such database preparation and query execution should preferably be scripted. Likewise, if OO programming was used, then the demonstration could be delivered in the form of unit tests.
Language:
CSS
Language:
HTML
Language:
JavaScript
Headline
A multi-paradigm programming language for the web et al.
Discussion
JavaScript counts as (imperative) OO programming language; it is prototype-based, though.
JavaScript provides first-class functions; hence it counts also as functional programming language.
The official name of JavaScript is ECMAScript.
Concept:
MVC
Headline
Division of an architecture into model, view, and controller
Discussion
The MVC (Model View Controller) pattern divides a program into three major parts:
- Model
- View
- Controller
Model
A part of MVC that handles the user input and notifies both the model and the view, if there are any changes in one of them. If there are changes in the model, the view will collect them directly from the model, when it gets notified. If there are changes in the view, the controller will delegate this to the model <cite>Burbeck1992MVC</cite>.
View
A part of MVC that contains the user interface.
Controller
A part of MVC that contains the data.
Concept:
User interface
Language:
XHTML
Headline
A markup language for documents on the Web
Description
XHTML is a derivative or dialect of Language:HTML.
It is more strictly XML-based.
Technology:
GlassFish
Technology:
JSF
Intent
Web-application framework for web-based user interfaces with Technology:Java EE
Description
"JavaServer Faces (JSF) is a standard Language:Java web-application framework for building user interfaces for web applications" <cite>schalk2007javaserver</cite>. In terms of MVC it is focused on the view (Technology:JSP, Technology:Facelets), the model (Technology:Java Bean) and the controller (provided by the Technology:Servlet API). Ajax is included from version 2.0. JavaServer Faces controls the navigation between different pages and connects the pages to Java components implemented as Java Bean <cite>schalk2007javaserver, JSF2012official</cite>.
Languages
Technologies
Technology:
Hibernate
Technology:
MySQL
Technology:
NetBeans
Intent
an IDE for Language:Java, Language:php, c++ and other languages
101companies hints
- Version 7.0 is recommended
Technology:
Servlet API
Technology:
XMLHttpRequest
Intent
a Language:JavaScript API for Technology:HTTP-Requests
Discussion
XMLHttpRequest is an API for transfering any data over Technology:HTTP. Most commonly it is used in combination with message formats like Language:XML or Language:JSON <cite>W3C2012XMLHttpRequest</cite>.