alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (Jsonp.scala)

This example Play Framework source code file (Jsonp.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

api, codec, contenttypeof, http, json, jsonp, jsvalue, lib, library, play, play framework, string, writeable

The Jsonp.scala Play Framework example source code

/*
 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
 */
package play.api.libs

import play.api.libs.json.JsValue
import play.api.http.{ ContentTypeOf, ContentTypes, Writeable }
import play.api.mvc.Codec

/**
 * JSONP helper.
 *
 * Example of use, provided the following route definition:
 * {{{
 *   GET  /my-service       Application.myService(callback: String)
 * }}}
 * The following action definition:
 * {{{
 *   def myService(callback: String) = Action {
 *     val json = ...
 *     Ok(Jsonp(callback, json))
 *   }
 * }}}
 * And the following request:
 * {{{
 *   GET /my-service?callback=foo
 * }}}
 * The response will have content type “text/javascript” and will look like the following:
 * {{{
 *   foo({...});
 * }}}
 *
 * Another example, showing how to serve either JSON or JSONP from the same action, according to the presence of
 * a “callback” parameter in the query string:
 * {{{
 *   def myService = Action { implicit request =>
 *     val json = ...
 *     request.queryString.get("callback").flatMap(_.headOption) match {
 *       case Some(callback) => Ok(Jsonp(callback, json))
 *       case None => Ok(json)
 *     }
 *   }
 * }}}
 */
case class Jsonp(padding: String, json: JsValue)

object Jsonp {

  implicit def contentTypeOf_Jsonp(implicit codec: Codec): ContentTypeOf[Jsonp] = {
    ContentTypeOf[Jsonp](Some(ContentTypes.JAVASCRIPT))
  }

  implicit def writeableOf_Jsonp(implicit codec: Codec): Writeable[Jsonp] = Writeable { jsonp =>
    codec.encode("%s(%s);".format(jsonp.padding, jsonp.json))
  }

}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework Jsonp.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.