文章标签 ‘webservice’
20156 月11

Nutz:集成 CXF Webservice [通过cxf-servlet.xml配置文件]

pom.xml

	<!--CXF START-->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-api</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-bindings-soap</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-ws-security</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-web</artifactId>
           <version>4.1.5.RELEASE</version>
        </dependency>
        <!--CXF END-->

web.xml

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/webservice/*</url-pattern>
    </servlet-mapping>

cxf-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xmlns:soap="http://cxf.apache.org/bindings/soap"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">

    <!-- IP地址输入拦截器 -->
    <bean id="ipAddressInInterceptor"
          class="com.auto.webservice.servlet.IpAddressInInterceptor" />

    <jaxws:server id="workflow" serviceClass="com.auto.webservice.server.WorkflowService" address="/workflow">
        <jaxws:serviceBean>
            <bean class="com.auto.webservice.server.WorkflowServiceImpl" />
        </jaxws:serviceBean>
    </jaxws:server>
</beans>

接口类
WorkflowService.java

package com.auto.webservice.server;

import org.nutz.json.Json;

import javax.jws.WebService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wizzer on 15-4-13.
 */
@WebService(targetNamespace = "http://server.webservice.auto.com/", name = "workflowServicePortType")
public interface WorkflowService {

    @WebResult(name = "return")
    @Action(input = "urn:start", output = "urn:startResponse")
    @RequestWrapper(localName = "start")
    @WebMethod(action = "urn:start")
    @ResponseWrapper(localName = "startResponse")
    String start(@WebParam(name = "flowKey") String flowKey, @WebParam(name = "userId") String userId);//启动流程
}

实现类

WorkflowServiceImpl.java
package com.auto.webservice.server;

import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.StartFormData;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;

import javax.jws.WebService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wizzer on 15-4-13.
 */
@IocBean(name = "workflowService")
@WebService
public class WorkflowServiceImpl implements WorkflowService {
    private final Log log = Logs.get();
    FormService formService=Mvcs.ctx().getDefaultIoc().get(FormService.class);
    IdentityService identityService=Mvcs.ctx().getDefaultIoc().get(IdentityService.class);
    RuntimeService runtimeService=Mvcs.ctx().getDefaultIoc().get(RuntimeService.class);
    TaskService taskService=Mvcs.ctx().getDefaultIoc().get(TaskService.class);
    RepositoryService repositoryService=Mvcs.ctx().getDefaultIoc().get(RepositoryService.class);

    /**
     * 启动一个流程
     *
     * @param flowKey 流程模型key
     * @param userId  用户ID
     * @return
     */
    public String start(String flowKey, String userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (!Strings.isEmpty(userId)) {
                identityService.setAuthenticatedUserId(userId);
            }
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(flowKey);
            map.put("errcode", 0);
            map.put("errmsg", "");
            map.put("processInstanceId", processInstance.getId());
        } catch (Exception e) {
            log.error("WebServcice启动流程出错", e);
            map.put("errcode", 1);
            map.put("errmsg", e.getMessage());
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
        return Json.toJson(map, JsonFormat.compact());
    }


}
 
/**
 * IP地址拦截器
 *
 * @author Sunshine
 */

public class IpAddressInInterceptor extends AbstractPhaseInterceptor {
    private final Log log = Logs.get();

    public IpAddressInInterceptor() {
        super(Phase.RECEIVE);
    }

    public void handleMessage(Message message) throws Fault {
        HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
        //获取所有的白名单访问主机
        UserInfoServiceImpl userInfoService = Mvcs.ctx().getDefaultIoc().get(UserInfoServiceImpl.class);
        List hostList = userInfoService.queryHostListByType("w");
        // 取客户端IP地址
        String ipAddress = request.getRemoteAddr();
        // 如果允许访问的集合非空,继续处理,否则认为全部IP地址均合法
        if (!hostList.isEmpty()) {
            boolean contains = false;
            for (ListInfo hostInfo : hostList) {
                log.debug("hostInfo:" + hostInfo.getIpaddress() + "|ipAddress:" + ipAddress);
                if (hostInfo.getIpaddress().equals(ipAddress)) {
                    contains = true;
                    break;
                }
            }
            if (!contains) {
                throw new Fault(new IllegalAccessException("IP address " + ipAddress + " is not allowed"));
            }
        }
    }

}
20155 月12

