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."; } }
/** * @param request The request object providing information about the HTTP request * @param response The response object providing functionality for modifying the response * @return The content to be set in the response * @throws Exception implementation can choose to throw exception */ public String handleGetPermaLinkPost(Request request, Response response) throws Exception { String permalink = request.params(":permalink"); System.out.println("/post: get " + permalink); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); return templateEngine.render(new ModelAndView(null, "redirect.ftl")); } else { // empty comment to hold new comment in form at bottom of blog entry detail page SimpleHash newComment = new SimpleHash(); newComment.put("name", ""); newComment.put("email", ""); newComment.put("body", ""); SimpleHash root = new SimpleHash(); root.put("post", post); root.put("comments", newComment); return templateEngine.render(new ModelAndView(root, "entry_template.ftl")); } }
@Test public void testGetFeedItems() { Request request = createRequestMock("logged-in"); Response response = createResponseMock(); GetFeedItemsRoute feedsRoute = new GetFeedItemsRoute("/feeds"); feedsRoute.setFeedItemProvider(createFeedItemProviderMock()); feedsRoute.setFeedUpdater(createFeedUpdaterMock()); feedsRoute.setFeedProvider(createFeedProviderMock()); when(request.params(":categoryId")).thenReturn("1"); when(request.params(":feedId")).thenReturn("2"); String jsonResponse = (String) feedsRoute.handle(request, response); String expectedJson = "[{\"feedItemId\":\"3\",\"username\":\"billblake\",\"catId\":\"1\",\"feedId\":\"2\",\"source\":\"source\",\"title\":\"title\",\"description\":\"description\",\"link\":\"link\",\"imageUrl\":null,\"pubDate\":10000000,\"formattedDate\":\"Jul 28\",\"read\":false,\"saved\":false,\"tags\":null}]"; assertEquals(expectedJson, jsonResponse); }
@Override public Object handle(Request request, Response response) throws Exception { try { String serviceName = request.params(":serviceName"); deleteServiceJob(serviceName, user, password, tenant, dbClient); response.status(HttpConstants.HTTP_OK); response.type(HttpConstants.APPLICATION_JSON); return "Deletion scheduled for service " + serviceName; } catch (Exception e) { response.status(HTTP_BAD_REQUEST); return e.toString(); } }
public static byte[] getOrigin(Request req, Response res) { res.header("Content-Type", "application/octet-stream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int x = Integer.parseInt(req.params("x")); int y = Integer.parseInt(req.params("y").replaceFirst("\\.dat$", "")); StaticSiteRequest.PointRequest pr = staticSiteRequest.getPointRequest(x, y); StaticComputer computer = new StaticComputer(pr, network, new TaskStatistics()); try { computer.write(baos); return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } }
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; } }
/** * @param request The request object providing information about the HTTP request * @param response The response object providing functionality for modifying the response * @return The content to be set in the response * @throws Exception implementation can choose to throw exception */ public String handleGetByTag(Request request, Response response) throws Exception { String username = sessionDAO.findUserNameBySessionId(request.cookie("session")); SimpleHash root = new SimpleHash(); String tag = StringEscapeUtils.escapeHtml4(request.params(":thetag")); List<Document> posts = blogPostDAO.findByTagDateDescending(tag); root.put("myposts", posts); if (username != null) { root.put("username", username); } return templateEngine.render(new ModelAndView(root, "blog_template.ftl")); }
private String removeUser(Request request, Response response) { String username = request.params(USER_NAME); try { userService.removeUser(username); response.status(204); return Constants.EMPTY_BODY; } catch (UsersRepositoryException e) { response.status(204); return "The user " + username + " does not exists"; } catch (IllegalArgumentException e) { LOGGER.info("Invalid user path", e); response.status(400); return Constants.EMPTY_BODY; } }
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."; } } }
public static Object getRoutes(Request req, Response res) { List<Route> routes = new ArrayList<>(); List<String> feeds = new ArrayList(); if (req.queryParams("feed") != null) { for (String feedId : req.queryParams("feed").split(",")) { if (ApiMain.getFeedSource(feedId) != null) { feeds.add(feedId); } } if (feeds.size() == 0) { halt(404, "Must specify valid feed id."); } // If feed is only param. else if (req.queryParams().size() == 1 && req.params("id") == null) { for (String feedId : req.queryParams("feed").split(",")) { FeedSource feedSource = ApiMain.getFeedSource(feedId); if (feedSource != null) routes.addAll(feedSource.feed.routes.values()); } return routes; } } else { // res.body("Must specify valid feed id."); // return "Must specify valid feed id."; halt(404, "Must specify valid feed id."); } // get specific route if (req.params("id") != null) { Route r = ApiMain.getFeedSource(feeds.get(0)).feed.routes.get(req.params("id")); if (r != null) // && currentUser(req).hasReadPermission(s.projectId)) return r; else halt(404, "Route " + req.params("id") + " not found"); } // bounding box else if (req.queryParams("max_lat") != null && req.queryParams("max_lon") != null && req.queryParams("min_lat") != null && req.queryParams("min_lon") != null) { Coordinate maxCoordinate = new Coordinate( Double.valueOf(req.queryParams("max_lon")), Double.valueOf(req.queryParams("max_lat"))); Coordinate minCoordinate = new Coordinate( Double.valueOf(req.queryParams("min_lon")), Double.valueOf(req.queryParams("min_lat"))); Envelope searchEnvelope = new Envelope(maxCoordinate, minCoordinate); for (String feedId : feeds) { // TODO: these are actually patterns being returned, NOT routes List<Route> searchResults = ApiMain.getFeedSource(feedId).routeIndex.query(searchEnvelope); routes.addAll(searchResults); } return routes; } // lat lon + radius else if (req.queryParams("lat") != null && req.queryParams("lon") != null) { Coordinate latLon = new Coordinate( Double.valueOf(req.queryParams("lon")), Double.valueOf(req.queryParams("lat"))); if (req.queryParams("radius") != null) { RoutesController.radius = Double.valueOf(req.queryParams("radius")); } Envelope searchEnvelope = GeomUtil.getBoundingBox(latLon, radius); for (String feedId : feeds) { List<Route> searchResults = ApiMain.getFeedSource(feedId).routeIndex.query(searchEnvelope); routes.addAll(searchResults); } return routes; } else if (req.queryParams("name") != null) { System.out.println(req.queryParams("name")); for (String feedId : feeds) { System.out.println("looping feed: " + feedId); // Check if feed is specified in feed sources requested // TODO: Check if user has access to feed source? (Put this in the before call.) // if (Arrays.asList(feeds).contains(entry.getKey())) { System.out.println("checking feed: " + feedId); // search query must be in upper case to match radix tree keys Iterable<Route> searchResults = ApiMain.getFeedSource(feedId) .routeTree .getValuesForKeysContaining(req.queryParams("name").toUpperCase()); for (Route route : searchResults) { routes.add(route); } } return routes; } // query for stop_id (i.e., get all routes that operate along patterns for a given stop) else if (req.queryParams("stop") != null) { return getRoutesForStop(req, feeds); } return null; }