© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_17

17. The Interweb

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

(Courtesy xkcd: Interblag)

../images/435475_2_En_17_Chapter/435475_2_En_17_Figa_HTML.jpg

Just about all software projects are now Internet-based, either web applications (those that produce HTML that is shown via a browser like Firefox) or web services (those that connect via JavaScript in the browser or through mobile apps, like those on Android and iOS devices).

This chapter is devoted to learning about the concepts and some code related to web applications and web services.

Web 101

The Web is a complex beast. Here’s what you need to know:
  • Server: The computer serving web pages and other content

  • Client: The computer that receives web pages and is used by a person

  • Request: The data sent to the Server from the Client

  • Response: The data sent back to the Client after a Request

  • HTML: The language used to define web pages

  • CSS: “Cascading style sheets”; defines the styles of the web page

  • JavaScript: A programming language that is used within web pages and executed on the client, although it can be used on the server side as well

My First Web App

You should make something very basic for your first web application. This way, you will have a better understanding of what’s going on “behind the scenes” of many web frameworks. A web framework is a set of related tools and libraries useful for building web applications.

Create a file called App.java and copy the following code into it:
 1   import java.io.IOException;
 2   import java.io.OutputStream;
 3   import java.net.InetSocketAddress;
 4   import com.sun.net.httpserver.*;
 5
 6   public class App {
 7
 8       static class MyHandler implements HttpHandler {
 9           public void handle(HttpExchange t) throws IOException {
10               String response = "<html> Hello Inter-webs! </html>";
11               t.sendResponseHeaders(200, response.length());
12               OutputStream os = t.getResponseBody();
13               os.write(response.getBytes());
14               os.close();
15           }
16       }
17
18       public static void main(String[] args) throws Exception {
19           HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
20           server.createContext("/", new MyHandler());
21           server.setExecutor(null); // creates a default executor
22           server.start();
23           System.out.println("Server running at http://localhost:8000");
24       }
25
26   }

All this does is create an HttpServer that listens for connections on port 8000 and responds with a message.

After running this code (javac App.java && java App), open your web browser and point it to http://localhost:8000/ (it should show “Hello Inter-webs!”). Press Ctrl+C to stop the application.

../images/435475_2_En_17_Chapter/435475_2_En_17_Figb_HTML.jpg localhost refers to the computer you’re on, and :8000 refers to port 8000.

Congratulations! You just made a web application! It’s not on the Internet yet, and it’s extremely simple, but it’s a good start.

Port?

URL (Uniform Resource Locator): The unique name used to locate resources on any network or machine. Sometimes it starts with “http”; sometimes it includes a port.

HTTP Hypertext Transfer Protocol: The typical protocol used to communicate over the wire.

HTTPS (Secure HTTP): Similar to HTTP but encodes all data using an asymmetrical key so no device can read the data except for the intended recipient.

Port: A number that must be specified when communicating between computers (the default port for HTTP is 80).

The Holy Grails

Grails is a web framework for Groovy that follows the example of Ruby on Rails (hence Grails). It is an opinionated web framework with a command-line tool that gets things done really fast. Grails uses convention over configuration to reduce configuration overhead. This can greatly reduce the effort required to get started on a new project or add additional functionality.

Grails lives firmly in the Java ecosystem and is built on technologies such as Spring Boot and Hibernate. Grails also includes an object-relational mapping (ORM) framework, which maps objects to database tables, called GORM, and has a large collection of plug-ins.

Quick Overview

This overview is based on Grails 4.0.0, but the basics should remain the same for all versions of Grails, 3.0 and above. After installing Grails,1 you can create an app by running the following on the command line:
1   $ mkdir g4
2   $ cd g4
3   $ grails create-app --inplace

Then, you can run commands such as create-domain-class and generate-all to create your application as you go. Run grails help to see the full list of commands available. We will cover these commands more fully later on in the chapter.

Grails applications have a very specific project structure. The following is a simple breakdown of most of that structure:
  • grails-app: The Grails-specific folder.
    • conf: Configuration files, such as application.yml and logback.groovy.

    • controllers: Controllers with methods for index/create/edit/delete, or anything else.

    • domain: Domain model; classes representing your persistent data.

    • i18n: Message bundles, useful for supporting multiple languages (English, Spanish, etc.).

    • init: Contains your Application.groovy and Bootstrap.groovy files that initialize the application when it starts.

    • services: Back-end services in which your back end or “business” logic goes.

    • taglib: You can very easily define your own tags for use in your GSP files.

    • views: Views of MVC; typically, these are GSP files (HTML-based with embedded Groovy code).

  • assets
    • stylesheets: CSS.

    • images: Images used by your web application.

    • javascripts: Your JavaScript files.

  • src: Common code that doesn’t fit anywhere else.
    • main/groovy: Groovy code.

    • test/groovy: Groovy tests.

  • gradle: Contains the Gradle wrapper jar.

To create new domain (model) classes, use the create-domain-class command. Run the following (in the root directory of the project):
1   $ grails create-domain-class example.Comment
2   $ grails create-domain-class example.User
3   $ grails create-domain-class example.Post
It’s a good idea to include a package for your domain classes (such as example.Post). This command creates both the domain class and an associated Spock Specification. Change User and Comment to look like the following:
 1   class User { String name }
 2   class Comment { String text }
