Play 2.1 for Http Server - api

I am new to play framework. My requirement is very simple. I want to create rest api server in scala using play framework. I could use play2-mini, but it seems it is outdated.
I want play 2.1 to be used in my project. Instead of setting play framework as dependency, I want only core module. So I have few questions -
What is core module of Play ? what is module name ?
Is it sufficient to use core module for creating asynchronous http server ?
This link says I can use core module instead of play-mini. If it's true, where can I get more info about it.

You can just simply setup a route and then point it to a controller that parses the data you send. Here is an example of json parsing and serving back a response with play.
http://www.playframework.com/documentation/2.1.1/ScalaJsonRequests
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.json._
// you need this import to have combinators
import play.api.libs.functional.syntax._
object Application extends Controller {
implicit val rds = (
(__ \ 'name).read[String] and
(__ \ 'age).read[Long]
) tupled
def sayHello = Action { request =>
request.body.asJson.map { json =>
json.validate[(String, Long)].map{
case (name, age) => Ok("Hello " + name + ", you're "+age)
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}.getOrElse {
BadRequest("Expecting Json data")
}
}
}
or even simpler...
def sayHello = 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))
}
}

Play Framework is a highly modular project. Internally it consists of around 20 subprojects. Some of them you can include in your project as a library dependency if you need them, for example anorm or jdbc. Other projects (i.e. PlayExceptions, RoutesCompiler, TemplatesCompiler etc.) are essential for any Play application, so you don't need to declare dependency on them. These projects could be called a 'core' of Play Framework.
In other words, if you need a Play application with minimum dependencies, just don't declare dependencies you don't need.
Play sources: https://github.com/playframework/Play20

I don't think there is much problem here. For example, this is my build.sbt used for a very small project, that uses json, in which I wanted to use Play libraries, but not necessarily create a full Play app:
name := "my-small-project"
version := "0.0.1-SNAPSHOT"
resolvers ++= Seq(
"TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases",
"Sonatype Repo" at "http://oss.sonatype.org/content/repositories/releases"
)
libraryDependencies ++= Seq(
"org.specs2" %% "specs2" % "2.3.7" % "test",
"commons-codec" % "commons-codec" % "1.8",
"com.typesafe.play" % "play_2.10" % "2.2.1",
"com.typesafe.play" % "play-json_2.10" % "2.2.1"
)
And You could still remove some dependencies here, especially if You don't need Base64 encoding. Here I consider play_2.10 as "the core" you're interested in. You should get yourself familiar with sbt though, but it's not that hard.
Also remember, that the difference between "a Play application" and "an application that uses Play libraries" is quite fuzzy, especially if you use sbt. And this is the beauty of it, this shows how Play creators thoughtfully tried not to invent a wheel once again by creating custom system requirements for their project to build. You can enter a Play app dir and type "sbt compile" for example instead of firing a Play console and it should work just fine.

Related

How to fix third party dll include not being staged correctly by Unreal Build Tool?

