Capsules for recovering Scala fever.

Scala is a multi-paradigm programming language that combines the features of object-oriented programming and functional programming. The word “Scala” refers to “Sca(Scalable)+la(Language)” i.e designed to grow with the demands of its users. Scala runs on the Java Virtual Machine.

Here We’ll discuss about some of the basic concepts in Scala that make it distinct from other programming languages.Let us start with some of the following:


1. Simple method in scala:-

object Check {
   def countcharacter(a: String, b: String) = { //Declaring a method in scala
       if (a.length > b.length) println("The large word is" + a) 
       else  println("The large word is" + b) 
 }

  def main(args: Array[String]) {                 // The main method in scala
      countcharacter("Neelkanth","Sachdeva")     //calling the method
  }

}




2. Scala Array with “for” loop :-

object forloopdemo {
  
  val name= new Array[String](4)     // Declaring an Array in scala
  name(0)="This"
    name(1)="is"
      name(2)="an"
        name(3)="array"
  
  def printarrayelem(args:Array[String]):Unit={  

   /*Creating a method named "printarrayelem" with return type "Unit",
   that will print out all the elements in array.  */                                             
                                                     
  for(arg <- args)      
  /* A sample for loop for printing all elements in array. */                                                  
  println(arg)         
}
  
  def main(args: Array[String]) {    //The main method in scala
  printarrayelem(name)
  }
}

3. Constructor in Scala:-


class construct(val name: String, val age: Int) {                
println("This is the example program of primary constructor")
}

object PrimaryConstructor {
  def main(args: Array[String]) {           //the main method.
    val cons = new construct("Neelkanth Sachdeva", 23) 
     /*passing the values for name and age at the time of object creation. */                                                
                                                       
    println(cons.name)      // accessing the value via constructor.
  }
}


4. Companion Objects. :-

In Java, you often have a class with both instance methods and static methods. In Scala, you achieve this by having a class and a “companion” object
of the same name. The class and its companion object can access each other’s private features. They must be located in the same source file.

class companion{
  private var balance=0.0
  private def deposit(amount:Double){      //Declaring a private method
  balance+=amount
  println(balance)
  }
}
object companion {
  def main(args: Array[String]) {
  val n=new companion
/*Accessing the private method of class in its companion object.  */
  n.deposit(78.00)                
   }
 }

5. Bypass the main method :-
In Scala, you need not to have main method always, you can bypass the main method by extending the “App” trait as follows.


object main_alternate extends App{       //extending the "App" trait 
                                         //to avoid main method.
 println("This is the alternate of main")
}


6.ArrayBuffer in Scala:-
Most operations on an array buffer have the same speed as for an array, because the operations simply access and modify the underlying array. Additionally, array buffers can have data efficiently added to the end.Array buffers are useful for efficiently building up a large collection whenever the new items are always added to the end.
import scala.collection.mutable.ArrayBuffer
object arraybuffdemo {
  val abuf = new ArrayBuffer[Int]()        //Array buffer
  val array = Array(1, 2, 3, 4, 5)         //Simple array

  def main(args: Array[String]) {

    abuf += 1            //Inserting an element to buffer
    println(abuf)

    abuf ++= array      //Inserting a whole array to arraybuffer
    println(abuf)

    abuf.trimStart(1)   //removing one element from 
                         //starting point in arraybuffer
    println(abuf)

    abuf.trimEnd(1)    //removing one element from 
                         //ending point in arraybuffer
    println(abuf)

    abuf.insert(1, 80, 81, 82)  //inserting the three element 
                                //say 80,81,82 at index 1. 
    println(abuf)
       
    abuf.remove(1, 2)   //removing two elements from the index 1
    println(abuf)

 }
}

Enjoiii Scala!!!! :-)

Categories: News

Seasons Greetings and Best Wishes for 2012

December 25, 2011 Leave a comment

Festival and Holiday season is all around us. Many of us are already on holidays, taking well deserved break and having fun with family and friends. This is also a time to sit back, take a look how things went in past 12 months and plan for the coming year.

For Inphina, it has been an eventful year. We did projects on lot of new and diverse technologies like Google Fusion Tables, Maps, Google App Engine, Lift, Scala and lot more. Our partners list also increased substantially this year and we got opportunity to work with organizations from Singapore, Australia, Germany, UK, USA and of-course India. We started with CSD (Certified Scrum Developer) program and were the first one to execute it in India. Along with many successful public and private courses in India, we were able to take it outside India and did our first International CSD course in Kathmandu, Nepal. Most importantly, we had great fun and learning all through-out the year. We would like to thank all our partners for their confidence and support.

