Practical Play Framework - Alberto Souza - E-Book

Practical Play Framework E-Book

Alberto Souza

0,0

Beschreibung

Developing web systems in Java has never been so fun! If you are tired of writing long Servlets, waste a lot of time fighting with the framework just to perform simple tasks and writing more code than is necessary to develop any functionality, the Play Framework is what you need. In this book, Alberto Souza will teach you how to create an application from the beginning to the end using the Play Framework in the Java version. Through common situations of daily life, ranging from the traditional registration, up to more advanced features like HTTPS authentication, REST services and creation of plugins.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 182

Veröffentlichungsjahr: 2014

Das E-Book (TTS) können Sie hören im Abo „Legimi Premium” in Legimi-Apps auf:

Android
iOS
Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Sumário

Capítulo 1: Introduction

1.1 Following or not the specification

1.2 No pause for class reloading

1.3 Designed to be scalable

1.4 The adventure begins

Capítulo 2: First Application

2.1 Creating the first project

2.2 Running for the first time

2.3 Conclusion

Capítulo 3: Setting up the application

3.1 Creating the project and importing it to eclipse

3.2 A bit about folder structure

3.3 Conclusion

Capítulo 4: Beginning the conference registration

4.1 Understanding a little more about Controllers

4.2 Accessing the page

4.3 Conclusion

Capítulo 5: Dealing with requests

5.1 Receiving the form parameters

5.2 Conclusion

Capítulo 6: Saving and listing the conferences

6.1 Saving with Ebean

6.2 Setting up Ebean

6.3 Creating the tables with the Evolutions

6.4 Listing the conferences and the Redirect

6.5 Conclusion

Capítulo 7: Converting and Validating Data

7.1 A little problem with the Evolution of Ebean

7.2 Problem in converting

7.3 Building your formatter

7.4 Validating the basic data

7.5 Html helpers to facilitate building the forms

7.6 Changing the validation messages

7.7 Creating a reusable validation

7.8 Specific model validation

7.9 Conclusion

Capítulo 8: Uploading the conference image

8.1 Dealing with upload at the Controller

8.2 Integrating the upload with saving the conference

8.3 Conclusion

Capítulo 9: Sending emails asynchronously

9.1 Approving the conference

9.2 Composing URLs with parameters

9.3 Sending email

9.4 Problems when running synchronous code

9.5 Native support for asynchronous execution

9.6 Conclusion

Capítulo 10: Caching the action results

10.1 Beginning with cache at Play

10.2 Invalidating the cache programmatically

10.3 Take care with the type of cache you want

10.4 Conclusion

Capítulo 11: Protecting the system

11.1 Performing login

11.2 Restricting access

11.3 Composing actions to avoid code duplication

11.4 Play Authentication Plugin

11.5 Conclusion

Capítulo 12: Serving different formats

12.1 Which format to use?

12.2 Problem generated by @Cached

12.3 Conclusion

Capítulo 13: Automated Testing

13.1 Integration Testing in DAOs

13.2 The problem of clearing the database between tests

13.3 Integration tests for controllers

13.4 Acceptance tests

13.5 Conclusion

Capítulo 14: Layout and reusing views

14.1 Organizing static resources

14.2 Creating the system template

14.3 Improving readability with includes

14.4 A little more Scala for views

14.5 Conclusion

Capítulo 15: Internationalizing the application

15.1 Externalizing strings

15.2 Changing the language programmatically

15.3 Beware the Cache

15.4 Conclusion

Capítulo 16: Deploying the application

16.1 Running in production mode

16.2 Setting up the production server

16.3 Scaling out

16.4 Stateless helping on scalability

16.5 Https

16.6 Deploy in cloud

16.7 Conclusion

16.8 See you

Capítulo 17: Reusing functionalities by means of plugins

17.1 Using and implementing the plugin

17.2 Details on implementing a plugin

17.3 Publishing

17.4 Conclusion

Capítulo 18: Taking care of the database evolution

18.1 Evolutions in Play

18.2 Common problems

18.3 Other tools

18.4 Conclusion

Capítulo 19: Time to practice

19.1 Keep in touch

19.2 Consultancy and events

Go to Code Crushing and see our other e-books - www.codecrushing.com.

Capítulo 1: Introduction

There are several MVC frameworks for developing WEB applications, and perhaps you may be asking yourself why should you learn a new one. The main motivation is to try to use a tool that will make you worry with nothing more than your business rules.

