Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf ·...

21
VO/KU (707.023/707.024; 706.706/706.707) Software Architecture (2016/17) Web Architecture - Java Web Application Tutorial Roman Kern ([email protected]) Heimo Gursch ([email protected]) http://kti.tugraz.at/staff/rkern/courses/sa/index.html http://kti.tugraz.at/

Transcript of Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf ·...

Page 1: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

VO/KU (707.023/707.024; 706.706/706.707)

Software Architecture (2016/17)

Web Architecture - Java Web Application Tutorial

Roman Kern ([email protected])Heimo Gursch ([email protected])

http://kti.tugraz.at/staff/rkern/courses/sa/index.html

http://kti.tugraz.at/

Page 2: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

Contents

1 Introduction 31.1 About this document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Dropwizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3 AngularJS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Application Layout and Setup 52.1 Create the Maven Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Web Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.3 Target Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.4 Final Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

3 Application 103.1 Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

3.1.1 WebApplication.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.1.2 WebResource.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.1.3 Request.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.1.4 Response.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.1.5 WebConfiguration.java . . . . . . . . . . . . . . . . . . . . . . . . . . 14

3.2 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.3 HTML and JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3.3.1 index.html . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.3.2 webAppController.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

4 Compiling and running the application 18

List of Figures 19

Listings 20

2

Page 3: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

1

Introduction

1.1 About this document

This document is aimed at students attending the Software Architecture lecture. During the course of thislecture, a web application needs to be implemented. This manual gives some insightes to set up a webApplication in Java, HTML and JavaScript using Maven and the Frameworks Dropwizard and AngularJS.

1.2 Dropwizard1

Web application development in Java was accompanied by Java application servers like Apache Tomcat,GlassFish, IBM WebSphere, JBoss, Jetty, etc. Such web application servers could contain multiple webapplications at once. These full scale web application server come with some drawbacks like

• It is problematic/complicated to separate the applications within the application server,

• The assignment of dedicated resources is tricky,

• Depending on the server used, there might occur scaling difficulties.

In many installations these problems are solved by just having one web application in a singe webapplication server. But then the question arises why the full-scale web server is necessary at all. Hence,embedded versions of Java application servers have been develop. Notable examples include

Jetty Embedded https://www.eclipse.org/jetty/documentation/current/embedding-jetty.html

Tomcat Embedded https://tomcat.apache.org/download-80.cgi.

These embedded severs are more light weighted and can be integrated in other software projects. Insome cases these embedded servers might lack infrastructural functions, like logging or user management.Therefore, additional libraries are needed. Projects like Dropwizard where started to combine embeddedapplication servers with the necessary libraries to facilitate a large software project. The goal of all ofthese projects it the creation of lightweight libraries which allow the fast and simple creation of webapplications. All the HTTP and servelt API should be provided by a simple Java API. There are someproject trying to achieve this goal, examples—and therefore Dropwizard competitors—are

Spring boot http://projects.spring.io/spring-boot

Spark http://sparkjava.com/

1http://dropwizard.io/

3

Page 4: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

Play https://www.playframework.com.

Software developed with one of these frameworks are often called micro services.In this tutorial Dropwizard will be used as an example for a modern, lightweight library to create

fully self managed web application. Dropwizard combines existing Java libraries to create the necessaryframework needed by a web application. Dropwizard includes:

Jetty in in embedded mode Does all the HTTP stuff

Jersey Java API for RESTful Web Services (JAX-RS)

Metrics Performance monitoring

Guava Google Java library providing a large amount of useful stuff

Jackson Mapping between Java objects and JSON

JDBI SQL database connection

Logback Logging

Miscellaneous Some other small stuff

In this tutorial Dropwizard will be used to serve static and dynamic content. The "Getting Started" manualat http://www.dropwizard.io/1.0.5/docs/getting-started.html shroud give a theneeded information to complete this tutorial.

1.3 AngularJS2

AngularJS is a JavaScript Framework to map dynamic data to the static page layout. It fills the dynamicdata coming from the server into the HTML Layout and feeds user inputs back to the server. AngularJStakes over the task of manipulating the HTML DOM-tree and the communication with the server. In thismanual just very few features of AngularJS are shown. The curious reader is referred to one of the manyAngularJS tutorials like http://www.w3schools.com/angular/ or https://docs.angularjs.org/tutorial.

In this tutorial no formatting of the HTML page is done. In many project Twitter Bootstrap3 is used toassist with the formatting. Bootstrap is a great help over conventional, simple CSS formatting HTMLpages.

