public static void main(String[] args) {
    HelloWorldSpark hs = new HelloWorldSpark();
    Spark.get(
        "/",
        new Route() {

          @Override
          public Object handle(Request req, Response resp) throws Exception {
            return "hello World from Spark!";
          }
        });

    Spark.get("/test", (req, resp) -> "This is a test page!");

    Spark.get("/echo/:thing", (req, resp) -> req.params(":thing"));

    Spark.get("/form", (req, resp) -> hs.getForm());

    Spark.post(
        "/form",
        (req, resp) -> {
          String fruit = req.queryParams("fruit");
          if (StringUtils.isNotEmpty(fruit)) {
            return "Your favorite fruit is " + fruit;
          } else {
            return "Your did not pick any fruit";
          }
        });
  }
Example #2
0
  public static void main(String[] args) {
    Spark.get(
        new Route("/") {
          @Override
          public Object handle(final Request request, final Response response) {
            return "Hello World\n";
          }
        });

    Spark.get(
        new Route("/test") {
          @Override
          public Object handle(final Request request, final Response response) {
            return "This is a test page\n";
          }
        });

    Spark.get(
        new Route("/echo/:thing") {
          @Override
          public Object handle(final Request request, final Response response) {
            return request.params(":thing");
          }
        });
  }
  public static void main(String[] args) {

    Spark.get(
        new Route("/") {
          @Override
          public Object handle(Request request, Response response) {
            // TODO Auto-generated method stub
            return "Hello world Generic";
          }
        });

    Spark.get(
        new Route("/test") {
          @Override
          public Object handle(Request request, Response response) {
            // TODO Auto-generated method stub
            return "Hello world test url of spark project";
          }
        });

    Spark.get(
        new Route("/test/:thing") {
          @Override
          public Object handle(Request request, Response response) {
            // TODO Auto-generated method stub
            return "Test url with wild char or params:: " + request.params(":thing");
          }
        });
  }
Example #4
0
  public static void main(String args[]) {

    Spark.options(
        "/*",
        (request, response) -> {
          String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
          if (accessControlRequestHeaders != null) {
            response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
          }

          String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
          if (accessControlRequestMethod != null) {
            response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
          }

          return "OK";
        });

    Spark.before(
        (request, response) -> {
          response.header("Access-Control-Allow-Origin", "*");
        });

    post(
        "/locacion/new",
        (request, response) -> {
          if (request.contentType().equals("application/json")) {

            System.out.println(request.body());
            System.out.println("--------------- conversion a java-------------------");
            System.out.println(GsonSingleton.Instance().fromJson(request.body(), Location.class));
            DB.getInstance().insertLocation(request.body());

          } else {
            response.status(401);
            return "A json must be sent";
          }
          return "registration Successful";
        });

    get(
        "/locacion/search",
        (request, response) -> {
          response.type("application/json");

          return DB.getInstance()
              .SearchLocation(
                  Double.parseDouble(request.queryParams("latitude")),
                  Double.parseDouble(request.queryParams("longitude")));
        });

    get(
        "/locacion/all",
        (request, response) -> {
          response.type("application/json");

          return DB.getInstance().getAllInteresPoints();
        });
  }
  public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloSparkFreemarker.class, "/");

    Spark.get(
        "/",
        new Route() {
          public Object handle(Request request, Response response) throws Exception {
            try {
              Template template = configuration.getTemplate("hello.ftl");
              StringWriter writer = new StringWriter();

              Map<String, Object> helloMap = new HashMap<String, Object>();
              helloMap.put("name", "Giovanni");

              template.process(helloMap, writer);
              return writer;

            } catch (Exception e) {
              e.printStackTrace();
              return "Error 500";
            }
          }
        });
  }
  /** @param args */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldFreeMarkerStyle.class, "/");

    Spark.get(
        new Route("/") {

          public Object handle(final Request request, final Response response) {

            StringWriter writer = new StringWriter();

            try {
              Template helloTemplate = configuration.getTemplate("hello.ftl");

              Map<String, Object> helloMap = new HashMap<String, Object>();
              helloMap.put("name", "Puneeth");
              // System.out.println(helloMap.get("name"));
              helloTemplate.process(helloMap, writer);
              // System.out.println(writer);

            } catch (Exception e) {
              // TODO: handle exception
              halt(500);
              e.printStackTrace();
            }
            return writer;
          }
        });
  }
  public static void main(String[] args) {
    final Configuration config = new Configuration();
    config.setClassForTemplateLoading(HelloWorldFreemarkerStyle.class, "/");

    Spark.get(
        new Route("/") {
          @Override
          public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
              Template hello = config.getTemplate("hello.ftl");

              Map<String, Object> map = new HashMap<String, Object>();
              map.put("name", "World");
              hello.process(map, writer);

            } catch (Exception e) {
              halt(500);
              e.printStackTrace();
            }

            return writer;
          }
        });
  }
  public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
    final DB db = client.getDB("course");

    Spark.get(
        new Route("/") {
          @Override
          public Object handle(Request request, Response response) {
            DBCollection users = db.getCollection("user");
            DBObject user = users.findOne();
            StringWriter writer = new StringWriter();
            Configuration configuration = new Configuration();
            configuration.setClassForTemplateLoading(
                HelloWorldMongoDBSparkFreemarkerStyle.class, "/");

            try {
              Template template = configuration.getTemplate("hello.ftl");
              template.process(user, writer);
            } catch (Exception e) {
              halt(100);
              e.printStackTrace();
            }

            return writer;
          }
        });
  }