“Play” already comes with many infrastructure decisions taken on by you. For example:

A server that will be used to publish the applicationFramework for object-relational mappingNative support for setting up environments, such as test, homolog, and productionUtility classes for making integration and acceptance tests easier to be writtenCompiled viewsTasks ready to package and distribute the applicationPlugin to monitor the database evolution and keep track of the creation of your chartsHighly performatic and scalable because of its asynchronous nature.

Note that all of this infrastructure alone is useless; the project development team spends several hours assembling such infrastructure project after project. With this part entirely ready, the developers may be mostly concerned with just writing business rules related to the application, which will probably be much more profitable for the company.

1.1 Following or not the specification

In order to provide much more than competitors, Play had to make a bold architectural decision. The specifications governing the development of Java web applications were not designed to provide the features offered by the framework. In order to avoid workarounds, Play decided not to follow the specifications of JavaEE. At first it may seem that you lose much, as it is now strongly coupled to it, but stop and think for a second. How often do you keep switching the implementation? How many times has a project in which you were participating had to change the JPA implementation? Or implementation of the JAX-WS specification? The one that handles the creation and use of Web services.

Based on that, the Play team decided not to give much importance to the specification. Going the other way, they managed to create a framework that offers you several technologies for the different layers of your application and with everything already integrated. These types of frameworks are known in the market as Full Stack and have been proving to be more productive than those of competitors. Examples already well-established are Rails, written in Ruby, and Django, written in Phyton.

1.2 No pause for class reloading

Another bad characteristic of web application development in Java is the famous mandatory reload that the application has to suffer when a class is changed. Think about how many times you have been waiting for Tomcat’s hot deploy after any change. And think about when you were with a logged-in user and the same was lost after the change. This is a recurring problem that makes developers lose precious minutes to inactivity. Therefore, many developers develop in debug mode all the time to try to minimize this waiting time. However, what about when a configuration file is changed, for example, some .properties or the persistence.xml of your application using JPA? There is no way for these examples; you have to wait for the redeploy until changes are shown.

As everything in Play is integrated, this problem has also been solved. Any file that you change in your application is automatically reloaded by Play, much like what happens during development using scripting languages like Ruby and Php. Programmers coming from .NET platform are also used to it due to the high level of integration between the platform frameworks and the IDE for development.

1.3 Designed to be scalable

One last point I want to discuss in order to convince you to devour this book as if your project depended on it is the power of scalability of Play. Even today, the most common solution to scale an application is to add more servers and then balance the load between them. This is a solution that will eventually have to be taken, but what you mostly want is to delay an increase in design complexity due to this decision. If your application is installed on several different servers, how will it handle data of the session user? This is just one example of added complexity.

Seeking to improve this aspect, Play uses a server called Netty, which was built already prepared for dealing with requests completely asynchronously. And it goes further, since it is of no use for your server to have this support if its APIs do not have the same principle. The core of Play is based on the Scala language, which runs over the JVM and has a strong concern with concurrence and parallelism. Moreover, the Akka project was implemented, which is the main project of the Java world nowadays when speaking about these characteristics. Therefore, everything within the framework happens in a non-blocking way, which greatly increases the scalability of just one instance of your application.

And if you still need to scale the application horizontally, including more servers, Play turns this into a trivial task. It was designed not to maintain any state, being stateless. Without a state, there is no reason to worry about in which server the request will fall. Your load balancing will be used at full capacity.

1.4 The adventure begins

If the above arguments have sharpened your curiosity, start reading the book now! In the next chapter you will already have a "Hello World" built in a matter of minutes. And enjoy,! If you realize you already have all of this, just go back to LeanPub and ask for a refund; you have a time period of up to 45 days for doing so.

Capítulo 2: First Application

To begin, let's create our first application with Play! Stay tuned, because in a moment you are going to have a Hello World to show your colleagues. The first thing we need to do, as with any framework, is to download Play by accessing the project website, whose address is http://www.playframework.org/, and clicking on the download link. The download of Play, as well as Java JDK, go far beyond the classes that will help us in writing the project. A set of tools will be downloaded that will help us create the project, start and stop the server, package the project, and utilize other features.

2.1 Creating the first project

After the download, choose the most suitable location for extracting the zip file. In order to facilitate our communication, from now on the chosen path for the extraction will be called $pathToPlay. Now let's create our first application; in a typical way, we can call it helloworld. Simply open a terminal, go to your project folder, and type the following:

