ICPC - LOCAL REGISTRATION SYSTEM

A Project

Presented to the faculty of the Department of Computer Science

California State University, Sacramento

Submitted in partial satisfaction of the requirements for the degree of

MASTER OF SCIENCE

in

Computer Science

by

Shiva Kumar Melam

FALL 2016

© 2016

Shiva Kumar Melam

ALL RIGHTS RESERVED

ii

ICPC - LOCAL REGISTRATION SYSTEM

A Project

by

Shiva Kumar Melam

Approved by:

______, Committee Chair John Clevenger, Ph.D

______, Second Reader Scott Gordon, Ph.D

______Date

iii

Student: Shiva Kumar Melam

I certify that this student has met the requirements for format contained in the University format manual, and that this project is suitable for shelving in the Library and credit is to be awarded for the project.

______, Graduate Coordinator ______Ying Jin, Ph.D. Date

Department of Computer Science

iv

Abstract

of

ICPC - LOCAL REGISTRATION SYSTEM

by

Shiva Kumar Melam

ICPC (International Collegiate Programming Contest) is a worldwide programming contest organized by ACM (Association for Computing Machinery) every year. Over

40,000 students from over 2500 Universities all around the globe participate in this prestigious competition. It is a team based multi-tier competition which follows the rules formulated by ACM. The competition initially takes place among the local universities and the winners of this contest get selected to the regional level competition. Winners at the regional level contest advance to the world finals.

Currently, the ICPC has a web-based registration system only for the regional and world finals Contests. Registration of the contestants/teams who participate in local contests has been a manual process i.e. the event organizers take the details of the contestants on a piece of paper. It has become a tedious process to archive and maintain the information of many such local contestants on paper. Moreover, this data couldn’t be shared among other contests. Local university contests usually determine the eligibility of the teams to v

compete in the regional and eventually to the world finals contest. This shows that there is a significant need for the ‘local registration’ data to be securely stored for further use.

The main intent of the project is to develop a RESTful API that provides services to the web based applications which makes the registration process of the contestants easy. The project also includes an AngularJS based web application which consumes these web services and stores the registered contestants’ data in a local database. The important aspect as a part of the project is to develop an API design Specification which acts as an interface that could essentially generate Javascript files for the front-end development and platform independent implementation code for the back-end. This feature gives an insight of the REST API and also provides information on how it could be implemented to develop applications.

______, Committee Chair John Clevenger, Ph.D.

______Date

vi

ACKNOWLEDGEMENTS

I would like to thank Dr. John Clevenger for taking up the role of my project advisor. He helped me understand the design processes involved in the creation of this application with ease. His feedback and guidance was very important for me to see the real purpose of my master’s project.

I would also like to thank Dr. Scott Gordon for taking time to review my report and giving me important feedback.

Added to that, I would like to thank the Department of Computer Science at California

State University, Sacramento for providing an opportunity to pursue my Masters Degree and guiding me all the way to become a successful student.

vii

TABLE OF CONTENTS

Page Acknowledgements………...... vii

List of figures…………………………………………………………………………….. x

Chapter

1. INTRODUCTION……………………………………………………………………... 1

1.1 Goal of the Project………………………………………………………………... 1

1.2 What is ICPC……………………………………………………………………... 1

1.3 Existing Problem…………………………………………………………………. 3

1.4 Proposed Solution………………………………………………………………… 3

2. TECHNOLOGY STACK……………………………………………………………… 5

2.1 Dropwizard……………………………………………………………………….. 5

2.2 MySQL…………………………………………………………………………… 7

2.3 AngularJS…………………………………………………………………………. 8

2.4 Bootstrap………………………………………………………………………….. 8

2.5 RAML…………………………………………………………………………….. 8

3. OVERVIEW OF SYSTEM DESIGN………………………………………………….. 9

3.1Architecture of the Application…………………………………………………… 9

3.1.1 Introducing RAML…………………………………………………………. 9 viii

3.1.2 Why RAML………………………………………………………………. .10

3.1.3 RAML VS Swagger……………………………………………………….. 11

3.2 Database Schema………………………………………………………………... 12

4. IMPLEMENTATION………………………………………………………………… 14

4.1 Implementing Database Schema………………………………………………… 14

4.2 RAML Specification and Implementation……………………………………… 17

4.3 RESTful API using Dropwizard………………………………………………… 25

4.4 AngularJS client Implementation……………………………………………….. 36

5. APPLICATION ILLUSTRATIONS…………………………………………………. 42

5.1 Register Individual……………………………………………………………… 44

5.2 Register Team…………………………………………………………………… 46

5.3 Create Division………………………………………………………………….. 49

5.4 Manage Registrations…………………………………………………………… 51

6. CONCLUSION………………………………………………………………………. 54

6.1 Lessons Learnt…………………………………………………………………... 54

6.2 Future Enhancements……………………………………………………………. 54

References……………………………………………………………………………….. 56

ix

LIST OF FIGURES

Figures Page

Figure 1 Entity - Relation Diagram...... 17

Figure 2 API Designer Editor...... 18

Figure 3 JAX-RS Implementation code...... 23

Figure 4 AngularJS code Snippet generated by RAMLAng...... 24

Figure 5 Dropwizard Project Setup...... 25

Figure 6 Maven Dependencies...... 26

Figure 7 AngularJS project structure...... 37

Figure 8 NPM command to start the server...... 38

Figure 9 LRS - API Portal...... 42

Figure 10 API Reference...... 43

Figure 11 API Notebook...... 43

Figure 12 Home Page...... 44

Figure 13 Register an Individual...... 45

Figure 14 List of Registered Individuals...... 46

Figure 15 Add Team Members...... 47

Figure 16 Register Team...... 48

Figure 17 List of Registered Teams...... 49

Figure 18 Create Division...... 50

x

