How to use getClassLoader method of net.serenitybdd.jbehave.Finder class

Best Serenity jBehave code snippet using net.serenitybdd.jbehave.Finder.getClassLoader

Source:SerenityStories.java Github

copy

Full Screen

...70        return configuration;71    }72    @Override73    public InjectableStepsFactory stepsFactory() {74        return SerenityStepFactory.withStepsFromPackage(getRootPackage(), configuration()).andClassLoader(getClassLoader());75    }76    /**77     * The class loader used to obtain the JBehave and Step implementation classes.78     * You normally don't need to worry about this, but you may need to override it if your application79     * is doing funny business with the class loaders.80     */81    public ClassLoader getClassLoader() {82        return Thread.currentThread().getContextClassLoader();83    }84    @Override85    public List<String> storyPaths() {86        Set<String> storyPaths = new HashSet<>();87        List<String> pathExpressions = getStoryPathExpressions();88        StoryFinder storyFinder = new StoryFinder();89        for (String pathExpression : pathExpressions) {90            if (absolutePath(pathExpression)) {91                storyPaths.add(pathExpression);92            }93            for (URL classpathRootUrl : allClasspathRoots()) {94                storyPaths.addAll(storyFinder.findPaths(classpathRootUrl, pathExpression, ""));95            }96            storyPaths = removeDuplicatesFrom(storyPaths);97            storyPaths = pruneGivenStoriesFrom(storyPaths);98        }99        return sorted(storyPaths);100    }101    private List<String> sorted(Set<String> storyPaths) {102        List<String> sortedStories = Lists.newArrayList(storyPaths);103        Collections.sort(sortedStories);104        return sortedStories;105    }106    private Set<String> removeDuplicatesFrom(Set<String> storyPaths) {107        Set<String> trimmedPaths = new HashSet<>();108        for(String storyPath : storyPaths) {109            if (!thereExistsALongerVersionOf(storyPath, storyPaths)) {110                trimmedPaths.add(storyPath);111            }112        }113        return trimmedPaths;114    }115    private boolean thereExistsALongerVersionOf(String storyPath, Set<String> storyPaths) {116        for(String existingPath : storyPaths) {117            if ((existingPath.endsWith("/" + storyPath)) || (existingPath.endsWith("\\" + storyPath))) {118                return true;119            }120        }121        return false;122    }123    private Set<String> pruneGivenStoriesFrom(Set<String> storyPaths) {124        List<String> filteredPaths = Lists.newArrayList(storyPaths);125        for (String skippedPrecondition : skippedPreconditions()) {126            filteredPaths = removeFrom(filteredPaths)127                    .pathsNotStartingWith(skippedPrecondition)128                    .and().pathsNotStartingWith("/" + skippedPrecondition)129                    .filter();130        }131        return new HashSet<>(filteredPaths);132    }133    class FilterBuilder {134        private final List<String> paths;135        public FilterBuilder(List<String> paths) {136            this.paths = paths;137        }138        public FilterBuilder pathsNotStartingWith(String skippedPrecondition) {139            List<String> filteredPaths = new ArrayList<>();140            for (String path : paths) {141                if (!startsWith(skippedPrecondition, path)) {142                    filteredPaths.add(path);143                }144            }145            return new FilterBuilder(filteredPaths);146        }147        public FilterBuilder and() {148            return this;149        }150        public List<String> filter() {151            return ImmutableList.copyOf(paths);152        }153        private boolean startsWith(String skippedPrecondition, String path) {154            return path.toLowerCase().startsWith(skippedPrecondition.toLowerCase());155        }156    }157    private FilterBuilder removeFrom(List<String> filteredPaths) {158        return new FilterBuilder(filteredPaths);159    }160    private List<String> skippedPreconditions() {161        return DEFAULT_GIVEN_STORY_PREFIX;162    }163    private boolean absolutePath(String pathExpression) {164        return (!pathExpression.contains("*"));165    }166    private Set<URL> allClasspathRoots() {167        try {168            Set<URL> baseRoots = new HashSet<>(Collections.list(getClassLoader().getResources(".")));169            return addGradleResourceRootsTo(baseRoots);170        } catch (IOException e) {171            throw new IllegalArgumentException("Could not load the classpath roots when looking for story files", e);172        }173    }174    private Set<URL> addGradleResourceRootsTo(Set<URL> baseRoots) throws MalformedURLException {175        Set<URL> rootsWithGradleResources = new HashSet<>(baseRoots);176        for (URL baseUrl : baseRoots) {177            String gradleResourceUrl = baseUrl.toString().replace("/build/classes/", "/build/resources/");178            rootsWithGradleResources.add(new URL(gradleResourceUrl));179        }180        return rootsWithGradleResources;181    }182    /**...

Full Screen

Full Screen

Source:ClassFinder.java Github

copy

Full Screen

...72        Reflections reflections = new Reflections(packageName,73                new SubTypesScanner(),74                new TypeAnnotationsScanner(),75                new MethodAnnotationsScanner(),76                new ResourcesScanner(), getClassLoader());77        Set<Class<?>> matchingClasses = new HashSet<>();78        for (Class<? extends Annotation> expectedAnnotation : expectedAnnotations) {79            matchingClasses.addAll(reflections.getTypesAnnotatedWith(expectedAnnotation));80            matchingClasses.addAll(classesFrom(reflections.getMethodsAnnotatedWith(expectedAnnotation)));81        }82        return ImmutableList.copyOf(matchingClasses);83    }84    private Collection<Class<?>> classesFrom(Set<Method> annotatedMethods) {85        return annotatedMethods.stream()86                .map(Method::getDeclaringClass)87                .collect(Collectors.toList());88    }89    private Enumeration<URL> classResourcesOn(String path) {90        try {91            return getClassLoader().getResources(path);92        } catch (IOException e) {93            throw new IllegalArgumentException("Could not access class path at " + path, e);94        }95    }96    /**97     * Recursive method used to find all classes in a given directory and subdirs.98     *99     * @param directory   The base directory100     * @param packageName The package name for classes found inside the base directory101     * @return The classes102     */103    private List<Class<?>> findClasses(URI directory, String packageName) {104        try {105            final String scheme = directory.getScheme();106            final String schemeSpecificPart = directory.getSchemeSpecificPart();107            if (scheme.equals("jar") && schemeSpecificPart.contains("!")) {108                return findClassesInJar(directory, packageName);109            } else if (scheme.equals("file")) {110                return findClassesInFileSystemDirectory(directory, packageName);111            }112            throw new IllegalArgumentException("cannot handle URI with scheme [" + scheme + "]");113        } catch (Exception e) {114            throw new RuntimeException(115                    "failed to find classes" +116                            "in directory=[" + directory + "], with packageName=[" + packageName + "]",117                    e118            );119        }120    }121    private List<Class<?>> findClassesInJar(URI jarDirectory, String packageName) throws IOException {122        final String schemeSpecificPart = jarDirectory.getSchemeSpecificPart();123        List<Class<?>> classes = new ArrayList<>();124        String[] split = schemeSpecificPart.split("!");125        URL jar = new URL(split[0]);126        try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {127            ZipEntry entry;128            while ((entry = zip.getNextEntry()) != null) {129                if (entry.getName().endsWith(".class")) {130                    String className = classNameFor(entry);131                    if (className.startsWith(packageName) && isNotAnInnerClass(className)) {132                        loadClassWithName(className).ifPresent(classes::add);133                    }134                }135            }136        }137        return classes;138    }139    private List<Class<?>> findClassesInFileSystemDirectory(URI jarDirectory, String packageName) {140        List<Class<?>> classes = new ArrayList<>();141        File directory = new File(jarDirectory);142        if (!directory.exists()) {143            return classes;144        }145        File[] files = directory.listFiles();146        if (files != null) {147            for (File file : files) {148                if (file.isDirectory()) {149                    classes.addAll(findClasses(file.toURI(), packageName + "." + file.getName()));150                } else if (file.getName().endsWith(".class") && isNotAnInnerClass(file.getName())) {151                    correspondingClass(packageName, file).ifPresent(classes::add);152                }153            }154        }155        return classes;156    }157    private static String classNameFor(ZipEntry entry) {158        return entry.getName().replaceAll("[$].*", "").replaceAll("[.]class", "").replace('/', '.');159    }160    private Optional<? extends Class<?>> loadClassWithName(String className) {161        try {162            return Optional.of(getClassLoader().loadClass(className));163        } catch (ClassNotFoundException e) {164//            throw new IllegalArgumentException("Could not find or access class for " + className, e);165            return Optional.empty();166        } catch (NoClassDefFoundError noClassDefFoundError) {167            return Optional.empty();168        }169    }170    private Optional<? extends Class<?>> correspondingClass(String packageName, File file) {171        String fullyQualifiedClassName = packagePrefixFor(packageName) + simpleClassNameOf(file);172        return loadClassWithName(fullyQualifiedClassName);173    }174    private String packagePrefixFor(String packageName) {175        return (packageName.isEmpty() || packageName.equals("/")) ? "" : packageName + '.';176    }177    private static ClassLoader getDefaultClassLoader() {178        return Thread.currentThread().getContextClassLoader();179    }180    private String simpleClassNameOf(File file) {181        return file.getName().substring(0, file.getName().length() - 6);182    }183    private boolean isNotAnInnerClass(String className) {184        return (!className.contains("$"));185    }186    public ClassLoader getClassLoader() {187        return classLoader;188    }189}...

Full Screen

Full Screen

Source:StoryPathFinder.java Github

copy

Full Screen

...59    private String withWildcard(String resourceName) {60        return "**/" + resourceName;61    }62    private Optional<URL> storyOnClasspath(String storyFile) {63        return Optional.ofNullable(getClassLoader().getResource(storyFile));64    }65    private List<String> rootStoryNamesFrom(String storyNames) {66        return Lists.newArrayList(Splitter.on(";").trimResults().omitEmptyStrings().split(storyNames));67    }68    private String join(String packagePath, String storyName) {69        if (packagePath == null) {70            return storyName;71        } else if (packagePath.endsWith("/")) {72            return packagePath + storyName;73        } else {74            return packagePath + "/" + storyName;75        }76    }77    private List<String> getClasspathPackages() {78        String storyDirectory = environmentVariables.getProperty(STORY_DIRECTORY,"stories");79        List<String> packages = Lists.newArrayList("/",storyDirectory,"/" + storyDirectory);80        String storyPackages = environmentVariables.getProperty(JBEHAVE_STORY_PACKAGES.getName());81        if (StringUtils.isNotEmpty(storyPackages)) {82            packages.addAll(Lists.newArrayList(Splitter.on(";").trimResults().omitEmptyStrings().split(storyPackages)));83        }84        return packages;85    }86    private ClassLoader getClassLoader() {87        return Thread.currentThread().getContextClassLoader();88    }89}...

Full Screen

Full Screen

getClassLoader

Using AI Code Generation

copy

Full Screen

1    ClassLoader classLoader = new Finder().getClassLoader();2    InputStream inputStream = classLoader.getResourceAsStream("login.story");3    String storyAsString = IOUtils.toString(inputStream);4    System.out.println(storyAsString);5    ClassLoader classLoader = getClass().getClassLoader();6    InputStream inputStream = classLoader.getResourceAsStream("login.story");7    String storyAsString = IOUtils.toString(inputStream);8    System.out.println(storyAsString);9    ClassLoader classLoader = getClass().getClassLoader();10    File file = new File(classLoader.getResource("login.story").getFile());11    String storyAsString = FileUtils.readFileToString(file);12    System.out.println(storyAsString);13    ClassLoader classLoader = getClass().getClassLoader();14    File file = new File(classLoader.getResource("login.story").getFile());15    String storyAsString = FileUtils.readFileToString(file);16    System.out.println(storyAsString);17    ClassLoader classLoader = getClass().getClassLoader();18    File file = new File(classLoader.getResource("login.story").getFile());19    String storyAsString = FileUtils.readFileToString(file);20    System.out.println(storyAsString);21    ClassLoader classLoader = getClass().getClassLoader();22    File file = new File(classLoader.getResource("login.story").getFile());23    String storyAsString = FileUtils.readFileToString(file);24    System.out.println(storyAsString);25    ClassLoader classLoader = getClass().getClassLoader();26    File file = new File(classLoader.getResource("login.story").getFile());27    String storyAsString = FileUtils.readFileToString(file);28    System.out.println(storyAsString);29    ClassLoader classLoader = getClass().getClassLoader();30    File file = new File(classLoader.getResource("login.story").getFile());31    String storyAsString = FileUtils.readFileToString(file);32    System.out.println(storyAsString);33    ClassLoader classLoader = getClass().getClassLoader();34    File file = new File(classLoader.getResource("login.story").getFile());35    String storyAsString = FileUtils.readFileToString(file);36    System.out.println(storyAsString);

Full Screen

Full Screen

getClassLoader

Using AI Code Generation

copy

Full Screen

1import java.io.*;2import java.util.*;3import java.util.stream.*;4import java.util.regex.*;5import java.util.function.*;6import java.nio.file.*;7import java.net.*;8import java.util.*;9import java.util.stream.*;10import java.util.regex.*;11import java.util.function.*;12import java.nio.file.*;13import java.net.*;14import java.io.*;15import java.util.*;16import java.util.stream.*;17import java.util.regex.*;18import java.util.function.*;19import java.nio.file.*;20import java.net.*;

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Serenity jBehave automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful