示例#1
0
  @Override
  public Message sendFile(File file, Message message) {
    checkVerification();
    if (!checkPermission(getJDA().getSelfInfo(), Permission.MESSAGE_WRITE))
      throw new PermissionException(Permission.MESSAGE_WRITE);
    if (!checkPermission(getJDA().getSelfInfo(), Permission.MESSAGE_ATTACH_FILES))
      throw new PermissionException(Permission.MESSAGE_ATTACH_FILES);
    if (file == null || !file.exists() || !file.canRead())
      throw new IllegalArgumentException(
          "Provided file is either null, doesn't exist or is not readable!");
    if (file.length() > 8 << 20) // 8MB
    throw new IllegalArgumentException("File is to big! Max file-size is 8MB");

    JDAImpl api = (JDAImpl) getJDA();
    try {
      MultipartBody body =
          Unirest.post(Requester.DISCORD_API_PREFIX + "channels/" + getId() + "/messages")
              .header("authorization", getJDA().getAuthToken())
              .header("user-agent", Requester.USER_AGENT)
              .field("file", file);
      if (message != null)
        body.field("content", message.getRawContent()).field("tts", message.isTTS());

      String dbg =
          String.format(
              "Requesting %s -> %s\n\tPayload: file: %s, message: %s, tts: %s\n\tResponse: ",
              body.getHttpRequest().getHttpMethod().name(),
              body.getHttpRequest().getUrl(),
              file.getAbsolutePath(),
              message == null ? "null" : message.getRawContent(),
              message == null ? "N/A" : message.isTTS());
      HttpResponse<JsonNode> response = body.asJson();
      Requester.LOG.trace(dbg + body);

      try {
        int status = response.getStatus();

        if (status >= 200 && status < 300) {
          return new EntityBuilder(api).createMessage(response.getBody().getObject());
        } else if (response.getStatus() == 429) {
          long retryAfter = response.getBody().getObject().getLong("retry_after");
          api.setMessageTimeout(guild.getId(), retryAfter);
          throw new RateLimitedException(retryAfter);
        } else {
          throw new RuntimeException(
              "An unknown status code was returned when attempting to upload file. Status: "
                  + status
                  + " JSON: "
                  + response.getBody().toString());
        }

      } catch (JSONException e) {
        Requester.LOG.fatal("Following json caused an exception: " + response.getBody().toString());
        Requester.LOG.log(e);
      }
    } catch (UnirestException e) {
      Requester.LOG.log(e);
    }
    return null;
  }
  public void onCommandMessageReceived(CommandMessageReceivedEvent event) {
    if (event.getCommand().equals("get")) {

      event
          .getChat()
          .sendMessage(
              SendableChatAction.builder().chatAction(ChatAction.UPLOADING_PHOTO).build(),
              ImageBot.bot);

      HttpResponse<JsonNode> response = null;
      try {
        response = Unirest.get(url + event.getArgsString().replace(" ", "+")).asJson();
      } catch (UnirestException e) {
        e.printStackTrace();
      }

      if (response.getBody().getObject().has("error")) {
        event
            .getChat()
            .sendMessage(
                "The Google API returned an error - Bot probably got ratelimited!", ImageBot.bot);
        System.out.println("Google API returned error: " + response.getBody());
        return;
      }

      JSONArray array = response.getBody().getObject().getJSONArray("items");
      if (array.length() == 0) {
        event.getChat().sendMessage("No images found!", ImageBot.bot);
        return;
      }
      JSONObject image = array.getJSONObject(ThreadLocalRandom.current().nextInt(array.length()));
      URL url;
      try {
        url = new URL(image.getString("link"));
      } catch (MalformedURLException e) {
        e.printStackTrace();
        event.getChat().sendMessage("Something went wrong while getting the image!", ImageBot.bot);
        return;
      }
      System.out.println("Uploading photo: " + url);
      event
          .getChat()
          .sendMessage(
              SendablePhotoMessage.builder()
                  .photo(new InputFile(url))
                  .replyTo(event.getMessage())
                  .build(),
              ImageBot.bot);
      System.out.println("Photo uploaded: " + url);
    }
  }
  @SuppressWarnings("unchecked")
  public Map<ProjectVersionRef, String> translateVersions(List<ProjectVersionRef> projects) {
    // Execute request to get translated versions
    HttpResponse<Map> r;
    try {
      r =
          Unirest.post(this.endpointUrl)
              .header("accept", "application/json")
              .header("Content-Type", "application/json")
              .body(projects)
              .asObject(Map.class);
    } catch (UnirestException e) {
      throw new RestException(
          String.format(
              "Request to server '%s' failed. Exception message: %s",
              this.endpointUrl, e.getMessage()));
    }

    // Handle some corner cases (5xx, 4xx)
    if (r.getStatus() / 100 == 5) {
      throw new ServerException(
          String.format(
              "Server at '%s' failed to translate versions. HTTP status code %s.",
              this.endpointUrl, r.getStatus()));
    } else if (r.getStatus() / 100 == 4) {
      throw new ClientException(
          String.format(
              "Server at '%s' could not translate versions. HTTP status code %s.",
              this.endpointUrl, r.getStatus()));
    }

    return r.getBody();
  }
