public static void main(String[] args) throws SQLException { // open database Connection conn = DriverManager.getConnection("jdbc:h2:./main"); createTables(conn); // serve external files Spark.externalStaticFileLocation("public"); Spark.init(); // insert test data if (selectCountries(conn).size() == 0) { insertCountry(conn, "United States", "US"); insertCountry(conn, "Canada", "CA"); insertCountry(conn, "Mexico", "MX"); } // create routes for AJAX Spark.get( "/get-countries", ((request, response) -> { JsonSerializer serializer = new JsonSerializer(); String json = serializer.serialize(selectCountries(conn)); return json; })); Spark.get( "/get-country", ((request, response) -> { String id = request.queryParams("id"); try { int idNum = Integer.valueOf(id); JsonSerializer serializer = new JsonSerializer(); String json = serializer.serialize(selectCountry(conn, idNum)); return json; } catch (Exception e) { } return ""; })); Spark.post( "/add-country", ((request, response) -> { String name = request.queryParams("name"); String abbrev = request.queryParams("abbrev"); if (name == null || abbrev == null) { Spark.halt(403); } insertCountry(conn, name, abbrev); return ""; })); }
public static void main(String[] args) { final Configuration configuration = new Configuration(Configuration.VERSION_2_3_23); configuration.setClassForTemplateLoading(HelloWorldFreemarkerStyle.class, "/"); get( "/", (request, response) -> { StringWriter writer = new StringWriter(); try { Template helloTemplate = configuration.getTemplate("hello.ftl"); Map<String, Object> helloMap = new HashMap<>(); helloMap.put("name", "Freemarker"); helloTemplate.process(helloMap, writer); } catch (Exception e) { halt(500); e.printStackTrace(); } return writer; }); }
@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(String[] args) { // serve static files from /www in resources staticFileLocation("/www"); // setup the database model Sql2o sql2o = new Sql2o("jdbc:h2:~/test", "sa", ""); Sql2oModel model = new Sql2oModel(sql2o); // url /hello // simple response return get("/hello", (req, res) -> "Hello Spark!"); // url /test-view // simple template "test-view.ftl" get( "/test-view", (req, res) -> { Map<String, Object> viewModel = new HashMap<>(); viewModel.put("message", "Hello Spark!"); return new ModelAndView(viewModel, "test-view.ftl"); }, new FreeMarkerEngine()); // url /books // data bound template get( "/books", (req, res) -> { Map<String, Object> viewModel = new HashMap<>(); viewModel.put("message", "Books"); List<Book> books = model.getBooks(); viewModel.put("books", books); return new ModelAndView(viewModel, "books.ftl"); }, new FreeMarkerEngine()); // url /books/new // initial get of input form for new book in database get( "/books/new", (req, res) -> { Map<String, Object> viewModel = new HashMap<>(); viewModel.put("message", "Add Book"); return new ModelAndView(viewModel, "new-book.ftl"); }, new FreeMarkerEngine()); // url /books/new // subsequent post of new book data back to the // server to get saved back to the database post( "/books/new", (req, res) -> { // todo: add response book to database, use custom viewModel class MultiMap<String> params = new MultiMap<String>(); UrlEncoded.decodeTo(req.body(), params, "UTF-8"); NewBookEditModel editModel = new NewBookEditModel(); BeanUtils.populate(editModel, params); long id = model.createBook( editModel.getTitle(), editModel.getAuthor(), editModel.getImageUrl()); res.redirect("/books"); halt(); return id; // ?? json & rest?? }); get( "/books/delete/:id", (req, res) -> { int id = Integer.parseInt(req.params().get(":id")); model.deleteBook(id); res.redirect("/books"); halt(); return null; }); // url /spi-test // json testbed page "spi-test.ftl" get( "/spi-test", (req, res) -> { Map<String, Object> viewModel = new HashMap<>(); viewModel.put("message", "SPI Test Page"); List<Book> books = model.getBooks(); viewModel.put("books", books); return new ModelAndView(viewModel, "spi-test.ftl"); }, new FreeMarkerEngine()); // Additional JSON Services? }
public static void main(String[] args) throws SQLException { Connection db = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/quiz?useSSL=false", "root", "root"); Entity.setDb(db); ClasspathLoader loader = new ClasspathLoader(); loader.setPrefix("views"); loader.setSuffix(".html.twig"); Cache<Object, PebbleTemplate> cache = CacheBuilder.newBuilder().maximumSize(0).build(); PebbleEngine pebbleEngine = new PebbleEngine.Builder() .defaultLocale(Locale.GERMAN) .loader(loader) .templateCache(cache) .build(); PebbleTemplateEngine engine = new PebbleTemplateEngine(pebbleEngine); Spark.staticFileLocation("public"); Spark.get( "/stop", (request, response) -> { Spark.stop(); return null; }); Spark.get( "/", (request, response) -> { response.redirect("/spiel/start"); return null; }); Spark.get( "/login", (request, response) -> { return new ModelAndView(null, "login"); }, engine); Spark.post( "/login", (request, response) -> { Spieler spieler = Spieler.findeNachEmail(request.queryParams("email")); Session session = request.session(true); if (spieler != null && spieler.istPasswortKorrekt(request.queryParams("passwort"))) { session.attribute("spieler", spieler); response.redirect("/spiel/start"); } else { session.removeAttribute("spieler"); response.redirect("/login"); } return null; }); Spark.get( "/logout", (request, response) -> { request.session(true).removeAttribute("spieler"); response.redirect("/login"); return null; }); Spark.before( "/admin/*", (request, response) -> { Session session = request.session(true); if (session.attribute("spieler") == null) { response.redirect("/login"); Spark.halt(401); } }); Spark.before( "/spiel/*", (request, response) -> { Session session = request.session(true); if (session.attribute("spieler") == null) { response.redirect("/login"); Spark.halt(401); } }); Spark.get( "/spiel/start", (request, response) -> { Spieler spieler = request.session(true).attribute("spieler"); ArrayList<Zuordnung> zuordnungen = Zuordnung.findeUnbeantworteteNachSpieler(spieler); if (zuordnungen.size() > 0) { response.redirect("/spiel/runde"); return null; } Map<String, Object> werte = new HashMap<>(); werte.put("fragen", Frage.findeAlle()); return new ModelAndView(werte, "spiel_start"); }, engine); Spark.post( "/spiel/start", (request, response) -> { Spieler spieler = request.session(true).attribute("spieler"); ArrayList<Frage> fragen = Frage.findeAlle(); Collections.shuffle(fragen); int anzahl = Integer.parseInt(request.queryParams("anzahl").trim()); Runde runde = new Runde(spieler); for (int i = 0; i < anzahl; i++) { new Zuordnung(fragen.get(i), runde).speichern(); } response.redirect("/spiel/runde"); return null; }); Spark.get( "/spiel/runde", (request, response) -> { Spieler spieler = request.session(true).attribute("spieler"); ArrayList<Zuordnung> zuordnungen = Zuordnung.findeUnbeantworteteNachSpieler(spieler); if (zuordnungen.isEmpty()) { response.redirect("/spiel/zusammenfassung"); Spark.halt(); return null; } else { Map<String, Object> werte = new HashMap<>(); Zuordnung naechsteZuordung = zuordnungen.get(0); naechsteZuordung.setGestellt(); werte.put("zuordnung", naechsteZuordung); return new ModelAndView(werte, "spiel_runde"); } }, engine); Spark.post( "/spiel/runde", (request, response) -> { Zuordnung zuordnung = Zuordnung.findeNachId(request.queryParams("zuordnung_id")); Antwort antwort = Antwort.findeNachId(request.queryParams("antwort_id")); zuordnung.setBeantwortet(); zuordnung.setRichtig(antwort.isRichtig()); zuordnung.speichern(); response.redirect("/spiel/runde"); return null; }); Spark.get( "/spiel/zusammenfassung", (request, response) -> { Map<String, Object> werte = new HashMap<>(); Spieler spieler = request.session(true).attribute("spieler"); ArrayList<Zuordnung> zuordnungen = Zuordnung.findeNachSpieler(spieler); int richtigeAntworten = 0; int beantworteteFragen = 0; for (Zuordnung zuordnung : zuordnungen) { if (zuordnung.getBeantwortet() != null) { beantworteteFragen++; if (zuordnung.isRichtig()) { richtigeAntworten++; } } } werte.put("gestellteFragen", zuordnungen.size()); werte.put("richtigeAntworten", richtigeAntworten); werte.put("beantworteteFragen", beantworteteFragen); return new ModelAndView(werte, "spiel_zusammenfassung"); }, engine); Spark.get( "/admin/frage", (request, response) -> { Map<String, Object> werte = new HashMap<>(); werte.put("fragen", Frage.findeAlle()); return new ModelAndView(werte, "admin_frage"); }, engine); Spark.post( "/admin/frage/neu", (request, response) -> { String aufgabe = request.queryParams("aufgabe").trim(); if (!aufgabe.isEmpty()) { new Frage(aufgabe).speichern(); } response.redirect("/admin/frage"); return null; }); Spark.get( "/admin/frage/loeschen/:frage_id", (request, response) -> { Frage.findeNachId(request.params(":frage_id")).loeschen(); response.redirect("/admin/frage"); return null; }); Spark.get( "/admin/frage/aendern/:frage_id", (request, response) -> { Map<String, Object> werte = new HashMap<>(); werte.put("frage", Frage.findeNachId(request.params(":frage_id"))); return new ModelAndView(werte, "admin_frage_aendern"); }, engine); Spark.post( "/admin/frage/aendern", (request, response) -> { Frage zuAenderndeFrage = Frage.findeNachId(request.queryParams("frage_id")); zuAenderndeFrage.setAufgabe(request.queryParams("aufgabe").trim()); zuAenderndeFrage.speichern(); response.redirect("/admin/frage"); return null; }); Spark.get( "/admin/frage/:frage_id/antwort", (request, response) -> { Map<String, Object> werte = new HashMap<>(); Frage frage = Frage.findeNachId(request.params(":frage_id")); werte.put("frage", frage); werte.put("antworten", frage.getAntworten()); return new ModelAndView(werte, "admin_frage_antwort"); }, engine); Spark.post( "/admin/antwort/neu", (request, response) -> { Frage frage = Frage.findeNachId(request.queryParams("frage_id")); String loesung = request.queryParams("loesung"); String richtig = request.queryParams("richtig"); Antwort antwort; if (richtig != null) { for (Antwort andereAntwort : Antwort.findeNachFrage(frage)) { if (andereAntwort.isRichtig()) { andereAntwort.setRichtig(false); andereAntwort.speichern(); } } antwort = new Antwort(loesung, true, frage); } else { antwort = new Antwort(loesung, false, frage); } antwort.speichern(); response.redirect("/admin/frage/" + frage.getId() + "/antwort"); return null; }); Spark.post( "/admin/frage/:frage_id/antwort/richtig/aendern", (Request request, Response response) -> { int richtigeAntwortId = Integer.parseInt(request.queryParams("richtig").trim()); Frage frage = Frage.findeNachId(request.params(":frage_id")); for (Antwort antwort : Antwort.findeNachFrage(frage)) { if (antwort.isRichtig() && antwort.getId() != richtigeAntwortId) { antwort.setRichtig(false); antwort.speichern(); } else if (!antwort.isRichtig() && antwort.getId() == richtigeAntwortId) { antwort.setRichtig(true); antwort.speichern(); } } response.redirect("/admin/frage/" + frage.getId() + "/antwort"); return null; }); Spark.get( "/admin/antwort/loeschen/:antwort_id", (request, response) -> { Antwort antwort = Antwort.findeNachId(request.params(":antwort_id")); antwort.loeschen(); response.redirect("/admin/frage/" + antwort.getFrage().getId() + "/antwort"); return null; }); Spark.get( "/admin/antwort/aendern/:antwort_id", (request, response) -> { Map<String, Object> werte = new HashMap<>(); werte.put("antwort", Antwort.findeNachId(request.params(":antwort_id"))); return new ModelAndView(werte, "admin_frage_antwort_aendern"); }, engine); Spark.post( "/admin/antwort/aendern", (Request request, Response response) -> { Antwort antwort = Antwort.findeNachId(request.queryParams("antwort_id")); antwort.setLoesung(request.queryParams("loesung")); antwort.speichern(); response.redirect("/admin/frage/" + antwort.getFrage().getId() + "/antwort"); return null; }); }
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 ""; }); }
public static void throwViolations(List<ConstraintViolation> violations) throws HaltException { // TODO: Proper error messages ConstraintViolation first = violations.get(0); halt(400, first.getMessage()); }
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; }