Figure 19 List of Divisions...... 51

Figure 20 Make a Team...... 52

Figure 21 Add Individual to team...... 53

xi

1

1. INTRODUCTION

1.1 Goal of the Project

There are many worldwide competitions that occur every year. ICPC (International

Collegiate Programming Contest) is one such event. Students from all over the world participate in this competition. These students have to initially register for the event through ICPC official website. Local contests usually determine the eligibility of the teams to compete in the regional and eventually to the world finals contest.

The goal of the project is to develop a web application that lets the contest administrator to register the contestants as individuals and teams in the local contest. This is achieved by creating a java RESTful API that would provide services to any web application, thereby making the whole registration process computerized. In addition to it, the main objective of the project is to develop an interface (API Specification) which can generate platform independent implementation code (for the back-end) and script files (for the front-end) which can be used by the application developers.

1.2 What is ICPC

ICPC (International Collegiate Programming Contest) is a world-wide programming contest conducted among Universities annually by ACM (Association for Computing

Machinery). It is a multi-tier, team based programming competition where participants come from over 2,500 universities, across 100 countries on six continents. The competition has gained so much prominence that each year the number of teams has 2 increased exponentially by 10-20%. Headquartered at Baylor University -Texas, the competition is operated according to the rules and regulations formulated by ACM. It is the oldest, largest and the most prestigious programming contest in the world and is often considered as the “Olympics of Programming Competitions” [1]. The competition has been sponsored by IBM since 1997.

This is a three-level competition in which the first round is held in the local universities and the winners in the first round qualify to advance to the regional level competition which is the second round. The winners from the regional universities will get qualified to ACM ICPC world finals. The top-placing teams of the ICPC finals receive medals and monetary prizes.

The rules are formulated by ACM since the beginning of the competition back in 1970.

The contest is a competition between teams each consisting of three students. The teams are given 8-12 programming problems to be solved within 5 hours. Teams are allowed to select from among several programming languages provided by the contest which currently include C, C++, Java and Python. The solutions submitted by the teams are run on test data. If the submitted program fails to give a correct answer, the teams are notified and are given another chance to submit the program. Saint Petersburg State University stood first in the recent ICPC-2016. ICPC-2017 world finals is planned to be conducted in South Dakota, USA [2].

3

1.3 Existing Problem

Currently the ICPC has a web-based registration system only for the regional and world finals Contests. Registration of the contestants/teams who participate in local contests has been a manual process i.e. the event organizers take the details of the contestants on a piece of paper. The event organizer registers the individuals and teams separately.

Organizer makes teams from the contestants who are registered as individuals based on certain criteria. This manual process of registering the contestants requires a lot of time. It has also become a tedious process to archive and maintain the information of many such local contestants on paper. Moreover, this data couldn‟t be shared among other contests.

1.4 Proposed Solution

The solution for the above mentioned problem is to develop a web-based registration interface that can be used by the local event organizers to document the details of the contestants and teams. The application provides Java RESTful web services developed using a Java RESTful framework. This information has to be stored in a local database to put or retrieve the data of the contestants. The architecture of the application is built in such a way that an API design specification acts as an interface between the front-end and back-end. This API Specification can then be used to generate executable scripts and implementation code that are platform independent.

The basic features of the Registration System include the following:

● Collect the detailed information of individuals and teams

● Create teams for individuals with no team 4

● Create Divisions (distinct groupings of teams)

● Store the information in the local database

● Add/Delete teams and divisions

● Shuffle contestants between teams and Divisions (If necessary)

5

2. TECHNOLOGY STACK

2.1 DropWizard

Dropwizard [3] is a Java framework intended to develop high performance, reliable and ops-friendly RESTful web services. It is a simple, light-weight package that bundles together a few powerful, open source frameworks and libraries. This makes it easy to get started with developing RESTful web services without having to worry about configuring them together. It was developed by Yammer [4] and has the following libraries and frameworks:

● Jetty for HTTP: Every web-application requires HTTP. So, Dropwizard has

Jetty [5], a built-in embedded library that acts as both HTTP server and servlet

container. It is directly embedded into the project and gets started from the main

method. This eliminates the hassles of deploying our application into some other

stand-alone server. Instead, each deployed application is packaged as jar file

which has its own embedded Jetty container.

● Jackson for JSON: REST uses different data formats and JSON is the most

popular among them. Dropwizard uses Jackson [6] which is a very prominent

java-library, to serialize/deserialize java objects to JSON and vice-versa. It offers

a very fast and sophisticated object mapper which makes the JSON processing

very efficient. Jackson provides three models for processing JSON, namely

Streaming API [7], Tree Model [8] and Data Binding [9] which allows choosing

between several convenient and flexible options. 6

● Jersey for JAX-RS: Dropwizard uses Jersey [10] - an open source RESTful web

services framework for developing web services in Java. It is considered as the

best for JAX-RS API reference implementation and has better production quality

features than other JAX-RS API reference implementations such as RESTlet [11],

RESTEasy [12]. Jersey allows application developers to write clean and testable

classes. It has JAXB and JSON support and provides APIs that allows developers

to extend Jersey for better RESTfulimplementation.

● Liquibase: Liquibase [13] is an open source tool used to manage database

changes independently. It is a great way to keep track of the database schema

without the need of depending upon DDL scripts. Dropwizard uses Liquibase for

database migrations which make it easier for a team of developers to keep track of

the changes made in the database schema. Liquibase applies high-level database

refactorings which are defined and stored in any of the one formats among XML,

JSON, YAML [14] rather than writing SQL operations directly against the

database.

● Metrics:Metrics [15] is a library which is used to keep track of the behavior of

critical components of an application in the production environment. It is

basically used to monitor the performance of the application throughout the

development. In Dropwizard, it is embedded with other libraries which enable it

to provide an insight of the code‟s behavior like the request/response time, etc.