Example #9
0
  public static void main(String[] args) {
    // writes your code here
    HashMap<String, User> users = new HashMap(); // creating list to hold users
    Spark.init();
    Spark.post(
        "/create-account",
        ((request, response) -> {
          String name = request.queryParams("username");
          String password = request.queryParams("password");

          Session session = request.session();
          session.attribute("username", name);

          if (users.get(name) == null) {
            User user = new User(); // creating new user
            user.name = name;
            user.password = password;
            users.put(name, user);
          }
          response.redirect("/");
          return "";
        }));
    Spark.get(
        "/",
        ((request, response) -> {
          Session session = request.session();
          String name = session.attribute("username");
          if (name != null) {
            HashMap m = new HashMap();
            m.put("count", users.size());
            m.put("accounts", users.values());
            return new ModelAndView(m, "logged-in.html");
          }
          HashMap m = new HashMap();
          return new ModelAndView(m, "not-logged-in.html");
        }),
        new MustacheTemplateEngine());
    Spark.post(
        "/logout",
        ((request, response) -> {
          Session session = request.session();
          session.invalidate();
          response.redirect("/");
          return "";
        }));
  }
  public static void main(String[] args) {

    Spark.get(
        new Route("/") {

          @Override
          public Object handle(Request request, Response response) {
            return "Hello World from Spark Web Romildo";
          }
        });
  }
Example #11
0
  private void start() {
    Spark.port(port);
    Spark.ipAddress(listen);
    Spark.staticFileLocation(view);
    logger.info("API Token: " + token);
    Spark.before(
        "/api/*",
        new Filter() {

          @Override
          public void handle(Request req, Response resp) throws Exception {
            if (!token.equals(req.queryParams("token"))) {
              Spark.halt(403);
            }
          }
        });
    new FullReportRoute(settings);
    new RunRoute(settings);
    new RunHTMLRoute(settings);
    new SearchHTMLRoute(settings);
  }
