@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();
  }
Exemplo n.º 2
0
  @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();
  }
 public static HttpResponse<JsonNode> get(String url) {
   HttpResponse<JsonNode> response = null;
   try {
     response = Unirest.get(url).asJson();
   } catch (UnirestException e) {
     LOGGER.warning(Messages.DockerRegistryHelper_InaccessibleUrl());
     e.printStackTrace();
   }
   return response;
 }
Exemplo n.º 4
0
 /**
  * Gets the {@link Room room} with the given ID.
  *
  * @param id The ID.
  * @return The room, or null if an error occurred.
  */
 public Room getRoom(String id) {
   try {
     if (rooms.containsKey(id)) return rooms.get(id);
     JSONObject o = requests().get("/rooms/" + id).asJson().getBody().getObject();
     return rooms.computeIfAbsent(id, i -> new RoomImpl(this, o));
   } catch (UnirestException e) {
     e.printStackTrace();
     return null;
   }
 }
Exemplo n.º 5
0
 /**
  * Gets the authenticated {@link User user} object.
  *
  * @return The user, or null if an error occurred.
  */
 public User getCurrentUser() {
   try {
     if (user != null) return user;
     JSONArray arr = requests().get("/user").asJson().getBody().getArray();
     return user = new UserImpl(this, arr.getJSONObject(0));
   } catch (UnirestException e) {
     e.printStackTrace();
     return null;
   }
 }
Exemplo n.º 6
0
  public static HttpResponse<JsonNode> executeSilently(final HttpRequestWithBody request) {
    HttpResponse<JsonNode> response = null;

    try {
      response = request.asJson();
    } catch (UnirestException e) {
      e.printStackTrace();
    }

    return response;
  }
  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;
    }
  }
  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);
    }
  }
Exemplo n.º 9
0
  public static HttpResponse executeSilently(final GetRequest request, final boolean asJson) {
    HttpResponse response = null;

    try {
      if (asJson) {
        response = request.asJson();
      } else {
        response = request.asString();
      }
    } catch (UnirestException e) {
      e.printStackTrace();
    }

    return response;
  }
Exemplo n.º 10
0
 public static synchronized void sendUpdate(Transfer trans, String gameid) {
   lamport.Add();
   try {
     Transaction transaction = new Transaction(trans, lamport.getTime());
     transfers.add(trans);
     transactions.add(transaction);
     String tmp = gson.toJson(trans);
     Unirest.post(replication + "/sync/" + gameid)
         .header("Content-Type", "application/json")
         .body(tmp)
         .asString();
   } catch (UnirestException e) {
     System.out.println("Konnte Dienste nicht synchronisieren.");
     e.printStackTrace();
   }
 }
Exemplo n.º 11
0
 /**
  * Gets a list of all {@link Room rooms} that the authenticated {@link User user} is a member of.
  *
  * @return The rooms, or null if an error occurred.
  */
 public List<Room> getCurrentRooms() {
   try {
     List<Room> rooms = new LinkedList<>();
     JSONArray arr = requests().get("/rooms").asJson().getBody().getArray();
     for (int i = 0, j = arr.length(); i < j; i++) {
       JSONObject o = arr.getJSONObject(i);
       String id = o.getString("id");
       if (!this.rooms.containsKey(id)) this.rooms.put(id, new RoomImpl(this, o));
       Room room = this.rooms.get(id);
       if (room.isMember()) rooms.add(room);
     }
     return rooms;
   } catch (UnirestException e) {
     e.printStackTrace();
     return null;
   }
 }
Exemplo n.º 12
0
  @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();
  }
Exemplo n.º 13
0
  @SuppressWarnings("unchecked")
  public String delete(String url, Map<String, String> headers) throws URISyntaxException {
    HttpResponse<String> httpResponse = null;

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

    try {
      httpResponse = Unirest.delete(url).headers(headers).asString();
    } 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.getStatusText();
  }
Exemplo n.º 14
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Enumeration<String> enumeration = request.getParameterNames();
    HttpResponse<JsonNode> jsonResponse = null;
    try {

      JSONObject jsonObject = new JSONObject();
      jsonObject.put("email", request.getParameter("form-email"));
      jsonObject.put("username", request.getParameter("form-username"));
      jsonObject.put("password", request.getParameter("form-password"));

      JsonNode jsonNode = new JsonNode(jsonObject.toString());
      jsonResponse =
          Unirest.post(Const.REST_BASE_URL + Const.Api.USER_REGISTER)
              .header("Content-Type", "application/json")
              .body(jsonNode)
              .asJson();
    } catch (UnirestException e) {
      e.printStackTrace();
    }
    response.sendRedirect("/sculture/index");
  }
 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);
 }
