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;
 }
Exemple #2
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;
   }
 }
Exemple #3
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;
   }
 }
Exemple #4
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);
    }
  }
Exemple #7
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;
  }
 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();
   }
 }
Exemple #9
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;
   }
 }
Exemple #10
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 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 "";
        });
  }