package for junit
184304
@SuppressWarnings({"PMD.NPathComplexity"})
	/*package*/ URI buildUri(final String rawUrl, final String branch, final String lastKnownCommit) throws URISyntaxException {
		URIBuilder builder = new URIBuilder();
		
		/*
		 * Examples:
		 * 
		 * ssh://git@company.com/project/repository.git
		 * https://username@company.com/scm/project/repository.git
		 * ssh://git@company.com/~username/repository.git
		 * https://username@company.com/scm/~username/repository.git
		 * 
		 */
		
		String repoUrlRaw = rawUrl;
		String repoUrlProcessed = repoUrlRaw;
		
		if (repoUrlProcessed.endsWith(".git")) {
			repoUrlProcessed = repoUrlProcessed.substring(0, repoUrlProcessed.lastIndexOf(".git"));
		}
		
		URI uri = URI.create(repoUrlProcessed.replaceAll(" ", "%20"));
		
		String host = uri.getHost();
		String scheme = "ssh".equalsIgnoreCase(uri.getScheme())? "https" : uri.getScheme();
		int port = uri.getPort();
		String path = uri.getPath();
		if ((path.startsWith("scm/") || path.startsWith("/scm")) && path.length() > 4) {
			path = path.substring(4);
		}
		if (path.length() > 0 && path.charAt(0) == '/') {
			path = path.substring(1, path.length());
		}
		
		String[] splitPath = path.split("/");
		String projectKey = "";
		String repositorySlug = "";
		
		if (splitPath.length > 1) {
			projectKey = splitPath[0];
			repositorySlug = path.substring(path.indexOf('/') + 1, path.length());
		} else {
			// Shouldn't get to this case
			projectKey = "";
			repositorySlug = path;
		}
		
		String apiPath = settings.getApi() != null? settings.getApi() : "";
		
		if (apiPath.endsWith("/")) {
			apiPath = settings.getApi().substring(0, settings.getApi().length() - 1);
		}
		
		builder.setScheme(scheme);
		builder.setHost(host);
		if (port != -1) {
			builder.setPort(port);
		}
		
		builder.setPath(apiPath + "/projects/" + projectKey + "/repos/" + repositorySlug + "/commits");
		if (branch == null || branch.length() == 0) {
			builder.addParameter("until", "master");
		} else {
			builder.addParameter("until", branch.replaceAll(" ", "%20"));
		}
		
		if (lastKnownCommit != null && lastKnownCommit.length() > 0) {
			builder.addParameter("since", lastKnownCommit);
		}
		
		if (settings.getPageSize() > 0) {
			builder.addParameter("limit", String.valueOf(settings.getPageSize()));
		}
		
		return builder.build();
	}
24870
public static void main(String[] args) {
        /*
         * Developers Notes:
         *
         * -No corresponding Junit test class currently
         * provided.  Test by eyeball of the output.
         *
         * -Add a menu with Help(About)
         * --> TBD.
         *
         * -Figure out some sane way to set initial default
         * column sizes.
         *
         * -Lots of inner classes here, done in order to keep
         * all the .class files easily identifiable.  Some of
         * this code is pretty ugly, very procedural in nature.
         * Lots of very tight coupling between all the classes,
         * thinly disguised switch statements, etc ..... This
         * code written on the fly, with almost no thought given
         * to OO design.
         *
         * -Also, I'm not really a GUI guy, so forgive any
         * transgressions.
         *
         */
            if ( args.length < 1 ) {
                System.err.println("File name is required!");
                usage();
                System.exit(1);
            }
        /*
         * Instantiate a DateTimeBrowser and invoke it's go method,
         * passing the input argument list.
         */
        new DateTimeBrowser().go( args );
    }
314357
def checklist(ctx):
    """"""
    checklist = """PRE-RELEASE CHECKLIST:
[ ]  Everything is checked in
[ ]  All tests pass w/ tox

RELEASE CHECKLIST:
[{x1}]  Bump version to new-version and tag repository (via bump_version)
[{x2}]  Build packages (sdist, bdist_wheel via prepare)
[{x3}]  Register and upload packages to testpypi repository (first)
[{x4}]    Verify release is OK and packages from testpypi are usable
[{x5}]  Register and upload packages to pypi repository
[{x6}]  Push last changes to Github repository

POST-RELEASE CHECKLIST:
[ ]  Bump version to new-develop-version (via bump_version)
[ ]  Adapt CHANGES (if necessary)
[ ]  Commit latest changes to Github repository
"""
    steps = dict(x1=None, x2=None, x3=None, x4=None, x5=None, x6=None)
    yesno_map = {True: "x", False: "_", None: " "}
    answers = {name: yesno_map[value]
               for name, value in steps.items()}
    print(checklist.format(**answers))