Exemplo n.º 16
0
  public static void main(String[] args) {

    transactions = new ArrayList<Transaction>();
    transfers = new ArrayList<Transfer>();
    banks = new HashMap<String, Collection<Account>>();
    Collection<Account> accountList = new ArrayList<Account>();
    BanksService banksService = new BanksService();

    Place place = new Place("boom");
    Player player1 = new Player("test", "", "", place, 1);
    Player player2 = new Player("test2", "", "", place, 1);
    Account account1 = new Account(player1, 350);
    Account account2 = new Account(player2, 100);

    accountList.add(account1);
    accountList.add(account2);
    banks.put("test", accountList);
    System.out.println("test banks: " + gson.toJson(banks.get("test")));

    try {
      Service service =
          new Service(
              "banks",
              "gruppe ingrid",
              "banks",
              "https://vs-docker.informatik.haw-hamburg.de/ports/11431/banks");
      System.out.println("service wird registriert...");
      String tmp = gson.toJson(service);
      Unirest.post("http://vs-docker.informatik.haw-hamburg.de:8053/services")
          .header("Content-Type", "application/json")
          .body(tmp)
          .asString();
    } catch (UnirestException e) {
      System.out.println("Service konnte nicht registriert werden.");
      e.printStackTrace();
    }

    get(
        "/banks",
        (request, response) -> {
          ArrayList<String> uris = new ArrayList<>();
          for (String uri : banks.keySet()) {
            uris.add(localUri + uri);
          }
          String json = gson.toJson(uris);
          response.status(200);
          return json;
        });

    post(
        "/banks",
        (request, response) -> {
          String gameid = UniqueId++ + "";
          Collection<Account> gameacc = new ArrayList<Account>();
          Game json = gson.fromJson(request.body(), Game.class);
          json.setGameid(gameid);
          for (Player player : json.getPlayers()) {
            Account acc = new Account();
            acc.setPlayer(player);
            acc.setSaldo(0);
            acc.setUri(localUri + gameid + "/players/" + player.getId());
            gameacc.add(acc);
          }
          banks.put(gameid, gameacc);
          response.status(200);
          response.header("location", localUri + gameid);
          return "ok";
        });

    get(
        "/banks/transfers",
        (request, response) -> {
          return gson.toJson(transfers);
        });

    get(
        "/banks/transfers/:transferid",
        (request, response) -> {
          String uri = localUri + "transfers/" + request.params(":transferid");
          for (Transfer trans : transfers) {
            if (trans.getUri().equals(uri)) {
              response.status(200);
              return gson.toJson(trans);
            }
          }
          response.status(404);
          return "Transfer not found.";
        });

    put(
        "/banks/:gameid",
        (request, response) -> {
          Game json = gson.fromJson(request.body(), Game.class);
          String gameid = request.params(":gameid");
          Collection<Account> gameacc = banks.getOrDefault(gameid, new ArrayList<Account>());
          for (Player player : json.getPlayers()) {
            Account acc = new Account();
            acc.setPlayer(player);
            acc.setSaldo(0);
            acc.setUri(localUri + gameid + "/players/" + player.getId());
            gameacc.add(acc);
          }
          banks.put(gameid, gameacc);
          response.header("uri", localUri + gameid + "/players");
          return "";
        });

    get(
        "/banks/:gameid",
        (request, response) -> {
          String gameid = request.params(":gameid");
          String json = gson.toJson(banks.getOrDefault(gameid, new ArrayList<Account>()));
          return json;
        });

    post(
        "/banks/:gameid/players",
        (request, response) -> {
          Type collectionType = new TypeToken<ArrayList<Account>>() {}.getType();
          ArrayList<Account> json = gson.fromJson(request.body(), collectionType);
          Collection<Account> current =
              banks.getOrDefault(request.params(":gameid"), new ArrayList<Account>());
          Set<Account> set = new HashSet<Account>(current);

          for (Account acc : json) {
            if (set.contains(acc)) {
              response.status(409);
              return "Player " + acc.getPlayer().getId() + " already exists.";
            } else {
              set.add(acc);
              current.add(acc);
            }
          }

          banks.put(request.params(":gameid"), (ArrayList<Account>) current);
          response.status(201);
          return "bank account has been created";
        });

    get(
        "/banks/:gameid/players/:playerid",
        (request, response) -> {
          if (banks.containsKey(request.params(":gameid"))) {
            Collection<Account> accounts = banks.get(request.params(":gameid"));
            for (Account account : accounts) {
              if (account.getPlayer().getId().equals(request.params(":playerid"))) {
                response.status(200);
                return account.getSaldo();
              }
            }
            response.status(404);
            return "Player not found.";
          } else {
            response.status(404);
            return "Game not found.";
          }
        });

    post(
        "/banks/:gameid/transfer/to/:to/:amount",
        (request, response) -> {
          return banksService.transferFromBankToPlayer(request, response);
        });

    post(
        "/banks/:gameid/transfer/from/:from/:amount",
        (request, response) -> {
          return banksService.transferFromPlayerToBank(request, response);
        });

    post(
        "/banks/:gameid/transfer/from/:from/to/:to/:amount",
        (request, response) -> {
          return banksService.transferFromPlayerToPlayer(request, response);
        });

    post(
        "/banks/sync/:gameid",
        (request, response) -> {
          return banksService.updateAccounts(request, response);
        });

    post(
        "/banks/sync/all",
        (request, response) -> {
          return banksService.replaceBanks(request, response);
        });

    get(
        "/banks/sync/all",
        (request, response) -> {
          String tmp = gson.toJson(banksService.banks);
          Unirest.post(replication + "/sync/all")
              .header("Content-Type", "application/json")
              .body(tmp)
              .asString();
          return "success";
        });

    post(
        "/banks/change/replication",
        (request, response) -> {
          replication = request.body();
          return replication;
        });

    get(
        "/stop/service",
        (request, response) -> {
          stop();
          return "";
        });
  }