mercredi 2 janvier 2013

Quick Sbt tutorial

As a beginner in Scala, I naturally began using sbt and it's very easy.

First, what is sbt? Sbt stands for Scala Build Tool. A build tool provides facility to compile, run, test, package your projects. Make, maven, ant, ivy can be included in this category. Sbt is one of them and focus mainly the Scala language.

In this post, I will show how to install sbt, setup a project, import it in Eclipse and add library dependencies.

Installation

sbt comes pre-built with several available packages for different OS : 
  • ZIP or TGZ packages
  • MSI for Windows
  • RPM package
  • DEB package
  • Homebrew or Macports for Mac
  • Gentoo emerge overlays
Or you can manually install sbt. Before, make sure that Java is installed because sbt/scala needs the JVM (Java Virtual Machine) to work. Download sbt-launch.jar and put it under a directory, for example sbt_home. Then, create a script that will launch sbt.  In windows, put the following lines the script (sbt.bat) :



In Linux,  include this line in the script:


Don't forget on Linux to make the script executable : chmod u+x sbt

Then create a variable SBT_HOME that references sbt_home directory and put it in the path.

In Linux, go to .bashrc file and adds the following lines (I presum that the sbt_home is in the home user directory) :



In windows, do the following steps :

  1. Start -> Computer- > Right-click -> System properties
  2. Click on  Advanced system settings > Advanced tab
  3. Click on Environment Variables, under System Variables
  4. Create a new variable SBT_HOME as a key, the sbt_home path directory as a value
  5. Edit the Path by adding %SBT_HOME%/sbt
  6. Ok

Create a project

We will now create a project called myfirstproject and import this project in Eclipse. 

First, create a directory myfirstproject. We will create a project layout that is similar to maven project layout. sbt uses the same directory structure as Maven for source files by default. On linux, type :



Under the same directory, create the build.sbt file. This file contains informations to build the project. For instance, the name, the version, the dependencies, the repositories and on which scala compiler this project depends on. Add the following lines :



Run sbt

To import your project to Eclipse, you must add sbteclipse to your plugin definition file. You can use either the global one at ~/.sbt/plugins/plugins.sbt or the project-specific one at PROJECT_DIR/project/plugins.sbt:

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.1")


Then run the command sbt eclipse. In Eclipse use the Import Wizard to import Existing Projects into Workspace. Make sure in Eclipse that you have the scala plugin installed or download the Scala Ide from Typesafe.

