Tries to download the plugin from the given remote maven repository.
352926
protected boolean downloadFromMavenRepo(File pluginFile, PluginCoordinates coordinates, URI mavenRepoUrl) {
        String artifactSubPath = PluginUtils.getMavenPath(coordinates);
        InputStream istream = null;
        OutputStream ostream = null;
        try {
            URL artifactUrl = new URL(mavenRepoUrl.toURL(), artifactSubPath);
            URLConnection connection = artifactUrl.openConnection();
            connection.connect();
            if (connection instanceof HttpURLConnection) {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                if (httpConnection.getResponseCode() != 200) {
                    throw new IOException();
                }
            }

            istream = connection.getInputStream();
            ostream = new FileOutputStream(pluginFile);
            IOUtils.copy(istream, ostream);
            ostream.flush();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            IOUtils.closeQuietly(istream);
            IOUtils.closeQuietly(ostream);
        }
    }
372049
public MavenProject getMavenProject(Artifact artifact) {
		try {
			final MavenSession session = getMavenSession();
			final MavenProject current = session.getCurrentProject();
			final MavenProject prj = getMavenProjectBuilder().buildFromRepository(
					artifact,
					current.getRemoteArtifactRepositories(),
					session.getLocalRepository());
			return prj;
		} catch (ProjectBuildingException e) {
			getLog().warn(e);
		}
		return null;
	}
145304
private Artifact getArtifactResult(Artifact desiredArtifact) throws MojoExecutionException {// NOSONAR
        ArtifactRequest artifactRequest = new ArtifactRequest();
        artifactRequest.setArtifact(desiredArtifact);
        artifactRequest.setRepositories(repositoryList);
        try {
            return repositorySystem.resolveArtifact(repositorySystemSession, artifactRequest).getArtifact();
        } catch (ArtifactResolutionException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
1001901
def download_jars_to(cls, folder):
        '''
        
        '''
        if not os.path.exists(folder):
            os.makedirs(folder)
        for info in JARS:
            jar = MavenJar(info[0], info[1], info[2])
            path = os.path.join(folder, jar.filename)

            if os.path.isfile(path):
                print("Skipping already downloaded file: %s" % jar.filename)
                continue

            print("Downloading %s..." % jar.filename)
            jar.download_to(folder)
1076747
public static Model loadPOM(String pomPath, String localRepo, Collection<RemoteRepository> repositories) throws ProjectException {
        RepositoryClient repoClient = new RepositoryClient(localRepo);
        NaetherModelResolver resolver = new NaetherModelResolver(repoClient, repositories);

        ModelBuildingRequest req = new DefaultModelBuildingRequest();
        req.setProcessPlugins( false );
        req.setPomFile( new File(pomPath) );
        req.setModelResolver( resolver );
        req.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );

        DefaultModelBuilder builder = (new DefaultModelBuilderFactory()).newInstance();
        try {
            return builder.build( req ).getEffectiveModel();
        } catch ( ModelBuildingException e ) {
            throw new ProjectException("Failed to build project from pom", e);
        }
    }
755996
def install_from_repo(pkgname, plugin_type, install_path, register_func):
    """"""
    rsession = requests.Session()
    rsession.mount("https://", HTTPAdapter(max_retries=3))

    logger.debug("trying to install %s from online repo", pkgname)
    pkgurl = "{}/{}s/{}.zip".format(defs.GITHUB_RAW, plugin_type, pkgname)
    try:
        logger.debug("Requesting HTTP HEAD: %s", pkgurl)
        r = rsession.head(pkgurl)
        r.raise_for_status()
        total_size = int(r.headers.get("content-length", 0))
        pkgsize = _sizeof_fmt(total_size)
        with click.progressbar(length=total_size, label="Downloading {} {} ({}).."
                               .format(plugin_type, pkgname, pkgsize)) as bar:
            r = rsession.get(pkgurl, stream=True)
            with tempfile.NamedTemporaryFile(delete=False) as f:
                downloaded_bytes = 0
                for chunk in r.iter_content(chunk_size=1):  # TODO: Consider increasing to reduce cycles
                    if chunk:
                        f.write(chunk)
                        downloaded_bytes += len(chunk)
                        bar.update(downloaded_bytes)
        return install_from_zip(f.name, install_path, register_func, delete_after_install=True)
    except requests.exceptions.HTTPError as exc:
        logger.debug(str(exc))
        raise exceptions.PluginNotFoundInOnlineRepo(pkgname)
    except requests.exceptions.ConnectionError as exc:
        logger.debug(str(exc))
        raise exceptions.PluginRepoConnectionError()
927734
static InstallException create(RepositoryException e, Throwable cause, RestRepositoryConnectionProxy proxy, boolean defaultRepo) {

        if (proxy != null && cause instanceof UnknownHostException)
            return create(Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("ERROR_TOOL_UNKNOWN_PROXY_HOST", proxy.getProxyURL().getHost()), e);
        else if (cause instanceof ConnectException && cause.getMessage() != null && cause.getMessage().contains("Connection refused") && proxy != null)
            return create(Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("ERROR_TOOL_INCORRECT_PROXY_PORT", String.valueOf(proxy.getProxyURL().getPort())),
                          e);
        else if (isCertPathBuilderException(cause))
            return create(Messages.INSTALL_KERNEL_MESSAGES.getLogMessage(defaultRepo ? "ERROR_FAILED_TO_CONNECT_CAUSED_BY_CERT" : "ERROR_FAILED_TO_CONNECT_REPOS_CAUSED_BY_CERT"),
                          e, InstallException.RUNTIME_EXCEPTION);
        else
            return create(Messages.INSTALL_KERNEL_MESSAGES.getLogMessage(defaultRepo ? "ERROR_FAILED_TO_CONNECT" : "ERROR_FAILED_TO_CONNECT_REPOS"),
                          e, InstallException.RUNTIME_EXCEPTION);
    }
1222420
def get_package(repo_url, pkg_name, timeout=1):
    """"""
    url = repo_url + "/packages/" + pkg_name
    headers = {'accept': 'application/json'}
    resp = requests.get(url, headers=headers, timeout=timeout)
    if resp.status_code == 404:
        return None
    return resp.json()
1325443
File downloadFromRemoteRepository(ArtifactCoordinates artifactCoordinates, String packaging, Path artifactDirectory) {
        String artifactRelativeHttpPath = toGradleArtifactPath(artifactCoordinates);
        String artifactRelativeMetadataHttpPath = artifactCoordinates.relativeMetadataPath('/');
        for (String remoteRepos : remoteRepositories) {
            String artifactAbsoluteHttpPath = remoteRepos + artifactRelativeHttpPath + ".";
            File targetArtifactPomDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":pom")).toFile();
            File targetArtifactDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + packaging)).toFile();

            File artifactFile = doDownload(remoteRepos, artifactAbsoluteHttpPath, artifactRelativeHttpPath, artifactCoordinates, packaging, targetArtifactPomDirectory, targetArtifactDirectory);
            if (artifactFile != null) {
                return artifactFile; // Success
            }

            //Try to doDownload the snapshot version
            if (artifactCoordinates.isSnapshot()) {
                String remoteMetadataPath = remoteRepos + artifactRelativeMetadataHttpPath;
                try {
                    String timestamp = MavenArtifactUtil.downloadTimestampVersion(artifactCoordinates + ":" + packaging, remoteMetadataPath);

                    String timestampedArtifactRelativePath = artifactCoordinates.relativeArtifactPath('/', timestamp);
                    String artifactTimestampedAbsoluteHttpPath = remoteRepos + timestampedArtifactRelativePath + ".";
                    File targetTimestampedArtifactPomDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + timestamp + ":pom")).toFile();
                    File targetTimestampedArtifactDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + packaging)).toFile();

                    File snapshotArtifactFile = doDownload(remoteRepos, artifactTimestampedAbsoluteHttpPath, timestampedArtifactRelativePath, artifactCoordinates, packaging, targetTimestampedArtifactPomDirectory, targetTimestampedArtifactDirectory);
                    if (snapshotArtifactFile != null) {
                        return snapshotArtifactFile; //Success
                    }
                } catch (XPathExpressionException | IOException ex) {
                    Module.getModuleLogger().trace(ex, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
                    // try next one
                }
            }
        }
        return null;
    }