On behalf of everyone at Inphina, we would like to wish you and your dear ones a Merry Christmas and happy times in the year ahead.

Categories: News

Using RDBMS on Google App Engine : Google Cloud SQL

December 16, 2011 5 comments

We have been working on Google App Engine since its early days and have developed and ported several applications on the platform for our clients. One of the major hinderance for our Enterprise clients for not being able to move to GAE has been Datastore being the only storage option available till date. Major reasons for these enterprises not using Datastore are:

  • (In case of migration) Substantial efforts in adapting the application code base to Google Datastore specifications
  • Potentially huge data-migration efforts
  • Vendor Lock-In as both the application code and data residing in Datastore can’t be taken to an in-premise Infrastructure or another cloud platform seamlessly

Keeping all these requests and potential business opportunities in mind, Google has recently announced Cloud SQL.

What is Google Cloud SQL

  • It’s a Relational Database on Cloud offering from Google.
  • Offers MySQL Database environment with JDBC support for Java applications and DB-API support for Python applications.
  • Being a service on Cloud, it offers traditional advantages of any Cloud service like no maintenance, administration, replication and backup efforts
  • To ensure high-availability, data gets replicated across multiple geographic regions
  • Easy to use Web-Interface for managing multiple Instances

Google Cloud SQL & Google App Engine

A very good integration has been provided for your applications running on Google App Engine to use Google Cloud SQL as back-end storage mechanism. Furthermore, one SQL instance can be shared across multiple Google App Engine applications. This feature should be quite helpful as often we have a family of Web Applications for different user-requirements but still sharing the same Database.
Read more…

Categories: Cloud, Java, Web Tags: ,

Basic Http authentication in Lift.

Lift web framework accommodate a no. of conspicuous features that are implemented in a unique and solitary way as compared to other frameworks. Here we’ll discuss about the basic “Http authentication” mechanism for security in Lift.

What is ‘LiftRules’ singleton ?
Nearby all configuration parameters for the http requests and response are defined in LiftRules singleton. The important thing to notice is that we can only change the configuration parameteres of LiftRules only during boot but not at other times. You can find more about LiftRules Here.

Now for our purpose of Http authentication what all you have to do , is to add some Lines of code using the LiftRules singleton present in lift, in to your Boot.scala File and you’ll find all gets done for a basic http authentication.

Let us have a look to the steps for doing it ::

*Firstly in your Boot.scala file make the class extends Loggable(part of “net.liftweb.common”) as :

class Boot extends Loggable {
  def boot {
   LiftRules.addToPackages("XYZ")
.....
.....
} }



*Now you have to proceed with the ‘prepend’ method(from LiftRules package) implementation in your Boot(def Boot) method & defining the name of html pages on which you want to implement the authentication as follows:
 LiftRules.httpAuthProtectedResource.prepend{
      case (Req("html_page_name":: Nil,_,_)) => Full(AuthRole("admin"))
      case (Req("securepage":: Nil,_,_)) => Full(AuthRole("admin"))
                       
      
// Just mention the above code for page on which you
// want to implement the http authentication.   

    }


*Call the authentication(have root in ‘HttpAuthentication.class’) from the LiftRules and mention the username and password for the authentication purpose as :
LiftRules.authentication = HttpBasicAuthentication("Authenticate Yourself") {      
      case("user_name","password",req) => {
        logger.info("Authentication Succeeded...Welcome!!")
         userRoles(AuthRole("admin"))
         true
      }
    }



* Now each time when user will try to access the page,browser will pop up for the http authentication like: :-)


Http Authentication in Lift

Note:- Don’t forgot the following basic imports:

import common.{Loggable, Full}
import http._
import auth.{userRoles, HttpBasicAuthentication, AuthRole}


::: Want to get start with Lift ? come Here.

Categories: News

Mercurial Branching Cheat Sheet

December 15, 2011 Leave a comment

I have been using Subversion as source code version control tool since many years. Though I have used Mercurial for couple of hobby projects earlier but few weeks back, I started using it on my first Industrial project. Here, we are working on multiple feature-sets which need to go into Production at different time-lines. The best way to manage such scenarios is the use of branches. The concept and way of working with branches in Mercurial is quite different from Subversion. Here are few commands which one might find helpful while starting to work with Mercurial branches:

