1.cxf 发布webservice接口
import javax.jws.WebParam; import javax.jws.WebService; import org.apache.cxf.interceptor.InInterceptors; @InInterceptors(interceptors={"com.venustech.tsoc.cupid.hazwww.service.AuthInterceptor"}) @WebService(targetNamespace = "http://service.hazwww.cupid.tsoc.venustech.com",serviceName="HazwService") public interface HazwService { public String platformRegister(@WebParam(name = "xml") String xml); public String platformLogout(@WebParam(name = "xml") String xml); public String systemStatusQuery(); public String riskInformationQuery(@WebParam(name = "xml") String xml); public String alarmsInformationQuery(@WebParam(name = "xml") String xml); }
接口实现类
@WebService(targetNamespace = "http://service.hazwww.cupid.tsoc.venustech.com",serviceName="HazwService") public class HazwServiceImp implements HazwService{ private static Logger logger = Logger.getLogger(HazwServiceImp.class); //告警下发订阅状态 private static int status = 0; @Inject private Dao dao; public static Map<Object,Object> getPlatformCode() { Properties msgConf = new Properties(); String msgConfPath = Cupid.getContextValueAs(String.class, "conf.dir"); msgConfPath = msgConfPath + "/hazwww/platformCode.properties"; InputStream inputStream; Map<Object,Object> map = null ; try { inputStream = new FileInputStream(msgConfPath); msgConf.load(inputStream); inputStream.close(); map = new HashMap<Object, Object>((Map<Object, Object>) msgConf); } catch (Exception e) { e.printStackTrace(); } return map; } /** * A.1 系统级联注册接口 * @param xml * @return */ public String platformRegister(String xml) { //获取配置文件中的接口名和密码 Map<String, String> result; String respXml = ""; try { if(xml.equals("") || xml.isEmpty()) { logger.error("请求xml不能为空"); }else{ result = dealResult(xml); logger.info("获取请求xml报文:" + xml); String platformCode = result.get("PlatformCode"); String platformCode1 = result.get("PlatformCode1"); String ip = result.get("IP"); String ip1 = result.get("IP1"); int port = Integer.parseInt(result.get("Port")); int port1 = Integer.parseInt(result.get("Port1")); //查询当前ip是否注册过 CasRegister ind = dao.fetch(CasRegister.class,Cnd.where("ipUp", "=", ip)); int status = 0; String desc = ""; if(ind == null) { CasRegister cas = new CasRegister(); cas.setId(TblMaxIdHelper.getTblMaxIdWithUpdate(dao,CasRegister.class)); cas.setPlatformCodeUp(platformCode); cas.setPlatformCodeDown(platformCode1); cas.setIpUp(ip); cas.setIpDown(ip1); cas.setPortUp(port); cas.setPortDown(port1); CasRegister insert = dao.insert(cas); if(insert != null) { status = 1; desc = "注册成功!"; respXml = getResponseString(status,desc); } }else{ status = 0; desc = "注册失败,您已注册过该地址,请注销后再注册!"; respXml = getResponseString(status,desc); } } } catch (DocumentException e) { e.printStackTrace(); logger.info("注册异常:" + e); } return respXml; }
使用servlet发布
public class HazwServlet extends CXFNonSpringServlet { private static final long serialVersionUID = -536305948526445202L; private static Logger logger = Logger.getLogger(HazwServlet.class); protected void loadBus(ServletConfig sc) { super.loadBus(sc); Bus b = getBus(); BusFactory.setDefaultBus(b); // 首先,拿到ioc容器 Ioc ioc = Mvcs.ctx.getDefaultIoc(); HazwServiceImp obj = ioc.get(HazwServiceImp.class); try { // 接口类 JaxWsServerFactoryBean sfb = new JaxWsServerFactoryBean (); // 设置服务接口类 sfb.setServiceClass(HazwService.class); // 服务请求路径 sfb.setAddress("/hazwService"); // 设置服务实现类 sfb.setServiceBean(obj); sfb.create(); } catch (Exception e) { e.printStackTrace(); } } }
配置web.xml
<servlet> <servlet-name>HazwServlet</servlet-name> <servlet-class> com.venustech.tsoc.cupid.hazwww.service.HazwServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HazwServlet</servlet-name> <url-pattern>/wss/*</url-pattern> </servlet-mapping>
配置cxf拦截器,验证权限
public class AuthInterceptor extends AbstractPhaseInterceptor<Message> { private static Logger logger = Logger.getLogger(AuthInterceptor.class); private static final String BASIC_PREFIX = "Basic "; //构造方法指定拦截器在什么地方生效 //Phase中常量指定生效位置 如PRE_INVOKE表示调用之前拦截 //RECEIVE 接收消息阶段有效 即使配置在OutInterceptor 的集合中也无效 public AuthInterceptor() { super(Phase.PRE_INVOKE); } @Override public void handleMessage(Message message) throws Fault { HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST); String auth = request.getHeader("Authorization"); if (auth == null) { SOAPException exception = new SOAPException("auth failed, header [Authorization] not exists"); throw new Fault(exception); } if (!auth.startsWith(BASIC_PREFIX)) { SOAPException exception = new SOAPException("auth failed, header [Authorization] is illegal"); throw new Fault(exception); } String plaintext = new String(Base64.decode(auth.substring(BASIC_PREFIX.length()))); if (StringUtils.isEmpty(plaintext) || !plaintext.contains(":")) { SOAPException exception = new SOAPException("auth failed, header [Authorization] is illegal"); throw new Fault(exception); } String[] userAndPass = plaintext.split(":"); String username = userAndPass[0]; String password = userAndPass[1]; if (!"sysadmin".equals(username) || !"venus.sysadmin".equals(password)) { SOAPException exception = new SOAPException("auth failed, username or password is incorrect"); throw new Fault(exception); } }
2.axis 调用webservice接口
public class WSUtil_Superior { /** * 调用接口 * @param ws_url 接口地址 * @param username 接口验证用户名 * @param password 接口验证密码 * @param operationName 调用的接口方法 * @param xml 接口参数xml * @param targetNamespace * @param xml2 * @return */ public static String invokeWS(String ws_url, String username, String password, String operationName, String xml){ String result = ""; try { Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress(ws_url); call.setTimeout(60000); call.setUsername(username); call.setPassword(password); call.setOperationName(new QName("http://service.hazwww.cupid.tsoc.venustech.com", operationName)); call.setReturnType(XMLType.XSD_STRING); if(StringUtils.isBlank(xml)){ result = (String) call.invoke(new Object[]{}); }else{ //添加接口参数 call.addParameter("xml", XMLType.XSD_STRING, ParameterMode.IN); result = (String) call.invoke(new Object[]{xml}); } call = null; } catch (AxisFault e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; } public static void main(String[] args) { String ws_url = "http://192.168.19.197:8888/usm/wss/hazwService?wsdl"; String username = "sysadmin"; String password = "venus.sysadmin"; String operationName = "platformRegister"; String xml ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><PlatformInfo><Higher><PlatformCode>10005</PlatformCode><IP>192.168.19.174</IP><Port>8888</Port></Higher><Lower><PlatformCode>20005</PlatformCode><IP>192.168.19.197</IP><Port>8888</Port></Lower></PlatformInfo>"; String result = invokeWS(ws_url, username, password, operationName, xml); System.out.println(result); } }