Beispiel #1
0
  public synchronized String transferFromBankToPlayer(Request request, Response response) {
    lamport.Add();
    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(":to"))) {
          int am = Integer.parseInt(request.params(":amount"));
          account.AddAmount(am);
          banks.put(request.params(":gameid"), accounts);

          String uri = localUri + "transfers/" + UniqueId++;
          Transfer trans =
              new Transfer(
                  request.params(":from"), request.params(":to"), am, request.body(), "", uri);
          Event event =
              new Event(
                  "bank transfer",
                  request.body(),
                  request.body(),
                  uri,
                  account.getPlayer().getId());
          transfers.add(trans);
          BanksService.sendUpdate(trans, request.params(":gameid"));

          response.status(201);
          return gson.toJson(event);
        }
      }
      response.status(404);
      return "Player not found.";
    } else {
      response.status(404);
      return "Game not found.";
    }
  }
  @Override
  public Object handle(final Request request, final Response response) throws Exception {
    if (!CreateGameDTO.isValidRequestJson(request.body())) {
      response.status(400);
      return BAD_JSON_MESSAGE;
    }

    final CommandExecutionResult result =
        GamesController.createGame(new CreateGameDTO(request.body()));

    if (result.errorOccurred()) {
      response.status(result.getStatus());
    } else {
      response.status(200);
    }

    // set any new cookies
    if (result.hasNewCookies()) {
      Map<String, String> cookies = result.getNewCookies();
      for (String key : cookies.keySet()) {
        Cookie cookie = new Cookie(key, cookies.get(key));
        cookie.setPath("/");
        response.raw().addCookie(cookie);
      }
    }

    return result.getBody();
  }
  @Override
  public Object handle(Request request, Response response) {

    JSONObject result;

    try {
      JSONObject requestJSON = new JSONObject(request.body());
      SudokuGame game =
          new SudokuGame(convertJSONObjectToStringArray(requestJSON.getJSONArray("data")));
      game.solve();
      result = convertStringToJSONObject(game.toString());
    } catch (CannotProceedException e) {
      result = createErrorMessage("cannot solve");
      logger.error(e.getMessage());
    } catch (Exception e) {
      result = createErrorMessage("unknown");
      logger.error(e.getMessage());
    }

    response.type("application/json");
    /*try {
        Thread.sleep(15000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }*/
    return result;
  }
Beispiel #4
0
 private String upsertUser(Request request, Response response) throws UsersRepositoryException {
   try {
     return userService.upsertUser(
         request.params(USER_NAME), jsonExtractor.parse(request.body()).getPassword(), response);
   } catch (JsonExtractException e) {
     LOGGER.info("Error while deserializing addUser request", e);
     response.status(400);
     return Constants.EMPTY_BODY;
   } catch (IllegalArgumentException e) {
     LOGGER.info("Invalid user path", e);
     response.status(400);
     return Constants.EMPTY_BODY;
   }
 }
Beispiel #5
0
 public synchronized String replaceBanks(Request request, Response response) {
   Type collectionType = new TypeToken<HashMap<String, Collection<Account>>>() {}.getType();
   HashMap<String, Collection<Account>> json = gson.fromJson(request.body(), collectionType);
   banks = json;
   return "success";
 }
Beispiel #6
0
  public synchronized String updateAccounts(Request request, Response response) {

    Transaction json = gson.fromJson(request.body(), Transaction.class);

    if (json.getTimestamp() > lamport.getTime()) {
      lamport.Update(json.getTimestamp());
      lamport.Add();
      Unirest.get(replication + "/sync/all");
      return "replacing database.";
    } else {
      lamport.Add();
      for (Transaction transaction : transactions) {
        if (transaction.getTransfer().equals(json.getTransfer())
            && transaction.getTimestamp() == json.getTimestamp()) {
          return "failure, transfer already exists.";
        }
      }
      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(":from"))) {
            int am = Integer.parseInt(request.params(":amount"));
            if (account.getSaldo() >= am) {
              account.SubtractAmount(am);

              banks.put(request.params(":gameid"), accounts);
              String uri = localUri + "transfers/" + UniqueId++;
              Transfer trans =
                  new Transfer(
                      request.params(":from"), request.params(":to"), am, request.body(), "", uri);
              Event event =
                  new Event(
                      "bank transfer",
                      request.body(),
                      request.body(),
                      uri,
                      account.getPlayer().getId());
              transfers.add(trans);
              Transaction transaction = new Transaction(trans, lamport.getTime());
              transactions.add(transaction);
              BanksService.sendUpdate(trans, request.params(":gameid"));

              response.status(201);
              return gson.toJson(event);
            } else {
              response.status(403);
              return "Insufficent funds.";
            }
          }
        }
        response.status(404);
        return "Player not found.";
      }

      // from Bank to Player
      else if (json.getTransfer().getFrom().equals("bank")) {
        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(":to"))) {
              int am = Integer.parseInt(request.params(":amount"));
              account.AddAmount(am);
              banks.put(request.params(":gameid"), accounts);

              String uri = localUri + "transfers/" + UniqueId++;
              Transfer trans =
                  new Transfer(
                      request.params(":from"), request.params(":to"), am, request.body(), "", uri);
              Event event =
                  new Event(
                      "bank transfer",
                      request.body(),
                      request.body(),
                      uri,
                      account.getPlayer().getId());
              transfers.add(trans);
              BanksService.sendUpdate(trans, request.params(":gameid"));

              response.status(201);
              return gson.toJson(event);
            }
          }
          response.status(404);
          return "Player not found.";
        }

        // from Player to Player
        else {
          Collection<Event> events = new ArrayList<Event>();
          boolean transactionSuccessful = false;
          Transfer trans = null;
          Collection<Account> accounts = banks.get(request.params(":gameid"));
          Collection<Account> copy = new ArrayList<>();
          copy.addAll(accounts);

          for (Account account : copy) {
            if (account.getPlayer().getId().equals(request.params(":from"))) {
              int am = Integer.parseInt(request.params(":amount"));
              if (account.getSaldo() >= am) {
                account.SubtractAmount(am);
                break;
              } else {
                response.status(403);
                return "Insufficent funds.";
              }
            }
          }

          for (Account account : copy) {
            if (account.getPlayer().getId().equals(request.params(":to"))) {
              int am = Integer.parseInt(request.params(":amount"));
              account.AddAmount(am);
              String uri = localUri + "transfers/" + UniqueId++;
              trans =
                  new Transfer(
                      request.params(":from"), request.params(":to"), am, request.body(), "", uri);
              Event event =
                  new Event(
                      "bank transfer",
                      request.body(),
                      request.body(),
                      uri,
                      account.getPlayer().getId());
              events.add(event);
              transactionSuccessful = true;
            }
          }

          if (transactionSuccessful) {
            // transfer was successful, time to "commit" the changes!
            banks.put(request.params(":gameid"), copy);
            transfers.add(trans);
            Transaction transaction = new Transaction(trans, lamport.getTime());
            transactions.add(transaction);
            BanksService.sendUpdate(trans, request.params(":gameid"));

            response.status(201);
            return gson.toJson(events);
          } else {
            // OH OH! Something went wrong! But we actually didn't change anything, so we're good.
            response.status(404);
            return "Player not found.";
          }
        }
      } else {
        return "Game not found.";
      }
    }
  }
Beispiel #7
0
 public SubmitHandler(Request request, Response response) {
   // get the users credentials using request.params(":id")
   SeleniumController.getInstance().submit(request.body());
 }