Archive

Archive for the ‘Grizzly’ Category

Grizzly Deployer was adopted (almost) by Akka

August 8th, 2010 No comments

Just to let you know that Grizzly Deployer was adopted (almost) by another framework : Akka.

Since May 22, 2010, viktorklang is working in a branch : deployer. here the description in the commit “Starting to add Deployer [viktorklang]”

You can browse the code on github : http://github.com/jboner/akka/tree/deployer/akka-core/

I hope to see that included in a next release.

You can follow me on Twitter

Categories: Grizzly Tags: , ,

Grizzly Deployer was adopted by Atmosphere

August 8th, 2010 No comments

Just to let you know that Grizzly Deployer was adopted by another framework : Atmosphere.

Since Atmosphere-0.6, Grizzly Deployer is in the module : spade-server

To launch Atmosphere application you could use Grizzly Deployer or use Atmosphere-Spade-Server (that used Grizzly Deployer under the hood).

You can browse the changes on github : http://github.com/Atmosphere/atmosphere/tree/master/extras/spade-server

I did the commit under the name “Unknown” :) It was my first git commit.

You can follow me on Twitter

Grizzly Deployer (1.9.19) new features

August 7th, 2010 No comments

It has been a while since a blog about Grizzly, I was too busy adding new features. The Grizzly Deployer’s community grows and requested theses new features.

Here a quick list of the changes :

  • Websockets support
  • Watch folder
  • Can starts without applications to deploy
  • Can be embedded and extended easily
  • and few bug fixes (thanks to the community)

A little overview or remainder of what is Grizzly Deployer

Grizzly Deployer is a bundle of Grizzly project that act as a web container. It will allow you to deploy applications (war, servlet).
Works fine for Comet, Atmosphere, JSP applications … For more details, I suggest this link Introduction to the first release of Grizzly Deployer

First, lets take a look at the command line parameters.


Usage: com.sun.grizzly.http.servlet.deployer.GrizzlyWebServerDeployer

  -a, --application=[path]    Application(s) path(s).

                              Application(s) deployed can be :
                              Servlet(s), war(s) and expanded war folder(s).
                              To deploy multiple applications
                              use File.pathSeparator

                              Example : -a /app.war:/servlet/web.xml:/warfolder/

  -p, --port=[port]           Runs Servlet on the specified port.
                              Default: 8080

  -c, --context=[context]     Force the context for a servlet.
                              Only valid for servlet deployed using
                              -a [path]/[filename].xml

  --dontstart=[true/false]    Won't start the server.
                              You will need to call the start method.
                              Useful for Unit testing.
                              Default : false

  --libraryPath=[path]        Add a libraries folder to the classpath.
                              You can append multiple folders using
                              File.pathSeparator

                              Example : --libraryPath=/libs:/common_libs

  --autodeploy=[path]         AutoDeploy to each applications.
                              You could add JSP support.
                              Just add a web.xml that contains Jasper

                              Example : --autodeploy=/autodeploy

  --webdefault=[path]         webdefault to be used by all applications, can be file or dir with multipe web.xmls.
                              If you want to add only one webdefault point it to web.xml file,
                              If you want multiple files to be included put them in one dir and provide this location here.

                              Example : --webdefault=webdefault.xml

  --cometEnabled=[true/false] Starts the AsyncFilter for Comet.
                              You need to active this for comet applications.
                              Default : false

  --websocketsEnabled=[true/false] Starts the AsyncFilter for Websockets.
                              You need to active this for websockets applications.
                              Default : false

  --forceWar=[true/false]     Force war's deployment over a expanded folder.
                              Will deploy the war instead of the folder.
                              Default : false

  --ajpEnabled=[true/false]   Enable mod_jk.
                              Default : false

  --watchInterval=[seconds]   Watch interval to scan for new applications to deploy in work folder.
                              Default : -1 ; disabled

  --watchFolder=[path]        Folder to scan for new applications to deploy in work folder
                              Default : none

Websocket support

The first feature added was Websockets support. It can be enabled at command line by using the parameter –websocketEnabled=true . That will allow you to deploy Websocket applications.

Watch folder

This feature is interesting, because most of the web container have it. Grizzly Deployer will watch a specific folder to applications to deploy. When this feature was added, I remove the need to specify a application to deploy by command line.
To enable this feature you need to use the command line parameter –watchFolder=[path]. It can be used with this other parameter : –watchInterval=[seconds].

