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); } }