Tuesday, March 6, 2012

Maven with Scala and Lift

  1. Use this lift-archetype-basic archetype which is hosted on http://scala-tools.org/repo-release.

mvn archetype:generate -DarchetypeGroupId=net.liftweb -DarchetypeArtifactId=lift-archetype-basic_2.9.1 -DarchetypeRepository=http://scala-tools.org/repo-releases -DremoteRepositories=http://scala-tools.org/repo-releases -DgroupId=com.dynamicobjx -DartifactId=lift-chat -Dversion=1.0
  1. This will prompt if you want the default version and configuration. Then you should change scala version to latest version. As of now the version is 2.9.1, that also change lift version which is 2.4.

  1. If you had error on dependency life-mapper, change the dependency definition by changing artifactId to life-mapper_2.9.1.

<dependency>
<groupId>net.liftweb</groupId>
<artifactId>lift-mapper_2.9.1</artifactId>
<version>2.4</version>
</dependency>
  1. If you had an error on test classes, this is due to its incompatibility to scala 2.9.1. Therefore, you have to change its artifact id of org.scala-tools.testing from specs to specs_2.9.1 and make the version to 1.6.9.

<dependency>
<groupId>org.scala-tools.testing</groupId>
<artifactId>specs_2.9.1</artifactId>
<version>1.6.9</version>
</dependency>

Now, resolve all the dependencies and make the project an eclipse project (eclipse is my prefered IDE) by executing:
mvn dependency:resolve eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true

This will download all the dependencies you defined on pom. You explicitly also say to download sources and javadocs using -DdownloadSources=true -DdownloadJavadocs=true (parameter for eclipse:eclipse). eclipse:eclipse is the command that let the maven project to be open on eclipse, this goal create files like .project, .classpath, .wtpmodels and .components that is needed by eclipse.

After that you can now import it to your eclipse. The structure of the project must be like this:

The project name will be the artifactid- the source file is categorized into two: one source file for testing and another for your actual source code. It will also generates a src/main/webapp directory, that contains all the *.html and public files like image, css and javascript.

To run the project you use:
mvn jetty:run

To run, with auto-compile if source code is change use this:
mvn scala:cc

If you want an on-the-fly reloading of changes made on Java class file, try to use JRebel. Right now, I don’t add it to my dependencies.

After running jetty:run goal, the output project can be seen on 0.0.0.0:9080.

At the end of today’s experience of mine on scala and lift, I found out that the Boot.scala file is the main Class of the project and its main page is index.html based on the sitemap() method of Boot class.

index.html
<lift:surround with="default" at="content">
<h2>Welcome to your project!</h2>
<p>
    <lift:helloWorld.howdy>
      <span>Welcome to lift-chat at <b:time/></span>
    </lift:helloWorld.howdy>
  </p>
</lift:surround>

This means that this html will be surrounded by the default.html content, where the enclosing content of list:surround will be placed on default.html on the place where lift:bind name=”content” is defined.
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:lift="http://liftweb.net/">
<head></head>
<body>
  <div class="container">
    <div class="column span-12 last" style="text-align: right">
      <h1 class="alt">lift-chat<img alt="" id="ajax-loader" style="display:none; margin-bottom: 0px; margin-left: 5px" src="/images/ajax-loader.gif"/></h1>
    </div>

    <hr/>

    <div class="column span-6 colborder sidebar">
      <hr class="space" />
      <lift:Menu.builder />
      <div>
        <lift:Msgs showAll="true"/>
        <hr class="space" />
      </div>
    </div>

    <div class="column span-17 last">
      <lift:bind name="content" /> <!-- this is where the content of index.html be injected -->
    </div>

    <hr />
    <div class="column span-23 last" style="text-align: center">
      <h4 class="alt">
        <a href="http://www.liftweb.net"><i>Lift</i></a>
       is Copyright 2007-2010 WorldWide Conferencing, LLC.  Distributed under an Apache 2.0 License.</h4>
    </div>
    
  </div>
</body>
</html>



(On index.html) Also <b: time> is also a binding tags, in here the value of b:time is defined on Helloworld.howdy. The binding tags is <lift:hellowWOrld.howdy>. in howdy method, they bind the b:time tags to the current time and date.

Resources:

Saturday, February 25, 2012

List of maven archetype available for Lift-Scala

All the stated archetype are host in http://scala-tools.org/repo-releases, all of this archetypes group id is net.liftweb:
* means 2.7.7/2.8.0/2.8.1/2.9.1 pattern
  • archetypes_*
  • lift-archetype-basic_*
  • lift-archetype-blank_*
  • lift-archetype-jpa-basic_*
  • lift-archetype-jpa-blank-single_*
  • lift-archetype-jpa-blank_*
  • lift-archetype-sbt_*