The parameter –watchInterval is used to create a watchdog that will monitor the watch folder. If the parameter –watchInterval is not present, when Grizzly Deployer starts, it will check
all applications that are in the watch folder at launch time and will deploy them, but it won’t monitor the folder after that.

When both of theses parameters are used, it will create a watchdog that will deploy and undeploy application put in the watch folder, and remove from that folder. If you deploy an application at command line and put another application with the
same context name in the watch folder, the application in the watch folder won’t be deploy twice.

Embedded Grizzly Deployer

Grizzly Deployer could already be embedded trough his API, but we got few feedback about to make it simplier. The problem wasn’t the API, it just that most people will only use the main part of Grizzly Deployer : deploy a war.

So to make it easier and faster to implement, I did a little refactoring. We now have 2 main config classes we could use to launch an Embedded Grizzly Deployer : DeployerServerConfiguration and DeployableConfiguration.

DeployerServerConfiguration

That file is used to launch Grizzly Deployer. It contains the same command line parameters. In fact, at runtime, the command line parser use that classe.


    GrizzlyWebServerDeployer deployer = new GrizzlyWebServerDeployer();

    DeployerServerConfiguration conf = new DeployerServerConfiguration();
    conf.cometEnabled = true;
    conf.watchFolder="C:/temp/webapps/";
    conf.watchInterval=15;
    deployer.launch(conf);

Once grizzly Deployer is launched in your application, you can deploy a war later. For that, you use this class : DeployableConfiguration.


    DeployableConfiguration warConfig = new DeployableConfiguration();
    warConfig.location = "C:/temp/webapps/grizzly-jmaki.war";

    deployer.deployApplication(warConfig);

You can follow me on Twitter.

Categories: Grizzly, Web Tags: , , ,

GWS Deployer 1.9.17 : Reloaded : New Features Part 3 : PHP Support

May 24th, 2010 No comments

In a previous post : PART2 I describe how to run JSP over Grizzly. Now I’ll show you how to run PHP over Grizzly.

here a sample web.xml file for PHP support. (I’m using Quercus, but you could use native PHP too).

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE web-app    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>  <description>Caucho Technology's PHP Implementation</description>

  <servlet>    <servlet-name>Quercus Servlet</servlet-name>    <servlet-class>com.caucho.quercus.servlet.QuercusServlet</servlet-class>  </servlet>

  <servlet-mapping>    <servlet-name>Quercus Servlet</servlet-name>    <url-pattern>*.php</url-pattern>  </servlet-mapping>

  <welcome-file-list>    <welcome-file>index.php</welcome-file>  </welcome-file-list>

</web-app>

The last step is to put the required jars into the classpath.
You could put them in the command line with -cp or –classpath or you could use Deployer’s param :

–libraryPath=[path]

Example : –libraryPath=/libs:/common_libs

With that you can have PHP support only if you want.

Follow us on Twitter

Categories: Grizzly, Web Tags: , , ,

GWS Deployer 1.9.17 : Reloaded : New Features Part 2 : JSP Support

May 24th, 2010 No comments

Grizzly Deployer got lot of activity recently over mailing list, so I took the time to give you a new feature
that been added to the release 1.9.17. The Autodeploy command.

You should see that option like a default web.xml config that will be append to all your webapps
that you will deploy. You can activate this feature by adding this param to the command line :

java -jar grizzly-http-servlet-deployer-1.9.18-SNAPSHOT.jar –autodeploy=[path]

Example : –autodeploy=/folder/autodeploy

You need to create one of more web.xml files that you will put in that folder. Each web.xml config will be append to all your webapps.

here a sample for JSP support using Jasper.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>  <servlet>    <servlet-name>jsp</servlet-name>    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>    <init-param>      <param-name>xpoweredBy</param-name>      <param-value>true</param-value>    </init-param>    <load-on-startup>3</load-on-startup>  </servlet>

  <servlet-mapping>    <servlet-name>jsp</servlet-name>    <url-pattern>*.jsp</url-pattern>  </servlet-mapping>

</web-app>

The last step is to put the required jars into the classpath.
You could put them in the command line with -cp or –classpath or you could use Deployer’s param :

