Download jar through {@link Grape} given an org, module and version
It is assumed that an ivy settings file exists on the classpath
5488
public static URI[] downloadJar(String org, String module, String version, boolean transitive) throws IOException {
    Map<String, Object> artifactMap = Maps.newHashMap();
    artifactMap.put("org", org);
    artifactMap.put("module", module);
    artifactMap.put("version", version);
    artifactMap.put("transitive", transitive);
    return downloadJar(artifactMap);
  }
1157572
public int execute() throws IOException {
        outputDir.mkdirs();

        if (packageName == null || packageName.length() == 0) {
            packageName = groupId + "." + artifactId;
        }

        String packageDir = packageName.replace('.', '/');

        debug("Creating archetype using Maven groupId: " + groupId + ", artifactId: " + artifactId + ", version: " + version + " in directory: " + outputDir);

        Map<String, String> replaceProperties = parseProperties();
        replaceProperties.putAll(overrideProperties);

        debug("Using replace properties: " + replaceProperties);

        ZipFile zip = null;
        try {
            zip = new ZipFile(archetypeFile);
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                final ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory()) {
                    String fullName = entry.getName();
                    if (fullName != null && fullName.startsWith(zipEntryPrefix)) {
                        String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()), replaceProperties);
                        debug("Processing resource: " + name);

                        int idx = name.lastIndexOf('/');
                        Matcher matcher = sourcePathRegexPattern.matcher(name);
                        String dirName;
                        if (packageName.length() > 0 && idx > 0 && matcher.matches()) {
                            String prefix = matcher.group(1);
                            dirName = prefix + packageDir + "/" + name.substring(prefix.length());
                        } else if (packageName.length() > 0 && name.startsWith(webInfResources)) {
                            dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources" + name.substring(webInfResources.length());
                        } else {
                            dirName = name;
                        }

                        // lets replace properties...
                        File file = new File(outputDir, dirName);
                        file.getParentFile().mkdirs();
                        FileOutputStream out = null;
                        try {
                            out = new FileOutputStream(file);
                            boolean isBinary = false;
                            for (String suffix : binarySuffixes) {
                                if (name.endsWith(suffix)) {
                                    isBinary = true;
                                    break;
                                }
                            }
                            if (isBinary) {
                                // binary file?  don't transform.
                                IOHelpers.copy(zip.getInputStream(entry), out);
                            } else {
                                // text file...
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                IOHelpers.copy(zip.getInputStream(entry), bos);
                                String text = new String(bos.toByteArray(), "UTF-8");
                                out.write(transformContents(text, replaceProperties).getBytes());
                            }
                        } finally {
                            if (out != null) {
                                IOHelpers.close(out);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        } finally {
            if (zip != null) {
                IOHelpers.close(zip);
            }
        }

        // now lets replace all the properties in the pom.xml
        if (!replaceProperties.isEmpty()) {
            File pom = new File(outputDir, "pom.xml");
            if (!pom.isFile()) {
                // must be non maven archetype?
                return 0;
            }
            String text = IOHelpers.readFully(new FileReader(pom));
            for (Map.Entry<String, String> e : replaceProperties.entrySet()) {
                text = replaceVariable(text, e.getKey(), e.getValue());
            }
            // replace name if we have a custom name
            if (Strings.isNotBlank(name)) {
                text = text.replaceFirst("<name>(.*)</name>", "<name>" + name + "</name>");
            }
            // replace description if we have a custom description
            if (Strings.isNotBlank(description)) {
                text = text.replaceFirst("<description>(.*)</description>", "<description>" + description + "</description>");
            }
            IOHelpers.writeTo(pom, text);
        }

        // now lets create the default directories
        if (createDefaultDirectories) {
            File srcDir = new File(outputDir, "src");
            File mainDir = new File(srcDir, "main");
            File testDir = new File(srcDir, "test");

            String srcDirName = "java";

            for (File dir : new File[]{mainDir, testDir}) {
                for (String name : new String[]{srcDirName + "/" + packageDir, "resources"}) {
                    new File(dir, name).mkdirs();
                }
            }
        }

        return 0;
    }
267868
function _downloadNode(
  version,
  directory,
  nodeConfigureArgs,
  nodeMakeArgs,
  nodeVCBuildArgs,
  complete,
) {
  var nodeFileDir = path.resolve(path.join(directory, framework, version)), // fixes #107, was process.cwd(), + rest.
    nodeFilePath = path.resolve(
      path.join(nodeFileDir, framework + '-' + version + '.tar.gz'),
    );

  // might already be downloaded, and unzipped
  if (
    _getNodeCompiler(
      nodeFileDir,
      nodeConfigureArgs,
      nodeMakeArgs,
      nodeVCBuildArgs,
      complete,
    )
  ) {
    return;
  }

  async.waterfall(
    [
      /**
       * first make the directory where the zip file will live
       */

      function makeDirectory(next) {
        mkdirp.sync(path.dirname(nodeFilePath));
        next();
      },

      /**
       * download node into the target directory
       */

      function downloadNode(next) {
        if (fs.existsSync(nodeFilePath)) return next();

        var uri = framework;

        if (framework === 'node') {
          uri = 'nodejs'; // if node, use nodejs uri
        } else if (framework === 'nodejs') {
          framework = 'node'; // support nodejs, and node, as framework.
        }

        var type = global.type;
        var url,
          prefix = 'https://' + uri + '.org/dist';

        if (version === 'latest') {
          url = prefix + '/' + framework + '-' + version + '.tar.gz';
        } else {
          url =
            prefix +
            '/v' +
            version +
            '/' +
            framework +
            '-v' +
            version +
            '.tar.gz';
        }

        _log('downloading %s', url);

        var output = fs.createWriteStream(nodeFilePath, {
          flags: 'w+',
        });

        // need to set user-agent to bypass some corporate firewalls
        var requestOptions = {
          url: url,
          headers: {
            'User-Agent': 'Node.js',
          },
        };

        _logProgress(request(requestOptions)).pipe(output);

        output.on('close', function() {
          next();
        });
      },

      /**
       * unzip in the same directory
       */

      function unzipNodeTarball(next) {
        var onError = function(err) {
          console.log(err.stack);
          _log('error', 'failed to extract the node source');
          process.exit(1);
        };

        if (isWin) {
          _log('extracting the node source [node-tar.gz]');

          // tar-stream method w/ gunzip-maybe
          var read = fs.createReadStream(nodeFilePath);
          var extract = tarstream.extract();
          var basedir = nodeFileDir;

          if (!fs.existsSync(nodeFileDir)) {
            fs.mkdirSync(nodeFileDir);
          }

          extract.on('entry', function(header, stream, callback) {
            // header is the tar header
            // stream is the content body (might be an empty stream)
            // call next when you are done with this entry

            var absolutepath = path.join(basedir, header.name);
            if (header.type === 'directory') {
              // handle directories.
              // console.log('dir:', header.name);
              fs.mkdirSync(absolutepath);
              return callback();
            } else if (header.type === 'file') {
              // handle files
              // console.log('file:', header.name);
            } else {
              console.log(header.type + ':', header.name);
              _log('warn', 'unhandled type in tar extraction, skipping');
              return callback();
            }

            var write = fs.createWriteStream(absolutepath);

            stream.pipe(write);

            write.on('close', function() {
              return callback();
            });

            stream.on('error', function(err) {
              return onError(err);
            });

            write.on('error', function(err) {
              return onError(err);
            });

            stream.resume(); // just auto drain the stream
          });

          extract.on('finish', function() {
            _log('extraction finished');
            return next();
          });

          read.pipe(gunzip()).pipe(extract);
        } else {
          _log('extracting the node source [native tar]');

          var cmd = ['tar', '-xf', nodeFilePath, '-C', nodeFileDir];
          _log(cmd.join(' '));

          var tar = spawn(cmd.shift(), cmd);
          tar.stdout.pipe(process.stdout);
          tar.stderr.pipe(process.stderr);

          tar.on('close', function() {
            return next();
          });
          tar.on('error', onError);
        }
      },

      /**
       * return the compiler object for the node version
       */

      function(next, type) {
        _getNodeCompiler(
          nodeFileDir,
          nodeConfigureArgs,
          nodeMakeArgs,
          nodeVCBuildArgs,
          next,
          type,
        );
      },
    ],
    complete,
  );
}
64532
private ScriptClassLoader loadClassByLoader() throws Exception 
	{
		ScriptClassLoader newClassLoader = new ScriptClassLoader();
		Set<Class<?>> allClass = newClassLoader.findedClass;
		Set<Class<?>> fileClass=new HashSet<>();
		for(DirClassFile dcf:scriptSource.getDirClassFiles())
		{
			File file=new File(dcf.getRootDir().getFile());
			if(!file.exists())
			{
				continue;
			}
			newClassLoader.addURL(dcf.getRootDir());
			for(String className:dcf.getClassNames())
			{
				Class<?> clazz=newClassLoader.loadClass(className);
				if(clazz!=null)
				{
					fileClass.add(clazz);
				}
			}
		}
		Set<Class<?>> urlClass=new HashSet<>();
		for(URLClassFile ucf:scriptSource.getUrlClassFiles())
		{
			newClassLoader.addURL(ucf.getURL());
			Class<?> clazz=newClassLoader.loadClass(ucf.getClassName());
			if(clazz!=null)
			{
				urlClass.add(clazz);
			}
		}
		Set<Class<?>> jarClass=new HashSet<>();
		for(URL jar:scriptSource.getJars())
		{
			JarFile jarFile=null;
			try {
				File file=new File(jar.getFile());
				if(!file.exists())
				{
					continue;
				}
				jarFile=new JarFile(jar.getFile());
				Map<String, JarEntry>  map=FileUtil.findClassByJar(jarFile);
				if(!map.isEmpty())
				{
					newClassLoader.addURL(jar);
					for(String className:map.keySet())
					{
						Class<?> clazz=newClassLoader.loadClass(className);
						if(clazz!=null)
						{
							jarClass.add(clazz);
						}
					}
				}
			} finally {
				if(jarFile!=null)
				{
					jarFile.close();
				}
			}
		}
		allClass.addAll(fileClass);
		allClass.addAll(urlClass);
		allClass.addAll(jarClass);
		_log.debug("classloader init complete,allClass:"+allClass.size()+",fileClass:" + fileClass.size() + ",urlClass:" + urlClass.size() + ",jarClass:" + jarClass.size());
		return newClassLoader;
	}
1213703
@Override
    public ResponseEntity<InputStream> downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId,
            @PathVariable("artifactId") final Long artifactId) {

        final SoftwareModule module = softwareModuleManagement.get(softwareModuleId)
                .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
        final Artifact artifact = module.getArtifact(artifactId)
                .orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId));

        final AbstractDbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash())
                .orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash()));
        final HttpServletRequest request = requestResponseContextHolder.getHttpServletRequest();
        final String ifMatch = request.getHeader(HttpHeaders.IF_MATCH);
        if (ifMatch != null && !HttpUtil.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) {
            return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED);
        }

        return FileStreamingUtil.writeFileResponse(file, artifact.getFilename(), artifact.getCreatedAt(),
                requestResponseContextHolder.getHttpServletResponse(), request, null);
    }
1295530
static URLSpec getReleaseDownloadUrl(String path, MavenSettings settings) throws IOException {
		String url = settings.mCentralUrl;
		if (settings.mMirrorUrl != null) url = settings.mMirrorUrl;
		return new URLSpec(url + path, settings.mProxyHost, settings.mProxyPort);
	}
703283
function downloadBootstrapAssets(version, path) {
  console.log(chalk.blue((`Downloading Bootstrap assets to ${path}`)))
  version = semver.clean(version)
  const url = 'https://maxcdn.bootstrapcdn.com/bootstrap'
  var proms = [
    'fonts/glyphicons-halflings-regular.eot',
    'fonts/glyphicons-halflings-regular.woff',
    'fonts/glyphicons-halflings-regular.woff2',
    'fonts/glyphicons-halflings-regular.ttf',
    'fonts/glyphicons-halflings-regular.svg'
  ].map(f => {
    return download(`${url}/${version}/${f}`, `${path}/fonts`)
      .catch(e => {
        console.log(chalk.red(`Downloading ${version}/${f} failed.`))
        return Promise.resolve()
      })
  })

  proms = proms.concat([
      'js/bootstrap.js',
      'js/bootstrap.min.js'
    ].map(f => {
      return download(`${url}/${version}/${f}`, `${path}/js`)
        .catch(e => {
          console.log(chalk.red(`Downloading ${version}/${f} failed.`))
          return Promise.resolve()
        })
    })
  )
  return Promise.all(proms)
}
1330170
private void processClasspath(String classpathElement) throws ResourceNotFoundException, ParseErrorException, Exception {
//        getLog().info("Classpath is " + classpathElement);
        if (classpathElement.endsWith(".jar")) {
            // TODO: implement JAR scanning
        } else {
            final File dir = new File(classpathElement);

            processPackage(dir, dir);
        }
    }