Just execute this command on your console with this pattern:
mvn archetype:generate -DarchetypeGroupId=net.liftweb -DarchetypeArtifactId=-DarchetypeRepository=http://scala-tools.org/repo-releases -DremoteRepositories=http://scala-tools.org/repo-releases -DgroupId=. -DartifactId= -Dversion=1.0

If I want to use the lift-archetype-basic_2.91 to create a ebook-repo project, i will execute:

mvn archetype:generate -DarchetypeGroupId=net.liftweb -DarchetypeArtifactId=lift-archetype-basic_2.9.1 -DarchetypeRepository=http://scala-tools.org/repo-releases -DremoteRepositories=http://scala-tools.org/repo-releases -DgroupId=com.lmn -DartifactId=ebook-repo -Dversion=1.0

Note:
If http://scala-tools.org/repo-releases doesn’t work as archetype and remote repository try to use this:
https://oss.sonatype.org/content/groups/scala-tools

Resources:


Sunday, February 19, 2012

Scala - My Three Hours Exploration


Before we start, you can run the Scala Interpreter on Eclipse with Scala Plugin by going to Window -> Show -> Scala Interpreter then you can execute snippets of code on it.

Everything in Scala is expression. Moreover, Scala interpretation will automatically assign the proper data type for the result of an expression like the provided example below:
1 + 1
result: Int = 2

In the given, Scala determined the result of adding one to itself will be an integer.

Difference between Values and Variables:

Values (val) are expression that is once linked to an expression that will never be reassigned to another expression. It's like a variable defined with final in java
Variables (var) that are expressions that can be rebind.

val two = 1 + 1
two: Int = 2

two = 2 + 2
error: reassignment to val

var three = 2 + 1
three: Int = 3

three = 3 + 3
three: Int = 6

Function in Scala
In scala, you can create function with def:
def functionName(identify: dataType, ...) : returnType = (expression)

def addOne(m: Int): Int = m + 1
addOne: (m: Int)Int

You can use know addOne by:
val four = addOne(3)
four: Int = 3

You can also leave off parameters of function doesn’t have params. On the other hand, if the return type can also not be specified, you can try the following:
def ten() = 5 + 5
three: ()Int

ten()
Int = 10

ten
Int = 10

You can also create anonymous functions.
(identify: datatype, ..) => (expression)

(x: Int, y: Int) => x + y
(Int) => Int =

You can pass anonymous functions around or save them into vals or vars.

val add = (x: Int, y: Int) => x + y

var result= add(5,23)
result: Int = 28


If your expression is more than one line enclose it with {}. This is also true for anonymous function shown below:

def displayResult(x: Int, y: Int): Unit = {println("sum = " + (x + y))}

Scala has this new Partial Application (which is something new for me). Here you can partially apply a function with an underscore, which gives you another function:
val add2 = adder(2, _:Int)
add2:(Int) => Int =

add2(3)
Int = 5

Curried function (something new to me also)

This is a technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of function, each with a single argument which technique is present in scala by:

def multiply(m: Int)(n:Int): Int = m * n

val timesTwo = multiply(2)(_)

timesTwo(3)

In the example, multiply take in one parameters which is m and returns a function as a result, then calls this function, passing the second parameters. This function computes the value and return the final result. Let's think of it as a method with an anonymous inner class.

Making Function a Curried (in here I Curried add function)
(add(_,_)).curried

Syntax for methods that can take parameters of a repeated type:
def capitalizeAll(args: String*) = {
 args.map { arg =>
   arg.capitalize
 }
}

this is like the ellipse (..) in java

Classes

class Calculator {
 var brand: String = "HP"
 def add(n: Int, m: Int): Int = {
   n + m
 }
}

val calc = new Calculator
calc.add(1,2)
calc.brand

Class with constructor

class Calculator(var brand: String) {
 var color: String = if (brand == "HELLO") {
   "black"
 } else {
   "green"
 } //everything is scala really is an expression

 def add(n: Int, m: Int): Int = {
   n + m
 }
}

var calc = new Calculator("Cann")
calc.brand

In first line, you defined a calculator with brand as a variable member and also you defined a constructor for Calculator class accepting a String that will be the value of brand.

Inheritance on Scala

class ScientificCalculator(brand: String) extends Calculator(brand) {
 def log(m: Double, base: Double) = math.log(m) / math.log(base)
}

same in java, scala uses extends for inheritance.

Overloading methods

class EvenMoreScientificCalculator(brand: String) extends ScientificCalculator(brand) {
 def log(m: Int) = log(m, math.exp(1))
}

Traits
Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods or variables. Unlike Java, Scala allows traits to be partially implemented, i.e. it is possible to define default implementation for some method.

trait Car {
 val brand: String
}

class BMW extends Car {
 val brand = "BMW"
}

