Tuesday, February 16, 2016

REST via Service Bean


This is based on Custom REST service in Xpages using a service bean by Stephan Wissel. But it doesn't show actually getting prints from the method sent. My work partner Brian Hester  and I both tried at the same time and ended up getting it at the same time – we actually started IM-ing each other that we had it. And this is the day before Bernd Hort posted his presentation.

So to intercept the REST methods, so you can get prints like this:

02/11/2016 09:06:26 AM HTTP JVM: renderService
02/11/2016 09:06:26 AM HTTP JVM: rType: GET
02/11/2016 09:06:40 AM HTTP JVM: renderService
02/11/2016 09:06:40 AM HTTP JVM: rType: POST

Once you get the method, you can have the bean do whatever you would like. It's nice to have it all in one place.

Here is the bean:
package com.companyname;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;

public class DynamicViewService extends CustomServiceBean {

public void DynamicViewService() {

System.out.println("init...");

}

@Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
System.out.println("renderService");
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();

response.setHeader("Content-Type", "application/json; charset=UTF-8");

// Here goes your code, get the response writer or stream
String rType = request.getMethod();
System.out.println("rType: " + rType);
try {
response.getWriter().write("<html><body>" + rType + "</body></html>");
response.getWriter().close();
return;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
return;
}
}

}


And here is the full Xpage:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core"
xmlns:xe="http://www.ibm.com/xsp/coreex">
<xe:restService id="JSONSearch" pathInfo="json" state="false">
<xe:this.service>
<xe:customRestService
contentType="application/json"
serviceBean="com.randstadusa.DynamicViewService">
</xe:customRestService>
</xe:this.service>
</xe:restService>
<xp:br></xp:br>
<xp:br></xp:br>
</xp:view>