7

● Hibernate Validator: Dropwizard makes use of Hibernate Validator [16] which

is a reference implementation of JSR 349 [17] that enables to express and validate

user input. It allows access to constraint configuration through metadata API

which has default metadata source as annotations.

The above are few Dropwizard‟s prominent libraries. Dropwizard also has few other libraries embedded into its package such as Guava [18], Logback [19], Mustache [20],

JDBI [21], etc. Since all these libraries are pre-embedded in Dropwizard, it makes it easy for developers to accomplish a quick bootstrap of a project. Maven [22] is typically used to manage a Dropwizard configuration. The developers don‟t have to go through the pain of configuring each module of the project to get started, instead just add the dependency to the POM (Project object Model) file which is an XML representation of a Maven

Project.

2.2 MySQL

MySQL [23] is a fast, easy-to-use and popular open source relational database management system owned by Oracle Corporation. It is very customizable and works well with many programming languages like Java, PHP, C, C++, Perl, etc. and can be installed on wide variety of operating systems. MySQL follows the SQL data language standards to perform retrieve and update operations. It is available as MySQL community server in the open source edition. It comes with MySQL workbench which provides a rich UI for the database schema and also allows the user to efficiently design and manage the schemata. 8

2.3 AngularJS

AngularJS [24] is a complete Javascript based structural web application framework which is commonly used to develop dynamic web pages and single page applications. It is an open-source framework, currently maintained by Google and a community of developers. It is based on MVC (Model-View-Controller) architecture and can be embedded in HTML using script tag. The core features of AngularJS include data binding, dependency injection and reusable code components.

2.4 Bootstrap

Bootstrap [25] is a free front-end framework which is used to develop responsive websites and web applications. Bootstrap package includes HTML templates, CSS based design templates and optional javascript plugins. Bootstrap can be customized and the components can be reusable. It supports most modern web browsers including Chrome,

Safari, Opera, Firefox, Internet Explorer etc.

2.5 RAML

RAML [26] stands for RESTful API Modelling Language. It is a YAML based language which is used to describe RESTful APIs that can be easily readable by both humans and machine. It gives developers the ability to design, build, test and document an API throughout the development life cycle of the API. RAML follows the „design first‟ approach, which makes it easier to reuse the specification and test the API even before it is fully developed. It also has many tools and parsers which can generate desired code and documentation of the project based on the specification. 9

3. OVERVIEW OF SYSTEM DESIGN

3.1Architecture of the Application

In general, most web applications have a common architecture where the front-end

(client) communicates with the back-end (server) directly through an API which might be just an ad-hoc collection of services that the server provides. This is a traditional architectural approach of most of the applications for which the developers have to have an idea of what the back-end is offering. In case of APIs, the developers who developed the API usually provide the users (developers) with a detailed documentation of what services their API is providing and also how to implement it. Few API developers take a further step and provide the users with an API portal where they offer API documentation along with a console, such that the users of the API can tweak and test it. In this project, we are introducing a new architecture wherein the application developers need not have an idea of what the API is providing but still they can utilize the API and in some cases they can also improve the API.

3.1.1 Introducing RAML

As mentioned earlier, RAML is a YAML based language that is used to describe

RESTful APIs. Many companies like Google, Microsoft and Facebook provide their

APIs to public and share an API portal which gives the complete information of how to access and use their services. It is never easy to design an API for such huge companies and sometimes the companies have to discontinue providing API for the developers due to lack of proper design and maintenance of the API. To avoid such situations, we have introduced RAML into this project. 10

The main reason to introduce RAML into the architecture of the project is that it aims to provide a common platform to API designers, developers and consumers to share a common language throughout the API development process - i.e., design, construct, document, test, share and support. All these stages of API development are interdependent and are very crucial to an API‟s prolonged survival. RAML focuses on clearly describing the resources of the API, methods and parameters that can be implemented on those resources, responses, HTTP constructs and media types that form the basic structure of an API. In addition to this, a well-defined RAML specification can be used to generate robust server implementations and client coding irrespective of the language platform.

RAML can be used in many ways during the process of API development. It is more commonly used during the design and specification stage of describing the API. One can also generate API documentation based on a well-defined RAML specification. In addition to these, it is also used to explore the API by generating mock API responses defined in the specification and also to implement interactive consoles.

3.1.2 Why RAML

RAML is a machine readable language and at the same time easy to understand for humans. It can be used throughout the development of the API right from designing to support stage. Swagger [27] is the other most common format (language) for describing the API that is considered to be competitor for RAML. 11

RAML makes use of schema and traits which makes the description of the API very clear and easily understandable. Since it is based on YAML, it inherits the hierarchical characteristics of YAML which is relatively easy to code and eliminates redundancy.

While defining the specification of the API, RAML dynamically generates an interactive console which lets the developers to test the API instantly. One can define OAuth security for an API just by implementing it in a RAML specification.

3.1.3 RAML VS Swagger

Swagger is another API design specification too which is considered as a strong competitor to RAML. The latest stable versions of Swagger (2.0) and RAML (1.0) are equally good and to choose the best between these two depends upon the choice of the

API developers to determine which serves their API better. These two are intended to design a specification for RESTful APIs which can be explored by many open source tools and projects that are available on their official websites. Below are few major differences [29] between RAML (v0.8) and Swagger (v1.5) which were the stable versions when this project was started.

● RAML is comparatively easy to start with for a developer who is new to using a

language to describe an API as it provides quick and easy to documentation along

with live demos.

● Swagger uses JSON format to write the specification while RAML is based on

YAML which makes it easy for anyone to read and update the specification. This 12

feature of RAML makes it perfect for designing the API from scratch and

eliminates the hassles of separately writing/updating the documentation.

● RAML has developed a tool called “API Notebook” which generates Javascript