trait Similarity {
 def isSimilar(x: Any): Boolean
 def isNotSimilar(x: Any): Boolean = !isSimilar(x)
}

class Point(xc: Int, yc: Int) extends Similarity {
 var x: Int = xc
 var y: Int = yc
 def isSimilar(obj: Any) =
   obj.isInstanceOf[Point] &&
   obj.asInstanceOf[Point].x == x
}

Types
Function can also be generic and work on any type. This is like generic typing in java. Types uses square bracket like:

trait Cache[K, V] {
 def get(key: K): V
 def put(key: K, value: V)
 def delete(key: K)
}

method with types

def remove[K](key: K)

Class with type

class Stack[T] {
 var elems: List[T] = Nil
 def push(x: T) { elems = x :: elems }
 def top: T = elems.head
 def pop() { elems = elems.tail }
}

Calling a class with type

val stack = new Stack[Int]

Apply method

In Scala, any object that has an apply method can be called with the .apply omitted.

class Array{
def apply(index:Int) = {println(index)}
}

2 ways to call apply:
val a = new Array()
a.apply(7)
a(7)

Objects

Object in scale used to hold single instances of a class. (Singleton)

object Timer {
 var count = 0

 def currentCount(): Long = {
   count += 1
   count
 }
}

to call currentCount:
Timer.currentCount()

Difference between Class and Object

A class is a definition, a description. It defines a type in terms of methods and composition of other types while object is a singleton, object has no constructor (one instance on one application)

This is my first time to write about programming language and I get pleasure from it . Scala is a great and well- designed language. It’s better than java in almost all aspects (too early for my conclusion, I just employ it in 3 hours) and more fun than ruby (being playing with ruby with rails framework for almost 3 months now). I believe that the community is not that large compare to ruby or java but it’s a great language to explore. Hope to use it in real action someday.

Reference

Making your system ready for Scala (Eclipse)


Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive. Code sizes are typically reduced by a factor of two to three when compared to an equivalent Java application.

Scala is supported by major java ide, which is comprised of eclipse, IDEA and netbeans. I choose eclipse plugin because I am more familiar of it.

Steps on installing scala-eclipse plugin:
  1. In your eclipse, go to Help -> Install New Software.
  2. If you want to install the niggler build of the plugin go to this site:
choose any of the 4 update site there. I choose the For Scala 2.10 master trunk.
If you want to install the stable version of the plugin go to this site:
and choose between Scala 2.9.x support or 2.8.x support.
  1. If you are a maven user and want a better integration of maven for scala, you can use this update site:
If installation failed, you can download the maven-eclipse-scala plugin manually in this site: https://github.com/sonatype/m2eclipse-scala/downloads. I downloaded the 0.2.3 version. then install it locally through: go to Help -> Install New Software -> Add -> Archive then browser the downloaded maven-eclipse-scala .jar file then okey

Tween Eclipse

Scala IDE is a resource eater. The default resource allocated by eclipse will not be enough to make the most of Scala IDE. You will need to tween the eclipse.ini and add this codes
--launcher.XXMaxPermSize
256m
-vmargs
-Xms256m
-Xmx1024m
-XX:PermSize=64m
-Xss1M
-server
-XX:+DoEscapeAnalysis

launcher.XXmaxPermSize is the maximum PermGen size of the launcher
All values after -vmargs are arguments meant for the JVM, this means that the Minimun HEAP size is 256m and its maximum capacity is 1024m (defined by -Xms and -Xmx). The initial PermGenSize of the VM is 64m (-XX:PermSize). The size of the stack for each thread is 1m defined by -Xss. The last argument says the vm can do Escape Analysis that means that it  will only be available on servers by means of -server properties.

Options:
You can also show Heap Status by going to Preference -> General -> Check Show heap status. With this you can manually trigger GC.


Resources



Thursday, February 9, 2012

Why is Weekend so important to programmer?


Weekend is a time for programmer to do his things on his own way. 


Those two days are filled with exploration, excitement and doing things beyond what he always do on weekdays. Those are the days where he enhances his programming practice which is his codebase. Those are days where he is learning new things and formulating a simple application to showcase it. Those are days of the week that he is so true, that no one may disturb him while he is on his logical and imaginative mind.


On those days, he will do things on his way, we will make sure that every minute counts. He will read everything that catches his mind and will implement it. He will do diffucult bugs also sometimes enhance it on that day. And as that weekend close, he will never see any TO DO on his codebase.


Those days, he will go beyond his capabilities, he will push himself to create and learn new things for only forty-eight hours. Sometimes he will fail on doing it but still he is happy, because he learn again new technology and created something that has put him to what makes him original on his programming life.


