Search in sources :

Example 21 with JsonNode

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

the class ScienceDirect method getUrlByDoi.

private String getUrlByDoi(String doi) throws UnirestException {
    String sciLink = "";
    try {
        String request = API_URL + doi;
        HttpResponse<JsonNode> jsonResponse = Unirest.get(request).header("X-ELS-APIKey", API_KEY).queryString("httpAccept", "application/json").asJson();
        JSONObject json = jsonResponse.getBody().getObject();
        JSONArray links = json.getJSONObject("full-text-retrieval-response").getJSONObject("coredata").getJSONArray("link");
        for (int i = 0; i < links.length(); i++) {
            JSONObject link = links.getJSONObject(i);
            if (link.getString("@rel").equals("scidir")) {
                sciLink = link.getString("@href");
            }
        }
        return sciLink;
    } catch (JSONException e) {
        LOGGER.debug("No ScienceDirect link found in API request", e);
        return sciLink;
    }
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JsonNode(com.mashape.unirest.http.JsonNode)

Example 22 with JsonNode

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

the class SpringerFetcher method processQuery.

@Override
public boolean processQuery(String query, ImportInspector inspector, OutputPrinter status) {
    shouldContinue = true;
    try {
        status.setStatus(Localization.lang("Searching..."));
        HttpResponse<JsonNode> jsonResponse;
        String encodedQuery = URLEncoder.encode(query, "UTF-8");
        jsonResponse = Unirest.get(API_URL + encodedQuery + "&api_key=" + API_KEY + "&p=1").header("accept", "application/json").asJson();
        JSONObject jo = jsonResponse.getBody().getObject();
        int numberToFetch = jo.getJSONArray("result").getJSONObject(0).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 startItem = 1; startItem <= numberToFetch; startItem += MAX_PER_PAGE) {
                if (!shouldContinue) {
                    break;
                }
                int noToFetch = Math.min(MAX_PER_PAGE, (numberToFetch - startItem) + 1);
                jsonResponse = Unirest.get(API_URL + encodedQuery + "&api_key=" + API_KEY + "&p=" + noToFetch + "&s=" + startItem).header("accept", "application/json").asJson();
                jo = jsonResponse.getBody().getObject();
                if (jo.has("records")) {
                    JSONArray results = jo.getJSONArray("records");
                    for (int i = 0; i < results.length(); i++) {
                        JSONObject springerJsonEntry = results.getJSONObject(i);
                        BibEntry entry = JSONEntryParser.parseSpringerJSONtoBibtex(springerJsonEntry);
                        inspector.addEntry(entry);
                        fetched++;
                        inspector.setProgress(fetched, numberToFetch);
                    }
                }
            }
            return true;
        } else {
            status.showMessage(Localization.lang("No entries found for the search string '%0'", encodedQuery), Localization.lang("Search %0", getTitle()), JOptionPane.INFORMATION_MESSAGE);
            return false;
        }
    } catch (IOException | 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) IOException(java.io.IOException)

Example 23 with JsonNode

use of com.mashape.unirest.http.JsonNode in project Javacord by BtoBastian.

the class ImplServer method createChannelBlocking.

/**
 * Creates a new channel.
 *
 * @param name The name of the channel.
 * @param voice Whether the channel should be voice or text.
 * @return The created channel.
 * @throws Exception If something went wrong.
 */
private Object createChannelBlocking(String name, boolean voice) throws Exception {
    logger.debug("Trying to create channel in server {} (name: {}, voice: {})", ImplServer.this, name, voice);
    JSONObject param = new JSONObject().put("name", name).put("type", voice ? "voice" : "text");
    HttpResponse<JsonNode> response = Unirest.post("https://discordapp.com/api/v6/guilds/" + id + "/channels").header("authorization", api.getToken()).header("Content-Type", "application/json").body(param.toString()).asJson();
    api.checkResponse(response);
    api.checkRateLimit(response, RateLimitType.UNKNOWN, ImplServer.this, null);
    if (voice) {
        return new ImplVoiceChannel(response.getBody().getObject(), this, api);
    } else {
        return new ImplChannel(response.getBody().getObject(), this, api);
    }
}
Also used : JSONObject(org.json.JSONObject) JsonNode(com.mashape.unirest.http.JsonNode)

