Archive

Archive for May 24th, 2010

Enhance your javadoc with ULMGraph

May 24th, 2010 No comments

We can’t live without Javadoc, but even if it useful, it’s not complete. One missing thing is UML within the Javadoc.

To add UML to your Javadoc, is quite simple. You need to add Graphviz into your maven build.

First you need to download and install Graphviz. Go there Graphviz

After that you should add the variable GRAPHVIZ_HOME (that point to the installation folder) into your system.

The last step is to add the plugin into your pom.

Add the lines in bold.


<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-javadoc-plugin</artifactId>
  <version>2.6.1</version>
  <configuration>
    <links>
      <link>http://java.sun.com/javase/6/docs/api/</link>
    </links>
    <detectOfflineLinks />
    <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
    <!--
      use this line or use the variable GRAPHVIZ_HOME
      <docletPath>/path/to/UmlGraph.jar</docletPath>
    -->
    <docletArtifact>
      <groupId>org.umlgraph</groupId>
      <artifactId>doclet</artifactId>
      <version>5.1</version>
    </docletArtifact>

    <additionalparam>-operations</additionalparam>
    <additionalparam>-qualify</additionalparam>
    <additionalparam>-types</additionalparam>
    <additionalparam>-visibility</additionalparam>
    <additionalparam>-collpackages</additionalparam>
    <show>private</show>
  </configuration>
</plugin>

With that you will have nice UML into your javadoc. I hope that help.

A simplier way is to add that instead in the pom.xml


<plugin>
  <artifactId>maven-javadoc-plugin</artifactId>
  <configuration>
              <show>package</show>
              <version>true</version>
              <javadocVersion>${source.version}</javadocVersion>
              <links>
                  <link>http://java.sun.com/javase/6/docs/api/</link>
                  <link>http://java.sun.com/products/servlet/2.5/docs/servlet-2_5-mr2/</link>
                  <link>http://joda-time.sourceforge.net/api-release/</link>
                  <link>http://findbugs.sourceforge.net/api/</link>
                  <link>http://tomcat.apache.org/tomcat-6.0-doc/api/</link>
                  <link>http://jetty.mortbay.org/jetty/jetty-6/apidocs/</link>
                  <link>http://download.eclipse.org/jetty/stable-7/apidocs/</link>
                  <link>https://grizzly.dev.java.net/nonav/apidocs/</link>
              </links>          <source>1.6</source>
     <code>javadoc:aggregate</code>
      <code>javadoc:test-aggregate</code>
    <doclet>gr.spinellis.umlgraph.doclet.UmlGraphDoc</doclet>
    <docletArtifact>
      <groupId>gr.spinellis</groupId>
      <artifactId>UmlGraph</artifactId>
      <version>4.6</version>
    </docletArtifact>
    <additionalparam>
      -inferrel -inferdep -quiet -hide java.*
      -collpackages java.util.* -qualify
      -postfixpackage -nodefontsize 9
      -nodefontpackagesize 7
    </additionalparam>
  </configuration>
</plugin>
Categories: Java Tools Tags: , , , ,

Extends javadoc with custom tag

May 24th, 2010 No comments

I would like to show you how you could extend your javadoc to include samples directly into the javadoc without extra work.

What I don’t like about javadoc is the lack of code sample. Something is can be hard to find the starting point of a new framework.

Let’s show a example, it will be easier to understand, and so simple.

 /**  * * This in a javadoc with a custom tag @example. * * @author Sebastien Dionne * * @example. * <pre> *  * SSDPControler controler = new SSDPControler(); *  * // sends messages each 30 seconds. * controler.getPeriodicMessageSender().setDelay(30000); * * controler.setPeriodicMessageSender(new SSDPPeriodicMessageSender(null) { *     @Override *     public List<String> returnHellos() { *         List<String> list = new ArrayList<String>(); * *         list.add("hello1"); *         list.add("hello2"); * *         return list; *     } * }); * controler.start(); * </pre> */

In this example, we used a custom tag @example. The result will look like this.

...public class SSDPControlerextends Objectimplements ISSDPControler...This in a javadoc with a custom tag @example.

Example :

    SSDPControler controler = new SSDPControler();

    // sends messages each 30 seconds.    controler.getPeriodicMessageSender().setDelay(30000);

    controler.setPeriodicMessageSender(new SSDPPeriodicMessageSender(null) {       @Override       public List<String> returnHellos() {           List<String> list = new ArrayList<String>();

           list.add("hello1");           list.add("hello2");

           return list;       }   });   controler.start();

There is a thing that you need to know to avoid surprises :

Javadoc tool will cut the custom tag as soon as it detect another annotation, so don’t forget to convert to HTML code like
@ : become : “&”#64;

To acheive that you need to add little config into your pom. Add the lines in bold.

<plugin>    <groupId>org.apache.maven.plugins</groupId>    <artifactId>maven-javadoc-plugin</artifactId>    <version>2.6.1</version>    <configuration>          <links>            <link>http://java.sun.com/javase/6/docs/api/</link>          </links>          <detectOfflineLinks/>                     <tags>            <tag>              <name>example.</name>              <placement>aoptcmf</placement>              <head>Example :</head>            </tag>          </tags>                </configuration></plugin>
Categories: Java Tools 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: ,

Read web.xml with one line of code Part 2

May 24th, 2010 No comments

I did a <a href=”http://weblogs.java.net/blog/survivant/archive/2008/12/read_webxml_wit.html”>previous post</a> about how to do it with XMLBean or JABX, but it was more an example how to do it. This time is the real deal.

