|
今回のPingアプリケーションの機能要件とは直接関係ないですが、Pingを受け取るServletを作ってみました。Ping対象サーバとしてこのServletを指定しておいて、確かにPingがうたれたことをログに残すなど、なんか使い道もありそうです。 うけつけるサーブレットでは、おなじみのApache XML-RPCを用います。 サーブレットのクラス名は nu.mine.kino.servlets.ping.PingReceiver としました。 サーブレットのdoPostを以下の通りOverrideします。 protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
logger.debug("doPost(HttpServletRequest, HttpServletResponse) - start");
XmlRpc.setEncoding("UTF-8");
XmlRpcServer xmlrpc = new XmlRpcServer();
// Handlerの追加。このハンドラは、weblogUpdates.ping というサービスを持っている。
// pingはメソッド名。
xmlrpc.addHandler("weblogUpdates", new UpdateHandler()); // 後述
try {
byte[] result = xmlrpc.execute(request.getInputStream());
response.setContentType("text/html");
response.setContentLength(result.length);
OutputStream out = response.getOutputStream();
out.write(result);
out.flush();
} catch (IOException e) {
logger.error("doPost(HttpServletRequest, HttpServletResponse)", e);
}
logger.debug("doPost(HttpServletRequest, HttpServletResponse) - end");
}
ここで xmlrpc.addHandler("weblogUpdates", new UpdateHandler()); // 後述
の意味ですが、このエンドポイントのweblogUpdates.hogeというメソッド名がよばれたら、UpdateHandler?というクラスのhogeというメソッドを呼び出すよ、という意味になります。 UpdateHandler?は特別なインタフェースを実装するわけではなく、hogeに相当するメソッドを定義しておきます。具体的には以下の通り。 public class UpdateHandler {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(UpdateHandler.class);
// pingというメソッド名を定義
public Hashtable ping(String name, String url) throws Exception {
logger.debug("ping(String, String) - start");
logger.debug("Name: " + name);
logger.debug("url : " + url);
Hashtable result_hash = new Hashtable();
result_hash.put("name", name);
result_hash.put("url", url);
result_hash.put("message", "Thanks for the ping");
result_hash.put("error", Boolean.FALSE);
logger.debug("ping(String, String) - end");
return result_hash;
}
}
これで、このエンドポイントのweblogUpdates.pingというメソッド名がよばれたら、このクラスのpingメソッドが呼び出されます*1。 ちなみに、このサービスのエンドポイントは http://[サーバ名]/[context]/[サーブレット名] となります。ここでは http://localhost:8080/PingWeb/PingReceiver としました。 この記事は 現在のアクセス:7400 |