To demonstrate the capabilities of the Web Service module in Pipes we wrote a simple web service in Java.
Below is the source code for the example web service that is called in this Pipe.
The web service below accepts JSON input, then appends some text to the title of each item, and emits the response in JSON format.
package util;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Simple example Web Service used to demonstrate the Pipes Web Service module
*
* @author Ido Green
*/
public class PipeWSTestServlet extends HttpServlet {
private static Logger logger = Logger.getLogger(PipeWSTestServlet.class
.getName());
/**
*
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
String data = request.getParameter("data");
if (data == null) {
// Nothing was received so notify the user
response.setContentType("text/xml");
out.println("\n");
out.println("No input data!\n");
return;
}
// Get the data from Pipes
JSONObject jsonObj = new JSONObject(data);
// Parse the data according to the list of the items in the feed
JSONArray items = jsonObj.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
// Run through the items
JSONObject item = items.getJSONObject(i);
// Only change the title, append the text (This text was added by the external Web Service)
String title = item.getString("title");
title += " (This text was added by the external Web Service)";
item.put("title", title);
items.put(i, item);
}
data = jsonObj.toString(1);
// Return the changes in JSON format to Pipes
response.setContentType("application/json");
out.println(data);
} catch (Exception e) {
String errMsg = stackToString(e);
logger.severe(errMsg);
response.setContentType("application/json");
out.println("\n");
out.println(" " + errMsg + "");
}
}
/**
* This method helps us get the stack trace as a string,
* in most cases you will want it in your 'util' pkg.
* @param e
* @return the stack trace of an exception
*/
private String stackToString(Exception e) {
if (e != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString() + "\n";
} catch (Exception ex) {
return "Could not show the stackTrace in String\n"
+ ex.getMessage();
}
}
return "";
}
}