SlideShare ist ein Scribd-Unternehmen logo
1 von 53
“Scala,
       Play 2.0 &
                 Cloud Foundry”

                 By:
              Pray Desai
   Intern – Scala Developer Advocate
             Cloud Foundry

             @praydesai
Scala
Introduction
• Scala is a programming language that combines
  features of object-oriented programming with
  functional programming.
• Scala (skah-la) stands for Scalable language
• Designed to grow with the demands of users
• Growing new types by defining easy-to-use
  libraries
• Growing new control constructs such as
  concurrent programming
• Write small scripts as well as build large systems
• Scala runs on the Java platform (Java Virtual
  Machine) as well as Dot Net platform.

• Designed by Martin Odersky in 2001 at EPFL, who
  was also one of the creators of javac compiler
  and generic java
• Open source
• Released in 2004
• Second version v 2.0 in 2006
• Current version is 2.9.2
Q : What is the one thing that makes
           Scala scalable ?

      Ans.: Combining OO with FP
Object Oriented programming

•   Purely OO
•   Every value is an object
•   Every operation is a method
•   No primitive types, everything is object
•   1 + 2 invokes a method + defined in class Int
Functional programming
• Not purely FP
What is Functional programming ?
• Concept came from Lambda Calculus
• Computation by evaluation of functions
• Basic fundamental is to evaluate an expression and use its
  result for some other expression
• Made up of functions that always return some value
• Char of FP absent in IP & OO : Always return same value for
  same inputs ; map input values to output values
• No side effects : state does not change
• Immutable data : Cannot change the value once set;
  so no need to lock the access of shared data
• Reuse same code in diff parts of the programs
• Free order of code execution
Functional programming in Scala
• Partially FP
• Supports mutable data as well as immutable
• Variables as well as Values

•   Functions are first-class values just like an integer or string
•   Higher – order functions: allows to combine parts of code easily
•   Pass functions as arguments to other functions
•   Return functions as results from functions
•   Store functions in variables
•   Define a function inside another function

• Closures - functions that capture variables defined in scope. Function can
  access variable even after scope is exited.
• Modern Collection Library that allows parallel execution of functions
• Supports immutable data structures in its libraries so no need of locks to
  access.
Syntax
    The implementation is similar to Java or C. We use the same operators and
    control structures.

•    Function definition starts with “def”
           def fact(x:Int) : Int = if(x==0)1 else x*fact(x-1)
•   variable definitions start with “var” and definitions of values (i.e. read only
    variables) start with “val”.
•   val is immutable where var is mutable
    Error :           Correct:
    val x=123        var x=123
    x=x+1            x=x+1
•   No need to write public. It is default visibility.
•   No semicolon
•   No need to specify data type, compiler infers it from context
•    Array types are written as Array[Int] rather than Int[], and array
    selections are written a(i) rather than a[i].
•   Looping becomes easy with the use of functional literals
    for (i<-0 to 10) print(i)
    for (I <-0 until 10) print(i)
Comparison with Java
• It is compatible with existing Java programs and we can
  use all java libraries.
• Its operates similar to Java. Its compiler generates byte
  code that is similar to java bytecode
• JVM cannot differentiate between scala code and java
  code. The only difference is an extra runtime library.
• Scala code can be decompiled to readable Java code,
  with the exception of certain constructor operations.
• Runs on Eclipse and Netbeans IDE just as Java.
• The only two things in scala which are absent in java
  are richer type system and support for functional
  programming.
Traits
• Traits are like interfaces in java but can also have
  method implementations and fields which can
  then be reused by mixing them into classes.
• Unlike class inheritance, in which each class must
  inherit from just one superclass, a class can mix in
  any number of traits.
• Members of class are added to members of
  multiple traits
• Avoids diamond problem in multiple inheritance
• Automatically add methods to a class in terms of
  methods the class already has.
