Search in sources :

Example 26 with JsonNode

use of com.mashape.unirest.http.JsonNode in project dataverse by IQSS.

the class DataCaptureModuleUtil method getScriptFromRequest.

/**
 * transfer script from DCM
 */
public static ScriptRequestResponse getScriptFromRequest(HttpResponse<JsonNode> uploadRequest) {
    int status = uploadRequest.getStatus();
    JsonNode body = uploadRequest.getBody();
    logger.fine("Got " + status + " with body: " + body);
    if (status == 404) {
        return new ScriptRequestResponse(status);
    }
    int httpStatusCode = uploadRequest.getStatus();
    String script = body.getObject().getString("script");
    String datasetIdentifier = body.getObject().getString("datasetIdentifier");
    long userId = body.getObject().getLong("userId");
    ScriptRequestResponse scriptRequestResponse = new ScriptRequestResponse(httpStatusCode, datasetIdentifier, userId, script);
    return scriptRequestResponse;
}
Also used : JsonNode(com.mashape.unirest.http.JsonNode)

Example 27 with JsonNode

use of com.mashape.unirest.http.JsonNode in project DisCal-Discord-Bot by NovaFox161.

the class UpdateDisPwData method updateSiteBotMeta.

private static void updateSiteBotMeta() {
    try {
        Integer serverCount = Main.client.getGuilds().size();
        JSONObject json = new JSONObject().put("server_count", serverCount);
        // noinspection unused
        HttpResponse<JsonNode> response = Unirest.post("https://bots.discord.pw/api/bots/265523588918935552/stats").header("Authorization", BotSettings.PW_TOKEN.get()).header("Content-Type", "application/json").body(json).asJson();
    } catch (Exception e) {
        // Handle issue.
        System.out.println("Failed to update Discord PW list metadata!");
        Logger.getLogger().exception(null, "Failed to update Discord PW list.", e, UpdateDisPwData.class, true);
        e.printStackTrace();
    }
}
Also used : JSONObject(org.json.JSONObject) JsonNode(com.mashape.unirest.http.JsonNode)

Example 28 with JsonNode

use of com.mashape.unirest.http.JsonNode in project DisCal-Discord-Bot by NovaFox161.

the class Authorization method pollForAuth.

