use of com.mashape.unirest.http.exceptions.UnirestException in project goci by EBISPOT.
the class EnsemblRestService method getRestCall.
/**
* Simple generic Ensembl REST API call method.
*
* @param endpoint_type the endpoint name
* @param data the data/id/symbol we want to query
* @param rest_parameters rest parameters
* @return the corresponding result
*/
public RestResponseResult getRestCall(String endpoint_type, String data, String rest_parameters) throws EnsemblRestIOException {
String endpoint = getEndpoints().get(endpoint_type);
URL url = null;
RestResponseResult restResponseResult = new RestResponseResult();
try {
rateLimit();
// Build URL
if (!Objects.equals(rest_parameters, "")) {
Matcher matcher = Pattern.compile("^\\?").matcher(rest_parameters);
if (!matcher.matches()) {
rest_parameters = '?' + rest_parameters;
}
}
url = new URL(getServer() + endpoint + data + rest_parameters);
restResponseResult = fetchJson(url.toString());
} catch (InterruptedException | MalformedURLException | UnirestException e) {
getLog().error("Encountered a " + e.getClass().getSimpleName() + " whilst trying to run mapping of SNP", e);
throw new EnsemblRestIOException("Encountered a " + e.getClass().getSimpleName() + " whilst trying to run mapping of SNP", e);
}
return restResponseResult;
}
use of com.mashape.unirest.http.exceptions.UnirestException 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;
}
use of com.mashape.unirest.http.exceptions.UnirestException in project jabref by JabRef.
the class SpringerLink method findFullText.
@Override
public Optional<URL> findFullText(BibEntry entry) throws IOException {
Objects.requireNonNull(entry);
Optional<URL> pdfLink = Optional.empty();
// Try unique DOI first
Optional<DOI> doi = entry.getField(FieldName.DOI).flatMap(DOI::parse);
if (doi.isPresent()) {
// Available in catalog?
try {
HttpResponse<JsonNode> jsonResponse = Unirest.get(API_URL).queryString("api_key", API_KEY).queryString("q", String.format("doi:%s", doi.get().getDOI())).asJson();
JSONObject json = jsonResponse.getBody().getObject();
int results = json.getJSONArray("result").getJSONObject(0).getInt("total");
if (results > 0) {
LOGGER.info("Fulltext PDF found @ Springer.");
pdfLink = Optional.of(new URL("http", CONTENT_HOST, String.format("/content/pdf/%s.pdf", doi.get().getDOI())));
}
} catch (UnirestException e) {
LOGGER.warn("SpringerLink API request failed", e);
}
}
return pdfLink;
}
use of com.mashape.unirest.http.exceptions.UnirestException in project Ardent by adamint.
the class UD method noArgs.
@Override
public void noArgs(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
Shard shard = GuildUtils.getShard(guild);
if (args.length == 1) {
sendTranslatedMessage("Search a word's definition from Urban Dictionary. Example: {0}ud test".replace("{0}", GuildUtils.getPrefix(guild)), channel, user);
} else {
GetRequest getRequest = Unirest.get("http://api.urbandictionary.com/v0/define?term=" + message.getRawContent().replace(GuildUtils.getPrefix(guild) + args[0] + " ", "").replaceAll(" ", "%20"));
String json = "";
try {
json = getRequest.asJson().getBody().toString();
} catch (UnirestException e) {
e.printStackTrace();
}
UrbanDictionary definition = shard.gson.fromJson(json, UrbanDictionary.class);
if (definition.getList().size() == 0) {
sendTranslatedMessage("There aren't any definitions for this word!", channel, user);
} else {
EmbedBuilder builder = MessageUtils.getDefaultEmbed(message.getAuthor());
UDList list = definition.getList().get(0);
String def = "Definition";
String author = "Author";
String example = "Example";
String link = "Link";
String thumbsUp = "Thumbs Up";
String thumbsDown = "Thumbs Down";
String urbanDictionary = "Urban Dictionary";
builder.setAuthor(urbanDictionary, shard.bot.getAvatarUrl(), shard.bot.getAvatarUrl());
builder.setThumbnail("https://i.gyazo.com/6a40e32928743e68e9006396ee7c2a14.jpg");
builder.setColor(Color.decode("#00B7BE"));
String definitionText = list.getDefinition();
String exampleText = list.getExample();
if (definitionText.length() > 1024)
definitionText = definitionText.substring(0, 1023);
if (exampleText.length() > 1024)
exampleText = exampleText.substring(0, 1023);
builder.addField(def, definitionText, true);
builder.addField(example, exampleText, true);
builder.addField(thumbsUp, String.valueOf(list.getThumbsUp() + ":thumbsup:"), true);
builder.addField(thumbsDown, String.valueOf(list.getThumbsDown() + ":thumbsdown:"), true);
builder.addField(author, list.getAuthor(), true);
builder.addField(link, list.getPermalink(), true);
sendEmbed(builder, channel, user);
}
}
}
use of com.mashape.unirest.http.exceptions.UnirestException in project Ardent by adamint.
the class EightBall method noArgs.
@Override
public void noArgs(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
if (args.length == 1) {
sendTranslatedMessage("Type something so the 8ball has something to respond to!", channel, user);
} else {
String query = message.getRawContent().replace(GuildUtils.getPrefix(guild) + args[0] + " ", "");
try {
String json = Unirest.get("https://8ball.delegator.com/magic/JSON/" + URLEncoder.encode(query)).asString().getBody();
EightBallResponse eightBallResponse = GuildUtils.getShard(guild).gson.fromJson(json, EightBallResponse.class);
sendTranslatedMessage(eightBallResponse.getMagic().getAnswer(), channel, user);
} catch (UnirestException e) {
sendTranslatedMessage("I can't answer that question!", channel, user);
e.printStackTrace();
}
}
}
Aggregations