Esempio n. 1
0
    public static void main(String[] args) {

        port(Integer.valueOf(System.getenv("PORT")));

        get("/", (request, response) -> {

            // Create a rest client
            TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);

            // Get the main account (The one we used to authenticate the client)
            Account mainAccount = client.getAccount();

            // Get all accounts including sub accounts
            AccountList accountList = client.getAccounts();

            // All lists implement an iterable interface, you can use the foreach
            // syntax on them
            for (Account a : accountList) {
                System.out.println(a.getFriendlyName());
            }

            // Send an sms (using the new messages endpoint)
            MessageFactory messageFactory = mainAccount.getMessageFactory();
            List<NameValuePair> messageParams = new ArrayList<NameValuePair>();
            messageParams.add(new BasicNameValuePair("To", "+19172164313; // Replace with a valid phone number
            messageParams.add(new BasicNameValuePair("From", "+19142054512")); // Replace with a valid phone
            // number in your account
            messageParams.add(new BasicNameValuePair("Body", "Hello from Fabian Patino"));
            messageFactory.create(messageParams);

            return "Hello From Fabian Patino";
        });
Esempio n. 2
0
  protected void initWebServer(ServiceProvider serviceProvider, IdeArguments ideArguments) {
    port(ideArguments.getPort());
    staticFileLocation("/public");
    externalStaticFileLocation(staticFolderForSpark);
    System.out.println("Reports are in: " + reportFolder);

    new DeviceController(serviceProvider.deviceService());
    new DomSnapshotController(serviceProvider.domSnapshotService());
    new FileBrowserController(serviceProvider.fileBrowserService());
    new SettingsController(serviceProvider.settingsService());
    new ProfilesController(serviceProvider.profilesService(), serviceProvider.settingsService());
    new TaskResultController(serviceProvider.taskResultService());
    new TesterController(serviceProvider.testerService());
    new HelpController();

    scheduledExecutorService.scheduleAtFixedRate(
        new TaskResultsStorageCleanupJob(
            taskResultsStorage,
            ideArguments.getKeepLastResults(),
            ideArguments.getZombieResultsTimeout(),
            reportFolder),
        ideArguments.getCleanupPeriodInMinutes(),
        ideArguments.getCleanupPeriodInMinutes(),
        TimeUnit.MINUTES);

    if (ideArguments.getProfile() != null) {
      serviceProvider.profilesService().loadProfile(ideArguments.getProfile());
    }
  }
Esempio n. 3
0
  public void start() {
    port(port);

    Map<String, String> map = new HashMap<>();

    staticFileLocation("/public");
    get("/", (req, res) -> new ModelAndView(map, "main"), new JadeTemplateEngine());
  }
  public static void main(String[] args) {

    port(Integer.valueOf(System.getenv("PORT")));
    staticFileLocation("/public");

    // get("/hello", (req, res) -> "Hello World");

    // get("/hello", (req, res) -> {
    //   RelativisticModel.select();

    //   String energy = System.getenv().get("ENERGY");

    //   Amount<Mass> m = Amount.valueOf(energy).to(KILOGRAM);
    //   return "E=mc^2: " + energy + " = " + m.toString();
    // });

    // get("/", (request, response) -> {
    //         Map<String, Object> attributes = new HashMap<>();
    //         attributes.put("message", "Hello World!");

    //         return new ModelAndView(attributes, "index.ftl");
    //     }, new FreeMarkerEngine());

    get(
        "/db",
        (req, res) -> {
          Connection connection = null;
          Map<String, Object> attributes = new HashMap<>();
          try {
            connection = DatabaseUrl.extract().getConnection();

            Statement stmt = connection.createStatement();
            stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
            stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
            ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");

            ArrayList<String> output = new ArrayList<String>();
            while (rs.next()) {
              output.add("Read from DB: " + rs.getTimestamp("tick"));
            }

            attributes.put("results", output);
            return new ModelAndView(attributes, "db.ftl");
          } catch (Exception e) {
            attributes.put("message", "There was an error: " + e);
            return new ModelAndView(attributes, "error.ftl");
          } finally {
            if (connection != null)
              try {
                connection.close();
              } catch (SQLException e) {
              }
          }
        },
        new FreeMarkerEngine());
  }
Esempio n. 5
0
 public static void main(String[] args) {
   port(getHerokuAssignedPort());
   get(
       "/hello",
       new Route() {
         @Override
         public Object handle(Request request, Response response) {
           return "Hello World!!";
         }
       });
 }
  public static void main(String[] args) {

    Sql2o sql2o = new Sql2o("jdbc:mysql://192.168.2.11:3306/db_school", "admin", "admin");

    String ipAddress = Optional.ofNullable(System.getenv("OPENSHIFT_DIY_IP")).orElse("0.0.0.0");
    int ipPort =
        Integer.parseInt(Optional.ofNullable(System.getenv("OPENSHIFT_DIY_PORT")).orElse("8008"));

    ipAddress(ipAddress);
    port(ipPort);

    new StudentController(new StudentService(sql2o));
    new SchoolClassController(new SchoolClassService(sql2o));
    new SchoolTimeTableController(new SchoolTimeTableService(sql2o));
  }
Esempio n. 7
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);
  }
Esempio n. 8
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);
  }
Esempio n. 9
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());
  }
Esempio n. 10
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());
        });
  }