972612
public static RepositoryPackage fromPackagist(String name) throws Exception {
		
		PackagistDownloader downloader = new PackagistDownloader();
		return downloader.loadPackage(name);
	}
513680
protected Path copyLocalFile(URL fileUrl) throws IOException, PluginException {
        Path destination = Files.createTempDirectory("pf4j-update-downloader");
        destination.toFile().deleteOnExit();

        try {
            Path fromFile = Paths.get(fileUrl.toURI());
            String path = fileUrl.getPath();
            String fileName = path.substring(path.lastIndexOf('/') + 1);
            Path toFile = destination.resolve(fileName);
            Files.copy(fromFile, toFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);

            return toFile;
        } catch (URISyntaxException e) {
            throw new PluginException("Something wrong with given URL", e);
        }
    }
246396
public void resolveDependencies(boolean downloadArtifacts, Map<String,String> properties) throws URLException, DependencyException {
        log.debug( "Resolving Dependencies" );
        
        log.debug("Local Repo Path: {}", localRepoPath);

        if ( log.isDebugEnabled() ) {
            log.debug("Remote Repositories:");
            for (RemoteRepository repo : getRemoteRepositories()) {
                log.debug("  {}", repo.toString());
            }
        }

        RepositoryClient repoClient = new RepositoryClient(this.getLocalRepoPath());
        if ( properties != null ) {
            repoClient.setProperties( properties );
        }
        
        // If there are local build artifacts, create a BuildWorkspaceReader to
        // override remote artifacts with the local build artifacts.
        if ( buildArtifacts.size() > 0 ) {
            repoClient.setBuildWorkspaceReader( buildArtifacts );
        }
        
        CollectRequest collectRequest = new CollectRequest();
        collectRequest.setDependencies( new ArrayList<Dependency>(getDependencies()));
        
        try {
            collectRequest.addRepository(RepoBuilder.remoteRepositoryFromUrl("file:" + this.getLocalRepoPath()));
        } catch (MalformedURLException e) {
            throw new URLException("Failed to add local repo to request", e);
        }

        for (RemoteRepository repo : getRemoteRepositories()) {
            collectRequest.addRepository(repo);
        }

        CollectResult collectResult;
        try {
            collectResult = repoClient.collectDependencies(collectRequest);
        } catch (DependencyCollectionException e) {
            throw new DependencyException(e);
        }

        preorderedNodeList = new PreorderNodeListGenerator();
        if (downloadArtifacts) {
            DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null);

            log.debug("Resolving dependencies to files");
            DependencyResult dependencyResult;
            try {
                dependencyResult = repoClient.resolveDependencies(dependencyRequest);
            } catch (DependencyResolutionException e) {
                throw new DependencyException(e);
            }
            dependencyResult.getRoot().accept(preorderedNodeList);

        } else {
            collectResult.getRoot().accept(preorderedNodeList);
        }

        //this.setDependencies( new HashSet<Dependency>(preorderedNodeList.getDependencies(true)));
        log.debug("Setting resolved dependencies: {}", this.getDependencies());
    }
