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);
}
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;
}
}
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();
}
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);
}
}
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();
}
Aggregations