• Make a thin interface into a rich one.
Abstract Class
• Class abstractions are extended by subclassing

  abstract class class1 extends trait1 {
  case subclass1 extends class1
  case subclass2 extends class1
  }
No getters and setters
public class Person{
          private String firstName = null;                public class Person {
          private String lastName = null;                           var firstName = ""
          private int age = 0;                                      var lastName = ""
                                                                    var age = 0
         public void setFirstName(String                  }
firstName) {
                   this.firstName = firstName;
         }

          public String getFirstName() {
                     return firstName;
          }

         public void setLastName(String
lastName) {
                   this.lastName = lastName;
         }
                                                 http://hedleyproctor.com/2012/04/why-java-
          public String getLastName() {          developers-should-be-learning-scala/
                     return lastName;
Data Structures
                [Containers of values]
1. List
• Collection of data that can be randomly accessed
  and can have different datatypes
• Immutable, new list generated every time
• Int list :            val a =List(1,2,3)
• Combination :                val b =List(“a”,’’b”,4)
• Concate lists :               a ::: b
• Any is catchall datatype
• Access value:                b(2)
2. Set
• Similar to list but independent of order
• Cannot combine datatypes in single set
• Immutable, new set generated everytime
• Set(1,2,3) == Set(3,1,2) true
• List(1,2,3)==List(3,1,2) false

  var a = Set(1,2,3)
  val b = Set(0,1,5)
• Add/remove value from set :
      a=a+4
      a=a-3
• Union :           a ++ b
• Intersection : a ** b
3. Map
• Key-value pair which maps keys of type A to
  values of type B

val m = Map (0 -> “abc”, 1->”def”, 2->”xyz”)
m(2)
4. Tuple
• Store different data types in same variable
• Used to return multiple objects from method
• Storing/Retrieving rows of tables in database

  val address=(201,”s 4 th st”)
  address (._1)
  address (._2)
  address
Pattern Matching
• Conditionally execute code based on some data
  provided
• Used in parsing xml and parsing messages
  between threads
• Similar to switch case, no breaks
• def chek(a:Int) { a match
  case 0 => …
  case 1 => ..
  case _ => ..
  }
Support to Parallel Processing
• In v2.9, collections support parallel operations
• It has two methods :
  c.par which returns parallel version of c
  c.seq which returns sequential version of c
• Divide work by number of processors
• Threads maintain work queues
Actors
• Actors are basic units of concurrency implemented
  on top of threads.
• Two basic operations: message send and receive.
• A send is asynchronous without waiting for the
  message to be received and processed
• Every actor has a mailbox in which incoming
  messages are queued.
• A receive block consists of a number of cases that
  each query the mailbox with a message pattern.
• The first message in the mailbox that matches any
  of the cases is selected, and the corresponding
  action is performed on it.
Scala features in Java 8

•   Lambda expressions
•   Higher order functions
•   Parallel Collections
•   Function chaining
•   Traits

           www.infoq.com/articles/java-8-vs-scala
Lambda expressions

Function Literal
• Function with input parameters and function
  body
• (type parameter) -> function_body
• ex: (String s1, String s2) - > s1.length()-
  s2.length();
Why Scala ?
• Compatible - with JVM
• Concise - reduced code
    //java                                                 //scala
    class student {                                        class student(id:Int, name:String)
    private int id;
    private String name;
    public student (int id, String name) {
    this.id = id;
    this.name = name;
    }
}

• High-level - more simpler, shorter code and easy to understand,
                            Use and design libraries for clear and concise code

• Statically typed – variable type known at compile time, less runtime errors

• XML literals - create and consuming XML quite easy within your applications.

• Parallel Processing - .par, .seq, Actors
Testing
 There are several ways to test code in Scala :
• ScalaTest
   Supports multiple testing styles and can integrate with Java-based
   testing frameworks
• ScalaCheck
    Generates automatic test case and minimizes failing test cases
• Specs2
   Library for writing executable software specifications
• ScalaMock
   Provides support for testing high-order and curried functions
• JUnit , TestNG
    Unit testing frameworks for java
• Borachio
   Provides support for testing high-order and curried functions.
Companies that work on Scala
• Twitter - for queuing system that handles heavy load
• LinkedIn – used in their framework “Nobert”
• Sony -library that manages updates, rollbacks and changes
  to database schemas
• Siemens – application for company wide employees
  communication to boost productivity
• Xerox – to improve customer experience
• Grid Grain - provides DSL for cloud computing
• Swiss bank UBS - for general production usage
• FourSquare - for message passing
• The Guardian newspaper - content API for selecting and
  collecting news content
• Juniper Networks – distributed software based on Akka
  middleware for multi-core processors
Limitations
• Syntax
  Difficult to understand as reading backwards.
  The return value is at the end of the
  declaration, and the types are declared after
  the variable names.
• Slow compilation and interpreter
  Takes much time to compile and run. We can
  use fsc compiler now (Fast Scala Compiler),
  which essentially stays resident in memory.
Further Enhancements
• Developer tools- Akka/Scala stack, Akka
  framework, which is the most widely used
  parallel computation framework on top of Java
• Style-checking tool, to be integrated in next
  release of the IDE.
• Visual Studio integration.
• Scala for JavaScript
• V2.10 : better support for dynamic languages,
  better reflection, better support for parallelism.
Conclusion
• “If I were to pick a language to use on JVM other
  than Java then it would be Scala” – James Gosling
• “Scala will be long term replacement of java, If
  someone had told me about Scala then I would
  have never created Groovy” – James Strachan ,
  Creator of Groovy
• “Scala is current heir apparent to Java throne, no
  other language capable to replace java than
  scala” – Charlies Nutter, JRuby Lead
Scala Resources
• Programming in Scala, 2nd edition
  by Martin Odersky

• http://www.scala-lang.org/

• http://twitter.github.com/scala_school/

• Free Online Course from 9/18/2012 for 7 weeks:
  https://www.coursera.org/course/progfun
Installing Scala in Eclipse
• Current versions: IDE: 2.0.2      Scala: 2.9.x
• Required: JDK 5 or 6, Eclipse Helios or Indigo

• http://scala-ide.org/
• Copy the url for the current version
• Help -> Install New Software
  OR
• Search Scala IDE in
  Help -> Eclipse Market Place
Hello World Program

object Hello {
  def main (args: Array[String])
  {
    println("Hello World")
  }
}
Play 2.0
Play 2.0
•   Web application framework
•   MVC
•   Light-weight
•   Core written in Scala
•   Local Host Server
•   No need to add any external jars !
•   Display errors in browser
Installing Play 2.0
• Required: JDK 6
• Download from
  http://www.playframework.org/
• Unzip and add play directory to working path
• For Mac :
  export PATH=$PATH:/Applications/play-2.0
• For Windows:
  Set path in the global environment variable
Play commands
• Check Play is installed
  play help

• Create a new Play app
  play new <app-name>
  cd <app-name>

• Run the app
  play run
  Go to browser and type - localhost:9000
  Ctrl + D to stop server

• Clean the server
  play clean
Play in Eclipse
• play eclipsify

• File -> Import -> Existing Projects into WS
Working Directory
• app
    controllers
    view
    model
• test
• conf
    application.conf
    routes
• logs
• project
• public
    images
    javascripts
    stylesheets
Hello World App
controllers/Application.scala               views/index.scala.html


package controllers                         @(message: String)

import play.api._
import play.api.mvc._                       @main("Welcome") {
                                              @message
object Application extends Controller {     }

    def index = Action {
      Ok(views.html.index("Hello World"))
    }

}
Configure routes
                             conf/routes


# Home page
GET /                     controllers.Application.index

# Map static resources from the /public folder to /assets URL path
GET /assets/*file         controllers.Assets.at(path="/public", file)
Play 2.0 Resources
• Go to the directory where you installed Play
  play-2.0/documentation/Play 2.0 Doc.pdf

• Sample apps :
 play-2.0/samples/scala

• http://www.playframework.org/documentatio
  n/2.0.2/ScalaHome
Cloud Foundry
What is Cloud Foundry ?
•   Open PaaS
•   “Linux of the Cloud”
•   Deploy and scale apps easily
•   Focus just on coding
•   Supports Scala & Play 2.0
•   Choice of many other services and frameworks
Register
• http://cloudfoundry.com/signup
• Get your credentails in email
        Welcome email




                                   28




• Check your login on http://uaa.cloudfoundry.com
Install RVM and Ruby
                      For Mac:

• Install Ruby Version Manager https://rvm.io//

• rvm install 1.9.2

• rvm use 1.9.2
For Windows:

• http://rubyinstaller.org/downloads
  Download version 1.9.2

• Check version by
  ruby –v
Install vmc [command line tool]
• gem install vmc

• Check version (0.3.18 or higher)
  vmc –v

• vmc login
• vmc target api.cloudfoundry.com
Deploy Play App on Cloud Foundry
• Package app
  cd app1
  play clean dist

Your application is ready in
/Users/desaip/app1/dist/app1-1.0-SNAPSHOT.zip

• vmc push --path=dist/app1-1.0-SNAPSHOT.zip
vmc push
                    [to deploy app for the first time]
desaip-mbp:~ desaip$ cd check1
desaip-mbp:check1 desaip$ vmc push --path=dist/check1-1.0-SNAPSHOT.zip
Application Name: check1
Detected a Play Framework Application, is this correct? [Yn]:
Application Deployed URL [check1.cloudfoundry.com]:
Memory reservation (128M, 256M, 512M, 1G, 2G) [256M]:
How many instances? [1]:
Create services to bind to 'check1'? [yN]: N
Would you like to save this configuration? [yN]: N
Creating Application: OK
Uploading Application:
 Checking for available resources: OK
 Processing resources: OK
 Packing application: OK
 Uploading (80K): OK
Push Status: OK
Staging Application 'check1': OK
Starting Application 'check1': OK

desaip-mbp:check1 desaip$
vmc update
                       [ to deploy updated app]
• cd app1
• play clean dist
• vmc update app1 --path=dist/app1-1.0-SNAPSHOT.zip

desaip-mbp:check1 desaip$ vmc update check1 --path=dist/check1-1.0-SNAPSHOT.zip
Uploading Application:
 Checking for available resources: OK
 Processing resources: OK
 Packing application: OK
 Uploading (80K): OK
Push Status: OK
Stopping Application 'check1': OK
Staging Application 'check1': OK
Starting Application 'check1': OK

desaip-mbp:check1 desaip$
vmc instances
             [ to scale your app]

• To create another instance
   vmc instances <app-name> +1

• To see other commands
   vmc help
Cloud Foundry Resources
• http://blog.cloudfoundry.com/2012/05/31/clo
  ud-foundry-now-supports-play/

• http://www.slideshare.net/chris.e.richardson/
  cloud-foundry-bootcamp-at-contributingcode

• http://cloudstory.in/2012/07/tutorial-getting-
  started-with-cloud-foundry-part-13/
THANK YOU

Weitere ähnliche Inhalte

Was ist angesagt?

Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaSaleem Ansari
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaDerek Chen-Becker
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in ScalaRose Toomey
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slidesMartin Odersky
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos3Pillar Global
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapDave Orme
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 

Was ist angesagt? (19)

Java
JavaJava
Java
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Java notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esectionJava notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esection
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Scalax
ScalaxScalax
Scalax
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
 
Simplicitly
SimplicitlySimplicitly
Simplicitly
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slides
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 

Ähnlich wie Scala, Play 2.0 & Cloud Foundry

Ähnlich wie Scala, Play 2.0 & Cloud Foundry (20)

ppt_on_java.pptx
ppt_on_java.pptxppt_on_java.pptx
ppt_on_java.pptx
 
chapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptxchapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptx
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Java
JavaJava
Java
 
Net framework
Net frameworkNet framework
Net framework
 
Java
Java Java
Java
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Unit 1
Unit 1Unit 1
Unit 1
 
Learning core java
Learning core javaLearning core java
Learning core java
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Android course session 5 (Threads & socket)
Android course session 5 (Threads & socket)Android course session 5 (Threads & socket)
Android course session 5 (Threads & socket)
 
Core java concepts
Core java conceptsCore java concepts
Core java concepts
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Java
JavaJava
Java
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Lambda Expressions Java 8 Features usage
Lambda Expressions  Java 8 Features usageLambda Expressions  Java 8 Features usage
Lambda Expressions Java 8 Features usage
 

Kürzlich hochgeladen

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Kürzlich hochgeladen (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Scala, Play 2.0 & Cloud Foundry

  • 1. “Scala, Play 2.0 & Cloud Foundry” By: Pray Desai Intern – Scala Developer Advocate Cloud Foundry @praydesai
  • 3. Introduction • Scala is a programming language that combines features of object-oriented programming with functional programming. • Scala (skah-la) stands for Scalable language • Designed to grow with the demands of users • Growing new types by defining easy-to-use libraries • Growing new control constructs such as concurrent programming • Write small scripts as well as build large systems
  • 4. • Scala runs on the Java platform (Java Virtual Machine) as well as Dot Net platform. • Designed by Martin Odersky in 2001 at EPFL, who was also one of the creators of javac compiler and generic java • Open source • Released in 2004 • Second version v 2.0 in 2006 • Current version is 2.9.2
  • 5. Q : What is the one thing that makes Scala scalable ? Ans.: Combining OO with FP
  • 6. Object Oriented programming • Purely OO • Every value is an object • Every operation is a method • No primitive types, everything is object • 1 + 2 invokes a method + defined in class Int
  • 8. What is Functional programming ? • Concept came from Lambda Calculus • Computation by evaluation of functions • Basic fundamental is to evaluate an expression and use its result for some other expression • Made up of functions that always return some value • Char of FP absent in IP & OO : Always return same value for same inputs ; map input values to output values • No side effects : state does not change • Immutable data : Cannot change the value once set; so no need to lock the access of shared data • Reuse same code in diff parts of the programs • Free order of code execution
  • 9. Functional programming in Scala • Partially FP • Supports mutable data as well as immutable • Variables as well as Values • Functions are first-class values just like an integer or string • Higher – order functions: allows to combine parts of code easily • Pass functions as arguments to other functions • Return functions as results from functions • Store functions in variables • Define a function inside another function • Closures - functions that capture variables defined in scope. Function can access variable even after scope is exited. • Modern Collection Library that allows parallel execution of functions • Supports immutable data structures in its libraries so no need of locks to access.
  • 10. Syntax The implementation is similar to Java or C. We use the same operators and control structures. • Function definition starts with “def” def fact(x:Int) : Int = if(x==0)1 else x*fact(x-1) • variable definitions start with “var” and definitions of values (i.e. read only variables) start with “val”. • val is immutable where var is mutable Error : Correct: val x=123 var x=123 x=x+1 x=x+1 • No need to write public. It is default visibility. • No semicolon • No need to specify data type, compiler infers it from context • Array types are written as Array[Int] rather than Int[], and array selections are written a(i) rather than a[i]. • Looping becomes easy with the use of functional literals for (i<-0 to 10) print(i) for (I <-0 until 10) print(i)
  • 11. Comparison with Java • It is compatible with existing Java programs and we can use all java libraries. • Its operates similar to Java. Its compiler generates byte code that is similar to java bytecode • JVM cannot differentiate between scala code and java code. The only difference is an extra runtime library. • Scala code can be decompiled to readable Java code, with the exception of certain constructor operations. • Runs on Eclipse and Netbeans IDE just as Java. • The only two things in scala which are absent in java are richer type system and support for functional programming.
  • 12. Traits • Traits are like interfaces in java but can also have method implementations and fields which can then be reused by mixing them into classes. • Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits. • Members of class are added to members of multiple traits • Avoids diamond problem in multiple inheritance • Automatically add methods to a class in terms of methods the class already has. • Make a thin interface into a rich one.
  • 13. Abstract Class • Class abstractions are extended by subclassing abstract class class1 extends trait1 { case subclass1 extends class1 case subclass2 extends class1 }
  • 14. No getters and setters public class Person{ private String firstName = null; public class Person { private String lastName = null; var firstName = "" private int age = 0; var lastName = "" var age = 0 public void setFirstName(String } firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } http://hedleyproctor.com/2012/04/why-java- public String getLastName() { developers-should-be-learning-scala/ return lastName;
  • 15. Data Structures [Containers of values] 1. List • Collection of data that can be randomly accessed and can have different datatypes • Immutable, new list generated every time • Int list : val a =List(1,2,3) • Combination : val b =List(“a”,’’b”,4) • Concate lists : a ::: b • Any is catchall datatype • Access value: b(2)
  • 16. 2. Set • Similar to list but independent of order • Cannot combine datatypes in single set • Immutable, new set generated everytime • Set(1,2,3) == Set(3,1,2) true • List(1,2,3)==List(3,1,2) false var a = Set(1,2,3) val b = Set(0,1,5) • Add/remove value from set : a=a+4 a=a-3 • Union : a ++ b • Intersection : a ** b
  • 17. 3. Map • Key-value pair which maps keys of type A to values of type B val m = Map (0 -> “abc”, 1->”def”, 2->”xyz”) m(2)
  • 18. 4. Tuple • Store different data types in same variable • Used to return multiple objects from method • Storing/Retrieving rows of tables in database val address=(201,”s 4 th st”) address (._1) address (._2) address
  • 19. Pattern Matching • Conditionally execute code based on some data provided • Used in parsing xml and parsing messages between threads • Similar to switch case, no breaks • def chek(a:Int) { a match case 0 => … case 1 => .. case _ => .. }
  • 20. Support to Parallel Processing • In v2.9, collections support parallel operations • It has two methods : c.par which returns parallel version of c c.seq which returns sequential version of c • Divide work by number of processors • Threads maintain work queues
  • 21. Actors • Actors are basic units of concurrency implemented on top of threads. • Two basic operations: message send and receive. • A send is asynchronous without waiting for the message to be received and processed • Every actor has a mailbox in which incoming messages are queued. • A receive block consists of a number of cases that each query the mailbox with a message pattern. • The first message in the mailbox that matches any of the cases is selected, and the corresponding action is performed on it.
  • 22. Scala features in Java 8 • Lambda expressions • Higher order functions • Parallel Collections • Function chaining • Traits www.infoq.com/articles/java-8-vs-scala
  • 23. Lambda expressions Function Literal • Function with input parameters and function body • (type parameter) -> function_body • ex: (String s1, String s2) - > s1.length()- s2.length();
  • 24. Why Scala ? • Compatible - with JVM • Concise - reduced code //java //scala class student { class student(id:Int, name:String) private int id; private String name; public student (int id, String name) { this.id = id; this.name = name; } } • High-level - more simpler, shorter code and easy to understand, Use and design libraries for clear and concise code • Statically typed – variable type known at compile time, less runtime errors • XML literals - create and consuming XML quite easy within your applications. • Parallel Processing - .par, .seq, Actors
  • 25. Testing There are several ways to test code in Scala : • ScalaTest Supports multiple testing styles and can integrate with Java-based testing frameworks • ScalaCheck Generates automatic test case and minimizes failing test cases • Specs2 Library for writing executable software specifications • ScalaMock Provides support for testing high-order and curried functions • JUnit , TestNG Unit testing frameworks for java • Borachio Provides support for testing high-order and curried functions.
  • 26. Companies that work on Scala • Twitter - for queuing system that handles heavy load • LinkedIn – used in their framework “Nobert” • Sony -library that manages updates, rollbacks and changes to database schemas • Siemens – application for company wide employees communication to boost productivity • Xerox – to improve customer experience • Grid Grain - provides DSL for cloud computing • Swiss bank UBS - for general production usage • FourSquare - for message passing • The Guardian newspaper - content API for selecting and collecting news content • Juniper Networks – distributed software based on Akka middleware for multi-core processors
  • 27. Limitations • Syntax Difficult to understand as reading backwards. The return value is at the end of the declaration, and the types are declared after the variable names. • Slow compilation and interpreter Takes much time to compile and run. We can use fsc compiler now (Fast Scala Compiler), which essentially stays resident in memory.
  • 28. Further Enhancements • Developer tools- Akka/Scala stack, Akka framework, which is the most widely used parallel computation framework on top of Java • Style-checking tool, to be integrated in next release of the IDE. • Visual Studio integration. • Scala for JavaScript • V2.10 : better support for dynamic languages, better reflection, better support for parallelism.
  • 29. Conclusion • “If I were to pick a language to use on JVM other than Java then it would be Scala” – James Gosling • “Scala will be long term replacement of java, If someone had told me about Scala then I would have never created Groovy” – James Strachan , Creator of Groovy • “Scala is current heir apparent to Java throne, no other language capable to replace java than scala” – Charlies Nutter, JRuby Lead
  • 30. Scala Resources • Programming in Scala, 2nd edition by Martin Odersky • http://www.scala-lang.org/ • http://twitter.github.com/scala_school/ • Free Online Course from 9/18/2012 for 7 weeks: https://www.coursera.org/course/progfun
  • 31. Installing Scala in Eclipse • Current versions: IDE: 2.0.2 Scala: 2.9.x • Required: JDK 5 or 6, Eclipse Helios or Indigo • http://scala-ide.org/ • Copy the url for the current version • Help -> Install New Software OR • Search Scala IDE in Help -> Eclipse Market Place
  • 32. Hello World Program object Hello { def main (args: Array[String]) { println("Hello World") } }
  • 34. Play 2.0 • Web application framework • MVC • Light-weight • Core written in Scala • Local Host Server • No need to add any external jars ! • Display errors in browser
  • 35. Installing Play 2.0 • Required: JDK 6 • Download from http://www.playframework.org/ • Unzip and add play directory to working path • For Mac : export PATH=$PATH:/Applications/play-2.0 • For Windows: Set path in the global environment variable
  • 36. Play commands • Check Play is installed play help • Create a new Play app play new <app-name> cd <app-name> • Run the app play run Go to browser and type - localhost:9000 Ctrl + D to stop server • Clean the server play clean
  • 37. Play in Eclipse • play eclipsify • File -> Import -> Existing Projects into WS
  • 38. Working Directory • app  controllers  view  model • test • conf  application.conf  routes • logs • project • public  images  javascripts  stylesheets
  • 39. Hello World App controllers/Application.scala views/index.scala.html package controllers @(message: String) import play.api._ import play.api.mvc._ @main("Welcome") { @message object Application extends Controller { } def index = Action { Ok(views.html.index("Hello World")) } }
  • 40. Configure routes conf/routes # Home page GET / controllers.Application.index # Map static resources from the /public folder to /assets URL path GET /assets/*file controllers.Assets.at(path="/public", file)
  • 41. Play 2.0 Resources • Go to the directory where you installed Play play-2.0/documentation/Play 2.0 Doc.pdf • Sample apps : play-2.0/samples/scala • http://www.playframework.org/documentatio n/2.0.2/ScalaHome
  • 43. What is Cloud Foundry ? • Open PaaS • “Linux of the Cloud” • Deploy and scale apps easily • Focus just on coding • Supports Scala & Play 2.0 • Choice of many other services and frameworks
  • 44. Register • http://cloudfoundry.com/signup • Get your credentails in email Welcome email 28 • Check your login on http://uaa.cloudfoundry.com
  • 45. Install RVM and Ruby For Mac: • Install Ruby Version Manager https://rvm.io// • rvm install 1.9.2 • rvm use 1.9.2
  • 46. For Windows: • http://rubyinstaller.org/downloads Download version 1.9.2 • Check version by ruby –v
  • 47. Install vmc [command line tool] • gem install vmc • Check version (0.3.18 or higher) vmc –v • vmc login • vmc target api.cloudfoundry.com
  • 48. Deploy Play App on Cloud Foundry • Package app cd app1 play clean dist Your application is ready in /Users/desaip/app1/dist/app1-1.0-SNAPSHOT.zip • vmc push --path=dist/app1-1.0-SNAPSHOT.zip
  • 49. vmc push [to deploy app for the first time] desaip-mbp:~ desaip$ cd check1 desaip-mbp:check1 desaip$ vmc push --path=dist/check1-1.0-SNAPSHOT.zip Application Name: check1 Detected a Play Framework Application, is this correct? [Yn]: Application Deployed URL [check1.cloudfoundry.com]: Memory reservation (128M, 256M, 512M, 1G, 2G) [256M]: How many instances? [1]: Create services to bind to 'check1'? [yN]: N Would you like to save this configuration? [yN]: N Creating Application: OK Uploading Application: Checking for available resources: OK Processing resources: OK Packing application: OK Uploading (80K): OK Push Status: OK Staging Application 'check1': OK Starting Application 'check1': OK desaip-mbp:check1 desaip$
  • 50. vmc update [ to deploy updated app] • cd app1 • play clean dist • vmc update app1 --path=dist/app1-1.0-SNAPSHOT.zip desaip-mbp:check1 desaip$ vmc update check1 --path=dist/check1-1.0-SNAPSHOT.zip Uploading Application: Checking for available resources: OK Processing resources: OK Packing application: OK Uploading (80K): OK Push Status: OK Stopping Application 'check1': OK Staging Application 'check1': OK Starting Application 'check1': OK desaip-mbp:check1 desaip$
  • 51. vmc instances [ to scale your app] • To create another instance vmc instances <app-name> +1 • To see other commands vmc help
  • 52. Cloud Foundry Resources • http://blog.cloudfoundry.com/2012/05/31/clo ud-foundry-now-supports-play/ • http://www.slideshare.net/chris.e.richardson/ cloud-foundry-bootcamp-at-contributingcode • http://cloudstory.in/2012/07/tutorial-getting- started-with-cloud-foundry-part-13/

Hinweis der Redaktion

  1. scalable bcoz ..easy-to-use libraries that feel like native language support add new types that can be used as conveniently as built-in types. “grow” the Scala language in new directions even as specialized as concurrent programming. use java’s rich, thread-based concurrency library and additional library that implements Erlang’s actor model Even though they are defined in a library, actors feel like an integral part of the Scala language.
  2. the one thing that makes it scalable is unification of functions and objects
  3. Simula in the mid-60’s and Smalltalk in the 70’s object is container – data and operationsNo primitive types at java level but handles JVM primitive types at bytecode level
  4. What is Functional programming ?before understanding how FP is implemeneted in scala, let us first understand what FP is ?
  5. first was Lisp in late 50s. Other popular are Erlang, Haskell, OCaml, and F#.
  6. Def: keywordFunction nameParameter listColonReturn type [optional; compiler can infer it from the context ]Equal toFunction bodyVal – FP concept Var – OO concept
  7. diamond inheritance” is when the same class is inherited via several different paths.
  8. Collection c;On compl work,
  9. No semicolonComparing Class and constructor in java with scala With use of Functional literals, avoid use of loops  Type inference- no need to specify types,optionalParameterize type, combine types, hide details,Build our own types, design interfaces Each variable, method parameter, return type etc. has a type known at compile time, either declared or inferred like java,c,c++.