Search in sources :

Example 1 with JsonNode

use of com.mashape.unirest.http.JsonNode in project blueocean-plugin by jenkinsci.

the class SSEClientRule method connect.

public void connect() throws UnirestException, InterruptedException {
    SecureRandom rnd = new SecureRandom();
    String clientId = "ath-" + rnd.nextLong();
    HttpResponse<JsonNode> httpResponse = Unirest.get(baseUrl + "/sse-gateway/connect?clientId=" + clientId).basicAuth(admin.username, admin.password).asJson();
    JsonNode body = httpResponse.getBody();
    Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
    WebTarget target = client.target(baseUrl + "/sse-gateway/listen/" + clientId + ";jsessionid=" + body.getObject().getJSONObject("data").getString("jsessionid"));
    source = EventSource.target(target).build();
    source.register(listener);
    source.open();
    JSONObject req = new JSONObject().put("dispatcherId", clientId).put("subscribe", new JSONArray(ImmutableList.of(new JSONObject().put("jenkins_org", "jenkins").put("jenkins_channel", "job")))).put("unsubscribe", new JSONArray());
    Unirest.post(baseUrl + "/sse-gateway/configure?batchId=1").basicAuth(admin.username, admin.password).body(req).asJson();
    logger.info("SSE Connected " + clientId);
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) SecureRandom(java.security.SecureRandom) JsonNode(com.mashape.unirest.http.JsonNode) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) SseFeature(org.glassfish.jersey.media.sse.SseFeature)

Example 2 with JsonNode

use of com.mashape.unirest.http.JsonNode in project jabref by JabRef.

the class DOAJFetcher method processQuery.

@Override
public boolean processQuery(String query, ImportInspector inspector, OutputPrinter status) {
    shouldContinue = true;
    try {
        status.setStatus(Localization.lang("Searching..."));
        HttpResponse<JsonNode> jsonResponse;
        jsonResponse = Unirest.get(SEARCH_URL + query + "?pageSize=1").header("accept", "application/json").asJson();
        JSONObject jo = jsonResponse.getBody().getObject();
        int numberToFetch = jo.getInt("total");
        if (numberToFetch > 0) {
            if (numberToFetch > MAX_PER_PAGE) {
                boolean numberEntered = false;
                do {
                    String strCount = JOptionPane.showInputDialog(Localization.lang("%0 references found. Number of references to fetch?", String.valueOf(numberToFetch)));
                    if (strCount == null) {
                        status.setStatus(Localization.lang("%0 import canceled", getTitle()));
                        return false;
                    }
                    try {
                        numberToFetch = Integer.parseInt(strCount.trim());
                        numberEntered = true;
                    } catch (NumberFormatException ex) {
                        status.showMessage(Localization.lang("Please enter a valid number"));
                    }
                } while (!numberEntered);
            }
            // Keep track of number of items fetched for the progress bar
            int fetched = 0;
            for (int page = 1; ((page - 1) * MAX_PER_PAGE) <= numberToFetch; page++) {
                if (!shouldContinue) {
                    break;
                }
                int noToFetch = Math.min(MAX_PER_PAGE, numberToFetch - ((page - 1) * MAX_PER_PAGE));
                jsonResponse = Unirest.get(SEARCH_URL + query + "?page=" + page + "&pageSize=" + noToFetch).header("accept", "application/json").asJson();
                jo = jsonResponse.getBody().getObject();
                if (jo.has("results")) {
                    JSONArray results = jo.getJSONArray("results");
                    for (int i = 0; i < results.length(); i++) {
                        JSONObject bibJsonEntry = results.getJSONObject(i).getJSONObject("bibjson");
                        BibEntry entry = jsonConverter.parseBibJSONtoBibtex(bibJsonEntry, Globals.prefs.getKeywordDelimiter());
                        inspector.addEntry(entry);
                        fetched++;
                        inspector.setProgress(fetched, numberToFetch);
                    }
                }
            }
            return true;
        } else {
            status.showMessage(Localization.lang("No entries found for the search string '%0'", query), Localization.lang("Search %0", getTitle()), JOptionPane.INFORMATION_MESSAGE);
            return false;
        }
    } catch (UnirestException e) {
        LOGGER.error("Error while fetching from " + getTitle(), e);
        ((ImportInspectionDialog) inspector).showErrorMessage(this.getTitle(), e.getLocalizedMessage());
        return false;
    }
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) JsonNode(com.mashape.unirest.http.JsonNode)

Example 3 with JsonNode

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

the class DiscordLoginHandler method handleDiscordCode.

public static String handleDiscordCode(Request request, Response response) {
    try {
        String code = request.queryParams("code");
        // POST request to discord for access...
        HttpResponse<JsonNode> httpResponse = Unirest.post("https://discordapp.com/api/v6/oauth2/token").header("Content-Type", "application/x-www-form-urlencoded").field("client_id", BotSettings.ID.get()).field("client_secret", BotSettings.SECRET.get()).field("grant_type", "authorization_code").field("code", code).field("redirect_uri", BotSettings.REDIR_URL.get()).asJson();
        JSONObject info = new JSONObject(httpResponse.getBody()).getJSONObject("object");
        // GET request for user info...
        HttpResponse<JsonNode> userDataResponse = Unirest.get("https://discordapp.com/api/v6/users/@me").header("Authorization", "Bearer " + info.getString("access_token")).asJson();
        JSONObject userInfo = new JSONObject(userDataResponse.getBody()).getJSONObject("object");
        // Saving session info and access info to memory until moved into the database...
        Map m = new HashMap();
        m.put("loggedIn", true);
        m.put("client", BotSettings.ID.get());
        m.put("year", LocalDate.now().getYear());
        m.put("redirUri", BotSettings.REDIR_URI.get());
        m.put("id", userInfo.getString("id"));
        m.put("username", userInfo.getString("username"));
        m.put("discrim", userInfo.getString("discriminator"));
        // Get guilds...
        m.put("guilds", GuildUtils.getGuilds(userInfo.getString("id")));
        m.put("goodTz", GoodTimezone.values());
        m.put("anTypes", AnnouncementType.values());
        m.put("eventColors", EventColor.values());
        DiscordAccountHandler.getHandler().addAccount(m, request.session().id());
        // Finally redirect to the dashboard seamlessly.
        response.redirect("/dashboard", 301);
    } catch (JSONException e) {
        Logger.getLogger().exception(null, "[WEB] JSON || Discord login failed!", e, DiscordLoginHandler.class, true);
        response.redirect("/dashboard", 301);
    } catch (Exception e) {
        Logger.getLogger().exception(null, "[WEB] Discord login failed!", e, DiscordLoginHandler.class, true);
        halt(500, "Internal Server Exception");
    }
    return response.body();
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) JSONException(org.json.JSONException) JsonNode(com.mashape.unirest.http.JsonNode) HashMap(java.util.HashMap) Map(java.util.Map) JSONException(org.json.JSONException)