Here are some of the most common sbt commands :
  • clean Deletes all generated files (in the target directory).
  • compile Compiles the main sources (in src/main/scala and src/main/java directories).
  • test Compiles and runs all tests.
  • console Starts the Scala interpreter with a classpath including the compiled sources and all dependencies. To return to sbt, type :quit, Ctrl+D (Unix), or Ctrl+Z (Windows).
  • run * Runs the main class for the project in the same virtual machine as sbt.
  • package Creates a jar file containing the files in src/main/resources and the classes compiled fromsrc/main/scala and src/main/java.
  • help Displays detailed help for the specified command. If no command is provided, displays brief descriptions of all commands.
  • reload Reloads the build definition (build.sbt, project/*.scala, project/*.sbt files). Needed if you change the build definition.


If you find typing command very tedious for creating a new project, there is a github project called giter8 that can generate files and directories output from templates. There is a lot of templates for giter, templates for Play, scala, akka, etc. You can find more on those website : 
  • https://github.com/n8han/giter8. You will find information about how to install, use giter in the command line
  • An example to setup a akka project.  The same method can be applied with the correct template : scala-sbt
  • List of templates for giter : https://github.com/typesafehub


Hello World

Create a new scala package (com.myfirstproject) and create the file Hello.scala in this package : 


In a terminal, type sbt run on the project root directory : 


Add Dependencies

Adding dependencies in sbt is also easy. If you want  to add a dependency, for instance scalatest, edit build.sbt and add the following line : 

libraryDependencies += "org.scalatest" %% "scalatest" % "1.6.1" % "test"
sbt uses uses the standard Maven2 repository by default but if your dependency isn't on one of the default repositories, you'll have to add a resolver to help sbt find it. For instance, if you want to add spring libraries in your project, edit build.sbt

libraryDependencies += "org.springframework.scala" % "spring-scala" % "1.0.0.M1"
resolvers += "Spring Dependencies" at "https://repo.springsource.org/libs-milestone" 

Then run sbt eclipse again to update the classpath. Once done, go to Eclipse and refresh the project. 


You can find more documentation in the sbt website : http://www.scala-sbt.org/

Thanks for reading and don't forget to leave some comments!!

mercredi 13 juin 2012

An Overview of Enum in Java

When I was learning Java at my university, the java version used was 1.4. Since then, the language has evolved I had to update myself with the new features that was added to the language.One day, I passed a skill test in Java that I totally failed. One of the questions was about enums and I was always thought that the enums in C and Java were similar. I was totally wrong.

Here is what I found.

Declaring and using an enum in Java is very simple : 


It's not required to put a semicolon after the enum declaration. 

Enums can be declared as their own separate class, or as a class member, however they must not be declared within a method.  Base on our previous example, it's totally legal to create a file named Color.java and declare my enums constants in this file. We could already conclude that enums are special kind of class.

The basic component of an enum are its constants. But contrary to the language C, enums constants are not integers or Strings. In fact, the constants are objects and their type is the type of the enum declaration. Which means,  RED is an  instance of Color, as for GREEN, BLUE, etc. So, this code is completely legal : 

System.out.println(mycolor.color instanceof Color);


Think of an enum as a kind of class. Our previours code sample could be written like this (but it's not totally right) :


Notice that every constant in our enum (RED, GREEN, BLUE, etc) are instances of type Color. They are represented as static and final which in the Java world is thought of as a constant. Also notice that each enum value knows its index or position, in other words, the order in which enums values are declared matters.

Because enum is a special kind of class, you can add constructors, methods, instances variables and something really strange called specific class body.

Imagine  that we would like to represent every color in our enum with their RGB code.



The method values() is a static method that returns an array of the enum's value in the order they are declared.

Some key points about constructors :
  • You can NEVER invoke an enum constructor directly. The enum constructor is invoked automatically, with the arguments you define after the constant value. For example, RED(255,0,0) invokes the Color constructor that takes 3 int and passing the 255,0,0 literals to the constructor.
  • You can define many arguments to our constructors and you can also overload the enum constructors. 

Let's add toString() method in our enum (remember that an enum is a special kind of class in Java) and we will redefine the toString method for the white color and black color in our application. Here is the code :



Java gives us the possibility override a method defined in the enum for a particular constant. It's like an anonymous inner class and it's called a specific class body. In our example, the WHITE and BLACK constants overrides the toString() method.


vendredi 14 octobre 2011

Ssh to VirtualBox

Hello, 

If you always ask yourself how to make an ssh connection to a virtualbox guest OS, this tutorial is for you. 

As you may know, VirtualBox supports NAT (Network Address Translation) as default networking mode. A virtual machine with NAT enabled acts  much like a real computer that connects to the Internet through a router. The "router", in this case, is the VirtualBox networking engine, which maps traffic from and to the virtual machine transparently. The disadvantage of NAT mode is that, much like a private network behind a router, the virtual machine is invisible and unreachable from the outside internet; you cannot run a server this way unless you set up port forwarding (described below). 

So our goal, in this to tutorial is to make virtualbox forward all the packets arriving to a certain port of the Host machine. For instance, any connection that arrives at a given TCP port (i.e. 2222) of the Host machine, will be forwarded to the TCP port 22 of the Guest Machine.

This tutorial is divided in 2 steps : 
  1. In the first step, you gonna make sure that we have a ssh server running on the guest operating system, otherwise we must install one. 
  2. In the second we are going to set up port forwarding in virtualbox.

For my experience, I used Windows 7 is the hosting system and Linux Mint as a guest. 


Let's go to the first step. We are going to make sure that ssh is already running on our guest operating system otherwise we must install the package openssh-server on the guest operating system. The process of installing a package on Linux Mint is similar in Ubuntu (or Debian) with the command : apt-get install openssh-server.

After installing the server, we are going to make some basic configuration. For that, go to the directory /etc/ssh and edit the file sshd_config (must have root access). This file contains all the configuration of our ssh server. Go the line that begins with 'PermitRootLogin'. 'PermitRootLogin' gives the possibility to connect to the server with a root user account. By default, this line is set to yes but change it to no if you dont want this possibility.


Then, launch the server with the following command : sudo service ssh start.

The second step is to enable port forwarding on the virtualbox machine. There is to 2 ways to do that : with the GUI or the commanline. But before we get into that, we must turn off the guest machine otherwise it won't work. 

If you want to use the gui, you must follow this steps : 
Open virtualbox main interface and selects your guest operation system. Mine is named mint.     
  1. Go to the network tab and selects Advanced -> Port Forwarding.
  2. Create a new rule by giving a name (ssh), a protocol (TCP), a host IP (if necessary), the host port (2222), the guest IP (also if necessary) and the host IP (22).
  3. Then save

If you want to do it with the command line, Virtualbox shifts with a command utility called VBoxManage. On windows 7, this command is on the directory C:\Program Files\Oracle\VirtualBox. You can use Windows PowerShell as a terminal and change directory by typing the cd command : cd ../../Program Files/Oracle/VirtualBox

Choose the VirtualBoxManage.exe file and type the following command :

VBoxManage.exe modifyvm "VM name" --natpf1 "ssh,tcp,,2222,,22" 

With the above command, all TCP traffic arriving on port 2222 on any host interface will be forwarded to port 22 in the guest. The protocol name tcp is a mandatory attribute defining which protocol should be used for forwarding (udp could also be used). The name ssh is purely descriptive and will be auto-generated if omitted. The number after --natpf denotes the network card, like in other parts of VBoxManage.


 Now you can relaunch your guest operating system and make sure that the ssh service is running. For isntance, you can execute the command : ps aux | grep sshd. 


If your host is a Linux machine,  you can execute the following commands  to connect to the guest OS:


ssh -l -p 2222 localhost 


or 


ssh -l -p 2222 aa.bb.cc.dd


aa.bb.cc.dd is the host IP address.


Since I am using windows, I had to download putty and puttygen and make some configuration. First, you must generate a pair of key (private/public) with puttygen. Launch puttygen and then click to the button Generate. You can also add a passphrase (not required) if you want. Copy/Paste the generated key in a txt file and saves it as client_id_dsa.pub. (the filename doesn't matter but his extension must be .pub).


Launch putty and go to the ssh category and next go to the auth category. And then upload your key (client_id_da.pub).


Then go in the Session section. And enter as hostname (or IP) : 127.0.0.1 and port 2222. Then open the connection. 


Tadaaa !!!


You can follow the same process to install other services like a web/ftp/pop/imap server, or a scm (source code management like SVN, git, bazaar), etc


Thanks for reading and don't forget to leave some comments!!


   












  




lundi 5 septembre 2011

Linux : 20 years already

For the 20 year anniversary of Linux, I decided to post 2 images that show the story and the evolution of Linux in the recent years.

lundi 15 août 2011

A Google+ joke


Retourner une valeur à partir d'un Thread

L'interface Runnable existe depuis le début de la plateforme Java et permet de créer des threads. Cette interface propose la méthode run qui ne prend aucun argument et ne retourne aucune valeur. Si on doit récupérer le résultat de calcul ou de l'exécution d'un thread, il faudrait passer par une classe intermédiaire et attendre la fin du thread pour récupérer le résultat. Par exemple :


Depuis Java 5, cela devient encore plus facile avec  l'interface Callable.  Cette interface est identique à Runnable sauf qu'elle définit la méthode call().

Cette méthode diffère de  run() en 2 points : elle peut retourner une valeur et peut lever une exception : 




Pour lancer un Callable, il faut passer l'objet Callable à un ExecutorService via la méthode submit dont voici la signature :



Comme l'implémentation des ExecutorService exécutent généralement leurs tâches de façon asynchrone, la méthode submit ne peut pas retourner le résultat de la méthode call. Elle retourne plutôt un objet de type Future qui est paramétré par le type du résultat du callable. L'objet Future est simplement une promesse de résultat dans le futur. 
 
La méthode get() de l'objet Future renvoie le résultat et sera bloqué jusqu'à ce que la tâche soit terminée. Cette méthode est équivalente à un join().
Imaginons un programme qui lance des objets Callable convertissant un String en majuscule. Voici le code : 


Chaque objet de type  StringCallable reçoit un String en paramètre et renvoie sa conversion en majuscule via la méthode call. On passe cet objet à un  ExecutorService via la méthode submit qui renvoie un objet de type Future. Pour récupérer le résultat, on utilise la méthode get().

Dans cet exemple, on a utilisé un ExecutorService pour lancer un Callable mais n'importe quel Executor fera l'affaire. Pour plus d'informations sur les Executors, je vous invite à visiter  cette page.