private void listLinksRoutine(RoutingContext routingContext) {
   routingContext.response().setChunked(true);
   FileSystem fs = routingContext.vertx().fileSystem();
   StringBuilder allLinks = linksIntoThePage(fs);
   routingContext.response().write(allLinks.toString());
   routingContext.response().end();
 }
 @Override
 public Object resolve(RoutingContext context, RequestBody annotation, Class<?> resultClass) {
   String body = context.getBodyAsString();
   if (resultClass.equals(String.class)) {
     return body;
   }
   String contentType = ContentTypeProcessor.getContentType(context);
   if (contentType == null) {
     log.error("No suitable Content-Type found, request body can't be read");
     return null;
   }
   if (contentType.equals("application/json") && resultClass.equals(JsonObject.class)) {
     return new JsonObject(body);
   }
   PayloadMarshaller marshaller = marshallers.get(contentType);
   if (marshaller == null) {
     log.error(
         "No marshaller found for Content-Type : " + contentType + ", request body can't be read");
     return null;
   }
   try {
     return marshaller.unmarshallPayload(body, resultClass);
   } catch (MarshallingException me) {
     context.fail(me);
     return null;
   }
 }
Example #3
0
  /**
   * Sets CORS on routing context using default headers & methods on specific ip and port (note:
   * does not call next() )
   *
   * @param rc
   * @param ipAndPort
   */
  public static void allow(RoutingContext rc, String ipAndPort) {
    if (ipAndPort == null || ipAndPort.length() == 0) return;

    rc.response().putHeader("Access-Control-Allow-Headers", defaultHeaders);
    rc.response().putHeader("Access-Control-Allow-Methods", defaultMethods);
    rc.response().putHeader("Access-Control-Allow-Origin", ipAndPort);
  }
 private void deleteOne(RoutingContext routingContext) {
   Long id = getId(routingContext);
   if (id == null) {
     routingContext.response().setStatusCode(400).end();
   } else {
     service.remove(id);
   }
   routingContext.response().setStatusCode(204).end();
 }
 private void addOne(RoutingContext routingContext) {
   FactorizationTask task =
       Json.decodeValue(routingContext.getBodyAsString(), FactorizationTask.class);
   task = service.create(task.getNumber());
   routingContext
       .response()
       .setStatusCode(201)
       .putHeader("content-type", "application/json; charset=utf-8")
       .end(Json.encodePrettily(task));
 }
 private void postRoutine(RoutingContext routingContext) {
   String body = routingContext.getBodyAsString();
   String res;
   try (JShellEvaluator evaluator = new JShellEvaluator()) {
     res = evaluator.evalSnippets(JShellParser.parseToSnippets(body));
   } catch (IOException e) {
     res = "Unable to evaluation the code";
   }
   routingContext.response().setChunked(true).putHeader("content-type", "text/html").write(res);
   routingContext.response().end();
 }
 @Override
 public void postHandle(RoutingContext context) {
   PaginationContext pageContext =
       (PaginationContext) context.data().get(PaginationContext.DATA_ATTR);
   String linkHeader = pageContext.buildLinkHeader(context.request());
   if (linkHeader != null) {
     context.response().headers().add(HttpHeaders.LINK, linkHeader);
   } else {
     log.warn("You did not set the total count on PaginationContext, response won't be paginated");
   }
   context.next();
 }
Example #8
0
 private boolean pathMatches(String mountPoint, RoutingContext ctx) {
   String thePath = mountPoint == null ? path : mountPoint + path;
   String requestPath =
       useNormalisedPath ? Utils.normalisePath(ctx.request().path(), false) : ctx.request().path();
   if (exactPath) {
     return pathMatchesExact(requestPath, thePath);
   } else {
     if (thePath.endsWith("/") && requestPath.equals(removeTrailing(thePath))) {
       return true;
     }
     return requestPath.startsWith(thePath);
   }
 }
Example #9
0
 @Override
 public void handle(RoutingContext context) {
   try {
     this.processRequest(context.request());
     if (!_redirect)
       context.response().setChunked(true).write(Jade4J.render(this._file, this._model)).end();
     else
       context
           .response()
           .setChunked(true)
           .setStatusCode(301)
           .putHeader("Location", this._redirectUrl);
   } catch (IOException e) {
     LogManager.getLogger("website").error("Opening" + this._file + " failed");
   }
 }
Example #10
0
 default void end(RoutingContext context, HttpResponseStatus statusCode) {
   context
       .response()
       .setStatusCode(statusCode.code())
       .setStatusMessage(statusCode.reasonPhrase())
       .end();
 }
