Archive for the ‘Sin categoría’ Category

FactoryPal: New Scala framework for creating objects as test data. Say no to Fixtures and Mocks.

by @mgonto, original article can be found here

Hey everyone! First of all, if you want to read the original article please go to this link

FactoryPal is a scala framework that lets you create objects as test data. All you have to do is define the templates for each of the classes that you want FactoryPal to create objects from. After that, FactoryPal takes care of the rest.

Have you ever heard of factory_girl a super cool Ruby framework? Well, FactoryPal is factory_girl for Scala. It is pretty similar in its use. The difference is that FactoryPal is 100% type safe, which all of us Scala people love.

Here is a link to Github for the anxious https://github.com/mgonto/factory_pal

How do we use this?

FactoryPal is a singleton object where you can register all of the templates. For example, you can define a template as follows:

FactoryPal.register[Person] { person =>
    person.name.mapsTo("gonto") and
    person.age.isRandom
}

In this example, we register a new template for class model. If we try to set a value for a property that Person doesn’t has, your project won’t compile. If you try to set a value to a property that isn’t the type of that property, the project won’t compile either. Pretty cool huh? This was possible thanks to Scala Macros and Dynamic, two features added in the latest Scala 2.10 RC release.

For the time being, there are 3 supported operations on a field template.

  • mapsTo: This sets a certain specific value to that property.
  • isRandom: This sets a random value based on the type of the field. I’ve created some implicit randomizers for common objects (String, Long, Int, Double, etc.) but you can create your own. This is pretty similar to Ordering[T] used in List.
  • isAnotherFactoryModel: You tell FactoryPal that this is an inner object that can be constructed with another template of FactoryPal. For the time being, there can only be one template for each class. I’m going to change this very soon.

After we created the template, we can instantiate objects of that template as follows:

val person = FactoryPal.create[Person]

The create method has another overload that lets you add some field overriders for certain test. For example you can do the following:

val person = FactoryPal.create[Person] { (person : ObjectBuilder[Person]) =>
    person.age.mapsTo(45) alone
}

And that’s it. That’s all you need to know to use this.

How can I add this to my project?

This is an example configuration for Build.scala for your SBT project :). There’re only snapshots for now as Scala 2.10 is not yet final. Once it’s, I’m going to make a release.

import sbt._
import sbt.Keys._
 
object ApplicationBuild extends Build {
 
  lazy val root = Project(
    id = "factory_pal_sample",
    base = file("."),
    settings = Project.defaultSettings ++ Seq(
      name := "factory_pal_sample",
      organization := "ar.com.gonto",
      version := "0.1",
      scalaVersion := "2.10.0-RC3",
      scalacOptions += "",
      licenses      := ("Apache2", new java.net.URL("http://www.apache.org/licenses/LICENSE-2.0.txt")) :: Nil,
      libraryDependencies ++= Seq(
       "org.scala-lang" % "scala-compiler" % "2.10.0-RC3",
       "ar.com.gonto" % "factory_pal_2.10" % "0.1-SNAPSHOT",
       "org.scalatest" % "scalatest_2.10.0-RC3" % "1.8-B1" % "test"
      ),
      resolvers ++= Seq(
         "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
         Resolver.url("Factory Pal Repository", 
          url("http://mgonto.github.com/snapshots/"))(Resolver.ivyStylePatterns)
      )
    )
  )
}

Take a look at the dependency and the repository!

What does it use internally?

Internally, this framework uses Scala Macros, Dynamic and the new Reflection library provided by Scala 2.10.

Next Steps

The next things I want to do are:

  • Add the posibility to have multiple templates for one Class
  • Add template inheritance
  • Add helpers to use this with ScalaTest and Specs2. For the moment, you can create the templates in the before.

For more information or to take a look at the code go to Github

¡Lanzamiento de Play 2.0!

Traducido del blog de Typesafe

¡Presentando Play 2.0!

En noviembre del año pasado anunciábamos que Play, el framework de alta productividad para Java y Scala, pasaría a formar parte del stack de Typesafe. Hoy, apenas unos meses más tarde, nos complace poder anunciar que Play 2.0 ya está disponible como parte del Stack Open Source de Typesafe en su versión 2.0, junto con el soporte comercial de la subscripción de Typesafe.

