You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@thrift.apache.org by Apache Wiki <wi...@apache.org> on 2012/04/02 12:37:34 UTC
[Thrift Wiki] Update of "Thrift & Eclipse & JUnit with TServlet" by DJDaveMark
Dear Wiki user,
You have subscribed to a wiki page or wiki category on "Thrift Wiki" for change notification.
The "Thrift & Eclipse & JUnit with TServlet" page has been changed by DJDaveMark:
http://wiki.apache.org/thrift/Thrift%20%26%20Eclipse%20%26%20JUnit%20with%20TServlet
Comment:
Initial tutorial
New page:
== Installation ==
If you haven't downloaded thrift yet: http://thrift.apache.org/download/
1. Download `thrift-`''`version`''`.tar.gz` and extract it somewhere, eg. "thrift-''version''" (from here referred to as `$thrift-`''`version`'').
1. For windows, download `thrift-version.exe`. and copy-paste it to `C:\Windows` then rename it `thrift.exe`.
1. For Linux: http://wiki.apache.org/thrift/ThriftInstallation
1. At the command prompt, go to `thrift-`''`version`''`/lib/java` and execute `ant` to compile the source code into the generated `build` folder.
== Installation Editeur Eclipse ==
1. Help` --> `Software Updates` --> `Add Site...
1. URL: http://thrift4eclipse.sourceforge.net/updatesite/
1. Tick: Thrift4Eclipse
1. Click Install
NOTE: It may take some time to install (5mins)
== Standalone Example ==
1. In Eclipse: File` --> `New` --> `Other... (Ctrl+N)` --> `Dynamic Web Project...
1. Project name: ThriftExample
1. In `thrift-`''`version`''`/lib/java` copy libthrift-version.jar to `ThriftExample/WebContent/WEB-INF/lib`
1. In `thrift-`''`version`''`/lib/java/lib` copy all the jars into `ThriftExample/WebContent/WEB-INF/lib`
1. In `ThriftExample/Java Resources/src` create the file `exemple.thrift` with the following content:
{{{
namespace java example
struct BeanExample {
1: bool booleanPrimive;
2: byte bytePrimive;
3: i16 shortPrimive;
4: i32 intPrimive;
5: i64 longPrimive;
6: double doublePrimive;
7: string stringObject; ;
8: binary byteArray; //ByteBuffer
}
service ServiceExample {
BeanExample getBean(1: i32 unArg; 2: string unAutre)
}
}}}
At the command prompt, got to folder containing `example.thrift` (eg. `C:\workspace\ThriftExample\src`) then executethe following command:
{{{
thrift --gen java -out . example.thrift
}}}
1. In Eclipse "refresh" the `ThriftExample` project to show the newly created package `example` below `src`.
1. In the package `example` create the following files:
ServiceExampleImpl.java
{{{
package example;
import java.nio.ByteBuffer;
import org.apache.thrift.TException;
public class ServiceExampleImpl implements ServiceExample.Iface {
@Override
public BeanExample getBean(int unArg, String unAutre) throws TException {
return new BeanExample(true, (byte) 2, (short) 3, 4, 5, 6.0,
"OK", ByteBuffer.wrap(new byte[] { 3, 1, 4 }));
}
}
}}}
ClientExample.java
{{{
package example;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class ClientExample {
private static final int PORT = 7911;
public static void main(String[] args) {
try {
TTransport transport = new TSocket("localhost", PORT);
Protocol protocol = new TBinaryProtocol(transport);
ServiceExample.Client client = new ServiceExample.Client(protocol);
transport.open();
BeanExample bean = client.getBean(1, "string");
transport.close();
System.out.println(bean.getStringObject());
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
}
}
}
}}}
ServerExample.java
{{{
package example;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
public class ServerExample implements Runnable {
private static final int PORT = 7911;
@Override
public void run() {
try {
TServerSocket serverTransport = new TServerSocket(PORT);
ServiceExample.Processor processor = new ServiceExample.Processor(new ServiceExampleImpl());
TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
System.out.println("Starting server on port " + PORT);
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Thread(new ServerExample()).run();
}
}
}}}
1. Execute the server (right-click `ServerExample.java`` --> `Run as` --> `Java Application) to see the message: `Starting server on port 7911`
1. Execute the client (right-click `ClientExample.java`` --> `Run as` --> `Java Application) to see the message: `OK`
NOTE: To stop the serveur you'll need to kill the process via the console.
== Unit Test ==
1. In Eclipse right-click the `ThriftExample` Project` --> `New` --> `Source Folder` --> `Folder name: `test`
1. In `test` create the package `example` then in there create the following file:
TestExample.java
{{{
package example;
import java.io.IOException;
import java.net.URISyntaxException;
import junit.framework.Assert;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestExample {
private static final int PORT = 7911;
@BeforeClass
@SuppressWarnings({ "static-access" })
public static void startServer() throws URISyntaxException, IOException {
// Start thrift server in a seperate thread
new Thread(new ServerExample()).start();
try {
// wait for the server start up
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testExample() throws TTransportException, TException {
TTransport transport = new TSocket("localhost", PORT);
TProtocol protocol = new TBinaryProtocol(transport);
ServiceExample.Client client = new ServiceExample.Client(protocol);
transport.open();
BeanExample bean = client.getBean(1, "string");
transport.close();
Assert.assertEquals("OK", bean.getStringObject());
}
}
}}}
Run the test by right-clicking the file` --> `Run as` --> `JUnit Test
== Thrift Servlet ==
1. In Eclipse: File` --> `New` --> `Servlet:
1. Project: `ThriftExample`
1. Java package: `example`
1. Class name: `TServletExample`
Replace the generated code with the following:
{{{
package example;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TServlet;
public class TServletExample extends TServlet {
public TServletExample() {
super(
new ServiceExample.Processor(
new ServiceExampleImpl()),
new TCompactProtocol.Factory()
);
}
}
}}}
1. Right-click the `TServletExample.java`` --> `Run as` --> `Run on server (hopefully you've already got a server configured ;o)
1. You should get the folling error (don't worry this is good!):
{{{
Error 500
javax.servlet.ServletException: org.apache.thrift.transport.TTransportException
org.apache.thrift.server.TServlet.doPost(TServlet.java:86)
org.apache.thrift.server.TServlet.doGet(TServlet.java:96)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
}}}
This is because we haven't created an HTTP client to communicate with the `TServlet`.<<BR>>
Note the URL if it's not the same as this one: `http://localhost:8080/ThriftExample/TServletExample`<<BR>>
You'll have to replace it in the following code if it's different:
== TServlet Test Unitaire ==
Declare the following fields at the top of the TestExample class:
{{{
private static BasicHttpParams params;
private static ThreadSafeClientConnManager cm;
}}}
Then copy-paste the following code at the end of the `startServer()` method:
{{{
// Set up Thrift HTTP client connection parameters
params = new BasicHttpParams();
params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
params.setParameter("http.protocol.content-charset", "UTF-8");
// Disable Expect-Continue
params.setParameter("http.protocol.expect-continue", false);
// Enable staleness check
params.setParameter("http.connection.stalecheck", true);
HttpConnectionParams.setSoTimeout(params, 10000); // 10 secondes
HttpConnectionParams.setConnectionTimeout(params, 10000); // 10 secondes
ConnManagerParams.setMaxTotalConnections(params, 20);
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 8080));
cm = new ThreadSafeClientConnManager(params, schemeRegistry);
}}}
Then add the following method (replacing the URL if needs be):
{{{
@Test
public void testServlet() throws TTransportException, TException {
// TODO : change this URL if it's not the right one ;o)
// TODO : change this URL if it's not the right one ;o)
// TODO : change this URL if it's not the right one ;o)
String servletUrl = "http://localhost:8080/ThriftExample/TServletExample";
THttpClient thc = new THttpClient(servletUrl, new DefaultHttpClient(cm, params));
TProtocol loPFactory = new TCompactProtocol(thc);
ServiceExample.Client client = new ServiceExample.Client(loPFactory);
BeanExample bean = client.getBean(1, "string");
Assert.assertEquals("OK", bean.getStringObject());
}
}}}
Run the unit tests again to test the `TServlet`: Right-click `TestExample.java`` --> `Run as` --> `JUnit Test.