Example #11
0
  default <T extends Throwable> void error(
      RoutingContext context, HttpResponseStatus code, String message, T object) {
    HttpServerResponse response = context.response().setStatusCode(code.code());
    response.putHeader("X-API-Gateway-Error", "true");

    if (message == null) {
      response.setStatusMessage(code.reasonPhrase());
    } else {
      response.setStatusMessage(message);
    }

    if (object != null) {
      JsonObject errorResponse =
          new JsonObject()
              .put("errorType", object.getClass().getSimpleName())
              .put("message", object.getMessage());

      response
          .setChunked(true)
          .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
          .end(errorResponse.toString(), "UTF-8");
    } else {
      response.end();
    }
  }
  @Override
  public void render(
      RoutingContext context, String templateFileName, Handler<AsyncResult<Buffer>> handler) {
    try {
      Template template = cache.get(templateFileName);
      if (template == null) {
        // real compile
        synchronized (this) {
          loader.setVertx(context.vertx());
          // Compile
          template = config.getTemplate(adjustLocation(templateFileName));
        }
        cache.put(templateFileName, template);
      }

      Map<String, RoutingContext> variables = new HashMap<>(1);
      variables.put("context", context);

      try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        template.process(variables, new OutputStreamWriter(baos));
        handler.handle(Future.succeededFuture(Buffer.buffer(baos.toByteArray())));
      }

    } catch (Exception ex) {
      handler.handle(Future.failedFuture(ex));
    }
  }
  @Override
  public void handle(RoutingContext context) {

    username = context.user().principal().getString("username");

    jdbcClient.getConnection(
        connectionRes -> {
          if (connectionRes.succeeded()) {
            // System.out.println("Able to get JDBC Connection");
            queryLocation(context, connectionRes);

          } else {
            log.error("Could not connect to the database.");
            context.fail(402);
          }
        });
  }
 /*
  * We got more than 8 lines on that method because
  * we could not really delegates more for other
  * function. That would made the code kind of hard
  * to read.
  * */
 private void getDemandExerciseRoutine(RoutingContext context) {
   String id = context.request().getParam("id");
   Path path = Paths.get(this.workingDirectory.toString(), id + ".mkdown");
   HttpServerResponse rep =
       context.response().setChunked(true).putHeader("content-type", "text/html");
   if (Files.exists(path)) {
     MarkdownToHTML markdownToHTML = new MarkdownToHTML();
     try {
       rep.write(markdownToHTML.parse(path));
     } catch (IOException e) {
       rep.write("Unable to load " + id + ".mkdow");
     }
   } else {
     rep.write("Excercice with id " + id + " no found");
   }
   rep.end();
 }
Example #15
0
 default <T> void writeBody(RoutingContext context, T object) {
   context
       .response()
       .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
       .setChunked(true)
       .setStatusCode(HttpResponseStatus.OK.code())
       .end(Json.encode(object), "UTF-8");
 }
 private void getOne(RoutingContext routingContext) {
   Long id = getId(routingContext);
   if (id == null) {
     routingContext.response().setStatusCode(400).end();
   } else {
     FactorizationTask task = service.getOne(id);
     if (task == null) {
       routingContext.response().setStatusCode(404).end();
     } else {
       routingContext
           .response()
           .putHeader("content-type", "application/json; charset=utf-8")
           // TODO don't serialize null values
           .end(Json.encodePrettily(task));
     }
   }
 }
Example #17
0
  /**
   * Sets CORS on routing context using default headers & methods on specific ips and ports (note:
   * does not call next() )
   *
   * @param rc
   * @param ipAndPort
   */
  public static void allow(RoutingContext rc, String[] ipAndPorts) {
    if (ipAndPorts == null || ipAndPorts.length == 0) return;

    rc.response().putHeader("Access-Control-Allow-Headers", defaultHeaders);
    rc.response().putHeader("Access-Control-Allow-Methods", defaultMethods);

    String ips = "";

    for (int i = 0; i < ipAndPorts.length; i++) {
      ips += ipAndPorts[i];

      if (i < ipAndPorts.length - 1) {
        ips += ",";
      }
    }

    rc.response().putHeader("Access-Control-Allow-Origin", ips);
  }