hg branches //shows all the branches present in the repository

There is always at-least one branch in Mercurial Repository which is called default as compared to trunk in Subversion.
hg branch new_branch_name //creates a new named branch

Named branches help in easy identification of the work being done on that branch.
hg commit //commits all the changes locally to the newly created branch
hg push --new-branch //pushes all the changes of this branch along with the branch to mercurial server

Only when we have committed and pushed our changes in newly created branch, other team members will be able to see the branch and our changes. Once a team member has committed the changes in a branch and other people would like to do further work on the same branch, they can use the following flow:
hg pull //gets all the changes on default as well as other branches
hg update -C branch_name //switches to the branch

On regular intervals, we will need to merge our changes from one branch to other for integrating different feature-sets. Following are the commands for the purpose
hg merge default //merges all the changes from default branch to your current working branch
hg commit //commits all the changes in your current working branch
hg push //pushes all the change-sets into the repository for other members to use them

For more detailed information on branching, please refer to branching tutorial available on Mercurial site.

Categories: News Tags: ,

Getting Started with Lift web framework : Your first step…!

November 3, 2011 1 comment

Lift is a sophisticated web development framework that runs inside a Java web container & uses the Scala programming language.Lift removes a lot of the burdens that other frameworks place on developers by mixing together the best ideas in the marketplace today & aims to make building real-time, highly interactive, and amazingly scalable applications.Here we are going to introduce you with the Lift web framework in a very easy and understandable manner to give you a better quick start with Lift.

1. First of all you have to install simple-build-tool(sbt) on your machine. (Know more about it Here )

2. After installing simple-build-tool(sbt), Just create a directory for your project say “Test” , enter in to directory and just say “sbt” as:

nsachdeva@nsachdeva-Vostro-3700:~/Test$ sbt

3. “sbt” will prompt you to ask for creating new project, just press “y” & give the Name to your project as shown in Fig. :

.

4. Now for creating the lift project, you’ll use a processor to generate the structure and default files you’ll need to start working on the application.From the shell, run this command:

*lift is org.lifty lifty 1.6.1

5. Now you have to execute the following command to populate a blank SBT project with Lift web specialities.

> lift create project-blank

6. Just give the name of your main package & the version of Lift you want to use, when it prompt for ask and then you will obtain the following type structure of your project.

7. After obtaining this point, proceed by a “reload” & “update”.This will download all the dependencies required.

8.Start the jetty and check the running application at http://localhost:8080.

Importing the project in “IntellijIdea”:

you can now import the project on any platform with which you want to work e.g for importing the project in intellijIdea just run the following commands. This will generate the “Test.iml” file within the project structure and you will be able to import this project in IntellijIdea.

>  *sbtIdeaRepo at http://mpeltonen.github.com/maven/
 > *idea is com.github.mpeltonen sbt-idea-processor 0.4.0
....
....
 > update
....
....
 > idea

Fig: The generated Project hierarchy

Categories: Lift web framework

Setting up environment to work with scala using play framework.

Play is an open source web application framework base on model-view controller architecture. Play is written in java but also provides support for the scala programming language. Here we are going to elaborate the steps about the initial environment setup to start working with scala using play framework.


1. Install scala for play using following command.

$ play install scala

2. Create new project as follows (Let us assume that application that is to be created has the name “Test”):
$ play new Test --with scala

3. Make the project able to import in IntellijIdea. (This is completely your choice. You can use your desired Platform to work with e.g Eclipse etc. )
$ play idealize Test

4. Run the Test application using following command:
$ play run Test

5. Check the created application at http://localhost:9000 and verify its working.

Now the created application can’t be directly imported in intellijIdea. Now do it as elaborated follow:

6. Create the new project in IntellijIdea. The location of the project must be the same as the directory where the play project is created.Don’t forget to uncheck the create module option because the created play project itself acts as a module.



7.Now select ‘Project Structure’ option from the file menu. Click the Module option and press the “+” button. Select the “Import existing module” option and then point towards the (.iml) file.



8.Let the Module selected,Then select the ‘tmp/generated’ directory in the right one tree and press the ‘Sources’ button. The HTML template pages are converted to scala source files by Play ,these source files are to be included in the project along with the source files in the Test directory.



