6.9 Java Extensions

This article will guide you through the process of writing and compiling your own Java server side extensions for SmartFoxServer 1.4 or higher.
All you need to get started is the Sun JDK (Java Development Kit), your favorite Java editor and, of course, SmartFoxsServer installed on your local machine.
In this tutorial we will also guide you to setup the Eclipse and NetBeans IDE. (Integrated Development Environment)

This is the list of topics addressed in this article

» The Basics

If you are familiar with Java web application development you could think of server extensions as servlets managed by a container (SmartFoxServer) which passes client requests and fires events to your custom server code.In other words, a server side extension is a fully fledged Java application that responds to specifc server calls and can integrate with any other libraries and frameworks to perform its job (including database access, ORMs, webserver interaction, etc...)

Similarly to the servlet methods doGet() and doPost(), an extension is expected to extend a base class and override two main methods called handleRequest() and handleInternalEvent().
The former is responsible for dealing with any custom extension request sent by the client while the latter handles asynchronous events fired internally by the server. These events provide notifications about important changes happening in the server such as the removal of a room, the disconnection of a user etc...

Server extensions can be plugged at two different levels, Zone level and Room level. If you are not familiar with this concept you should read the "Extension Architecture" document found at chapter 6.2 of the documentation.

^top

» The extension base class and the overridable methods

Every Java Extension is expected to extend the AbstractExtension base class found in the it.gotoandplay.extensions.examples package. (You can consult the javadocs for further details)
The following is a list of methods that your class should override:

method signature description
void init() called as soon as the extension is activated
void destroy() called when shutting down the extensions
void handleRequest(String cmd, ActionscriptObject ao, User u, int fromRoom) handles a request in XML format
void handleRequest(String cmd, String params[], User u, int fromRoom) handles a request in Raw format
void handleRequest(String cmd, JSONObject jso, User u, int fromRoom) handles a request in JSON format (only for SmartFoxServer 1.5.0 or higher)
void handleInternalEvent(InternalEventObject ieo) handles an internal server event
Object handleInternalRequest(Object o) (optional) handles communications with other objects / extensions / servlets (Since SmartFoxServer 1.6)

^top

» Simple extension code

The following code example shows the implementation of a basic server extension:

import java.nio.channels.SocketChannel;
import java.util.*;

import it.gotoandplay.smartfoxserver.db.*;
import it.gotoandplay.smartfoxserver.data.*;
import it.gotoandplay.smartfoxserver.exceptions.*;
import it.gotoandplay.smartfoxserver.extensions.*;
import it.gotoandplay.smartfoxserver.lib.ActionscriptObject;
import it.gotoandplay.smartfoxserver.events.InternalEventObject;

import org.json.JSONObject; 

public class ExtensionTemplate extends AbstractExtension
{

	public void init()
	{
		trace("Extension initialized");	
	}

	public void destroy()
	{
		trace("Extension destroyed");
	}

	public void handleRequest(String cmd, ActionscriptObject ao, User u, int fromRoom)
	{
		// Your code here, handles XML-based requests
	}
	
	public void handleRequest(String cmd, JSONObject jso, User u, int fromRoom)
	{
		// Your code here, handles JSON-based requests
	}
	
	public void handleRequest(String cmd, String params[], User u, int fromRoom)
	{
		// Your code here, handles String-based requests
	}

	public void handleInternalEvent(InternalEventObject ieo)
	{
		// Your code here, handles server events
	}
	
	public void handleInternalRequest(Object param)
	{
		// (Optional) Your code here, handles an internal request
	}
	
}

^top

» Java Extensions Examples

Bundled with any installation of SmartFoxServer PRO you will find a number of extensions examples that you can study.
The examples sources are found in {your-sfs-installation-path}/Server/javaExtensions/ folder, under the it.gotoandplay.smartfoxserver.extensions.examples package:

^top

» External libraries dependencies

Compiling your Java extensions requires that you include a few references to provided .jar files in your classpath.
All the necessary libraries are located in the {your-sfs-installation-path}/Server/lib/ folder.

Depending on the SmartFoxServer version you are using, these are the libraries to inlcude:

^top

» Compiling the extension using javac

Supposing that your extension source is located in the Server/javaExtensions/ folder and you're using version 1.6.x, this is what you should type in your shell/terminal window:

javac -classpath "../lib/jysfs.jar:../lib/json.jar:../lib/json-lib-2.1-jdk15.jar" MyJavaExtension.java  

NB: the classpath separator ":" (colon) is valid for all Linux/Unix (including MacOS X) operating systems. Under Windows you should use ";" (semicolon)

^top

» Setting up the Eclipse IDE

