Groovy and Tomcat, Pt3 – Groovy Scripts

In this part I’m going to show you how to use Groovy Scripts on a Tomcat. It’s very easy to do!

First add these libraries to your project:

– groovy.jar
– groovy-json.jar
– groovy-servlet.jar
– groovy-xml.jar
– antlr.jar
– asm.jar

You might need to add more to the project depending on the functionality of your scripts, but this is the minimum I needed to not encounter any exceptions.

Next, in your web.xmladd the following servlet;


<servlet>
 <servlet-name>GroovyScript</servlet-name>
 <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
 </servlet>

<servlet-mapping>
 <servlet-name>GroovyScript</servlet-name>
 <url-pattern>*.groovy</url-pattern>
 </servlet-mapping>

Groovy will then compile your scripts and run them as requested. For a quick test, put this in your webapp root folder and have its name end with .groovy, I named mine script.groovy, but you should name it something more meaningful.


def ip = request.getRemoteAddr()

println """
<html>
<head>
<title>Groovy Scripts</title>
</head>
<body>
<p>Hello ${ip}</p>
</body>
</html>
"""

Navigate to the url of the script and you’ll get a warm welcome.

Wasn’t that easy?

Stay tuned,
Eek.

Groovy and Tomcat, Pt2 – Groovy extends HttpServlet

Continuing where we left off…

The jars you’ll need for this part are the same as the ones for part 1:

– groovy.jar
– antlr.jar
– asm.jar

GroovyHttpServlet


package net.mymilkedeek.tomcat

import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class GroovyHttpServlet extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
 req.session.setAttribute("language", "groovy")
 req.session.setAttribute"sentiment", "awesome")
 req.session.setAttribute("message", JavaGroovy.message())
 resp.sendRedirect("index.jsp")
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
 super.doPost(req, resp)
 }
}

And add it to the web.xml

</pre>
<servlet>
 <servlet-name>GroovyHttpServlet</servlet-name>
 <servlet-class>net.mymilkedeek.tomcat.GroovyHttpServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>GroovyHttpServlet</servlet-name>
 <url-pattern>/groovyhttpservlet</url-pattern>
 </servlet-mapping>
<pre>

Now, navigate to the Servlet url and watch Groovy take care of everything:

So, in short, what we did was replace a Java HttpServlet with a Groovy HttpServlet.

For my next blog post, I’ll show you how to set up a Groovy Script in a webapplication.

Stay tuned,
Eek.

Groovy and Tomcat, Pt1 – Calling Groovy from a Java Servlet

For this first post, I’ll keep it very simple: a Java servlet calls Groovy code to display a message to the screen. Start by setting up a regular Java servlet application. After your simple web application is set up, read the code snippets below.


index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Eek's Groovy Sandbox</title>
</head>
<body>
<p>I'm using <c:out value="${language}" />! That's <c:out value="${sentiment}" /></p>
<p><c:out value="${message}" /></p>
</body>
</html>

In this .jsp code, we’ll print three attributes. Two handled by the Java servlet and one handed to us by our Groovy utility class.

The Java servlet


package net.mymilkedeek.tomcat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * The Java Servlet
 *
 * @author My Milked Eek
 */
public class JavaServlet extends HttpServlet {
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 req.getSession().setAttribute("language", "java");
 req.getSession().setAttribute("sentiment", "ok...");
 resp.sendRedirect("index.jsp"); }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 version="2.5">

<servlet>
 <servlet-name>JavaServlet</servlet-name>
 <servlet-class>net.mymilkedeek.tomcat.JavaServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>JavaServlet</servlet-name>
 <url-pattern>/javacallinggroovy</url-pattern>
</servlet-mapping>

</web-app>

That’s a simple webapplication. Now add the following dependencies to your project:

– groovy.jar
– antlr.jar
– asm.jar

Now add a Groovy Class, I named it JavaGroovy.

Groovy Class

package net.mymilkedeek.tomcat

class JavaGroovy {

static def message() {
 "I was called from Groovy. Exciting, isn't it?"
 }
}

And add following line to your Java Servlet:

...
req.getSession().setAttribute("message", JavaGroovy.message());
...

Now, navigate to the url of the Java Servlet and watch the magic happen:

So, in short, what we did was make a call to a Java Servlet. This servlet then gets a message from a Groovy class. And then we added that message to the session.

This kind of setup with Groovy is particularly useful with an existing Java Servlet: You only need to add Groovy jars and you can start hacking away.

For my next post, I’ll show you how to get Groovy extending HttpServlet.

Stay tuned,
Eek.

Groovy and Tomcat

It’s been a while since my last non-ludum blog post. Since I wrote “iText on the JVM” I’ve been playing with Groovy and Python occasionally. But for the past month and a half, I’ve been getting into Groovy a lot. So much that my next Ludum Dare entry will be written in Groovy/Java.