2https://angularjs.org/3https://getbootstrap.com/

4

Page 5: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

2

Application Layout and Setup

2.1 Create the Maven1 Project

The complete Java software is handled as an Maven project. Maven is an build tool which manages theJava dependencies and overlooks the building process. Gradle2 is an more modern alternative achievingthe same and even more as Maven. A Maven project can be initiated in an IDE (Integrated DevelopmentEnvironment) of your choice. Eclipse, IntelliJ, NetBeans and other should work perfectly well. The firstthing is to create a new Maven project. In this tutorial the project is called SaWebApp, shorthand forSoftware Architecture Web Application. In this tutorial Maven version 3 is used. When using Mavendirectly and not interacting with it by your IDE, the line

1 mvn -B archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=at.tugraz.kti -DartifactId=SaWebApp

Listing 2.1: Maven command line instructions to create the project

creates a new Maven project. When using an IDE, use the dialogues to create a new Maven project andname it accordingly. When the project in generated, it can be compiled with

1 mvn compile

Listing 2.2: Maven command line instructions to compile the project

and packaged with

1 mvn package

Listing 2.3: Maven command line instructions to build and package the project

Both commands have to be executed in the newly generate project directory so that Maven finds thepom.xml descriptor. Further information on using Maven can be found at https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html. It is strongly advisedto use an IDE, than all this Maven command line stuff is hidden from you.

Maven generates the basic directory structure. Figure 2.1 shows the basic empty directory structure.This structure needs to be extended by some other files and directories. This will be explained later on.The automatically generated pom.xml needs to be extended too. At the end, the pom.xml should looklike

1 <?xml version="1.0" encoding="UTF-8"?>2 <project xmlns="http://maven.apache.org/POM/4.0.0"3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/

xsd/maven-4.0.0.xsd">5 <modelVersion>4.0.0</modelVersion>

1https://maven.apache.org/2https://gradle.org/

5

Page 6: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

Figure 2.1: Basic empty directory structure as it is generated by Maven

6 <groupId>at.tugraz.kti.sawebapp</groupId>7 <!-- name of the app -->8 <artifactId>SaWebApp</artifactId>9 <version>0.0.1-SNAPSHOT</version>

