use of kong.unirest.UnirestException in project Slimefun4 by Slimefun.
the class MetricsService method download.
/**
* Downloads the version specified to Slimefun's data folder.
*
* @param version
* The version to download.
*/
private boolean download(int version) {
File file = new File(parentFolder, "Metrics-" + version + ".jar");
try {
plugin.getLogger().log(Level.INFO, "# Starting download of MetricsModule build: #{0}", version);
if (file.exists()) {
// Delete the file in case we accidentally downloaded it before
Files.delete(file.toPath());
}
AtomicInteger lastPercentPosted = new AtomicInteger();
GetRequest request = Unirest.get(DOWNLOAD_URL + "/" + version + "/" + JAR_NAME + ".jar");
HttpResponse<File> response = request.downloadMonitor((b, fileName, bytesWritten, totalBytes) -> {
int percent = (int) (20 * (Math.round((((double) bytesWritten / totalBytes) * 100) / 20)));
if (percent != 0 && percent != lastPercentPosted.get()) {
plugin.getLogger().info("# Downloading... " + percent + "% " + "(" + bytesWritten + "/" + totalBytes + " bytes)");
lastPercentPosted.set(percent);
}
}).asFile(file.getPath());
if (response.isSuccess()) {
plugin.getLogger().log(Level.INFO, "Successfully downloaded {0} build: #{1}", new Object[] { JAR_NAME, version });
// Replace the metric file with the new one
cleanUp();
Files.move(file.toPath(), metricsModuleFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
metricVersion = String.valueOf(version);
hasDownloadedUpdate = true;
return true;
}
} catch (UnirestException e) {
plugin.getLogger().log(Level.WARNING, "Failed to fetch the latest jar file from the builds page. Perhaps GitHub is down? Response: {0}", e.getMessage());
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Failed to replace the old metric file with the new one. Please do this manually! Error: {0}", e.getMessage());
}
return false;
}
use of kong.unirest.UnirestException in project Slimefun4 by Slimefun.
the class MetricsService method getLatestVersion.
/**
* Gets the latest version available as an int.
* This is an internal method used by {@link #checkForUpdate(String)}.
* If it cannot get the version for whatever reason this will return 0, effectively always
* being behind.
*
* @return The latest version as an integer or -1 if it failed to fetch.
*/
private int getLatestVersion() {
try {
HttpResponse<JsonNode> response = Unirest.get(RELEASES_URL).asJson();
if (!response.isSuccess()) {
return -1;
}
JsonNode node = response.getBody();
if (node == null) {
return -1;
}
return node.getObject().getInt("tag_name");
} catch (UnirestException e) {
plugin.getLogger().log(Level.WARNING, "Failed to fetch latest builds for Metrics: {0}", e.getMessage());
return -1;
}
}
use of kong.unirest.UnirestException in project Slimefun4 by Slimefun.
the class GitHubConnector method download.
/**
* This method will connect to GitHub and store the received data inside a local
* cache {@link File}.
* Make sure to call this method asynchronously!
*/
void download() {
file = new File("plugins/Slimefun/cache/github/" + getFileName() + ".json");
if (github.isLoggingEnabled()) {
Slimefun.logger().log(Level.INFO, "Retrieving {0}.json from GitHub...", getFileName());
}
try {
// @formatter:off
HttpResponse<JsonNode> response = Unirest.get(url).queryString(getParameters()).header("User-Agent", USER_AGENT).asJson();
if (response.isSuccess()) {
onSuccess(response.getBody());
writeCacheFile(response.getBody());
} else {
if (github.isLoggingEnabled()) {
Slimefun.logger().log(Level.WARNING, "Failed to fetch {0}: {1} - {2}", new Object[] { url, response.getStatus(), response.getBody() });
}
// It has the cached file, let's just read that then
if (file.exists()) {
JsonNode cache = readCacheFile();
if (cache != null) {
onSuccess(cache);
}
}
}
} catch (UnirestException e) {
if (github.isLoggingEnabled()) {
Slimefun.logger().log(Level.WARNING, "Could not connect to GitHub in time.", e);
}
// It has the cached file, let's just read that then
if (file.exists()) {
JsonNode cache = readCacheFile();
if (cache != null) {
onSuccess(cache);
return;
}
}
// If the request failed and it failed to read the cache then call onFailure.
onFailure();
}
}
use of kong.unirest.UnirestException in project dependency-track by DependencyTrack.
the class CargoMetaAnalyzer method analyze.
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {
final UnirestInstance ui = UnirestFactory.getUnirestInstance();
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
try {
final HttpResponse<JsonNode> response = ui.get(url).header("accept", "application/json").asJson();
if (response.getStatus() == 200) {
if (response.getBody() != null && response.getBody().getObject() != null) {
final JSONObject crate = response.getBody().getObject().optJSONObject("crate");
if (crate != null) {
final String latest = crate.getString("newest_version");
meta.setLatestVersion(latest);
}
final JSONArray versions = response.getBody().getObject().optJSONArray("versions");
if (versions != null) {
for (int i = 0; i < versions.length(); i++) {
final JSONObject version = versions.getJSONObject(i);
final String versionString = version.optString("num");
if (meta.getLatestVersion() != null && meta.getLatestVersion().equals(versionString)) {
final String publishedTimestamp = version.optString("created_at");
try {
meta.setPublishedTimestamp(DateUtil.fromISO8601(publishedTimestamp));
} catch (IllegalArgumentException e) {
LOGGER.warn("An error occurred while parsing published time", e);
}
}
}
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
}
} catch (UnirestException e) {
handleRequestException(LOGGER, e);
}
}
return meta;
}
use of kong.unirest.UnirestException in project dependency-track by DependencyTrack.
the class GemMetaAnalyzer method analyze.
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {
final UnirestInstance ui = UnirestFactory.getUnirestInstance();
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
try {
final HttpResponse<JsonNode> response = ui.get(url).header("accept", "application/json").asJson();
if (response.getStatus() == 200) {
if (response.getBody() != null && response.getBody().getObject() != null) {
final String latest = response.getBody().getObject().getString("version");
meta.setLatestVersion(latest);
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
}
} catch (UnirestException e) {
handleRequestException(LOGGER, e);
}
}
return meta;
}
Aggregations