Up until this blog post I’ve just been experimenting with Groovy, using it to quickly test issues and bugs, but I wanted to do a bit more with it, so I tried using it in Tomcat. I didn’t set up Grails, didn’t want to do that just yet, but I set up Groovy and I’ll document several ways to use Groovy in Tomcat.

Table of contents:

  1. Java HttpServlet calling Groovy
  2. Groovy HttpServlet
  3. Groovy Scripts
  4. Groovy Servlet Pages
  5. Bringing it all together

We’ll start out really simple; use Groovy as an extension to an existing Java servlet and work our way to using scripts in combination with .gsp’s.

Stay tuned,
Eek.

I wrote a Google+ Library

Because of a project, I have been trying out several Google+ Libraries. The following libraries were the ones I tried:

The first being made by Google and the second by… Not Google.

I cannot say I was satisfied with any of those two. The first one required what seemed like a thousand dependencies while the second one refused to work due to a JSON exception that seemed to have no documentation on-line. So, I decided I’d do myself a favor and make something that works the way I want it to work: with as few dependencies as possible and very easy to use.

I used three dependencies:

I picked these three (well, two actually, commons-codec was required by scribe) because they are easy in use and do not require other dependencies.

And this is the result: My very own Google+ library

I designed it with a few guidelines in mind:

 1. Easy to get it working

GooglePlus gPlus = new GooglePlus(apiKey, secret);
 Desktop.getDesktop().browse(new URI(gPlus.getAuthorizationUrl()));
 gPlus.verifyUser(new Scanner(System.in).next()); 

Three lines and we’re connected to the G+ api.

 2. Cope with calls that weren’t predefined

 private static final String apiUrl = &quot;https://www.googleapis.com/plus/v1/&quot;;

public Response getResponse(String apiCall) {
 OAuthRequest request = new OAuthRequest(Verb.GET, apiUrl + apiCall);
 oAuthService.signRequest(accessToken, request);
 Response response = request.send();
 return response;
}

The library provides predefined calls to the api, such as “findUser(String query)”. Normally the inner workings would be shielded from external use, but if you need to make your own calls to G+, you can call the above method in net.mymilkedeek.social.gplus.core.Manager with your custom api call.

This will come in handy if Google updates its G+ api and this library doesn’t get updated. No need to wait, just put in the new api calls and process the Json response.

3. Easy to expand

This is awesomely achieved. To add the functionality for Comments I needed to:

  1. Create a Comment class (with fields)
  2. Create CommentManager (extends Manager<Comment>)
  3. Create CommentJsonParser (implement JsonParser<Comment>)
  4. Parse the Json to the Comment object
  5. Write one line functions in the Manager

The to-do’s

  • Add optional parameters.
  • Write more comments.
  • Better exception handling.

Download it, browse the source code, don’t download it. Do with it as you please. As long as you report bugs/notify me of things that could have been better.

  Some Example

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Scanner;

import net.mymilkedeek.social.gplus.GooglePlus;
import net.mymilkedeek.social.gplus.activity.Activity;
import net.mymilkedeek.social.gplus.activity.ActivityManager;
import net.mymilkedeek.social.gplus.comment.Comment;
import net.mymilkedeek.social.gplus.comment.CommentManager;
import net.mymilkedeek.social.gplus.person.Person;
import net.mymilkedeek.social.gplus.person.PersonManager;

import org.json.JSONException;

public class Main {

private static final String apiKey = &quot;XXX&quot;;
private static final String secret = &quot;XXX&quot;;

 public static void main(String[] args) throws JSONException, IOException,
 URISyntaxException {
 GooglePlus gPlus = new GooglePlus(apiKey, secret);
 Desktop.getDesktop().browse(new URI(gPlus.getAuthorizationUrl()));
 gPlus.verifyUser(new Scanner(System.in).next());

 ActivityManager activityManager = gPlus.getActivityManager();
 List&lt;Activity&gt; activities = activityManager
.getActivitiesFromUser(&quot;111486046861792612952&quot;); // that's me!

 for (Activity a : activities) {
 System.out.println(a.getId());
 PersonManager personManager = gPlus.getPersonManager();
 List&lt;Person&gt; persons = personManager.findByActivityId(a.getId(),
 PersonManager.PLUSONERS);

 for (Person p : persons) {
 System.out.println(p);
 }

 persons = personManager.findByActivityId(a.getId(),
 PersonManager.RESHARERS);

 for (Person p : persons) {
 System.out.println(p);
 }
 }
 }
}

This piece of code gets all of my activities (or posts) and then gets all the users who +1’d my post or shared it. Easy peasy.