10 <packaging>jar</packaging>11 <properties>12 <!-- set the source encoding -->13 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>14 <!-- set Java version -->15 <maven.compiler.source>1.8</maven.compiler.source>16 <maven.compiler.target>1.8</maven.compiler.target>17 <!-- variables setting the dependency versions -->18 <dropwizard.version>1.0.5</dropwizard.version>19 <dropwizard.redirect.version>1.0.0</dropwizard.redirect.version>20 </properties>212223 <build>24 <plugins>25 <!-- The Maven shades plugin generates an all-in-one ("fat") jar at26 the end of the building process. The web application is then fully27 contained in this jar. Only this fat-jar and the configuration files28 need to be shipped to the customer. -->29 <plugin>30 <groupId>org.apache.maven.plugins</groupId>31 <artifactId>maven-shade-plugin</artifactId>32 <version>2.4.3</version>33 <configuration>34 <createDependencyReducedPom>true</createDependencyReducedPom>35 <filters>36 <filter>37 <artifact>*:*</artifact>38 <excludes>39 <exclude>META-INF/*.SF</exclude>40 <exclude>META-INF/*.DSA</exclude>41 <exclude>META-INF/*.RSA</exclude>42 </excludes>43 </filter>44 </filters>45 </configuration>46 <executions>47 <execution>48 <phase>package</phase>49 <goals>50 <goal>shade</goal>51 </goals>52 <configuration>

6

Page 7: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

53 <transformers>54 <transformer implementation="org.apache.maven.plugins.shade.resource

.ServicesResourceTransformer" />55 <transformer implementation="org.apache.maven.plugins.shade.resource

.ManifestResourceTransformer">56 <mainClass>at.tugraz.kti.sawebapp.WebApplication</mainClass>57 </transformer>58 </transformers>59 </configuration>60 </execution>61 </executions>62 </plugin>6364 <!-- generate JavaDoc JAR -->65 <plugin>66 <groupId>org.apache.maven.plugins</groupId>67 <artifactId>maven-javadoc-plugin</artifactId>68 <version>2.10.4</version>69 <executions>70 <execution>71 <id>attach-javadocs</id>72 <goals>73 <goal>jar</goal>74 </goals>75 </execution>76 </executions>77 </plugin>7879 <!-- generate sources JAR -->80 <plugin>81 <groupId>org.apache.maven.plugins</groupId>82 <artifactId>maven-source-plugin</artifactId>83 <version>3.0.1</version>84 <executions>85 <execution>86 <id>attach-sources</id>87 <goals>88 <goal>jar</goal>89 </goals>90 </execution>91 </executions>92 </plugin>9394 </plugins>95 </build>9697 <!-- Dropwizard dependencies -->98 <dependencies>99 <!-- Dropwizard itself -->

100 <dependency>101 <groupId>io.dropwizard</groupId>102 <artifactId>dropwizard-core</artifactId>103 <version>${dropwizard.version}</version>104 </dependency>105 <!-- Static assets bundle - Needed to serve static resources like106 HTML- and JS- files. -->107 <dependency>108 <groupId>io.dropwizard</groupId>109 <artifactId>dropwizard-assets</artifactId>110 <version>${dropwizard.version}</version>111 </dependency>112 <!-- Redirect Bundle - Needed to redirect users from the plain the web113 address to the index.html file -->

7

Page 8: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

114 <dependency>115 <groupId>io.dropwizard-bundles</groupId>116 <artifactId>dropwizard-redirect-bundle</artifactId>117 <version>${dropwizard.redirect.version}</version>118 </dependency>119 </dependencies>120121 </project>

Listing 2.4: Content of the pom.xml file

2.2 Web Setup

Similarly to Maven in the Java word, also in the web development world helpers and frameworks havebeen created. Many of this tools in the web development domain use Node.js3 as an execution platform.Some important examples are:

Yeoman is a scaffolding tool. This means it sets up the necessary file and folder structure4

Angular-Cli is a scaffolding tool specially for AngularJS 25; currently the first release is still underdevelopment

Bower manages packages and dependences, so that there is no need to manually link them into yourHTML code6

Grunt is a build system to build, preview and test an application7

Gulp alternative to Grunt8

2.3 Target Architecture

The target architecture depicted in Figure 2.2 follows a client-server principle. The client is fully executedwithin a Web browser and consists of two parts. The first part is done in HTML and manages the userinteractions. For an easy and prettier formation in CSS, Twitter Bootstrap is used. The second part on theclient is implemented in JavaScript and deals with data management, server communication and processlogic done on the server. Looking on the server side, Dropwizard and all the Java libraries it provides laya very good platform for the Java code implementing the business logic. Java components to connect todatabases or other web services are also provided by Dropwizard.

2.4 Final Project Structure

In this section the parts of the web application will be enumerated. Figure 2.3 shows this structure. Thepom.xml-file was already discussed in the previous section. The other files or folders will be explainedhere.

src->main->java Contains all Java code. See Section 3.1

src->main->resources->assets Contains all HTML and JavaScript code. See Section 3.33https://nodejs.org/4http://yeoman.io/5https://github.com/angular/angular-cli6https://bower.io/7http://gruntjs.com/8http://gulpjs.com/

8

Page 9: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

Figure 2.2: Desired Client-Server Architecture

Figure 2.3: Full Project structure

target Output directory where Maven will place the files it build. In here the final fat-jar will be placed

9

Page 10: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

config.yml Configuration file for the web app. See Section 3.2

10

Page 11: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

3

Application

This chapter goes through all project files and lists their content.

3.1 Java

This section covers all Java classed needed to create the server side part of the application.

3.1.1 WebApplication.java

WebApplication.java is the main class of the project. This class describes what parts of the webapplication consist of and how these parts work together.

1 package at.tugraz.kti.sawebapp;23 import at.tugraz.kti.sawebapp.model.WebConfiguration;4 import io.dropwizard.Application;5 import io.dropwizard.assets.AssetsBundle;6 import io.dropwizard.bundles.redirect.PathRedirect;7 import io.dropwizard.bundles.redirect.RedirectBundle;8 import io.dropwizard.jersey.setup.JerseyEnvironment;9 import io.dropwizard.setup.Bootstrap;

10 import io.dropwizard.setup.Environment;1112 /**13 * Software Architecture Web Application - Tutorial14 *15 * Simple Dropwizard web application providing a client-side static HTML page16 * and a server-side java servlet.17 *18 * See http://www.dropwizard.io/1.0.5/docs/getting-started.html for more19 * information.20 *21 * <p><em>Date:</em> 2016-11-23</p>22 * @author <a href="mailto:[email protected]">Heimo Gursch</a>23 */24 public class WebApplication extends Application<WebConfiguration> {2526 /**27 * Initialises the application.28 *29 * Creates a static assets bundle for delivering static content from within30 * the Dropwizard app jar file.31 *32 * @param bootstrap Configuration as it is read from the YAML-configuration33 * file34 */

11

Page 12: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

35 @Override36 public void initialize(Bootstrap<WebConfiguration> bootstrap) {37 // Serv static assets via the root path38 bootstrap.addBundle(new AssetsBundle("/assets", "/"));39 // Redirect users to the index.html file if they did not specify a40 // particular file41 bootstrap.addBundle( new RedirectBundle( new PathRedirect("/", "/index.html") )

);42 }4344 /**45 * Setup for the main part of the Dropwizard web application.46 *47 * Creates the servlet (=resource) and puts it into service.48 *49 * @param configuration The configuration as read from the50 * YAML-configuration file51 * @param environment All services and configurations Dropwizard offers to52 * this application53 * @throws Exception Thrown if something goes wrong. Not used so far...54 */55 @Override56 public void run(WebConfiguration configuration, Environment environment) throws