示例#4
0
文件: Gist.java 项目: Ribesg/Nexus
  public String create() {
    try {
      JsonObject gistJson = new JsonObject();
      gistJson.addProperty("description", this.getDescription());
      gistJson.addProperty("public", this.isPublic());

      JsonObject filesJson = new JsonObject();

      for (int i = 0; i < getFiles().length; i++) {
        GistFile gistFile = getFiles()[i];
        JsonObject file = new JsonObject();
        file.addProperty("content", gistFile.getContent());
        String name = gistFile.getFileName();
        filesJson.add(
            (name == null || name.isEmpty() ? "" : name + "-") + date.replace(' ', '_'), file);
      }

      gistJson.add("files", filesJson);

      HttpResponse<JsonNode> response =
          Unirest.post(GitHub.GISTS_API_URL)
              .header(
                  "authorization",
                  "token " + Nexus.getInstance().getGitHubConfig().getNexusGitHubApiKey())
              .header("accept", "application/json")
              .header("content-type", "application/json; charset=utf-8")
              .body(gistJson.toString())
              .asJson();
      return response.getBody().getObject().getString("html_url");
    } catch (UnirestException e) {
      throw new GistException("Failed to Gist!", e);
    }
  }
  @SuppressWarnings("unchecked")
  public String postJSON(String url, String jsonData, Map<String, String> headers)
      throws URISyntaxException, ParseException {
    HttpResponse<JsonNode> httpResponse = null;

    if (!validatorUtil.isHttpURLValid(url)) {
      throw new URISyntaxException(url, "The URL is not absolute");
    }

    if (!validatorUtil.isJSONValid(jsonData)) {
      throw new ParseException(ParseException.ERROR_UNEXPECTED_TOKEN);
    }

    try {
      httpResponse = Unirest.post(url).headers(headers).body(jsonData).asJson();
    } catch (UnirestException e) {

      LOGGER.error("Exception occured while making post call");
      JSONObject errorObject = new JSONObject();
      errorObject.put("status", "500");
      errorObject.put("message", e.getLocalizedMessage());
      return errorObject.toJSONString();
    }
    return httpResponse.getBody().toString();
  }
  private void changeMetadata(final String content, final Upload upload) {

    final Map<String, Object> params = new HashMap<>(METADATA_PARAMS_SIZE);

    params.putAll(getMetadataSocial(upload));
    params.putAll(getMetadataMonetization(content, upload));
    params.putAll(getMetadataMetadata(upload));
    params.putAll(getMetadataPermissions(upload));

    System.out.println(Joiner.on(MODIFIED_SEPERATOR).skipNulls().join(params.keySet()));
    params.put("modified_fields", Joiner.on(MODIFIED_SEPERATOR).skipNulls().join(params.keySet()));
    params.put("creator_share_feeds", "yes");
    final String token = extractor(content, "var session_token = \"", "\"");
    params.put("session_token", token);
    params.put("action_edit_video", "1");

    try {
      final HttpResponse<String> response =
          Unirest.post(
                  String.format(
                      "https://www.youtube.com/metadata_ajax?video_id=%s", upload.getVideoid()))
              .fields(params)
              .asString();

      LOGGER.info(response.getBody());
    } catch (final Exception e) {
      LOGGER.warn("Metadata not set", e);
    }
  }
  @Override
  public void activateBrowserfeatures(final Upload upload) throws UnirestException {

    // Create a local instance of cookie store
    // Populate cookies if needed
    final CookieStore cookieStore = new BasicCookieStore();
    for (final PersistentCookieStore.SerializableCookie serializableCookie :
        upload.getAccount().getSerializeableCookies()) {
      final BasicClientCookie cookie =
          new BasicClientCookie(
              serializableCookie.getCookie().getName(), serializableCookie.getCookie().getValue());
      cookie.setDomain(serializableCookie.getCookie().getDomain());
      cookieStore.addCookie(cookie);
    }

    final HttpClient client =
        HttpClientBuilder.create().useSystemProperties().setDefaultCookieStore(cookieStore).build();
    Unirest.setHttpClient(client);

    final HttpResponse<String> response =
        Unirest.get(String.format(VIDEO_EDIT_URL, upload.getVideoid())).asString();

    changeMetadata(response.getBody(), upload);

    final RequestConfig clientConfig =
        RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000).build();
    Unirest.setHttpClient(HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).build());
  }