I am using a pre-built C++ library in my Unreal project using a dynamic library file (let's say it's called MyPluginLib.dll). The library is contained in a plugin, let’s call it MyPlugin.
Building, packaging, playing in editor works fine. However, a packaged build doesn’t start, giving the following error: Code execution cannot proceed, MyPluginLib.dll was not found.
The packaging process places MyPluginLib.dll file in MyGame\Plugins\MyPlugin\Binaries. However, the execution process is seemingly looking for it in MyGame\Binaries – moving the library there manually solves this issue.
Why is the OS unable to find the dll in the first folder? Is there something wrong in the build.cs, or my folder structure?
The folder structure of the plugin folder is as follows:
Includes in Plugins\MyPlugin\Source\ThirdParty\MyPluginLib\
Binaries in Plugins\MyPlugin\Binaries\(PLATFORM)\
The plugin’s Build.cs looks like this:
public class MyPlugin : ModuleRules
{
public MyPlugin(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
string PluginRoot = Path.GetFullPath(Path.Combine(ModuleDirectory, "..", ".."));
string PlatformString = Target.Platform.ToString();
string LibraryDirectory = Path.Combine(PluginRoot, "Binaries", PlatformString);
PublicIncludePaths.Add(Path.Combine(PluginRoot, "Source", "ThirdParty", "MyPluginLib"));
if ((Target.Platform == UnrealTargetPlatform.Win64))
{
PublicAdditionalLibraries.Add(Path.Combine(LibraryDirectory, "MyPluginLib.lib"));
RuntimeDependencies.Add(Path.Combine(LibraryDirectory, "MyPluginLib.dll"), StagedFileType.NonUFS);
}
else if (Target.Platform == UnrealTargetPlatform.Linux)
{
// linux binaries...
}
}
Would appreciate any help.
Check your packaged games files, unreal loves to not include certain thing in packaged builds regarding plugins.

Need one example deno on how to use karate scripts for peformance testing using gatling from scratch

I am very new to perf testing, i went through the sample project created using karate scripts in gatling, but unable to understand how to do it,
Can anyone please provide explanation on how to use karate for performance testing using gatling by using some public api like below
Scenario: Get State specific information - one state
Given url 'http://services.groupkt.com/state/get/IND/AP'
When method get
Then status 200
* def resp = response.RestResponse.result.name
* print resp
so that we can use it in our project. unable to understand the current demo project available in github karate
You just have to Git-clone and run (using Maven) this simple, stand-alone project: https://github.com/ptrthomas/karate-gatling-demo
Take the help of someone who knows their way around a Maven project if needed.
Once you get this running, you will be able to understand and modify this in no time.
package mock
import com.intuit.karate.gatling.PreDef._
import io.gatling.core.Predef._
import scala.concurrent.duration._
class CatsSimulation extends Simulation {
val protocol = karateProtocol(
"/cats/{id}" -> Nil,
"/cats" -> Nil
)
val create = scenario("create").exec(karateFeature("classpath:mock/cats-create.feature"))
val delete = scenario("delete").exec(karateFeature("classpath:mock/cats-delete.feature"))
setUp(
create.inject(rampUsers(10) over (5 seconds)).protocols(protocol),
delete.inject(rampUsers(5) over (5 seconds)).protocols(protocol)
)
}

Unresolved dependencies de.joergviola#play-pdf_2.10;0.6-SNAPSHOT with Play 2.0 PDF module

I would like to use that module:
Play 2.0 PDF
with my play 2.2.1 application, but unfortunatelly I've got an error:
unresolved dependencies de.joergviola#play-pdf_2.10;0.6-SNAPSHOT: not found
please help, or advice any other pdf library to use.
I would like to generate pdf from html and also from data/code
There is a forked repo that has the following information:
"Currently, the module is hosted at http://alias1.github.io/play2pdf/snapshots/ Therefore, including the following lines in your Build.scala will resolve it:"
val appDependencies = Seq(
...
"de.joergviola" %% "play2pdf_2.10" % "0.6.3-SNAPSHOT"
)
val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings(
...
resolvers += Resolver.url("play2pdf Repository", url("http://alias1.github.io/play2pdf/snapshots/"))(Resolver.ivyStylePatterns)
)
This may work as a temporary work around for you until you can find a better supported PDF library for Java.

Using Forms after migrating from playframework 2.0 to 2.1 RC2 (java)

I have updated my controllers with to use play.data.Form.form() method instead of Controller.form(). When I try to run my application I get errors like:
error: method render in class create_user cannot be applied to given types;
return ok(create_user.render("", Form.form(CreateUserInfo.class), creator.get()));
required: String, play.api.data.Form, User
found: String, play.data.Form, User
It looks like the my templates expect to get play.api.data.Form instead of play.data.Form. Is there suppost to be any implicit conversion or should I update my templates to use play.data.Form?
If I'm using play.data.Form in my templates I am missing out on some of the features of play.api.data.Form, like the ability to request parameters through the apply method ( ex: createUserForm("username") )
The solution was provided by Guillaume Bort at the playframework google group.
I forgot to add javaCore as a dependency for my application after updating Build.scala. You have to explicitly add javaCore as a dependency in 2.1.
val appDependencies = Seq(
javaCore
)
And remember to start using play.Project instead of PlayProject:
val main = play.Project(appName, appVersion, appDependencies).settings(
// Add your own project settings here
)

How to use a dependency of a module within a Play app

I am writing a Play Framework module in order to share some common logic among multiple Play apps. One of the things I would like my module to do is provide some frequently-used functionality by way of 3rd-party modules, for example the excellent Markdown module.
First of all, is it possible to do this? I want all the apps that include my module to be able to use the .markdown().raw() String extension without needing to explicitly declare the Markdown module as a dependency. The Play Framework Cookbook chapter 5 seems to imply that it is possible, unless I am reading it wrong.
Secondly, if it is possible, how does it work? I have created the following vanilla example case, but I'm still getting errors.
I created a new, empty application "myapp", and a new, empty module "mymod", both in the same parent directory. I then modified mymod/conf/dependencies.yml to:
self: mymod -> mymod 0.1
require:
- play
- play -> markdown [1.5,)
I ran play deps on mymod and it successfully downloaded and installed the Markdown module. Running play build-module also worked fine with no errors.
Then, I modified myapp/conf/dependencies.yml to:
# Application dependencies
require:
- play
- mymod -> mymod 0.1
repositories:
- Local Modules:
type: local
artifact: ${application.path}/../[module]
contains:
- mymod
I ran play deps on myapp and it successfully found mymod, and generated the myapp/modules/mymod file, containing the absolute path to mymod.
I ran myapp using play run and was able to see the welcome page on http://localhost:9000/. So far so good.
Next, I modified myapp/app/views/Application/index.html to:
#{extends 'main.html' /}
#{set title:'Home' /}
${"This is _MarkDown_, by [John Gruber](http://daringfireball.net/projects/markdown/).".markdown().raw()}
I restarted myapp, and now I get the following error.
09:03:23,425 ERROR ~
#6a6eppo46
Internal Server Error (500) for request GET /
Template execution error (In /app/views/Application/index.html around line 4)
Execution error occured in template /app/views/Application/index.html. Exception raised was MissingMethodException : No signature of method: java.lang.String.markdown() is applicable for argument types: () values: [].
play.exceptions.TemplateExecutionException: No signature of method: java.lang.String.markdown() is applicable for argument types: () values: []
at play.templates.BaseTemplate.throwException(BaseTemplate.java:86)
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:257)
at play.templates.Template.render(Template.java:26)
at play.templates.GroovyTemplate.render(GroovyTemplate.java:187)
at play.mvc.results.RenderTemplate.<init>(RenderTemplate.java:24)
at play.mvc.Controller.renderTemplate(Controller.java:660)
at play.mvc.Controller.renderTemplate(Controller.java:640)
at play.mvc.Controller.render(Controller.java:695)
at controllers.Application.index(Application.java:13)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:548)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:502)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:478)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:473)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:161)
at Invocation.HTTP Request(Play!)
Caused by: groovy.lang.MissingMethodException: No signature of method: java.lang.String.markdown() is applicable for argument types: () values: []
at /app/views/Application/index.html.(line:4)
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:232)
... 13 more
And just to confirm I'm not crazy, I tried adding the play -> markdown [1.5,) line to myapp/conf/dependencies.yml and restarted the app, and confirmed that it works.
I feel like I'm missing something obvious. Many thanks in advance to anyone who can help! :)
Yes I had the same problem, it seems that transitive dependencies through custom home made modules does not work