Veamos algunas de sus principales características.

Soporte nativo para Java y Scala

Mientras que la versión original de Play Framework estaba escrita principalmente en Java, ofreciendo soporte para scala a través de plug-in, Play 2.0 adopta Scala de una manera más decidida. No sólo el núcleo central de Play ha sido migrado a Scala, sino que esta nueva versión brinda un soporte de primer nivel para el desarrollo de aplicaciones web con Scala. De manera tal que la nueva versión del framework provee dos API totalmente completas: una para desarrolladores de Scala y otra para desarrolladores Java.

Un controlador hecho con Java

El mismo controlador usando Scala

Desarrollo rápido de aplicaciones

Una de las características que hacían a la “experiencia de usuario” del desarrollador Play de la serie 1.x, era la consola de desarrollo y el reporte de errores en el propio explorador web. Play 2.0 mejora estas prestaciones al permitirle al desarrollador ejecutar porciones de código, pruebas o scripts de la línea de comando interactuando directamente con el runtime de la aplicación, y también compilando muchas de las partes típicas de una aplicación web.

Interactuando con los modelos de una aplicación Play 2.0 desde la consola

Llevando la seguridad de tipos a un nuevo nivel

Una de las ventajas de utilizar un lenguaje estáticamente tipado para escribir aplicaciones de Play, es que el compilador podía verificar partes del código por usted, Es por ello que Play 2.0 utiliza por defecto un lenguaje de templates basado en Scala, incluso para aquéllos desarrolladores que usen Java como su principal lenguaje de programación. Esto no signifca que usted deba convertirse en un experto en Scala para escribir templates en Play 2.0. Pero ahí está Scala, sin que usted lo note, trabajando en su beneficio.

Play 2.0 lleva las verificaciones en tiempo de compilación y el chequeo de tipos todavía más a fondo. Las rutas (que definen los URLs y el mapeo con las acciones), los templates, e incluso los recursos de la aplicación web son compilados (utilizando LESS, CoffeScript y el compilador de Google Clousure), poniendo a su disposición un entorno de desarrollo unificado tanto para los desarrolladores del lado del cliente como para los del lado del servidor. El resultado de todo esto es que más errores serán detectados en tiempo de compilación, acelerando el proceso de desarrollo de aplicaciones web. También hará muchísimo más simple trabajar en proyectos grandes que involucren numerosos desarrolladores.

Example route compilation failure detection

Jugando limpio

Play 1.x implementaba muchas de sus originales ideas (como la implementación automática de propiedades para Java y la recarga dinámica de sus clases) utilizando técnicas que requerían un runtime específico para Play. En cambio, Play 2.0 adopta un enfoque mucho más estándar para el despliegue del runtime. Esto fue posible escribiendo parte del framework en scala, y también aprovechando prestaciones de SBT, la popular herramienta de Scala para la construcción y despliegue de aplicaciones.

Play 2.0 mantiene la misma experiencia de los usuarios de la versión 1.x acostumbrados a ejecutar “play new, run start”, al mismo tiempo que parte de una base más fácil de extender. Play 2.0 ya trae configurado un script de compilación que funcionará sin modificaciones en la mayoría de los casos, pero si usted necesita personalizar la manera en que su aplicación es construida y desplegada, tendrá las herramientas a su alcance para adapatarla a sus necesidades. Como resultado de todo esto, hallará que será mucho más simple desplegar sus aplicaciones de Play 2.0 en los escenarios más variados.

Elija tan sólo las partes que va a usar

Dado que el diseño de aplicaciones web ha evolucionado en gran medida en los últimos años, Play 2.0 está construido siguiendo un criterio modular que le dará gran flexibilidad a la hora de elegir la tecnología a usar. ¿No desea usar una base de datos? Puede simplemente deshabilitar el plugin DB. ¿Quiere usar su propio motor de templates? Simplemente agrégue el plugin. ¿No necesita un framework web con todos los chiches? Use play como una simple librería. Usted decide qué tanto de la arquitectura de Play quiere usar en sus aplicaciones.

Deshabilitando plugins en el archivo conf/application.conf

Escale su apliación con Akka