199967
public static void populateModuleSpecWithResources(ModuleSpec.Builder moduleSpecBuilder, ScriptArchive scriptArchive) throws ModuleLoadException {
        Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder");
        Objects.requireNonNull(scriptArchive, "scriptArchive");

        MultiplePathFilterBuilder pathFilterBuilder = PathFilters.multiplePathFilterBuilder(true);
        Set<String> archiveEntryNames = scriptArchive.getArchiveEntryNames();
        pathFilterBuilder.addFilter(PathFilters.in(archiveEntryNames), true);

        // add the root resources and classes to the module. If the root is a directory, all files under the tree
        // are added to the module. If it's a jar, then all files in the jar are added.
        URL url = scriptArchive.getRootUrl();
        if (url != null) {
            try {
                File file = Paths.get(url.toURI()).toFile();
                String filePath = file.getPath();
                ResourceLoader rootResourceLoader = null;
                if (file.isDirectory()) {
                    rootResourceLoader = ResourceLoaders.createFileResourceLoader(filePath, file);
                } else if (file.getPath().endsWith(".jar")) {
                    try {
                        rootResourceLoader = ResourceLoaders.createJarResourceLoader(filePath, new JarFile(file));
                    } catch (IOException e) {
                        throw new ModuleLoadException(e);
                    }
                }
                if (rootResourceLoader != null) {
                    moduleSpecBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(rootResourceLoader, pathFilterBuilder.create()));
                }
            } catch (URISyntaxException e) {
                throw new ModuleLoadException("Unsupported URL syntax: " + url, e);
            }
        }
        // add dependencies to the module spec
        ScriptModuleSpec scriptModuleSpec = scriptArchive.getModuleSpec();

        // add string based properties from module spec metadata to the module spec being created
        Map<String, Object> archiveMetadata = scriptModuleSpec.getMetadata();
        Map<String, String> stringMetadata = new HashMap<String, String>();
        for (Entry<String, Object> entry: archiveMetadata.entrySet()) {
            if (entry.getValue() instanceof String) {
                stringMetadata.put(entry.getKey(), (String)entry.getValue());
            }
        }
        addPropertiesToSpec(moduleSpecBuilder, stringMetadata);

        // override the default ModuleClassLoader to use our customer classloader
        moduleSpecBuilder.setModuleClassLoaderFactory(JBossModuleClassLoader.createFactory(scriptArchive));
    }