clients to tweak and test the API instantly.

● Swagger is based on bottom-up approach of describing the API which lacks

hierarchical pattern, making the specification look clumsy.

● The major difference between these two is that RAML follows a „design first‟

approach while Swagger is mostly used for describing the APIs that are already

developed and which need some documentation to be shared with fellow

developers.

3.2 Database Schema

The main feature of the proposed application is to register individuals and teams who want to participate in the contest based on some acceptance criteria. Considering the requirement, it is clear that the application needs two tables to separately store the details of the contestants as individuals and teams. Every individual registered as team member under team registration has his/her information in an „Individual‟ table which is bidirectionally related to „Team‟ table. In addition to these tables, a separate table to create „Divisions‟ is also used. Every individual belongs to only one team and one division. Similarly, each team has only one division while division can have any number of teams and individuals.

In Dropwizard, the relation between the tables is represented by Hibernate with JPA annotations [30]. We will discuss in detail about the relations between the tables in 13 chapter 4. As mentioned earlier, Liquibase is used in Dropwizard to manage the database.

Liquibase uses a changelog file to maintain the database changes. The changelog file can be created in XML, YAML, JSON or SQL format. The changes made to the database are stored automatically in „databasechangelog‟ table which is created when the change log file is executed. Liquibase supports multiple database types, automatically generating

SQL scripts for DBA (Database Administrator) code review and also has the ability to generate and manage rollback logic.

14

4. IMPLEMENTATION

4.1 Implementing Database Schema

Liquibase uses changelog file that comprises of tags used to group database changes. Each changeSet tag is uniquely identified by the properties „id‟ which is used as an identifier and „author‟ is the name of the person who created the changeSet. As

Liquibase executes the changelog file, it makes sure to read through every changeSet in order and checks the „databasechangelog‟ table to see if the combination of „id‟ and

„author‟ has been run. Below is a changelog file created to generate the tables required to store the contestants‟ information.

15

Ascript to create a Individuals table

A script to create a Teams table

A script to create a Divisions table

The changelog file is self-explanatory. It has XML elements (tags) to create tables, add columns and define constraints on those columns. In „Individual‟ table, team_in is a foreign key referring to primary key team_id in Team table. Similarly, division_in is a foreign key referring to primary key division_id in Division table. In Team table, division_in is a foreign key referred to primary key division_id in Division table. The above file created the tables shown in the figure [1].

17

Figure 1 Entity - Relation Diagram

The above figure depicts the columns in each table, their data types and relations between three tables used in this project.

4.2 RAML Specification and Implementation

A RAML spec is a YAML based file which describes a RESTful API. It strictly follows the YAML indentation rules to increase the readability of the API definition. To define the RAML specification, we use API Designer [31], a web editor provided by RAML. It 18 enables the user to mock the API instantly in the console whenever resources with http methods are defined in the spec.

Figure 2. API Designer Editor

Figure [2] describes a RAML specification defined in API Designer. On the right side of the figure is a console to mock the API and on the left side is a list of folders which has traits and schemas to avoid redundancy in the specification. The below snippet is a part of the RAML specification which is created to design the API for this project.

#%RAML 0.8 baseUri: http://localhost:8080/api title: ICPC-Local Registration System version: v1.0 /individuals:&individuals get: 19 description: Get a list of registered individuals responses: 200: body: application/: example: | [ { "individual_id": 19, "first_name": "Dheeru", "last_name": "raj", "email_id": "[email protected]", "education": "UnderGrad", "units_taken": 5, "preferred_division": "LowerGrad", "team_in": 33, "division_in": 10, "assigned": true }, { "individual_id": 20, "first_name": "shiva", "last_name": "melam", "email_id": "[email protected]", "education": "Masters", "units_taken": 9, "preferred_division": "Graduate", "team_in": 5, "division_in": 3, "assigned": true } ] post: description: Add a new individual body: application/json: example: | 20

{ "first_name": "Aditya", "last_name": "Kankanala", "email_id": "[email protected]", "education": "UnderGrad", "units_taken": 5, "preferred_division": "LowerGrad", "team_in": 33, "division_in": 10, "assigned": true } responses: 201: body: application/json:

/{individualid}: get: description: Get information of a specific individual put: description: Update the details of a specific individual delete: description: Remove the individual

/teams: &teams get: description: Get the list of registered teams responses: 200: body: application/json: post: description: Add a new team /{teamid}: get: description: Get the information of a specific team put: 21

description: Update the details of a team delete: description: Remove the team

/individuals: get: description: Get the details of individuals in a specific team

/divisions: get: description: Get the list of Divisions responses: 200: body: application/json: post: description: Add a new Division /{divisionid}: get: description: Get the information of a particular division put: description: Update the information of a specific division delete: description: Remove the division /teams: get: description: Get the details of team in a specific division

RAML specification starts with defining the version of RAML, a baseUri which is the address of the API, title of the API followed by version number of the API. After these, the resources and the HTTP methods are defined. One can include description, query parameters, JSON responses, examples, security schema on each of the resources.

22

RAML has wide range of projects [32] available in their official website. These projects include developing tools and parsers that can explore RAML specification to automatically generate API documentation, code templates, API consoles, etc. Based on the RAML specification for this project, we generate AngularJS script files and Java implementation code. For my project, I used a parser called „RAML for JAX-RS‟ [33] to generate JAX-RS implementation code and „RAMLang‟ [34] which is a Yoeman [35] generator, to generate AngularJS scripts.

23

Figure 3. JAX-RS Implementation code

Figure [3] is a code snippet of server side implementation code that is being generated using „RAML for JAX-RS‟ parser. It generates similar code for each resource defined in the RAML specification. It can also generate a RAML API definition based on existing

Java + JAX-RS application. 24

Figure 4.AngularJS code Snippet generated by RAMLang