Example #18
0
 @Override
 public void handle(RoutingContext context) {
   if (auth) {
     super.handle(context);
   } else {
     // No auth required
     context.next();
   }
 }
  @Override
  public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    String remainingPath = Utils.pathOffset(req.path(), context);

    if (req.method() != HttpMethod.GET && req.method() != HttpMethod.POST) {
      context.next();
    }

    JSONAware json = null;
    try {
      // Check access policy
      requestHandler.checkAccess(
          req.remoteAddress().host(), req.remoteAddress().host(), getOriginOrReferer(req));
      if (req.method() == HttpMethod.GET) {
        json = requestHandler.handleGetRequest(req.uri(), remainingPath, getParams(req.params()));
      } else {
        Arguments.require(
            context.getBody() != null, "Missing body, make sure that BodyHandler is used before");
        // TODO how to get Stream ?
        InputStream inputStream = new ByteBufInputStream(context.getBody().getByteBuf());
        json =
            requestHandler.handlePostRequest(
                req.uri(), inputStream, StandardCharsets.UTF_8.name(), getParams(req.params()));
      }
    } catch (Throwable exp) {
      json =
          requestHandler.handleThrowable(
              exp instanceof RuntimeMBeanException
                  ? ((RuntimeMBeanException) exp).getTargetException()
                  : exp);
    } finally {
      if (json == null)
        json =
            requestHandler.handleThrowable(
                new Exception("Internal error while handling an exception"));

      context
          .response()
          .setStatusCode(getStatusCode(json))
          .putHeader(HttpHeaders.CONTENT_TYPE, contentType)
          .end(json.toJSONString());
    }
  }
  private void checkMemory(RoutingContext routingContext) {
    OperatingSystemMXBean bean =
        (OperatingSystemMXBean) ManagementFactoryHelper.getOperatingSystemMXBean();
    long max = bean.getTotalPhysicalMemorySize();
    long free = bean.getFreePhysicalMemorySize();

    routingContext
        .response()
        .putHeader("Content-Type", "text/plain")
        .setStatusCode(HttpResponseStatus.OK.code())
        .end(String.valueOf(max - free));
  }
  private void uploadGraphFile(RoutingContext routingContext, boolean isGraphFile) {
    File uploadsDir = new File("uploads");
    try {
      if (!uploadsDir.exists()) {
        uploadsDir.mkdir();
      }
      routingContext.request().setExpectMultipart(true);

      routingContext
          .request()
          .uploadHandler(
              new Handler<HttpServerFileUpload>() {
                @Override
                public void handle(final HttpServerFileUpload upload) {
                  upload.exceptionHandler(
                      new Handler<Throwable>() {
                        @Override
                        public void handle(Throwable event) {}
                      });
                  upload.endHandler(
                      new Handler<Void>() {
                        @Override
                        public void handle(Void event) {
                          routingContext.request().response().end("1");
                        }
                      });
                  upload.streamToFileSystem("uploads/" + upload.filename());
                  if (isGraphFile) {
                    dtoConfig.setGraphfileName(upload.filename());
                  } else {
                    dtoConfig.setTextfileName(upload.filename());
                  }
                }
              });

    } catch (SecurityException se) {
      System.out.println("Permission denied to create uploads directroy.");
    }
  }
  private void queryActivites(RoutingContext context, SQLConnection connection) {
    // Retrieve Activies
    connection.query(
        "SELECT name FROM activities",
        res5 -> {
          if (res5.succeeded()) {
            // System.out.println("Able to get activities query");
            for (JsonArray line3 : res5.result().getResults()) {
              // System.out.println("Activities: "+line3.encode());
              String ActTemp = line3.encode();
              ActTemp = ActTemp.replaceAll("[^a-zA-Z,' '0-9]", "");
              Act[Actcounter] = ActTemp;
              Actcounter++;
            }
            Actcounter = 0;
            context.session().put("activities", Act);

            context.next();
          } else {
            log.error("could not select form the activites table");
          }
        });
  }
  private void queryLocation(RoutingContext context, AsyncResult<SQLConnection> connectionRes) {
    // Get and set locations of user for future queries
    SQLConnection connection = connectionRes.result();
    // System.out.println("SELECT Location FROM preferences WHERE username = '******'");
    connection.query(
        "SELECT Location FROM preferences WHERE username = '******'",
        res2 -> {
          if (res2.succeeded()) {
            // System.out.println("Able to get query location");
            ResultSet resultSet = res2.result();
            for (JsonArray line : res2.result().getResults()) {
              Location = line.encode();
              Location = Location.replaceAll("[^a-zA-Z,' ']", "");
              // System.out.println("userLocation:"+Location);
            }
            context.session().put("location", Location);
            queryBudget(context, connection);

          } else {
            log.error("Could not select from the user table");
          }
        });
  }
  private void queryResturants(final RoutingContext context, final SQLConnection connection) {
    // Retrieve Resturants
    connection.query(
        "SELECT name FROM resturant",
        res4 -> {
          if (res4.succeeded()) {
            // System.out.println("Able to get resturant query");
            for (JsonArray line2 : res4.result().getResults()) {
              // System.out.println("resturant: "+line2.encode());
              String Resttemp = line2.encode();
              Resttemp = Resttemp.replaceAll("[^a-zA-Z,' '0-9]", "");
              Rest[Restcounter] = Resttemp;
              Restcounter++;
            }
            Restcounter = 0;
            context.session().put("resturants", Rest);

            queryActivites(context, connection);
          } else {
            log.error("could not select form resturant table");
          }
        });
  }
 private void queryHotelPricing(RoutingContext context, SQLConnection connection) {
   // Retrieve Hotel Pricing
   connection.query(
       "SELECT price FROM hotel",
       res3 -> {
         if (res3.succeeded()) {
           // System.out.println("Able to get hotel pricing");
           Hotelcounter = 0;
           for (JsonArray line1 : res3.result().getResults()) {
             String temp = Hotel[Hotelcounter];
             temp = temp.concat("   ($" + line1.encode() + ")");
             temp = temp.replaceAll("[^a-zA-Z,' '0-9$()]", "");
             Hotel[Hotelcounter] = temp;
             // System.out.println("hotel with price: " + Hotel[Hotelcounter]);
             Hotelcounter++;
           }
           context.session().put("hotels", Hotel);
           queryResturants(context, connection);
           Hotelcounter = 0;
         } else {
           log.error("could not select from user table above");
         }
       });
 }
