Play Frameworkで開発したWebアプリケーションを、Linuxのサービスとして実行するシェルスクリプト。

seen from Malaysia

seen from Bangladesh
seen from United States

seen from Türkiye
seen from United Kingdom

seen from Germany
seen from China
seen from United Kingdom
seen from China

seen from India

seen from United Kingdom
seen from China
seen from Germany

seen from United States
seen from China
seen from Germany
seen from United Kingdom
seen from Brazil

seen from United Kingdom
seen from United States
Play Frameworkで開発したWebアプリケーションを、Linuxのサービスとして実行するシェルスクリプト。
Test Javascripts and Coffeescripts in playframework
We would like to test our Javascripts and Coffeescripts within Play. There’s the sbt plugin, sbt-jasmine-plugin. It uses the Jasmine framework.
There are 2 problems with sbt-jasmine-plugin:
1. The test cannot be written in Coffeescripts 2. It uses Mozilla's rhino and env-js. And env-js is not maintained anymore. Plus, env-js emulates a browser environment, which can be problematic. It's better to use PhantomJS.
We have built sbt-web-test-js to overcome the above problems.
sbt-web-test-js performs the below steps:
1. Utilises sbt-coffeescript for compiling Coffeescripts files to Javascripts files 2. Generates the Jasmine HTML file 3. Execute the HTML page with PhantomJS. 4. Parse the result from the HTML page
If you would like to test Javascripts/Coffeescripts in Play, please try sbt-web-test-js
Exclude directories from assets pipeline
Note: here's our Stackoverflow's answer on the problem
So, it is not simple to exclude certain files or directories from the assets pipeline. I have no friggin' idea why it is the case.
First, we need sbt-filter. It provides a filter as a pipeline stage. Then, we can put a FileFilter that only exclude the unwanted files/directories. The code looks like this:
includeFilter in filter := new FileFilter { def accept(pathname: File): Boolean = { pathname.getAbsolutePath.contains("public/uploads/") } } pipelineStages := Seq(filter, digest, gzip)
There is one notable thing.
We cannot exclude directories with the example provided in sbt-filter because a tring is implicitly converted to one of the NameFilter's subclasses, and they only look at file/directory name. Therefore, you can only exclude by name, and this also works:
includeFilter in filter := "uploads"
But if you have multiple directories named "uploads" and want to exclude only one of them, then it won't work anymore.
Blazzzing fast transactional emails using Play Framework 2.3, MandrillApp & ZURB in 1 day
MandrillApp has created a transactional email service and it is so amazing! Pair that with Play Framework and ZURB and you'll be unstoppable!
Last weekend I started using it for my side project Itemize to send notifications when shared items changed, were restored, were deleted, etc. Most ESPs I’ve worked with in the past have been very bulky so I was dreading working on this at all. BUT, Mandrill was quite a nice surprise. I layered it in using a Scala trait by providing my Play controller a sendMessage api. I created a trait called EmailService
Hold on hold on! Let’s take a step back and talk about Mandrill for a second… They offer a transactional email service free of charge for up to 12K emails/month with an hourly quota, which makes it ideal for small projects. Integrating them in a side project is super easy since their API is fully RESTful and the documentation is beautiful. Once you create an account you can setup a couple of API keys for different environments. I created one for prod and dev environments each. Emails sent from the dev environment are not actually sent out, though their sandbox tool allows you to view the content as it would be sent. As you can see in the snippet above, I just put this key in the Play config and imported it and the API url into my service layer. That’s it! Mandrill ready-to-use…
Creating Templates using Twirl
Originally, I wanted to have the sendMessage method accept a typed template instead of a String. Twirl templates are of type BaseScalaTemplate[...] with TemplateX[...]. The ‘X’ signifies the number of parameters the template accepts (and being a case class it maxes out at 22). The idea was to generic-ify the signature of sendMessage (a work-in-progress) to maintain type-safety yet keeping things flexible, but I wasn’t able to do that easily. In the mean time, it made sense to keep EmailService simple stupid and have it accept the rendered template as a String.
As with most software, the key to moving fast with email templates is to use a framework that provides well tested responsive templates. Thankfully this is where Zurb’s Email Templates came into the picture. Zurb offers 5 template types (I just picked the Basic template and customized it a little) along with tons of resources to make your templates work on different email clients. This saved me a whole lot of time and effort. Thanks Zurb team!!!!
Just to elaborate, since I’m using Play templates, I easily separated out the Zurb template markup and styling into different files (email_layout.scala.html & email_styling.scala.html), with the former importing the latter since email template styling has to be inline. In addition, creating different emails was super easy since I just pass in a HTML content variable into the layout @()(content: Html) ... for each email.
Play WS Client
After configuring Mandrill and setting up the EmailMessage api plus the template I leveraged Play’s WS API to make API calls.
The first step was to use the Play WS client to setup a method that would send json (note: the communication format was set to json using the .json at the end of the url and the Content-Type header) requests to Mandrill endpoints. Next, I hooked in my sendMessage method.
Notice that I use EmailPacket, EmailMessage, EmailRecipient and SendResponse case-classes to handle sending and receiving data from Mandrill. Along with the classes, I wrote Play’s Writes[T] to convert each of them to json using Play’s Json library. One thing to note here is that I didn’t account for failure responses from Mandrill, but those could be baked in a very similar fashion as above and I leave that up to you.
Parting Thoughts
It’s been such a pleasure to work on this using the tri-fecta of Mandrill, Play and ZURB. I was so excited because these tools make it so much easier to build features that were much more tedious to build even 5 years ago. In fact, I built all this in 1 day! I hope you are able to leverage some (if not all) of these tools to build your next email service quickly too!
Que debo de usar para mi aplicación web
Hola amigos, casi no he tenido tiempo para poder escribir algo en mi blog, por lo que mejor es ir soltando pequeñas cosas que voy encontrando.
Lenguajes dinámicos o estático?
Tengo un tiempo con querer crear una aplicación personal web, pero tenia que elegir las tecnologías, fue todo un tema, especialmente para la parte de frontend. Yo eh trabajado con php, python, java y ahora scala.
Por el lado de php no le eh dado más vuelta, aunque me parece genial el poder usar alguna aplicación ya echa de las muchas de hay echas en php, no es un lenguaje que elegiría para comenzar una aplicación de cero. Python es un lenguaje que me encanta y existe buenos frameworks, pero por esta vez prefiero optar por un lenguaje que tenga mejor performance, por lo que opte por ver lenguajes con JIT.
Frameworks
Comencé a ver frameworks agiles, pues aunque trabajo a diario con java y spring, spring no es un framework que se destaque por ser un framework agil, no como RubyOnRails, DJango, pylons, etc, a pesar que ahora esta tratando de cambiar su imagen.
Entonces comencé a buscar alguno que se adapte a mi, ya que vengo del mundo python, y ver como RubyOnRails se ha echo su fama, busque algo similar, y felizmente lo encontré y se llama Play Framework, es un framework, que corre en la JVM, tiene api, para java, para scala, no es el clásico JEE, en cambio usa como base el servidor Netty, los cambios son inmediatos, sin tener que redeployar, y muchas cosas más.
El Lenguaje, Java o Scala
Ya elegido el framework y debido a que soporta nativamente tanto java como scala, tengo la opción de elegir para mi desarrollo cual seria mi lenguaje por defecto, tengo un tiempo desarrollando pequeñas herramientas para mi trabajo diario, y cosas en mi casa, por otro lado vengo trabajando con java como lenguaje oficial en mi trabajo, por lo que se cuales son la ventajas de cada lenguaje, esto esta muy claro para mi, Scala sería mi lenguaje por defecto.
Frontend
Aunque al principio estaba claro que usaría las herramientas que brinda Play Framework, mirando a futuro, decidí investigar diferentes opciones, teniendo claro que usaría en el backend, scala+playframework, aunque me encantaría usar scala.js como lenguaje para el frontend, y mantener una sola linea, siendo realista, este proyecto es realmente nuevo, por lo que me di una vuelta por internet y me encontre con diferentes opciones, el mismo coffescript que trae play, y aunque me parece un avance sobre javascript, no es lo suficientemente extendido, o con soporte, si lo probé, me di unos encontronazos usandolo, pero no me termino de convencer, por lo que retorne a javascript, investigando me encontré que web con alto trafico como linkedin, usan javascript y llevando las plantillas que normalmente las tenemos en el lado del backend como jsp, templates de python, o cosas por el estilo, lo pasan a html+javascript, y existen varias opciones.
Una opción que esta dando bastante que hablar es AngularJs, un framework para javascript, pero aunque es una mejora aún persistía el problema del lenguaje, javascript no escala, claro desde mi punto de visto, y lo digo por el lado de desarrollo, darle mantenibilidad, crecer o refactorizar es toda una odisea, sin importar si usas jquery, sencha, angular, etc. así que decidí seguir buscando y me encontré con angular.dart, realmente interesante, de los mismos creadores de GWT, donde GWT es toda una plataforma, compilador, lenguaje, frameworks para UI, etc. claro no prospero por el lenguaje, java es muy cuadriculado para estos menesteres.
Pensé que encontré la solución, pero aunque Angular.js seguía avanzando no lo hacia de la misma forma su contraparte en dart, no leía noticias nuevas, lo cual nunca es un buen sigo, así que me puse a buscar de nuevo porque pasaba esto, y me encuentro que aunque angular también se encubó dentro de google, google decidió evolucionar junto con html5 y nació Polymer, un framework para componentes web, el cual anda muy bien de salud, y para mi es el futuro, el detalle de nuevo era que originalmente es javascript, pero, y aquí viene el gol, existe Polymer para Dart, y se integran muy bien.
Porque Dart + Polymer?
Ni que hablar de Polymer, me parece que es la decisión acertada, es el futuro, usar webcomponentes es muy muy sencillo, polymer nos ayudar a crearlos.
Por otro lado esta Dart, el lenguaje, bueno esto puede ser cuestionable, google quiere imponer este lenguaje, integrarlo con la vm de su browser al igual que lo hace con javascript, pero esto es todo un tema, pues aunque al tener la capacidad de tener variables tanto de tipo dinámico como de tipo estático, tiene mejor performance, el problema es que también tendría que convencer a firefox y todos los demás navegadores, de implementar. Por lo que actualmente también compila a javascript, algo similar a GWT, pues es un lenguaje, tiene su propio ide, y herramientas al rededor de dart, claro todo no es completamente color de rosa, cosa que comentare en otro post, sus ventajas son muchos más que las cosas que pueden ser desfavorables, es la mejor solución que encontré hasta ahora.
Conclusión
Dividir la aplicación en dos partes, una backend, y otra frontend, donde el backend solo son webservices, así si en algún momento necesito cambiar la implementación no pegue contra toda la ui ya construida, el tiempo de renderizado ya no es asumido por el servidor, por lo que el servidor puede atender más clientes, todo esto solo por mencionar algunas ventajas, y para no cansar más pues este post resulto siendo más largo de que lo pensaba, las cosas quedan así, Play Framework con Scala para el backend, y Polymer (web components) + Dart, para el frontend.
Play Framework 업그레이드 적용하기
이번에 Play Framework 2.2.2 가 릴리즈되어, 기존 프로젝트를 업그레이드하였는데, 절차는 다음과 같다.
project/plugins.sbt 버전 변경
play clean-all
play compile
play update
play run
위와 같이 해주면, 특별한 오류 없이 업그레이드 적용이 잘 될 것이다.
A great opportunity for technology and startup enthusiasts. #java #webtechnologies #mvc #playframework #delhiNCR #tapandeat #startup
Play 2: POST リクエストを扱う
conf/routes で POST をうけつけるアクションを指定する。
GET /hello controllers.Hello.index POST /hello/create controllers.Hello.create
Content-Type が「application/x-www-form-urlencoded」の場合、asFormUrlEncoded メソッドを使う。
package controllers import play.api._ import play.api.mvc._ object Hello extends Controller { def index = Action { Ok("Hello World") } def create = Action { request => val values = request.body.asFormUrlEncoded Ok(values.get("foo")(0)) } }
httpie を使って POST リクエストを送信してみよう。
http -v -f POST localhost:3000/hello/create foo=bar
次は JSON を扱えるようにしてみよう。
package controllers import play.api._ import play.api.mvc._ import play.api.libs.json._ import play.api.libs.functional.syntax._ object Hello extends Controller { implicit val rds = ( (__ \ 'name).read[String] and (__ \ 'age).read[Long] ) tupled def index = Action { Ok("Hello World") } def create = Action(parse.json) { request => request.body.validate[(String, Long)].map{ case (name, age) => Ok("Hello " + name + ", you're "+age) }.recoverTotal{ e => BadRequest("Detected error:"+ JsError.toFlatJson(e)) } } }
httpie で試してみよう。
http -v localhost:3000/create name=Toto age:=32