Example 24 with JsonNode

use of com.mashape.unirest.http.JsonNode in project Javacord by BtoBastian.

the class ImplMessageHistory method request.

/**
 * Requests messages.
 *
 * @param api The used api.
 * @param channelId The id of the channel.
 * @param messageId Gets the messages before or after the message with the given id.
 * @param before Whether it should get the messages before or after the given message.
 * @param limit The maximum number of messages.
 * @return The amount of requested messages.
 * @throws Exception if something went wrong.
 */
private int request(ImplDiscordAPI api, String channelId, String messageId, boolean before, int limit) throws Exception {
    if (limit <= 0) {
        return 0;
    }
    logger.debug("Requesting part of message history (channel id: {}, message id: {}, before: {}, limit: {}", channelId, messageId == null ? "none" : messageId, before, limit);
    String link = messageId == null ? "https://discordapp.com/api/v6/channels/" + channelId + "/messages?&limit=" + limit : "https://discordapp.com/api/v6/channels/" + channelId + "/messages?&" + (before ? "before" : "after") + "=" + messageId + "&limit=" + limit;
    HttpResponse<JsonNode> response = Unirest.get(link).header("authorization", api.getToken()).asJson();
    api.checkResponse(response);
    api.checkRateLimit(response, RateLimitType.UNKNOWN, null, null);
    JSONArray messages = response.getBody().getArray();
    for (int i = 0; i < messages.length(); i++) {
        JSONObject messageJson = messages.getJSONObject(i);
        String id = messageJson.getString("id");
        Message message = api.getMessageById(id);
        if (message == null) {
            message = new ImplMessage(messageJson, api, null);
        }
        if (newestMessage == null || message.compareTo(newestMessage) > 0) {
            newestMessage = message;
        }
        if (oldestMessage == null || message.compareTo(oldestMessage) < 0) {
            oldestMessage = message;
        }
        this.messages.put(id, message);
    }
    return messages.length();
}
Also used : JSONObject(org.json.JSONObject) Message(de.btobastian.javacord.entities.message.Message) JSONArray(org.json.JSONArray) JsonNode(com.mashape.unirest.http.JsonNode)

Example 25 with JsonNode

use of com.mashape.unirest.http.JsonNode in project Javacord by BtoBastian.

the class ImplDiscordAPI method requestTokenBlocking.

/**
 * Requests a new token.
 *
 * @return The requested token.
 */
public String requestTokenBlocking() {
    try {
        logger.debug("Trying to request token (email: {}, password: {})", email, password.replaceAll(".", "*"));
        HttpResponse<JsonNode> response = Unirest.post("https://discordapp.com/api/v6/auth/login").header("User-Agent", Javacord.USER_AGENT).header("Content-Type", "application/json").body(new JSONObject().put("email", email).put("password", password).toString()).asJson();
        JSONObject jsonResponse = response.getBody().getObject();
        if (response.getStatus() == 400) {
            throw new IllegalArgumentException("400 Bad request! Maybe wrong email or password? StatusText: " + response.getStatusText() + "; Body: " + response.getBody());
        }
        if (response.getStatus() < 200 || response.getStatus() > 299) {
            throw new IllegalStateException("Received http status code " + response.getStatus() + " with message " + response.getStatusText() + " and body " + response.getBody());
        }
        if (jsonResponse.has("password") || jsonResponse.has("email")) {
            throw new IllegalArgumentException("Wrong email or password!");
        }
        String token = jsonResponse.getString("token");
        logger.debug("Requested token {} (email: {}, password: {})", token.replaceAll(".{10}", "**********"), email, password.replaceAll(".", "*"));
        return token;
    } catch (UnirestException e) {
        logger.warn("Couldn't request token (email: {}, password: {}). Please contact the developer!", email, password.replaceAll(".", "*"), e);
        return null;
    }
}
Also used : JSONObject(org.json.JSONObject) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) 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