–libraryPath=[path]
Example : –libraryPath=/libs:/common_libs

With that you can have JSP support only if you want.

Follow us on Twitter

Categories: Grizzly, Web Tags: , , ,

GWS Deployer 1.9.17 : Reloaded : New Features Part 1

May 24th, 2010 No comments

It has been a while since my last post, but I’m back :)

I worked hard on new features that will bring GWS Deployer to another level. You can check the features that were there before 1.9.17 in my previous post here

It will be easier to list the new features by looking at the command line parameters.

Usage: com.sun.grizzly.http.servlet.deployer.GrizzlyWebServerDeployer

  --application=[path]*       Application(s) path(s).  --port=[port]               Runs Servlet on the specified port.  --context=[context]         Force the context for a servlet.  --dontstart=[true/false]    Won't start the server.  --libraryPath=[path]        Add a libraries folder to the classpath.  --autodeploy=[path]         AutoDeploy to each applications  --cometEnabled              Starts the AsyncFilter for Comet  --forceWar                  Force war's deployment over a expanded folder.  --ajpEnabled                Enable mod_jk.  --help                      Show this help message.  --longhelp                  Show detailled help message.

  * are mandatory

The first new parameter is : –longhelp

This parameter will give a better explanation and default values.

 java -jar http-servlet-deployer-1.9.17-SNAPSHOT.jar --longhelp

Usage: com.sun.grizzly.http.servlet.deployer.GrizzlyWebServerDeployer

  -a, --application=[path]*   Application(s) path(s).

                              Application(s) deployed can be :                              Servlet(s), war(s) and expanded war folder(s).                              To deploy multiple applications                              use File.pathSeparator

                              Example : -a /app.war:/servlet/web.xml:/warfolder/

  -p, --port=[port]           Runs Servlet on the specified port.                              Default: 8080

  -c, --context=[context]     Force the context for a servlet.                              Only valid for servlet deployed using                              -a [path]/[filename].xml

  --dontstart=[true/false]    Won't start the server.                              You will need to call the start method.                              Useful for Unit testing.                              Default : false

  --libraryPath=[path]        Add a libraries folder to the classpath.                              You can append multiple folders using                              File.pathSeparator

                              Example : --libraryPath=/libs:/common_libs

  --autodeploy=[path]         AutoDeploy to each applications.                              You could add JSP support.                              Just add a web.xml that contains Jasper

                              Example : --autodeploy=/autodeploy

  --cometEnabled=[true/false] Starts the AsyncFilter for Comet.                              You need to active this for comet applications.                              Default : false

  --forceWar=[true/false]     Force war's deployment over a expanded folder.                              Will deploy the war instead of the folder.                              Default : false

  --ajpEnabled=[true/false]   Enable mod_jk.                              Default : false

  Default values will be applied if invalid values are passed.

  * are mandatory

Follow us on Twitter

Categories: Grizzly, Web Tags: ,

New Grizzly enhancement : Servlet AutoDeployer

May 24th, 2010 No comments

We got something really cool for Grizzly. It’s a Servlet AutoDeployer for GrizzlyWebServer.

Now that it said.. let’s talk more about that.

When you have servlets, you will need a AppServer or a WebServer to deploy your applications. Nothing new there.. it’s a been like that for years. Mostly you had to create a web.xml, put that in a war and deploy it.

There are others alternatives, like using GrizzlyWebServer, but you will have to put your web.xml into code.

GrizzlyWebServer ws = new GrizzlyWebServer(80);

try {    ServletAdapter sa = new ServletAdapter();    sa.setContextPath("/");

    // need to load JspRuntimeContext    Class.forName("org.apache.jasper.compiler.JspRuntimeContext");

    Servlet servlet = (Servlet)ClassLoaderUtil.load("ca.sebastiendionne.welcome_jsp");    sa.setServletInstance(servlet);

    ws.addGrizzlyAdapter(sa, new String[]{});    ws.start();} catch (Exception e){    s_logger.error("Error Launching GrizzlyWebServer",e);}

What’s wrong with that ?

In my point of view.. it’s not efficient. I don’t want to use a WebServer to deploy a simple servlet and I don’t want code what I could simply extract from a config file.

That why a servlet autodeployer could be useful. Yes a WebServer or AppServer do that already, but like I said.. you can skip it and go for a smaller and faster solution.

