Play-Framework-Cookbook.Pdf

Total Page:16

File Type:pdf, Size:1020Kb

Play-Framework-Cookbook.Pdf Play Framework Cookbook Over 60 incredibly effective recipes to take you under the hood and leverage advanced concepts of the Play framework Alexander Reelsen BIRMINGHAM - MUMBAI Play Framework Cookbook Copyright © 2011 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: July 2011 Production Reference: 2290711 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-849515-52-8 www.packtpub.com Cover Image by Fillippo ([email protected]) Credits Author Project Coordinator Alexander Reelsen Joel Goveya Reviewers Proofreader Erik Bakker Aaron Nash Guillaume Bort Steve Chaloner Indexer Hemangini Bari Pascal Voitot Tejal Daruwale Acquisition Editor Eleanor Duffy Graphics Nilesh Mohite Development Editor Roger D’souza Production Coordinator Aparna Bhagat Technical Editor Kavita Iyer Cover Work Aparna Bhagat Copy Editor Neha Shetty Foreword Why Play is a small revolution in the Java world Looking at the past years of application development, as a developer you might have noticed a significant shift from desktop applications to web applications. The Web has evolved as the major platform for applications and is going to take over many facets—not only in development but also in everyday life, resulting in this shift accelerating. Who would have thought 10 years ago that current mobile phones are indeed only very strong ironed notebooks with a permanent Internet connection? The Internet provides a very direct connection between consumer and producer. For application developers this implies a very easy -to- use- and- handle platform. Looking around, many application frameworks have evolved in recent years in order to be very Internet-centric. These frameworks interpret the Web as an ubiquitous platform for providing not only ordinary web pages, as it was done 10 years ago. The web has become a data provider on top of one of the most proven protocols in industry, the HyperText Transfer Protocol (HTTP). The core concepts of the Internet being a decentralized highly available network with HTTP as a protocol on top of it are the inner core of a big part of today’s applications. Furthermore, another development took place in the last years. The browser became more and more a replacement of the operating system. Fully fledged web applications like Google Docs, which act and look like desktop applications, are becoming more popular. JavaScript engines like Google V8 or SpiderMonkey are getting insanely fast to deliver web browser performance not thought of several years ago. This means current web applications are now capable of delivering a real user experience similar to applications locally installed on your system. So many software engineers today are also web engineers as well. This poses a very big problem. As most of software engineering is based on abstraction, many tools, frameworks, and languages try to hide complexity from the engineer, which sounds good at first. No web engineer cares about the fragmentation of the IP packets which are sent throughout the whole world in milliseconds. By abstracting and layering your software to reduce the complexity per layer, you inadvertently might hide features of the underlying protocol your software is built upon. Many frameworks try to resemble the style of programming desktop applications, with the exception of application being in the Web. However, in order to make use of HTTP and its features you cannot easily hide them away in your application framework. This is especially a problem in the Java world. The defined standard is the servlet spec, which defines how web applications have to be accessible in a standard way. This implies the use of classes like HttpServletRequest, HttpServletResponse, HttpServlet, or HttpSession on which most of the available web frameworks are built upon. The servlet specification defines the abstraction of the HTTP protocol into Java applications. Though it is quite a good spec as HTTP carries quite some complexity around, it forces frameworks to obey certain conventions which never got challenged in the past. While many web frameworks like Django, Rails, or Symfony do not carry the burden of having to implement a big specification and do not need to fit into a big standardized ecosystem, most Java web frameworks have never questioned this. There are countless excellent web frameworks out there which implement the servlet specification, Grails, Tapestry, Google Web Toolkit, Spring Web MVC, and Wicket to name a few. However, there always was one gap: having a framework which allows quick deployment like Django or rails while still being completely Java based. This is what the Play framework finally delivers. This feature set does not sound too impressive, but it is. Being Java based implies two things: f Using the JVM and its ecosystem: This implies access to countless libraries, proven threading, and high performance. f Developer reusability: There are many Java developers who actually like this language. You can count me in as well. Have you ever tried to convince Java developers to use JavaScript as a backend language? Or PHP? Though Groovy and Scala are very nice languages, you do not want your developers to learn a new framework and a new language for your next project. And I do not talk about the hassle of IDE support for dynamic languages. Shortening development cycles is also an economic issue. As software engineers are quite expensive you do not want to pay them to wait for another “compile-deploy-restart” cycle. The Play framework solves this problem. All of the new generation web frameworks (Django in Python, Rails on Ruby, expressjs on top of nodejs in JavaScript) impose their own style of architecture, where HTTP is a first class citizen. In Java, HTTP is only another protocol that a Java application has to run on. So the Play framework is a pure Java-based solution, which brings a real HTTP focused framework with lots of helpers to speed up development resulting in shorter iterations and faster deployments. This book should help you to get the most out of the Play framework and to be as fast as any other developer on any platform when creating web applications. Prerequisites I made several assumptions about the persons reading this book. One of the first assumptions is that you already have used Play a little bit. This does not mean that you have deployed a 20 node cluster and are running a shop on top of it. It means that you downloaded the framework, took a brief look at the documentation, and ran through a few of the examples. While reading the documentation you will also take a first look at the source, which is surprisingly short. I will try to repeat introductory stuff only when it is necessary and I will try to keep new things as short as possible, as this is a cookbook and should come with handy solutions in more complex situations. What is missing: A Scala chapter No book is perfect. Neither is this. Many people would be eager to read a chapter about integration of Play and Scala. When I started writing this book, my Scala knowledge was far from competitive (and still is in many areas). Furthermore I currently do not think about using Scala in a production web application together with Play. This will change with growing maturity of the integration of these two technologies. Alexander Reelsen About the Author Alexander Reelsen is a software engineer living in Munich, Germany, where he has been working on different software systems, for example, a touristic booking engine, a campaign management and messaging platform, and a b2b ecommerce portal. He has been using the Play framework since 2009 and was immediately astonished by the sheer simplicity of this framework, while still being pure Java. His other interests includes scaling shared-nothing web architectures and NoSQL databases. Being a system engineer most of the time, when he started playing around with Linux at the age of 14, Alexander got to know software engineering during studies and decided that web applications are more interesting than system administration. If not hacking in front of his notebook, he enjoys playing a good game of basketball or streetball. Sometimes he even tweets at http://twitter.com/spinscale and can be reached anytime at [email protected]. If I do not thank my girlfriend for letting me spend more time with the laptop than with her while writing this book, I fear unknown consequences. So, thanks Christine! Uncountable appreciation goes out to my parents for letting me spent days and (possibly not knowing) nights in front of the PC, and to my brother Stefan, who introduced me into the world of IT - which worked pretty well until now. Thanks for the inspiration, fun, and fellowship to all my current and former colleagues, mainly of course to the developers. They always open up views and opinions to make developing enjoyable. Many thanks go out to the Play framework developers and especially Guillaume, but also to the other core developers.
Recommended publications
  • Hibernate ORM Query Simplication Using Hibernate
    2016 3rd National Foundation for Science and Technology Development Conference on Information and Computer Science Hibernate ORM Query Simplication Using Hibernate Criteria Extension (HCE) Kisman Sani M. Isa Master of Information Technology Master in Computer Science Bina Nusantara University Bina Nusantara University Jl. Kebon Jeruk Raya No. 27, Jakarta Barat, DKI Jl. Kebon Jeruk Raya No. 27, Jakarta Barat, DKI Jakarta, Indonesia 11530 Jakarta, Indonesia 11530 [email protected] [email protected] Abstract— Software development time is a critical issue interfaced by a query. The software engineer will make in software development process, hibernate has been the query specified to database used. Each database widely used to increase development speed. It is used in vendor has their Structured Query Language (SQL). As database manipulation layer. This research develops a the development of software technology and most of library to simplify hibernate criteria. The library that is programming languages are object oriented, some called as Hibernate Criteria Extension (HCE) provides API functions to simplify code and easily to be used. Query engineer or software institutions try to simplify the associations can be defined by using dot. The library will query process. They try to bind object in application to automatically detect the join association(s) based on database. This approach is called as Object Relational mapping in entity class. It can also be used in restriction Mapping (ORM). ORM is a translation mechanism from and order. HCE is a hibernate wrapper library. The object to relational data, vice versa. ORM has “dialect” configuration is based on hibernate configuration.
    [Show full text]
  • 2019 Stateof the Software Supply Chain
    2019 State of the Software Supply Chain The 5th annual report on global open source software development presented by in partnership with supported by Table of Contents Introduction................................................................................. 3 CHAPTER 4: Exemplary Dev Teams .................................26 4.1 The Enterprise Continues to Accelerate ...........................27 Infographic .................................................................................. 4 4.2 Analysis of 12,000 Large Enterprises ................................27 CHAPTER 1: Global Supply of Open Source .................5 4.3 Component Releases Make Up 85% of a Modern Application......................................... 28 1.1 Supply of Open Source is Massive ...........................................6 4.4 Characteristics of Exemplary 1.2 Supply of Open Source is Expanding Rapidly ..................7 Development Teams ................................................................... 29 1.3 Suppliers, Components and Releases ..................................7 4.5 Rewards for Exemplary Development Teams ..............34 CHAPTER 2: Global Demand for Open Source ..........8 CHAPTER 5: The Changing Landscape .......................35 2.1 Accelerating Demand for 5.1 Deming Emphasizes Building Quality In ...........................36 Open Source Libraries .....................................................................9 5.2 Tracing Vulnerable Component Release 2.2 Automated Pipelines and Downloads Across Software Supply Chains
    [Show full text]
  • Processwire-Järjestelmän Perusteet Kehittäjille
    PROCESSWIRE-JÄRJESTELMÄN PERUSTEET KEHITTÄJILLE Teppo Koivula Opinnäytetyö Joulukuu 2015 Tietojärjestelmäosaamisen koulutusohjelma, YAMK TIIVISTELMÄ Tampereen ammattikorkeakoulu Tietojärjestelmäosaamisen koulutusohjelma, YAMK KOIVULA, TEPPO: ProcessWire-järjestelmän perusteet kehittäjille Opinnäytetyö 120 sivua, joista liitteitä 96 sivua Joulukuu 2015 Tämän opinnäytetyön tavoitteena oli tuottaa monipuolinen, helppokäyttöinen ja ennen kaikkea suomenkielinen perehdytysmateriaali sivustojen, sovellusten ja muiden web- ympäristössä toimivien ratkaisujen toteuttamiseen hyödyntäen sisällönhallintajärjestel- mää ja sisällönhallintakehystä nimeltä ProcessWire. ProcessWire on avoimen lähdekoodin alusta, jonka suunniteltu käyttöympäristö on PHP-kielen, MySQL-tietokannan sekä Apache-web-palvelimen muodostama palve- linympäristö. Koska järjestelmä sisältää piirteitä sekä sisällönhallintajärjestelmistä että sisällönhallintakehyksistä, se on käytännössä osoittautunut erittäin joustavaksi ratkai- suksi monenlaisiin web-pohjaisiin projekteihin. Opinnäytteen varsinaisena lopputuotteena syntyi opas, jonka tavoitteena on sekä teo- riapohjan että käytännön ohjeistuksen välittäminen perustuen todellisiin projekteihin ja niiden tiimoilta esiin nousseisiin havaintoihin. Paitsi perehdytysmateriaalina järjestel- mään tutustuville uusille käyttäjille, oppaan on jatkossa tarkoitus toimia myös koke- neempien käyttäjien apuvälineenä. Opinnäytetyöraportin ensimmäinen luku perehdyttää lukijan verkkopalvelujen teknisiin alustaratkaisuihin pääpiirteissään, minkä jälkeen
    [Show full text]
  • Programming Technologies for the Development of Web-Based Platform for Digital Psychological Tools
    (IJACSA) International Journal of Advanced Computer Science and Applications, Vol. 9, No. 8, 2018 Programming Technologies for the Development of Web-Based Platform for Digital Psychological Tools Evgeny Nikulchev1, Dmitry Ilin2 Pavel Kolyasnikov3 Ilya Zakharov5, Sergey Malykh6 4 MIREA – Russian Technological Vladimir Belov Psychological Institute of Russian University & Russian Academy Russian Academy Science Academy of Education Science, Moscow, Russia Moscow, Russia Moscow, Russia Abstract—The choice of the tools and programming In addition, large accumulated data sets can become the technologies for information systems creation is relevant. For basis for machine learning mechanisms and other approaches every projected system, it is necessary to define a number of using artificial intelligence. Accumulation of data from criteria for development environment, used libraries and population studies into a single system can allow a technologies. The paper describes the choice of technological breakthrough in the development of systems for automated solutions using the example of the developed web-based platform intellectual analysis of behavior data. of the Russian Academy of Education. This platform is used to provide information support for the activities of psychologists in The issue of selecting methodological tools for online and their research (including population and longitudinal offline research includes several items. researches). There are following system features: large scale and significant amount of developing time that needs implementation First, any selection presupposes the existence of generally and ensuring the guaranteed computing reliability of a wide well-defined criteria, on the basis of which a decision can be range of digital tools used in psychological research; ensuring made to include or not to include techniques in the final functioning in different environments when conducting mass toolkit.
    [Show full text]
  • Play Framework One Web Framework to Rule Them All
    Play Framework One Web Framework to rule them all Felix Müller Agenda Yet another web framework? Introduction for Java devs Demo Summary Yet another web framework? Yet another web framework? Why do we need another web framework? Existing solutions: Servlets, Ruby on Rails, Grails, Django, node.js Yet another web framework? Threaded Evented 1 thread per 1 thread per cpu request core threads may block threads shall never during request block processing Yet another web framework? Threaded Evented Servlets Node.js Ruby on Rails Play Framework Grails Django Yet another web framework? Play is completely asynchronous horizontally scalable out of the box and a lot other goodies... Introduction for Java devs Play Framework MVC pattern Scala and Java API asset compiler for CoffeeScript and LESS + Google Closure Compiler + require.js Play Console play new <appName> play compile|test|run|debug play ~compile|test|run Application structure app directory contains source code, templates and assets standard packages based on MVC: app/controllers app/models app/views Application structure public directory is default for assets as css and javascript files public/stylesheets public/javascripts public/images served directly by web server Routes configuration contains url to controller mapping statically typed pattern: <HTTP method> <url> <controller> Controllers import play.mvc.*; public class Application extends Controller { public static Result index() { return ok("It works!"); } } Templates built-in Scala based template engine
    [Show full text]
  • Applicazioni Web in Groovy E Java
    Università degli Studi di Padova Applicazioni web in Groovy e Java Laurea Magistrale Laureando: Davide Costa Relatore: Prof. Giorgio Clemente Dipartimento di Ingegneria dell’Informazione Anno Accademico 2011-2012 Indice INTRODUZIONE ........................................................................................... 1 1 GROOVY ............................................................................................... 5 1.1 Introduzione a Groovy ................................................................................. 5 1.2 Groovy Ver 1.8 (stable).............................................................................. 10 1.3 Installare Groovy ........................................................................................ 14 1.3.1 Installazione da codice sorgente......................................................... 15 1.4 L’interprete Groovy e groovyConsole ....................................................... 16 1.5 Esempi ........................................................................................................ 17 2 NETBEANS .......................................................................................... 20 2.1 Introduzione a Netbeans ............................................................................. 20 2.2 Installare Netbeans 7.1 ............................................................................... 22 2.3 “Hello World!” in Netbeans ....................................................................... 23 3 ARCHITETTURA MVC .......................................................................
    [Show full text]
  • Spring Framework Cookbook I
    Spring Framework Cookbook i Spring Framework Cookbook Spring Framework Cookbook ii Contents 1 Spring Framework Best Practices 1 1.1 Define singleton beans with names same as their class or interface names.....................1 1.2 Place Spring bean configuration files under a folder instead of root folder.....................1 1.3 Give common prefixes or suffixes to Spring bean configuration files........................2 1.4 Avoid using import elements within Spring XML configuration files as much as possible.............2 1.5 Stay away from auto wiring in XML based bean configurations...........................2 1.6 Always externalize bean property values with property placeholders........................3 1.7 Select default version-less XSD when importing namespace definitions.......................3 1.8 Always place classpath prefix in resource paths...................................4 1.9 Create a setter method even though you use field level auto wiring.........................4 1.10 Create a separate service layer even though service methods barely delegate their responsibilities to correspond- ing DAO methods...................................................4 1.11 Use stereotype annotations as much as possible when employing annotation driven bean configuration......5 1.12 Group handler methods according to related scenarios in different Controller beans................6 1.13 Place annotations over concrete classes and their methods instead of their interfaces................6 1.14 Prefer throwing runtime exceptions instead of checked exceptions
    [Show full text]
  • Anembeddedquerylanguage in Scala
    Master Thesis An Embedded Query Language in Scala Amir Shaikhha Professor Martin Odersky Supervisors Vojin Jovanovic, Eugene Burmako Expert Stefan Zeiger, Typesafe Semester Spring 2013 An Embedded Query Language in Scala, p. 1 Abstract In this thesis we address the problem of integrating general purpose programming languages with relational databases. An approach to solving this problem is using raw strings to represent SQL statements. This approach leads to run-time errors and security vulnerabilities like SQL injection. The second approach is integrating the query in a host language. The most well-known example of the second approach is LINQ. This approach provides static checking of types and syntax during compilation. This thesis presents an embedded query language in Scala, namely Shadow Embedding in Slick. Shadow Embedding provides even stronger compile-time guarantees than LINQ and similar sys- tems in Scala. The experimental results show that the performance of our approach is very similar to the case of using raw Strings, thanks to static code analysis and clever code caching. An Embedded Query Language in Scala, p. 2 Acknowledgement First, I would like to thank Prof. Martin Odersky for giving me the opportunity to do my master thesis in Typesafe and LAMP. Vojin Jovanovic helped me tremendously during the whole period of my thesis. Thank you to Stefan Zeiger for believing in me and providing me with the opportunity to work on the Slick project. I would like to thank Eugene Burmako for all his support, Christopher Vogt for the great discussions, and everybody at Typesafe and the LAMP team. I can never thank my parents enough for believing in me and supporting me through all periods of my life.
    [Show full text]
  • Play Framework Documentation
    Play framework documentation Welcome to the play framework documentation. This documentation is intended for the 1.1 release and may significantly differs from previous versions of the framework. Check the version 1.1 release notes. The 1.1 branch is in active development. Getting started Your first steps with Play and your first 5 minutes of fun. 1. Play framework overview 2. Watch the screencast 3. Five cool things you can do with Play 4. Usability - details matter as much as features 5. Frequently Asked Questions 6. Installation guide 7. Your first application - the 'Hello World' tutorial 8. Set up your preferred IDE 9. Sample applications 10. Live coding script - to practice, and impress your colleagues with Tutorial - Play guide, a real world app step-by-step Learn Play by coding 'Yet Another Blog Engine', from start to finish. Each chapter will be a chance to learn one more cool Play feature. 1. Starting up the project 2. A first iteration of the data model 3. Building the first screen 4. The comments page 5. Setting up a Captcha 6. Add tagging support 7. A basic admin area using CRUD 8. Adding authentication 9. Creating a custom editor area 10. Completing the application tests 11. Preparing for production 12. Internationalisation and localisation The essential documentation Generated with playframework pdf module. Page 1/264 Everything you need to know about Play. 1. Main concepts i. The MVC application model ii. A request life cycle iii. Application layout & organization iv. Development lifecycle 2. HTTP routing i. The routes file syntax ii. Routes priority iii.
    [Show full text]
  • Appendix a the Ten Commandments for Websites
    Appendix A The Ten Commandments for Websites Welcome to the appendixes! At this stage in your learning, you should have all the basic skills you require to build a high-quality website with insightful consideration given to aspects such as accessibility, search engine optimization, usability, and all the other concepts that web designers and developers think about on a daily basis. Hopefully with all the different elements covered in this book, you now have a solid understanding as to what goes into building a website (much more than code!). The main thing you should take from this book is that you don’t need to be an expert at everything but ensuring that you take the time to notice what’s out there and deciding what will best help your site are among the most important elements of the process. As you leave this book and go on to updating your website over time and perhaps learning new skills, always remember to be brave, take risks (through trial and error), and never feel that things are getting too hard. If you choose to learn skills that were only briefly mentioned in this book, like scripting, or to get involved in using content management systems and web software, go at a pace that you feel comfortable with. With that in mind, let’s go over the 10 most important messages I would personally recommend. After that, I’ll give you some useful resources like important websites for people learning to create for the Internet and handy software. Advice is something many professional designers and developers give out in spades after learning some harsh lessons from what their own bitter experiences.
    [Show full text]
  • Java Web Frameworks Which One to Choose?
    Java Web Frameworks Which One to Choose? Mohamadou Nassourou Department of Computer Philology & Modern German Literature University of Würzburg Am Hubland D - 97074 Würzburg [email protected] Abstract This article discusses web frameworks that are available to a software developer in Java language. It introduces MVC paradigm and some frameworks that implement it. The article presents an overview of Struts, Spring MVC, JSF Frameworks, as well as guidelines for selecting one of them as development environment. 1. Introduction Over the last decade, the number of Java Web Frameworks has considerably increased. There are basically two types of Java Web Frameworks: component oriented frameworks and action based ones. Action frameworks are mainly focussing on request/response processing. Action frameworks are very procedural with little reusability of code/components. Component frameworks focus on object oriented web design. They do not concentrate on request/response processing. There exist several actions frameworks among them Struts and Spring MVC that I am going to present. I will introduce Java Server Faces (JSF) which is a component framework. All the frameworks that will be presented follow Model-View-Controller design pattern. 2. Model-View-Controller (MVC) Model-View-Controller design pattern helps developers to better organise their program's code. In fact it provides a way of separating user interface i.e View from the business logic i.e Model. A Controller is responsible for invoking appropriate pages according to user's request. It determines also what business logic to call for a given request. Practically JSP pages represent the view and servlets the controller.
    [Show full text]
  • The Drupal Decision
    The Drupal Decision Stephen Sanzo | Director of Marketing and Business Development | Isovera [email protected] www.isovera.com Agenda 6 Open Source 6 The Big Three 6 Why Drupal? 6 Overview 6 Features 6 Examples 6 Under the Hood 6 Questions (non-technical, please) Open Source Software “Let the code be available to all!” 6 Software that is available in source code form for which the source code and certain other rights normally reserved for copyright holders are provided under a software license that permits users to study, change, and improve the software. 6 Adoption of open-source software models has resulted in savings of about $60 billion per year to consumers. http://en.wikipedia.org/wiki/Open-source_software www.isovera.com Open Source Software However… Open source doesn't just mean access to the source code. The distribution terms of open-source software must comply criteria established by the Open Source Initiative. http://www.opensource.org/docs/osd www.isovera.com Open Source Software Free as in… Not this… www.isovera.com Open Source CMS Advantages for Open Source CMS 6 No licensing fees - allows you to obtain enterprise quality software at little to no cost 6 Vendor flexibility - you can choose whether or not you want to hire a vendor to help you customize, implement, and support it, or do this internally. If at any point along the way you decide you don’t like your vendor, you are free to find another. 6 Software flexibility – in many cases, proprietary software is slow to react to the markets needs.
    [Show full text]