private void handleJson(HttpServerRequest req) {
   String result = Json.encode(Collections.singletonMap("message", "Hello, world!"));
   int contentLength = result.getBytes(StandardCharsets.UTF_8).length;
   req.response().putHeader("Content-Type", "application/json; charset=UTF-8");
   req.response().putHeader("Content-Length", String.valueOf(contentLength));
   req.response().end(result);
 }
 @Override
 public String getPathInfo() {
   try {
     return urlDecode(request.params().get("param0"));
   } catch (URISyntaxException e) {
     return request.params().get("param0");
   }
 }
 @Override
 public void handle(HttpServerRequest req) {
   Path p = Paths.get(assetRoot, req.path().substring(1));
   if (fileSystem.existsSync(p.toString())) {
     super.handle(req);
   } else {
     req.response().end("File Not Found!");
   }
 }
 private void replyForError(JsonObject message) {
   if (message != null) {
     log.error(message.getString("message"));
     request.response().end("{}");
   } else {
     log.error("Empty Request");
     request.response().setStatusCode(400);
   }
   cleanup(requestId);
 }
 @Override
 public void handle(HttpServerRequest request) {
   request.response().setStatusCode(200);
   request.response().putHeader(WebStrings.CONTENT_TYPE, WebStrings.APP_JSON);
   log.info("Put Object Request");
   String reqId = UUID.randomUUID().toString();
   UploadEncObjectReplyHandler replyHandler = new UploadEncObjectReplyHandler(reqId, request);
   UploadEncObjectBodyHandler bodyHanlder = new UploadEncObjectBodyHandler(reqId, replyHandler);
   replyHandlers.put(reqId, replyHandler);
   bodyHandlers.put(reqId, bodyHanlder);
   request.bodyHandler(bodyHanlder);
 }
 private void isUserOrAdmin(
     HttpServerRequest request, UserInfos user, final Handler<Boolean> handler) {
   final String userId = request.params().get("userId");
   if (user.getUserId().equals(userId)) {
     handler.handle(true);
     return;
   }
   final UserInfos.Function adminLocal = getFunction(user, handler);
   if (adminLocal == null) return;
   String query =
       "MATCH (s:Structure)<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u:User {id : {userId}}) "
           + "WHERE s.id IN {structures} "
           + "RETURN count(*) > 0 as exists ";
   JsonObject params =
       new JsonObject()
           .putArray("structures", new JsonArray(adminLocal.getScope().toArray()))
           .putString("userId", userId);
   Neo4j.getInstance()
       .execute(
           query,
           params,
           new Handler<Message<JsonObject>>() {
             @Override
             public void handle(Message<JsonObject> message) {
               JsonArray res = message.body().getArray("result");
               handler.handle(
                   "ok".equals(message.body().getString("status"))
                       && res != null
                       && res.size() == 1
                       && res.<JsonObject>get(0).getBoolean("exists", false));
             }
           });
 }
  private boolean basicAuth(HttpServerRequest request, String encodedAuth) {
    byte[] authBytes = Base64.decodeBase64(encodedAuth);
    String decodedString = new String(authBytes);
    String[] splitAuth = StringUtils.split(StringUtils.trim(decodedString), ":"); // $NON-NLS-1$

    if (splitAuth.length != 2) return false;

    if (fileBasicAuthData.containsKey(splitAuth[0])) {
      String storedHash = new String(Base64.decodeBase64(fileBasicAuthData.get(splitAuth[0])));

      MessageDigest digest;
      try {
        digest = MessageDigest.getInstance("SHA-256"); // $NON-NLS-1$
        digest.update(splitAuth[1].getBytes());

        String receivedHash = new String(digest.digest());

        if (storedHash.equals(receivedHash)) {
          return true;
        }
      } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e.getCause());
      }
    }

    request
        .response()
        .headers()
        .add(
            "WWW-Authenticate",
            "Basic realm=\"" + config.getRealm() + "\""); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    return false;
  }
 @Override
 public void handle(HttpServerRequest request) {
   if (!config.isAuthenticationEnabled() || authenticate(request)) {
     super.handle(request);
   } else {
     notAuthorised(request.response());
   }
 }
