示例#1
0
  public void initRoutes() {
    get("api/devices", (request, response) -> deviceService.getAllDevices(), toJson());

    post(
        "api/devices",
        (req, res) -> {
          DeviceRequest createDeviceRequest = mapper.readValue(req.body(), DeviceRequest.class);
          deviceService.createDevice(createDeviceRequest);
          return "created";
        });

    get(
        "api/devices/:deviceId",
        (req, res) -> deviceService.getDevice(req.params("deviceId")),
        toJson());

    put(
        "api/devices/:deviceId",
        (req, res) -> {
          String deviceId = req.params("deviceId");
          if (deviceId != null && !deviceId.trim().isEmpty()) {
            DeviceRequest createDeviceRequest = mapper.readValue(req.body(), DeviceRequest.class);
            deviceService.changeDevice(deviceId, createDeviceRequest);
            return "modified";
          } else throw new RuntimeException("Incorrect request, missing device id");
        });

    delete(
        "api/devices/:deviceId",
        (req, res) -> {
          String deviceId = req.params("deviceId");
          if (deviceId != null && !deviceId.trim().isEmpty()) {
            deviceService.shutdownDevice(deviceId);
            return "Delete device " + deviceId;
          } else throw new RuntimeException("Incorrect request, missing device id");
        },
        toJson());

    post(
        "api/devices/:deviceId/tasks",
        (req, res) -> {
          String deviceId = req.params("deviceId");
          String requestBody = req.body();

          DeviceTask task = DeviceTaskParser.parseTask(mapper, mapper.readTree(requestBody));
          return deviceService.executeTask(deviceId, task);
        },
        toJson());

    get(
        "api/devices/:deviceId/tasks",
        (req, res) -> {
          String deviceId = req.params("deviceId");
          return deviceService.getCurrentTasks(deviceId);
        },
        toJson());
  }
示例#2
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);
        });
  }
示例#3
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();
          }
        });
  }
示例#4
0
  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 "";
        });
  }