301350
def _jython_set_classpath(jars):
    '''
    
    '''
    from java.net import URL, URLClassLoader
    from java.lang import ClassLoader
    from java.io import File
    m = URLClassLoader.getDeclaredMethod("addURL", [URL])
    m.accessible = 1
    urls = [File(i).toURL() for i in jars]
    m.invoke(ClassLoader.getSystemClassLoader(), urls)
816374
public List<Dependency> getModuleAncestors(final String moduleName, final String moduleVersion) throws GrapesCommunicationException {
        final Client client = getClient();
        final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactAncestors(moduleName, moduleVersion));
        final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_TEST_PARAM, "true")
                .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

        client.destroy();
        if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
            final String message = String.format(FAILED_TO_GET_MODULE, "get module ancestors", moduleName, moduleVersion);
            if(LOG.isErrorEnabled()) {
                LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
            }
            throw new GrapesCommunicationException(message, response.getStatus());
        }

        return response.getEntity(new GenericType<List<Dependency>>(){});
    }
1284914
private void handleDownloadProject(final HttpServletRequest req,
      final HttpServletResponse resp, final Session session) throws ServletException,
      IOException {

    final User user = session.getUser();
    final String projectName = getParam(req, "project");
    logger.info(user.getUserId() + " is downloading project: " + projectName);

    final Project project = this.projectManager.getProject(projectName);
    if (project == null) {
      this.setErrorMessageInCookie(resp, "Project " + projectName
          + " doesn't exist.");
      resp.sendRedirect(req.getContextPath());
      return;
    }

    if (!hasPermission(project, user, Type.READ)) {
      this.setErrorMessageInCookie(resp, "No permission to download project " + projectName
          + ".");
      resp.sendRedirect(req.getContextPath());
      return;
    }

    int version = -1;
    if (hasParam(req, "version")) {
      version = getIntParam(req, "version");
    }

    ProjectFileHandler projectFileHandler = null;
    FileInputStream inStream = null;
    OutputStream outStream = null;
    try {
      projectFileHandler =
          this.projectManager.getProjectFileHandler(project, version);
      if (projectFileHandler == null) {
        this.setErrorMessageInCookie(resp, "Project " + projectName
            + " with version " + version + " doesn't exist");
        resp.sendRedirect(req.getContextPath());
        return;
      }
      final File projectZipFile = projectFileHandler.getLocalFile();
      final String logStr =
          String.format(
              "downloading project zip file for project \"%s\" at \"%s\""
                  + " size: %d type: %s  fileName: \"%s\"",
              projectFileHandler.getFileName(),
              projectZipFile.getAbsolutePath(), projectZipFile.length(),
              projectFileHandler.getFileType(),
              projectFileHandler.getFileName());
      logger.info(logStr);

      // now set up HTTP response for downloading file
      inStream = new FileInputStream(projectZipFile);

      resp.setContentType(APPLICATION_ZIP_MIME_TYPE);

      final String headerKey = "Content-Disposition";
      final String headerValue =
          String.format("attachment; filename=\"%s\"",
              projectFileHandler.getFileName());
      resp.setHeader(headerKey, headerValue);
      resp.setHeader("version",
          Integer.toString(projectFileHandler.getVersion()));
      resp.setHeader("projectId",
          Integer.toString(projectFileHandler.getProjectId()));

      outStream = resp.getOutputStream();

      final byte[] buffer = new byte[this.downloadBufferSize];
      int bytesRead = -1;

      while ((bytesRead = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
      }

    } catch (final Throwable e) {
      logger.error(
          "Encountered error while downloading project zip file for project: "
              + projectName + " by user: " + user.getUserId(), e);
      throw new ServletException(e);
    } finally {
      IOUtils.closeQuietly(inStream);
      IOUtils.closeQuietly(outStream);

      if (projectFileHandler != null) {
        projectFileHandler.deleteLocalFile();
      }
    }

  }
182491
public static File jarFile(Class<?> clazz) throws IOException {
        return jarFile(classFileUrl(clazz), clazz.getName().replace('.', '/') + ".class");
    }
1184428
File doDownload(String remoteRepos, String artifactAbsoluteHttpPath, String artifactRelativeHttpPath, ArtifactCoordinates artifactCoordinates, String packaging, File targetArtifactPomDirectory, File targetArtifactDirectory) {
        //Download POM
        File targetArtifactPomFile = new File(targetArtifactPomDirectory, toGradleArtifactFileName(artifactCoordinates, "pom"));
        try {
            MavenArtifactUtil.downloadFile(artifactCoordinates + ":pom", artifactAbsoluteHttpPath + "pom", targetArtifactPomFile);
        } catch (IOException e) {
            Module.getModuleLogger().trace(e, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
            // try next one
        }

        //Download Artifact
        File targetArtifactFile = new File(targetArtifactDirectory, toGradleArtifactFileName(artifactCoordinates, packaging));
        try {
            MavenArtifactUtil.downloadFile(artifactCoordinates + ":" + packaging, artifactAbsoluteHttpPath + packaging, targetArtifactFile);
            if (targetArtifactFile.exists()) {
                return targetArtifactFile;
            }
        } catch (IOException e) {
            Module.getModuleLogger().trace(e, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
            // try next one
        }
        return null;
    }
710486
private void setClassPath() throws IOException {
    String fullPath = file.getAbsolutePath();
    String rootPath = fullPath.substring(0, fullPath.lastIndexOf(classFile.getRelativePath()));
    List<File> classPath = new ArrayList<>();
    classPath.add(new File(rootPath));
    parserEnv.fileManager().setLocation(StandardLocation.CLASS_PATH, classPath);
  }
400408
@SuppressWarnings("unchecked")
    private void apply(File root, Iterable<? extends File> classPath) throws IOException {
        if (!root.isDirectory()) {
            throw new GradleException("Not a directory: " + root);
        }
        ClassLoaderResolver classLoaderResolver = new ClassLoaderResolver();
        try {
            List<Plugin.Factory> factories = new ArrayList<Plugin.Factory>(byteBuddyExtension.getTransformations().size());
            for (Transformation transformation : byteBuddyExtension.getTransformations()) {
                String plugin = transformation.getPlugin();
                try {
                    factories.add(new Plugin.Factory.UsingReflection((Class<? extends Plugin>) Class.forName(plugin,
                            false,
                            classLoaderResolver.resolve(transformation.getClassPath(root, classPath))))
                            .with(transformation.makeArgumentResolvers())
                            .with(Plugin.Factory.UsingReflection.ArgumentResolver.ForType.of(File.class, root),
                                    Plugin.Factory.UsingReflection.ArgumentResolver.ForType.of(Logger.class, project.getLogger()),
                                    Plugin.Factory.UsingReflection.ArgumentResolver.ForType.of(BuildLogger.class, new GradleBuildLogger(project.getLogger()))));
                    project.getLogger().info("Resolved plugin: {}", transformation.getRawPlugin());
                } catch (Throwable throwable) {
                    throw new GradleException("Cannot resolve plugin: " + transformation.getRawPlugin(), throwable);
                }
            }
            EntryPoint entryPoint = byteBuddyExtension.getInitialization().getEntryPoint(classLoaderResolver, root, classPath);
            project.getLogger().info("Resolved entry point: {}", entryPoint);
            List<ClassFileLocator> classFileLocators = new ArrayList<ClassFileLocator>();
            for (File artifact : classPath) {
                classFileLocators.add(artifact.isFile()
                        ? ClassFileLocator.ForJarFile.of(artifact)
                        : new ClassFileLocator.ForFolder(artifact));
            }
            ClassFileLocator classFileLocator = new ClassFileLocator.Compound(classFileLocators);
            Plugin.Engine.Summary summary;
            try {
                project.getLogger().info("Processing class files located in in: {}", root);
                Plugin.Engine pluginEngine;
                try {
                    ClassFileVersion classFileVersion;
                    JavaPluginConvention convention = (JavaPluginConvention) project.getConvention().getPlugins().get("java");
                    if (convention == null) {
                        classFileVersion = ClassFileVersion.ofThisVm();
                        project.getLogger().warn("Could not locate Java target version, build is JDK dependant: {}", classFileVersion.getMajorVersion());
                    } else {
                        classFileVersion = ClassFileVersion.ofJavaVersion(Integer.parseInt(convention.getTargetCompatibility().getMajorVersion()));
                        project.getLogger().debug("Java version detected: {}", convention.getTargetCompatibility().getMajorVersion());
                    }
                    pluginEngine = Plugin.Engine.Default.of(entryPoint, classFileVersion, byteBuddyExtension.getMethodNameTransformer());
                } catch (Throwable throwable) {
                    throw new GradleException("Cannot create plugin engine", throwable);
                }
                try {
                    summary = pluginEngine
                            .with(byteBuddyExtension.isExtendedParsing()
                                    ? Plugin.Engine.PoolStrategy.Default.EXTENDED
                                    : Plugin.Engine.PoolStrategy.Default.FAST)
                            .with(classFileLocator)
                            .with(new TransformationLogger(project.getLogger()))
                            .withErrorHandlers(Plugin.Engine.ErrorHandler.Enforcing.ALL_TYPES_RESOLVED, byteBuddyExtension.isFailOnLiveInitializer()
                                    ? Plugin.Engine.ErrorHandler.Enforcing.NO_LIVE_INITIALIZERS
                                    : Plugin.Engine.Listener.NoOp.INSTANCE, byteBuddyExtension.isFailFast()
                                    ? Plugin.Engine.ErrorHandler.Failing.FAIL_FAST
                                    : Plugin.Engine.Listener.NoOp.INSTANCE)
                            .apply(new Plugin.Engine.Source.ForFolder(root), new Plugin.Engine.Target.ForFolder(root), factories);
                } catch (Throwable throwable) {
                    throw new GradleException("Failed to transform class files in " + root, throwable);
                }
            } finally {
                classFileLocator.close();
            }
            if (!summary.getFailed().isEmpty()) {
                throw new GradleException(summary.getFailed() + " type transformations have failed");
            } else if (summary.getTransformed().isEmpty()) {
                project.getLogger().warn("No types were transformed during plugin execution");
            } else {
                project.getLogger().info("Transformed {} types", summary.getTransformed().size());
            }
        } finally {
            classLoaderResolver.close();
        }
    }
1330448
private JnlpResource locateResource( DownloadRequest dreq )
            throws IOException, ErrorResponseException
    {
        if ( dreq.getVersion() == null )
        {
            return handleBasicDownload( dreq );
        }
        else
        {
            return handleVersionRequest( dreq );
        }
    }