All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.coderu.adapters.junit.utils.CompileUnitFactory Maven / Gradle / Ivy

There is a newer version: 1.2.12
Show newest version
package org.coderu.adapters.junit.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

import org.apache.commons.lang3.StringUtils;
import org.coderu.core.api.CompileUnit;

import com.google.common.base.Function;


public final class CompileUnitFactory {

    public static CompileUnit createByClassLocation(final Class clazz){
        return new CompileUnit(getClasspath(clazz));
    }
    
    public static final Function,CompileUnit> CLASS_2_COMPILE_UNIT = 
        new Function, CompileUnit>() {
        
        public CompileUnit apply(Class o) {
            return CompileUnitFactory.createByClassLocation(o);
        }
    };
    
    private static File getClasspath(Class clazz) {
        final String classname = clazz.getName();
        final String classnameAsResource = classname.replace('.', '/') + ".class";
        final ClassLoader classLoader = clazz.getClassLoader();
        final URL url = classLoader.getResource(classnameAsResource);
        final String path = decode(url);
        final String pathWithoutClassName = removeFilePrefix(removeClassName(classnameAsResource, path));
        return new File(removeClassNameIncaseOfJar(pathWithoutClassName));
    }

    private static String decode(final URL url){
        try {
            return URLDecoder.decode(url.toExternalForm(),"UTF8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private static String removeClassName(final String classnameAsResource, final String path) {
        return path.substring(0, path.length() - classnameAsResource.length());
    }
    
    private static String removeClassNameIncaseOfJar(final String path){
        final String[] split = StringUtils.split(path, '!');
        return split[0];
    }
    
    private static String removeFilePrefix(final String path){
        return path.substring(path.indexOf(":/")+1, path.length());
    }


}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy