Pivotal GemFire Function Service and Scala

Yes Pivotal GemFire functions can be written in Scala. Pivotal GemFire Functions are described here
I am not going to write all the details about function Service. Since Scala is inter operable with Java, One can easily write Pivotal Gemfire functions in Scala and they will work as you wrote the functions in Java

Following is the Scala implementation of the MultiGetFunction taken from Function Service.

Step 1 : Write a Java wrapper around Gemfire Function Interface like below

package pivotal.scala.wrapper.functions;

import com.gemstone.gemfire.cache.execute.FunctionAdapter;
import com.gemstone.gemfire.cache.execute.FunctionContext;

public abstract class ScalaFunctionAdapter extends FunctionAdapter {    
  @Override
  public void execute(FunctionContext arg0) {
    executeScalaWrapper(arg0);
  }
  @Override
  public String getId() {
    return getIdScalaWrapper();
  }
  public abstract String getIdScalaWrapper();    
  public abstract void executeScalaWrapper(FunctionContext arg0);    
}

Step 2: Implement this interface in Scala , for example like below

package scala.gemfire.quickstart

import scala.collection.JavaConversions._
import com.gemstone.gemfire.cache.execute.FunctionAdapter
import com.gemstone.gemfire.cache.CacheFactory
import com.gemstone.gemfire.cache.execute.RegionFunctionContext
import com.gemstone.gemfire.cache.Region
import com.gemstone.gemfire.cache.Declarable
import com.gemstone.gemfire.cache.execute.FunctionContext
import com.gemstone.gemfire.cache.partition.PartitionRegionHelper
import pivotal.scala.wrapper.functions.ScalaFunctionAdapter

class MultiGetFunction extends ScalaFunctionAdapter {

  def getIdScalaWrapper: String = this.getClass.getName

  def executeScalaWrapper(fc: FunctionContext): Unit = {
    fc match {
      case frc: RegionFunctionContext => {
        val context = frc.asInstanceOf[RegionFunctionContext]
        val keys = context.getFilter()
        var keysTillSecondLast = new scala.collection.mutable.HashSet[Any]()
        keysTillSecondLast.addAll(keys.take(keys.size - 1))
        keysTillSecondLast.foreach { key =>
          context.getResultSender().
            sendResult(PartitionRegionHelper.
              getLocalDataForContext(context).get(key));
        }
        context.getResultSender().
          lastResult(PartitionRegionHelper.
            getLocalDataForContext(context).get(keys.last));
      }
      case _ => {
        fc.getResultSender().
          lastResult(Runtime.getRuntime().freeMemory() / (1024 * 1024));
      }
    }
  } 
}

Step 3 : Build code using sbt ( Java Wrapper + Scala Implementation of the functionAdapter)
Step 4: Use the built jar as a Function Execution code in java project.
Step 5: Note to add scala-library.jar in the classpath, sbt assembly combine all the deps but I have not tried that yet.

Advertisements