private void isSuperAdmin(UserInfos user, Handler<Boolean> handler) {
   Map<String, UserInfos.Function> functions = user.getFunctions();
   if (functions == null || functions.isEmpty()) {
     handler.handle(false);
     return;
   }
   handler.handle(functions.containsKey(DefaultFunctions.SUPER_ADMIN));
 }
 /**
  * Delegates handling the given event to the {@link Handler} this object is wrapping
  *
  * @param event the event to handle
  */
 @Override
 public void handle(Object event) {
   LOGGER.log(LEVEL, Utils.toString(handler) + ".handle(" + Utils.toString(event) + ")");
   Handler<Object> h = getHandler();
   if (h == null) {
     return;
   }
   h.handle(event);
 }
Example #3
0
 private void decOustanding() {
   if (outstandingTasks.decrementAndGet() == 0) {
     closedHandler.handle(null);
     // Now there are no more oustanding tasks we can close the context
     close();
   }
 }
 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));
             }
           });
 }
Example #5
0
 void handleException(Exception e) {
   if (exceptionHandler != null) {
     exceptionHandler.handle(e);
   } else {
     vertx.reportException(e);
   }
 }
  @Override
  public void handle(Message<? extends Object> event) {
    final Object payload = event.body;
    //		this.logger.info("TARGETPUMP recv = "+payload);

    if (payload instanceof Buffer) {
      writeBuffer((Buffer) payload);
    } else if (payload instanceof String) {
      if (PumpStates.END.name().equals(payload)) {
        this.eb.unregisterHandler(ebId);
        //				this.eb.send(address, PumpStates.END.name());
      } else if (PumpStates.SOURCEPUMPREADY.name().equals(payload)) {
        this.setSourcePumpReady();
      }
      /*
      else if(PumpStates.SOURCEPUMPISFULL.name().equals(payload)){
      	this.setTargetPumpFull();
      }else if(PumpStates.SOURCEPUMPISEMPTY.name().equals(payload)){
      	this.setTargetPumpEmpty();
      }
      */
    } else if (payload instanceof JsonObject) {

    } else {
      exceptionHandler.handle(
          new IllegalStateException(
              "event of type " + event.getClass().getCanonicalName() + " is unknown!"));
    }
  }
  private void setTargetPumpEmpty() {
    TargetPumpStub.this.targetPumpIsFull = false;

    if (drainHandler != null) {
      drainHandler.handle(null);
      drainHandler = null;
    }
  }
 void handleException(Exception e) {
   checkThread();
   if (exceptionHandler != null) {
     exceptionHandler.handle(e);
   } else {
     log.error("Unhandled exception", e);
   }
 }
 void handleResponse(HttpClientResponse resp) {
   try {
     if (resp.statusCode == 100) {
       if (continueHandler != null) {
         continueHandler.handle(null);
       }
     } else {
       respHandler.handle(resp);
     }
   } catch (Throwable t) {
     if (t instanceof Exception) {
       handleException((Exception) t);
     } else {
       log.error("Unhandled exception", t);
     }
   }
 }
 private UserInfos.Function getFunction(UserInfos user, Handler<Boolean> handler) {
   Map<String, UserInfos.Function> functions = user.getFunctions();
   if (functions == null || functions.isEmpty()) {
     handler.handle(false);
     return null;
   }
   if (functions.containsKey(DefaultFunctions.SUPER_ADMIN)) {
     handler.handle(true);
     return null;
   }
   UserInfos.Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL);
   if (adminLocal == null || adminLocal.getScope() == null) {
     handler.handle(false);
     return null;
   }
   return adminLocal;
 }
Example #11
0
 protected void handleClosed() {
   if (closedHandler != null) {
     setContext();
     try {
       closedHandler.handle(null);
     } catch (Throwable t) {
       handleHandlerException(t);
     }
   }
 }
Example #12
0
 public void deployModuleFromZip(
     String zipFileName, JsonObject config, int instances, Handler<String> doneHandler) {
   final String modName = zipFileName.substring(0, zipFileName.length() - 4);
   ModuleIdentifier modID = new ModuleIdentifier("__vertx_tmp#" + modName + "#__vertx_tmp");
   if (unzipModule(modID, new ModuleZipInfo(false, zipFileName), false)) {
     deployModule(modID.toString(), config, instances, doneHandler);
   } else {
     doneHandler.handle(null);
   }
 }
Example #13
0
 void handleWebsocketConnect(DefaultServerWebSocket ws) {
   try {
     if (wsHandler != null) {
       setContext();
       wsHandler.handle(ws);
       this.ws = ws;
     }
   } catch (Throwable t) {
     handleHandlerException(t);
   }
 }
 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);
   }
 }