Example 4 with JsonNode

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

the class Authorization method requestCode.

public void requestCode(MessageReceivedEvent event, GuildSettings settings) {
    try {
        String body = "client_id=" + clientData.getClientId() + "&scope=" + CalendarScopes.CALENDAR;
        com.mashape.unirest.http.HttpResponse<JsonNode> response = Unirest.post("https://accounts.google.com/o/oauth2/device/code").header("Content-Type", "application/x-www-form-urlencoded").body(body).asJson();
        if (response.getStatus() == HttpStatusCodes.STATUS_CODE_OK) {
            Type type = new TypeToken<CodeResponse>() {
            }.getType();
            CodeResponse cr = new Gson().fromJson(response.getBody().toString(), type);
            // Send DM to user with code.
            EmbedBuilder em = new EmbedBuilder();
            em.withAuthorIcon(Main.client.getGuildByID(266063520112574464L).getIconURL());
            em.withAuthorName("DisCal");
            em.withTitle(MessageManager.getMessage("Embed.AddCalendar.Code.Title", settings));
            em.appendField(MessageManager.getMessage("Embed.AddCalendar.Code.Code", settings), cr.user_code, true);
            em.withFooterText(MessageManager.getMessage("Embed.AddCalendar.Code.Footer", settings));
            em.withUrl(cr.verification_url);
            em.withColor(36, 153, 153);
            IUser user = event.getAuthor();
            Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Code.Request.Success", settings), em.build(), user);
            // Start timer to poll Google Cal for auth
            Poll poll = new Poll(user, event.getGuild());
            poll.setDevice_code(cr.device_code);
            poll.setRemainingSeconds(cr.expires_in);
            poll.setExpires_in(cr.expires_in);
            poll.setInterval(cr.interval);
            pollForAuth(poll);
        } else {
            Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Code.Request.Failure.NotOkay", settings), event.getAuthor());
            Logger.getLogger().debug(event.getAuthor(), "Error requesting access token.", "Status code: " + response.getStatus() + " | " + response.getStatusText() + " | " + response.getBody().toString(), this.getClass(), true);
        }
    } catch (Exception e) {
        // Failed, report issue to dev.
        Logger.getLogger().exception(event.getAuthor(), "Failed to request Google Access Code", e, this.getClass(), true);
        IUser u = event.getAuthor();
        Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Code.Request.Failure.Unknown", settings), u);
    }
}
Also used : CodeResponse(com.cloudcraftgaming.discal.api.object.json.google.CodeResponse) Gson(com.google.gson.Gson) JsonNode(com.mashape.unirest.http.JsonNode) IOException(java.io.IOException) Type(java.lang.reflect.Type) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) IUser(sx.blah.discord.handle.obj.IUser) Poll(com.cloudcraftgaming.discal.api.object.network.google.Poll)

Example 5 with JsonNode

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

the class DataCaptureModuleServiceBeanIT method startFileSystemImportJob.

private static JsonObject startFileSystemImportJob(HttpResponse<JsonNode> uploadRequest) {
    JsonObjectBuilder jab = Json.createObjectBuilder();
    jab.add("status", uploadRequest.getStatus());
    int status = uploadRequest.getStatus();
    JsonNode body = uploadRequest.getBody();
    logger.info("Got " + status + " with body: " + body);
    if (status != 200) {
        jab.add("message", body.getObject().getString("message"));
        return jab.build();
    }
    jab.add("executionId", body.getObject().getJSONObject("data").getLong("executionId"));
    jab.add("message", body.getObject().getJSONObject("data").getString("message"));
    return jab.build();
}
Also used : JsonNode(com.mashape.unirest.http.JsonNode) JsonObjectBuilder(javax.json.JsonObjectBuilder)

Aggregations

JsonNode (com.mashape.unirest.http.JsonNode)38 JSONObject (org.json.JSONObject)20 UnirestException (com.mashape.unirest.http.exceptions.UnirestException)13 JSONArray (org.json.JSONArray)11 IOException (java.io.IOException)8 RestResponseResult (uk.ac.ebi.spot.goci.model.RestResponseResult)5 ActionException (org.apache.zeppelin.elasticsearch.action.ActionException)4 ActionResponse (org.apache.zeppelin.elasticsearch.action.ActionResponse)4 HitWrapper (org.apache.zeppelin.elasticsearch.action.HitWrapper)4 PluginConfigurationException (alien4cloud.paas.exception.PluginConfigurationException)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Gson (com.google.gson.Gson)3 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 InputStream (java.io.InputStream)3 Type (java.lang.reflect.Type)3 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3