The GrizzlyServletDeployer (or the super fast and super easy thing for GrizzlyWebServer) will do everything for you.

In one simple command line you can deploy multiple applications.

Let’s take a look at the command line first.

java -jar grizzly-servlet-deployer-1.9.11-SNAPSHOT.jar [options]

where options are :

-p : the port [default 8080]
-a : applications to deploy (everything is done from that)

You can deploy many things from the option “-a” (servlets, war, multiple wars, expanded wars). Let’s decribe what can be done.

Syntax examples :

# 1 : Deploy a war

java -jar grizzly-servlet-deployer-1.9.11-SNAPSHOT.jar -a c:/temp/hudson.war

That will deploy the war file. The same way a WebServer will deploy it. The web.xml will be read and the servlets will be deployed.

The context will be the war file. In this example : http://localhost:8080/hudson/

#2 – Deploy a expanded war.

java -jar grizzly-servlet-deployer-1.9.11-SNAPSHOT.jar -a c:/temp/hudson

Your application could be a expanded war, or have the same hierarchy.

That will give the same result as #1

#3 Deploy servlets

java -classpath myservlet.jar;.;grizzly-servlet-deployer-1.9.11-SNAPSHOT.jar com.sun.grizzly.http.servlet.deployer.GrizzlyWebServerDeployer -a web.xml
You can skip the step to create a war file if you want. Simply declare a web.xml and put the jars into the classpath (in this case the servlet is in myservlet.jar)

The context will be the default “/”

http://localhost:8080/

#4 – Deploy multiples war in the same time.

This one is more advanced. It will deploy all the war files or expanded wars that are in a root folder.

java -jar grizzly-servlet-deployer-1.9.11-SNAPSHOT.jar -a /MultipleWarFolder

(yes it’s the same syntax as #2)

Example :

Here what the folders will look like

...../MultipleWarFolder/                      /freemarker                           /WEB-INF                               /classes/                               /lib/                              /templates/                             /web.xml                      hudson.war                      struts2-showcase-2.0.12.war                      cometd-demo.war                      sebastiendionne-is-the-man.war

The folder /MultipleWarFolder contains 4 war files and 1 expanded folder.

Serlvet-Deployer will check all the folders in the root (/MultipleWarFolder) and check if it can apply #1 or #2.

If it find one that contains /WEB-INF/web.xml it will consider it as #2 (expanded war) and if it find a .war it will do #1 (war file).

The context for each application will be the folder name (freemarker) or the war file.

If you want to can use it in a testcase easily.

GrizzlyWebServerDeployer gws = new GrizzlyWebServerDeployer();

try {

    args = new String[]{"-a","./web.xml"};

    // ready to launch    gws.init(args);    gws.launch();

    ... launch your tests...

} catch (Exception e){    e.printStackTrace();}

I think when you will start using that, you will love it :)

GrizzlyWebServer is really powerful and so small. It’s a Asynchronous IO server that support multiples protocols : HTTP(s), Comet, PHP, JSP, Freemarker, AJP protocol (mod_jk) and more check (https://grizzly.dev.java.net/).

Categories: Grizzly, Web Tags: ,

PHP on Grizzly with JSR223

May 24th, 2010 No comments

This time I will show you how to run PHP applications on GrizzlyWebServer using 100% pure java solutions.
I used Caucho Quercus to handle the PHP and GrizzlyWebServer as my WebServer.

The first implementation that I did was really simple. I used the demo that I did for JSPOnGrizzly and replace the servlet
by Quercus. You can see what the code looks like :

public void launch(){		GrizzlyWebServer ws = new GrizzlyWebServer(80);

		try {            ServletAdapter sa = new ServletAdapter();            sa.setContextPath("/");

            Servlet servlet = (Servlet)ClassLoaderUtil.load("com.caucho.quercus.servlet.QuercusServlet");    	      sa.setServletInstance(servlet);

    	      ws.addGrizzlyAdapter(sa, new String[]{});            ws.start();        } catch (Exception e){            s_logger.error("Error Launching GrizzlyWebServer",e);        }}

I was expecting that would work within a few seconds, but I got few exceptions when I tried to run the application.

2009-02-02 17:28:03 com.sun.grizzly.http.servlet.ServletAdapter serviceGRAVE: service exception:java.lang.UnsupportedOperationException: Not supported yet.	at com.sun.grizzly.http.servlet.HttpServletRequestImpl.getRealPath(HttpServletRequestImpl.java:624)	at com.caucho.quercus.servlet.QuercusServletImpl.getPath(QuercusServletImpl.java:244)	at com.caucho.quercus.servlet.QuercusServletImpl.service(QuercusServletImpl.java:112)	at com.caucho.quercus.servlet.QuercusServlet.service(QuercusServlet.java:407)	at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)	at com.sun.grizzly.http.servlet.FilterChainImpl.doFilter(FilterChainImpl.java:174)	at com.sun.grizzly.http.servlet.FilterChainImpl.invokeFilterChain(FilterChainImpl.java:123)	at com.sun.grizzly.http.servlet.ServletAdapter.service(ServletAdapter.java:254)	at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:165)	at com.sun.grizzly.http.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:653)	at com.sun.grizzly.http.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:570)	at com.sun.grizzly.http.DefaultProcessorTask.process(DefaultProcessorTask.java:840)	at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:153)	at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:136)	at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:103)	at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:89)	at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)	at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:67)	at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)	at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)	at java.util.concurrent.FutureTask.run(Unknown Source)	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)	at java.lang.Thread.run(Unknown Source)