Play está basado en una arquitectura liviana, sin estado, pensada para la web, que le asegura un consumo de recursos mínimo y predecible (en términos de CPU, memoria, threads) para desarrollar aplicaciones que requieren alta escalabidad. Esto es posible en parte gracias a Akka 2.0, el middleware basado en eventos que se encuentra en el corazón de Play 2.0. Los desarrolladores tienen acceso a toda la funcionalidad provista por Akka para construir aplicaciones altamente distribuidas que puedan ser escaladas para cumplir con los más altos niveles de demanda.

En este ejemplo puede ver como el resultado de un actor encargado de realizar un cálculo complejo, puede ser mapeado a un resultado de Play de una manera no-bloqueante

En este ejemplo puede ver como el actor ChatRoom envía un mensaje en porciones al cliente utilizando Comet

Manejo avanzado de entrada/salida y de Streams

Una de las más recientes tendencias en el desarrollo de aplicaciones web es el énfasis puesto en tecnologías de tipo push y no-bloqueantes. Play 2.0 utiliza una implementación de entrada/salida basada en Iteratee, que provee soporte para tecnologías avanzadas de push y streaming, partiendo desde WebSockets y Comet hasta streaming de archivos.

Un controlador de scala que utiliza el soporte para WebSockets de Play 2.0

Listos… preparados… a jugar con Play!

Play 2.0 es el resultado de una intensa colaboración entre Typesafe (liderados por Peter Hausel), el fundador del proyecto Guillaume Bort, la comunidad Play y Zenexity, la consultora orientada a la web donde Play fue creado. Ha sido una experiencia divertida y excitante trabajar junto con un grupo tan talentoso de desarrolladores.

Estamos sumamente complacidos de que Play hoy sea parte del Stack de Typesafe, junto con Scala, Akka y el soporte comercial, mantenimiento y herramientas de despliegue y administración (como la nueva consola de Typesafe) que juntas conforman el paquete de Subscripción de Typesafe. Typesafe también ofrece cursos de capacitación y consultoría para la nueva versión 2.0, para que su equipo pueda cuanto antes comenzar a desarrollar aplicaciones con Play 2.0.

Estamos convencido de que el lanzamiento de Play 2.0 marcará un antes y un después en las comunidades de Java y Scala, poniendo al alcance de los desarrolladores una experiencia novedosa que posibilitará inéditos niveles de escalabilidad y productividad.

Para que pueda empezar ya mismo con Play 2.0, hemos provisto varias aplicaciones de ejemplo con esta nueva versión. Así que lo invitamos a verlo en acción para decidir por usted mismo, ¡y divertirse haciéndolo!

Ya que ha llegado hasta aquí, no pierda los anuncios recientes de la versión 2.0 del Stack de TypesafeAkka 2.0, y la Consola de Typesafe.

Para más información, lean el anuncio original en el blog de Typesafe

Kotlin and Playframework :: JetBrains Developer Community

Via Scoop.itplayframework

In this discussion kotlin developers confirm the rummours that kotlin will finally chose play framework 2 as their own web framework. Here is the whole discussion and my thoughts on the subject.
Via devnet.jetbrains.net

Openshift module for Play framework 0.1.2 – quickfix release

Consider voting for Play framework native support on Openshift.

We’ve just released the version 0.1.2 of the openshift module.

Openshift jboss cartridge name changed from jboss-7.0 to jboss-7, so the script in charge of creating a new application was giving an error.

This quickfix version solves that issue.

To upgrade your app to the latest version, edit your conf/dependencies.yml file like this:

# Application dependencies

require:
    - play
    - play -> openshift 0.1.2

And then run

play deps

If you want to remove the previous version you can run

play deps --sync

Take into account that the --sync options will remove every file in lib folder that is not managed by the dependencies.yml file.

To remove the previous openshift module version from play installation, just remove the folder at <play install>/modules/openshift-x.x.x, and then run play install openshift to install the latest version on your play framework installation folder.

Good luck and don’t hesitate to report any issue at https://github.com/opensas/openshift.

For more infomation on the usage of openshift module, check this article.

Saludos

Sas

Podcast en Java Hispano: Introducción a Play Framework