On those days, he will be staying on his cave, maybe it will be a room, in the living room or maybe even in the kitchen. After forty- eight hours of meditating, he will evolve as a new man. He now has a new skill set on his sleeve, new methodology that he discovers more efficient, a new thinking that had been formulated on the two days of rumination and that novel view that programmer is never selfish, for he will be grateful to share it to the world. He knows that what he discovered on that two divine days will be of great use and not just meant on a recycle bin. Most of all, he know that if he share it to others, what he had discover on that two days will unlock more astounding designs that programmers can use.


Those are the days when the programmer rest. It‘s just that REST for programmer is doing things beyond their limits and a means to breakaway.  Rest for him is learning new things, creating and producing something valuable through them.

Sunday, January 29, 2012

Add new YUM repository Fedora

All the RPM (RedHat Package Manager) that are based linux (such as Fedora, CentOS, RHEL) use yum for software management. Yum always help you to install application through remote repository of rpms.

Yum Repository in Deeper Sense

If you want to tween yum, you can do so by editing /etc/yum.conf (I will explain the configuration next week). And by default, all the configuration of yum repository are located on /etc/yum.d and /etc/yum/repos.d dir. (defined by reposdir)

Installing RPM direct from the repo

If you know the location of an RPM on the web, you can install it by adding it’s remote repository (so RPM does not belong to any repository) just by:

        rpm -Uhv protocol://location-of-file-in-the-web

where U means upgrade; this will install the new version (if your rpm is the new version) and remove the old one.

v means verbose; this will print verbose information - error messages or warning

h means hash; this will print 50 hash marks as the package archive is unpacked.

protocol://location-of-file-in-the-web - this represent the location of your rpm to be installed on your local computer.

        rpm -Uhv http://origin-download.mono-project.com/download-stable/openSUSE_11.4/x86_64/glib-sharp2-2.12.10-27.11.x86_64.rpm

 

Installing 3rd party repository manually

Based on the example, Let’s say I wanted to add a repository where glibsharp2 is located. So first I will create a file on /etc/yum.repos.d named mono.repo (to make it more meaningful)

        cd /etc/yum.repos.d

        vi mon.repo

Then put:

        [mono]

name=mono

baseurl=http://origin-download.mono-project.com/download-stable/openSUSE_11.4/
enabled=1
gpgcheck=1
gpgkey=http://origin-download.mono-project.com/download-stable/openSUSE_11.4/repodata/repomd.xml.key

save and close it by pressing escape and :wq and enter.

where

[mono] - repository name

name=mono - repository name in more human readable string

baseurl=http://origin-download.mono-project.com/download-stable/openSUSE_11.4/ - the url of the repository, this location must include the content which is the repodata directory. This repodata contains all the information of the repo.

enabled=1 - means this repo is enabled, 0 if disabled.

gpgcheck=1 - security feature is enabled, 0 if disabled. This uses GPG key.

gpgkey=http://origin-download.mono-project.com/download-stable/openSUSE_11.4/repodata/repomd.xml.key - location of the gpg key of the repo

Sometimes you have to manually import the gpg key of the repository which is done by:

rpm --import http://origin-download.mono-project.com/download-stable/openSUSE_11.4/repodata/repomd.xml.key


If you need more information about rpm, yum and it’s configuration just:

man yum.conf

man yum

man rpm

Hope this can help you.. :)

Thursday, January 26, 2012

Branching and Merging for Git

Branching is a technique wherein you can create an active line of development for your source code. Through this, you will be able to create a separate copy of your source code  that you can edit and merge to your original or other copies (branches).

In order to create a branch named “testing” on an existing git repository:

git branch testing

This will create a branch named testing.

In order to check your local branch:

        git branch -l

To check for your remote branch

        git branch -r

To check all available branch for your repo:

        git branch -a

Example you inputted git branch -l, this will list all the branch on your local repo

        testing

        *master

The asterisk marks the branch you are currently on. For you to transfer to testing just:

        git checkout testing

For you to transfer to master again, commit your changes first for testing branch then checkout master:

        git checkout master

Therefore, the change you made on the testing branch is not visible on master.You can change then commit it.

If you are on master and you want to merge the changes of master and testing, you can do so by running:

        git merge testing

If you’re on testing:

        git merge master

Sometimes, there are conflicts on merging the two branch (conflict means you edit the same file on the same line). You can see all the file that has conflict by the use of:

        git diff

If you can’t fixed the conflict on files and decided to give up you can:

        git reset --hard HEAD

or if the change is committed use:

        git reset --hard ORIG_HEAD

If you want to delete testing branch, just execute:

        git branch -d testing

REFENCE:

http://book.git-scm.com/7_glossary.html

http://book.git-scm.com/3_basic_branching_and_merging.html

Wednesday, January 25, 2012

The Promise

I promise to myself that will be active on updating this blog. Come to think of this, I learn new things everyday which means that I must have one post per day in this blog, may it be simple or chart topping, I must journal it and post it in here. :)