Grizzly doesn’t completely implement HttpServletRequest (yet). The easy way doesn’t always work the first time.
BUT there is still a way to do PHP with GrizzlyWebServer. An alternative is to use Quercus’s JSR223 implementation.

We will have to replace QuercusServlet by my Servlet that uses Quercus libraries.

Servlet servlet = (Servlet)ClassLoaderUtil.load("ca.sebastiendionne.grizzly.servlet.QuercusHttpServlet");

QuercusHttpServlet

package ca.sebastiendionne.grizzly.servlet;

import java.io.FileReader;import java.io.IOException;import java.io.StringWriter;import java.util.Enumeration;import java.util.Iterator;import java.util.Map;

import javax.script.ScriptContext;import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;import org.slf4j.LoggerFactory;

public class QuercusHttpServlet extends HttpServlet {	private static final long serialVersionUID = -1649882114668014299L;

	private static final Logger s_logger = LoggerFactory.getLogger(QuercusHttpServlet.class);

	private static ScriptEngineManager scriptManager = new ScriptEngineManager();	private static ScriptEngine phpEngine = scriptManager.getEngineByExtension("php");

	@SuppressWarnings("unchecked")	protected void doPut (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		ScriptContext context = phpEngine.getContext();

		try {			context.setWriter(new StringWriter());

			//put the parameters and attributes into the engine			Enumeration attributes = req.getAttributeNames();

			while (attributes.hasMoreElements()) {				String key = (String) attributes.nextElement();

				// put the parameters and attributes into the engine				phpEngine.put(key, req.getAttribute(key));			}

			Map<String, Object> params = req.getParameterMap();

			for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) {				String key = (String) iterator.next();

				// put the parameters and attributes into the engine				phpEngine.put(key, params.get(key));			}

			// need a better way to find the requested file			String uri = req.getRequestURI();

			if(uri.startsWith("/")){				uri = uri.substring(1);			}

			phpEngine.eval(new FileReader(uri), context);			StringWriter writer = (StringWriter) context.getWriter();			res.getWriter().println(writer.toString());		} catch (Exception e) {			s_logger.error("Error Evaluating PHP",e);		}

	}

	protected void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {		doPut(req, res);	}

}

We need a php page to test our application.
phpinfo.php

<?php

// Show all information, defaults to INFO_ALLphpinfo();

?>

The output won’t be the same as the native php. Here the output from Quercus implementation.

QuercusPHP Version => 5.2.0System => Windows XP 5.1 x86Build Date => 20070628T2777Configure Command => n/aServer API => CGIVirtual Directory Support => disabledConfiguration File (php.ini) Path => WEB-INF/php.iniPHP API => 20031224PHP Extension => 20041030Debug Build => noThread Safety => enabledRegistered PHP Streams => php, file, http, httpsVariable => Value....

You can download the source code for this project here.

Categories: Grizzly, Web Tags: , , ,

JSP On Grizzly

May 24th, 2010 No comments

We had a lot of people that ask how to put JSP over Grizzly, but we didn’t have a implementation or a working sample to show them.
It couldn’t stay like that for ever … so I took a little of my spare time and I got something for you :)