En el último podcast de Java Hispano han publicado una entrevista a Jorge Aliss (@jaliss) y Sebastián Scarano (@develsas), dos entusiastas miembros de la comunidad Play y asiduos colaboradores de este blog.

Aquí tienen la nota de Java hispano, y desde aquí pueden escuchar la entrevista:

http://www.javahispano.org/storage/podcasts/137_JavahispanoPodcast_PlayFramework.mp3

Estos son algunos de los temas tratados:

Queremos agradecer especialmente al equipo de Java Hispano por todo el trabajo que vienen realizando incansablemente para difundir java en la comunidad hispano-hablante y por la oportunidad que nos han dado de hablar sobre Play.

Secure JSON Services with Play Scala and SecureSocial, by Matt Raible

Matt Raible has kindly agreed to let us publish his article on playlatam. You can find the original article at his site.

 

Last November, I traveled to Antwerp to speak at Devoxx. After my talk on HTML5 with Play Scala, Mattias Karlsson approached me and we had a chat about doing the same talk at Jfokus in Stockholm. I agreed and we began talking details after Trish and I returned to the US.

jFocus

I wrote this article on a plane between Denver and Seattle and will be hopping over the North Pole to Stockholm via Iceland tonight. For the past couple of weeks, I’ve been updating my Play More! HTML5/mobile app to add some new features. Most notably, I wanted to upgrade to Play 2.0, create JSON services and add authentication.

Upgrading to Play 2.0

My attempt to upgrade to Play 2.0 involved checking out the source from GitHub, building and installing the RC1 snapshot. As I tried to upgrade my app and started getting failed imports, I turned to the internet (specifically StackOverflow) to see if it was a good idea. The first answer for that question suggested I stay with 1.x.

If it’s a critical project, to be finished before next March 2012, I would go with Play 1.x. If it’s a less important project, which could be delayed, and that in any case won’t be released before March 2012, try Play 2.0.

While I didn’t plan on releasing Play More! before Jfokus, I decided upgrading didn’t add a whole lot to the talk. Also, I couldn’t find a Play Scala 0.9.1 to Play 2.0 upgrade guide and I didn’t have enough time to create one. So I decided to stick with Play 1.2.4 and add some JSON services for my iPhone client.

JSON Servers

I found Manuel Bernhardt’s Play! Scala and JSON. This led me to Jerkson, built by the now infamous@coda. I was able to easily get things working fairly quickly and wrote the following WorkoutService.scala:

package controllers.api

import play.mvc.Controller
import models._
import com.codahale.jerkson.Json._

object WorkoutService extends Controller {

  def workouts = {
    response.setContentTypeIfNotSet("application/json")
    generate(Workout.find().list())
  }
  def edit(id: Long) = {
    generate(Workout.byIdWithAthleteAndComments(id))
  }

  def create() = {
    var workout = params.get("workout", classOf[Workout])
    Workout.create(workout)
  }

  def save(id: Option[Long]) = {
    var workout = params.get("workout", classOf[Workout])
    Workout.update(workout)
  }

  def delete(id: Long) = {
    Workout.delete("id={id}").on("id" -> id).executeUpdate()
  }
}

Next, I added routes for my new API to conf/routes:

GET     /api/workouts               api.WorkoutService.workouts
GET     /api/workout/{id}           api.WorkoutService.edit
POST    /api/workout                api.WorkoutService.create
PUT     /api/workout/{id}           api.WorkoutService.save
DELETE  /api/workout/{id}           api.WorkoutService.delete

Then I created an ApiTest.scala class that verifies the first method works as expected.

import play.test.FunctionalTest
import play.test.FunctionalTest._
import org.junit._

class ApiTests extends FunctionalTest {
  
    @Test
    def testGetWorkouts() {
        var response = GET("/api/workouts");
        assertStatus(200, response);
        assertContentType("application/json", response)
        println(response.out)
    }
}

I ran “play test”, opened my browser to http://localhost:9000/@tests and clicked ApiTests -> Start to verify it worked. All the green made me happy.

Play More API Tests

Finally, I wrote some CoffeeScript and jQuery to allow users to delete workouts and make sure delete functionality worked.