The above figure is a code snippet of AngularJSRESTful services that is generated using

RAMLang. These scripts are used on the client to communicate with RESTful APIs. 25

4.3 RESTful API using Dropwizard

Dropwizard comes with an embedded pre-configuration which makes it easier for developers for a quick project bootstrap. It comes with auto generated packages to differentiate all the classes and files used in this project. Figure [5] represents the project setup in IDE for a typical Dropwizard application. Figure [6] represents the

Maven dependencies used in this project.

Figure 5.Dropwizard Project setup 26

Figure 6. Maven Dependencies 27

Maven dependencies include all the libraries that are embedded in Dropwizard framework. Before creating the classes, we add the dropwizard version property and also

„dropwizard-core‟ library as a dependency in the POM file. As we go further in creating the application we add new dependencies in the POM file. Below is the POM file for this project.

POM.xml

io.dropwizard dropwizard-bom ${dropwizard.version} pom import

io.dropwizard dropwizard-core

io.dropwizard dropwizard-hibernate

mysql mysql-connector-java 5.1.38

io.dropwizard 28

dropwizard-auth

io.dropwizard dropwizard-migrations

io.dropwizard dropwizard-assets

org.eclipse.jetty jetty-servlets

org.liquibase liquibase-maven-plugin 3.4.2

src/main/resources/migrations.xml com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/LRS shiva Password process-resources update

29

Every Dropwizard application comes with two important classes: Configuration class and

Application class. In this project, LocalRegistrationSystemApplication.java,

LocalRegistrationSystemConngfiguration.java are the two core classes present in com.pc2.LRS package. Configuration class specifies environment - specific parameters which are defined in a YAML configuration file. This file gets deserialized to an instance of the application‟s Configuration class.

The Application subclass is where the static main method() is written and it is considered the entry point of any Dropwizard application that provides basic functionality by pulling together various commands, bundles and variables.

