houyouliang / dozer

0 stars 0 forks source link

webserviceUtil #4

Open houyouliang opened 7 years ago

houyouliang commented 7 years ago

public class WebServiceUtils {

private static final Logger logger = LoggerFactory.getLogger(WebServiceUtils.class);

/**
 * 将webservice返回结果生成的类转化到目标类中
 * 
 * <p>
 * 
 * </p>
 * 
 * @param sourceObj
 *            需要访问的wsdl地址
 * @param targetObj
 *            请求wsdl地址需要的请求参数
 * @param fieldRequest
 *            上传的源文件jar包的地址可以通过wsimport自动生成
 * @param className
 *            源类文件 包名+类名
 * @return 返回结果为生成的源目标的java类
 * 
 * @see XmlAndJsonUtil
 * */
public static Object fromSourceToTarget(Object sourceObj, Object targetObj, FieldRequest fieldRequest) {
    Object obj = XmlAndJsonUtil.xmlOrJsonToObject(sourceObj, targetObj, fieldRequest);
    return obj;
}

/**
 * 根据提交的jar包及类将返回的字符串转成java类
 * 
 * <p>
 * 
 * Object obj =
 * WebServiceUtils.fromJsonToObject("http://localhost/soap/flight",
 * "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:int=\"http://inter.webservice.demo.psdp.com/\"><soapenv:Header/><soapenv:Body><int:shopping><arg0><channel>10</channel><arrv><arrvCode>PEK</arrvCode><deptCode>SHA</deptCode></arrv><backDate>2017-10-11</backDate><dept><arrvCode>SHA</arrvCode><deptCode>PEK</deptCode></dept><deptDate>2017-10-10</deptDate></arg0></int:shopping></soapenv:Body></soapenv:Envelope>";"
 * , "shopping", "E:/targetfile/shopping.jar",
 * "com.psdp.demo.bean.ShoppingRes"); System.out.println(new
 * GsonBuilder().create().toJson(obj));
 * </p>
 * 
 * @param wsdl
 *            需要访问的wsdl地址
 * @param params
 *            请求wsdl地址需要的请求参数
 * @param jarPath
 *            上传的源文件jar包的地址可以通过wsimport自动生成
 * @param className
 *            源类文件 包名+类名
 * @return 返回结果为生成的源目标的java类
 * */
public static Object fromJsonToObject(String wsdl, String params, String jarPath, String className) {
    String xml = visitWebService(wsdl, params);
    // 将webservice接口返回的数据转化为json数组
    JSONArray jsonArray = XmlBeanUtils.performRequest(xml);
    URLClassLoader urlClassLoader = null;
    Object res = null;
    try {
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        // 判断是否有生成jar包
        if (StringUtils.isNotEmpty(jarPath))  {
            // 根据提交的jar包获取类加载器
            urlClassLoader = new URLClassLoader(new URL[] { new URL("file:" + jarPath) });
            // 加载用户指定的类
            Class<?> clazz = urlClassLoader.loadClass(className);
            // 将获取的json对象转化为java对象
            res = JsonUtils.formJSONString(jsonObject.toJSONString(), clazz);
        } else {
            // 如果没有提交jar包则直接返回json字符串
            return jsonObject.toString();
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        // 判断类加载器是否为空如果不为空则调用close方法停掉
        if (urlClassLoader != null) {
            try {
                urlClassLoader.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }
    return res;
}

/**
 * 根据提交的参数获取webservice返回的xml文件信息
 * 
 * visitWebService("http://localhost/soap/flight", "<int:shopping/>")
 * 
 * @param wsdl
 *            提交的webservice地址
 * @param params
 *            webservice请求参数
 * @return 返回对应weservice 请求结果
 * */
public static String visitWebService(String wsdl, String params) {
    OutputStream os = null;
    HttpURLConnection conn = null;
    StringBuffer stringBuffer = new StringBuffer();
    InputStream is = null;
    try {
        // wsdl地址
        URL wsUrl = new URL(wsdl);
        conn = (HttpURLConnection) wsUrl.openConnection();
        // 设置输入操作为true
        conn.setDoInput(true);
        // 设置输出操作为true
        conn.setDoOutput(true);
        // 设置请求方式为POST
        conn.setRequestMethod("POST");
        // 设置请求类型为xml字符编码为UTF-8
        conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
        // 创建输出流
        os = conn.getOutputStream();
        // 将请求参数写入输出流
        os.write(params.getBytes());
        // 创建输入流
        is = conn.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = is.read(b)) != -1) {
            String ss = new String(b, 0, len, "UTF-8");
            stringBuffer.append(ss);
        }
        return stringBuffer.toString();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        logger.error(e.getMessage());
        return null;
    } finally {
        try {
            // 判断输入流是否为空,如果不为空则调用close方法关闭
            if (is != null) {
                is.close();
            }
            // 判断输出流是否为空,如果不为空则调用close方法关闭
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        // 判断连接是否为空如果不为空,则调用disconnect方法断开连接
        if (conn != null) {
            conn.disconnect();
        }
    }
}
houyouliang commented 7 years ago

@Test public void getWebServiceResponse() { String xml = WebServiceUtils.visitWebService(url, params); String xmlTypeName = findClassName(xml); String fileTemp = String.valueOf(System.currentTimeMillis()); String webserviceclass = "E:/webserviceclass/"; String javaSourcePath = webserviceclass + fileTemp + "/"; File javaSourceFile = new File(javaSourcePath); if (!javaSourceFile.exists()) { javaSourceFile.mkdirs(); } String packageName = "com.flight.mu"; String jarPath = "E:/webservicejar/" + packageName.replaceAll("\.", "/") + "/" + fileTemp + ".jar"; String wsimportCommand = "wsimport -d "+javaSourcePath+" -p "+packageName+" " + url; String jarCommand = "jar cvf "+jarPath+" -C "+ javaSourcePath + " ."; File jarFile = new File(jarPath); // 检测是否存在目录 if (!jarFile.getParentFile().exists()) { jarFile.getParentFile().mkdirs(); } if (jarFile.exists()) { jarFile.delete(); } try { System.out.println("run javac reslt code:" + Runtime.getRuntime().exec(CommandUtils.getOSCommand(wsimportCommand)).waitFor()); System.out.println("run javac reslt code:" + Runtime.getRuntime().exec(CommandUtils.getOSCommand(jarCommand)).waitFor()); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(getClassName(xmlTypeName, jarPath)); }