$('#delete').click ->
  $.ajax
    type: 'POST'
    url: $(this).attr('rel')
    error: ->
      alert('Delete failed, please try again.')
    success: (data) ->
      location.href = "/more"

I was very impressed with how easy Play made it to create JSON services and I smiled as my CoffeeScript skills got a refresher.

The Friday before we left for Devoxx, I saw the module registration request for SecureSocial.

SecureSocial with Play Scala
From SecureSocial’s README:

SecureSocial allows you to add an authentication UI to your app that works with services based on OAuth1, OAuth2, OpenID and OpenID+OAuth hybrid protocols.

It also provides a Username and Password mechanism for users that do not wish to use existing accounts in other networks.

The following services are supported in this release:

  • Twitter (OAuth1)
  • Facebook (OAuth2)
  • Google (OpenID + OAuth Hybrid)
  • Yahoo (OpenID + OAuth Hybrid)
  • LinkedIn (OAuth1)
  • Foursquare (OAuth2)
  • MyOpenID (OpenID)
  • WordPress (OpenID)
  • Username and Password

In other words, it sounded like a dream come true and I resolved to try it once I found the time. That time found me last Monday evening and I sent a direct message to @jaliss (the module’s author) via Twitter.

Does Secure Social work with Play Scala? I’d like to use it in my Play More! project.

Jorge responded 16 minutes later saying that he hadn’t used Play Scala and he’d need to do some research. At 8 o’clock that night (1.5 hours after my original DM), Jorge had a sample working and emailed it to me. 10 minutes later I was adding a Secure trait to my project.

package controllers

import play.mvc._
import controllers.securesocial.SecureSocial

/*
 * @author Jorge Aliss <jaliss@gmail.com> of Secure Social fame.
 */
trait Secure {
  self: Controller =>

  @Before def checkAccess() {
    SecureSocial.DeadboltHelper.beforeRoleCheck()
  }

  def currentUser = {
    SecureSocial.getCurrentUser
  }
}

I configured Twitter and Username + Password as my providers by adding the following toconf/application.conf.

securesocial.providers=twitter,userpass

I also had to configure a number of securesocial.twitter.* properties. Next, I made sure my routes were aware of SecureSocial by adding the following to the top of conf/routes:

  *       /auth               module:securesocial

Then I specified it as a dependency in conf/dependencies.yml and ran “play deps”.

    - play -> securesocial 0.2.4

After adding “with Secure” to my Profile.scala controller, I tried to access its route and was prompted to login. Right off the bat, I was shown an error about a missing jQuery 1.5.2 file in my “javascripts” folder, so I added it and rejoiced when I was presented with a login screen. I had to add the app on Twitter to use its OAuth servers, but I was pumped when both username/password authentication worked (complete with signup!) as well as Twitter.

The only issue I ran into with SecureSocial was that it didn’t find the default implementation of SecureSocial’s UserService.Service when running in prod mode. I was able to workaround this by adding a SecureService.scala implementation to my project and coding it to talk to my Athlete model. I didn’t bother to hook in creating a new user when they logged in from Twitter, but that’s something I’ll want to do in the future. I was also pleased to find out customizing SecureSocial’s views was a breeze. I simply copied them from the module into my app’s views and voila!

package services

import play.db.anorm.NotAssigned
import play.libs.Codec
import collection.mutable.{SynchronizedMap, HashMap}
import models.Athlete
import securesocial.provider.{ProviderType, UserService, SocialUser, UserId}

class SecureService extends UserService.Service {
  val activations = new HashMap[String, SocialUser] with SynchronizedMap[String, SocialUser]

  def find(userId: UserId): SocialUser = {
    val user = Athlete.find("email={email}").on("email" -> userId.id).first()

    user match {
      case Some(user) => {
        val socialUser = new SocialUser
        socialUser.id = userId
        socialUser.displayName = user.firstName
        socialUser.email = user.email
        socialUser.isEmailVerified = true
        socialUser.password = user.password
        socialUser
      }
      case None => {
        if (!userId.provider.eq(ProviderType.userpass)) {
          var socialUser = new SocialUser
          socialUser.id = userId
          socialUser
        } else {
          null
        }
      }
    }
  }