1 sh **$pathToPlay**/activator new helloworld

Don’t forget to replace the $pathToPlay by your installation directory. When the line above is run, a Play message will be displayed to you with some options to be used as a template for your project, something like that:

Fig. 2.1

Choose the option number 3. This template will make activator to create a project with the minimum necessary.

Just choose option 2, and a folder with the project name will be created. In a simple and practical way, we have created a new project. Inside the project folder, you can see that Play has created a specific structure for us. Try holding your curiosity; I know it is difficult, but it is not interesting to go on dissecting folders without having a real need. The important thing now is to mount the server and see our first application running.

2.2 Running for the first time

Again, we need to access the installation path of Play. By the way, typing this path all the time tends to get really annoying; therefore, let´s add it to the path of our system to make it simpler. On Unix systems, this process is as simple as running the following command:

Version 2.3 forward, everything that is needed to run your project, is in the the folder created by Activator. Now, in order to access the console, from the folder of the project, just type this command:

1 ./activator

If you are doing this for the first time, you will need to wait. All dependencies should be downloaded before you can start the project. Remember, wait for whole process until the end. After this phase, the Play's console will be opened in your terminal.

The Play console will be opened on the terminal, similar to the following:

Fig. 2.2

Now let’s enter the run command and the Play server will start. Notice that the server runs, by default, in the 9000 port. Access the URL http://localhost:9000 and that’s it! Our first application is already working. Part of the page that will be displayed is like the one below:

Fig. 2.3

Press Ctrl+D and then enter to stop the server and, to leave the console, type exit.

Exporting the sdk path

Every time we need to create a new project, we have to type the path to the activator download folder, $pathToPlay/activator. To avoid that, we can export this to path of your system. In Unix systems this process is as simple as execute the command bellow:

1 export PATH=$PATH:$caminhosdkplay

We can't forget to let the file $pathToPlay/activator executable:

1 chmod a+x $caminhosdkplay/activator

In the earlier versions, this same executable used to be called play instead of activator.

2.3 Conclusion

In this chapter we built our first application draft, hopefully without many difficulties. In the next chapters we will start building a real application, and—really, don’t go to sleep yet—there are many emotions coming in the next scenes!

Capítulo 3: Setting up the application

Now that we tried a first example and are more familiar with the flow of project creation, let us begin to build the application we are going to use during the book. Our project will be based on Agendatech, an application written using the Rails framework, which attempts to map events that are to take place in Brazil. The interesting thing about being based on Agendatech is that we already have a known domain where you can see all the potential that Play has to offer.

To give you a taste, we bring you the features that we plan to implement as you read the book. Remember, for every problem that comes, we will use a Play facility to help us solve it. Below is the list:

Registration of events that are to occurRegistration of events categoriesEvents listingUpload of the event logo in different formatsEvent approvalEmail of approvalImproved performance and scalability of the applicationEvents compatible with an external application, i.e., a mobileLogin through Facebook and Twitter

The index page of our project may be similar to this:

Fig. 3.3

3.1 Creating the project and importing it to eclipse

The first step is to create a project, and for this we will use the sdk we downloaded. As we already moved the sdk to the path of our operating system, just choose the folder you like and run the following command line on the _terminal_:

1 play new agendatech

Now we have the project structure created. A detail that has not been discussed so far is the IDE we are going to use for the development. For ease, we will choose Eclipse. This step may sometimes hinder our flow. Who never spent a lot of time trying to fix the classpath, or who never got hung up because one of the IDE setup files did not come together with the project? To help on this part, Play brings with it a task for importing the project to Eclipse. The first step is to access the folder where the project has been created. Now, at the command line, run the following instruction:

1 play

This is going to open the command console of Play. If you want to take a look at everything that is available, just enter the following:

1 help play

A list of the available commands will be presented. Below is an example:

Fig. 3.1

Eclipse is precisely one of the commands which allow us to create the entire structure needed to import the project to Eclipse. Without wasting much time, go on and import the application. Just enter the command in the console, as shown below:

1 eclipse

Now just import the project into your Eclipse. After importing it, the structure of your project should be like this one, as follows:

Fig. 3.2

To check if everything is right, enter the command run in the terminal to launch the application. If everything is OK, the standard Play welcome screen should be displayed. Let’s now stop the server, and for that just press _ctrl + d_.

3.2 A bit about folder structure