void pollForAuth(Poll poll) {
    GuildSettings settings = DatabaseManager.getManager().getSettings(poll.getGuild().getLongID());
    try {
        String body = "client_id=" + clientData.getClientId() + "&client_secret=" + clientData.getClientSecret() + "&code=" + poll.getDevice_code() + "&grant_type=http://oauth.net/grant_type/device/1.0";
        // Execute
        com.mashape.unirest.http.HttpResponse<JsonNode> response = Unirest.post("https://www.googleapis.com/oauth2/v4/token").header("Content-Type", "application/x-www-form-urlencoded").body(body).asJson();
        // Handle response.
        if (response.getStatus() == 403) {
            // Handle access denied
            Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Poll.Failure.Deny", settings), poll.getUser());
        } else if (response.getStatus() == 400) {
            try {
                // See if auth is pending, if so, just reschedule.
                Type type = new TypeToken<AuthPollResponseError>() {
                }.getType();
                AuthPollResponseError apre = new Gson().fromJson(response.getBody().toString(), type);
                if (apre.error.equalsIgnoreCase("authorization_pending")) {
                    // Response pending
                    PollManager.getManager().scheduleNextPoll(poll);
                } else if (apre.error.equalsIgnoreCase("expired_token")) {
                    Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Poll.Failure.Expired", settings), poll.getUser());
                } else {
                    Message.sendDirectMessage(MessageManager.getMessage("Notification.Error.Network", settings), poll.getUser());
                    Logger.getLogger().debug(poll.getUser(), "Poll Failure!", "Status code: " + response.getStatus() + " | " + response.getStatusText() + " | " + response.getBody().toString(), this.getClass(), true);
                }
            } catch (Exception e) {
                // Auth is not pending, error occurred.
                Logger.getLogger().exception(poll.getUser(), "Failed to poll for authorization to google account.", e, this.getClass(), true);
                Logger.getLogger().debug(poll.getUser(), "More info on failure", "Status code: " + response.getStatus() + " | " + response.getStatusText() + " | " + response.getBody().toString(), this.getClass(), true);
                Message.sendDirectMessage(MessageManager.getMessage("Notification.Error.Network", settings), poll.getUser());
            }
        } else if (response.getStatus() == 429) {
            // We got rate limited... oops. Let's just poll half as often.
            poll.setInterval(poll.getInterval() * 2);
            PollManager.getManager().scheduleNextPoll(poll);
        } else if (response.getStatus() == HttpStatusCodes.STATUS_CODE_OK) {
            // Access granted
            Type type = new TypeToken<AuthPollResponseGrant>() {
            }.getType();
            AuthPollResponseGrant aprg = new Gson().fromJson(response.getBody().toString(), type);
            // Save credentials securely.
            GuildSettings gs = DatabaseManager.getManager().getSettings(poll.getGuild().getLongID());
            AESEncryption encryption = new AESEncryption(gs);
            gs.setEncryptedAccessToken(encryption.encrypt(aprg.access_token));
            gs.setEncryptedRefreshToken(encryption.encrypt(aprg.refresh_token));
            DatabaseManager.getManager().updateSettings(gs);
            try {
                Calendar service = CalendarAuth.getCalendarService(gs);
                List<CalendarListEntry> items = service.calendarList().list().setMinAccessRole("writer").execute().getItems();
                Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Poll.Success", settings), poll.getUser());
                for (CalendarListEntry i : items) {
                    if (!i.isDeleted()) {
                        EmbedBuilder em = new EmbedBuilder();
                        em.withAuthorIcon(Main.client.getGuildByID(266063520112574464L).getIconURL());
                        em.withAuthorName("DisCal");
                        em.withTitle(MessageManager.getMessage("Embed.AddCalendar.List.Title", settings));
                        em.appendField(MessageManager.getMessage("Embed.AddCalendar.List.Name", settings), i.getSummary(), false);
                        em.appendField(MessageManager.getMessage("Embed.AddCalendar.List.TimeZone", settings), i.getTimeZone(), false);
                        em.appendField(MessageManager.getMessage("Embed.AddCalendar.List.ID", settings), i.getId(), false);
                        em.withUrl(CalendarMessageFormatter.getCalendarLink(i.getId()));
                        em.withColor(56, 138, 237);
                        Message.sendDirectMessage(em.build(), poll.getUser());
                    }
                }
            // Response will be handled in guild, and will check. We already saved the tokens anyway.
            } catch (IOException e1) {
                // Failed to get calendars list and check for calendars.
                Logger.getLogger().exception(poll.getUser(), "Failed to list calendars from external account!", e1, this.getClass(), true);
                Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Poll.Failure.ListCalendars", settings), poll.getUser());
            }
        } else {
            // Unknown network error...
            Message.sendDirectMessage(MessageManager.getMessage("Notification.Error.Network", settings), poll.getUser());
            Logger.getLogger().debug(poll.getUser(), "Network error; poll failure", "Status code: " + response.getStatus() + " | " + response.getStatusText() + " | " + response.getBody().toString(), this.getClass(), true);
        }
    } catch (Exception e) {
        // Handle exception.
        Logger.getLogger().exception(poll.getUser(), "Failed to poll for authorization to google account", e, this.getClass(), true);
        Message.sendDirectMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), poll.getUser());
    }
}
Also used : AESEncryption(com.cloudcraftgaming.discal.api.crypto.AESEncryption) Calendar(com.google.api.services.calendar.Calendar) Gson(com.google.gson.Gson) JsonNode(com.mashape.unirest.http.JsonNode) IOException(java.io.IOException) AuthPollResponseGrant(com.cloudcraftgaming.discal.api.object.json.google.AuthPollResponseGrant) IOException(java.io.IOException) Type(java.lang.reflect.Type) CalendarListEntry(com.google.api.services.calendar.model.CalendarListEntry) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) TypeToken(com.google.gson.reflect.TypeToken) List(java.util.List) AuthPollResponseError(com.cloudcraftgaming.discal.api.object.json.google.AuthPollResponseError) GuildSettings(com.cloudcraftgaming.discal.api.object.GuildSettings)

Example 29 with JsonNode

use of com.mashape.unirest.http.JsonNode in project DisCal-Discord-Bot by NovaFox161.

