WebLab Eclipse Plugin

From WebLab Wiki
Jump to: navigation, search

This page is a tutorial for the WebLab Eclipse Plugin. This plugin aims to ease the creation of a Java Web Application, especially WebLab Application. This plugin is still in a beta phase, more functionnalities should be add later.

Requirements

Before the installation of the WebLab Eclipse plugin, you must make sure that you already have installed Maven ( http://maven.apache.org/ ). Any version (2.x.x or 3.x.x) should work fine.

Installation

The installation of the plugin is quite easy, it works like any other eclipse plugin :

  1. In Eclipse, go in "Help" -> "Install New Software..."
  2. Click on "Add" and create a new Repositoy Location with "http://weblab.ow2.org/plugin/update-site/"
  3. Click on "WebLab" (as shown on screenshot)
  4. Click on "Next"... "Next"... Accept the terms and "Finish"
WebLab-Plugin-Installation .png

If it is not already done, you have to set the M2_REPO variables in Eclipse. To do so, you have to go in "Window" -> "Preferences" -> "Java" -> "Build Path" -> "Classpath Variables", click on new and add the "M2_REPO" variable, with the path to the maven repository.

M2REPO-setting.png

Then the installation is over.

Creation of a WebLab Service

In order to create a WebLab service, you have to use the WebLab Wizard. You can find it in "File" -> "New" -> "Project" -> "WebLab" -> "WebLab Project".

In the first page, if a maven program is not found automatically, you will be ask to browse for one.

Plugin-page-one.png

In the second page, you will have to fill the information needed to create the service :

  • serviceName : "langDetectorService"
  • the groupId : "org.tutorial.ws"
  • the artifactId : "langDetectorService"
Plugin-page-two.png

You also have to check the "analyser" button, and then Click on "Finish".

The project should look like this:

Plugin-service-created-tree.png


Now we will modify the XML file called pom.xml that contains information about the project and configuration details used by maven to build the project. Open the file langDetectorService/pom.xml, which should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
 
	<parent>
		<groupId>org.ow2.weblab.webservices</groupId>
		<artifactId>parent</artifactId>
		<version>1.2.2</version>
	</parent>
 
	<groupId>org.tutorial.ws</groupId>
	<artifactId>langDetectorService</artifactId>
	<version>1.0-SNAPSHOT</version>
 
	<packaging>war</packaging>
	<name>langDetectorService</name>
 
	<description>This is a project generated WebLab Maven plug-in</description>
 
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
 
	<dependencies>
    <dependency>
      <groupId>org.ow2.weblab.core.helpers</groupId>
      <artifactId>rdf-helper-jena</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

To adapt this file to our needs, you have to add dependencies for the language detection API. To do this, you can copy the lines provided below under the <dependencies></dependencies> markups.

[...]
<dependencies>
    [...]
    <dependency>
        <groupId>de.spieleck.app.ngramj</groupId>
        <artifactId>cngram</artifactId>
        <version>1.0-0.060327</version>
    </dependency>
</dependencies>
[...]
<repositories>
    [...]
    <repository>                         
        <id>OW2 Maven2</id>                        
        <url>http://maven.ow2.org/maven2/</url> 
    </repository>
</repositories>
[...]

Then, right-click on your project, and on the WebLab Menu, click on "mvn eclipse:eclipse", as on the screenshot below.

Maven eclipse.png

It will enables Maven to load the jar librairies and all its dependencies.

The next step is the actual implementation of the service. In the WebLab platform, services interfaces have been standardized in a small set of generic interfaces that rely on the same data exchange model. They define the method that are used by the multiple components that can be used in a multimedia processing chain (see on WebLab documentation on the wiki[1] for more information). Thus a "WebLab-compliant" service need to implement one of these generic interfaces. For our new service, we will use the Analyser interface. A UML description of this interface can be found in WebLab documentation whereas the WSDL itself can be found in the source repository. This WSDL has been used to generate the JAVA interface (through CXF) which will be used in our example. It includes the JAVA classes associated with elements of the data exchange model.

Implementation of the Web service class

The implementation itself will be quite easy. Our new service is an Analyser, so we have to implement this interface which force us to add only one unique method. It is called to parse resources and named process(ProcessArgs args). It receive a Resource as input and answer a Resource as output (the ProcessArgs could optionally contain an extra object called UsageContext but it will be ignored for this tutorial).

In order to implement the language detector, you just have to edit your-service-path/src/main/java/org/tutorial/ws/Langdetectorservice.java in order to fill it like this (this is an example of implementation for the tutorial).

package org.tutorial.ws;
 
import java.io.IOException;
import java.util.List;
 
import javax.jws.WebService;
 
import org.apache.commons.logging.LogFactory;
import org.ow2.weblab.core.extended.factory.AnnotationFactory;
import org.ow2.weblab.core.extended.ontologies.DublinCore;
import org.ow2.weblab.core.extended.util.ResourceUtil;
import org.ow2.weblab.core.helper.PoKHelper;
import org.ow2.weblab.core.helper.RDFHelperFactory;
import org.ow2.weblab.core.model.Annotation;
import org.ow2.weblab.core.model.Document;
import org.ow2.weblab.core.model.Resource;
import org.ow2.weblab.core.model.Text;
import org.ow2.weblab.core.services.AccessDeniedException;
import org.ow2.weblab.core.services.Analyser;
import org.ow2.weblab.core.services.ContentNotAvailableException;
import org.ow2.weblab.core.services.InsufficientResourcesException;
import org.ow2.weblab.core.services.InvalidParameterException;
import org.ow2.weblab.core.services.ServiceNotConfiguredException;
import org.ow2.weblab.core.services.UnexpectedException;
import org.ow2.weblab.core.services.UnsupportedRequestException;
import org.ow2.weblab.core.services.analyser.ProcessArgs;
import org.ow2.weblab.core.services.analyser.ProcessReturn;
 
import de.spieleck.app.cngram.NGramProfiles;
 
/**
 * Basic service that annotate Text unit with the 2-char code of the detected
 * language
 * @author WebLab team
 */
@WebService(endpointInterface = "org.ow2.weblab.core.services.Analyser")
public class LangDetectorService implements Analyser {
 
	private NGramProfiles nps = null;
	private NGramProfiles.Ranker ranker = null;
 
	/**
	 * Simple constructor that initiate the language profiles for NGramJ
	 */
	public LangDetectorService() {
		try {
			nps = new NGramProfiles();
			ranker = nps.getRanker();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
	@Override
	public ProcessReturn process(ProcessArgs args)
			throws AccessDeniedException, ContentNotAvailableException,
			InsufficientResourcesException, InvalidParameterException,
			ServiceNotConfiguredException, UnexpectedException,
			UnsupportedRequestException {
		// check we received a valid request
		checkArgs(args);
		// Get text units in the Document received
		List<Text> texts = 
			ResourceUtil.getSelectedSubResources(args.getResource(), 
					Text.class);
		StringBuilder sb = new StringBuilder();
		Resource res = args.getResource();
		// Concatenation of the document text sections
		for (Text text : texts) {
			if (text.getContent() == null || text.getContent().isEmpty()) {
				LogFactory.getLog(this.getClass())
						.debug("Text '" + text.getUri()
								+ "' has no content; ignored.");
				continue;
			}
			sb.append(text.getContent());
			sb.append("\n\n\n"); // insert line break to separate successive texts
		}
		// detecting of the language of the text
		String textLanguage = this.detectLanguage(sb.toString());
		// integration of the annotation dc:language in the document
		Annotation annot = AnnotationFactory.createAndLinkAnnotation(res);
		PoKHelper pokH = RDFHelperFactory.getPoKHelper(annot);
		pokH.setAutoCommitMode(false);
		pokH.createLitStat(res.getUri(), DublinCore.LANGUAGE_PROPERTY_NAME,
				textLanguage);
		pokH.commit();
		LogFactory.getLog(this.getClass()).info(
				"Document '" + res.getUri()
						+ "' annotated with the dc:language property : "
						+ textLanguage);
 
		ProcessReturn pr = new ProcessReturn();
		pr.setResource(res);
 
		return pr;
	}
 
	/**
	 * Detecting the language of the text content passed as a String with NGramJ
	 * @param text : the text content
	 * @return a string that contains the 2 char code for the detected language 
	 * or xx if the language is unkown
	 */
	private String detectLanguage(String text) {
		String retVal = "xx";
		if (!ranker.equals(null)) {
			ranker.reset();
			ranker.account(text);
			NGramProfiles.RankResult res = ranker.getRankResult();
 
			if (res.getScore(0) > 0.1)
				retVal = res.getName(0);
		}
		return retVal;
	}
 
	/**
	 * Check the request sent to the service, mostly for null content.
	 * @param args the arguments sent to the service
	 * @throws InvalidParameterException
	 * @throws UnsupportedRequestException
	 */
	private void checkArgs(final ProcessArgs args)
			throws InvalidParameterException, UnsupportedRequestException {
		if (args == null) {
			throw new InvalidParameterException("ProcessArgs was null.",
					"ProcessArgs was null.");
		}
		final Resource res = args.getResource();
		if (res == null) {
			throw new InvalidParameterException("Resource was null.",
					"Resource was null.");
		}
		if (!(res instanceof Document)) {
			throw new UnsupportedRequestException(
					"Resource was not a document.",
					"Resource was not a document.");
		}
	}
}

That's all folks, now the code is ready, let's test it.

Compilation, packaging and test

The next step is to package our web service into a war file in order to deploy it on a web server and to test it. For this, you can right-click on the project, and on the WebLab Menu, click on "mvn clean package", as on the screenshot below.

Maven package.png

This command will compile the project and create the war file of your web service under the directory langDetectorService/target. You can now deploy it on your tomcat server (we assume you used the tomcat web server provided with the demo) : simply copy the resulting WAR file from langDetectorService/target/langDetectorService.war to <tomcat-home>/webapps/. To ensure the service is correctly deployed on tomcat, check the log (open <tomcat-home>/logs/catalina.out) or go to the service welcome page URL http://localhost:8080/langDetectorService. If the service is correctly statred you should see :

ServiceWelcomeCXF.png

Welcome page of the service correclty deployed on tomcat

To test this service, you have to install SoapUI (see SoapUI documentation[2]). Then simply :

  1. Create a New soapUI project ;
  2. Copy the URL of the service in the 'Initial WSDL/WADL' box

(i.e. http://localhost:8080/langDetectorService/analyser?wsdl) ;

  1. Edit the 'process' request and copy the request provided hereafter ;
  2. Send the request and check the results.

<soapenv:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:analyser="http://weblab.ow2.org/core/1.2/services/analyser"
xmlns:model="http://weblab.ow2.org/core/1.2/model#" >
    <soapenv:Header/>
    <soapenv:Body>
        <analyser:processArgs>
            <resource xsi:type="model:Document" uri="weblab://aaa/1">
                <mediaUnit xsi:type="model:Text" uri="weblab://aaa/1#0">
                    <content>The WebLab platform is the generic name of the development and execution environment
                        platform provided by EADS in several research projects (Vitalas, WebContent, e-WokHub, Citrine...)
                        involving the process of several types of media.</content>
                </mediaUnit>
            </resource>
        </analyser:processArgs>
    </soapenv:Body>
</soapenv:Envelope>

You can see here the result of this query :

SoapUI result.png

Test of the langDetectorService using soapUI

Moreover if you check the logs of your apache tomcat server (default logger write in <tomcat-home>/logs/catalina.out), you should see :

INFO [http-9080-2] (LangDetectorService.java:85) - Document 'weblab://aaa/1' annotated with the dc:language property : en

So that's the end of the service tutorial. The next section will provide you some insight that may be useful when trying to go further and implement your own service.

Going further

Extra documentation

For more information, follow the links hereafter:


  1. http://weblab-project.org
  2. http://www.soapui.org/