OSGi环境中部署XML-RPC Server
private WebServer webServer;
public void start(BundleContext context) throws Exception {
webServer = new WebServer(Integer.parseInt("8080"));
XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
//phm.setRequestProcessorFactoryFactory(new MyRequestProcessorFactoryFactory(new Class[]{BundleContext.class}, new Object[]{context}));
//phm.setTypeConverterFactory(new MyTypeConverterFactoryImpl());
phm.addHandler("service", CommunicationImpl.class);
phm.addHandler("Calculator", Calculator.class);
xmlRpcServer.setHandlerMapping(phm);
XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();
serverConfig.setEnabledForExtensions(true);
serverConfig.setContentLengthOptional(false);
webServer.start();
}
public void stop(BundleContext context) throws Exception {
webServer.shutdown();
}
Ref: http://ws.apache.org/xmlrpc/server.html
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.addHandler("service", CommunicationImpl.class);
以上语句可使CommunicationImpl的方法作为XML-RPC服务发布。在客户端调用CommunicationImpl的实例方法时,该服务端程序会实例化CommunicationImpl对象。
但实例化时,默认情况下仅调用CommunicationImpl的默认构造函数(无参数的构造函数)。
场景一 (支持带参数构造函数)
若要使服务端程序实例化CommunicationImpl对象时,调用CommunicationImpl的带参数的构造函数,如OSGi环境下CommunicationImpl的构造函数可能是CommunicationImpl(BundleContext context),改如何做呢?
对于此场景,具体方法如下:
1 创建RequestProcessorFactoryFactory的子类,
并重写getRequestProcessor(Class, XmlRpcRequest)方法。
2 调用setRequestProcessorFactoryFactory方法,设定1步中创建的实例。
如:
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.setRequestProcessorFactoryFactory(new MyRequestProcessorFactoryFactory(new Class[]{BundleContext.class}, new Object[]{context}));
public class MyRequestProcessorFactoryFactory extends RequestSpecificProcessorFactoryFactory {
private Class[] clazz = null;
private Object[] objs = null;
public MyRequestProcessorFactoryFactory() {
this.clazz = null;
this.objs = null;
}
public MyRequestProcessorFactoryFactory(Class[] clazz, Object[] objs) {
this.clazz = clazz;
this.objs = objs;
}
protected Object getRequestProcessor(Class pClass, XmlRpcRequest pRequest) throws XmlRpcException {
// return Util.newInstance(pClass);
if(clazz == null && objs == null) {
return org.apache.xmlrpc.metadata.Util.newInstance(pClass);
}else {
try {
Constructor cst = pClass.getConstructor(clazz);
return cst.newInstance(objs);
} catch (...) {
...
}
}