The more curious reader should have noticed that inside the project and target folders are files in Scalalanguage. Do not worry; the Play2 core is written in Scala, but we will be dealing only with Java in almost every development.

Another interesting point is the package structure that Play has generated for us. As previously discussed, instead of spending time on how to separate this kind of thing, the framework has already generated a source folder, called app, with the following packages:

controllersviews

Do not be concerned with them right now. In the next chapter, we will begin to develop the first application functionalities, and of course, they will be around!

3.3 Conclusion

In this chapter, the idea of the project that we are going to develop throughout the book has been presented. We will use Agendatech because it has several features that are common in different projects. And that's what we should worry about, business rules! The framework will be in charge of the infrastructure details.

Capítulo 4: Beginning the conference registration

Now that the Project has been created, it is time to begin the implementation of the functionalities. The first thing to be done is the registration screen for new events, so we begin to use the structure provided by Play. The screen is very simple, just an HTML.

1 <html> 2 <body> 3 <formaction="/conferences"method="POST"> 4 <inputtype="text"id="name"name="nome"value=""> 5 <inputtype="text"id="contactEmail" 6 name="contactEmail"value=""> 7 <textareaid="description"name="description"> 8 </textarea> 9 <inputtype="text"id="site"name="site"value="">10 <inputtype="submit"value="New conference">11 </form>12 </body>13 </html>

For the moment, our view is no big deal, just a simple HTML. A file called new_conference.scala.html will be created and placed in the app/views/conferences package. And now we can learn about some details of Play. The first one is the scala word in the file name. Play uses this language to enable the writing of dynamic pages. Think of it as another view technology that you have studied. Let's just remember some:

JSP. Widely used in conjunction with Java frameworks in the market.Velocity. Once it was a powerful alternative to JSPs.Freemarker. Also widely used due to its template mechanisms.ERB. Used in the Ruby world, especially with the Rails framework.

The use of the Scala language is for the view of Play just like the _Expression Language_ is for JSPs. It has some very interesting points, which will be discovered as long as its functionalities are developed. Another point to notice is that the page should be created inside the views/conferences package. The views package is what Play uses as a standard to store pages. All pages created in it get a special treatment of the framework. One that is going to be used is the fact that the page is transformed into a class that can be accessed from everywhere. Inside the views, you are free to create the structure you want. Throughout this book, the Play standards will be respected, and the reason is that we do not want to waste time on infrastructure!

The highlight of having a view that is compiled is that it is not necessary to wait for the page to run to discover an error. If you want to check if everything that is being developed is being compiled, access the terminal in your computer, go to your project’s folder, and enter the command play.

After the Play console has opened, enter ∼run. The run command, as already seen, starts the server, and the ~ before it is for Play to keep recompiling any alterations and to keep applying them to the project. This way, any possible error is promptly shown at the terminal. In Play, everything is compiled, not just the Java classes.

4.1 Understanding a little more about Controllers

The first thought might be that to access this page you should write the name of the file in the browser, and that’s it. Remember, your page may contain logics such as:

* conference listing * messages of success and error presented * values recovered to be displayed in the form fields

If the access were direct, all this logic would probably be placed into the view, which would result in serious maintenance problems. We would be mixing many responsibilities and writing Java code in an inappropriate place. Because of that, Play prohibits direct access to any view. The idea is that you always go through a class that can retrieve some objects that are necessary for the page, and this class takes the decision on which view will be called. These classes are called Controllers. Note that the name itself indicates that it controls the flow of execution of your web application. The controllers created in the application, following the standards, will be placed in the controllers package. As the views package, we will keep on the standards so as not to waste time configuring unnecessary details.

1 importplay.mvc.*;2 publicclassConferencesControllerextendsController{3 4 publicstaticResultform(){5 returnnull;6 }7 }

There is an interesting detail in relation to the imports that will be used throughout the book. As Play supports the development in Scala or Java, they had to make a division in imports. Be aware that any import with the api package is from the Scala world. The use of Scala classes in its Java code should always be done with much analysis. The package used for the Java world is play.mvc.

Just inherit from Controller and your class will have earned several methods ready to handle the web requests. We have taken the opportunity to add a method whose purpose is to direct the user to the new events page.

The return of the new method is an object type _Result_. This is the class that represents its Response on a project using Play. Through it, we can return a different status and the type of content that will be returned to the user in our application. If we wanted to return only 200, indicating that all worked out, we would have the following code:

1 importplay.mvc.*;2 publicclassConferencesControllerextendsController{3 4 public