Knowledge7

The Linux and Mobile Solution Provider

  • About
  • Training
  • Services
  • Clients
  • In the news
  • Blog
  • Contact Us
You are here: Home / Blog

Infrastructure services

This topic is part of our Linux Network Services and Security training

Dynamic Host Control Protocol (DHCP)

Linux can be used as a DHCP server.

Quoting the official Red Hat Deployment guide, “DHCP is useful for automatic configuration of client network interfaces. When configuring the client system, the administrator chooses DHCP instead of specifying an IP address, netmask, gateway, or DNS servers. The client retrieves this information from the DHCP server. DHCP is also useful if an administrator wants to change the IP addresses of a large number of systems. Instead of reconfiguring all the systems, he can just edit one DHCP configuration file on the server for the new set of IP addresses. If the DNS servers for an organization changes, the changes are made on the DHCP server, not on the DHCP clients. When the administrator restarts the network or reboots the clients, the changes will go into effect.”

The preferred way to configure a DHCP server is to start from a sample dhcpd.conf.

Domain Name Service (DNS)

Linux provides Bind, a full-fledged DNS server. Bind can operate as a caching nameserver as well as a DNS server which is fully authoritative for a zone (or many zones). The preferred way to configure Bind is to start from sample named.conf and zones.

This topic is part of our Linux Network Services and Security training

Our forthcoming training courses

  • No training courses are scheduled.

Picks of the Week #6

You want to receive our Picks of the Week every Monday morning?

Thank you for reading the sixth edition of the Knowledge7’s Picks of the Week.

Every week, Avinash Meetoo will make you discover interesting articles and websites to help you broaden your understanding of the world of open source software and information technology in general.


The Metasploit Framework
There is currently an ongoing battle between pirates and system administrators. And, of course, given the prevalence of Linux on the Internet, this is true for Linux system administrators too. “The Metasploit Framework is both a penetration testing system and a development platform for creating security tools and exploits. The framework is used by network security professionals to perform penetration tests, system administrators to verify patch installations, product vendors to perform regression testing, and security researchers world-wide. The framework is written in the Ruby programming language!”

The Mirah Programming Language
“Mirah (nee Duby) is a new experimental language born out of the JRuby project. In order to make implementing Ruby on the JVM easier and more approachable for Java and Ruby developers alike. Charles Oliver Nutter wanted to create a language that essentially looked like Ruby, but was statically typed and compiled to fast JVM bytecode. Mirah is the result.” What is sure is that the Java programming language is starting to show its age: its syntax is based on an ancient language called C++ (remember that?) and its programming model is too complex (is an integer an object?). Does Mirah has a chance to succeed? Only time will tell. But it’s going to be tough with Scala, Clojure as well as JRuby (mentioned above) innovating on all fronts…

The Facebook Blog: The Spirit of Openness
“Here’s a secret: Mark Zuckerberg didn’t write all of Facebook in his dorm room at Harvard. (Sorry, Mark, your secret is out.) He had a lot of help. No, I’m not talking about all the wonderful folks who work on the site every day. I’m talking about the unsung hero of many a young Web site: open-source and free software. Without it, there’d be no Facebook.” “Almost all our servers are running open-source software. Our Web servers use Linux and Apache and PHP. Our database servers run MySQL. […] The list goes onโ€”like many Web sites, we use it from top to bottom.” “But we also make it a point to give back.” To all those who want to build the next Facebook in Mauritius: follow a decent PHP/MySQL training. Why not something like ours? ๐Ÿ™‚

Drizzle: A Database for the Cloud
“Drizzle is a community-driven open source project that is forked from the popular MySQL database.” Here are its main features: “optimized for Cloud infrastructure and Web applications”, “designed for massive concurrency on modern multi-cpu architecture”, “optimized memory [utilisation] for increased performance and parallelism” and (of course) “Open source, open community, open design”. Why fork MySQL you may ask? The Drizzle developers say that they wanted to “remove non-essential code, refactore the rest and move towards C++”. What they get is a database which is reliable, which supports transactions and which is ACID compliant (atomicity, consistency, isolation, durability). Phew. I initially thought that they forked MySQL because of Oracle…