the class Authorization method requestNewAccessToken.

public String requestNewAccessToken(GuildSettings settings, AESEncryption encryption) {
    try {
        String body = "client_id=" + clientData.getClientId() + "&client_secret=" + clientData.getClientSecret() + "&refresh_token=" + encryption.decrypt(settings.getEncryptedRefreshToken()) + "&grant_type=refresh_token";
        com.mashape.unirest.http.HttpResponse<JsonNode> httpResponse = Unirest.post("https://www.googleapis.com/oauth2/v4/token").header("Content-Type", "application/x-www-form-urlencoded").body(body).asJson();
        if (httpResponse.getStatus() == HttpStatusCodes.STATUS_CODE_OK) {
            Type type = new TypeToken<AuthRefreshResponse>() {
            }.getType();
            AuthRefreshResponse response = new Gson().fromJson(httpResponse.getBody().toString(), type);
            // Update Db data.
            settings.setEncryptedAccessToken(encryption.encrypt(response.access_token));
            DatabaseManager.getManager().updateSettings(settings);
            // Okay, we can return the access token to be used when this method is called.
            return response.access_token;
        } else {
            // Failed to get OK. Send debug info.
            Logger.getLogger().debug(null, "Error requesting new access token.", "Status code: " + httpResponse.getStatus() + " | " + httpResponse.getStatusText() + " | " + httpResponse.getBody().toString(), this.getClass(), true);
            return null;
        }
    } catch (Exception e) {
        // Error occurred, lets just log it and return null.
        Logger.getLogger().exception(null, "Failed to request new access token.", e, this.getClass(), true);
        return null;
    }
}
Also used : Type(java.lang.reflect.Type) Gson(com.google.gson.Gson) JsonNode(com.mashape.unirest.http.JsonNode) AuthRefreshResponse(com.cloudcraftgaming.discal.api.object.json.google.AuthRefreshResponse) IOException(java.io.IOException)

Example 30 with JsonNode

use of com.mashape.unirest.http.JsonNode in project yorc-a4c-plugin by ystia.

the class RestClient method getDeployments.

/**
 * Get the list of deployments known by Yorc
 * @return List of deployments
 */
public List<String> getDeployments() throws UnirestException {
    List<String> ret = new ArrayList<>();
    String fullUrl = providerConfiguration.getUrlYorc() + "/deployments";
    log.debug("getDeployments " + fullUrl);
    HttpResponse<JsonNode> res = Unirest.get(fullUrl).header("accept", "application/json").asJson();
    if (res == null) {
        log.debug("Cannot reach Yorc: null response");
        return null;
    }
    if (res.getBody() != null) {
        JSONObject obj = res.getBody().getObject();
        JSONArray array = obj.getJSONArray("deployments");
        for (int i = 0; i < array.length(); i++) {
            String depl = array.getJSONObject(i).getString("href");
            log.debug("Found a deployment in Yorc: " + depl);
            ret.add(depl);
        }
    }
    return ret;
}
Also used : JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JsonNode(com.mashape.unirest.http.JsonNode)

Aggregations

JsonNode (com.mashape.unirest.http.JsonNode)47 UnirestException (com.mashape.unirest.http.exceptions.UnirestException)20 JSONObject (org.json.JSONObject)19 IOException (java.io.IOException)14 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)12 JSONArray (org.json.JSONArray)11 RestResponseResult (uk.ac.ebi.spot.goci.model.RestResponseResult)5 Incident (io.github.asw.i3a.operatorsWebClient.entitites.Incident)4 List (java.util.List)4 ActionException (org.apache.zeppelin.elasticsearch.action.ActionException)4 ActionResponse (org.apache.zeppelin.elasticsearch.action.ActionResponse)4 HitWrapper (org.apache.zeppelin.elasticsearch.action.HitWrapper)4 JSONException (org.json.JSONException)4 Gson (com.google.gson.Gson)3 Type (java.lang.reflect.Type)3 JsonObjectBuilder (javax.json.JsonObjectBuilder)3 Test (org.junit.Test)3 RestTemplate (org.springframework.web.client.RestTemplate)3 HttpResponse (com.mashape.unirest.http.HttpResponse)2 HttpRequest (com.mashape.unirest.request.HttpRequest)2