Example #9
0
 static void setCORS(HttpServerRequest req) {
   String origin = req.getHeader("Origin");
   if (origin == null) {
     origin = "*";
   }
   req.response.putHeader("Access-Control-Allow-Origin", origin);
   req.response.putHeader("Access-Control-Allow-Credentials", "true");
 }
 @Override
 public void handle(HttpServerRequest req) {
   String path = req.path();
   switch (path.charAt(1)) {
     case 'p':
       handlePlainText(req);
       break;
     case 'j':
       handleJson(req);
       break;
     case 'd':
       handleDbMongo(req);
       break;
     default:
       req.response().setStatusCode(404);
       req.response().end();
   }
 }
 private void authorizeOwner(
     HttpServerRequest request, UserInfos user, String serviceMethod, Handler<Boolean> handler) {
   String id = request.params().get("id");
   if (id != null && !id.trim().isEmpty()) {
     String query = "{ \"_id\": \"" + id + "\", \"owner\": \"" + user.getUserId() + "\" }";
     executeCountQuery(
         request, DocumentDao.DOCUMENTS_COLLECTION, new JsonObject(query), 1, handler);
   } else {
     handler.handle(false);
   }
 }
 @Override
 public void handle(JsonObject message) {
   if (message.containsField("error")) {
     replyForError(message);
   }
   message.removeField(MessageUtils.FROM);
   message.removeField(MessageUtils.TO);
   message.removeField(MessageUtils.COMTYPE);
   message.removeField(MessageUtils.MSGID);
   message.removeField(MessageUtils.MSGTYPE);
   request.response().end(message.toString());
   cleanup(requestId);
 }
  private boolean authenticate(HttpServerRequest request) {
    String authString = request.headers().get(HttpHeaders.AUTHORIZATION);

    if (authString == null) return false;

    String[] basicAuth = StringUtils.splitByWholeSeparator(authString, "Basic "); // $NON-NLS-1$

    if (basicAuth.length == 1) {
      return basicAuth(request, basicAuth[0]);
    }

    return false;
  }
  /**
   * Does something with a session id. It will use the session id provided by the client inside the
   * http server request. If it cannot find it, it will create a new session.
   *
   * @param req The http server request.
   * @param handler The handler to call with the created or found session id.
   */
  public void withSessionId(final HttpServerRequest req, final Handler<String> handler) {
    String value = req.headers().get("Cookie");
    if (value != null) {
      Set<Cookie> cookies = new CookieDecoder().decode(value);
      for (final Cookie cookie : cookies) {
        if (cookieField.equals(cookie.getName())) {
          handler.handle(cookie.getValue());
          return;
        }
      }
    }

    startSession(req, handler);
  }
  private void authorizeCommentOwner(
      HttpServerRequest request,
      UserInfos user,
      String serviceMethod,
      final Handler<Boolean> handler) {
    final String id = request.params().get("id");
    final String commentId = request.params().get("commentId");
    JsonObject query =
        new JsonObject(
            "{ \"_id\": \""
                + id
                + "\", \"comments.id\": \""
                + commentId
                + "\", \"comments.author\": \""
                + user.getUserId()
                + "\"  }");

    if (commentId != null && !commentId.trim().isEmpty()) {
      executeCountQuery(request, DocumentDao.DOCUMENTS_COLLECTION, query, 1, handler);
    } else {
      handler.handle(false);
    }
  }
Example #16
0
 @Post("/function/:profile")
 @SecuredAction("profile.create.function")
 public void createFunction(final HttpServerRequest request) {
   final String profile = request.params().get("profile");
   bodyToJson(
       request,
       pathPrefix + "createFunction",
       new Handler<JsonObject>() {
         @Override
         public void handle(JsonObject event) {
           profileService.createFunction(
               profile, event, notEmptyResponseHandler(request, 201, 409));
         }
       });
 }
  private void authorizeRevisionOwner(
      HttpServerRequest request,
      UserInfos user,
      String serviceMethod,
      final Handler<Boolean> handler) {
    final String revisionId = request.params().get("revisionId");
    JsonObject query =
        new JsonObject(
            "{ \"_id\": \"" + revisionId + "\", \"userId\": \"" + user.getUserId() + "\" }");

    if (revisionId != null && !revisionId.trim().isEmpty()) {
      executeCountQuery(request, Workspace.REVISIONS_COLLECTION, query, 1, handler);
    } else {
      handler.handle(false);
    }
  }
 private void authorizeGetDocument(
     HttpServerRequest request, UserInfos user, String serviceMethod, Handler<Boolean> handler) {
   String id = request.params().get("id");
   if (id != null && !id.trim().isEmpty()) {
     String query =
         "{ \"_id\": \""
             + id
             + "\", \"$or\" : [{ \"owner\": \""
             + user.getUserId()
             + "\"}, { \"protected\" : true}, { \"public\" : true}, {\"shared\" : { \"$elemMatch\" : "
             + orSharedElementMatch(user, serviceMethod)
             + "}}]}";
     executeCountQuery(
         request, DocumentDao.DOCUMENTS_COLLECTION, new JsonObject(query), 1, handler);
   } else {
     handler.handle(false);
   }
 }
 private void executeCountQuery(
     final HttpServerRequest request,
     String collection,
     JsonObject query,
     final int expectedCountResult,
     final Handler<Boolean> handler) {
   request.pause();
   mongo.count(
       collection,
       query,
       new Handler<Message<JsonObject>>() {
         @Override
         public void handle(Message<JsonObject> event) {
           request.resume();
           JsonObject res = event.body();
           handler.handle(
               res != null
                   && "ok".equals(res.getString("status"))
                   && expectedCountResult == res.getInteger("count"));
         }
       });
 }
  private void handleDbMongo(final HttpServerRequest req) {
    int queriesParam = 1;
    try {
      queriesParam = Integer.parseInt(req.params().get("queries"));
    } catch (NumberFormatException e) {
      // do nothing
    }

    final MongoHandler dbh = new MongoHandler(req, queriesParam);
    final Random random = ThreadLocalRandom.current();

    for (int i = 0; i < queriesParam; i++) {
      vertx
          .eventBus()
          .send(
              "hello.persistor",
              new JsonObject()
                  .putString("action", "findone")
                  .putString("collection", "world")
                  .putObject(
                      "matcher", new JsonObject().putNumber("id", (random.nextInt(10000) + 1))),
              dbh);
    }
  }
 private void authorizeDocuments(
     HttpServerRequest request, UserInfos user, String serviceMethod, Handler<Boolean> handler) {
   String ids = request.params().get("ids");
   if (ids != null && !ids.trim().isEmpty()) {
     JsonArray idsArray = new JsonArray(ids.split(","));
     String query =
         "{ \"_id\": { \"$in\" : "
             + idsArray.encode()
             + "}, "
             + "\"$or\" : [{ \"owner\": \""
             + user.getUserId()
             + "\"}, {\"shared\" : { \"$elemMatch\" : "
             + orSharedElementMatch(user, serviceMethod)
             + "}}]}";
     executeCountQuery(
         request,
         DocumentDao.DOCUMENTS_COLLECTION,
         new JsonObject(query),
         idsArray.size(),
         handler);
   } else {
     handler.handle(false);
   }
 }
Example #22
0
 static void setJSESSIONID(AppConfig config, HttpServerRequest req) {
   String cookies = req.getHeader("Cookie");
   if (config.isInsertJSESSIONID()) {
     // Preserve existing JSESSIONID, if any
     if (cookies != null) {
       String[] parts;
       if (cookies.contains(";")) {
         parts = cookies.split(";");
       } else {
         parts = new String[] {cookies};
       }
       for (String part : parts) {
         if (part.startsWith("JSESSIONID")) {
           cookies = part + "; path=/";
           break;
         }
       }
     }
     if (cookies == null) {
       cookies = "JSESSIONID=dummy; path=/";
     }
     req.response.putHeader("Set-Cookie", cookies);
   }
 }
 @Override
 public String getRequestURI() {
   return request.uri();
 }
Example #24
0
 private void processRequest(String targetID, HttpServerRequest req) {
   String result = retrieveDetails(targetID);
   if (result != null) req.response().end(result);
   else req.response().end("No response received");
 }
 public VertxHttpRequestWrapper(HttpServerRequest request) {
   this.request = request;
   this.response = request.response();
 }
 @Override
 public String getMethod() {
   return request.method();
 }
 private void isAdmin(HttpServerRequest request, UserInfos user, Handler<Boolean> handler) {
   UserInfos.Function adminLocal = getFunction(user, handler);
   if (adminLocal == null) return;
   String structureId = request.params().get("structureId");
   handler.handle(adminLocal.getScope().contains(structureId));
 }
 @Override
 public String getQueryString() {
   return request.query();
 }
 @Override
 public void setContentType(String contentType) {
   request.response().putHeader("Content-Type", contentType);
 }
  /** text/javascript text/css text/html; charset=GBK */
  @Override
  public void handle(final HttpServerRequest req) {

    final HttpServerResponse res = req.response();

    String uri = req.path().substring(1);

    if (uri.startsWith("web")) {
      uri = uri.substring(4);
    }
    if (uri.isEmpty()) {
      uri = indexPage;
    }
    String ext = Utils.getFileExtWithDot(uri);
    if (".js".equals(ext) || ".css".equals(ext) || ".html".equals(ext)) {
      int i = 0;
      if (".css".equals(ext)) {
        i = 1;
      } else {
        i = 2;
      }
      res.headers().set("content-type", ctary[i]);
      String finalFile = webRootPath.resolve(uri).toString();

      //      if(fileSystem.existsSync(finalFile)){
      //        fileSystem.readFile(finalFile, new AsyncResultHandler<Buffer>() {
      //          public void handle(AsyncResult<Buffer> ar) {
      //            if (ar.succeeded()) {
      //              res.headers().set("content-length", ar.result().length() + "");
      //              res.end(ar.result());
      //            } else {
      //              logger.error("Failed to open file", ar.cause());
      //              res.end("File Read Error!");
      //            }
      //          }
      //        });
      //      } else {
      //        res.end("File Not Found!");
      //      }

      fileSystem.open(
          finalFile,
          new AsyncResultHandler<AsyncFile>() {
            public void handle(AsyncResult<AsyncFile> ar) {
              if (ar.succeeded()) {
                AsyncFile asyncFile = ar.result();
                res.setChunked(true);
                Pump.createPump(asyncFile, res).start();
                asyncFile.endHandler(
                    new VoidHandler() {
                      public void handle() {
                        res.end();
                      }
                    });
              } else {
                logger.error("Failed to open file", ar.cause());
                res.end("File Not Found!");
              }
            }
          });
    } else {
      res.sendFile(webRootPath.resolve(uri).toString());
    }
  }