Example #12
0
  public static void main(String[] args) throws SQLException {
    final BeastConf beastConf = new BeastConf();
    for (int i = 1; i <= 16; i++)
      beastConf.addMysqlShard(
          String.format("jdbc:mysql://mysql-%d/kv%d", i, i)
              + "?useUnicode=true&useConfigs=maxPerformance"
              + "&characterEncoding=UTF-8&user=root&password=chamran");

    final MyBeastClient beast = new MyBeastClient(beastConf);

    Spark.port(9090);
    Spark.threadPool(200);
    // Spark.secure("/etc/sync-server/sahab", "sahab123",
    // "/etc/sync-server/sahab", "sahab123");

    Spark.get("/api/v1/hi", (request, response) -> "Hi:)");

    Spark.get(
        "/api/v1/approxsize",
        (request, response) -> {
          response.type("text/json");
          response.status(200); // Allow anyone
          return String.format("%,d", beast.approximatedSize());
        },
        new JsonTransformer());

    Spark.get(
        "/api/v1/get/:id",
        (request, response) -> {
          response.type("text/json; charset=UTF-8");
          response.status(200); // Allow anyone
          long l = Long.parseLong(request.params(":id"));
          Optional<byte[]> x = beast.get(l);
          return new String(GZip4Persian.uncompress(x.get()));
        },
        new JsonTransformer());
  }
 /** @param args */
 public static void main(String[] args) {
   // Default Port for spark is 4567
   // Calling a static method of spark class i.e get and giving it a route.
   // Route specifies the pattern that should match
   Spark.get(
       new Route("/") {
         // So when "/" is encountered, i.e. home. It calls the handle method
         // Handle method returns "Hello World from Spark" as the Response to the get request
         @Override
         public Object handle(final Request arg0, final Response arg1) {
           // TODO Auto-generated method stub
           return "Hello World from Spark";
         }
       });
 }
  public static void main(String[] args) {
    Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldSparkFreemarkerStyle.class, "/");

    try {
      Template helloTemplate = configuration.getTemplate("hello.ftl");
      StringWriter writer = new StringWriter();
      Map<String, Object> helloMap = new HashMap<String, Object>();
      helloMap.put("name", "freemarker");

      helloTemplate.process(helloMap, writer);
      // System.out.println(writer);
      spark.Spark.get("/hello", (req, res) -> writer);

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  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.setClassForTemplateLoading(HelloWorldMongodbSparkFreemarkerStyle.class, "/");

    MongoClient client = new MongoClient();

    MongoDatabase db = client.getDatabase("course");

    final MongoCollection<Document> coll = db.getCollection("hello");

    coll.drop();

    coll.insertOne(new Document("name", "Mongodb"));

    Spark.get(
        new Route("/") {

          @Override
          public Object handle(Request arg0, Response arg1) {
            StringWriter writer = new StringWriter();
            try {
              Template helloTemplate = configuration.getTemplate("hello.ftl");

              Document document = coll.find().first();

              helloTemplate.process(document, writer);

              // System.out.println(writer);

            } catch (Exception e) {
              halt(500);
              e.printStackTrace();
            }
            return writer;
          }
        });
  }
Example #17
0
  public static void main(String[] args) {

    // precisa de um package publico (pub)
    // onde ficam os css, js, imgs, conteúdo fixo
    Spark.staticFileLocation("/pub");

    // precisa de um package apresentacao (views)
    // onde ficam os HTML's
    MustacheTemplateEngine engine = new MustacheTemplateEngine("apresentacao");

    PaginaInicialControlador paginaInicial = new PaginaInicialControlador();

    // get ou post (get ler informações, post submeter informações)
    Spark.get("/", paginaInicial, engine);

    NovoControlador novoControlador = new NovoControlador();

    // abrir o form
    Spark.get("/novo", novoControlador, engine);

    SalvaControlador salvaControlador = new SalvaControlador();

    // submissão do form
    Spark.post("/salva", salvaControlador, engine);

    ListaControlador listaControlador = new ListaControlador();

    Spark.get("/lista", listaControlador, engine);

    ExcluiControlador excluiControlador = new ExcluiControlador();

    Spark.get("/exclui/:numero", excluiControlador, engine);

    // FotoControlador upador = new FotoControlador();
    // Spark.post("/recebefoto", upador);

  }
 @AfterClass
 public static void stopServer() {
   Spark.stop();
 }
Example #19
0
  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();
          }
        });
  }
