cxf 客户端调用

来源:互联网 发布:js object 转为字符串 编辑:程序博客网 时间:2024/06/04 19:40
,将5种调用方式集中在一个工程中,并使用Maven重组的调用方式。

本例下载地址:

http://dl.iteye.com/topics/download/c647dae6-de86-3eec-9590-7fcf83e9def4

  •   WSDL2Java generated Client
  •   JAX-WS Proxy
  •   JAX-WS Dispatch APIs
  •   JAX-WS Client Proxy
  •   Dynamic Client
    •   Reflection API
    •   Service Model API

在这里Dispatch本节内容不做介绍。

WSDL2Java generated Client

也就是依据wsdl文件生成java客户端,直接调用。查看调用方式,也就是OrderProcessService的getOrderProcessPort方法,获得服务的引用。

启动服务端

mvn test –Pserver

在启动服务端时,通过maven-compiler-plugin编译class,通过cxf-codegen-plugin依据src/main/resources/OrderProcess.wsdl生成存根类OrderProcessService

Xml代码 复制代码收藏代码
  1. <plugins> 
  2.             <plugin> 
  3.                 <artifactId>maven-compiler-plugin</artifactId> 
  4.                 <configuration> 
  5.                     <source>1.5</source> 
  6.                     <target>1.5</target> 
  7.                 </configuration> 
  8.             </plugin> 
  9.             <plugin> 
  10.                 <groupId>org.apache.cxf</groupId> 
  11.                 <artifactId>cxf-codegen-plugin</artifactId> 
  12.                 <version>${cxf.version}</version> 
  13.                 <executions> 
  14.                     <execution> 
  15.                         <id>generate-sources</id> 
  16.                         <phase>generate-sources</phase> 
  17.                         <configuration> 
  18.                             <wsdlOptions> 
  19.                                 <wsdlOption> 
  20.                                     <wsdl>src/main/resources/OrderProcess.wsdl</wsdl> 
  21.                                 </wsdlOption> 
  22.                             </wsdlOptions> 
  23.                         </configuration> 
  24.                         <goals> 
  25.                             <goal>wsdl2java</goal> 
  26.                         </goals> 
  27.                     </execution> 
  28.                 </executions> 
  29.             </plugin> 
  30.         </plugins> 
<plugins>            <plugin>                <artifactId>maven-compiler-plugin</artifactId>                <configuration>                    <source>1.5</source>                    <target>1.5</target>                </configuration>            </plugin>            <plugin>                <groupId>org.apache.cxf</groupId>                <artifactId>cxf-codegen-plugin</artifactId>                <version>${cxf.version}</version>                <executions>                    <execution>                        <id>generate-sources</id>                        <phase>generate-sources</phase>                        <configuration>                            <wsdlOptions>                                <wsdlOption>                                    <wsdl>src/main/resources/OrderProcess.wsdl</wsdl>                                </wsdlOption>                            </wsdlOptions>                        </configuration>                        <goals>                            <goal>wsdl2java</goal>                        </goals>                    </execution>                </executions>            </plugin>        </plugins>

 

启动客户端

mvn test -PStubClient

JAX-WS Proxy

和生成存根类的方式相反,proxy是不需要执行wsdl2java的。但是在编译环境中需要接口类和VO类。这里,通过指定WSDL_LOCATION和PORT_NAME,使用Service.create创建service,使用service.getPort获得服务引用。

