Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2014 the original author or authors.
   *
   * Licensed 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.codehaus.gmavenplus.util;
 
 
 import java.io.File;
 import java.net.URL;
 import java.util.List;


Handles getting Groovy classes and version from the specified classpath.

Author(s):
Keegan Witt
Since:
1.2
 
 public class ClassWrangler {

    
Cached Groovy version.
 
     protected String groovyVersion = null;

    
Cached whether Groovy supports invokedynamic (indy jar).
 
     protected Boolean isIndy = null;

    
ClassLoader to use for class wrangling.
 
     protected ClassLoader classLoader;

    
Plugin log.
 
     protected Log log;

    
Creates a new ClassWrangler using the specified ClassLoader.

Parameters:
classLoaderForLoading the ClassLoader to use to load classes
pluginLog the Maven log to use for logging
 
     public ClassWrangler(final ClassLoader classLoaderForLoadingfinal Log pluginLog) {
          = pluginLog;
          = classLoaderForLoading;
     }

    
Creates a new ClassWrangler using a new ClassLoader, loaded with the items from the specified classpath.

Parameters:
classpath the classpath to load the new ClassLoader with
pluginLog the Maven log to use for logging
Throws:
java.net.MalformedURLException
 
     public ClassWrangler(final List classpathfinal Log pluginLogthrows MalformedURLException {
          = pluginLog;
         // create an isolated ClassLoader with all the appropriate project dependencies in it
          = createNewClassLoader(classpath);
     }

    
Gets the version string of Groovy used from classpath.

Returns:
The version string of Groovy used by the project
 
     public String getGroovyVersionString() {
         if ( == null) {
             // this method should work for all Groovy versions >= 1.6.6
             try {
                 Class groovySystemClass = getClass("groovy.lang.GroovySystem");
                 String ver = (String) ReflectionUtils.invokeStaticMethod(ReflectionUtils.findMethod(groovySystemClass"getVersion"));
                 if (ver != null && ver.length() > 0) {
                      = ver;
                 }
            } catch (ClassNotFoundException e) {
                // do nothing, will try another way
            } catch (IllegalAccessException e) {
                // do nothing, will try another way
            } catch (InvocationTargetException e) {
                // do nothing, will try another way
            } catch (IllegalArgumentException e) {
                // do nothing, will try another way
            }
            // this should work for Groovy versions < 1.6.6 (technically can work up to 1.9.0)
            if ( == null) {
                .info("Unable to get Groovy version from GroovySystem, trying InvokerHelper.");
                try {
                    Class invokerHelperClass = getClass("org.codehaus.groovy.runtime.InvokerHelper");
                    String ver = (String) ReflectionUtils.invokeStaticMethod(ReflectionUtils.findMethod(invokerHelperClass"getVersion"));
                    if (ver != null && ver.length() > 0) {
                         = ver;
                    }
                } catch (ClassNotFoundException e) {
                    // do nothing, will try another way
                } catch (IllegalAccessException e) {
                    // do nothing, will try another way
                } catch (InvocationTargetException e) {
                    // do nothing, will try another way
                } catch (IllegalArgumentException e) {
                    // do nothing, will try another way
                }
            }
            /*
             * This handles the circumstances in which neither the GroovySystem or InvokerHelper methods
             * worked (GAE with versions older than 1.6.6 is one example, see
             * https://jira.codehaus.org/browse/GROOVY-3884).  One case this can't handle properly is uber
             * jars that include Groovy.  It should also be noted this method assumes jars will be named
             * in the Maven convention (<artifactId>-<version>-<classifier>.jar).
             */
            if ( == null) {
                .warn("Unable to get Groovy version from InvokerHelper or GroovySystem, trying jar name.");
                String jar = getGroovyJar();
                int idx = .;
                for (int i = 0; i < 9; i++) {
                    int newIdx = jar.indexOf("-" + i);
                    if (newIdx >= 0 && newIdx < idx) {
                        idx = newIdx;
                    }
                }
                if (idx < .) {
                     = jar.substring(idx + 1, jar.length() - 4).replace("-indy""").replace("-grooid""");
                }
            }
        }
        return ;
    }

    
Gets the version of Groovy used from the classpath.

Returns:
The version of Groovy used by the project
    public Version getGroovyVersion() {
        try {
            return Version.parseFromString(getGroovyVersionString());
        } catch (Exception e) {
            .error("Unable to determine Groovy version.  Is Groovy declared as a dependency?");
            return null;
        }
    }

    
Gets whether the version of Groovy on the classpath supports invokedynamic.

Returns:
true if the version of Groovy uses invokedynamic, false if not or Groovy dependency cannot be found.
    public boolean isGroovyIndy() {
        if ( == null) {
            try {
                getClass("org.codehaus.groovy.vmplugin.v7.IndyInterface");
                 = true;
            } catch (ClassNotFoundException e) {
                 = false;
            }
        }
        return ;
    }

    
Returns the filename of the Groovy jar on the classpath.

Returns:
the Groovy jar filename
    public String getGroovyJar() {
        try {
            String groovyObjectClassPath = getJarPath();
            String groovyJar = null;
            if (groovyObjectClassPath != null) {
                groovyJar = groovyObjectClassPath.replaceAll("!.+""");
                groovyJar = groovyJar.substring(groovyJar.lastIndexOf("/") + 1, groovyJar.length());
            }
            return groovyJar;
        } catch (ClassNotFoundException e) {
            .error("Unable to determine Groovy version.  Is Groovy declared as a dependency?");
            return null;
        }
    }

    
Returns the path of the Groovy jar on the classpath.

Returns:
the path of the Groovy jar
Throws:
java.lang.ClassNotFoundException when Groovu couldn't be found on the classpath
    protected String getJarPath() throws ClassNotFoundException {
        Class groovyObjectClass = Class.forName("groovy.lang.GroovyObject"true);
        String groovyObjectClassPath = String.valueOf(groovyObjectClass.getResource("/" + groovyObjectClass.getName().replace('.''/') + ".class"));
        if (groovyObjectClassPath == null) {
            CodeSource codeSource = groovyObjectClass.getProtectionDomain().getCodeSource();
            if (codeSource != null) {
                groovyObjectClassPath = String.valueOf(codeSource.getLocation());
            }
        }
        return groovyObjectClassPath;
    }

    
Logs the version of groovy used by this mojo.

Parameters:
goal The goal to mention in the log statement showing Groovy version
    public void logGroovyVersion(final String goal) {
        if (.isInfoEnabled()) {
            .info("Using Groovy " + getGroovyVersionString() + " to perform " + goal + ".");
        }
    }

    
Creates a new ClassLoader with the specified classpath.

Parameters:
classpath the classpath (a list of file path Strings) to include in the new loader
Returns:
the new ClassLoader
Throws:
java.net.MalformedURLException when a classpath element provides a malformed URL
    public ClassLoader createNewClassLoader(final List classpaththrows MalformedURLException {
        List<URLurlsList = new ArrayList<URL>();
        for (Object classPathObject : classpath) {
            String path = (StringclassPathObject;
            urlsList.add(new File(path).toURI().toURL());
        }
        URL[] urlsArray = urlsList.toArray(new URL[urlsList.size()]);
        return new URLClassLoader(urlsArray, ClassLoader.getSystemClassLoader());
    }

    
Gets a class for the given class name.

Parameters:
className the class name to retrieve the class for
Returns:
the class for the given class name
Throws:
java.lang.ClassNotFoundException when a class for the specified class name cannot be found
    public Class getClass(final String classNamethrows ClassNotFoundException {
        return Class.forName(classNametrue);
    }

    
Returns the classloader used for loading classes.

Returns:
the classloader used for loading classes
    public ClassLoader getClassLoader() {
        return ;
    }
New to GrepCode? Check out our FAQ X