示例#8
0
  // @Test(groups = "mainPage")
  public void _02_Test() throws InterruptedException, IOException, UnirestException {

    HttpResponse<JsonNode> jsonResponse =
        Unirest.post("https://my.15five.com/mobile/login")
            .header("HTTP_USER_AGENT", "15Five/APItest")
            .queryString("debug_api", "1")
            .field("password", "qwerty")
            .field("email", "*****@*****.**")
            .asJson();

    System.out.println("----------------------------");
    System.out.println(jsonResponse.getBody());
    System.out.println(jsonResponse.getStatus());
    System.out.println(jsonResponse.getBody().getObject().get("result"));
    System.out.println(jsonResponse.getBody().getObject().get("last_name"));
    System.out.println("----------------------------");

    Thread.sleep(1000);
  }
 // auth.test
 private JSONObject getUser(String token) throws UnirestException {
   HttpResponse<JsonNode> response2 =
       Unirest.post("https://slack.com/api/auth.test")
           .header("cache-control", "no-cache")
           .header("postman-token", "8fde8d56-5dba-fa69-6c1e-81c34bf24e78")
           .header("content-type", "application/x-www-form-urlencoded")
           .body("token=" + token)
           .asJson();
   JSONObject userdata = response2.getBody().getObject();
   return userdata;
 }
  private JSONObject getFreegeoip(HttpServletRequest request) {
    try {
      String dirIp = extractIP(request);

      HttpResponse<JsonNode> response = Unirest.get("http://freegeoip.net/json/" + dirIp).asJson();
      return response.getBody().getObject();

    } catch (UnirestException e) {
      e.printStackTrace();
      return null;
    }
  }
  @RequestMapping(value = "/rec/rec", method = RequestMethod.GET)
  public ResponseEntity<ArrayList<String>> recomendaciones(
      @RequestParam("url") String url,
      @RequestParam(value = "custom", required = false) String custom,
      @RequestParam(value = "expire", required = false) String expireDate,
      @RequestParam(value = "hasToken", required = false) String hasToken,
      HttpServletRequest request) {

    UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"});
    /*
     * Check if url comes through http or https
     */
    if (urlValidator.isValid(url)) {
      /*
       * Hash of URL or custom
       */
      String id;
      if (!custom.equals("")) {

        id = custom;

        if (shortURLRepository.findByHash(id) == null) {
          System.out.println("1");
          return new ResponseEntity<>(HttpStatus.CREATED);
        } else {
          System.out.println("2");
          try {
            HttpResponse<JsonNode> response =
                Unirest.get("https://wordsapiv1.p.mashape.com/words/" + id + "/synonyms")
                    .header("X-Mashape-Key", "VLzNEVr9zQmsh0gOlqs6wudMxDo1p1vCnjEjsnjNBhOCFeqLxr")
                    .header("Accept", "application/json")
                    .asJson();
            ObjectMapper map = new ObjectMapper();
            Synonym sin = map.readValue(response.getBody().toString(), Synonym.class);
            return new ResponseEntity<>(sin.getSynonyms(), HttpStatus.BAD_REQUEST);
          } catch (Exception e) {
            /*
             * Caso en el que la id seleccionada esta cogida y la
             * API no da alternativas
             */
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
          }
        }
      } else {
        return new ResponseEntity<>(HttpStatus.OK);
      }
    } else {
      System.out.println("3");
      return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
  }
 public static MktmpioInstance create(
     final String urlRoot,
     final String token,
     final String dbType,
     final boolean shutdownWithBuild)
     throws IOException, InterruptedException {
   final String url = urlRoot + "/api/v1/new/" + dbType;
   HttpResponse<JsonNode> json;
   try {
     json =
         Unirest.post(url)
             .header("accept", "application/json")
             .header("X-Auth-Token", token)
             .asJson();
   } catch (UnirestException ex) {
     System.err.println("Error creating instance:" + ex.getMessage());
     throw new IOException(ex.getMessage(), ex);
   }
   if (json.getStatus() >= 400) {
     String message = json.getBody().getObject().optString("error", json.getStatusText());
     System.err.println("Used token: " + token);
     System.err.println("error response: " + json.getStatusText());
     System.err.println("response body: " + json.getBody().toString());
     throw new IOException("Error creating " + dbType + " instance, " + message);
   }
   JSONObject res = json.getBody().getObject();
   String id = res.getString("id");
   String host = res.getString("host");
   int port = res.getInt("port");
   String username = res.optString("username", "");
   String password = res.optString("password", "");
   final MktmpioEnvironment env =
       new MktmpioEnvironment(
           token, id, host, port, username, password, dbType, shutdownWithBuild);
   return new MktmpioInstance(env);
 }
 public String hello(Request request, Response response) {
   String token = readToken(request);
   HttpResponse<Car[]> carHttpResponse;
   try {
     carHttpResponse =
         Unirest.get("https://localhost:8099/cars")
             .header("Accept", "application/json")
             .header("Authorization", "Bearer " + token)
             .asObject(Car[].class);
   } catch (UnirestException e) {
     throw new RuntimeException(e);
   }
   Car[] cars = carHttpResponse.getBody();
   List<String> carNames = Arrays.stream(cars).map(Car::getName).collect(toList());
   return "We have these cars available: " + carNames;
 }
  @SuppressWarnings("unchecked")
  public String getJSON(String url, Map<String, Object> queryParams) throws URISyntaxException {
    HttpResponse<JsonNode> httpResponse = null;
    if (!validatorUtil.isHttpURLValid(url)) {
      throw new URISyntaxException(url, "The URL is not absolute");
    }

    try {
      httpResponse = Unirest.get(url).queryString(queryParams).asJson();
    } catch (UnirestException e) {
      LOGGER.error("Exception occured while making get call");
      JSONObject errorObject = new JSONObject();
      errorObject.put("status", "500");
      errorObject.put("message", e.getLocalizedMessage());
      return errorObject.toJSONString();
    }
    return httpResponse.getBody().toString();
  }
    // Handles all incoming webhook notifications
    public void handle(HttpExchange t) throws IOException {

      System.out.println("Request received");

      // Reject non-POST requests
      if (!t.getRequestMethod().equals("POST")) {
        t.sendResponseHeaders(405, 0);
        t.getResponseBody().close();
      }

      Headers requestHeaders = t.getRequestHeaders();
      String callbackSignature = requestHeaders.get("X-square-signature").get(0);
      String callbackBody = IOUtils.toString(t.getRequestBody(), (String) null);

      if (!isValidCallback(callbackBody, callbackSignature)) {
        System.out.println("Webhook event with invalid signature detected!");
        t.sendResponseHeaders(200, 0);
        t.getResponseBody().close();
        return;
      }

      JSONObject requestBody = new JSONObject(callbackBody);
      if (requestBody.has("event_type")
          && requestBody.getString("event_type").equals("PAYMENT_UPDATED")) {

        // Get the ID of the updated payment
        String paymentId = requestBody.getString("entity_id");

        // Get the ID of the payment's associated location
        String locationId = requestBody.getString("location_id");
        HttpResponse<JsonNode> response;
        try {
          response =
              Unirest.get(_connectHost + "/v1/" + locationId + "/payments/" + paymentId).asJson();
        } catch (UnirestException e) {
          System.out.println("Failed to retrieve payment details");
          return;
        }
        System.out.println(response.getBody().getObject());
      }

      t.sendResponseHeaders(200, 0);
      t.getResponseBody().close();
    }
 // oauth.access
 private JSONObject getAccessToken(String code) throws UnirestException, JSONException {
   String access_token_body =
       "client_id="
           + Constant_Auth.CLIENT_ID
           + "&client_secret="
           + Constant_Auth.CLIENT_SECRET
           + "&code="
           + code;
   HttpResponse<JsonNode> response1 =
       Unirest.post("https://slack.com/api/oauth.access")
           .header("cache-control", "no-cache")
           .header("postman-token", "c207fe41-f818-2d0c-e9c9-2df4f72967de")
           .header("content-type", "application/x-www-form-urlencoded")
           .body(access_token_body)
           .asJson();
   JSONObject accessdata = response1.getBody().getObject();
   System.out.println("Slack accessdata after authentication = " + accessdata);
   return accessdata;
 }
  @Override
  public ImageProc parse(HttpResponse<JsonNode> response, Hashtable<String, Boolean> options) {
    JSONObject auxiliar = new JSONObject();
    try {
      JSONObject obj = response.getBody().getObject();
      int cantPhotos = ((JSONArray) obj.get("photos")).length();
      JSONArray photos = (JSONArray) obj.get("photos");
      for (int j = 0; j < cantPhotos; j++) {
        int imgHeight = (int) ((JSONArray) obj.get("photos")).getJSONObject(j).get("height");
        int imgWidth = (int) ((JSONArray) obj.get("photos")).getJSONObject(j).get("width");

        JSONArray faces = photos.getJSONObject(j).getJSONArray("tags");

        for (int i = 0; i < faces.length(); i++) {
          JSONObject face = (JSONObject) faces.get(i);
          JSONObject coordenadas = face.getJSONObject("center");
          double faceH = (double) face.get("height") / 100 * imgHeight;
          double faceW = (double) face.get("width") / 100 * imgWidth;
          double valueX = (((double) coordenadas.get("x")) / 100 * imgWidth) - faceW / 2;
          double valueY = ((double) coordenadas.get("y")) / 100 * imgHeight - faceH / 2;
          double valueHeight = faceH;
          double valueWidth = faceW;
          auxiliar.put("x", valueX);
          auxiliar.put("y", valueY);
          auxiliar.put("height", valueHeight);
          auxiliar.put("width", valueWidth);
          imageProc.addFace(
              new Rect((int) valueX, (int) valueY, (int) valueHeight, (int) valueWidth));
          for (String s : options.keySet()) {
            addPoint(s, options, face, imgHeight, imgWidth);
          }
        }
      }
      return imageProc;
    } catch (ParseException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return null;
  }
示例#18
0
 private static String getTrackUrl(String query) {
   String url = "http://api.spotify.com/v1/search";
   HttpResponse<JsonNode> jsonResponse;
   try {
     jsonResponse =
         Unirest.get(url)
             .header("accept", "application/json")
             .queryString("q", query)
             .queryString("type", "track")
             .asJson();
     return jsonResponse
         .getBody()
         .getObject()
         .getJSONObject("tracks")
         .getJSONArray("items")
         .getJSONObject(0)
         .getString("preview_url");
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
  @Override
  public void updateMetaData(final String atomData, final String videoId, final Account account)
      throws MetaBadRequestException, MetaIOException {
    try {
      final HttpResponse<String> response =
          Unirest.put(String.format("%s/%s", METADATA_UPDATE_URL, videoId))
              .header("GData-Version", GDATAConfig.GDATA_V2)
              .header("X-GData-Key", "key=" + GDATAConfig.DEVELOPER_KEY)
              .header("Content-Type", "application/atom+xml; charset=UTF-8;")
              .header("Authorization", accountService.getAuthentication(account).getHeader())
              .body(atomData)
              .asString();

      if (SC_OK != response.getCode()) {
        LOGGER.error("Metadata - invalid", response.getBody());
        throw new MetaBadRequestException(atomData, response.getCode());
      }
    } catch (final MetaBadRequestException e) {
      throw e;
    } catch (final Exception e) {
      throw new MetaIOException(e);
    }
  }
  private void vanish(MessageContext context, String args) {
    Message message = context.getMessage();
    if (args.isEmpty()) {
      return;
    }

    try {
      final int cap = 100;
      final int capPages = 10;
      String[] vals = args.split(" ");
      String userId;
      int numMsgs;
      if (vals.length == 2) {
        User user = findUser(context, vals[0]);
        userId = user.getId();
        if (user == NO_USER) {
          userId = vals[0];
        }
        numMsgs = Math.max(1, Math.min(cap, Integer.parseInt(vals[1])));
      } else if (vals.length == 1) {
        userId = "";
        numMsgs = Math.max(1, Math.min(cap, Integer.parseInt(vals[0])));
      } else {
        userId = "";
        numMsgs = 10;
      }

      int limit = numMsgs;
      String before = message.getId();
      //  Limit search to 10 pages (500 msgs)
      //  Instead of deleting them when we find them, we build a list instead
      List<String> messagesToDelete = new ArrayList<>(limit);
      for (int k = 0; k < capPages && limit > 0; k++) {
        Map<String, String> headers = new HashMap<>();
        headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        headers.put(HttpHeaders.AUTHORIZATION, apiClient.getToken());
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("limit", 50);
        queryParams.put("before", before);
        HttpResponse<JsonNode> response =
            Unirest.get(ApiConst.CHANNELS_ENDPOINT + message.getChannelId() + "/messages")
                .headers(headers)
                .queryString(queryParams)
                .asJson();
        JSONArray ret = response.getBody().getArray();
        if (userId.isEmpty()) {
          for (int i = 0; i < ret.length() && limit > 0; i++) {
            JSONObject msg = ret.getJSONObject(i);
            String mid = msg.getString("id");
            before = mid;
            messagesToDelete.add(mid);
            limit--;
          }
        } else {
          for (int i = 0; i < ret.length() && limit > 0; i++) {
            JSONObject msg = ret.getJSONObject(i);
            String mid = msg.getString("id");
            JSONObject msgUsr = msg.getJSONObject("author");
            String uid = msgUsr.getString("id");
            before = mid;
            if (userId.equals(uid)) {
              messagesToDelete.add(mid);
              limit--;
            }
          }
        }
      }
      LOGGER.info("Deleting {} messages", messagesToDelete.size());
      //  Using bulk delete endpoint
      apiClient.bulkDeleteMessages(
          context.getChannel().getId(),
          messagesToDelete.toArray(new String[messagesToDelete.size()]));
    } catch (Exception e) {
      LOGGER.warn("Unable to get messages", e);
    }
  }
 private void setNick(MessageContext context, String args) {
   if (context.getServer() == null || context.getServer() == NO_SERVER) {
     return;
   }
   String serverId = context.getServer().getId();
   Channel channel = context.getChannel();
   String[] split = args.split(" ", 2);
   String newNickname;
   if (split.length == 1) {
     //  Clearing nickname, set to empty string
     newNickname = "";
   } else {
     newNickname = split[1];
   }
   User[] mentions = context.getMessage().getMentions();
   if (mentions.length == 0) {
     apiClient.sendMessage(loc.localize("commands.mod.setnick.response.blank"), channel);
   }
   User target = mentions[0];
   Map<String, String> headers = new HashMap<>();
   headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
   headers.put(HttpHeaders.AUTHORIZATION, apiClient.getToken());
   try {
     HttpResponse<JsonNode> response =
         Unirest.patch(
                 "https://discordapp.com/api/guilds/" + serverId + "/members/" + target.getId())
             .headers(headers)
             .body("{\"nick\":\"" + newNickname + "\"}")
             .asJson();
     int status = response.getStatus();
     if (status != 204) {
       if (status == 403) {
         apiClient.sendMessage(
             loc.localize("commands.mod.setnick.response.failed.no_perms"), channel);
       } else if (status == 404) {
         apiClient.sendMessage(
             loc.localize("commands.mod.setnick.response.failed.not_found"), channel);
       } else {
         apiClient.sendMessage(
             loc.localize(
                 "commands.mod.setnick.response.unknown_error",
                 status,
                 response.getStatusText(),
                 response.getBody().toString()),
             channel);
       }
     } else {
       if (newNickname.isEmpty()) {
         apiClient.sendMessage(
             loc.localize("commands.mod.setnick.response.removed", target.getUsername()), channel);
       } else {
         apiClient.sendMessage(
             loc.localize(
                 "commands.mod.setnick.response.changed", target.getUsername(), newNickname),
             channel);
       }
     }
   } catch (UnirestException e) {
     LOGGER.warn(
         "Exception while setting nickname for {} {} in {} {}",
         target.getUsername(),
         target.getId(),
         context.getServer().getName(),
         serverId);
     LOGGER.warn("Nickname set exception", e);
   }
 }
示例#22
0
  @Override
  public boolean processQuery(String query, ImportInspector inspector, OutputPrinter status) {
    shouldContinue = true;
    try {
      status.setStatus(Localization.lang("Searching..."));
      HttpResponse<JsonNode> jsonResponse;
      query = URLEncoder.encode(query, "UTF-8");
      jsonResponse =
          Unirest.get(API_URL + query + "&api_key=" + API_KEY + "&p=1")
              .header("accept", "application/json")
              .asJson();
      JSONObject jo = jsonResponse.getBody().getObject();
      int hits = jo.getJSONArray("result").getJSONObject(0).getInt("total");
      int numberToFetch = 0;
      if (hits > 0) {
        if (hits > maxPerPage) {
          while (true) {
            String strCount =
                JOptionPane.showInputDialog(
                    Localization.lang("References found")
                        + ": "
                        + hits
                        + "  "
                        + Localization.lang("Number of references to fetch?"),
                    Integer.toString(hits));

            if (strCount == null) {
              status.setStatus(Localization.lang("Search canceled"));
              return false;
            }

            try {
              numberToFetch = Integer.parseInt(strCount.trim());
              break;
            } catch (RuntimeException ex) {
              status.showMessage(Localization.lang("Please enter a valid number"));
            }
          }
        } else {
          numberToFetch = hits;
        }

        int fetched = 0; // Keep track of number of items fetched for the progress bar
        for (int startItem = 1; startItem <= numberToFetch; startItem += maxPerPage) {
          if (!shouldContinue) {
            break;
          }

          int noToFetch = Math.min(maxPerPage, numberToFetch - startItem);
          jsonResponse =
              Unirest.get(
                      API_URL
                          + query
                          + "&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);
              BibtexEntry entry = jep.SpringerJSONtoBibtex(springerJsonEntry);
              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", "Springer"),
            JOptionPane.INFORMATION_MESSAGE);
        return false;
      }
    } catch (UnirestException e) {
      LOGGER.warn("Problem searching Springer", e);
    } catch (UnsupportedEncodingException e) {
      LOGGER.warn("Cannot encode query", e);
    }
    return false;
  }