Example #15
0
 @Override
 public void handle(final YokeHttpServerRequest request, final Handler<Object> next) {
   if ("/favicon.ico".equals(request.path())) {
     for (Map.Entry<String, Object> header : icon.headers.entrySet()) {
       request.response().putHeader(header.getKey(), header.getValue());
     }
     request.response().end(icon.body);
   } else {
     next.handle(null);
   }
 }
Example #16
0
 private void handleRequest(DefaultHttpServerRequest req, DefaultHttpServerResponse resp) {
   setContext();
   try {
     this.currentRequest = req;
     pendingResponse = resp;
     if (requestHandler != null) {
       requestHandler.handle(req);
     }
   } catch (Throwable t) {
     handleHandlerException(t);
   }
 }
Example #17
0
 protected void handleException(Exception e) {
   if (exceptionHandler != null) {
     setContext();
     try {
       exceptionHandler.handle(e);
     } catch (Throwable t) {
       handleHandlerException(t);
     }
   } else {
     handleHandlerException(e);
   }
 }
  /**
   * 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 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);
   }
 }
Example #21
0
 private void createConn(Channel ch, Handler<ClientConnection> connectHandler) {
   final ClientConnection conn =
       new ClientConnection(
           vertx, DefaultHttpClient.this, ch, tcpHelper.isSSL(), host, port, keepAlive, actualCtx);
   conn.closeHandler(
       new VoidHandler() {
         public void handle() {
           // The connection has been closed - tell the pool about it, this allows the pool to
           // create more
           // connections. Note the pool doesn't actually remove the connection, when the next
           // person to get a connection
           // gets the closed on, they will check if it's closed and if so get another one.
           pool.connectionClosed();
         }
       });
   connectionMap.put(ch, conn);
   connectHandler.handle(conn);
 }
Example #22
0
  @Override
  public void handle(HttpClientResponse clientResponse) {
    delegate.handle(clientResponse);

    MultiMap headers = clientResponse.headers();
    for (String headerName : rewriteHeaders) {
      List<String> headerValues = headers.getAll(headerName);
      int size = headerValues.size();
      if (size > 0) {
        List<String> newHeaders = new ArrayList<String>(size);
        for (String headerValue : headerValues) {
          String newValue = headerValue;
          if (headerValue != null && headerValue.length() > 0) {
            newValue = proxyMappingDetails.rewriteBackendUrl(headerValue);
          }
        }
        LOG.info(
            "Rewriting header " + headerName + " from: " + headerValues + " to: " + newHeaders);
        headers.set(headerName, newHeaders);
      }
    }
  }
  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);
    }
  }
 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 #25
0
  @Override
  public void handle(final YokeRequest request, final Handler<Object> next) {
    // default session
    final YokeCookie cookie = new YokeCookie(name, hmacSHA256);
    cookie.setPath(path);
    cookie.setHttpOnly(httpOnly);
    cookie.setMaxAge(maxAge);

    // path validation mismatch
    if (request.path().indexOf(cookie.getPath()) != 0) {
      next.handle(null);
      return;
    }

    // find the session cookie
    final YokeCookie sessionCookie = request.getCookie(name);

    int hash = 0;

    if (sessionCookie != null) {
      // session cookies must be signed
      if (sessionCookie.isSigned()) {
        String unsigned = sessionCookie.getUnsignedValue();
        if (unsigned != null) {
          hash = crc16(unsigned);
          request.setSessionId(unsigned);
        }
      }
    }

    final int originalHash = hash;
    final YokeResponse response = request.response();

    // call us when headers are being set for the response
    response.headersHandler(
        new Handler<Void>() {
          @Override
          public void handle(Void done) {
            String sessionId = request.getSessionId();

            // removed
            if (sessionId == null) {
              if (sessionCookie != null) {
                cookie.setValue("");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
              }
            } else {
              // only send secure cookies over https
              if (cookie.isSecure() && !request.isSecure()) {
                return;
              }

              // compare hashes, no need to set-cookie if unchanged
              if (originalHash != crc16(sessionId)) {
                // modified session
                cookie.setValue(sessionId);
                cookie.sign();
                response.addCookie(cookie);
              }
            }
          }
        });

    next.handle(null);
  }
Example #26
0
  private void route(
      final YokeRequest request, final PatternBinding binding, final Handler<Object> next) {
    final Matcher m = binding.pattern.matcher(request.path());
    final Vertx vertx = vertx();

    if (m.matches()) {
      final MultiMap params = request.params();

      if (binding.paramNames != null) {
        // Named params
        new AsyncIterator<String>(binding.paramNames) {
          @Override
          public void handle(String param) {
            if (hasNext()) {
              params.set(param, m.group(param));
              final Middleware paramMiddleware = paramProcessors.get(param);
              if (paramMiddleware != null) {
                // do not block main loop
                vertx.runOnContext(
                    new Handler<Void>() {
                      @Override
                      public void handle(Void event) {
                        paramMiddleware.handle(
                            request,
                            new Handler<Object>() {
                              @Override
                              public void handle(Object err) {
                                if (err == null) {
                                  next();
                                } else {
                                  next.handle(err);
                                }
                              }
                            });
                      }
                    });
              } else {
                next();
              }
            } else {
              // middlewares
              new AsyncIterator<Middleware>(binding.middleware) {
                @Override
                public void handle(final Middleware middleware) {
                  if (hasNext()) {
                    // do not block main loop
                    vertx.runOnContext(
                        new Handler<Void>() {
                          @Override
                          public void handle(Void event) {
                            middleware.handle(
                                request,
                                new Handler<Object>() {
                                  @Override
                                  public void handle(Object err) {
                                    if (err == null) {
                                      next();
                                    } else {
                                      next.handle(err);
                                    }
                                  }
                                });
                          }
                        });
                  } else {
                    next.handle(null);
                  }
                }
              };
            }
          }
        };
      } else {
        // Un-named params
        for (int i = 0; i < m.groupCount(); i++) {
          params.set("param" + i, m.group(i + 1));
        }

        // middlewares
        new AsyncIterator<Middleware>(binding.middleware) {
          @Override
          public void handle(final Middleware middleware) {
            if (hasNext()) {
              // do not block main loop
              vertx.runOnContext(
                  new Handler<Void>() {
                    @Override
                    public void handle(Void event) {
                      middleware.handle(
                          request,
                          new Handler<Object>() {
                            @Override
                            public void handle(Object err) {
                              if (err == null) {
                                next();
                              } else {
                                next.handle(err);
                              }
                            }
                          });
                    }
                  });
            } else {
              next.handle(null);
            }
          }
        };
      }
    } else {
      next.handle(null);
    }
  }
 void handleDrained() {
   checkThread();
   if (drainHandler != null) {
     drainHandler.handle(null);
   }
 }
 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 void authorize(
     final HttpServerRequest request,
     final Binding binding,
     final UserInfos user,
     final Handler<Boolean> handler) {
   final String serviceMethod = binding.getServiceMethod();
   if (serviceMethod != null && serviceMethod.startsWith(WorkspaceService.class.getName())) {
     String method = serviceMethod.substring(WorkspaceService.class.getName().length() + 1);
     switch (method) {
       case "getDocument":
         authorizeGetDocument(request, user, binding.getServiceMethod(), handler);
         break;
       case "commentDocument":
       case "commentFolder":
       case "updateDocument":
       case "moveDocument":
       case "moveTrash":
       case "copyDocument":
       case "deleteDocument":
       case "restoreTrash":
       case "shareJson":
       case "shareJsonSubmit":
       case "removeShare":
       case "getRevision":
       case "listRevisions":
         authorizeDocument(request, user, binding.getServiceMethod(), handler);
         break;
       case "deleteRevision":
         authorizeRevisionOwner(
             request,
             user,
             binding.getServiceMethod(),
             new Handler<Boolean>() {
               public void handle(Boolean check) {
                 if (check) {
                   authorizeDocument(
                       request,
                       user,
                       serviceMethod.substring(0, WorkspaceService.class.getName().length() + 1)
                           + "updateDocument",
                       handler);
                 } else {
                   authorizeDocument(request, user, binding.getServiceMethod(), handler);
                 }
               }
             });
         break;
       case "deleteComment":
         authorizeCommentOwner(
             request,
             user,
             binding.getServiceMethod(),
             new Handler<Boolean>() {
               public void handle(Boolean check) {
                 if (check) {
                   authorizeDocument(
                       request,
                       user,
                       serviceMethod.substring(0, WorkspaceService.class.getName().length() + 1)
                           + "commentDocument",
                       handler);
                 } else {
                   authorizeDocument(request, user, binding.getServiceMethod(), handler);
                 }
               }
             });
         break;
       case "moveDocuments":
       case "copyDocuments":
         authorizeDocuments(request, user, binding.getServiceMethod(), handler);
         break;
       case "renameDocument":
       case "renameFolder":
         authorizeOwner(request, user, binding.getServiceMethod(), handler);
         break;
       default:
         handler.handle(false);
     }
   } else if (serviceMethod != null && serviceMethod.startsWith(QuotaController.class.getName())) {
     String method = serviceMethod.substring(QuotaController.class.getName().length() + 1);
     switch (method) {
       case "getQuota":
         isUserOrAdmin(request, user, handler);
         break;
       case "update":
         isAdminFromUsers(request, user, handler);
         break;
       case "getQuotaStructure":
         isAdmin(request, user, handler);
         break;
       case "updateDefault":
       case "getQuotaGlobal":
         isSuperAdmin(user, handler);
         break;
       case "getDefault":
         UserInfos.Function adminLocal = getFunction(user, handler);
         if (adminLocal != null) handler.handle(true);
         break;
       default:
         handler.handle(false);
     }
   }
 }
Example #30
0
 public void run() {
   handler.handle(timerID);
 }