LocalRegistrationSystemAppliation.java publicclassLocalRegistrationSystemApplicationextendsApplication { finalHibernateBundlehibernateBundle =New HibernateBundle(Individual.class,Team.class, Division.class) { @Override publicPooledDataSourceFactory getDataSourceFactory(LocalRegistrationSystemConfiguration configuration { // TODO Auto-generated method stub returnconfiguration.getDataSourceFactory(); } };

publicstaticvoidmain(finalString[] args) throwsException { newLocalRegistrationSystemApplication().run(args); }

30

@Override publicvoidinitialize(finalBootstrap bootstrap) { // TODO: application initialization bootstrap.addBundle(newMigrationsBundle() {

@Override publicPooledDataSourceFactory getDataSourceFactory(LocalRegistrationSystemConfiguration configuration) { // TODO Auto-generated method stub returnconfiguration.getDataSourceFactory(); } });

bootstrap.addBundle(hibernateBundle);

}

@Override publicvoidrun(finalLocalRegistrationSystemConfiguration configuration, finalEnvironment environment) { // TODO: implement application finalIndividualDAOindividualDAO = newIndividualDAO(hibernateBundle.getSessionFactory()); finalTeamDAOteamDAO= newTeamDAO(hibernateBundle.getSessionFactory()); finalDivisionDAOdivisionDA= newDivisionDAO(hibernateBundle.getSessionFactory());

environment.jersey().register(new Welcome()); environment.jersey().register(newIndividualResource(individualDAO)); environment.jersey().register(newTeamResource(teamDAO)); environment.jersey().register(newDivisionResource(divisionDAO)); environment.jersey().register(newAuthDynamicFeature( newBasicCredentialAuthFilter.Builder() .setAuthenticator(newUserAuth(configuration.getPassword())) .setRealm("SECURITY REALM") .buildAuthFilter() )); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(newAuthValueFactoryProvider.Binder<>(User.cl ass));

31

LocalRegistrationSystemConfiguration.java public class LocalRegistrationSystemConfiguration extends Configuration { // TODO: implement service configuration

@NotEmpty private String password;

@JsonProperty public String getPassword() { return password; }

@NotNull @Valid privateDataSourceFactorydataSourceFactory = new DataSourceFactory();

@NotNull @JsonProperty("database") @Valid publicDataSourceFactorygetDataSourceFactory() { returndataSourceFactory; } }

Config.yml

# password password: p@ssw0rd

#server settings. server: rootPath: '/api/*' applicationConnectors: - type: http port: 8080 - type: https port: 8443 keyStorePath: lrs.keystore keyStorePassword: p@ssw0rd 32 validateCerts: false

# Database settings. database:

# JDBC driver driverClass: com.mysql.jdbc.Driver

# username user: shiva

# password password: Password

# JDBC URL url: 'jdbc:mysql://localhost:3306/LRS'

Then we create the classes for actual entities of the project. Each entity has one POJO (Plain Old Java Object) [36] class, a DAO (Data Access Object) [37] class and a Resource class as shown in figure [5].

Individual.java

@Entity @Table(name="individual") @NamedQueries({ @NamedQuery(name="com.pc2.LRS.core.Individual.findAllIndividuals", query="select i from Individual i"), @NamedQuery(name="com.pc2.LRS.core.Individual.findById", query="select i from Individual i" ), @NamedQuery(name="com.pc2.LRS.core.Individual.manage", query="select i from Individual i " + "where i.team.team_id=null"), @NamedQuery(name="com.pc2.LRS.core.Individual.findForTeam", query="select i from Individual i " + "where i.team.team_id= :team"), @NamedQuery(name="com.pc2.LRS.core.Individual.remove", query="delete from Individual i " + "where i.individual_id = :individual_id") }) public class Individual {

@Id @GeneratedValue(strategy=GenerationType.IDENTITY) 33

@Column(name="individual_id", nullable=false) private long individual_id;

@Column(name="first_name") private String first_name;

@Column(name="last_name") private String last_name;

@Column(name="email_id", nullable=true) private String email_id;

@Column(name="education") private String education;

@Column(name="units_taken") privateintunits_taken;

@Column(name="preferred_division") private String preferred_division;

@Column(name = "division_in", nullable= true) private String division_in;

@Column(name="assigned") privateboolean assigned;

@ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name="team_in", referencedColumnName="team_id") @JsonBackReference private Team team;

The above code snippet is from Individual POJO class. The annotations @Entity,

@Table, @NamedQuery are Hibernate - JPA annotations which represent the table entity in the database and the queries performed on those tables. The annotations @ID,

@GeneratedValue, @Column are used to map the POJO elements to columns in the database tables.The annotations @ManyToOne, @JoinColumn, @OneToMany are used to represent the relations between the tables in database. 34

IndividualResource.java

@Path("/individuals") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class IndividualResource { privateIndividualDAOdao;

publicIndividualResource(IndividualDAOdao) { this.dao = dao;}

@GET @UnitOfWork public ListgetIndividuals(){ returndao.findall();}

@POST @UnitOfWork public Individual saveIndividual(Individual individual){ System.out.print("The recived values are "+ individual.toString()); returndao.save(individual);}

private OptionalfindIfAvailable(long indvId) { Optional result = dao.findById(indvId); if(result.isPresent()){ return result;} else { System.out.println("Indivividual not present");} returndao.findById(indvId);}

@GET @Path("/{id}") @UnitOfWork public OptionalgetIndividual(@PathParam("id") LongParamindividual_id) { returnfindIfAvailable(individual_id.get());}

@GET @Produces(MediaType.APPLICATION_JSON) @Path("/manage") @UnitOfWork 35

public ListmanageIndividuals(){ System.out.println("Manage"); System.out.println(dao.unAssigned()); returndao.unAssigned();}

@PUT @Path("/{id}") @UnitOfWork public Response update(@PathParam("id") Long individual_id, Individual individual){

Response response; String error = "{ \"message\" : \"RESOURCE NOT FOUND\"}"; Individual foundIndividual = dao.findById2(individual_id);

if(foundIndividual == null){ response= Response.status(Status.NOT_FOUND).entity(error).build(); }else{ response = Response.status(Status.OK).entity(dao.update(individual_id, individual)).build(); } return response;}

@DELETE @Path("/{id}") @UnitOfWork public Optional delete(@PathParam("id") LongParam id) { Optional individual = findIfAvailable(id.get()); if (individual.isPresent()) { dao.delete(individual.get());} return individual; } }

The terms @Path, @PRODUCES, @CONSUMES, @GET etc are JAX-RS annotations which are used to perform operations on the resources based on the requests from the clients.

36

4.4 AngularJS client Implementation

To access the REST resources created in Dropwizard, CORS (Cross-Origin Resource

Sharing) [38] has to enabled both on server side and client side. The code to enable

CORS is as follows:

//enable cors: finalFilterRegistration.Dynamiccors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); //config CORS params cors.setInitParameter("allowedOrigins", "*"); cors.setInitParameter("allowedHeaders", "*"); cors.setInitParameter("allowedMethods","OPTIONS,GET,PUT,POST,DELETE,HEAD";

//add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");

Figure [7] depicts the AngularJS project structure. The structure is based on „angular- seed‟ [39] which is a basic template for AngularJS web applications. The template comes with different Javascript files and libraries including Bootstrap, CSS, bower_components

[40], and node_modules [41]. In app.js file, the main module of the AngularJS application is defined which is the first file executed when we run the application.

For this project, we have separate folders for Individuals, Teams and Divisions which include corresponding Javascript and HTML files. Controllers are defined in .js files and the templates defined in these file are redirected to corresponding HTML file.

37

Figure 7.AngularJS project structure 38

Figure 8. NPM Command to start the server

According to angular-seed configuration, the AngularJS application runs on localhost at port number 8000. This can be seen in figure [8]. The default package manager for

Node.JS [42] is npm [43] which starts the server by the command „npm start‟ in command prompt.

39

App.js file

'use strict';

// Declare app level module which depends on views, and components varmyApp=angular.module('myApp', [ 'ngRoute', 'ngAnimate', 'ui.bootstrap', 'myApp.individuals', 'myApp.teams', 'myApp.divisions', 'myApp.version', 'myApp.lrsapi-Mainapi', 'myApp.lrsapi-teamapi', 'myApp.lrsapi-Individualapi', 'myApp.lrsapi-Divisionapi', ]); myApp.config(['$routeProvider','$httpProvider','$compileProvider', function($routeProvider,$httpProvider,$compileProvider) {

$routeProvider.when('/home', { templateUrl: 'admin/admin_home.html', }) //$httpProvider.defaults.useXDomain=true; $routeProvider.otherwise({redirectTo: '/home'}); }]);

All the dependencies and sub modules are injected in the main module of the application.

From the above code snippet, it can be noticed that the sub modules myApp.individuals, myApp.teams, myApp.divisions, etc are injected into the main module myApp.

„$routeProvider‟ declared in myApp.config controls the navigation of the application.

40

Individual.js

'use strict'; angular.module('myApp.individuals', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/individuals', { templateUrl: 'individuals/individuals_list.html', controller: 'IndividualCtrl' }) .when('/individuals/details/:id', { templateUrl: 'individuals/individual_details.html', controller: 'IndividualCtrl' }) .when('/individuals/add', { templateUrl: 'individuals/add_individual.html', controller: 'IndividualCtrl' }) .when('/individuals/edit/:id', { templateUrl: 'individuals/edit_individual.html', controller: 'IndividualCtrl' }) .when('/individuals/manage', { templateUrl: 'individuals/manage.html', controller: 'IndividualCtrl' }) }])

.controller('IndividualCtrl',['$scope','$http','$location','$routeParams','TeamApi',function( $scope, $http, $location, $routeParams, TeamApi) { console.log('IndividualCtrl loaded...');

$http.get('http://localhost:8080/api/individuals').success(function(response){ $scope.individuals = response; });

$http.get('http://localhost:8080/api/individuals/manage').success(function(response){ $scope.individuals_manage = response; });

//to select preferred division $http.get('http://localhost:8080/api/divisions').success(function(response){ $scope.divisions = response; 41

});

$scope.addIndividual = function(){ $http.post('http://localhost:8080/api/individuals', $scope.individual).success(function(response){ window.location.href='#/individuals'; }); }

$scope.getIndividual = function(){ var id = $routeParams.id; $http.get('http://localhost:8080/api/individuals/'+id).success(function(response){ $scope.individual = response; }); }

$scope.removeIndividual=function(id){ $http.delete('http://localhost:8080/api/individuals/'+id).success(function(response) { window.location.href='#/individuals'; }); }

$scope.updateIndividual = function(){ var id = $routeParams.id; $http.put('http://localhost:8080/api/individuals/'+id, $scope.individual).then(function(response){ window.location.href='#/individuals'; }); }

The above code represents the Individual sub module in the application. It has a controller „IndividualCtrl‟ in which different dependencies are injected. A routeProvider to display the views is defined in the module‟s config. Different Angular directives are included in HTML tags which determine how the html pages are rendered.

42

5. APPLICATION ILLUSTRATIONS

Figure [9] represents the „ICPC - Local Registration System‟ API portal which is available for developers. It includes an API reference, external links to know more about the ICPC and API Notebook [43]. Figure [10] represents an API reference which is an interactive console generated based on the RAML specification that allows the developers to test the API. API Notebook is another interactive tool based on the RAML specification which can generate Javascript clients that allows the developers to explore the endpoints, make requests and view the responses. This is depicted in figure [11].

Figure 9. LRS - API Portal 43

Figure 10. API Reference

Figure 11. API Notebook

44

5.1 Register Individual

The AngularJS application gets started on port number 8000 in local machine. Upon the start of the application, the first page that is rendered is a „home‟ page as shown in figure

[12]. It has the options to view the list of individuals, teams and divisions. The page also has links to register individuals and teams, create divisions and manage the registrations.

Figure 12. Home Page

45

Figure 13. Register an Individual

Figure [13] represents the registration page of an individual contestant. The event organizer enters the information of the individuals into the web page, which stores the information in „Individual‟ table. This registration is for individuals without a team. 46

Figure 14. List of Registered Individuals

The list of individuals rendered has a unique ID number for each individual as shown in figure [14]. Selecting the „Details‟ button redirects to a page where the all the details of a particular individual is displayed.

5.2 Register Team

Team registration is similar to individual registration except, the team has a name and the preferred division of all the team members is the same. Figure [15] represents the Team registration.

47

Figure 15. Add Team Members

48

Figure 16. Register Team

The admin adds the members based on the number of team members. Figure [16] represents team registration. Admin can remove the member before registering the team.

When clicked on submit, the team details are stored in „Team‟ table and the individuals are saved in „Individual‟ table. Figure [17] shows the list of registered teams with individuals. When clicked on “details” button, its shows the team details such as name, number of team members, preferred division etc.

49

Figure 17. List or Registered Teams

5.3 Create Division

The admin creates the divisions. Teams are added after the creation of divisions. While registering as individuals or teams, the contestants can choose one preferred division from the created divisions. Figure [18] shows the page for creating divisions. 50

Figure 18. Create Division 51

Figure 19. List of Divisions

Based on the „preferred division‟ and eligibility, teams are added to divisions. Figure [19] shows the list of created divisions. When clicked on „details‟ button, details such as division ID, name of the division, number of teams are shown.

5.4 Manage Registrations

When clicked on the „manage‟ link on the home page, it redirects to a page which has the list of individuals without a team. Event organizer (admin) adds these individuals into existing teams based on their preferred division or creates a new team for them. Once all the individuals are assigned to a team, the admin adds the teams into divisions. Figure 52

[20] shows the list of individuals without a team and a button to create a team and add those individuals to that team.

Figure 20. Make a Team

When clicked on „Make a Team‟ button, a pop up window appears as shown in figure

[21]. It has a list of individuals without a team under the „unassigned‟ column and a list of individuals that are added to team on the „assigned‟ column. The admin gets to choose which individual to add while creating a new team. 53

Figure 21. Add Individual to team

54

6. CONCLUSION

6.1 Lessons Learnt

During the course of developing this project, I have learnt many conceptual aspects of application development. I got the opportunity to learn the principles of a good API and also developed a RESTful API from scratch. Getting to know about RAML helped me understand the importance of API development life cycle. Developing both frontend and backend helped me understand in detail the concepts of client-server communication. I came across many new technologies while developing the REST API. To start with, I got familiar with Dropwizard Java RESTful framework which is a bundle of powerful libraries such as Jackson, Jersey, Hibernate etc. On the frontend side, I also had the opportunity to learn about a few web technologies such as AngularJS, Twitter Bootstrap,

HTML5. On the database side, I learnt about Liquibase and MySQL which made me understand the concepts of Relational databases.

6.2 Future Enhancements

● Currently, the developed REST API has Basic Authentication provided by

Dropwizard. The API can be made more secure by implementing OAuth security

framework.

● RAML has released version 2.0 which noticeably has improved features than its

previous version (0.8). A new RAML Specification can be created using the latest

version which allows exploring more about RAML and its projects. 55

● On the front-end, UI can be made more user friendly and thereby improve the

user experience.

● There are different RAML parsers available that can generate server

implementation code in languages other than java such as .NET, Node.JS, GO,

Scala etc to develop REST APIs

56

REFERENCES

[1] CodecChef. About ACM ICPC. [Online].

Available: https://www.codechef.com/icpc. Accessed in August 2016

[2] Wikipedia. ACM ICPC 2004-2007 Finals. [Online]. Available:

https://en.wikipedia.org/wiki/ACM_International_Collegiate_Programming_Contest.

Accessed in August 2016

[3] Dropwizard. Getting started with Dropwizard. [Online]. Available:

http://www.dropwizard.io/0.9.2/docs/getting-started.html. Accessed in September 2016

[4] Yammer. Yammer Home page. [Online]

Available: https://www.yammer.com/.Accessed in September 2016

[5] Eclipse. About Eclipse Jetty. [Online].

Available: http://www.eclipse.org/jetty/about.html. Accessed in August 2016

[6] FasterXML. Jackson Json Processor Wiki. [Online].

Available: http://wiki.fasterxml.com/JacksonHome. Accessed in October 2016

[7] Json Three Ways. Streaming API. [Online].

Available: http://wiki.fasterxml.com/JacksonStreamingApi. Accessed in October 2016

[8] Json Three Ways. Tree model. [Online].

Available: http://wiki.fasterxml.com/JacksonTreeModel. Accessed in October 2016

[9] Json Three Ways. Data Binding. [Online].

Available: http://wiki.fasterxml.com/JacksonDataBinding. Accessed in October 2016

[10] Jersey – RESTfulWebservices in Java. [Online].

Available: https://jersey.java.net.Accessed in July 2016 57

[11] RESTlet. The Fastest and Easiest Way to build APIs. [Online].

Availabe: https://restlet.com/. Accessed in August 2016

[12] JBoss. RESTEasy. [Online]. Available: http://resteasy.jboss.org/.

Accessed in September 2016

[13] Liquibase. Source Control for your database. [Online].

Available: http://www.liquibase.org/. Accessed in July 2016

[14] YAML. YAML Ain‟t Markup Language. [Online].

Available: http://www.yaml.org/. Accessed in September 2016

[15] Dropwizard. Metrics. [Online]. Available: http://metrics.dropwizard.io/3.1.0/.

Accessed in August 2016

[16] Hibernate. Hibernate Validator. [Online].Available: http://hibernate.org/validator/.

Accessed in june 2016

[17] Java Community Process. Java Specification Request 349. [Online]. Available:

https://jcp.org/en/jsr/detail?id=349. Accessed in August 2016

[18] Github. Guava‟s user guide. [Online].

Available: https://github.com/google/guava/wiki. Accessed in October 2016

[19] Logback. Fast and Reliable Logging Framework. [Online].

Available: http://logback.qos.ch/. Accessed in October 2016

[20] Mustache. Logic less Templates. [Online]. Available: http://mustache.github.io/.

Accessed in August 2016

[21] JDBI. Introduction to JDBI. [Online]. Available: http://www.jdbi.org/.

Accessed inJuly 2016 58

[22] Welcome to . Apache Maven project. [Online].

Avaliable: https://maven.apache.org/. Accessed in July 2016

[23] Oracle. MySQL. [Online]. Available: http://www.mysql.com/.

Accessed in August2016

[24] AngularJS. What is Angular. [Online].

Available: https://docs.angularjs.org/guide/introduction. Accessed in July 2016

[25] Bootstrap. [Online]. Available: http://getbootstrap.com/. Accessed in August 2016

[26] RAML. About RAML. [Online]. Available: http://raml.org/. Accessed in July 2016

[27] Swagger. Getting Started. [Online]. Available: http://swagger.io/.

Accessed in August 2016

[28] API Blueprint. API Blueprint Documentation. [Online].

Available: https://apiblueprint.org/. Accessed in August 2016

[29] RAML vs Swagger vs API Blueprint. [Online]. Available:

http://www.mikestowe.com/blog/2014/07/raml-vs-swagger-vs-api-blueprint.php.

Accessed in September 2016

[30] Hibernate . JPA Annotations. [Online].

Available: http://www.techferry.com/articles/hibernate-jpa-annotations.html.

Accessed in August 2016

[31] Mulesoft‟s API Designer. [Online]. Available:

https://github.com/mulesoft/api-designer. Accessed in August 2016

[32] RAML. RAML projects. [Online]. Available: http://raml.org/projects/projects.

Accessed in August 2016

[33] Mulesoft. RAML for JAX-RS. [Online]. 59

Available: https://github.com/mulesoft/raml-for-jax-rs. Accessed in August 2016

[34] NPM. RAMLAng Generator. [Online].

Available: https://www.npmjs.com/package/generator-ramlang.

Accessed in October2016

[35] Yoeman. Getting Started with Yeoman. [Online]. Available: http://yeoman.io/.

Accessed in October 2016

[36] Wikipedia. Plain Old Java Object. [Online]. Available:

https://en.wikipedia.org/wiki/Plain_Old_Java_Object. Accessed in July 2016

[37] Oralce. Data Access Object. [Online].

Avaliable:http://www.oracle.com/technetwork/java/dataaccessobject-138824.html.

Accessed in September 2016

[38] Wikiperdia. Cross Origin Resource Sharing. [Online]. Available:

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing.

Accessed in August 2016

[39] Github. Angular-Seed. [Online]. Available: https://github.com/angular/angular-seed.

Accessed in September 2016

[40] Bower. Bower Components. [Online].Available: https://bower.io/.

Accessed in September 2016

[41] NodeJS. Node Modules. [Online].

Available: https://nodejs.org/docs/v0.4.1/api/modules.html.

Accessed in September 2016

[42] NodeJS. [Online]. Available: https://nodejs.org/en/. Accessed in August 2016

60

[43] Wikipedia. Node Package Manager. [Online].

Available: https://en.wikipedia.org/wiki/Npm_(software). Accessed in August 2016