I used JABX to generate the java classes from the schemas and use that to parse the web.xml.

The result is a simple class : WebAppLoader that will load the web.xml.

Here a example :

WebappLoader webappLoader = new WebappLoader();
WebApp webapp = webappLoader.load(“/web-2.2.xml”);

The object WebApp contains all the infos extracted from the web.xml. The representation is based on webapp 3.0.

you can get the source code from my repository : <a href=”http://kenai.com/projects/sebastiendionne/sources/repository/show/dtd-schemas-generator”>http://kenai.com/projects/sebastiendionne/sources/repository/show/dtd-schemas-generator</a>

Categories: Java Tools, Web Tags: , ,

How to configure proxy on Glassfish v3

May 24th, 2010 1 comment

If you are behind a proxy maybe you will want to set the proxy in Glassfish. There are few different ways to do that. #1 – You could use the admin web page. You can add the proxy settings : host and port with the admin. Into the admin web page, go to the Application Server at your left. After that on your right select : JVM Settings / JVM Options. Just add theses settings : http.proxyHost=myproxy.mydomain http.proxyPort=myproxy.port Glassfish_proxy.png Click here to enlarge #2 – You could use the command line Go into your Glassfish installation /bin and enter theses commands : asadmin create-jvm-options “-Dhttp.proxyHost=myproxy.mydomain” asadmin create-jvm-options “-Dhttp.proxyPort=myproxy.port” #3 – The last option is to edit manually domain.xml You add the settings in the “<java-config>” element. <java-config ...> <jvm-options>-Dhttp.proxyHost=myproxy.mydomain</jvm-options> <jvm-options>-Dhttp.proxyPort=myproxy.port</jvm-options> ...

Categories: Glassfish Tags:

JAXB : web.xml : dtd and xsd classes generator

May 24th, 2010 No comments

I created a little demo to show how easy it can be to create a kit of classes from DTD and XSD using Maven and JAXB.

To generate from XSD schemas

In your pom.xml, you will have to add this.

<dependencies>    <dependency>		  <groupId>com.sun.xml.bind</groupId>		  <artifactId>jaxb-xjc</artifactId>		  <version>2.1</version>		</dependency>		<dependency>        <groupId>javax.xml.bind</groupId>        <artifactId>jaxb-api</artifactId>        <version>2.1</version>    </dependency></dependencies>

<build>  <plugins>    <plugin>      <artifactId>maven-compiler-plugin</artifactId>      <configuration>        <source>1.5</source>        <target>1.5</target>      </configuration>    </plugin>    <plugin>      <groupId>org.jvnet.jaxb2.maven2</groupId>      <artifactId>maven-jaxb2-plugin</artifactId>      <executions>        <execution>          <goals>            <goal>generate</goal>          </goals>          <configuration>            <!--  if you want to put DTD somewhere else            <schemaDirectory>src/main/jaxb</schemaDirectory>            -->          </configuration>        </execution>      </executions>      <dependencies>        <dependency>          <groupId>org.jvnet.jaxb2-commons</groupId>          <artifactId>property-listener-injector</artifactId>          <version>1.0</version>        </dependency>      </dependencies>    </plugin>  </plugins></build>

The important thing to know is that you have to generate your classes with one schema each time. If you put webapp schemas 2.2 and 2.3 in the same time,
you will obtain errors. Be sure to include all the files related to your webapp schema to generate your java classes.

Example : webapp 2.4 need
web-app_2_4.xsd
j2ee_1_4.xsd
jsp_2_0.xsd

You can even do some customization with a config file named : domain.jaxb (/src/main/resources).

To generate from DTD

In your pom.xml, you will have to add this.

<dependencies>  <dependency>	  <groupId>com.sun.xml.bind</groupId>	  <artifactId>jaxb-xjc</artifactId>	  <version>2.0</version>	</dependency>	<dependency>      <groupId>javax.xml.bind</groupId>      <artifactId>jaxb-api</artifactId>      <version>2.0</version>  </dependency></dependencies>

<build>  <plugins>    <plugin>      <artifactId>maven-compiler-plugin</artifactId>      <configuration>        <source>1.5</source>        <target>1.5</target>      </configuration>    </plugin>    <plugin>      <groupId>org.jvnet.jaxb2.maven2</groupId>      <artifactId>maven-jaxb2-plugin</artifactId>      <executions>        <execution>          <goals>            <goal>generate</goal>          </goals>          <configuration>            <!--  if you want to put DTD somewhere else            <schemaDirectory>src/main/jaxb</schemaDirectory>            -->            <extension>true</extension>            <schemaLanguage>DTD</schemaLanguage>            <schemaIncludes>              <schemaInclude>*.dtd</schemaInclude>            </schemaIncludes>            <bindingIncludes>              <bindingInclude>*.jaxb</bindingInclude>            </bindingIncludes>            <args>              <arg>-Xinject-listener-code</arg>            </args>          </configuration>        </execution>      </executions>      <dependencies>        <dependency>          <groupId>org.jvnet.jaxb2-commons</groupId>          <artifactId>property-listener-injector</artifactId>          <version>1.0</version>        </dependency>      </dependencies>    </plugin>  </plugins></build>

The DTD generation is the same pattern as XSD. The principal differences are in the pom.xml

You can download a complete project that use webapp xsd and dtd to parse any web.xml. It could be useful when you want to keep it simple :)

You can browse the code from : my Kenai repository

Categories: Java Tools, 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: , , ,