I’ll show you how to to compile your JSP with Jasper and use them with GrizzlyWebServer.
I used Jasper that came with Tomcat 6. I’ll need to include some librairies to your project.
I didn’t try with Tomcat 4.x, but maybe you could save some space.
I’ll skip the jars required for Jasper to the end of this article. Now let’s take a look at the beast (ok, mini-beast).

The JSP page is really simple. If you want to use framework like Struts, you will have more work to do, but I won’t cover that.

<html>	<body>

		Hello to you : 		<table>			<tr>		<% for(int i=0;i<5;i++){%>			<td><%=i%></td>		<%}%>		</tr>	</table>	</body>	</html>

We need to compile the JSP if we want to use it with our GrizzlyWebServer. It isn’t really complicated.

public void compileJSP(String[] params) throws Exception {		JspC jasper = new JspC();

		jasper.setArgs(params);		jasper.execute();}

...  

String jasperParams[] = new String[]{				"-webapp", 				"./jsp",				"-v",				"-p", 				"ca.sebastiendionne", 				"-d", 				"./classes", 				"-l", 				"-s", 				//"-webxml", // if you want JSPC to generate a webxml				//"./web_jasper.xml", 				"-compile"};

//compile the JSPcompileJSP(jasperParams);

That will generate the welcome_jsp.java and compile into /classes. Now we need to call it in our application.

public void launch(){		GrizzlyWebServer ws = new GrizzlyWebServer(80);

		try {            ServletAdapter sa = new ServletAdapter();            sa.setContextPath("/");

            // need to load JspRuntimeContext            Class.forName("org.apache.jasper.compiler.JspRuntimeContext");

            Servlet servlet = (Servlet)ClassLoaderUtil.load("ca.sebastiendionne.welcome_jsp");    	      sa.setServletInstance(servlet);

    	      ws.addGrizzlyAdapter(sa, new String[]{});            ws.start();        } catch (Exception e){            s_logger.error("Error Launching GrizzlyWebServer",e);        }}

The final touch is to test it. You will obtain a very nice output :) http://localhost

Hello to you :0 	1 	2 	3 	4

I didn’t go to deep into JSPC. I used JSPC, the class used by the Ant task. So because of that, we will need
to include Ant jars into the project. If you have problems with that, I’m sure that you could extract the code from
the ant task too.
The jars needed are :

ant-launcher.jar // from ant 1.7x
ant.jar // from ant 1.7x
el-api.jar // from Tomcat 6.x
jasper-el.jar // from Tomcat 6.x
jasper-jdt.jar // from Tomcat 6.x
jasper.jar // from Tomcat 6.x
jsp-api.jar // from Tomcat 6.x
servlet-api.jar // from Tomcat 6.x
tomcat-juli.jar // from Tomcat 6.x : for the logging into JSPC

You can download the source code here.

Categories: Grizzly, Web Tags: , ,

Grizzly : Drop connection for banned IP

May 24th, 2010 No comments

I want to show you how you can block IPs in your Grizzly server. I pretty sure that you can found lot of reasons why you could want that.
I’ll use a list from http://iblocklist.com/ as input for my demo.
What you have to do to close the connection from client that isn’t wanted is pretty simple.

    Controller controller = new Controller();    TCPSelectorHandler tcpSelectorHandler = new TCPSelectorHandler(){        public SelectableChannel acceptWithoutRegistration(SelectionKey key) throws IOException {            ServerSocketChannel server = (ServerSocketChannel) key.channel();            SocketChannel channel = server.accept();

            if (isAddressBanned(channel.socket().getInetAddress()))  {                if(s_logger.isDebugEnabled()){                  s_logger.debug("This IP [" + channel.socket().getInetAddress() +                   "] is banned, the connection will be close");                }                closeChannel(channel);                return null;            }

            return channel;        }    };    tcpSelectorHandler.setPort(port);    controller.addSelectorHandler(tcpSelectorHandler);

With that, as soon as a connection is made, Grizzly will valid if the IP is valid and close the connection is required.
I won’t show the implementation of “isAddressBanned”, because is not really related to Grizzly, but you can find it in the source code.
You can download the complete source code from here.

Categories: Grizzly, Web Tags: ,