A domain class in Grails also defines its mapping to the database. For example, edit your domain class representing a blog post to look like the following (assuming User and Comment have already been created):
 1   class Post {
 2       String text
 3       int rating
 4       Date created = new Date()
 5       User createdBy
 6
 7       static hasMany = [comments: Comment]
 8
 9       static constraints = {
10           text(size:10..500)
11       }
12   }

The static hasMany field is a map that represents one-to-many relationships in your database—this means a Post can have many Comments. Grails uses Hibernate in the background to create tables for all your domain classes and relationships. Every table gets an id field for the primary key by default which is automatically assigned.

To have Grails automatically create your controller and views (and tests) after you have defined the domain classes, run the following:
1   $ grails generate-all example.User
2   $ grails generate-all example.Comment
3   $ grails generate-all example.Post

../images/435475_2_En_17_Chapter/435475_2_En_17_Figc_HTML.jpg Grails will ask if you want to overwrite existing files, if they exist. So, be careful when using this command.

When you want to test your app, you simply run the following:
1   $ grails run-app

It should output eventually the following:

Grails application running at http://localhost:8080 in environment: development.

Next, open a browser and go to that URL. You should see the following based on the default generated views which has a list of Controllers, Application Status, Artefacts, and a list of Installed Plugins:

../images/435475_2_En_17_Chapter/435475_2_En_17_Figd_HTML.jpg

If you follow the links to the respective controllers, you can create Users, then create Posts, and then create Comments on those Posts.

Plug-ins

The Grails 4.0 system now includes over 190 plug-ins. To list all of the plug-ins, simply execute the following:
1   $ grails list-plugins
When you’ve picked out a plugin you want to use, execute the following to see more information about the plugin (with the plugin name):
1   $ grails plugin-info [NAME]

This will tell you how to add the plug-in to your project. Edit your build.gradle file and add the dependency there.

../images/435475_2_En_17_Chapter/435475_2_En_17_Fige_HTML.jpg Only an Overview This has been only a brief overview of Grails. Many books have been written about Grails and how to use it. For more information on using Grails, please visit grails.org.2

Cloud

Grails is supported by the following cloud providers:
  • CloudFoundry3

  • Amazon4

  • Heroku5

However, it is not within the scope of this book to go over all of them, but we will shortly discuss Heroku.

Heroku was one of the first cloud platforms and has been in development since June 2007. When it began, it supported only Ruby, but it has since added support for Java, Scala, Groovy, Node.js, Clojure, and Python. Heroku supports multiple tiered accounts, including a free account.

Heroku relies on git for pushing changes to your server. For example, to create an app in Heroku using the CLI, do the following:
1   $ heroku create
2   $ git push heroku master

Your app will be up and running, and Heroku will identify the URL where you will find it.

../images/435475_2_En_17_Chapter/435475_2_En_17_Figf_HTML.jpg Go launch a Grails app on Heroku!

The REST

REST stands for REpresentational State Transfer.6 It was designed in a PhD dissertation and has gained huge popularity as the new web service standard. Many developers have praised it as a much better standard than SOAP (which I will not attempt to describe).

At the most basic level in REST, each CRUD (create, read, update, delete) operation is mapped to an HTTP method. For example:
  • Create: POST

  • Read: GET

  • Update: PUT

  • Delete: DELETE

The transport mechanism is assumed to be HTTP, but the message contents can be of any type, usually XML or JSON.

The JSR community has designed the JAX-RS API for building RESTful Java web services, while Groovy and Scala both have some built-in support for XML and JSON and various ways of building web services. Spring Boot7 and Spring MVC also have great support for REST.

Using Maven Archetypes

You can create a simple Java REST (JAX-RS) application using Maven, as follows:
1   mvn archetype:generate

Wait for things to download and then choose “tomcat-maven-archetype (type tomcat-maven and press Enter, then type “1”; Enter; Enter). You will need to enter a groupId and artifactId.

After creating your application, you can start it by typing the following command:
1   mvn tomcat:run

Using Grails JSON Views

Grails has a plugin for rendering views as JSON. First run plugin-info to see how to include it in your build:
1   $ grails plugin-info views-json

After adding it to your Grails project’s build dependencies, you can use a Groovy DSL to define how to render your responses in JSON. See the documentation8 for more information.

As a summary, JSON views allows you to define views under the grails-app/views directory with the .gson extension that can use a DSL for producing JSON rather than the .gsp files which produce HTML. This is useful when writing a web service that produces JSON for example.

Create a file named grails-app/views/hello.gson with the following:
json.message {
    hello "world"
}

This would produce {"message":{ "hello":"world"}} as JSON.

Summary

Congratulations! You now understand the Interweb. Yes, it is a series of tubes. Ted Stevens (see following) was right!

…They want to deliver vast amounts of information over the Internet. And again, the Internet is not something that you just dump something on. It’s not a big truck. It’s a series of tubes. And if you don’t understand, those tubes can be filled and if they are filled, when you put your message in, it gets in line and it’s going to be delayed by anyone that puts into that tube enormous amounts of material, enormous amounts of material.

—Theodore “Ted” Fulton Stevens, Sr., US senator from Alaska, December 24, 1968–January 3, 2009

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset