public void initRoutes() { get("api/devices", (request, response) -> deviceService.getAllDevices(), toJson()); post( "api/devices", (req, res) -> { DeviceRequest createDeviceRequest = mapper.readValue(req.body(), DeviceRequest.class); deviceService.createDevice(createDeviceRequest); return "created"; }); get( "api/devices/:deviceId", (req, res) -> deviceService.getDevice(req.params("deviceId")), toJson()); put( "api/devices/:deviceId", (req, res) -> { String deviceId = req.params("deviceId"); if (deviceId != null && !deviceId.trim().isEmpty()) { DeviceRequest createDeviceRequest = mapper.readValue(req.body(), DeviceRequest.class); deviceService.changeDevice(deviceId, createDeviceRequest); return "modified"; } else throw new RuntimeException("Incorrect request, missing device id"); }); delete( "api/devices/:deviceId", (req, res) -> { String deviceId = req.params("deviceId"); if (deviceId != null && !deviceId.trim().isEmpty()) { deviceService.shutdownDevice(deviceId); return "Delete device " + deviceId; } else throw new RuntimeException("Incorrect request, missing device id"); }, toJson()); post( "api/devices/:deviceId/tasks", (req, res) -> { String deviceId = req.params("deviceId"); String requestBody = req.body(); DeviceTask task = DeviceTaskParser.parseTask(mapper, mapper.readTree(requestBody)); return deviceService.executeTask(deviceId, task); }, toJson()); get( "api/devices/:deviceId/tasks", (req, res) -> { String deviceId = req.params("deviceId"); return deviceService.getCurrentTasks(deviceId); }, toJson()); }
@SuppressWarnings("unchecked") private void setupRoutes() { before( (req, res) -> { log.info("Path is: " + req.pathInfo()); CallingContext ctx = ctxs.get(req.session().id()); if (ctx == null) { // check x-api-key header String apiKey = req.headers("x-api-key"); if (StringUtils.isNotBlank(apiKey)) { ctx = Kernel.INSTANCE.loadContext(APP_KEY, apiKey); if (ctx == null) { String msg = String.format("Invalid apiKey [%s] for app [%s]", apiKey, APP_KEY); log.warn(msg); halt(401, msg); } String id = req.session(true).id(); ctxs.put(id, ctx); } else { log.warn("x-api-key header not found, rejecting..."); halt(401, "Please provide 'x-api-key' header to access this API"); } } }); post( "/doc/:authority", (req, res) -> { log.info(req.body()); Map<String, Object> data = JacksonUtil.getMapFromJson(req.body()); String authority = req.params(":authority"); String config = (String) data.get("config"); CallingContext ctx = getContext(req); if (Kernel.getDoc().docRepoExists(ctx, authority)) { halt(409, String.format("Repo [%s] already exists", authority)); } Kernel.getDoc().createDocRepo(ctx, authority, config); return new RaptureURI(authority, Scheme.DOCUMENT).toString(); }); get( "/doc/*", (req, res) -> { String meta = req.queryParams("meta"); if (StringUtils.isNotBlank(meta)) { return Kernel.getDoc().getDocAndMeta(getContext(req), getDocUriParam(req)); } return Kernel.getDoc().getDoc(getContext(req), getDocUriParam(req)); }); put( "/doc/*", (req, res) -> { return Kernel.getDoc().putDoc(getContext(req), getDocUriParam(req), req.body()); }); delete( "/doc/:authority", (req, res) -> { Kernel.getDoc().deleteDocRepo(getContext(req), req.params(":authority")); return true; }); delete( "/doc/*", (req, res) -> { return Kernel.getDoc().deleteDoc(getContext(req), getDocUriParam(req)); }); post( "/blob/:authority", (req, res) -> { log.info(req.body()); Map<String, Object> data = JacksonUtil.getMapFromJson(req.body()); String authority = req.params(":authority"); String config = (String) data.get("config"); String metaConfig = (String) data.get("metaConfig"); CallingContext ctx = getContext(req); if (Kernel.getBlob().blobRepoExists(ctx, authority)) { halt(409, String.format("Repo [%s] already exists", authority)); } Kernel.getBlob().createBlobRepo(ctx, authority, config, metaConfig); return new RaptureURI(authority, Scheme.BLOB).toString(); }); get( "/blob/*", (req, res) -> { return Kernel.getBlob().getBlob(getContext(req), getBlobUriParam(req)); }, json()); put( "/blob/*", (req, res) -> { String uri = getBlobUriParam(req); Kernel.getBlob().putBlob(getContext(req), uri, req.bodyAsBytes(), req.contentType()); return uri; }); delete( "/blob/:authority", (req, res) -> { Kernel.getBlob().deleteBlobRepo(getContext(req), req.params(":authority")); return true; }); delete( "/blob/*", (req, res) -> { Kernel.getBlob().deleteBlob(getContext(req), getBlobUriParam(req)); return true; }); post( "/series/:authority", (req, res) -> { log.info(req.body()); Map<String, Object> data = JacksonUtil.getMapFromJson(req.body()); String authority = req.params(":authority"); String config = (String) data.get("config"); CallingContext ctx = getContext(req); if (Kernel.getSeries().seriesRepoExists(ctx, authority)) { halt(409, String.format("Repo [%s] already exists", authority)); } Kernel.getSeries().createSeriesRepo(ctx, authority, config); return new RaptureURI(authority, Scheme.SERIES).toString(); }); get( "/series/*", (req, res) -> { return Kernel.getSeries().getPoints(getContext(req), getSeriesUriParam(req)); }, json()); put( "/series/*", (req, res) -> { String uri = getSeriesUriParam(req); Map<String, Object> data = JacksonUtil.getMapFromJson(req.body()); List<String> keys = (List<String>) data.get("keys"); List<Object> values = (List<Object>) data.get("values"); if (!values.isEmpty()) { Object obj = values.get(0); if (obj instanceof Long) { Kernel.getSeries() .addLongsToSeries(getContext(req), uri, keys, (List<Long>) (List<?>) values); } else if (obj instanceof String) { Kernel.getSeries() .addStringsToSeries(getContext(req), uri, keys, (List<String>) (List<?>) values); } else if (obj instanceof Double) { Kernel.getSeries() .addDoublesToSeries(getContext(req), uri, keys, (List<Double>) (List<?>) values); } else { halt(400, "Unknown type in values parameter"); } } return uri; }); delete( "/series/:authority", (req, res) -> { Kernel.getSeries().deleteSeriesRepo(getContext(req), req.params(":authority")); return true; }); delete( "/series/*", (req, res) -> { Kernel.getSeries().deleteSeries(getContext(req), getSeriesUriParam(req)); return true; }); post( "/workorder/*", (req, res) -> { Map<String, String> params = new HashMap<>(); String body = req.body(); if (StringUtils.isNotBlank(body)) { Map<String, Object> data = JacksonUtil.getMapFromJson(body); params = (Map<String, String>) data.get("params"); } return Kernel.getDecision() .createWorkOrder(getContext(req), getWorkorderUriParam(req), params); }); }
public static void main(final String[] args) throws UnknownHostException { final MongoClient mongo = new MongoClient(); final DB mongoDb = mongo.getDB("left4u"); final boolean firstStart = !mongoDb.collectionExists("stuff"); final DBCollection stuffCollection = mongoDb.getCollection("stuff"); if (firstStart) { final EnsureLocationIndexQuery ensureLocationIndexQuery = new EnsureLocationIndexQuery(stuffCollection); ensureLocationIndexQuery.execute(); } Spark.get( new Route("/stuff/") { @Override public Object handle(final Request request, final Response response) { DBObject result; final String sortType = request.queryParams("sort"); final String tags = request.queryParams("filter"); if (sortType != null) { if (sortType.equals("location")) { final String lat = request.queryParams("lat"); final String lon = request.queryParams("long"); final String distance = "10"; final BrowseStuffQuery findQuery = new BrowseStuffQuery(stuffCollection, lat, lon, distance); result = findQuery.execute(); } else if (sortType.equals("created")) { final BrowseStuffQuery findQuery = new BrowseStuffQuery(stuffCollection, true); result = findQuery.execute(); } else { throw new IllegalArgumentException("Unsupported sort parameter"); } } else if (tags != null) { final List<String> tagsList = Arrays.asList(tags.split(",")); final BrowseStuffQuery findQuery = new BrowseStuffQuery(stuffCollection, tagsList); result = findQuery.execute(); } else { final BrowseStuffQuery findQuery = new BrowseStuffQuery(stuffCollection, false); result = findQuery.execute(); } return result; } }); Spark.get( new Route("/stuff/:id") { @Override public Object handle(final Request request, final Response response) { final String id = request.params(":id"); final GetStuffByIdQuery findQuery = new GetStuffByIdQuery(stuffCollection, id); return findQuery.execute(); } }); Spark.post( new Route("/stuff/") { @Override public Object handle(final Request request, final Response response) { final ObjectId id = new ObjectId(); final DBObject insert = (DBObject) JSON.parse(request.body()); insert.put("_id", id); final InsertQuery insertQuery = new InsertQuery(stuffCollection, insert); response.header("Location", id.toString()); return insertQuery.execute().getN(); } }); Spark.put( new Route("/stuff/:id") { @Override public Object handle(final Request request, final Response response) { final String id = request.params(":id"); final DBObject update = (DBObject) JSON.parse(request.body()); final UpdateQuery putQuery = new UpdateQuery(stuffCollection, id, update); return putQuery.execute().getN(); } }); Spark.delete( new Route("/stuff/:id") { @Override public Object handle(final Request request, final Response response) { final String id = request.params(":id"); final DeleteQuery deleteQuery = new DeleteQuery(stuffCollection, id); return deleteQuery.execute().getN(); } }); }
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 ""; }); }
public UserController() { get( "dbeb/users", "application/json", (request, response) -> { String email = request.queryParams("facebookId"); List<User> objs = HibernateUtil.getSession() .createCriteria(User.class) .add(Restrictions.eq("facebookId", email)) .list(); return objs; }, new JsonTransformer()); get( "dbeb/users/:id", "application/json", (request, response) -> { long id = Long.parseLong(request.params(":id")); User obj = (User) HibernateUtil.getSession().get(User.class, id); if (obj == null) halt(404); return obj; }, new JsonTransformer()); post( "dbeb/users", "application/json", (request, response) -> { User obj = JacksonUtil.readValue(request.body(), User.class); HibernateUtil.getSession().saveOrUpdate(obj); response.status(201); return obj; }, new JsonTransformer()); put( "dbeb/users/:id", "application/json", (request, response) -> { long id = Long.parseLong(request.params(":id")); User obj = (User) HibernateUtil.getSession().get(User.class, id); if (obj == null) halt(404); obj = JacksonUtil.readValue(request.body(), User.class); obj = (User) HibernateUtil.getSession().merge(obj); return obj; }, new JsonTransformer()); delete( "dbeb/users/:id", (request, response) -> { long id = Long.parseLong(request.params(":id")); User obj = (User) HibernateUtil.getSession().get(User.class, id); if (obj == null) halt(404); HibernateUtil.getSession().delete(obj); response.status(204); return ""; }); }
private void setupRoutes() { get( "/transactionservice/transaction/:id", (req, res) -> { try { long id = Long.parseLong(req.params(":id")); Transaction tx = store.getTxById(id); if (tx == null) { res.status(HTTP_NOT_FOUND); return errorUnknownIdBody; } return gson.toJson(tx); } catch (Exception e) { res.status(HTTP_REQUEST_ERROR); return errorInvalidBody; } }); // Queries for a type will always succeed: If there is no transaction, the (valid) response is // an empty list. get( "/transactionservice/types/:type", (req, res) -> gson.toJson(store.getTxIdsByType(req.params(":type")))); get( "/transactionservice/sum/:id", (req, res) -> { try { long id = Long.parseLong(req.params(":id")); double sum = store.getSum(id); JsonObject resJson = new JsonObject(); resJson.addProperty("sum", sum); return resJson; } catch (TransactionNotFoundException e) { res.status(HTTP_NOT_FOUND); return errorUnknownIdBody; } catch (Exception e) { res.status(HTTP_REQUEST_ERROR); return errorInvalidBody; } }); put( "/transactionservice/transaction/:id", (req, res) -> { try { JsonObject input = (JsonObject) new JsonParser().parse(req.body()); long id = Long.parseLong(req.params(":id")); double amount = input.get("amount").getAsDouble(); // TODO: Specify and enforce allowed characters in the type string. Currently, all // strings are valid. String type = input.get("type").getAsString(); // Parent ID is optional; set to zero if not provided long parentId = 0L; if (input.has("parent")) { parentId = input.get("parent").getAsLong(); } store.addTx(id, amount, type, parentId); } catch (DuplicateTransactionException e) { res.status(HTTP_CONFLICT); return errorDuplicateBody; } catch (InvalidParentTransactionException e) { res.status(HTTP_REQUEST_ERROR); return errorInvalidParent; } catch (Exception e) { // Something else went wrong (e.g. unparseable request format) res.status(HTTP_REQUEST_ERROR); return errorInvalidBody; } // If everything went OK, the resource has now been created: Return the appropriate HTTP // status res.status(HTTP_CREATED); return okBody; }); }