Example #26
0
 @Override
 public void preHandle(RoutingContext context) {
   context.data().put(PaginationContext.DATA_ATTR, PaginationContext.fromContext(context));
   context.next();
 }
Example #27
0
  synchronized boolean matches(RoutingContext context, String mountPoint, boolean failure) {

    if (failure && failureHandler == null || !failure && contextHandler == null) {
      return false;
    }
    if (!enabled) {
      return false;
    }
    HttpServerRequest request = context.request();
    if (!methods.isEmpty() && !methods.contains(request.method())) {
      return false;
    }
    if (path != null && pattern == null && !pathMatches(mountPoint, context)) {
      return false;
    }
    if (pattern != null) {
      String path =
          useNormalisedPath
              ? Utils.normalisePath(context.request().path(), false)
              : context.request().path();
      if (mountPoint != null) {
        path = path.substring(mountPoint.length());
      }

      Matcher m = pattern.matcher(path);
      if (m.matches()) {
        if (m.groupCount() > 0) {
          Map<String, String> params = new HashMap<>(m.groupCount());
          if (groups != null) {
            // Pattern - named params
            // decode the path as it could contain escaped chars.
            try {
              for (int i = 0; i < groups.size(); i++) {
                final String k = groups.get(i);
                final String value =
                    URLDecoder.decode(URLDecoder.decode(m.group("p" + i), "UTF-8"), "UTF-8");
                if (!request.params().contains(k)) {
                  params.put(k, value);
                } else {
                  context.pathParams().put(k, value);
                }
              }
            } catch (UnsupportedEncodingException e) {
              context.fail(e);
              return false;
            }
          } else {
            // Straight regex - un-named params
            // decode the path as it could contain escaped chars.
            try {
              for (int i = 0; i < m.groupCount(); i++) {
                String group = m.group(i + 1);
                if (group != null) {
                  final String k = "param" + i;
                  final String value = URLDecoder.decode(group, "UTF-8");
                  if (!request.params().contains(k)) {
                    params.put(k, value);
                  } else {
                    context.pathParams().put(k, value);
                  }
                }
              }
            } catch (UnsupportedEncodingException e) {
              context.fail(e);
              return false;
            }
          }
          request.params().addAll(params);
          context.pathParams().putAll(params);
        }
      } else {
        return false;
      }
    }
    if (!consumes.isEmpty()) {
      // Can this route consume the specified content type
      String contentType = request.headers().get("content-type");
      boolean matches = false;
      for (String ct : consumes) {
        if (ctMatches(contentType, ct)) {
          matches = true;
          break;
        }
      }
      if (!matches) {
        return false;
      }
    }
    if (!produces.isEmpty()) {
      String accept = request.headers().get("accept");
      if (accept != null) {
        List<String> acceptableTypes = Utils.getSortedAcceptableMimeTypes(accept);
        for (String acceptable : acceptableTypes) {
          for (String produce : produces) {
            if (ctMatches(produce, acceptable)) {
              context.setAcceptableContentType(produce);
              return true;
            }
          }
        }
      } else {
        // According to rfc2616-sec14,
        // If no Accept header field is present, then it is assumed that the client accepts all
        // media types.
        context.setAcceptableContentType(produces.iterator().next());
        return true;
      }
      return false;
    }
    return true;
  }
  public void PostChoir(RoutingContext rc) {
    Choir choir = TestUtility.toChoirFromJson(rc.getBodyAsString());

    rc.response().end(choir.toJson(false));
  }
 private Long getId(RoutingContext routingContext) {
   return ofNullable(routingContext.request().getParam("id")).map(Long::valueOf).orElse(null);
 }
 private void readingDirectoryRoutine(RoutingContext routingContext) {
   routingContext.response().setChunked(true);
   routingContext.response().sendFile("webroot/index.html");
 }