1344898
void buildPackagePrefix(final String className) {
        // TODO test
        final int lastPackageSeparator = className.lastIndexOf('/');
        final String packageName = className.substring(0, lastPackageSeparator == -1 ? className.length() : lastPackageSeparator);
        final String[] splitPackage = packageName.split("/");

        if (splitPackage.length >= PROJECT_PACKAGE_HIERARCHIES) {
            projectPackagePrefix = IntStream.range(0, PROJECT_PACKAGE_HIERARCHIES).mapToObj(i -> splitPackage[i]).collect(Collectors.joining("/"));
        } else {
            projectPackagePrefix = packageName;
        }
    }
691418
public static void main(Class main, String[] args, String[] packageNamesToWeave) throws Exception{
    for (String packageName : packageNamesToWeave) {
      weavePackage(packageName);
    }
    ArrayList<String> l = new ArrayList<String>(Arrays.asList(args));
    l.add(0, "-mainClass");
    l.add(1, main.getName());
    _init.boot2(l.toArray(new String[0]));
  }
713657
public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            System.out.println("There should be an argument: path to a jar.");
            System.exit(0);
        }
        String jarInput = args[0];
        extract(new File(jarInput), new File("/tmp/junit-ekstazi-agent.jar"),
                new String[] { Names.EKSTAZI_PACKAGE_BIN }, new String[] {});
        for (String name : extractClassNames("/tmp/junit-ekstazi-agent.jar")) {
            System.out.println(name);
        }
    }
1120557
def main(argv=None):
    
    @contextmanager
    def tmpdir():
        """ Create a self-deleting temporary directory. """
        path = mkdtemp()
        try:
            yield path
        finally:
            rmtree(path)
        return

    def test():
        """ Execute the test suite. """
        install = "{:s} install -r requirements-test.txt"
        check_call(install.format(pip).split())
        pytest = join(path, "bin", "py.test")
        test = "{:s} test/".format(pytest)
        check_call(test.split())
        uninstall = "{:s} uninstall -y -r requirements-test.txt"
        check_call(uninstall.format(pip).split())
        return

    args = _cmdline(argv)
    path = join(abspath(args.root), args.name)
    with tmpdir() as tmp:
        clone = "git clone {:s} {:s}".format(args.repo, tmp)
        check_call(clone.split())
        chdir(tmp)
        checkout = "git checkout {:s}".format(args.checkout)
        check_call(checkout.split())
        virtualenv = "virtualenv {:s}".format(path)
        check_call(virtualenv.split())
        pip = join(path, "bin", "pip")
        install = "{:s} install -U -r requirements.txt .".format(pip)
        check_call(install.split())
        if args.test:
            test()
    return 0
604782
def system(session):
    """"""
    system_test_path = os.path.join("tests", "system.py")
    system_test_folder_path = os.path.join("tests", "system")
    # Sanity check: Only run tests if the environment variable is set.
    if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""):
        session.skip("Credentials must be set via environment variable")

    system_test_exists = os.path.exists(system_test_path)
    system_test_folder_exists = os.path.exists(system_test_folder_path)
    # Sanity check: only run tests if found.
    if not system_test_exists and not system_test_folder_exists:
        session.skip("System tests were not found")

    # Use pre-release gRPC for system tests.
    session.install("--pre", "grpcio")

    # Install all test dependencies, then install this package into the
    # virtualenv's dist-packages.
    session.install("mock", "pytest")
    for local_dep in LOCAL_DEPS:
        session.install("-e", local_dep)
    session.install("-e", "../test_utils/")
    session.install("-e", ".")

    # Run py.test against the system tests.
    if system_test_exists:
        session.run("py.test", "--quiet", system_test_path, *session.posargs)
    if system_test_folder_exists:
        session.run("py.test", "--quiet", system_test_folder_path, *session.posargs)
1099456
private TypeSpec generateContentValuesBuilderClass(ObjectMappableAnnotatedClass clazz,
      String mapperClassName, String className) {

    String cvVarName = "contentValues";

    MethodSpec constructor = MethodSpec.constructorBuilder()
        .addModifiers(Modifier.PRIVATE)
        .addStatement("$L = new $T()", cvVarName, ClassName.get(ContentValues.class))
        .build();

    TypeSpec.Builder builder = TypeSpec.classBuilder(className)
        .addJavadoc(
            "Builder class to generate type sage {@link $T } . At the end you have to call {@link #build()}\n",
            TypeName.get(ContentValues.class))
        .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
        .addField(ContentValues.class, cvVarName, Modifier.PRIVATE)
        .addMethod(constructor)
        .addMethod(MethodSpec.methodBuilder("build")
            .addJavadoc("Creates and returns a $T from the builder\n",
                TypeName.get(ContentValues.class))
            .addJavadoc("@return $T", TypeName.get(ContentValues.class))
            .addModifiers(Modifier.PUBLIC)
            .addStatement("return $L", cvVarName)
            .returns(ContentValues.class)
            .build());

    String packageName = getPackageName(clazz);
    for (ColumnAnnotateable e : clazz.getColumnAnnotatedElements()) {
      e.generateContentValuesBuilderMethod(builder,
          ClassName.get(packageName, mapperClassName, className), cvVarName);
    }

    return builder.build();
  }