Example #20
0
  public static void main(String[] args) throws IOException {
    String indexHTML = new String(Files.readAllBytes(Paths.get("index.html")));
    String createHTML = new String(Files.readAllBytes(Paths.get("create.html")));

    Spark.port(80);

    Spark.get(
        "/create-submit",
        (request, response) -> {
          Game newGame =
              new Game(request.queryParams("name"), Integer.valueOf(request.queryParams("size")));
          games.put(newGame.hashCode(), newGame);
          // response.redirect("/game/" + newGame.hashCode());
          response.redirect("/");
          return "success";
        });

    Spark.get(
        "/create",
        (request, response) -> {
          return createHTML;
        });

    Spark.get(
        "/game/:gameID/:player/:x/:y/:xOffset/:yOffset",
        (request, response) -> {
          Game game = games.get(Integer.parseInt(request.params(":gameID")));
          game.update(
              Integer.parseInt(request.params(":x")),
              Integer.parseInt(request.params(":y")),
              request.params(":player"),
              Integer.parseInt(request.params(":xOffset")),
              Integer.parseInt(request.params(":yOffset")));
          return game.draw(request.params(":player"));
        });

    Spark.get(
        "/game/:gameID/:player/:x/:y",
        (request, response) -> {
          Game game = games.get(Integer.parseInt(request.params(":gameID")));
          game.update(
              Integer.parseInt(request.params(":x")),
              Integer.parseInt(request.params(":y")),
              request.params(":player"),
              1,
              1);
          return game.draw(request.params(":player"));
        });

    Spark.get(
        "/game/:gameID/:player",
        (request, response) -> {
          return games
              .get(Integer.parseInt(request.params(":gameID")))
              .draw(request.params(":player"));
        });

    Spark.get(
        "/game/:gameID",
        (request, response) -> {
          return "";
        });

    // default route, home page
    Spark.get(
        "/",
        (request, response) -> {
          StringBuilder gameList = new StringBuilder();

          ArrayList<Game> gamesList = new ArrayList<>(games.values());
          Collections.sort(gamesList);
          for (Game game : gamesList) {
            gameList.append(
                "			"
                    + game.getName()
                    + "\t<a href=\"/game/"
                    + game.hashCode()
                    + "/green\">Green</a>\t<a href=\"/game/"
                    + game.hashCode()
                    + "/red\">Red</a>\n"
                    + "			</br>\n");
          }
          return indexHTML.replace("<!--INSERT_GAME_LIST-->", gameList.toString());
        });
  }
Example #21
0
 @Override
 public void init() {
   // accept any type except JSON
   Spark.get("/*", "*/*;q=1.0, application/json;q=0.0", new ServeStaticFileRoute("/index.html"));
 }
Example #22
0
  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;
        });
  }
Example #23
0
 protected void after() {
   Spark.stop();
 }
Example #24
0
  public static void main(String[] args) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:h2:./main");
    Statement stmt = conn.createStatement();
    stmt.execute("CREATE TABLE IF NOT EXISTS beers (name VARCHAR, type VARCHAR, id IDENTITY)");

    Spark.get(
        "/",
        ((request, response) -> {
          Session session = request.session();
          String username = session.attribute("username");
          if (username == null) {
            return new ModelAndView(new HashMap(), "not-logged-in.html");
          }
          HashMap m = new HashMap();
          m.put("username", username);
          m.put("beers", selectBeer(conn));
          return new ModelAndView(m, "logged-in.html");
        }),
        new MustacheTemplateEngine());
    Spark.post(
        "/login",
        ((request, response) -> {
          String username = request.queryParams("username");
          Session session = request.session();
          session.attribute("username", username);
          response.redirect("/");
          return "";
        }));
    Spark.post(
        "/create-beer",
        ((request, response) -> {
          // Beer beer = new Beer();
          // beer.id = beers.size() + 1;
          String name = request.queryParams("beername");
          String type = request.queryParams("beertype");
          insertBeer(conn, name, type);
          response.redirect("/");
          return "";
        }));
    Spark.post(
        "/delete-beer",
        ((request, response) -> {
          String id = request.queryParams("beerid");
          int idNum = Integer.valueOf(id);

          deleteBeer(conn, idNum);

          //                    try {
          //                        beers.remove(idNum-1);
          //                        for (int i = 0; i < beers.size(); i++) {
          //                            beers.get(i).id = i + 1;
          //                        }
          //                    } catch (Exception e) {
          //
          //                    }

          response.redirect("/");
          return "";
        }));
    Spark.post(
        "edit-beer",
        ((request, response) -> {
          String id = request.queryParams("beerid");
          int idNum = Integer.valueOf(id);
          String name = request.queryParams("beername");
          String type = request.queryParams("beertype");

          editBeer(conn, idNum, name, type);

          response.redirect("/");
          return "";
        }));
  }