843883
def download(cls, url, filename=None):
        
        return utility.download(url, cls.directory(), filename)
1094571
public static String findMavenUrlForRoboconf( String artifactId, String version )
	throws IOException {
		return findMavenUrl( "net.roboconf", artifactId, version, "jar" );
	}
716357
public PluginDescriptor loadPlugin(Plugin plugin)
			throws MojoExecutionException {
		try {
			final Object repositorySessionObject = this.getRepositorySessionMethod.invoke(this.session);
			return (PluginDescriptor) this.loadPluginMethod.invoke(
					this.buildPluginManager,
					plugin,
					getSession().getCurrentProject().getRemotePluginRepositories(),
					repositorySessionObject);
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			throw new MojoExecutionException(e.getLocalizedMessage(), e);
		}
	}
106299
public int download() {
		try {
			//if (url.startsWith("https://packagist.org") || url.startsWith("https://getcomposer.org")) {
			if (url.startsWith("https://")) {
				registerSSLContext(client.getBackend());
			}
			
			final HttpGet httpGet = new HttpGet(url);
			
			
			if (httpGet.isAborted()) {
				httpGet.abort();
			}
			
			client.execute(httpGet, new FutureCallback<HttpResponse>() {
				
				@Override
				public void failed(Exception e) {
					for (DownloadListenerInterface listener : listeners) {
						listener.errorOccured(e);
					}
				}

				@Override
				public void completed(HttpResponse response) {
					for (DownloadListenerInterface listener : listeners) {
						try {
							listener.dataReceived(response.getEntity().getContent(), httpGet.getURI().toString());
						} catch (Exception e) {
							listener.errorOccured(e);
						}
					}
				}

				@Override
				public void cancelled() {
					for (DownloadListenerInterface listener : listeners) {
						listener.aborted(httpGet.getURI().toString());
					}
				}
			});
			
			httpGets.add(httpGet);
//			client.shutdown();
			
			lastSlot = httpGets.size() - 1;
						
			return lastSlot;
			
		} catch (Exception e) {
			for (DownloadListenerInterface listener : listeners) {
				listener.errorOccured(e);
			}
		}
		
		return -1;
	}
36486
function downloadRepo(config, tmpFolder, callback) {

  console.log('Downloading repo...'.magenta);

  // Keep track if the request fails to prevent the continuation of the install
  var requestFailed = false;

  var repoUrl = 'http://server.webhook.com/';

  if(config.server) {
    if(config.server.indexOf('http://') !== 0) {
      config.server = config.server += 'http://';
    }

    if(config.server.indexOf(config.server.length - 1) !== '/') {
      config.server += '/';
    }

    repoUrl = config.server;
  }

  var repoRequest = request(repoUrl + 'download/?site=' + config.siteName + '&token=' + config.siteToken);

  repoRequest
    .on('response', function (response) {
      // If we fail, set it as failing and remove zip file
      if (response.statusCode !== 200) {
        requestFailed = true;
        fs.unlinkSync('repo.zip');
        callback(true);
      }
    })
    .pipe(fs.createWriteStream('repo.zip'))
    .on('close', function () {
      if (requestFailed) return;

      console.log('Extracting Files...'.magenta);
      // Unzip into temporary file
      var zip = new Zip('repo.zip');
      zip.extractAllTo(tmpFolder);
      fs.unlinkSync('repo.zip');
      callback(null, tmpFolder + '/' + fs.readdirSync(tmpFolder)[0]);
    });
}