35655
protected final PackageDescr compilationUnit(PackageDescrBuilder pkg) throws RecognitionException {
        try {
            // package declaration?
            if (input.LA(1) != DRL6Lexer.EOF && helper.validateIdentifierKey(DroolsSoftKeywords.PACKAGE)) {
                String pkgName = packageStatement(pkg);
                pkg.name(pkgName);
                if (state.failed)
                    return pkg.getDescr();

                // unit declaration?
                // this is only allowed immediately after the package declaration
                if (input.LA(1) != DRL6Lexer.EOF && helper.validateIdentifierKey(DroolsSoftKeywords.UNIT)) {
                    unitStatement(pkg);
                }
            }

            // statements
            while (input.LA(1) != DRL6Lexer.EOF) {
                int next = input.index();
                if (helper.validateStatement(1)) {
                    statement(pkg);
                    if (state.failed)
                        return pkg.getDescr();

                    if (next == input.index()) {
                        // no token consumed, so, report problem:
                        resyncToNextStatement();
                    }
                } else {
                    resyncToNextStatement();
                }

                if (input.LA(1) == DRL6Lexer.SEMICOLON) {
                    match(input,
                            DRL6Lexer.SEMICOLON,
                            null,
                            null,
                            DroolsEditorType.SYMBOL);
                    if (state.failed)
                        return pkg.getDescr();
                }
            }
        } catch (RecognitionException e) {
            helper.reportError(e);
        } catch (Exception e) {
            helper.reportError(e);
        } finally {
            helper.setEnd(pkg);
        }
        return pkg.getDescr();
    }
383285
private static StackTraceElement findStackTraceElement(Throwable t) {
       StackTraceElement element = t.getStackTrace().length > 0 ? t.getStackTrace()[0] : null;
       int index = 0;
        String chorusAssertClassName = ChorusAssert.class.getName();
        String junitAssertClassName = "org.junit.Assert";  //junit may not be in classpath so don't use Assert.class.getName()
        String junitLegacyClassName = "junit.framework.Assert";  //need to support alternative (legacy?) junit 3 style Assert
        while ( element != null && (
                element.getClassName().contains(chorusAssertClassName) ||
                element.getClassName().contains(junitAssertClassName) ||
                element.getClassName().contains(junitLegacyClassName))
            ) {
           index += 1;
           element = t.getStackTrace().length > index ? t.getStackTrace()[index] : null;
       }
       return element;
    }
30352
def build(check, sdist):
    """"""
    if check in get_valid_checks():
        check_dir = os.path.join(get_root(), check)
    else:
        check_dir = resolve_path(check)
        if not dir_exists(check_dir):
            abort('`{}` is not an Agent-based Integration or Python package'.format(check))

        check = basepath(check_dir)

    echo_waiting('Building `{}`...'.format(check))

    dist_dir = os.path.join(check_dir, 'dist')
    remove_path(dist_dir)

    result = build_package(check_dir, sdist)
    if result.code != 0:
        abort(result.stdout, result.code)

    echo_info('Build done, artifact(s) in: {}'.format(dist_dir))
    echo_success('Success!')
1026307
def main():
    """"""
    description = ('PATH can be either the path to a scratch file, or a '
                   'directory containing scratch files. Multiple PATH '
                   'arguments can be provided.')
    parser = OptionParser(usage='%prog -p PLUGIN_NAME [options] PATH...',
                          description=description,
                          version='%prog {}'.format(__version__))
    parser.add_option('-d', '--plugin-dir', metavar='DIR',
                      help=('Specify the path to a directory containing '
                            'plugins. Plugins in this directory take '
                            'precedence over similarly named plugins '
                            'included with Hairball.'))
    parser.add_option('-p', '--plugin', action='append',
                      help=('Use the named plugin to perform analysis. '
                            'This option can be provided multiple times.'))
    parser.add_option('-k', '--kurt-plugin', action='append',
                      help=('Provide either a python import path (e.g, '
                            'kelp.octopi) to a package/module, or the path'
                            ' to a python file, which will be loaded as a '
                            'Kurt plugin. This option can be provided '
                            'multiple times.'))
    parser.add_option('-q', '--quiet', action='store_true',
                      help=('Prevent output from Hairball. Plugins may still '
                            'produce output.'))
    parser.add_option('-C', '--no-cache', action='store_true',
                      help='Do not use Hairball\'s cache.', default=False)
    options, args = parser.parse_args(sys.argv[1:])

    if not options.plugin:
        parser.error('At least one plugin must be specified via -p.')
    if not args:
        parser.error('At least one PATH must be provided.')

    if options.plugin_dir:
        if os.path.isdir(options.plugin_dir):
            sys.path.append(options.plugin_dir)
        else:
            parser.error('{} is not a directory'.format(options.plugin_dir))

    hairball = Hairball(options, args, cache=not options.no_cache)
    hairball.initialize_plugins()
    hairball.process()
    hairball.finalize()
605863
private void scanClasses0(String basePackage)
            throws IOException, ClassNotFoundException, FileNotFoundException {
        File packageDirectory = null;
        ClassLoader cld = getLoader();
        String basePackagePath = basePackage.replace('.', '/');
        Enumeration<URL> basePackageUrls = cld.getResources(basePackagePath);
        if (basePackageUrls == null || !basePackageUrls.hasMoreElements()) {
            throw new ClassNotFoundException("Base package path not found: [" + basePackagePath
                    + "]");
        }
        while (basePackageUrls.hasMoreElements()) {
            String packagePath = basePackageUrls.nextElement().getFile();
            if (packagePath.contains(JAR_FILE_PATTERN)) {
                scanJarFile(basePackagePath, packagePath);
            } else {
                packageDirectory = new File(packagePath);
                scanDirectory(basePackage, packageDirectory);
            }
        }
    }
340686
function &_buildFrame(&$package)
    {
        ob_start();

        echo '<body id="frame">', "\n\n";

        echo '<h1><a href="package-summary.html" target="main">', $package->name(), "</a></h1>\n\n";

        $classes =& $package->ordinaryClasses();
        if ($classes && is_array($classes)) {
            ksort($classes);
            echo "<h2>Classes</h2>\n";
            echo "<ul>\n";
            foreach ($classes as $name => $class) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $classes[$name]->asPath(), '" target="main">', $classes[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $interfaces =& $package->interfaces();
        if ($interfaces && is_array($interfaces)) {
            ksort($interfaces);
            echo "<h2>Interfaces</h2>\n";
            echo "<ul>\n";
            foreach ($interfaces as $name => $interface) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $interfaces[$name]->asPath(), '" target="main">', $interfaces[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $traits =& $package->traits();
        if ($traits && is_array($traits)) {
            ksort($traits);
            echo "<h2>Traits</h2>\n";
            echo "<ul>\n";
            foreach ($traits as $name => $trait) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $traits[$name]->asPath(), '" target="main">', $traits[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $exceptions =& $package->exceptions();
        if ($exceptions && is_array($exceptions)) {
            ksort($exceptions);
            echo "<h2>Exceptions</h2>\n";
            echo "<ul>\n";
            foreach ($exceptions as $name => $exception) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $exceptions[$name]->asPath(), '" target="main">', $exceptions[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $functions =& $package->functions();
        if ($functions && is_array($functions)) {
            ksort($functions);
            echo "<h2>Functions</h2>\n";
            echo "<ul>\n";
            foreach ($functions as $name => $function) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $functions[$name]->asPath(), '" target="main">', $functions[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        $globals =& $package->globals();
        if ($globals && is_array($globals)) {
            ksort($globals);
            echo "<h2>Globals</h2>\n";
            echo "<ul>\n";
            foreach ($globals as $name => $global) {
                echo '<li><a href="', str_repeat('../', $package->depth() + 1), $globals[$name]->asPath(), '" target="main">', $globals[$name]->name(), "</a></li>\n";
            }
            echo "</ul>\n\n";
        }

        echo '</body>', "\n\n";

        $output = ob_get_contents();
        ob_end_clean();

        return $output;
    }
1213848
def main():
    """"""
    source_files = (
        ('integration', r'results/results.xml'),
        ('unittests', r'results/unittests.xml'),
        ('coverage', r'results/coverage.xml')
    )

    parsed = {k: ElementTree.parse(v).getroot().attrib for k, v in source_files}

    with open(r'results/summary.json', 'w') as fh:
        json.dump(parsed, fh)
1038232
private String getJUnitReportsFolder() {
        if (ClassUtils.isPresent("org.testng.annotations.Test", getClass().getClassLoader())) {
            return "test-output" + File.separator + "junitreports";
        } else if (ClassUtils.isPresent("org.junit.Test", getClass().getClassLoader())) {
            JUnitReporter jUnitReporter = new JUnitReporter();
            return jUnitReporter.getReportDirectory() + File.separator + jUnitReporter.getOutputDirectory();
        } else {
            return new LoggingReporter().getReportDirectory();
        }
    }