Search in sources :

Example 1 with UnirestException

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;
}
Also used : Plugin(org.bukkit.plugin.Plugin) HttpResponse(kong.unirest.HttpResponse) Files(java.nio.file.Files) URL(java.net.URL) IOException(java.io.IOException) GetRequest(kong.unirest.GetRequest) Unirest(kong.unirest.Unirest) File(java.io.File) CommonPatterns(io.github.bakedlibs.dough.common.CommonPatterns) InvocationTargetException(java.lang.reflect.InvocationTargetException) StandardCopyOption(java.nio.file.StandardCopyOption) Level(java.util.logging.Level) URLClassLoader(java.net.URLClassLoader) JsonNode(kong.unirest.JsonNode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Slimefun(io.github.thebusybiscuit.slimefun4.implementation.Slimefun) UnirestException(kong.unirest.UnirestException) Method(java.lang.reflect.Method) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GetRequest(kong.unirest.GetRequest) UnirestException(kong.unirest.UnirestException) IOException(java.io.IOException) File(java.io.File)

Example 2 with UnirestException

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;
    }
}
Also used : UnirestException(kong.unirest.UnirestException) JsonNode(kong.unirest.JsonNode)

Example 3 with UnirestException

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();
    }
}
Also used : UnirestException(kong.unirest.UnirestException) JsonNode(kong.unirest.JsonNode) File(java.io.File)

Example 4 with UnirestException

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;
}
Also used : UnirestInstance(kong.unirest.UnirestInstance) JSONObject(kong.unirest.json.JSONObject) JSONArray(kong.unirest.json.JSONArray) UnirestException(kong.unirest.UnirestException) JsonNode(kong.unirest.JsonNode)

Example 5 with UnirestException

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;
}
Also used : UnirestInstance(kong.unirest.UnirestInstance) UnirestException(kong.unirest.UnirestException) JsonNode(kong.unirest.JsonNode)

Aggregations

UnirestException (kong.unirest.UnirestException)152 IOException (java.io.IOException)86 MollieException (be.woutschoovaerts.mollie.exception.MollieException)75 JSONObject (kong.unirest.json.JSONObject)29 Pagination (be.woutschoovaerts.mollie.data.common.Pagination)24 JsonNode (kong.unirest.JsonNode)18 SeleniumRobotServerException (com.seleniumtests.customexception.SeleniumRobotServerException)14 ConnectorsTest (com.seleniumtests.ConnectorsTest)13 ScenarioException (com.seleniumtests.customexception.ScenarioException)13 HttpRequest (kong.unirest.HttpRequest)13 UnirestInstance (kong.unirest.UnirestInstance)13 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)13 Test (org.testng.annotations.Test)13 File (java.io.File)11 ArrayList (java.util.ArrayList)11 JSONException (kong.unirest.json.JSONException)11 List (java.util.List)9 ConfigurationException (com.seleniumtests.customexception.ConfigurationException)8 JSONArray (kong.unirest.json.JSONArray)6 MyteamServerErrorException (ru.mail.jira.plugins.myteam.exceptions.MyteamServerErrorException)6