How to Pick a Co-Founder
When I founded Knowledge7 at the end of 2008, I didn’t pick a co-founder. Sure, I was not alone, we were seven shareholders (hence the name!). But, in hindsight, I should have asked one of them to join me at Knowledge7 as a co-founder. I would have chosen the one who has “a complementary temperament” with mine, with skills sufficiently different from mine, someone who “shares my expectations” of life, someone who has the “same overall vision” for the company, someone with whom I’ve worked with in the past and someone I like. In other words, I should have asked my wife, Christina, to join me ๐Ÿ™‚

Our forthcoming training courses

  • No training courses are scheduled.

Using UI Component tags

This topic is part of our Web Application Development in Java training

Struts contains a number of powerful UI (User Interface) components. In essence, each UI component:

  • Generate (complex) HTML
  • Links HTML form fields to Java properties
  • Does automatic type conversion and validation

Out of the tens of UI components, four are very powerful while being relatively easy to use. They are:

  • select
  • radio
  • doubleselect
  • updownselect

Work to do

Write a Struts web application which showcases the four above UI components. Look at the image above for some inspiration…

Bonus

Want autocompletion like in Google Search? Look no further than the autocompleter tag. Try it!

This topic is part of our Web Application Development in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Building the view

This topic is part of our Web Application Development in Java training

Struts has different categories of tags which are used within JSP views:

Control tags

  • if
  • elseif
  • else
  • append
  • generator
  • iterator
  • merge
  • sort
  • subset

Data tags

  • a
  • action
  • bean
  • date
  • debug
  • i18n
  • include
  • param
  • property
  • push
  • set
  • text
  • url

Non-Form tags

  • actionerror
  • actionmessage
  • component
  • div
  • fielderror
ย Form tags

  • checkbox
  • checkboxlist
  • combobox
  • doubleselect (Powerful!)
  • head
  • file
  • form
  • hidden
  • inputtransferselect
  • label
  • optiontransferselect
  • optgroup
  • password
  • radio (Very useful!)
  • reset
  • select (Very useful!)
  • submit
  • textarea
  • textfield
  • token
  • updownselect (Powerful!)

Ajax tags

  • a
  • autocompleter (Powerful!)
  • bind
  • datetimepicker
  • div
  • head
  • submit
  • tabbedpanel
  • textarea
  • tree
  • treenode
This topic is part of our Web Application Development in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Adding workflow with interceptors

This topic is part of our Web Application Development in Java training


We will, first of all, rewrite the BestSongs application using Struts:

  • Create a new web application called BestSongsStruts
  • Add the required libraries (including the MySQL connector)
  • Copy the models from a previous project in an appropriate package
  • Add an action called Countries with a getter for a property called countries which returns a List of Country objects (use the DAO)
  • Write the view (using Struts tags like s:iterator and s:a)
  • Test!
    • Artists is slightly different from Countries as it require a parameter (countryid) to work properly. It therefore needs to implement the ParameterAware interface (and, consequently, implement the setParameters method).

      • Implement the Artists action and its corresponding view.
      • Do the same for Songs
      • Test!

      Adding a logging interceptor

      In Struts, interceptors are used to modify the workflow of an application.

      In all Struts applications, there exist a default stack of interceptors (notice ParametersInterceptor, ActionMappingParametersInteceptor and StaticParametersInterceptor).

      Also notice that there is an interceptor called “logger” but it is not part of the default stack.

      Let us add the logger before the default stack and let us observe what happens:

      <action name="Songs" class="com.knowledge7.strutsbestsongs.actions.Songs">
          <interceptor-ref name="logger" />
          <interceptor-ref name="defaultStack" />
          <result>/Songs.jsp</result>
          <result name="error">/Error.jsp</result>
      </action>
      

      The order can also be changed.

      Creating a custom logging interceptor

      User-made interceptors are straightforward to write and they can then be added to any Action (e.g. Songs). We will now write a custom logging interceptor which will log everything in a table in the database:

      • Create a new table with fields: logid (an autonumber), occurence (a timestamp) and reason a varchar(255).
      • Create a LogDAO with one static method “void log(String reason)”
      • Create a class called DatabaseLoggingInterceptor (which needs to implement the Interceptor interface and the implement method)
      • Declare the interceptor in struts.xml as databaseLogger
      • And, finally, replace logger (above) by databaseLogger
      • Test!

      Enjoy!

      This topic is part of our Web Application Development in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Using Struts actions

