Best Mockito code snippet using org.mockitoutil.ClassLoaders.names.iterator
Source:ClassLoaders.java
1package org.mockitoutil;2import java.io.ByteArrayInputStream;3import java.io.File;4import java.io.IOException;5import java.io.InputStream;6import java.net.*;7import java.util.*;8import static java.util.Arrays.asList;9public abstract class ClassLoaders {10 protected ClassLoader parent = currentClassLoader();11 protected ClassLoaders() {}12 public static IsolatedURLClassLoaderBuilder isolatedClassLoader() {13 return new IsolatedURLClassLoaderBuilder();14 }15 public static ExcludingURLClassLoaderBuilder excludingClassLoader() {16 return new ExcludingURLClassLoaderBuilder();17 }18 public static InMemoryClassLoaderBuilder inMemoryClassLoader() {19 return new InMemoryClassLoaderBuilder();20 }21 public static ReachableClassesFinder in(ClassLoader classLoader) {22 return new ReachableClassesFinder(classLoader);23 }24 public static ClassLoader jdkClassLoader() {25 return String.class.getClassLoader();26 }27 public static ClassLoader systemClassLoader() {28 return ClassLoader.getSystemClassLoader();29 }30 public static ClassLoader currentClassLoader() {31 return ClassLoaders.class.getClassLoader();32 }33 public abstract ClassLoader build();34 public static Class<?>[] coverageTool() {35 HashSet<Class<?>> classes = new HashSet<Class<?>>();36 classes.add(safeGetClass("net.sourceforge.cobertura.coveragedata.TouchCollector"));37 classes.add(safeGetClass("org.slf4j.LoggerFactory"));38 classes.remove(null);39 return classes.toArray(new Class<?>[classes.size()]);40 }41 private static Class<?> safeGetClass(String className) {42 try {43 return Class.forName(className);44 } catch (ClassNotFoundException e) {45 return null;46 }47 }48 public static class IsolatedURLClassLoaderBuilder extends ClassLoaders {49 private final ArrayList<String> privateCopyPrefixes = new ArrayList<String>();50 private final ArrayList<URL> codeSourceUrls = new ArrayList<URL>();51 public IsolatedURLClassLoaderBuilder withPrivateCopyOf(String... privatePrefixes) {52 privateCopyPrefixes.addAll(asList(privatePrefixes));53 return this;54 }55 public IsolatedURLClassLoaderBuilder withCodeSourceUrls(String... urls) {56 codeSourceUrls.addAll(pathsToURLs(urls));57 return this;58 }59 public IsolatedURLClassLoaderBuilder withCodeSourceUrlOf(Class<?>... classes) {60 for (Class<?> clazz : classes) {61 codeSourceUrls.add(obtainClassPathOf(clazz.getName()));62 }63 return this;64 }65 public IsolatedURLClassLoaderBuilder withCurrentCodeSourceUrls() {66 codeSourceUrls.add(obtainClassPathOf(ClassLoaders.class.getName()));67 return this;68 }69 public ClassLoader build() {70 return new LocalIsolatedURLClassLoader(71 jdkClassLoader(),72 codeSourceUrls.toArray(new URL[codeSourceUrls.size()]),73 privateCopyPrefixes74 );75 }76 }77 static class LocalIsolatedURLClassLoader extends URLClassLoader {78 private final ArrayList<String> privateCopyPrefixes;79 public LocalIsolatedURLClassLoader(ClassLoader classLoader, URL[] urls, ArrayList<String> privateCopyPrefixes) {80 super(urls, classLoader);81 this.privateCopyPrefixes = privateCopyPrefixes;82 }83 @Override84 public Class<?> findClass(String name) throws ClassNotFoundException {85 if(classShouldBePrivate(name)) return super.findClass(name);86 throw new ClassNotFoundException("Can only load classes with prefix : " + privateCopyPrefixes);87 }88 private boolean classShouldBePrivate(String name) {89 for (String prefix : privateCopyPrefixes) {90 if (name.startsWith(prefix)) return true;91 }92 return false;93 }94 }95 public static class ExcludingURLClassLoaderBuilder extends ClassLoaders {96 private final ArrayList<String> privateCopyPrefixes = new ArrayList<String>();97 private final ArrayList<URL> codeSourceUrls = new ArrayList<URL>();98 public ExcludingURLClassLoaderBuilder without(String... privatePrefixes) {99 privateCopyPrefixes.addAll(asList(privatePrefixes));100 return this;101 }102 public ExcludingURLClassLoaderBuilder withCodeSourceUrls(String... urls) {103 codeSourceUrls.addAll(pathsToURLs(urls));104 return this;105 }106 public ExcludingURLClassLoaderBuilder withCodeSourceUrlOf(Class<?>... classes) {107 for (Class<?> clazz : classes) {108 codeSourceUrls.add(obtainClassPathOf(clazz.getName()));109 }110 return this;111 }112 public ExcludingURLClassLoaderBuilder withCurrentCodeSourceUrls() {113 codeSourceUrls.add(obtainClassPathOf(ClassLoaders.class.getName()));114 return this;115 }116 public ClassLoader build() {117 return new LocalExcludingURLClassLoader(118 jdkClassLoader(),119 codeSourceUrls.toArray(new URL[codeSourceUrls.size()]),120 privateCopyPrefixes121 );122 }123 }124 static class LocalExcludingURLClassLoader extends URLClassLoader {125 private final ArrayList<String> privateCopyPrefixes;126 public LocalExcludingURLClassLoader(ClassLoader classLoader, URL[] urls, ArrayList<String> privateCopyPrefixes) {127 super(urls, classLoader);128 this.privateCopyPrefixes = privateCopyPrefixes;129 }130 @Override131 public Class<?> findClass(String name) throws ClassNotFoundException {132 if(classShouldBePrivate(name)) throw new ClassNotFoundException("classes with prefix : " + privateCopyPrefixes + " are excluded");133 return super.findClass(name);134 }135 private boolean classShouldBePrivate(String name) {136 for (String prefix : privateCopyPrefixes) {137 if (name.startsWith(prefix)) return true;138 }139 return false;140 }141 }142 public static class InMemoryClassLoaderBuilder extends ClassLoaders {143 private Map<String , byte[]> inMemoryClassObjects = new HashMap<String , byte[]>();144 public InMemoryClassLoaderBuilder withParent(ClassLoader parent) {145 this.parent = parent;146 return this;147 }148 public InMemoryClassLoaderBuilder withClassDefinition(String name, byte[] classDefinition) {149 inMemoryClassObjects.put(name, classDefinition);150 return this;151 }152 public ClassLoader build() {153 return new InMemoryClassLoader(parent, inMemoryClassObjects);154 }155 }156 static class InMemoryClassLoader extends ClassLoader {157 public static final String SCHEME = "mem";158 private Map<String , byte[]> inMemoryClassObjects = new HashMap<String , byte[]>();159 public InMemoryClassLoader(ClassLoader parent, Map<String, byte[]> inMemoryClassObjects) {160 super(parent);161 this.inMemoryClassObjects = inMemoryClassObjects;162 }163 protected Class findClass(String name) throws ClassNotFoundException {164 byte[] classDefinition = inMemoryClassObjects.get(name);165 if (classDefinition != null) {166 return defineClass(name, classDefinition, 0, classDefinition.length);167 }168 throw new ClassNotFoundException(name);169 }170 @Override171 public Enumeration<URL> getResources(String ignored) throws IOException {172 return inMemoryOnly();173 }174 private Enumeration<URL> inMemoryOnly() {175 final Set<String> names = inMemoryClassObjects.keySet();176 return new Enumeration<URL>() {177 private final MemHandler memHandler = new MemHandler(InMemoryClassLoader.this);178 private final Iterator<String> it = names.iterator();179 public boolean hasMoreElements() {180 return it.hasNext();181 }182 public URL nextElement() {183 try {184 return new URL(null, SCHEME + ":" + it.next(), memHandler);185 } catch (MalformedURLException rethrown) {186 throw new IllegalStateException(rethrown);187 }188 }189 };190 }191 }192 public static class MemHandler extends URLStreamHandler {193 private InMemoryClassLoader inMemoryClassLoader;194 public MemHandler(InMemoryClassLoader inMemoryClassLoader) {195 this.inMemoryClassLoader = inMemoryClassLoader;196 }197 @Override198 protected URLConnection openConnection(URL url) throws IOException {199 return new MemURLConnection(url, inMemoryClassLoader);200 }201 private static class MemURLConnection extends URLConnection {202 private final InMemoryClassLoader inMemoryClassLoader;203 private String qualifiedName;204 public MemURLConnection(URL url, InMemoryClassLoader inMemoryClassLoader) {205 super(url);206 this.inMemoryClassLoader = inMemoryClassLoader;207 qualifiedName = url.getPath();208 }209 @Override210 public void connect() throws IOException { }211 @Override212 public InputStream getInputStream() throws IOException {213 return new ByteArrayInputStream(inMemoryClassLoader.inMemoryClassObjects.get(qualifiedName));214 }215 }216 }217 protected URL obtainClassPathOf(String className) {218 String path = className.replace('.', '/') + ".class";219 String url = ClassLoaders.class.getClassLoader().getResource(path).toExternalForm();220 try {221 return new URL(url.substring(0, url.length() - path.length()));222 } catch (MalformedURLException e) {223 throw new RuntimeException("Classloader couldn't obtain a proper classpath URL", e);224 }225 }226 protected List<URL> pathsToURLs(String... codeSourceUrls) {227 return pathsToURLs(Arrays.asList(codeSourceUrls));228 }229 private List<URL> pathsToURLs(List<String> codeSourceUrls) {230 ArrayList<URL> urls = new ArrayList<URL>(codeSourceUrls.size());231 for (String codeSourceUrl : codeSourceUrls) {232 URL url = pathToUrl(codeSourceUrl);233 urls.add(url);234 }235 return urls;236 }237 private URL pathToUrl(String path) {238 try {239 return new File(path).getAbsoluteFile().toURI().toURL();240 } catch (MalformedURLException e) {241 throw new IllegalArgumentException("Path is malformed", e);242 }243 }244 public static class ReachableClassesFinder {245 private ClassLoader classLoader;246 private Set<String> qualifiedNameSubstring = new HashSet<String>();247 public ReachableClassesFinder(ClassLoader classLoader) {248 this.classLoader = classLoader;249 }250 public ReachableClassesFinder omit(String... qualifiedNameSubstring) {251 this.qualifiedNameSubstring.addAll(Arrays.asList(qualifiedNameSubstring));252 return this;253 }254 public Set<String> listOwnedClasses() throws IOException, URISyntaxException {255 Enumeration<URL> roots = classLoader.getResources("");256 Set<String> classes = new HashSet<String>();257 while(roots.hasMoreElements()) {258 URI uri = roots.nextElement().toURI();259 if (uri.getScheme().equalsIgnoreCase("file")) {260 addFromFileBasedClassLoader(classes, uri);261 } else if(uri.getScheme().equalsIgnoreCase(InMemoryClassLoader.SCHEME)) {262 addFromInMemoryBasedClassLoader(classes, uri);263 } else {264 throw new IllegalArgumentException(String.format("Given ClassLoader '%s' don't have reachable by File or vi ClassLoaders.inMemory", classLoader));265 }266 }267 return classes;268 }269 private void addFromFileBasedClassLoader(Set<String> classes, URI uri) {270 File root = new File(uri);271 classes.addAll(findClassQualifiedNames(root, root, qualifiedNameSubstring));272 }273 private void addFromInMemoryBasedClassLoader(Set<String> classes, URI uri) {274 String qualifiedName = uri.getSchemeSpecificPart();275 if(excludes(qualifiedName, qualifiedNameSubstring)) {276 classes.add(qualifiedName);277 }278 }279 private Set<String> findClassQualifiedNames(File root, File file, Set<String> packageFilters) {280 if(file.isDirectory()) {281 File[] files = file.listFiles();282 Set<String> classes = new HashSet<String>();283 for (File children : files) {284 classes.addAll(findClassQualifiedNames(root, children, packageFilters));285 }286 return classes;287 } else {288 if (file.getName().endsWith(".class")) {289 String qualifiedName = classNameFor(root, file);290 if (excludes(qualifiedName, packageFilters)) {291 return Collections.singleton(qualifiedName);292 }293 }294 }295 return Collections.emptySet();296 }297 private boolean excludes(String qualifiedName, Set<String> packageFilters) {298 for (String filter : packageFilters) {299 if(qualifiedName.contains(filter)) return false;300 }301 return true;302 }303 private String classNameFor(File root, File file) {304 String temp = file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1).305 replace(File.separatorChar, '.');306 return temp.subSequence(0, temp.indexOf(".class")).toString();307 }308 }309}...
Source:Math_72_rank-2_new.java
1package org.mockitoutil;2import java.io.ByteArrayInputStream;3import java.io.File;4import java.io.IOException;5import java.io.InputStream;6import java.net.MalformedURLException;7import java.net.URI;8import java.net.URISyntaxException;9import java.net.URL;10import java.net.URLClassLoader;11import java.net.URLConnection;12import java.net.URLStreamHandler;13import java.util.*;14import static java.util.Arrays.asList;15public abstract class ClassLoaders {16 protected ClassLoader parent = currentClassLoader();17 protected ClassLoaders() {}18 public static IsolatedURLClassLoaderBuilder isolatedClassLoader() {19 return new IsolatedURLClassLoaderBuilder();20 }21 public static ExcludingURLClassLoaderBuilder excludingClassLoader() {22 return new ExcludingURLClassLoaderBuilder();23 }24 public static InMemoryClassLoaderBuilder inMemoryClassLoader() {25 return new InMemoryClassLoaderBuilder();26 }27 public static ReachableClassesFinder in(ClassLoader classLoader_without_jUnit) {28 return new ReachableClassesFinder(classLoader_without_jUnit);29 }30 public static ClassLoader jdkClassLoader() {31 return String.class.getClassLoader();32 }33 public static ClassLoader systemClassLoader() {34 return ClassLoader.getSystemClassLoader();35 }36 public static ClassLoader currentClassLoader() {37 return ClassLoaders.class.getClassLoader();38 }39 public abstract ClassLoader build();40 public static class IsolatedURLClassLoaderBuilder extends ClassLoaders {41 private final ArrayList<String> privateCopyPrefixes = new ArrayList<String>();42 private final ArrayList<URL> codeSourceUrls = new ArrayList<URL>();43 public IsolatedURLClassLoaderBuilder withPrivateCopyOf(String... privatePrefixes) {44 privateCopyPrefixes.addAll(asList(privatePrefixes));45 return this;46 }47 public IsolatedURLClassLoaderBuilder withCodeSourceUrls(String... urls) {48 codeSourceUrls.addAll(pathsToURLs(urls));49 return this;50 }51 public IsolatedURLClassLoaderBuilder withCodeSourceUrlOf(Class<?>... classes) {52 for (Class<?> clazz : classes) {53 codeSourceUrls.add(obtainClassPathOf(clazz.getName()));54 }55 return this;56 }57 public IsolatedURLClassLoaderBuilder withCurrentCodeSourceUrls() {58 codeSourceUrls.add(obtainClassPathOf(ClassLoaders.class.getName()));59 return this;60 }61 public ClassLoader build() {62 return new LocalIsolatedURLClassLoader(63 jdkClassLoader(),64 codeSourceUrls.toArray(new URL[codeSourceUrls.size()]),65 privateCopyPrefixes66 );67 }68 }69 static class LocalIsolatedURLClassLoader extends URLClassLoader {70 private final ArrayList<String> privateCopyPrefixes;71 public LocalIsolatedURLClassLoader(ClassLoader classLoader, URL[] urls, ArrayList<String> privateCopyPrefixes) {72 super(urls, classLoader);73 this.privateCopyPrefixes = privateCopyPrefixes;74 }75 @Override76 public Class<?> findClass(String name) throws ClassNotFoundException {77 if(classShouldBePrivate(name)) return super.findClass(name);78 throw new ClassNotFoundException("Can only load classes with prefix : " + privateCopyPrefixes);79 }80 private boolean classShouldBePrivate(String name) {81 for (String prefix : privateCopyPrefixes) {82 if (name.startsWith(prefix)) return true;83 }84 return false;85 }86 }87 public static class ExcludingURLClassLoaderBuilder extends ClassLoaders {88 private final ArrayList<String> privateCopyPrefixes = new ArrayList<String>();89 private final ArrayList<URL> codeSourceUrls = new ArrayList<URL>();90 public ExcludingURLClassLoaderBuilder without(String... privatePrefixes) {91 privateCopyPrefixes.addAll(asList(privatePrefixes));92 return this;93 }94 public ExcludingURLClassLoaderBuilder withCodeSourceUrls(String... urls) {95 codeSourceUrls.addAll(pathsToURLs(urls));96 return this;97 }98 public ExcludingURLClassLoaderBuilder withCodeSourceUrlOf(Class<?>... classes) {99 for (Class<?> clazz : classes) {100 codeSourceUrls.add(obtainClassPathOf(clazz.getName()));101 }102 return this;103 }104 public ExcludingURLClassLoaderBuilder withCurrentCodeSourceUrls() {105 codeSourceUrls.add(obtainClassPathOf(ClassLoaders.class.getName()));106 return this;107 }108 public ClassLoader build() {109 return new LocalExcludingURLClassLoader(110 jdkClassLoader(),111 codeSourceUrls.toArray(new URL[codeSourceUrls.size()]),112 privateCopyPrefixes113 );114 }115 }116 static class LocalExcludingURLClassLoader extends URLClassLoader {117 private final ArrayList<String> privateCopyPrefixes;118 public LocalExcludingURLClassLoader(ClassLoader classLoader, URL[] urls, ArrayList<String> privateCopyPrefixes) {119 super(urls, classLoader);120 this.privateCopyPrefixes = privateCopyPrefixes;121 }122 @Override123 public Class<?> findClass(String name) throws ClassNotFoundException {124 if(classShouldBePrivate(name)) throw new ClassNotFoundException("classes with prefix : " + privateCopyPrefixes + " are excluded");125 return super.findClass(name);126 }127 private boolean classShouldBePrivate(String name) {128 for (String prefix : privateCopyPrefixes) {129 if (name.startsWith(prefix)) return true;130 }131 return false;132 }133 }134 public static class InMemoryClassLoaderBuilder extends ClassLoaders {135 private Map<String , byte[]> inMemoryClassObjects = new HashMap<String , byte[]>();136 public InMemoryClassLoaderBuilder withParent(ClassLoader parent) {137 this.parent = parent;138 return this;139 }140 public InMemoryClassLoaderBuilder withClassDefinition(String name, byte[] classDefinition) {141 inMemoryClassObjects.put(name, classDefinition);142 return this;143 }144 public ClassLoader build() {145 return new InMemoryClassLoader(parent, inMemoryClassObjects);146 }147 }148 static class InMemoryClassLoader extends ClassLoader {149 public static final String SCHEME = "mem";150 private Map<String , byte[]> inMemoryClassObjects = new HashMap<String , byte[]>();151 public InMemoryClassLoader(ClassLoader parent, Map<String, byte[]> inMemoryClassObjects) {152 super(parent);153 this.inMemoryClassObjects = inMemoryClassObjects;154 }155 protected Class findClass(String name) throws ClassNotFoundException {156 byte[] classDefinition = inMemoryClassObjects.get(name);157 if (classDefinition != null) {158 return defineClass(name, classDefinition, 0, classDefinition.length);159 }160 throw new ClassNotFoundException(name);161 }162 @Override163 public Enumeration<URL> getResources(String ignored) throws IOException {164 return inMemoryOnly();165 }166 private Enumeration<URL> inMemoryOnly() {167 final Set<String> names = inMemoryClassObjects.keySet();168 return new Enumeration<URL>() {169 private final MemHandler memHandler = new MemHandler(InMemoryClassLoader.this);170 private final Iterator<String> it = names.iterator();171 public boolean hasMoreElements() {172 return it.hasNext();173 }174 public URL nextElement() {175 try {176 return new URL(null, SCHEME + ":" + it.next(), memHandler);177 } catch (MalformedURLException rethrown) {178 throw new IllegalStateException(rethrown);179 }180 }181 };182 }183 }184 public static class MemHandler extends URLStreamHandler {185 private InMemoryClassLoader inMemoryClassLoader;186 public MemHandler(InMemoryClassLoader inMemoryClassLoader) {187 this.inMemoryClassLoader = inMemoryClassLoader;188 }189 @Override190 protected URLConnection openConnection(URL url) throws IOException {191 return new MemURLConnection(url, inMemoryClassLoader);192 }193 private static class MemURLConnection extends URLConnection {194 private final InMemoryClassLoader inMemoryClassLoader;195 private String qualifiedName;196 public MemURLConnection(URL url, InMemoryClassLoader inMemoryClassLoader) {197 super(url);198 this.inMemoryClassLoader = inMemoryClassLoader;199 qualifiedName = url.getPath();200 }201 @Override202 public void connect() throws IOException { }203 @Override204 public InputStream getInputStream() throws IOException {205 return new ByteArrayInputStream(inMemoryClassLoader.inMemoryClassObjects.get(qualifiedName));206 }207 }208 }209 protected URL obtainClassPathOf(String className) {210 String path = className.replace('.', '/') + ".class";211 String url = ClassLoaders.class.getClassLoader().getResource(path).toExternalForm();212 try {213 return new URL(url.substring(0, url.length() - path.length()));214 } catch (MalformedURLException e) {215 throw new RuntimeException("Classloader couldn't obtain a proper classpath URL", e);216 }217 }218 protected List<URL> pathsToURLs(String... codeSourceUrls) {219 return pathsToURLs(Arrays.asList(codeSourceUrls));220 }221 private List<URL> pathsToURLs(List<String> codeSourceUrls) {222 ArrayList<URL> urls = new ArrayList<URL>(codeSourceUrls.size());223 for (String codeSourceUrl : codeSourceUrls) {224 URL url = pathToUrl(codeSourceUrl);225 urls.add(url);226 }227 return urls;228 }229 private URL pathToUrl(String path) {230 try {231 return new File(path).getAbsoluteFile().toURI().toURL();232 } catch (MalformedURLException e) {233 throw new IllegalArgumentException("Path is malformed", e);234 }235 }236 public static class ReachableClassesFinder {237 private ClassLoader classLoader;238 private Set<String> qualifiedNameSubstring = new HashSet<String>();239 public ReachableClassesFinder(ClassLoader classLoader) {240 this.classLoader = classLoader;241 }242 public ReachableClassesFinder omit(String... qualifiedNameSubstring) {243 this.qualifiedNameSubstring.addAll(Arrays.asList(qualifiedNameSubstring));244 return this;245 }246 public Set<String> listOwnedClasses() throws IOException, URISyntaxException {247 Enumeration<URL> roots = classLoader.getResources("");248 Set<String> classes = new HashSet<String>();249 while(roots.hasMoreElements()) {250 URI uri = roots.nextElement().toURI();251 if (uri.getScheme().equalsIgnoreCase("file")) {252 addFromFileBasedClassLoader(classes, uri);253 } else if(uri.getScheme().equalsIgnoreCase(InMemoryClassLoader.SCHEME)) {254 addFromInMemoryBasedClassLoader(classes, uri);255 } else {256 throw new IllegalArgumentException(String.format("Given ClassLoader '%s' don't have reachable by File or vi ClassLoaders.inMemory", classLoader));257 }258 }259 return classes;260 }261 private void addFromFileBasedClassLoader(Set<String> classes, URI uri) {262 File root = new File(uri);263 classes.addAll(findClassQualifiedNames(root, root, qualifiedNameSubstring));264 }265 private void addFromInMemoryBasedClassLoader(Set<String> classes, URI uri) {266 String qualifiedName = uri.getSchemeSpecificPart();267 if(excludes(qualifiedName, qualifiedNameSubstring)) {268 classes.add(qualifiedName);269 }270 }271 private Set<String> findClassQualifiedNames(File root, File file, Set<String> packageFilters) {272 if(file.isDirectory()) {273 File[] files = file.listFiles();274 Set<String> classes = new HashSet<String>();275 for (File children : files) {276 classes.addAll(findClassQualifiedNames(root, children, packageFilters));277 }278 return classes;279 } else {280 if (file.getName().endsWith(".class")) {281 String qualifiedName = classNameFor(root, file);282 if (excludes(qualifiedName, packageFilters)) {283 return Collections.singleton(qualifiedName);284 }285 }286 }287 return Collections.emptySet();288 }289 private boolean excludes(String qualifiedName, Set<String> packageFilters) {290 for (String filter : packageFilters) {291 if(qualifiedName.contains(filter)) return false;292 }293 return true;294 }295 private String classNameFor(File root, File file) {296 String temp = file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1).replace('/', '.');297 return temp.subSequence(0, temp.indexOf(".class")).toString();298 }299 }300}...
Source:Math_72_rank-1_new.java
1package org.mockitoutil;2import java.io.ByteArrayInputStream;3import java.io.File;4import java.io.IOException;5import java.io.InputStream;6import java.net.MalformedURLException;7import java.net.URI;8import java.net.URISyntaxException;9import java.net.URL;10import java.net.URLClassLoader;11import java.net.URLConnection;12import java.net.URLStreamHandler;13import java.util.*;14import static java.util.Arrays.asList;15public abstract class ClassLoaders {16 protected ClassLoader parent = currentClassLoader();17 protected ClassLoaders() {}18 public static IsolatedURLClassLoaderBuilder isolatedClassLoader() {19 return new IsolatedURLClassLoaderBuilder();20 }21 public static ExcludingURLClassLoaderBuilder excludingClassLoader() {22 return new ExcludingURLClassLoaderBuilder();23 }24 public static InMemoryClassLoaderBuilder inMemoryClassLoader() {25 return new InMemoryClassLoaderBuilder();26 }27 public static ReachableClassesFinder in(ClassLoader classLoader_without_jUnit) {28 return new ReachableClassesFinder(classLoader_without_jUnit);29 }30 public static ClassLoader jdkClassLoader() {31 return String.class.getClassLoader();32 }33 public static ClassLoader systemClassLoader() {34 return ClassLoader.getSystemClassLoader();35 }36 public static ClassLoader currentClassLoader() {37 return ClassLoaders.class.getClassLoader();38 }39 public abstract ClassLoader build();40 public static class IsolatedURLClassLoaderBuilder extends ClassLoaders {41 private final ArrayList<String> privateCopyPrefixes = new ArrayList<String>();42 private final ArrayList<URL> codeSourceUrls = new ArrayList<URL>();43 public IsolatedURLClassLoaderBuilder withPrivateCopyOf(String... privatePrefixes) {44 privateCopyPrefixes.addAll(asList(privatePrefixes));45 return this;46 }47 public IsolatedURLClassLoaderBuilder withCodeSourceUrls(String... urls) {48 codeSourceUrls.addAll(pathsToURLs(urls));49 return this;50 }51 public IsolatedURLClassLoaderBuilder withCodeSourceUrlOf(Class<?>... classes) {52 for (Class<?> clazz : classes) {53 codeSourceUrls.add(obtainClassPathOf(clazz.getName()));54 }55 return this;56 }57 public IsolatedURLClassLoaderBuilder withCurrentCodeSourceUrls() {58 codeSourceUrls.add(obtainClassPathOf(ClassLoaders.class.getName()));59 return this;60 }61 public ClassLoader build() {62 return new LocalIsolatedURLClassLoader(63 jdkClassLoader(),64 codeSourceUrls.toArray(new URL[codeSourceUrls.size()]),65 privateCopyPrefixes66 );67 }68 }69 static class LocalIsolatedURLClassLoader extends URLClassLoader {70 private final ArrayList<String> privateCopyPrefixes;71 public LocalIsolatedURLClassLoader(ClassLoader classLoader, URL[] urls, ArrayList<String> privateCopyPrefixes) {72 super(urls, classLoader);73 this.privateCopyPrefixes = privateCopyPrefixes;74 }75 @Override76 public Class<?> findClass(String name) throws ClassNotFoundException {77 if(classShouldBePrivate(name)) return super.findClass(name);78 throw new ClassNotFoundException("Can only load classes with prefix : " + privateCopyPrefixes);79 }80 private boolean classShouldBePrivate(String name) {81 for (String prefix : privateCopyPrefixes) {82 if (name.startsWith(prefix)) return true;83 }84 return false;85 }86 }87 public static class ExcludingURLClassLoaderBuilder extends ClassLoaders {88 private final ArrayList<String> privateCopyPrefixes = new ArrayList<String>();89 private final ArrayList<URL> codeSourceUrls = new ArrayList<URL>();90 public ExcludingURLClassLoaderBuilder without(String... privatePrefixes) {91 privateCopyPrefixes.addAll(asList(privatePrefixes));92 return this;93 }94 public ExcludingURLClassLoaderBuilder withCodeSourceUrls(String... urls) {95 codeSourceUrls.addAll(pathsToURLs(urls));96 return this;97 }98 public ExcludingURLClassLoaderBuilder withCodeSourceUrlOf(Class<?>... classes) {99 for (Class<?> clazz : classes) {100 codeSourceUrls.add(obtainClassPathOf(clazz.getName()));101 }102 return this;103 }104 public ExcludingURLClassLoaderBuilder withCurrentCodeSourceUrls() {105 codeSourceUrls.add(obtainClassPathOf(ClassLoaders.class.getName()));106 return this;107 }108 public ClassLoader build() {109 return new LocalExcludingURLClassLoader(110 jdkClassLoader(),111 codeSourceUrls.toArray(new URL[codeSourceUrls.size()]),112 privateCopyPrefixes113 );114 }115 }116 static class LocalExcludingURLClassLoader extends URLClassLoader {117 private final ArrayList<String> privateCopyPrefixes;118 public LocalExcludingURLClassLoader(ClassLoader classLoader, URL[] urls, ArrayList<String> privateCopyPrefixes) {119 super(urls, classLoader);120 this.privateCopyPrefixes = privateCopyPrefixes;121 }122 @Override123 public Class<?> findClass(String name) throws ClassNotFoundException {124 if(classShouldBePrivate(name)) throw new ClassNotFoundException("classes with prefix : " + privateCopyPrefixes + " are excluded");125 return super.findClass(name);126 }127 private boolean classShouldBePrivate(String name) {128 for (String prefix : privateCopyPrefixes) {129 if (name.startsWith(prefix)) return true;130 }131 return false;132 }133 }134 public static class InMemoryClassLoaderBuilder extends ClassLoaders {135 private Map<String , byte[]> inMemoryClassObjects = new HashMap<String , byte[]>();136 public InMemoryClassLoaderBuilder withParent(ClassLoader parent) {137 this.parent = parent;138 return this;139 }140 public InMemoryClassLoaderBuilder withClassDefinition(String name, byte[] classDefinition) {141 inMemoryClassObjects.put(name, classDefinition);142 return this;143 }144 public ClassLoader build() {145 return new InMemoryClassLoader(parent, inMemoryClassObjects);146 }147 }148 static class InMemoryClassLoader extends ClassLoader {149 public static final String SCHEME = "mem";150 private Map<String , byte[]> inMemoryClassObjects = new HashMap<String , byte[]>();151 public InMemoryClassLoader(ClassLoader parent, Map<String, byte[]> inMemoryClassObjects) {152 super(parent);153 this.inMemoryClassObjects = inMemoryClassObjects;154 }155 protected Class findClass(String name) throws ClassNotFoundException {156 byte[] classDefinition = inMemoryClassObjects.get(name);157 if (classDefinition != null) {158 return defineClass(name, classDefinition, 0, classDefinition.length);159 }160 throw new ClassNotFoundException(name);161 }162 @Override163 public Enumeration<URL> getResources(String ignored) throws IOException {164 return inMemoryOnly();165 }166 private Enumeration<URL> inMemoryOnly() {167 final Set<String> names = inMemoryClassObjects.keySet();168 return new Enumeration<URL>() {169 private final MemHandler memHandler = new MemHandler(InMemoryClassLoader.this);170 private final Iterator<String> it = names.iterator();171 public boolean hasMoreElements() {172 return it.hasNext();173 }174 public URL nextElement() {175 try {176 return new URL(null, SCHEME + ":" + it.next(), memHandler);177 } catch (MalformedURLException rethrown) {178 throw new IllegalStateException(rethrown);179 }180 }181 };182 }183 }184 public static class MemHandler extends URLStreamHandler {185 private InMemoryClassLoader inMemoryClassLoader;186 public MemHandler(InMemoryClassLoader inMemoryClassLoader) {187 this.inMemoryClassLoader = inMemoryClassLoader;188 }189 @Override190 protected URLConnection openConnection(URL url) throws IOException {191 return new MemURLConnection(url, inMemoryClassLoader);192 }193 private static class MemURLConnection extends URLConnection {194 private final InMemoryClassLoader inMemoryClassLoader;195 private String qualifiedName;196 public MemURLConnection(URL url, InMemoryClassLoader inMemoryClassLoader) {197 super(url);198 this.inMemoryClassLoader = inMemoryClassLoader;199 qualifiedName = url.getPath();200 }201 @Override202 public void connect() throws IOException { }203 @Override204 public InputStream getInputStream() throws IOException {205 return new ByteArrayInputStream(inMemoryClassLoader.inMemoryClassObjects.get(qualifiedName));206 }207 }208 }209 protected URL obtainClassPathOf(String className) {210 String path = className.replace('.', '/') + ".class";211 String url = ClassLoaders.class.getClassLoader().getResource(path).toExternalForm();212 try {213 return new URL(url.substring(0, url.length() - path.length()));214 } catch (MalformedURLException e) {215 throw new RuntimeException("Classloader couldn't obtain a proper classpath URL", e);216 }217 }218 protected List<URL> pathsToURLs(String... codeSourceUrls) {219 return pathsToURLs(Arrays.asList(codeSourceUrls));220 }221 private List<URL> pathsToURLs(List<String> codeSourceUrls) {222 ArrayList<URL> urls = new ArrayList<URL>(codeSourceUrls.size());223 for (String codeSourceUrl : codeSourceUrls) {224 URL url = pathToUrl(codeSourceUrl);225 urls.add(url);226 }227 return urls;228 }229 private URL pathToUrl(String path) {230 try {231 return new File(path).getAbsoluteFile().toURI().toURL();232 } catch (MalformedURLException e) {233 throw new IllegalArgumentException("Path is malformed", e);234 }235 }236 public static class ReachableClassesFinder {237 private ClassLoader classLoader;238 private Set<String> qualifiedNameSubstring = new HashSet<String>();239 public ReachableClassesFinder(ClassLoader classLoader) {240 this.classLoader = classLoader;241 }242 public ReachableClassesFinder omit(String... qualifiedNameSubstring) {243 this.qualifiedNameSubstring.addAll(Arrays.asList(qualifiedNameSubstring));244 return this;245 }246 public Set<String> listOwnedClasses() throws IOException, URISyntaxException {247 Enumeration<URL> roots = classLoader.getResources("");248 Set<String> classes = new HashSet<String>();249 while(roots.hasMoreElements()) {250 URI uri = roots.nextElement().toURI();251 if (uri.getScheme().equalsIgnoreCase("file")) {252 addFromFileBasedClassLoader(classes, uri);253 } else if(uri.getScheme().equalsIgnoreCase(InMemoryClassLoader.SCHEME)) {254 addFromInMemoryBasedClassLoader(classes, uri);255 } else {256 throw new IllegalArgumentException(String.format("Given ClassLoader '%s' don't have reachable by File or vi ClassLoaders.inMemory", classLoader));257 }258 }259 return classes;260 }261 private void addFromFileBasedClassLoader(Set<String> classes, URI uri) {262 File root = new File(uri);263 classes.addAll(findClassQualifiedNames(root, root, qualifiedNameSubstring));264 }265 private void addFromInMemoryBasedClassLoader(Set<String> classes, URI uri) {266 String qualifiedName = uri.getSchemeSpecificPart();267 if(excludes(qualifiedName, qualifiedNameSubstring)) {268 classes.add(qualifiedName);269 }270 }271 private Set<String> findClassQualifiedNames(File root, File file, Set<String> packageFilters) {272 if(file.isDirectory()) {273 File[] files = file.listFiles();274 Set<String> classes = new HashSet<String>();275 for (File children : files) {276 classes.addAll(findClassQualifiedNames(root, children, packageFilters));277 }278 return classes;279 } else {280 if (file.getName().endsWith(".class")) {281 String qualifiedName = classNameFor(root, file);282 if (excludes(qualifiedName, packageFilters)) {283 return Collections.singleton(qualifiedName);284 }285 }286 }287 return Collections.emptySet();288 }289 private boolean excludes(String qualifiedName, Set<String> packageFilters) {290 for (String filter : packageFilters) {291 if(qualifiedName.contains(filter)) return false;292 }293 return true;294 }295 private String classNameFor(File root, File file) {296 String temp = file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1).replace('/', '.');297 return temp.subSequence(0, temp.indexOf(".class")).toString();298 }299 }300}...
names.iterator
Using AI Code Generation
1package org.mockitoutil;2import java.io.IOException;3import java.util.Enumeration;4import java.util.Iterator;5import java.util.jar.JarEntry;6import java.util.jar.JarFile;7import java.util.zip.ZipEntry;8import java.util.zip.ZipFile;9public class ClassLoaders {10 public static Iterator<String> names(final ClassLoader classLoader, final String packageName) throws IOException {11 final String path = packageName.replace('.', '/');12 return new Iterator<String>() {13 Enumeration<URL> resources = classLoader.getResources(path);14 Iterator<String> namesInJar = null;15 public boolean hasNext() {16 if (namesInJar == null) {17 if (!resources.hasMoreElements()) {18 return false;19 }20 String resource = resources.nextElement().toString();21 if (resource.startsWith("jar:")) {22 resource = resource.substring(4, resource.indexOf("!"));23 }24 namesInJar = namesInJar(new JarFile(resource), path);25 }26 if (namesInJar.hasNext()) {27 return true;28 }29 namesInJar = null;30 return hasNext();31 }32 public String next() {33 return namesInJar.next();34 }35 public void remove() {36 throw new UnsupportedOperationException();37 }38 };39 }40 private static Iterator<String> namesInJar(final JarFile jar, final String path) {41 return new Iterator<String>() {42 Enumeration<JarEntry> entries = jar.entries();43 public boolean hasNext() {44 return entries.hasMoreElements();45 }46 public String next() {47 return entries.nextElement().getName();48 }49 public void remove() {50 throw new UnsupportedOperationException();51 }52 };53 }54}55public static Iterator<String> namesInJar(final JarFile jar, final String path) {56 return new Iterator<String>() {57 Enumeration<JarEntry> entries = jar.entries();58 public boolean hasNext() {59 return entries.hasMoreElements();60 }61 public String next() {62 return entries.nextElement().getName();63 }64 public void remove() {65 throw new UnsupportedOperationException();66 }67 };68 }
names.iterator
Using AI Code Generation
1import java.util.Iterator;2import org.mockitoutil.ClassLoaders;3public class ClassLoadersTest {4 public static void main(String[] args) {5 Iterator<String> names = ClassLoaders.names("java.lang.String");6 while (names.hasNext()) {7 System.out.println(names.next());8 }9 }10}
names.iterator
Using AI Code Generation
1import org.junit.Test;2import org.mockitoutil.ClassLoaders;3public class ExampleTest {4 public void test() {5 ClassLoaders classLoaders = new ClassLoaders();6 classLoaders.names().iterator();7 }8}9import org.junit.Test;10import org.mockitoutil.ClassLoaders;11public class TestClassLoaders {12 public void test() {13 ClassLoaders classLoaders = new ClassLoaders();14 classLoaders.names().iterator();15 }16}17import org.junit.Test;18import org.mockitoutil.ClassLoaders;19public class TestClassLoaders2 {20 public void test() {21 ClassLoaders classLoaders = new ClassLoaders();22 classLoaders.names().iterator();23 }24}25import org.junit.Test;26import org.mockitoutil.ClassLoaders;27public class TestClassLoaders3 {28 public void test() {29 ClassLoaders classLoaders = new ClassLoaders();30 classLoaders.names().iterator();31 }32}33import org.junit.Test;34import org.mockitoutil.ClassLoaders;35public class TestClassLoaders4 {36 public void test() {37 ClassLoaders classLoaders = new ClassLoaders();38 classLoaders.names().iterator();39 }40}41import org.junit.Test;42import org.mockitoutil.ClassLoaders;43public class TestClassLoaders5 {44 public void test() {45 ClassLoaders classLoaders = new ClassLoaders();46 classLoaders.names().iterator();47 }48}49import org.junit.Test;50import org.mockitoutil.ClassLoaders;51public class TestClassLoaders6 {52 public void test() {53 ClassLoaders classLoaders = new ClassLoaders();
names.iterator
Using AI Code Generation
1public class 1 {2 public static void main(String[] args) {3 ClassLoaders classLoader = new ClassLoaders();4 Iterator<String> names = classLoader.names.iterator();5 while (names.hasNext()) {6 String name = names.next();7 System.out.println(name);8 }9 }10}
names.iterator
Using AI Code Generation
1import org.mockitoutil.ClassLoaders;2import java.util.Iterator;3public class 1 {4 public static void main(String args[]) {5 Iterator names = ClassLoaders.of(1.class).iterator();6 while (names.hasNext()) {7 System.out.println(names.next());8 }9 }10}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!