Nutz:集成CXF webservice

通过配置文件实现(这个支持CXF spring注解)点这里

pom.xml

	<!--CXF START-->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-api</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-bindings-soap</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>2.7.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-ws-security</artifactId>
            <version>2.7.15</version>
        </dependency>
        <!--CXF END-->

web.xml

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>com.auto.webservice.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/webservice/*</url-pattern>
    </servlet-mapping>
CXFServlet.java:
package com.auto.webservice.servlet;

import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.transport.servlet.CXFNonSpringServlet;
import org.nutz.ioc.Ioc;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;

import javax.jws.WebService;
import javax.servlet.ServletConfig;
import javax.xml.namespace.QName;

/**
 * Created by wizzer on 15-4-10.
 */
@SuppressWarnings("serial")
public class CXFServlet extends CXFNonSpringServlet {
    private final Log log = Logs.get();

    @Override
    protected void loadBus(ServletConfig sc) {
        super.loadBus(sc);

        //全局配置
        Bus bus = getBus();
        //添加白名单过滤器
        bus.getInInterceptors().add(new IpAddressInInterceptor());
        //使用全局配置
        BusFactory.setDefaultBus(bus);
        Ioc ioc = Mvcs.ctx().getDefaultIoc();
        for (String name : ioc.getNames()) {
            try {
                Object obj = ioc.get(null, name);
                if (!obj.getClass().getPackage().getName().equals("com.auto.webservice.server")) {
                    continue;
                }
                if (obj.getClass().getAnnotation(WebService.class) == null)
                    continue;
                Class face = Class.forName(obj.getClass().getPackage().getName() + "." + Strings.upperFirst(name));
                ServerFactoryBean serverFactoryBean = new ServerFactoryBean();
                // 设置服务接口类
                serverFactoryBean.setServiceClass(face);
                // 服务请求路径
                serverFactoryBean.setAddress("/" + name.substring(0, name.indexOf("Service")));
                // 设置服务实现类
                serverFactoryBean.setServiceBean(obj);
                serverFactoryBean.setBindingId("http://schemas.xmlsoap.org/wsdl/soap12/");
                serverFactoryBean.create();
            } catch (Throwable e) {
            }
        }


    }
}

接口类

WorkflowService.java
package com.auto.webservice.server;

import org.nutz.json.Json;

import javax.jws.WebService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wizzer on 15-4-13.
 */
@WebService
public interface WorkflowService {
    String start(String flowKey, String userId);//启动流程

}

 

实现类

WorkflowServiceImpl.java

 

package com.auto.webservice.server;

import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.StartFormData;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;

import javax.jws.WebService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wizzer on 15-4-13.
 */
@IocBean(name = "workflowService")
@WebService
public class WorkflowServiceImpl implements WorkflowService {
    private final Log log = Logs.get();
    @Inject
    Dao dao;
    @Inject
    FormService formService;
    @Inject
    IdentityService identityService;
    @Inject
    RepositoryService repositoryService;
    @Inject
    RuntimeService runtimeService;
    @Inject
    TaskService taskService;

    /**
     * 启动一个流程
     *
     * @param flowKey 流程模型key
     * @param userId  用户ID
     * @return
     */
    public String start(String flowKey, String userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (!Strings.isEmpty(userId)) {
                identityService.setAuthenticatedUserId(userId);
            }
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(flowKey);
            map.put("errcode", 0);
            map.put("errmsg", "");
            map.put("processInstanceId", processInstance.getId());
        } catch (Exception e) {
            log.error("WebServcice启动流程出错", e);
            map.put("errcode", 1);
            map.put("errmsg", e.getMessage());
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
        return Json.toJson(map, JsonFormat.compact());
    }


}

 

20106 月28

PHP webservice客户端 推送文章和附件(xsd:base64Binary)