Using a Jave IDE like can boost your productivity thanks to code completion, code templates, automated project building and deployment and more.
The following is a visual walkthrough that will guide you in the setup of the Eclipse IDE and the creation of a SmartFoxServer extension.

Assuming you already have installed Eclipse, let's go ahead and launche the IDE.
Click on File > New > Project in order to create a new Java project:

step01

Select Java Project and click Next

step20

Give a name to the project (e.g. "MyExtension") and in the "Project layout" make sure to select "Create separate source and output folder".
This will create two different directories for your source and compiled files.
Let's go ahead by clicking "Next"

step03

The Java Settings window contains a set of sub panels where you can configure all the details of your project. Click on the "Libraries" tab and on the "Add External JARs..." button. This will open a dialogue box where you can add additional libraries for your project.

step4

Navigate your file system and reach the SmartFoxServer installation folder. From there move to the Server/lib/ directory and select both jysfs.jar and json.jar by holding the CTRL key (Windows/Linux) or Command key (Mac) .

(NB: if you're using SmartFoxServer prior to version 1.5 you only need to select Server/lib/smartfoxserver.jar)

step5

Click Finish to create the project and make sure your Package Explorer is open.
(You can toggle it from Window > Open perspective > Java)
We can now create our first class in the project which will be the main extension class: right click the "src" folder and select New > Class

step6

In the "New Java Class" dialogue box we specify the package name ("test") and the class name ("MyExtension")
Go ahead and click "Finish"

step7

The class is now ready. You can write your code and take advantage of the powerful features of Eclipse.
By default your class will be auto-compiled in the bin/ folder of your project each time you save the source.

step8

^top

» Setting up the Netbeans IDE

The following is a visual walkthrough that will guide you in the setup of the NetBeans IDE and the creation of a SmartFoxServer extension.
Let's start with the creation of a new project. Select File > New Project... from the main menu.

step 1

In the dialog window that appears we choose Java from the Categories list and click on Java Application and click Next

step 2

In the next screen we specify the name of the Project and click Finish to conclude the operation.

step 3

The project has been successfully created and it's now visible in the Project's tree.
Click the project name to collapse the the main node, right-click the Libraries icon and click on Add JAR/Folder...

step 4

Now we're going to specify the dependencies that should be reference by our project.
Navigate your local disk to {your-sfs-installation-path}/Server/lib/ and multiple select the files as show in the picture below.
(You should keep the CTRL key pressed to select multiple files under Linux and Windows, use Command under MacOS X)

step 5

Finally we can create the Extension class. Right-click on the package icon and select New > Java Class

step 6

In the dialogue box type the name of the Extension class and click on Finish to close the wizard.

step 7

The class should have been created and opened in the Java editor. You're now able to use the auto-complete features. In the picture below we make the class extend the it.gotoandplay.smartfoxserver.extensions.AbstractExtension class.

step 8

Finally we get the the "stub methods" auto-created for us by the IDE by clicking the lamp icon on the left of the editor.

step 9

^top

» Deploying the extension

There are a few options that you can choose for deploying your Java extension:

» SIMPLE: use the javaExtensions/ folder:
You can simply copy your classes (including the packages folder structure) to the javaExtensions/ folder. This folder is already added to the standard server classpath so you don't need to add it yourself.
Your classes will be immediately available to the server, you just need to add an <extension/> definition to your Zone in the config.xml file.

» ADVANCED: Point the server classpath to your class/jar files:
Another option is to create a .jar archive of your class files and copy it in one of the server folders.
We suggest to always use the Server/javaExtensions/ folder for your custom Java extensions and the Server/lib/ folder for additional libraries.

Adding your .jar files to the classpath can be done in two different ways, depending on the way you're running the server:

Standalone:
just edit your start.bat (Windows) or start.sh (Linux / Unix / MacOS X)

Service / Deamon:
Open the wrapper.conf file inside the Server/conf/ folder and add a new classpath entry. (Windows / Linux / Unix)
(This doesn't apply to MacOS X. Just use the "standalone" method.)

^top

» Reloading Extensions at runtime

SmartFoxServer PRO allows you detect class changes at runtime and reload your server-side code on the fly. In order for this feature to work there are a few things you should setup.

NOTE: Dynamic reloading does not work outside of the javaExtensions/ folder and does not support .jar files

^top

» More resources

Where to go next?
We recommend to experiment with the provided example extensions and to inspect the javadoc which provides a reference to the server side classes.
In particular the ExtensionHelper class which is the main entry point to the server side API.
For further reference you can also check the introductory articles and the extension template provided in this same section of the documentation.

Finally here follows a of list additional resources you might be interested into:

 


doc index