This topic is part of our
Web Application Development in Java
training

Struts is a family of powerful MVC frameworks for Java.

Struts 1.x is the previous generation framework which is still being used in a lot of legacy applications.

Struts 2.x is a new framework (originally known as WebWork 2) which is now popular. As it is an MVC framework, it naturally supports Models, Views as well as Controllers.

In Struts 2.x, a request is processed by a Filter called FilterDispatcher. This filter is configured by an XML file called struts.xml (found in WEB-INF/classes) and which contain Actions.

When processing a request, the FilterDispatcher checks whether it matches one of the defined Actions. If true, the execute() method of the Action is called (this is where the Action can interact with Models) and that method then returns one of the various Struts 2.x constants (SUCCESS, INPUT, ERROR, etc.) An appropriate View is then shown depending on the return value. The View can easily access the properties of the Action.

In essence, Actions are like Controllers. Their execute method is called when a request comes. The Action interacts with Models and select a View.

Work to do

  • Create a new Java dynamic web application.
  • Add to it the following Struts libraries (commons-fileupload, commons-io, freemarker, javassist, ognl, struts2-core and xwork-core). The libraries can be found in the Struts 2 lib directory except for javassist which is the Blank demo application.
  • Add a filter (FilterDispatcher) with URL pattern /* (i.e. everything!)
  • Remove the welcome-file-list
  • Create a HelloWorld JavaBean which implements Action and, consequently, the execute() method. Make sure it has (at least) a getter for a property called message (a String).
  • Test it using unit testing.
  • Create /WEB-INF/classes/struts.xml and reference the HelloWorld action in it. Make sure that the default view is HelloWorld.jsp
  • Create HelloWorld.jsp and make sure you interact with the Action in it. The best way to do that is to use the Struts 2.x tag library. Here, <s:property> needs to be used.
  • Test it!

Let’s now create a simple menu:

  • Create a View called Welcome.jsp. Make sure that the view has a link to the HelloWorld action.
  • Add a mapping without an action to struts.xml
  • Test!
  • Change the mapping to wildcard mapping.
  • Test!

Adding a login form

Struts 2.x also supports form tags which allow complex forms to be built very quickly.

  • Create a Login form with two fields: username and password. Do not use the classical HTML tags here. Use the Struts 2.x tags instead. The action of the form should be Authenticate (which has not been written yet!)
  • Add this view as a mapping with a corresponding action in struts.xml
  • Add Login to the menu to make it easier to access.
  • Test!
  • Add the Authenticate action. execute should only return SUCCESS when both the username and the password are “java” and, consequently, a nice “Authentication Done” needs to be shown. If one of the values has not been entered, the login form needs to be displayed again. Otherwise, “Authentication Error” should be displayed. How many new views do we need?
  • Test!

Validation on the client

Struts 2.x has full support for server-side and client-side validation.

  • Add a EnterDetails view as pictured above.
  • Make sure that the GetCharacter as well as DisplayCharacter view work well.

Now, let’s make validation work by (1) adding validate=”true” to the form and (2) by adding something similar to the following to the GetCharacter action:

@Validations (
	requiredFields = {
		@RequiredFieldValidator(fieldName="string", message="The string needs to be specified"),
		@RequiredFieldValidator(fieldName="position", message="The position needs to be specified")
	},
	requiredStrings = {
		@RequiredStringValidator(fieldName="string", message="The string needs to contain characters")
	},
	stringLengthFields = {
		@StringLengthFieldValidator(fieldName="string", minLength="1", maxLength="100", message="The string must be between 1 and 100 characters long")
	},
	intRangeFields = {
		@IntRangeFieldValidator(fieldName="position", min="1", max="100", message="The position should lie between 1 and 100")
	}
)

What do you notice? Where is validation being done?

Validation on the server

In some applications, it’s better (not to say simpler) to validate on the server instead of on the client. To do that, do the following simple changes:

  • Remote validate=”true” in the JSP.
  • Make the action extend ActionSupport instead of implementing Action

What do you observe when the application is run?

Further validation

ActionSupport has a method called validate() which can be used for more complex validations. For example, validate() can query databases and do calculations before emitting errors.

This topic is part of our
Web Application Development in Java
training

Our forthcoming training courses

  • No training courses are scheduled.

Picks of the Week #5

You want to receive our Picks of the Week every Monday morning?

Thank you for reading the fifth edition of the Knowledge7’s Picks of the Week.

Every week, Avinash Meetoo will make you discover interesting articles and websites to help you broaden your understanding of the world of open source software and information technology in general.


Jolicloud
Jolicloud is a new Linux distribution derived from Ubuntu which is itself derived from the oh so powerful Debian. Jolicloud is designed for netbooks having relatively small screens and amount of memory. Its philosophy is based upon blurring the distinction between native applications and web applications. For example, in Jolicloud, Skype and Flickr are accessed in the same way even though Skype is an application and Flickr is a website. This makes Jolicloud an easy operating system to use by beginners. Jolicloud is still young (version 1.1 has just been released) but it certainly has a lot of potential. I advise all Linux fans who have a spare netbook to give Jolicloud a try. Who knows? Some Windows fan might fall in love with Linux!

An In-Depth Exploration of the Art of Shell Scripting
I have been teaching Linux for ten years now and the one thing which always amaze most people is the shell (i.e. the command line). There are many reasons for that: (1) Linux and all the other Unixes as a matter of fact have many commands (about 2000…), (2) a lot of those commands are filters which transform data and are used in combination (in pipes) and (3) a set of commands (including conditionals and loops) can be saved in a shell script which then becomes indistinguishable from pre-existing commands (i.e. the set of commands is infinitely extensible). Of course, mastering everything takes a lot of dedication and a lot of time. This tutorial is an essential reading for anyone willing to, one day, become a Linux guru.

Yii Framework
PHP is a powerful programming language and major web applications like Wikipedia and Facebook are built using it. When developing a new application, one can write everything from scratch or use a framework. Most of the time, people tend to use a framework because of the added productivity this provides. Yii is a new PHP framework based on the Model View Controller (MVC) architecture and which supports AJAX and jQuery, interacts with relational databases (like MySQL) and provides multi-language support, performance optimisation through caching and security through role-based access control. Yii implements many of the good ideas of Ruby on Rails like minimal need for configuration, scaffolding (automatic PHP code generation based on a database table, for example) and full testability. All PHP programmers should give Yii a try.

Node.js
In the past, web applications were mostly server-based with only a few bits of verification and validation being done on the client. In 2011, this is not true anymore: any decent web application needs to have a complex Javascript portion to deal with AJAX as well as to provide a modern user interface. In other words, having Javascript in the client and, say, PHP on the server (using something like Yii for example). Node.js challenges this. With Node.js, it is possible to run Javascript on the server. In fact, Node.js adds to Javascript the capability to work as a web server with full support for all kids of databases through add-on modules. The advantage is, naturally, that the programmer only has to master one programming language instead of two. jQuery has revolutionized client-side programming. Can Node.js be as innovative on the server front? Only time will tell.

Clojure
Clojure is yet another programming language for the Java virtual machine. I talked about Scala previously but Clojure has had a lot of buzz since it was launched in 2007. Clojure is a LISP and, therefore, will look incompressible at first to those of you not versed into LISPdom. But it is also a very powerful general purpose language with extensive support for functional programming, it has a very powerful macro system inspired by the one in LISP and provides immutable data structures which allows for helps in writing efficient concurrent programs. Given that the programming environment in 2011 is essentially multi-core, it is important for all of us to start looking at alternative programming languages built with parallel processing in mind. Clojure is such a language. And, remember, parentheses are cool.

Our forthcoming training courses

  • No training courses are scheduled.

Using JSP Standard and Custom Tags

This topic is part of our
Web Application Development in Java
training

JSP is a powerful technology and it gets even more powerful when used properly!

As mentioned in the previous topic, most web applications are built using an MVC architecture. Most of the time, the controller will be a Java servlet, the model a POJO (Plain Old Java Object) or a JavaBean which exposes methods and the views are JSP.

We saw how to add an attribute to a request in the controller and access it from the JSP using EL and the requestScope object. In the previous example, the attribute was a scalar value. In most large applications, the attribute(s) might be complex object hierarchies and, consequently, it is important that JSP tags be extended to include conditionals, looping constructs and so on.

This is the role of JSTL, the JSP Standard Tags Library.

We will rewrite the Countries/Artists/Songs application to be compliant with the MVC architecture. We will also make sure that views leverage the tags found in JSTL. We will follow the following steps:

  • We create three model POJOs: Artist, Country and Song. Those classes have the same attributes as in the database and appropriate getters/setters.
  • We import the singleton DatabaseConnection.
  • The next step is to create Data Access Objects (DAO) so that our model is decoupled from the underlying database. We also create a new runtime exception, DAOException, to be thrown instead of SQLException in case of problems. Create DAOException, CountryDAO (with a findAll method which returns a list of Countries) and CountryDAOTest.
  • The next step is to create CountriesController (as a Java Servlet). This controller uses CountryDAO to get a list of all countries, assigns the list as an attribute to the request and selects a view (CountriesView.jsp).
  • As the view requires JSTL, it is important that jstl.jar and standard.jar (from the Tomcat installation) be added to the project.
  • Finally, the view, CountriesView.jsp, is written.
    • CountriesView.jsp uses the JSTL Core tag library (taglib) so the following line is needed:

      • <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

      Furthermore, the view will get the list of countries from the requestScope and loop through the countries using the c:forEach tag.

      For information, JSTL Core contains the following tags:

      • c:catch
      • c:choose
      • c:forEach
      • c:forTokens
      • c:if
      • c:import
      • c:otherwise
      • c:out
      • c:param
      • c:redirect
      • c:remove
      • c:set
      • c:url
      • c:when

      Displaying artists…

      The next step is to write ArtistsDAO (with a findByCountryid(int countryid) method which returns a list of artists who are from the same country), ArtistsController (which now takes one parameter, the countryid). Interestingly, this means that two views need to be writter, the expected ArtistsView.jsp and ErrorView.jsp in case, for instance, countryid is not valid.

      ArtistsView.jsp will, of course, be written using JSTL tags (including, most probably, c:if, to know when to display the list of artists). Accessing a request parameter (which is not the same thing as a request attribute) is done through the param object in JSP.

      … and songs + and the rest

      To display songs, we need SongDAO (with the findByArtistid(int artistid) method), SongsController (which now takes two parameters: countryid and artistid) and the corresponding view, SongsView.jsp.

      The rest is straightforward:

      • Adding AddToCartController (which when given a songid adds that song to the shopping cart belonging to the session) requires that the method findById(int songid) be implemented in SongDAO. For cosmetic reasons, an AddToCartView.jsp is also needed.
      • CartController is trivial because it just forwards to CartView.jsp. The shopping cart is accessed through the sessionScope object and, as it is a list of songs, a c:forEach can be used to display them.
      • Clearing the cart is left as an exercise…

      Using custom tags

      The standard tag library is very useful as it is but it is also possible to create custom tag libraries with custom tags. For example, we will do the following:

      • Create a tags folder in WEB-INF
      • Add a simple footer.tag to it
      • Refer to the footer tag from the existing JSP
      • Add a header.tag which takes as a parameter a title
      • Refer to the header tag from the existing JSP
      • Finally, create and use a link.tag which makes writing the various HTML links in the web application easier. One possibility is illustrated above.
      This topic is part of our
      Web Application Development in Java
      training

Our forthcoming training courses

  • No training courses are scheduled.

Creating JavaServer Pages (JSP)

This topic is part of our Web Application Development in Java training

JavaServer Pages (JSP) first appears in 1999 as an alternative to ASP and PHP for writing server-side software easily.

Like ASP and PHP, JSP allows code (in its case, Java) to be interleaved with HTML. The Java code is delimited by <% and %> and can refer to the following objects:

  • out, a PrintWriter
  • request, an HttpServletRequest
  • response, an HttpServletResponse
  • session, an HttpSession. Note that a JSP always runs within a session. This is mandated by the J2EE specs.

Write a small Java web application which:

  • allows the user to enter an integer and when submit is clicked
  • calculates and shows its factorial by using a JSP. This means that the code for doing the calculation as well as for creating the output needs to belong to the same JSP.

We are going to enhance the web application so that the logic for the calculation of the factorial is encapsulated in a distinct class. We will make that class follow JavaBean conventions so that we can use it easily from a JSP. In essence, a class is a JavaBean if the following are all true:

  • It must have a public default constructor
  • It must provide getters and setters for accessing attributes
  • It must be serializable

JavaBeans can then easily be used, properties set and retrieved

Web applications generally follow a MVC (Model View Controller) architecture. In such an architecture, the application has three types of components:

  • Controllers receive HTTP requests, call upon Models for all domain logic and then select a View
  • Models manage the domain logic (business rules as well as data)
  • Views render HTTP responses

We can enhance our application to become MVC compliant by implementing a controller as a Servlet. The controller gets a request, calls appropriate methods on our existing JavaBean to get the factorial (this is our model), sets the factorial as another attribute of the request and then selects a JSP (our view) for producing an HTML response.

The JSP can then access the attribute from its requestScope using Expression Language. The requestScope maps attribute names to their values. It allows JSP to access the attributes of the request object.

This topic is part of our Web Application Development in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Learn how to build powerful, efficient and secure websites

[img_assist|nid=223|title=|desc=|link=none|align=center|width=318|height=448]

A lot of companies rely on PHP and MySQL for powering their mission critical websites and web applications. Consequently, developers working in those companies need to be skillful in PHP and MySQL.

Knowledge7 is organising a Web Development with PHP and MySQL training starting on 14 March and will run over five Mondays from 9:00 to 16:00.

IT and HR Managers will be pleased to know that their staff will be more skilled and efficient by becoming conversant with the latest web technologies. Of course, trainees will also be exposed to best-practices and standards as used in industry allowing them to easily overcome challenges they might come across during their career.

Our Web Development with PHP and MySQL is MQA approved. Call Liliane on 5834-9001 for more information.

Book your seat now. Places are limited.

Our forthcoming training courses

  • No training courses are scheduled.
« Previous Page
Next Page »

Looking for something?

Want to know more?

Get our newsletter

Discover the latest news, tips and tricks on Linux, the Web and Mobile technologies every week for FREE

This work is licensed by Knowledge7 under an Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license.