<?php
//设定字符集
header('Content-Type:text/html;charset=utf-8');

//调用webserver接口class类
require_once('./lib/nusoap.php');

require_once('Article.class.php');     //封装文章信息类
require_once('Attribute.class.php');    //封装字段attr类
require_once('Appendix.class.php');     //封装附件信息类

//-------------------封装推送信息内容开始
$a1 = new Attribute();
$a1->setAttrName('aaa');
$a1->setAttrValue('aaaaa');
$a2 = new Attribute();
$a2->setAttrName('bbb');
$a2->setAttrValue('bbbbbb');
$ar[] = $a1;
$ar[] = $a2;
echo $ar[0]->getAttrName('aaa');

$Article = new Article();
$Article->setArticleContent(mb_convert_encoding('vvvvvvvvvvv<a href="a.txt">a.txt</a>...<img src="tmp.jpg">','UTF-8','GBK'));   //文章正文
$Article->setArticleTitle(mb_convert_encoding("12212AAABBBABAAA".date('Ymd'),'UTF-8','GBK'));   //文章题目
$Article->setAttr($ar);      //文章定制属性组
$Article->setCreateTime(date('YmdHis'));   //文章创立时间
$Article->setDepartment("tongjiju");    //用户部门
$Article->setDescription("description");      //文章描述
$Article->setImportant("0");      //文章级别
$Article->setKeyword("keyword");       //文章关键字
$Article->setLoginName("tongjiju");     //用户登录名
$Article->setModifyTime(date('YmdHis'));   //文章修改时间
$Article->setPassword("tongjiju");     //用登录口令
$Article->setWebName(mb_convert_encoding("市政府子网站群二期 > 市统计局 > 市情简介",'UTF-8','GBK')); //网站的名称
$Article->setCommendId(0);
$client = new nusoap_client("http://221.122.*.*:7006/cmsweb/services/TransferArticle?wsdl", true);
$err = $client->getError();
if ($err) {
echo "<h2>Constructor error</h2><pre>". $err ."</pre>";
}
$godata='';
//文章中存在附件 'finishMark'=>false-------------------------------------------------------------
$godata=array('article'=>$Article,'finishMark'=>false);
$result = $client->call("transferContent", $godata);
if ($client->fault) {
echo "<h2>Fault</h2><pre>";
print_r($result);
echo "</pre>";
} else {
$err = $client->getError();
if ($err) {
   echo "<h2>Error</h2><pre>" . $err . "</pre>";
} else {
   echo "<h2>Result</h2><pre>";
   print_r($result);
   echo "</pre>";
}
}
$aid=$result['transferContentReturn'];

if ($aid){

//第一个附件 'finishMark'=>false-------------------------------------------------------------
$filepath='a.txt';
$fp=fopen($filepath, "rb");
    $filedata=fread($fp, filesize($filepath));
fclose($fp);
$Appendix = new Appendix();
$Appendix->setFileContent(base64_encode($filedata));
$Appendix->setFileName('a.txt');
$Appendix->setFileType('txt');
$godataf=array('aid'=>$aid,'apd'=>$Appendix,'finishMark'=>false);
$resultf = $client->call("transferAppendix", $godataf);
echo '<br><br>';
echo "<h2>Result_f</h2><pre>";
print_r($resultf);
echo "</pre>";

//最后附件 'finishMark'=>true-------------------------------------------------------------
$filepath2='tmp.jpg';
$fp2=fopen($filepath2, "rb");
    $filedata2=fread($fp2, filesize($filepath2));
fclose($fp2);
$Appendix2 = new Appendix();
$Appendix2->setFileContent(base64_encode($filedata2));
$Appendix2->setFileName('tmp.jpg');
$Appendix2->setFileType('image_title');//image_title 此图片为标题图
$godataf2=array('aid'=>$aid,'apd'=>$Appendix2,'finishMark'=>true);
$resultf2 = $client->call("transferAppendix", $godataf2);
echo '<br><br>';
echo "<h2>Result_f2</h2><pre>";
print_r($resultf2);
echo "</pre>";
}
?>