Пример #1
0
  public static void main(final String[] args) {
    setPort(50845);
    externalStaticFileLocation("public"); // Static files

    new RecoController();
    new UserController();
    new TagController();

    get(
        "/",
        (request, response) -> {
          response.redirect("/index.html");
          return "";
        });

    before(
        (request, response) -> {
          HibernateUtil.getSession().beginTransaction();
        });

    after(
        (request, response) -> {
          HibernateUtil.getSession().getTransaction().commit();
          HibernateUtil.closeSession();
        });

    exception(
        Exception.class,
        (e, request, response) -> {
          HibernateUtil.getSession().getTransaction().rollback();
          HibernateUtil.closeSession();
          response.status(500);
        });
  }
Пример #2
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();
        });
  }
Пример #3
0
  public static void main(String... args) throws Exception {
    // read config
    File in = new File(args[0]);
    staticSiteRequest = JsonUtilities.objectMapper.readValue(in, StaticSiteRequest.class);

    // read network
    File cacheDir = new File("cache");
    if (!cacheDir.exists()) cacheDir.mkdir();
    TransportNetworkCache cache = new TransportNetworkCache(args[1], cacheDir);
    if (staticSiteRequest.request.scenario != null
        || staticSiteRequest.request.scenarioId != null) {
      network =
          cache.getNetworkForScenario(
              staticSiteRequest.transportNetworkId, staticSiteRequest.request);
    } else {
      network = cache.getNetwork(staticSiteRequest.transportNetworkId);
    }

    // precompute metadata and stop tree
    ByteArrayOutputStream mbaos = new ByteArrayOutputStream();
    StaticMetadata sm = new StaticMetadata(staticSiteRequest, network);
    sm.writeMetadata(mbaos);
    metadata = mbaos.toByteArray();

    ByteArrayOutputStream sbaos = new ByteArrayOutputStream();
    sm.writeStopTrees(sbaos);
    stopTrees = sbaos.toByteArray();

    TransitiveNetwork tn = new TransitiveNetwork(network.transitLayer);
    ByteArrayOutputStream tnbaos = new ByteArrayOutputStream();
    JsonUtilities.objectMapper.writeValue(tnbaos, tn);
    transitive = tnbaos.toByteArray();

    // optionally allow specifying port
    if (args.length == 3) {
      port(Integer.parseInt(args[2]));
    }

    // add cors header
    before((req, res) -> res.header("Access-Control-Allow-Origin", "*"));

    get("/query.json", StaticServer::getQuery);
    get("/stop_trees.dat", StaticServer::getStopTrees);
    get("/transitive.json", StaticServer::getTransitiveNetwork);
    get("/:x/:y", StaticServer::getOrigin);
  }
Пример #4
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);
  }
Пример #5
0
  @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);
        });
  }
Пример #6
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;
        });
  }