Exception {57 // Create Servlet58 WebResource webResource = new WebResource(configuration.fromYaml);5960 // Add servelet61 JerseyEnvironment jersey = environment.jersey();62 jersey.register(webResource);63 }6465 /**66 * Main method to start the Dropwizard application.67 *68 * @param args Dropwizard needs the path to the YAML configuration file as69 * parameters. Run the application with parameter:70 * {@code server <path-to-config-file>/<config-file-name>.yml}71 * @throws java.lang.Exception Something when wrong wile starting the72 * Dropwizard application.73 */74 public static void main(String[] args) throws Exception {75 new WebApplication().run(args);76 }7778 }

Listing 3.1: WebApplication.java

3.1.2 WebResource.java

The class WebResource is the only servlet in this application. It does the actual work, i. e. it answerersthe requests from the web clients.

1 package at.tugraz.kti.sawebapp;23 import at.tugraz.kti.sawebapp.model.Request;4 import at.tugraz.kti.sawebapp.model.Response;5 import javax.inject.Singleton;6 import javax.ws.rs.Consumes;7 import javax.ws.rs.GET;8 import javax.ws.rs.POST;9 import javax.ws.rs.Path;

12

Page 13: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

10 import javax.ws.rs.Produces;11 import javax.ws.rs.QueryParam;12 import javax.ws.rs.core.MediaType;13 import javax.xml.ws.WebServiceException;141516 /**17 * Simple servlet providing two methods:18 * <br><ul>19 * <li> {@link #calc(at.tugraz.kti.sawebapp.model.Request)}: subtract,20 * multiply or divide two numbers.21 * <li> {@link #echo(java.lang.String)} a string with an appended22 * {@code helloString}-parameter23 * </ul>24 * <br>25 * <ul>26 * <li> The {@code @Path}-annotation tells the container the URL-extension of27 * this servlet.28 * <li>The {@code @Produces}-annotation tells the container witch content-type29 * this servelt generates.30 * <li> The {@code @Singleton}-annotation tells the container to instantiate31 * this servlet only once.32 * </ul>33 *34 * <p>35 * Content-type specification with {@code @Produces} and {@code @Consumes} can36 * be done for the class, or for each method separately.37 * </p>38 *39 * <p><em>Date:</em> 2016-11-23</p>40 * @author <a href="mailto:[email protected]">Heimo Gursch</a>41 */42 @Path("/resource")43 @Produces(MediaType.APPLICATION_JSON)44 @Singleton45 public class WebResource{46 /**47 * Configured String48 */49 private final String helloString;5051 /**52 * Creates new instance and sets the helloString53 *54 * @param helloString The String this servelt will use for the greeting its55 * visitors.56 */57 public WebResource( String helloString ){58 this.helloString = helloString;59 }6061 /**62 * Simple echo method63 *64 * @param text String to be the prefix of the response65 * @return the sent text appended with hello-Sting66 */67 @GET68 @Path("echo")69 public String echo( @QueryParam("string") String text ){70 return text+helloString;71 }72

13

Page 14: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

73 /**74 * Method to add, subtract, multiply or divide two numbers.75 *76 * The {@code @POST}-annotation specifies the HTTP method to call this77 * implementation The {@code @Path}-annotation tells the container the78 * URL-extension of this method79 *80 * @param request Input numbers and operation. Send to this method in the81 * body of a HTTP POST request82 * @return The calculation result.83 */84 @POST85 @Path("calc")86 @Consumes(MediaType.APPLICATION_JSON)87 public Response calc( Request request ){88 Response response = new Response();89 switch( request.operation ){90 case "plus":91 response.result = request.first+request.second;92 return response;93 case "minus":94 response.result = request.first-request.second;95 return response;96 case "multiply":97 response.result = request.first*request.second;98 return response;99 case "divide":

100 response.result = request.first/request.second;101 return response;102 default:103 throw new WebServiceException( "Unknown operation \""+request.operation+"\""

);104 }105 }106 }

Listing 3.2: WebResource.java

3.1.3 Request.java

Class holding the values send form the JavaScript to the server.

1 package at.tugraz.kti.sawebapp.model;23 /**4 * Holds the input parameters for the calculation5 *6 * Since this class is only used for communication and no logic is done here7 * (not even value verification) all fields are public and no getter and setter8 * are used.9 *

10 * <p><em>Date:</em> 2016-11-23</p>11 * @author <a href="mailto:[email protected]">Heimo Gursch</a>12 */13 public class Request{14 public double first;15 public double second;16 public String operation;17 }

Listing 3.3: Request.java

14

Page 15: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

3.1.4 Response.java

Class holding the servers response to the clients request.1 package at.tugraz.kti.sawebapp.model;23 /**4 * Hold the result of the calculation5 *6 * Since this class is only used for communication and no logic is done here7 * (not even value verification) all fields are public and no getter and setter8 * are used.9 *

10 * <p><em>Date:</em> 2016-11-23</p>11 * @author <a href="mailto:[email protected]">Heimo Gursch</a>12 */13 public class Response{14 public double result;15 }

Listing 3.4: Response.java

3.1.5 WebConfiguration.java

This class extends the web Dropwizard configuration class. All properties defined in this class are readfrom the configuration file at the start of the server (see also Section 3.2).

1 package at.tugraz.kti.sawebapp.model;23 import com.fasterxml.jackson.annotation.JsonProperty;4 import io.dropwizard.Configuration;5 import javax.validation.Valid;6 import javax.validation.constraints.NotNull;789 /**

10 * Configuration class to read in configuration parameter11 *12 * Since this class is only used for communication and no logic is done here13 * (value verification is done by annotations) all fields are public and no14 * getter and setter are used.15 *16 * <p><em>Date:</em> 2016-11-23</p>17 * @author <a href="mailto:[email protected]">Heimo Gursch</a>18 */19 public class WebConfiguration extends Configuration{20 /**21 * Annotations are used to verify the parsed configuration22 */23 @Valid24 @NotNull25 @JsonProperty26 public String fromYaml;27 }

Listing 3.5: WebConfiguration.java

3.2 Configuration

The configuration file is written in the YAML-format. The configuration parameters are made up ofDropwizard specific configurations and of the configuration properties specified in the project specificconfiguration. The project specific configuration is defined in the WebConfiguration-class from

15

Page 16: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

Listing 3.6. The only required configuration form Dropwizard are the port and root path definitions, whichare stated in the lines 2-13 of Listing 3.6. The root path is used for all the servlets (i. e. DropwizardResource classes) and not for the static files (i. e. HTML and JavaScript) also served by Dropwizard.

1 # Configure ports an paths of Dropwizard server2 server:3 # Application port, i.e. used by the user4 applicationConnectors:5 - type: http6 port: 80807 # Specify the URL prefix for servlets (=resources)8 rootPath: "/api/*"9

10 # Housekeeping port, i.e. used to check statistics11 adminConnectors:12 - type: http13 port: 80811415 # Application specific settings16 fromYaml: "This is the config String"

Listing 3.6: config.yml

3.3 HTML and JavaScript

This section contains the software which will be delivered to the client’s web browser.

3.3.1 index.html

The HTML-file contains all the elements which are shown to the user. To get a better formatting, CSSwould be needed which is not included here.

1 <!DOCTYPE html>2 <!-- Simple HTML Page. As there is only one ng-app, it is bound to the whole page

and not to a singe HTML element -->3 <html ng-app="SaWebApp">4 <head>5 <title>Software Architecture: Web Application - Tutorial</title>67 <!-- Include AngularJS -->8 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.

js"></script>9 <!-- Include the angular controller written for this page -->

10 <script src="js/webAppController.js"></script>11 </head>1213 <body ng-controller="webAppController">1415 <div>First number:16 <!-- Create an input-field and establish the two-way binding with the

JavaScript variables -->17 <input type="text" ng-model="firstNumber">18 </div>19 <br/>20 <div>Second number:21 <!-- Create an input-field and establish the two-way binding with the

JavaScript variables -->22 <input type="text" ng-model="secondNumber">23 </div>2425 <br/>26

16

Page 17: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

27 <div>Result:28 <!-- Show the result, if there is any. The resultAvailable()-method29 checks if there is a result30 The double curly braces tell AngularJs to show the value in the31 variable, not the variable name32 -->33 <div ng-if="resultAvailable()">{{result}}</div>34 </div>3536 <br/>37 <br/>3839 <!-- Create input buttons. Tell Angular to run the calculate() method if a

button is clicked -->40 <button ng-click="calculate(’plus’)">Add</button>41 <button ng-click="calculate(’minus’)">Subtract</button>42 <button ng-click="calculate(’multiply’)">Multiply</button>43 <button ng-click="calculate(’divide’)">Divide</button>44 </body>45 </html>

Listing 3.7: index.html

3.3.2 webAppController.js

The JavaScript file holds all the logic used to interact with the server and map the data between the serverand the HTML page.

1 /**2 * Create the simplest possible AngularJS 1 application consisting only of a3 * controller.4 *5 * - "SaWebApp" is the name of the complete application, consisting only of this6 * controller7 * - "webAppController" is the name of this controller8 * - "$scope" is the scope/namespace of this controller9 * - "$http" AngluarJS object to do HTTP communication

10 *11 * See https://docs.angularjs.org/guide for more details12 */1314 angular.module("SaWebApp", []).controller("webAppController", [ "$scope", "$http",

function($scope, $http) {15 // Create variables and initialise them16 $scope.firstNumber = 1.3;17 $scope.secondNumber = 2.1;18 $scope.result = null;1920 // Calls the REST method on the server.21 $scope.calculate = function(operation){22 // Build and send the request23 $http({24 // Specify the URL25 url: "api/resource/calc",26 // Specify the HTTP method27 method: "POST",28 // Specify the request’s payload29 data: {30 "first": $scope.firstNumber,31 "second": $scope.secondNumber,32 "operation": operation33 }34

17

Page 18: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

35 // In the case of a successful response, the result is written in the36 // corresponding variable37 }).success(function(response) {38 $scope.result = response.result;39 // In the case of a negative response, a message is shown40 }).error(function(message) {41 alert("Error while retrieving search result");42 });43 };444546 // Checks if there is a result available.47 $scope.resultAvailable = function(){48 return $scope.result!==undefined && $scope.result!==null;49 };50 }]);

Listing 3.8: webAppController.js

18

Page 19: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

4

Compiling and running the application

The complete application can be build with Maven, either via the command line or through the IDE. Whenthe project is run or build the first time, Maven needs to download all dependencies. This can take awhile. Also the building process can take a while, since the creation of the fat-jar might be complicatedfor Maven. If the project has been build, it can started it with the parameters

1 server config.yml

Listing 4.1: Running the project

The parameters shown in Listing 4.1 are needed to tell Dropwizard that it should be run in its server modeand that the file config.yml contains the configuration for the server.

If the fat-jar is used to run the server, the web application can be started with

1 java - jar SaWebApp.jar server config.yml

Listing 4.2: Running the jar

When the web application is up and running, logging information will be displayed in the console.The resulting web page can be seen under the URL redirected URL http://localhost:8080/ orthe full http://localhost:8080/index.html. The http://localhost:8081 presents apage with some small statistic about the running Dropwizard service.

19

Page 20: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

List of Figures

2.1 Basic Maven Directory Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.2 Desired Client-Server Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.3 Full Project structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

20

Page 21: Software Architecture (2016/17)kti.tugraz.at/staff/rkern/courses/sa/2016/SaWebApp - Tutorial.pdf · This document is aimed at students attending the Software Architecture lecture.

Listings

2.1 Maven command line instructions to create the project . . . . . . . . . . . . . . . . . . 52.2 Maven command line instructions to compile the project . . . . . . . . . . . . . . . . . 52.3 Maven command line instructions to build and package the project . . . . . . . . . . . . 52.4 Content of the pom.xml file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.1 WebApplication.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.2 WebResource.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.3 Request.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.4 Response.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.5 WebConfiguration.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.6 config.yml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.7 index.html . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.8 webAppController.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164.1 Running the project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184.2 Running the jar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

21