9.Select Global Libraries > scala-compiler-2.9.1, Then press the ‘Attach Classes’ button and navigate to the ‘lib’ directory in your Scala 2.9.1 directory. Then select the following files & press Apply.
-scala-compiler.jar
-scala-library.jar



10. Now add another global library as Global Library > scala-library-2.9.1, containing the files scala-dbc.jar, scala-library.jar and scala-swing.jar. Select these files and press OK.

11.Now go to the Modules > Dependencies, press Add button to add new library called “scala-library-2.9.1″ to dependencies.



12. Go to Module,select the scala under Test branch and set the compiler library to the presented one on your machine e.g on my machine this is the “scala-compiler-2.9.1″.



13.Save the Project Structure by clicking the “Ok” button.Again verify the project at http://localhost:9000. Your Project development environment is now ready.

Categories: Play, Scala

Happy Diwali 2011

October 26, 2011 Leave a comment

Wishing you all a very Happy, Joyous and Fun-Filled Diwali 2011. We sincerely Thank you for all your support and hope the same for years to come.

Categories: News

Create web application menus using the Lift web framework

September 30, 2011 1 comment

Lift is a powerful & secure web framework having elegant features and also stresses the importance of security, maintainability, scalability and performance. Lift applications are written in Scala.

Here we will discuss about creating the menus in Lift. These are the approaches to create a menu:

  • Define the url names and routes directly in Boot.scala.
  • Create the seperate Singleton for defining menu items.

Let us see how this works:

Define the url names and routes in Boot.scala

class Boot {
  def boot {
    // where to search snippet
    LiftRules.addToPackages("demo.helloworld")

    // Build SiteMap
    val entries =
      Menu(Loc("Home", List("index"), "Home"))::
      Menu(Loc("Items", List("items"), "Items")) ::
      Menu(Loc("Search", List("search"), "Search")) :: Nil

    // Sitemap
    LiftRules.setSiteMap(SiteMap(entries:_*))

  }
}

And here is the output:



Create the seperate Singleton for defining menu items

We will define the sitemap in Boot.scala. Sitemap will obtained from the Application Singleton

class Boot {
  def boot {
    LiftRules.setSiteMap(SiteMap(Application.sitemap: _*))
  }
}

Now define your menu items in this seperate singleton say "Application" singleton.

object Application {
  // Sitemap
  val sitemap = List(
    Menu.i("Items") / "items",
    Menu.i("Search") / "search"
  ) ::: User.menus
}

When working with html pages always provide the links to pages corresponds to as defined in your singleton's sitemap e.g

  <li><a href="/items">Items</a></li>
  <li><a href="/search">Search</a></li>

Lift will search for corresponding HTML pages defined either in Boot.scala or in Application.scala in src/main/webapp folder.

Categories: Scala, Web Tags:

Hot reload / Build on save for Adobe Flex

September 26, 2011 Leave a comment

If you’re not using Adobe Flash Builder for developing Adobe Flex apps, you might be missing the build on save (or build automatically / hot reload) feature.

Here’s a little Node.js utility that does the same. While working on Flex with gedit (or any other text editor), just keep “hotflex” running in the background. It watches all MXML and AS3 files and rebuilds the project on save.

Screenshots

This slideshow requires JavaScript.

Dependencies

Node.js and NPM are required, refer to – Setup Node.js and NPM on Ubuntu

For notifications on Ubuntu, install libnotify-bin:

    sudo apt-get install libnotify-bin

Install

From NPM:

    sudo npm install hotflex -g

From GitHub

    git clone git://github.com/Srirangan/hotflex.git
    cd hotflex
    sudo npm install -g

Configure

You will need to create a hotflex.json file containing the following parameters:

    { "source": "./src/main/flex/main.mxml"
    , "sourceFolder": "./src"
    , "target": "./bin/main.swf"
    , "lib": "./lib"
    }

The lib parameter is optional while the rest are mandatory.

Run

Execute hotflex from the folder containing the hotflex.json file, preferably your project root.

hotflex

Meta

GitHub repository – https://github.com/Srirangan/hotflex
NPM – http://search.npmjs.org/#/hotflex

To do

  • Integration with Adobe Flex Compiler Shell fcsh for faster builds
  • Integration for Growl for OSX notifications. Currently notifications work for Ubuntu.
Categories: Web Tags: ,
Follow

Get every new post delivered to your Inbox.