Java代码 复制代码收藏代码
  1. package demo.order.client; 
  2.  
  3. import java.net.URL; 
  4. import javax.xml.namespace.QName; 
  5. import javax.xml.ws.Service; 
  6.  
  7. import demo.order.Order; 
  8. import demo.order.OrderProcess; 
  9.  
  10. public class ProxyClient { 
  11.  
  12.     private static final QName SERVICE_NAME = new QName("http://order.demo/", "OrderProcessService"); 
  13.     private static final QName PORT_NAME = new QName("http://order.demo/", "OrderProcessPort"); 
  14.  
  15.     private static final String WSDL_LOCATION = "http://localhost:8080/OrderProcess?wsdl"; 
  16.  
  17.     public static void main(String args[]) throws Exception { 
  18.         URL wsdlURL = new URL(WSDL_LOCATION); 
  19.         Service service = Service.create(wsdlURL, SERVICE_NAME); 
  20.         OrderProcess port = service.getPort(PORT_NAME, OrderProcess.class);   
  21.  
  22.         Order order = new Order(); 
  23.         order.setCustomerID("C001"); 
  24.         order.setItemID("I001"); 
  25.         order.setPrice(100.00); 
  26.         order.setQty(20); 
  27.  
  28.         String result = port.processOrder(order); 
  29.         System.out.println("The order ID is " + result); 
  30.          
  31.     } 
  32.      
package demo.order.client;import java.net.URL;import javax.xml.namespace.QName;import javax.xml.ws.Service;import demo.order.Order;import demo.order.OrderProcess;public class ProxyClient {    private static final QName SERVICE_NAME = new QName("http://order.demo/", "OrderProcessService");    private static final QName PORT_NAME = new QName("http://order.demo/", "OrderProcessPort");    private static final String WSDL_LOCATION = "http://localhost:8080/OrderProcess?wsdl";    public static void main(String args[]) throws Exception {        URL wsdlURL = new URL(WSDL_LOCATION);        Service service = Service.create(wsdlURL, SERVICE_NAME);        OrderProcess port = service.getPort(PORT_NAME, OrderProcess.class);  Order order = new Order();order.setCustomerID("C001");order.setItemID("I001");order.setPrice(100.00);order.setQty(20);        String result = port.processOrder(order);        System.out.println("The order ID is " + result);        }    }

启动服务端

mvn test –Pserver

启动客户端

mvn test -PProxyClient

Client Proxy

使用JaxWsProxyFactoryBean 类简化Proxy。

Java代码 复制代码收藏代码
  1. package demo.order.client; 
  2.  
  3.  
  4. import demo.order.Order; 
  5. import demo.order.OrderProcess; 
  6. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; 
  7.  
  8. public class ClientProxyClient { 
  9.  
  10.     public static void main(String args[]) throws Exception { 
  11.         JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); 
  12.         factory.setServiceClass(OrderProcess.class); 
  13.         factory.setAddress("http://localhost:8080/OrderProcess"); 
  14.         OrderProcess service = (OrderProcess)factory.create(); 
  15.  
  16.         Order order = new Order(); 
  17.         order.setCustomerID("C001"); 
  18.         order.setItemID("I001"); 
  19.         order.setPrice(100.00); 
  20.         order.setQty(20); 
  21.  
  22.         String result = service.processOrder(order); 
  23.         System.out.println("The order ID is " + result); 
  24.          
  25.     } 
  26.      
package demo.order.client;import demo.order.Order;import demo.order.OrderProcess;import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;public class ClientProxyClient {    public static void main(String args[]) throws Exception {        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();        factory.setServiceClass(OrderProcess.class);        factory.setAddress("http://localhost:8080/OrderProcess");        OrderProcess service = (OrderProcess)factory.create();Order order = new Order();order.setCustomerID("C001");order.setItemID("I001");order.setPrice(100.00);order.setQty(20);        String result = service.processOrder(order);        System.out.println("The order ID is " + result);        }    }

启动服务端

mvn test –Pserver

启动客户端

mvn test -PClientProxyClient

Dynamic Client

甚至不需要SEI接口类,

Reflection API

JaxWsDynamicClientFactory.newInstance获得JaxWsDynamicClientFactory实例。通过dcf.createClient获得Client客户端引用。

Java代码 复制代码收藏代码
  1. package demo.order.client; 
  2.  
  3. import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory; 
  4. import org.apache.cxf.endpoint.Client; 
  5.  
  6. import java.lang.reflect.Method; 
  7.  
  8. public class OrderProcessJaxWsDynamicClient { 
  9.     public OrderProcessJaxWsDynamicClient() { 
  10.     } 
  11.  
  12.     public static void main(String str[]) throws Exception { 
  13.         JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); 
  14.         Client client = dcf.createClient("http://localhost:8080/OrderProcess?wsdl"); 
  15.                  
  16.         Object order = Thread.currentThread().getContextClassLoader().loadClass("demo.order.Order").newInstance(); 
  17.         Method m1 = order.getClass().getMethod("setCustomerID", String.class); 
  18.         Method m2 = order.getClass().getMethod("setItemID", String.class); 
  19.         Method m3 = order.getClass().getMethod("setQty", Integer.class); 
  20.         Method m4 = order.getClass().getMethod("setPrice", Double.class); 
  21.         m1.invoke(order, "C001"); 
  22.         m2.invoke(order, "I001"); 
  23.         m3.invoke(order, 100); 
  24.         m4.invoke(order, 200.00); 
  25.                  
  26.         Object[] response = client.invoke("processOrder", order); 
  27.         System.out.println("Response is " + response[0]); 
  28.  
  29.     } 
package demo.order.client;import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;import org.apache.cxf.endpoint.Client;import java.lang.reflect.Method;public class OrderProcessJaxWsDynamicClient {public OrderProcessJaxWsDynamicClient() {}public static void main(String str[]) throws Exception {JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();Client client = dcf.createClient("http://localhost:8080/OrderProcess?wsdl");                Object order = Thread.currentThread().getContextClassLoader().loadClass("demo.order.Order").newInstance();Method m1 = order.getClass().getMethod("setCustomerID", String.class);Method m2 = order.getClass().getMethod("setItemID", String.class);Method m3 = order.getClass().getMethod("setQty", Integer.class);Method m4 = order.getClass().getMethod("setPrice", Double.class);m1.invoke(order, "C001");m2.invoke(order, "I001");m3.invoke(order, 100);m4.invoke(order, 200.00);                Object[] response = client.invoke("processOrder", order);System.out.println("Response is " + response[0]);}}

启动服务端

mvn test –Pserver

启动客户端

mvn test -POrderProcessJaxWsDynamicClient

Service Model API

最后,Service Model是CXF内置的获取Service的信息。

Java代码 复制代码收藏代码
  1. package demo.order.client; 
  2.  
  3. import java.beans.PropertyDescriptor; 
  4. import java.util.List; 
  5.  
  6. import javax.xml.namespace.QName; 
  7.  
  8.  
  9. import org.apache.cxf.endpoint.Client; 
  10. import org.apache.cxf.endpoint.Endpoint; 
  11. import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory; 
  12. import org.apache.cxf.service.model.BindingInfo; 
  13. import org.apache.cxf.service.model.BindingMessageInfo; 
  14. import org.apache.cxf.service.model.BindingOperationInfo; 
  15. import org.apache.cxf.service.model.MessagePartInfo; 
  16. import org.apache.cxf.service.model.ServiceInfo; 
  17.  
  18. public class OrderProcessJaxWsDynClient { 
  19.  
  20.     public OrderProcessJaxWsDynClient() { 
  21.     } 
  22.  
  23.     public static void main(String str[]) throws Exception { 
  24.         JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); 
  25.         Client client = dcf.createClient("http://localhost:8080/OrderProcess?wsdl"); 
  26.         Endpoint endpoint = client.getEndpoint(); 
  27.  
  28.  
  29.         // Make use of CXF service model to introspect the existing WSDL 
  30.         ServiceInfo serviceInfo = endpoint.getService().getServiceInfos().get(0); 
  31.         QName bindingName = new QName("http://order.demo/", "OrderProcessServiceSoapBinding"); 
  32.         BindingInfo binding = serviceInfo.getBinding(bindingName); 
  33.         QName opName = new QName("http://order.demo/", "processOrder"); 
  34.         BindingOperationInfo boi = binding.getOperation(opName); // Operation name is processOrder 
  35.         BindingMessageInfo inputMessageInfo = null; 
  36.         if (!boi.isUnwrapped()) { 
  37.             //OrderProcess uses document literal wrapped style. 
  38.             inputMessageInfo = boi.getWrappedOperation().getInput(); 
  39.         } else { 
  40.             inputMessageInfo = boi.getUnwrappedOperation().getInput(); 
  41.         } 
  42.  
  43.         List<MessagePartInfo> parts = inputMessageInfo.getMessageParts(); 
  44.         MessagePartInfo partInfo = parts.get(0); // Input class is Order 
  45.  
  46.         // Get the input class Order 
  47.         Class<?> orderClass = partInfo.getTypeClass(); 
  48.         Object orderObject = orderClass.newInstance(); 
  49.  
  50.         // Populate the Order bean 
  51.         // Set customer ID, item ID, price and quantity 
  52.         PropertyDescriptor custProperty = new PropertyDescriptor("customerID", orderClass); 
  53.         custProperty.getWriteMethod().invoke(orderObject, "C001"); 
  54.         PropertyDescriptor itemProperty = new PropertyDescriptor("itemID", orderClass); 
  55.         itemProperty.getWriteMethod().invoke(orderObject, "I001"); 
  56.         PropertyDescriptor priceProperty = new PropertyDescriptor("price", orderClass); 
  57.         priceProperty.getWriteMethod().invoke(orderObject, Double.valueOf(100.00)); 
  58.         PropertyDescriptor qtyProperty = new PropertyDescriptor("qty", orderClass); 
  59.         qtyProperty.getWriteMethod().invoke(orderObject, Integer.valueOf(20)); 
  60.  
  61.         // Invoke the processOrder() method and print the result 
  62.         // The response class is String 
  63.         Object[] result = client.invoke(opName, orderObject); 
  64.         System.out.println("The order ID is " + result[0]); 
  65.     } 
package demo.order.client;import java.beans.PropertyDescriptor;import java.util.List;import javax.xml.namespace.QName;import org.apache.cxf.endpoint.Client;import org.apache.cxf.endpoint.Endpoint;import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;import org.apache.cxf.service.model.BindingInfo;import org.apache.cxf.service.model.BindingMessageInfo;import org.apache.cxf.service.model.BindingOperationInfo;import org.apache.cxf.service.model.MessagePartInfo;import org.apache.cxf.service.model.ServiceInfo;public class OrderProcessJaxWsDynClient {    public OrderProcessJaxWsDynClient() {    }    public static void main(String str[]) throws Exception {        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();        Client client = dcf.createClient("http://localhost:8080/OrderProcess?wsdl");        Endpoint endpoint = client.getEndpoint();        // Make use of CXF service model to introspect the existing WSDL        ServiceInfo serviceInfo = endpoint.getService().getServiceInfos().get(0);        QName bindingName = new QName("http://order.demo/", "OrderProcessServiceSoapBinding");        BindingInfo binding = serviceInfo.getBinding(bindingName);        QName opName = new QName("http://order.demo/", "processOrder");        BindingOperationInfo boi = binding.getOperation(opName); // Operation name is processOrder        BindingMessageInfo inputMessageInfo = null;        if (!boi.isUnwrapped()) {            //OrderProcess uses document literal wrapped style.            inputMessageInfo = boi.getWrappedOperation().getInput();        } else {            inputMessageInfo = boi.getUnwrappedOperation().getInput();        }        List<MessagePartInfo> parts = inputMessageInfo.getMessageParts();        MessagePartInfo partInfo = parts.get(0); // Input class is Order        // Get the input class Order        Class<?> orderClass = partInfo.getTypeClass();        Object orderObject = orderClass.newInstance();        // Populate the Order bean        // Set customer ID, item ID, price and quantity        PropertyDescriptor custProperty = new PropertyDescriptor("customerID", orderClass);        custProperty.getWriteMethod().invoke(orderObject, "C001");        PropertyDescriptor itemProperty = new PropertyDescriptor("itemID", orderClass);        itemProperty.getWriteMethod().invoke(orderObject, "I001");        PropertyDescriptor priceProperty = new PropertyDescriptor("price", orderClass);        priceProperty.getWriteMethod().invoke(orderObject, Double.valueOf(100.00));        PropertyDescriptor qtyProperty = new PropertyDescriptor("qty", orderClass);        qtyProperty.getWriteMethod().invoke(orderObject, Integer.valueOf(20));        // Invoke the processOrder() method and print the result        // The response class is String        Object[] result = client.invoke(opName, orderObject);        System.out.println("The order ID is " + result[0]);    }}

启动服务端

mvn test –Pserver

启动客户端

mvn test -POrderProcessJaxWsDynClient 

 

 

 

 

动态调用时cxf有bug,重写了一下

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.cxf.common.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.HashSet;
import java.util.Set;

import org.apache.cxf.helpers.FileUtils;

public class Compiler {
    private long maxMemory = Runtime.getRuntime().maxMemory();
    private boolean verbose;
    private String target;
    private String outputDir;
    private String classPath;
    private boolean forceFork = Boolean.getBoolean(Compiler.class.getName() + "-fork");
   
    public Compiler() {
    }
   
    public void setMaxMemory(long l) {
        maxMemory = l;
    }
    public void setVerbose(boolean b) {
        verbose = b;
    }
    public void setTarget(String s) {
        target = s;
    }
    public void setOutputDir(File s) {
        if (s != null) {
            outputDir = s.getAbsolutePath().replace(File.pathSeparatorChar, '/');
        } else {
            outputDir = null;
        }
    }
    public void setOutputDir(String s) {
        outputDir = s.replace(File.pathSeparatorChar, '/');
    }
    public void setClassPath(String s) {
        classPath = StringUtils.isEmpty(s) ? null : s;
    }
   
    private void addArgs(List<String> list) {
        if (verbose) {
            list.add("-verbose");
        }
        if (!StringUtils.isEmpty(target)) {
            list.add("-target");
            list.add(target);
        }

        if (!StringUtils.isEmpty(outputDir)) {
            list.add("-d");
            list.add(outputDir);
        }
       
        if (StringUtils.isEmpty(classPath)) {
            String javaClasspath = System.getProperty("java.class.path");
            boolean classpathSetted = javaClasspath != null ? true : false;
            if (!classpathSetted) {
                File f = new File(getClass().getClassLoader().getResource(".").getFile());
                f = new File(f, "../lib");
                if (f.exists() && f.isDirectory()) {
                    list.add("-extdirs");
                    list.add(f.toString());                   
                }
            } else {
                list.add("-classpath");
                list.add(javaClasspath);
            }
        } else {
            list.add("-classpath");
            list.add(classPath);
        }

    }
   
    public boolean compileFiles(String[] files) {
        String endorsed = System.getProperty("java.endorsed.dirs");
        if (!forceFork) {
            try {
                Class.forName("javax.tools.JavaCompiler");
                return useJava6Compiler(files);
            } catch (Exception ex) {
                //ignore - fork javac
            }
        }
       
        List<String> list = new ArrayList<String>();

        // Start of honoring java.home for used javac
        String fsep = System.getProperty("file.separator");
        String javacstr = "javac";
        String platformjavacname = "javac";

        if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
            platformjavacname = "javac.exe";
        }

        if (new File(System.getProperty("java.home") + fsep + platformjavacname).exists()) {
            // check if java.home is jdk home
            javacstr = System.getProperty("java.home") + fsep + platformjavacname;
        } else if (new File(System.getProperty("java.home") + fsep + ".." + fsep + "bin" + fsep
                            + platformjavacname).exists()) {
            // check if java.home is jre home
            javacstr = System.getProperty("java.home") + fsep + ".." + fsep + "bin" + fsep
                       + platformjavacname;
        }

        list.add(javacstr);
        // End of honoring java.home for used javac

        if (!StringUtils.isEmpty(endorsed)) {
            list.add("-endorseddirs");
            list.add(endorsed);
        }

        //fix for CXF-2081, set maximum heap of this VM to javac.
        list.add("-J-Xmx" + maxMemory);

        addArgs(list);
       
        int idx = list.size();
        list.addAll(Arrays.asList(files));

        return internalCompile(list.toArray(new String[list.size()]), idx);
    }

    private boolean useJava6Compiler(String[] files)
        throws Exception {
       
        Object compiler = Class.forName("javax.tools.ToolProvider")
            .getMethod("getSystemJavaCompiler").invoke(null);
        Object fileManager = compiler.getClass().getMethod("getStandardFileManager",
                                                           Class.forName("javax.tools.DiagnosticListener"),
                                                           Locale.class,
                                                           Charset.class).invoke(compiler, null, null, null);
        Object fileList = fileManager.getClass().getMethod("getJavaFileObjectsFromStrings", Iterable.class)
            .invoke(fileManager, Arrays.asList(files));
       
       
        List<String> args = new ArrayList<String>();
        addArgs(args);
        Object task = compiler.getClass().getMethod("getTask",
                                                    Writer.class,
                                                    Class.forName("javax.tools.JavaFileManager"),
                                                    Class.forName("javax.tools.DiagnosticListener"),
                                                    Iterable.class,
                                                    Iterable.class,
                                                    Iterable.class)
                                                    .invoke(compiler, null, fileManager, null,
                                                            args, null, fileList);
        Boolean ret = (Boolean)task.getClass().getMethod("call").invoke(task);
        fileManager.getClass().getMethod("close").invoke(fileManager);
        return ret;
    }

   public boolean internalCompile(String[] args, int sourceFileIndex) {
        Process p = null;
        String cmdArray[] = null;
        File tmpFile = null;
  String pathString = "";
  int flagPath=0;
  boolean isWeblogic = true;
        try {
            if (isLongCommandLines(args) && sourceFileIndex >= 0) {
                PrintWriter out = null;
                tmpFile = FileUtils.createTempFile("cxf-compiler", null);
                out = new PrintWriter(new FileWriter(tmpFile));
                for (int i = sourceFileIndex; i < args.length; i++) {
                    if (args[i].indexOf(" ") > -1) {
                        args[i] = args[i].replace(File.separatorChar, '/');
                        //
                        // javac gives an error if you use forward slashes
                        // with package-info.java. Refer to:
                        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6198196
                        //
                        if (args[i].indexOf("package-info.java") > -1
                            && System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
                            out.println("\"" + args[i].replaceAll("/", "\\\\\\\\") + "\"");
                        } else {
                            out.println("\"" + args[i] + "\"");
                        }
                    } else {
                        out.println(args[i]);
                    }
                }
                out.flush();
                out.close();
                cmdArray = new String[sourceFileIndex + 1];
                System.arraycopy(args, 0, cmdArray, 0, sourceFileIndex);
                cmdArray[sourceFileIndex] = "@" + tmpFile;
            } else {
                cmdArray = new String[args.length];
                System.arraycopy(args, 0, cmdArray, 0, args.length);
            }

            if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
                for (int i = 0; i < cmdArray.length; i++) {
                    if (cmdArray[i].indexOf("package-info") == -1) {
                      //  cmdArray[i] = cmdArray[i].replace('\\', '/');
                    }
     if(isWeblogic){
       if (!(cmdArray[i].indexOf("weblogic") == -1)) {
        pathString = cmdArray[i];
        flagPath = i;
                    }
     }

                }
            }
        if(isWeblogic){
         pathString = pathString.replaceAll(" ", "");
   String array[] = pathString.split(";");
         ArrayList<String> arrayList=new ArrayList<String>();
   for (int i = 0; i < array.length; i++) {
    String arr=array[i].substring(0, array[i].lastIndexOf(System.getProperty("file.separator")))+System.getProperty("file.separator")+"*.jar;";
    if(!arrayList.contains(arr)){
        arrayList.add(arr);
       }
   }
   StringBuilder builder = new StringBuilder();
   for(String arry:arrayList){
    builder.append(arry);
   }
            cmdArray[flagPath] = builder.toString();
  }
             p= Runtime.getRuntime().exec(cmdArray);
            if (p.getErrorStream() != null) {
                StreamPrinter errorStreamPrinter = new StreamPrinter(p.getErrorStream(), "", System.out);
                errorStreamPrinter.start();
            }

            if (p.getInputStream() != null) {
                StreamPrinter infoStreamPrinter = new StreamPrinter(p.getInputStream(), "[INFO]", System.out);
                infoStreamPrinter.start();
            }

            if (p != null) {
                return p.waitFor() == 0 ? true : false;
            }
        } catch (SecurityException e) {
            System.err.println("[ERROR] SecurityException during exec() of compiler \"" + args[0] + "\".");
        } catch (InterruptedException e) {
            // ignore

        } catch (IOException e) {
            System.err.print("[ERROR] IOException during exec() of compiler \"" + args[0] + "\"");
            System.err.println(". Check your path environment variable.");
        } finally {
            if (tmpFile != null && tmpFile.exists()) {
                FileUtils.delete(tmpFile);
            }
        }

        return false;
    }

    private boolean isLongCommandLines(String args[]) {
        StringBuilder strBuffer = new StringBuilder();
        for (int i = 0; i < args.length; i++) {
            strBuffer.append(args[i]);
        }
        return strBuffer.toString().length() > 4096 ? true : false;
    }

   
}

 

原创粉丝点击