  def save(user: SocialUser) {
    if (find(user.id) == null) {
      val firstName = user.displayName
      val lastName = user.displayName
      Athlete.create(Athlete(NotAssigned, user.email, user.password, firstName, lastName))
    }
  }

  def createActivation(user: SocialUser): String = {
    val uuid: String = Codec.UUID()
    activations.put(uuid, user)
    uuid
  }

  def activate(uuid: String): Boolean = {
    val user: SocialUser = activations.get(uuid).asInstanceOf[SocialUser]
    var result = false

    if (user != null) {
      user.isEmailVerified = true
      save(user)
      activations.remove(uuid)
      result = true
    }

    result
  }

  def deletePendingActivations() {
    activations.clear()
  }
}

Jorge was a great help in getting my authentication needs met and he even wrote a BasicAuth.scala trait to implement Basic Authentication on my JSON services.

package controllers

import _root_.securesocial.provider.{UserService, ProviderType, UserId}
import play._
import play.mvc._
import play.libs.Crypto

import controllers.securesocial.SecureSocial

/*
 * @author Jorge Aliss <jaliss@gmail.com> of Secure Social fame.
 */
trait BasicAuth {
  self: Controller =>

  @Before def checkAccess = {
    if (currentUser != null) {
      // this allows SecureSocial.getCurrentUser() to work.
      renderArgs.put("user", currentUser)
      Continue
    }

    val realm =
      Play.configuration.getProperty("securesocial.basicAuth.realm", "Unauthorized")

    if (request.user == null || request.password == null) {
      Unauthorized(realm)
    } else {
      val userId = new UserId
      userId.id = request.user
      userId.provider = ProviderType.userpass
      val user = UserService.find(userId)

      if (user == null ||
        !Crypto.passwordHash(request.password).equals(user.password)) {
        Unauthorized(realm)
      } else {
        // this allows SecureSocial.getCurrentUser() to work.
        renderArgs.put("user", user)
        Continue
      }
    }
  }

  def currentUser = {
    SecureSocial.getCurrentUser()
  }
}

Summary

My latest pass at developing with Scala and leveraging Play to build my app was a lot of fun. While there were issues with class reloading every-so-often and Scala versions with Scalate, I was able to add the features I wanted. I wasn’t able to upgrade to Play 2.0, but I didn’t try that hard and figured it’s best to wait until its upgrade guide has been published.

I’m excited to describe my latest experience to the developers at Jfokus this week. In addition, the conference has talks on Play 2.0CoffeeScriptHTML5Scala and Scalate. I hope to attend many of these and learn some new tricks to improve my skills and my app.

Update: The Delving developers have written an article on Migration to Play 2. While it doesn’t provide specific details on what they needed to change, it does have good information on how long it took and things to watch for.

Republished from Raible Designs. You can find the original article here.

Spanish translation of Play framework documentation is ready!

Note: this article is also available in spanish.

We have finally completed the translation of the play framework site, you can reach it at http://playdoces.appspot.com/

It was just three months ago that we announced on the play framework spanish google group (http://groups.google.com/group/play-latam) that together with a couple of colleagues we were starting the translation of Play Framework documentation, and we also invited all spanish-speaking Play users to join us.

Play Framework in Spanish

Play Framework in Spanish

Today, while we are waiting for the Play 2.0 release, thanks to the collaboration of several developers from Latin America and Spain, we can finally announce that we completed the translation of all Play Framework documentation.

Here you have the links:

Main page: http://playdoces.appspot.com/

If you happen to live in one of the countries whom google denies access to Google Application Engine (I wonder what happened to the “don’t be evil” mantra) we have deployed a copy of the site at openshift: http://playdoces-opensas.rhcloud.com/

Play 2.0 announcement: http://playdoces.appspot.com/2.0

We’d like to thank @rodriguezlaurag and @mfmontanari from Argentina, @gualtrapa from Spain, @pjquero from Venezuela and @alfonsokim from Mexico, and also to the developers of the japanese translation of play framework site, @garbagetown and @ikeike443, whose work we shamelessly forked 😉

We hope you enjoy it, and that this site might help spread the word about this wonderful framework among Spanish speaking developers all over the world.

Saludos

Sas (follow me on @develsas)

%d bloggers like this: