Sunday, November 23, 2014
This article provides a quick introduction to Scala programming language.

What is Scala?

  • Scala is acronym for "Scalable Language".
  • Scala integrates object-oriented and functional language concepts.
  • Scala is often referred to as object-functional programming language.
  • Scala source code gets compiled to Java byte-code and runs on the Java Virtual Machine (JVM).
  • Java and Scala classes can be easily mixed. Java libraries can be used in Scala code and vice versa.
  • Scala design decisions have been made to address some of the shortcomings of Java.
  • Scala can also run on Android.

Hello Scala

Let us quickly jump into our first Scala program.

object SayHello {
  def main(args: Array[String]) {
    println("Hello");
  }
}

To compile this program use scalac, the Scala compiler. This is similar to using "javac" for Java programs.
scalac SayHello.scala

To run this program use scala command. This is similar to using "java" command for Java programs.
scala -classpath . SayHello

Refer to Quick Start with Scala for Scala installation steps.

Some of the obvious differences to a Java programmer when looking at this Scala program:
  • Scala doesn't require semicolons to end statements.
  • Scala uses object keyword to create singleton objects. There is no class declaration or a static declaration. Scala doesn't have static variables or methods.
  • Scala needs def keyword to precede function definitions.
  • Scala doesn't need an explicit access modifier and by default visibility is public. 
  • In Scala parameter types follow the variable name unlike Java.

Java interaction

Let us look at our second example where we use Java libraries inside our Scala code. In this example, we print the current date using java.util.Date.

import java.util.Date

object UseJavaAPI {
  def main(args: Array[String]) {
    var today = new Date
    println(today toString)
  }
}

Some of the obvious differences to a Java programmer when looking at this Scala program:

  • Scala uses var keyword to declare variables.
  • Scala supports variable type inference based on the value assigned to it. In this example, we have not specified the type for variable "today" and is inferred to be Date type based on the value assigned. Also it is important to note that Scala is a statically typed language.
  • Scala has syntactic flexibility. For example, to invoke toString() function on variable today as "today.toString()" it would suffice to write "today toString".
There are several other interesting features in Scala which we explore in rest of the articles. These include:
  • Type inference
  • Lazy evaluation
  • Functions are objects
  • Mixin based composition
  • Traits
  • Closures
  • Tuples
  • Higher order functions
  • Currying
  • Nested functions
  • etc.
Hope this article gives a short introduction to understand basic Scala programs. Proceed to read other other Scala tutorials.

Sunday, November 16, 2014
This article provides a quick start with Scala and to enables to write your first program with Scala. 

Scala Installation

Scala Pre-requisites

To install the Scala software distribution we need Java run-time version 1.6 or higher. You can check this using "java -version" from the command line.

C:\Users\mad>java -version
java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)

Upgrade Java if needed from this link.

Scala Binaries

Download the Scala binaries from this link. For Windows it is a MSI installer package and pretty straightforward to install. For other platforms download and unpack the archive. For quick access add scala (Scala Interpreter) and scalac (Scala Compiler) to the path settings.

For Windows,
set SCALA_HOME=C:\Installs\scala
set PATH=%PATH%;%SCALA_HOME%\bin

For Unix,
export SCALA_HOME=/usr/installs/scala
export PATH=$PATH;$SCALA_HOME/bin

Scala IDE for Eclipse

The easiest way to get started with Scala and be productive is to use Scala IDE for eclipse. Download and install the eclipse bundle from this link for the required Scala version.

Scala First Program

There are several approaches to write you first program. (1) Using the Scala interactive shell (2) Using compile and execute and (3) Using Eclipse IDE.

Using the Scala interactive shell

Simply open the interactive shell by typing the command "scala" from the command line. Enter the commands below interactively to execute your first program.

C:\Users\mad>scala
Welcome to Scala version 2.11.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.

scala> object Hello {
     | def main(args: Array[String]) {
     | println("Hello")
     | }
     | }
defined object Hello

scala> Hello.main(null)
Hello

scala> :q

Using compile and execute

Create a file with the following contents and name it "SayHello.scala".

object SayHello {
    def main(args: Array[String]) {
    println("Hello");
  }
}

Now compile the program using scalac the Scala compiler and execute using scala command. The scala compiler works similar to the java compiler and generates class files in the current directory.

C:\Users\mad>scalac SayHello.scala

C:\Users\mad>scala SayHello
Hello

Using the Scala Eclipse IDE

Using the Scala Eclipse IDE Create a Scala project using "File -- New -- Scala Project" in the IDE.


One Scala project is created select the SayHello project in IDE and Create a new Scala object using "File -- New -- Scala Object".


Enter SayHello program listing below and do RunAs -- Scala Application to generate the output.


Congratulations you are done with your first Scala program. Proceed to read other Scala Tutorials.
Saturday, October 25, 2014

Java RMI Introduction

Java Remote Method Invocation (RMI) enables remote communication between programs running across different Java Virtual Machines (JVM). RMI essentially allows an object running in one JVM to invoke a method on another object running in a different JVM. Java RMI provides the ability to write distributed objects in a simple and secure manner with the power of passing complete objects as arguments and return values.

Java RMI applications typically have a client and server. A server program binds the remote objects via registry and makes it accessible by clients. The client program typically does a look-up for the remote objects in the registry, obtains a remote object reference and perform a method call on the remote object. RMI is the mechanism which the server and client use to exchange the information.

Java RMI Application Architecture
Some of the key Java interfaces and classes necessary to understand and build an RMI application are listed below.
  • java.rmi.Remote - Marker interface that needs to be extended directly or indirectly by a remote interface. Refer to Java RMI Interface Example below.
  • java.rmi.RemoteException - Superclass of all exceptions thrown by the RMI runtime during the remote method invocation.
  • java.rmi.server.UnicastRemoteObject - Provides the server function and provides a singleton remote object.
Note: To use this application invoke the rmiregistry application which is a simple bootstrap nameserver that comes with the Java distribution.

Java RMI Interface Example

First step in a RMI application is to design the remotely accessible part of the application from another Java virtual machine. This is achieved by extending the java.rmi.Remote interface. In this example we define a simple interface with a single method to be invoked over RMI.

package com.sourcetricks.intf;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface ComputeIntf extends Remote {
 int doubleThis(int input) throws RemoteException;
}

Java RMI Server Example

To implement a RMI server the remote object usually extends the UnicastRemoteObject and implements the remote interface we have defined earlier. Then we create a Registry instance and then bind the remote object reference to a specific name which can be accessed by client program over RMI.

package com.sourcetricks.server;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import com.sourcetricks.intf.ComputeIntf;

public class RmiServer extends UnicastRemoteObject 
implements ComputeIntf {
  
  private static final long serialVersionUID = 1L;
  
  protected RmiServer() throws RemoteException {
    super();
  }

  @Override
  public int doubleThis(int input) throws RemoteException {     
    return (input * 2);   
  }

  public static void main(String[] args) {
    try {
      // Name to be used in the registry
      String name = "ComputeEngine";
      
      // The remote object
      RmiServer engine = new RmiServer();
      
      // Creates and exports a Registry instance on  
      // the local host that accepts requests on the 
      // specified port.
      Registry registry = LocateRegistry.createRegistry(3500);
      
      // Replaces the binding for the specified name 
      // in this registry with the supplied remote ref. 
      // If there is an existing binding for the specified 
      // name, it is discarded.
      registry.rebind(name, engine);
      
      System.out.println("RmiServer bound");
        
    } catch (Exception e) {
        System.err.println("RmiServer exception:");
        e.printStackTrace();
    }
  }
}

Java RMI Client Example

Writing an RMI client application to access a remote object is simple. In the example below we locate the remote object registry on a specified port. We look-up the registry with the specific name and get a reference to the remote object. Then we invoke the remote method similar to a local method and the invocation happens over RMI.

package com.sourcetricks.client;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import com.sourcetricks.intf.ComputeIntf;

public class RmiClient {

  public static void main(String args[]) {
    try {
      String name = "ComputeEngine";
      
      // Returns a reference to the the remote object
      // Registry for the local host on the specified
      // port.
      Registry registry = LocateRegistry.getRegistry(3500);
      
      // Returns the remote reference bound to the  
      // specified name in this registry.
      ComputeIntf comp = (ComputeIntf) registry.lookup(name);     
      
      System.out.println(comp.doubleThis(10));
      
    } catch (Exception e) {
      System.err.println("RmiClient exception:");
      e.printStackTrace();
    }
  }   
}

Java RMI References

Saturday, October 18, 2014

Java Messaging Service (JMS) Introduction

Java Messaging Service (JMS) provides a mechanism for applications to create, send and receive messages using reliable, asynchronous and loosely coupled communication. JMS is defined as part of the Java Enterprise Edition.

JMS supports two messaging models, point-to-point model and the publish subscribe model. In the point to point messaging model we have a message queue and there is one consumer for the messages, but there could be multiple producers writing to the message queue. The publish subscribe message model is more like a bulletin board where there could be multiple consumers for a message. JMS client address messages to a Topic.

Some of the common terminology used with JMS applications is listed below.

  1. JMS Provider The underlying messaging system that implements the JMS APIs and supports the administrative and control features. ActiveMQ is a JMS Provider.
  2. JMS Client An application that produces or consumes messages.
  3. Message Objects used for communication between JMS clients.
  4. Administrative Objects Preconfigured objects like connection factories and destinations that are created by an administrator and used by clients.

ActiveMQ Introduction and Configuration

ApacheMQ is a popular and powerful open source messaging provider and fully supports the JMS API specifications. There are several other JMS providers including Oracle Weblogic, WebSphere MQ from IBM, OpenJMS to name a few. For the purpose of this tutorial we will use ActiveMQ as the JMS provider.

Installation and configuration of ActiveMQ is pretty simple.
  1. Download binary release for the specific platform from this link http://activemq.apache.org/.
  2. Unzip the downloaded file to a specific folder.
  3. Start ActiveMQ using the below command on a terminal window.
  4. C:\Installs\ApacheMQ\bin\activemq start
    
  5. Test if ApacheMQ is running correctly by checking if it is listening on port 61616.
  6. C:\Users\dummy>netstat -an | find "61616"
      TCP    0.0.0.0:61616    0.0.0.0:0     LISTENING
      TCP    [::]:61616       [::]:0        LISTENING
    
  7. ApacheMQ can be monitored through the Web Console using this url http://localhost:8161/admin. Username and password is admin/ admin.

JMS Producer Example

In the JMS Producer application we use a ActiveMQ connection factory object to create a Connection to the underlying messaging system. Then we create a context for sending messages using the Session object. Then we create a Topic instance to get publish and subscribe behavior. MessageProducer is used for sending messages.

Note. Include "activemq-all-5.10.0.jar" available in the ActiveMQ installation directory as an external jar to the JMS Producer project.

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;

public class PublisherMain {
  
  public static void main (String[] args) {

    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    
    try {     
      // Get a connection for sending messages
      connectionFactory = new ActiveMQConnectionFactory();
      connection = connectionFactory.createConnection();
      connection.start();
      
      // Create a session
      Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
      
      // Create a topic and send messages
      Topic topic = session.createTopic("test1");
      MessageProducer producer = session.createProducer(topic);
      while ( true ) {
        TextMessage message = session.createTextMessage();
        message.setText("This is a test JMS Message");
        producer.send(message);
        Thread.sleep(10000);
      }
    } catch (JMSException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    finally {
      try {
        connection.close();
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
  }
}

JMS Consumer Example


In the JMS Producer application we use a ActiveMQ connection factory object to create a Connection to the underlying messaging system. Then we create a Session context and subscribe to the topic. MessageConsumer is used for receiving messages.

Note. Include "activemq-all-5.10.0.jar" available in the ActiveMQ installation directory as an external jar to the JMS Consumer project.

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Message;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ListenerMain {
  
  public static void main(String[] args) {
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    try {
      // Get a connection for receiving messages    
      connectionFactory = new ActiveMQConnectionFactory();
      connection = connectionFactory.createConnection();
      connection.start();
      
      // Create a session
      Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
      
      // Create a topic and subscribe
      Topic topic = session.createTopic("test1");       
      MessageConsumer consumer = session.createConsumer(topic);
          
      // Receive the messages and print
      while ( true ) {
        Message message = consumer.receive();
        
        if (message instanceof TextMessage) {
              TextMessage textMessage = (TextMessage) message;
              System.out.println("Received message: "
                      + textMessage.getText());
        }
      }
    } catch (JMSException e) {
      e.printStackTrace();
    }
    finally {
      try {
        connection.close();
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
  }
}

This program produces the following output.

Received message: This is a test JMS Message
Received message: This is a test JMS Message
Received message: This is a test JMS Message
Received message: This is a test JMS Message

Read other Java tutorials from here.

Contact Form

Name

Email *

Message *

Back to Top