Home » geronimo-2.2-source-release » org.apache.geronimo.jaxws.wsdl » [javadoc | source]

    1   /**
    2    *  Licensed to the Apache Software Foundation (ASF) under one or more
    3    *  contributor license agreements.  See the NOTICE file distributed with
    4    *  this work for additional information regarding copyright ownership.
    5    *  The ASF licenses this file to You under the Apache License, Version 2.0
    6    *  (the "License"); you may not use this file except in compliance with
    7    *  the License.  You may obtain a copy of the License at
    8    *
    9    *     http://www.apache.org/licenses/LICENSE-2.0
   10    *
   11    *  Unless required by applicable law or agreed to in writing, software
   12    *  distributed under the License is distributed on an "AS IS" BASIS,
   13    *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   14    *  See the License for the specific language governing permissions and
   15    *  limitations under the License.
   16    */
   17   package org.apache.geronimo.jaxws.wsdl;
   18   
   19   import java.io.ByteArrayOutputStream;
   20   import java.io.File;
   21   import java.io.FileFilter;
   22   import java.io.IOException;
   23   import java.io.InputStream;
   24   import java.io.OutputStream;
   25   import java.net.MalformedURLException;
   26   import java.net.URL;
   27   import java.net.URLClassLoader;
   28   import java.util.ArrayList;
   29   import java.util.LinkedHashSet;
   30   import java.util.List;
   31   import java.util.Random;
   32   import java.util.Set;
   33   
   34   import org.apache.geronimo.deployment.DeploymentContext;
   35   import org.apache.geronimo.j2ee.deployment.Module;
   36   import org.apache.geronimo.kernel.config.Configuration;
   37   import org.apache.geronimo.kernel.config.ConfigurationResolver;
   38   import org.apache.geronimo.kernel.config.MultiParentClassLoader;
   39   import org.apache.geronimo.kernel.config.NoSuchConfigException;
   40   import org.slf4j.Logger;
   41   import org.slf4j.LoggerFactory;
   42   
   43   public class WsdlGeneratorUtils {
   44   
   45       private static final Logger LOG = LoggerFactory.getLogger(WsdlGeneratorUtils.class);
   46       
   47       public static void getModuleClasspath(Module module, DeploymentContext context, StringBuilder classpath) throws Exception {
   48           LinkedHashSet<URL> jars = new LinkedHashSet<URL>();
   49           getModuleClasspath(module, context, jars);
   50           buildClasspath(jars, classpath);
   51       }
   52       
   53       public static void getModuleClasspath(Module module, DeploymentContext context, LinkedHashSet<URL> classpath) throws Exception {        
   54           getModuleClasspath(module.getEarContext(), classpath);       
   55           if (module.getRootEarContext() != module.getEarContext()) {
   56               getModuleClasspath(module.getRootEarContext(), classpath);
   57           }         
   58       }
   59   
   60       public static void getModuleClasspath(DeploymentContext deploymentContext, LinkedHashSet<URL> classpath) throws Exception {
   61           Configuration configuration = deploymentContext.getConfiguration();
   62           getModuleClasspath(configuration, classpath);
   63       }
   64       
   65       public static void getModuleClasspath(Configuration configuration, LinkedHashSet<URL> classpath) throws Exception {
   66           ConfigurationResolver resolver = configuration.getConfigurationResolver();
   67           List<String> moduleClassPath = configuration.getClassPath();
   68           for (String pattern : moduleClassPath) {
   69               try {
   70                   Set<URL> files = resolver.resolve(pattern);
   71                   classpath.addAll(files);
   72               } catch (MalformedURLException e) {
   73                   throw new Exception("Could not resolve pattern: " + pattern, e);
   74               } catch (NoSuchConfigException e) {
   75                   throw new Exception("Could not resolve pattern: " + pattern, e);
   76               }
   77           }
   78       }
   79       
   80       public static Set<URL> getClassLoaderClasspath(ClassLoader loader) {
   81           LinkedHashSet<URL> jars = new LinkedHashSet<URL>();
   82           getClassLoaderClasspath(loader, jars);
   83           return jars;        
   84       }
   85       
   86       public static void getClassLoaderClasspath(ClassLoader loader, LinkedHashSet<URL> classpath) {
   87           if (loader == null || loader == ClassLoader.getSystemClassLoader()) {
   88               return;
   89           } else if (loader instanceof MultiParentClassLoader) {
   90               MultiParentClassLoader cl = (MultiParentClassLoader)loader;
   91               for (ClassLoader parent : cl.getParents()) {   
   92                   getClassLoaderClasspath(parent, classpath);
   93               }
   94               for (URL u : cl.getURLs()) {
   95                   classpath.add(u);
   96               }
   97           } else if (loader instanceof URLClassLoader) {
   98               URLClassLoader cl = (URLClassLoader)loader;
   99               getClassLoaderClasspath(cl.getParent(), classpath);
  100               for (URL u : cl.getURLs()) {
  101                   classpath.add(u);
  102               }
  103           } else {
  104               getClassLoaderClasspath(loader.getParent(), classpath);
  105           }
  106       }
  107       
  108       public static String buildClasspath(Set<URL> files) {
  109           StringBuilder classpath = new StringBuilder();
  110           buildClasspath(files, classpath);
  111           return classpath.toString();
  112       }
  113       
  114       public static void buildClasspath(Set<URL> files, StringBuilder classpath) {
  115           for (URL url: files) {
  116               if ("file".equals(url.getProtocol())) {
  117                   String path = toFileName(url);
  118                   classpath.append(path);
  119                   classpath.append(File.pathSeparator);
  120               }
  121           }
  122       }
  123       
  124       public static String getClasspath(ClassLoader loader) {
  125           Set<URL> jars = getClassLoaderClasspath(loader);
  126           return buildClasspath(jars);
  127       }
  128       
  129       public static File toFile(URL url) {
  130           if (url == null || !url.getProtocol().equals("file")) {
  131               return null;
  132           } else {
  133               String filename = toFileName(url);
  134               return new File(filename);
  135           }
  136       }
  137       
  138       public static String toFileName(URL url) {
  139           String filename = url.getFile().replace('/', File.separatorChar);
  140           int pos =0;
  141           while ((pos = filename.indexOf('%', pos)) >= 0) {
  142               if (pos + 2 < filename.length()) {
  143                   String hexStr = filename.substring(pos + 1, pos + 3);
  144                   char ch = (char) Integer.parseInt(hexStr, 16);
  145                   filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);
  146               }
  147           }
  148           return filename;
  149       }
  150       
  151       public static File createTempDirectory(File baseDir) throws IOException {
  152           Random rand = new Random();       
  153           while(true) {
  154               String dirName = String.valueOf(Math.abs(rand.nextInt()));        
  155               File dir = new File(baseDir, dirName);
  156               if (!dir.exists()) {
  157                   if (!dir.mkdir()) {
  158                       throw new IOException("Failed to create temporary directory: " + dir);
  159                   } else {
  160                       return dir;
  161                   }
  162               }
  163           }               
  164       }
  165       
  166       private static File[] getWsdlFiles(File baseDir) {
  167           File[] files = baseDir.listFiles(new FileFilter() {
  168               public boolean accept(File file) {
  169                   return (file.isFile() && file.getName().endsWith(".wsdl"));
  170               }
  171           });
  172           return files;
  173       }
  174       
  175       public static File findWsdlFile(File baseDir, String serviceName) {
  176           File[] files = getWsdlFiles(baseDir);
  177           if (files == null || files.length == 0) {
  178               // no wsdl files found
  179               return null;
  180           } else {
  181               if (files.length == 1) {
  182                   // found one wsdl file, must be it
  183                   return files[0];
  184               } else if (serviceName != null) {
  185                   // found multiple wsdl files, check filenames to match serviceName          
  186                   String wsdlFileName = serviceName + ".wsdl";
  187                   for (File file : files) {
  188                       if (wsdlFileName.equalsIgnoreCase(file.getName())) {
  189                           return file;
  190                       }
  191                   }
  192                   return null;
  193               } else {
  194                   // found multiple wsdl files and serviceName is not specified 
  195                   // so we don't know which wsdl file is the right one
  196                   return null;
  197               }
  198           }
  199       }
  200       
  201       public static String getRelativeNameOrURL(File baseDir, File file) {
  202           String basePath = baseDir.getAbsolutePath();
  203           String path = file.getAbsolutePath();
  204           
  205           if (path.startsWith(basePath)) {
  206               if (File.separatorChar == path.charAt(basePath.length())) {
  207                   return path.substring(basePath.length() + 1);
  208               } else {
  209                   return path.substring(basePath.length());
  210               }
  211           } else {
  212               return file.toURI().toString();
  213           }
  214       }
  215       
  216       public static boolean execJava(List<String> arguments, long timeout) throws Exception {           
  217           List<String> cmd = new ArrayList<String>();
  218           String javaHome = System.getProperty("java.home");                       
  219           String java = javaHome + File.separator + "bin" + File.separator + "java";
  220           cmd.add(java);
  221           cmd.addAll(arguments);
  222           return exec(cmd, timeout);
  223       }
  224       
  225       public static boolean exec(List<String> cmd, long timeout) throws Exception {        
  226           LOG.debug("Executing process: {}", cmd);
  227                 
  228           ProcessBuilder builder = new ProcessBuilder(cmd);
  229           builder.redirectErrorStream(true);
  230                   
  231           Process process = builder.start();
  232           return waitFor(process, timeout);
  233       }
  234       
  235       private static boolean waitFor(Process process, long timeout) throws Exception {  
  236           CaptureOutputThread outputThread = new CaptureOutputThread(process.getInputStream());
  237           outputThread.start();        
  238                   
  239           long sleepTime = 0;        
  240           while(sleepTime < timeout) {            
  241               try {
  242                   int errorCode = process.exitValue();
  243                   if (errorCode == 0) {
  244                       LOG.debug("Process output: {}", outputThread.getOutput());
  245                       return true;
  246                   } else {
  247                       LOG.error("Process failed: {}", outputThread.getOutput()); 
  248                       return false;
  249                   }
  250               } catch (IllegalThreadStateException e) {
  251                   // still running
  252                   try {
  253                       Thread.sleep(WsdlGeneratorOptions.FORK_POLL_FREQUENCY);
  254                   } catch (InterruptedException ee) {
  255                       // interrupted
  256                       process.destroy();
  257                       throw new Exception("Process was interrupted");
  258                   }
  259                   sleepTime += WsdlGeneratorOptions.FORK_POLL_FREQUENCY;
  260               }
  261           }
  262           
  263           // timeout;
  264           process.destroy();
  265           
  266           LOG.error("Process timed out: {}", outputThread.getOutput());
  267           
  268           throw new Exception("Process timed out");
  269       }
  270       
  271       private static class CaptureOutputThread extends Thread {
  272           
  273           private InputStream in;
  274           private ByteArrayOutputStream out;
  275           
  276           public CaptureOutputThread(InputStream in) {
  277               this.in = in;
  278               this.out = new ByteArrayOutputStream();
  279           }
  280           
  281           public String getOutput() {
  282               // make sure the thread is done
  283               try {
  284                   join(10 * 1000);
  285                   
  286                   // if it's still not done, interrupt it
  287                   if (isAlive()) {
  288                       interrupt();
  289                   }
  290               } catch (InterruptedException e) {
  291                   // that's ok
  292               }            
  293               
  294               // get the output
  295               byte [] arr = this.out.toByteArray();
  296               String output = new String(arr, 0, arr.length);
  297               return output;
  298           }
  299           
  300           public void run() {
  301               try {
  302                   copyAll(this.in, this.out);
  303               } catch (IOException e) {
  304                   // ignore
  305               } finally {
  306                   try { this.out.close(); } catch (IOException ee) {}
  307                   try { this.in.close(); } catch (IOException ee) {}
  308               }
  309           }
  310           
  311           private static void copyAll(InputStream in, OutputStream out) throws IOException {
  312               byte[] buffer = new byte[4096];
  313               int count;
  314               while ((count = in.read(buffer)) > 0) {
  315                   out.write(buffer, 0, count);
  316               }
  317               out.flush();
  318           }
  319       }
  320   
  321   }

Home » geronimo-2.2-source-release » org.apache.geronimo.jaxws.wsdl » [javadoc | source]