Gets source for a class.

@param koanClass the koan class
@return the source code as a string
322896
public static String getSourceByClass(Class<?> koanClass) {

        File file = new File(getKoanFileLocation(koanClass));
   		StringBuilder contents = new StringBuilder();
   		BufferedReader reader = null;

   		try {
   			reader = new BufferedReader(new FileReader(file));
   			String text = null;

   			while ((text = reader.readLine()) != null) {
   				contents.append(text).append(System.lineSeparator());
   			}
   		} catch (IOException e) {
   			e.printStackTrace();
   		} finally {
   			try {
   				if (reader != null) {
   					reader.close();
   				}
   			} catch (IOException e) {
   				e.printStackTrace();
   			}
   		}
   		return contents.toString();
   	}
294494
public Class<? extends Supplier<RoutingHandler>> compileClass()
    {
        try {
            this.generateRoutes();

            log.debug("\n\nGenerated Class Source:\n\n" + this.sourceString);

            return CompilerUtils.CACHED_COMPILER.loadFromJava(packageName + "." + className, this.sourceString);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
1028687
public Class<?> getMappingClass(Class<?> from) {
		if (mapping != null) {
			Class<?> ret = mapping.get(from);
			return ret != null ? ret : from;
		} else {
			return from;
		}
	}
822572
public <T> T getAnnotation(Class<T> annotationClass) {
        for (Annotation annotation : m_annotations) {
            if (annotation.annotationType().equals(annotationClass)){
                return (T) annotation;
            }
        }
        return null;
    }
635635
public static String readClassName (File source)
        throws IOException
    {
        // load up the file and determine it's package and classname
        String pkgname = null, name = null;
        BufferedReader bin = new BufferedReader(new FileReader(source));
        String line;
        while ((line = bin.readLine()) != null) {
            Matcher pm = PACKAGE_PATTERN.matcher(line);
            if (pm.find()) {
                pkgname = pm.group(1);
            }
            Matcher nm = NAME_PATTERN.matcher(line);
            if (nm.find()) {
                name = nm.group(2);
                break;
            }
        }
        bin.close();

        // make sure we found something
        if (name == null) {
            throw new IOException("Unable to locate class or interface name in " + source + ".");
        }

        // prepend the package name to get a name we can Class.forName()
        if (pkgname != null) {
            name = pkgname + "." + name;
        }

        return name;
    }
127569
@SuppressFBWarnings("ES_COMPARING_STRINGS_WITH_EQ")
    public String getDottedClassConstantOperand() {
        if (dottedClassConstantOperand != null) {
            assert dottedClassConstantOperand != NOT_AVAILABLE;
            return dottedClassConstantOperand;
        }
        if (classConstantOperand == NOT_AVAILABLE) {
            throw new IllegalStateException("getDottedClassConstantOperand called but value not available");
        }
        dottedClassConstantOperand = ClassName.toDottedClassName(classConstantOperand);
        return dottedClassConstantOperand;
    }
1115964
public final String getRealDataSourceClassName() {
		if ((realDataSourceClassName == null || realDataSourceClassName.isEmpty()) && (configuration != null)) {
			realDataSourceClassName = doGetRealDataSourceClassName();
		}
		return realDataSourceClassName;
	}
818330
@SuppressWarnings("unchecked")
	public <T> Class<T> getImplementingClass(Class<T> theClass) {
		if (!theClass.isAssignableFrom(getImplementingClass())) {
			throw new ConfigurationException("Unable to convert " + getImplementingClass() + " to " + theClass);
		}
		return (Class<T>) getImplementingClass();
	}
1148040
@DefinedBy(Api.COMPILER)
    public JavaFileObject getSource() {
        if (source == null)
            return null;
        else
            return source.getFile();
    }
821991
public ClassNode getClassNode() {
        if (classNode == null && GroovyObject.class.isAssignableFrom(theClass)) {
            // let's try load it from the classpath
            String groovyFile = theClass.getName();
            int idx = groovyFile.indexOf('$');
            if (idx > 0) {
                groovyFile = groovyFile.substring(0, idx);
            }
            groovyFile = groovyFile.replace('.', '/') + ".groovy";

            //System.out.println("Attempting to load: " + groovyFile);
            URL url = theClass.getClassLoader().getResource(groovyFile);
            if (url == null) {
                url = Thread.currentThread().getContextClassLoader().getResource(groovyFile);
            }
            if (url != null) {
                try {

                    /*
                     * todo there is no CompileUnit in scope so class name
                     * checking won't work but that mostly affects the bytecode
                     * generation rather than viewing the AST
                     */
                    CompilationUnit.ClassgenCallback search = new CompilationUnit.ClassgenCallback() {
                        public void call(ClassVisitor writer, ClassNode node) {
                            if (node.getName().equals(theClass.getName())) {
                                MetaClassImpl.this.classNode = node;
                            }
                        }
                    };

                    CompilationUnit unit = new CompilationUnit();
                    unit.setClassgenCallback(search);
                    unit.addSource(url);
                    unit.compile(Phases.CLASS_GENERATION);
                }
                catch (Exception e) {
                    throw new GroovyRuntimeException("Exception thrown parsing: " + groovyFile + ". Reason: " + e, e);
                }
            }

        }
        return classNode;
    }
810770
private static Class getClass(final String fqcn) {

		try {

			return Class.forName(fqcn);

		} catch (Throwable t) {

		}

		return null;
	}
502136
public <T> T convert(Object source, Class<T> toClass) throws Exception {
        Constructor<T> constructor = toClass.getConstructor(java.lang.String.class);
        return constructor.newInstance(source);
    }
322365
synchronized public ClassSource getClassSource( String className )
    {
        // Before triggering classpath mapping (initialization) check for
        // explicitly set class sources (e.g. generated classes).  These would
        // take priority over any found in the classpath anyway.
        ClassSource cs = (ClassSource)classSource.get( className );
        if ( cs != null )
            return cs;

        insureInitialized(); // trigger possible mapping

        cs = (ClassSource)classSource.get( className );
        if ( cs == null && compPaths != null )
            for (int i=0; i<compPaths.size() && cs==null; i++)
                cs = ((BshClassPath)compPaths.get(i)).getClassSource(className);
        return cs;
    }

    /**
        Explicitly set a class source.  This is used for generated classes, but
        could potentially be used to allow a user to override which version of
        a class from the classpath is located.
    */
    synchronized public void setClassSource( String className, ClassSource cs )
    {
        classSource.put( className, cs );
    }

    /**
        If the claspath map is not initialized, do it now.
        If component maps are not do them as well...

        Random note:
        Should this be "insure" or "ensure".  I know I've seen "ensure" used
        in the JDK source.  Here's what Webster has to say:

            Main Entry:ensure Pronunciation:in-'shur
            Function:transitive verb Inflected
            Form(s):ensured; ensuring : to make sure,
            certain, or safe : GUARANTEE synonyms ENSURE,
            INSURE, ASSURE, SECURE mean to make a thing or
            person sure. ENSURE, INSURE, and ASSURE are
            interchangeable in many contexts where they
            indicate the making certain or inevitable of an
            outcome, but INSURE sometimes stresses the
            taking of necessary measures beforehand, and
            ASSURE distinctively implies the removal of
            doubt and suspense from a person's mind. SECURE
            implies action taken to guard against attack or
            loss.
    */
    public void insureInitialized()
    {
        insureInitialized( true );
    }

    /**
        @param topPath indicates that this is the top level classpath
        component and it should send the startClassMapping message
    */
    protected synchronized void insureInitialized( boolean topPath )
    {
        // If we are the top path and haven't been initialized before
        // inform the listeners we are going to do expensive map
        if ( topPath && !mapsInitialized )
            startClassMapping();

        // initialize components
        if ( compPaths != null )
            for (int i=0; i< compPaths.size(); i++)
                ((BshClassPath)compPaths.get(i)).insureInitialized( false );

        // initialize ourself
        if ( !mapsInitialized )
            map( (URL[])path.toArray( new URL[0] ) );

        if ( topPath && !mapsInitialized )
            endClassMapping();

        mapsInitialized = true;
    }

    /**
        Get the full path including component paths.
        (component paths listed first, in order)
        Duplicate path components are removed.
    */
    protected List getFullPath()
    {
        List list = new ArrayList();
        if ( compPaths != null ) {
            for (int i=0; i<compPaths.size(); i++) {
                List l = ((BshClassPath)compPaths.get(i)).getFullPath();
                // take care to remove dups
                // wish we had an ordered set collection
                Iterator it = l.iterator();
                while ( it.hasNext() ) {
                    Object o = it.next();
                    if ( !list.contains(o) )
                        list.add( o );
                }
            }
        }
        list.addAll( path );
        return list;
    }


    /**
        Support for super import "*";
        Get the full name associated with the unqualified name in this
        classpath.  Returns either the String name or an AmbiguousName object
        encapsulating the various names.
    */
    public String getClassNameByUnqName( String name )
        throws ClassPathException
    {
        insureInitialized();
        UnqualifiedNameTable unqNameTable = getUnqualifiedNameTable();

        Object obj = unqNameTable.get( name );
        if ( obj instanceof AmbiguousName )
            throw new ClassPathException("Ambigous class names: "+
                ((AmbiguousName)obj).get() );

        return (String)obj;
    }

    /*
        Note: we could probably do away with the unqualified name table
        in favor of a second name source
    */
    private UnqualifiedNameTable getUnqualifiedNameTable() {
        if ( unqNameTable == null )
            unqNameTable = buildUnqualifiedNameTable();
        return unqNameTable;
    }

    private UnqualifiedNameTable buildUnqualifiedNameTable()
    {
        UnqualifiedNameTable unqNameTable = new UnqualifiedNameTable();

        // add component names
        if ( compPaths != null )
            for (int i=0; i<compPaths.size(); i++) {
                Set s = ((BshClassPath)compPaths.get(i)).classSource.keySet();
                Iterator it = s.iterator();
                while(it.hasNext())
                    unqNameTable.add( (String)it.next() );
            }

        // add ours
        Iterator it = classSource.keySet().iterator();
        while(it.hasNext())
            unqNameTable.add( (String)it.next() );

        return unqNameTable;
    }

    public String [] getAllNames()
    {
        insureInitialized();

        List names = new ArrayList();
        Iterator it = getPackagesSet().iterator();
        while( it.hasNext() ) {
            String pack = (String)it.next();
            names.addAll(
                removeInnerClassNames( getClassesForPackage( pack ) ) );
        }

        if ( nameCompletionIncludesUnqNames )
            names.addAll( getUnqualifiedNameTable().keySet() );

        return (String [])names.toArray(new String[0]);
    }

    /**
        call map(url) for each url in the array
    */
    synchronized void map( URL [] urls )
    {
        for(int i=0; i< urls.length; i++)
            try{
                map( urls[i] );
            } catch ( IOException e ) {
                String s = "Error constructing classpath: " +urls[i]+": "+e;
                errorWhileMapping( s );
            }
    }

    synchronized void map( URL url )
        throws IOException
    {
        if ("jrt".equals(url.getProtocol())) {
            classMapping("FileSystem: "+url );
            map( searchJrtFSForClasses( url ), new JrtClassSource(url) );
        } else  if ("jar".equals(url.getProtocol())) {
            classMapping("FileSystem: "+url );
            map( searchJarFSForClasses( url ), new JarClassSource(url) );
        } else {
            String name = url.getFile();
            File f = new File( name );

            if ( f.isDirectory() ) {
                classMapping( "Directory "+ f.toString() );
                map( traverseDirForClasses( f ), new DirClassSource(f) );
            } else if ( isArchiveFileName( name ) ) {
                classMapping("Archive: "+url );
                map( searchArchiveForClasses( url ), new JarClassSource(url) );
            } else {
                String s = "Not a classpath component: "+ name ;
                errorWhileMapping( s );
            }
        }
    }

    private void map( String [] classes, Object source ) {
        for(int i=0; i< classes.length; i++) {
            //System.out.println( classes[i] +": "+ source );
            mapClass( classes[i], source );
        }
    }

    private void mapClass( String className, Object source )
    {
        // add to package map
        String [] sa = splitClassname( className );
        String pack = sa[0];
        Set set = (Set)packageMap.get( pack );
        if ( set == null ) {
            set = new HashSet();
            packageMap.put( pack, set );
        }
        set.add( className );

        // Add to classSource map
        Object obj = classSource.get( className );
        // don't replace previously set (found earlier in classpath or
        // explicitly set via setClassSource() )
        if ( obj == null )
            classSource.put( className, source );
    }
1270739
public static File getClassJar(Class clazz) {
		File file = null;

		try {
			file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
		} catch (URISyntaxException e) {}

		return file;
	}
1206363
public static <E extends Enum<E>> LinkedHashMap<String, E> getEnumMap(final Class<E> enumClass) {
		final LinkedHashMap<String, E> map = new LinkedHashMap<String, E>();
		for (final E e : enumClass.getEnumConstants()) {
			map.put(e.name(), e);
		}
		return map;
	}
755176
private <D,S> JMapper<D,S> getJMapper(HashMap<String,JMapper> map,Object source){
		Class<?> sourceClass = source instanceof Class?((Class<?>)source):source.getClass();
		JMapper<D,S> jMapper = map.get(sourceClass.getName());
		if(jMapper == null) Error.classNotMapped(source, configuredClass);
		return jMapper;
	}
331606
public final Parser<String> source() {
    return new Parser<String>() {
      @Override boolean apply(ParseContext ctxt) {
        int begin = ctxt.getIndex();
        if (!Parser.this.apply(ctxt)) {
          return false;
        }
        ctxt.result = ctxt.source.subSequence(begin, ctxt.getIndex()).toString();
        return true;
      }
      @Override public String toString() {
        return "source";
      }
    };
  }